diff --git a/.github/workflows/bazel.yml b/.github/workflows/bazel.yml index 539e9cb8e0..64e831e5fd 100644 --- a/.github/workflows/bazel.yml +++ b/.github/workflows/bazel.yml @@ -28,14 +28,17 @@ jobs: target: x86_64-apple-darwin # Linux - - os: ubuntu-24.04-arm - target: aarch64-unknown-linux-gnu - os: ubuntu-24.04 target: x86_64-unknown-linux-gnu - - os: ubuntu-24.04-arm - target: aarch64-unknown-linux-musl - os: ubuntu-24.04 target: x86_64-unknown-linux-musl + # 2026-02-27 Bazel tests have been flaky on arm in CI. + # Disable until we can investigate and stabilize them. + # - os: ubuntu-24.04-arm + # target: aarch64-unknown-linux-musl + # - os: ubuntu-24.04-arm + # target: aarch64-unknown-linux-gnu + # TODO: Enable Windows once we fix the toolchain issues there. #- os: windows-latest # target: x86_64-pc-windows-gnullvm diff --git a/.github/workflows/issue-deduplicator.yml b/.github/workflows/issue-deduplicator.yml index ae855ab90b..62af691fe6 100644 --- a/.github/workflows/issue-deduplicator.yml +++ b/.github/workflows/issue-deduplicator.yml @@ -7,15 +7,17 @@ on: - labeled jobs: - gather-duplicates: - name: Identify potential duplicates + gather-duplicates-all: + name: Identify potential duplicates (all issues) # Prevent runs on forks (requires OpenAI API key, wastes Actions minutes) if: github.repository == 'openai/codex' && (github.event.action == 'opened' || (github.event.action == 'labeled' && github.event.label.name == 'codex-deduplicate')) runs-on: ubuntu-latest permissions: contents: read outputs: - codex_output: ${{ steps.select-final.outputs.codex_output }} + issues_json: ${{ steps.normalize-all.outputs.issues_json }} + reason: ${{ steps.normalize-all.outputs.reason }} + has_matches: ${{ steps.normalize-all.outputs.has_matches }} steps: - uses: actions/checkout@v6 @@ -29,7 +31,6 @@ jobs: CURRENT_ISSUE_FILE=codex-current-issue.json EXISTING_ALL_FILE=codex-existing-issues-all.json - EXISTING_OPEN_FILE=codex-existing-issues-open.json gh issue list --repo "$REPO" \ --json number,title,body,createdAt,updatedAt,state,labels \ @@ -47,22 +48,6 @@ jobs: }]' \ > "$EXISTING_ALL_FILE" - gh issue list --repo "$REPO" \ - --json number,title,body,createdAt,updatedAt,state,labels \ - --limit 1000 \ - --state open \ - --search "sort:created-desc" \ - | jq '[.[] | { - number, - title, - body: ((.body // "")[0:4000]), - createdAt, - updatedAt, - state, - labels: ((.labels // []) | map(.name)) - }]' \ - > "$EXISTING_OPEN_FILE" - gh issue view "$ISSUE_NUMBER" \ --repo "$REPO" \ --json number,title,body \ @@ -71,7 +56,6 @@ jobs: echo "Prepared duplicate detection input files." echo "all_issue_count=$(jq 'length' "$EXISTING_ALL_FILE")" - echo "open_issue_count=$(jq 'length' "$EXISTING_OPEN_FILE")" # Prompt instructions are intentionally inline in this workflow. The old # .github/prompts/issue-deduplicator.txt file is obsolete and removed. @@ -158,9 +142,59 @@ jobs: echo "has_matches=$has_matches" } >> "$GITHUB_OUTPUT" + gather-duplicates-open: + name: Identify potential duplicates (open issues fallback) + # Pass 1 may drop sudo on the runner, so run the fallback in a fresh job. + needs: gather-duplicates-all + if: ${{ needs.gather-duplicates-all.result == 'success' && needs.gather-duplicates-all.outputs.has_matches != 'true' }} + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + issues_json: ${{ steps.normalize-open.outputs.issues_json }} + reason: ${{ steps.normalize-open.outputs.reason }} + has_matches: ${{ steps.normalize-open.outputs.has_matches }} + steps: + - uses: actions/checkout@v6 + + - name: Prepare Codex inputs + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + set -eo pipefail + + CURRENT_ISSUE_FILE=codex-current-issue.json + EXISTING_OPEN_FILE=codex-existing-issues-open.json + + gh issue list --repo "$REPO" \ + --json number,title,body,createdAt,updatedAt,state,labels \ + --limit 1000 \ + --state open \ + --search "sort:created-desc" \ + | jq '[.[] | { + number, + title, + body: ((.body // "")[0:4000]), + createdAt, + updatedAt, + state, + labels: ((.labels // []) | map(.name)) + }]' \ + > "$EXISTING_OPEN_FILE" + + gh issue view "$ISSUE_NUMBER" \ + --repo "$REPO" \ + --json number,title,body \ + | jq '{number, title, body: ((.body // "")[0:4000])}' \ + > "$CURRENT_ISSUE_FILE" + + echo "Prepared fallback duplicate detection input files." + echo "open_issue_count=$(jq 'length' "$EXISTING_OPEN_FILE")" + - id: codex-open name: Find duplicates (pass 2, open issues) - if: ${{ steps.normalize-all.outputs.has_matches != 'true' }} uses: openai/codex-action@main with: openai-api-key: ${{ secrets.CODEX_OPENAI_API_KEY }} @@ -200,7 +234,6 @@ jobs: - id: normalize-open name: Normalize pass 2 output - if: ${{ steps.normalize-all.outputs.has_matches != 'true' }} env: CODEX_OUTPUT: ${{ steps.codex-open.outputs.final-message }} CURRENT_ISSUE_NUMBER: ${{ github.event.issue.number }} @@ -243,15 +276,27 @@ jobs: echo "has_matches=$has_matches" } >> "$GITHUB_OUTPUT" + select-final: + name: Select final duplicate set + needs: + - gather-duplicates-all + - gather-duplicates-open + if: ${{ always() && needs.gather-duplicates-all.result == 'success' && (needs.gather-duplicates-open.result == 'success' || needs.gather-duplicates-open.result == 'skipped') }} + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + codex_output: ${{ steps.select-final.outputs.codex_output }} + steps: - id: select-final name: Select final duplicate set env: - PASS1_ISSUES: ${{ steps.normalize-all.outputs.issues_json }} - PASS1_REASON: ${{ steps.normalize-all.outputs.reason }} - PASS2_ISSUES: ${{ steps.normalize-open.outputs.issues_json }} - PASS2_REASON: ${{ steps.normalize-open.outputs.reason }} - PASS1_HAS_MATCHES: ${{ steps.normalize-all.outputs.has_matches }} - PASS2_HAS_MATCHES: ${{ steps.normalize-open.outputs.has_matches }} + PASS1_ISSUES: ${{ needs.gather-duplicates-all.outputs.issues_json }} + PASS1_REASON: ${{ needs.gather-duplicates-all.outputs.reason }} + PASS2_ISSUES: ${{ needs.gather-duplicates-open.outputs.issues_json }} + PASS2_REASON: ${{ needs.gather-duplicates-open.outputs.reason }} + PASS1_HAS_MATCHES: ${{ needs.gather-duplicates-all.outputs.has_matches }} + PASS2_HAS_MATCHES: ${{ needs.gather-duplicates-open.outputs.has_matches }} run: | set -eo pipefail @@ -289,8 +334,8 @@ jobs: comment-on-issue: name: Comment with potential duplicates - needs: gather-duplicates - if: ${{ needs.gather-duplicates.result != 'skipped' }} + needs: select-final + if: ${{ needs.select-final.result != 'skipped' }} runs-on: ubuntu-latest permissions: contents: read @@ -299,7 +344,7 @@ jobs: - name: Comment on issue uses: actions/github-script@v8 env: - CODEX_OUTPUT: ${{ needs.gather-duplicates.outputs.codex_output }} + CODEX_OUTPUT: ${{ needs.select-final.outputs.codex_output }} with: github-token: ${{ github.token }} script: | diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 4ed08b077e..5d6d3f7ca0 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -494,6 +494,11 @@ jobs: --package codex-responses-api-proxy \ --package codex-sdk + - name: Stage installer scripts + run: | + cp scripts/install/install.sh dist/install.sh + cp scripts/install/install.ps1 dist/install.ps1 + - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: diff --git a/.github/workflows/shell-tool-mcp.yml b/.github/workflows/shell-tool-mcp.yml index 1a36d71903..76658c61bd 100644 --- a/.github/workflows/shell-tool-mcp.yml +++ b/.github/workflows/shell-tool-mcp.yml @@ -146,9 +146,8 @@ jobs: shell: bash run: | set -euo pipefail - git clone --depth 1 https://github.com/bolinfest/bash /tmp/bash + git clone https://git.savannah.gnu.org/git/bash /tmp/bash cd /tmp/bash - git fetch --depth 1 origin a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b git checkout a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b git apply "${GITHUB_WORKSPACE}/shell-tool-mcp/patches/bash-exec-wrapper.patch" ./configure --without-bash-malloc @@ -188,9 +187,8 @@ jobs: shell: bash run: | set -euo pipefail - git clone --depth 1 https://github.com/bolinfest/bash /tmp/bash + git clone https://git.savannah.gnu.org/git/bash /tmp/bash cd /tmp/bash - git fetch --depth 1 origin a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b git checkout a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b git apply "${GITHUB_WORKSPACE}/shell-tool-mcp/patches/bash-exec-wrapper.patch" ./configure --without-bash-malloc diff --git a/.vscode/settings.json b/.vscode/settings.json index 5adec04a83..1e857367cb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,7 @@ { "rust-analyzer.checkOnSave": true, "rust-analyzer.check.command": "clippy", - "rust-analyzer.check.extraArgs": ["--all-features", "--tests"], + "rust-analyzer.check.extraArgs": ["--tests"], "rust-analyzer.rustfmt.extraArgs": ["--config", "imports_granularity=Item"], "rust-analyzer.cargo.targetDir": "${workspaceFolder}/codex-rs/target/rust-analyzer", "[rust]": { diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 5777c6a36b..9b459b9941 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -617,6 +617,10 @@ "arrayvec_0.7.6": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.4\"},{\"default_features\":false,\"name\":\"borsh\",\"optional\":true,\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"matches\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.4\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "ascii-canvas_3.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"diff\",\"req\":\"^0.1\"},{\"name\":\"term\",\"req\":\"^0.7\"}],\"features\":{}}", "ascii_1.1.0": "{\"dependencies\":[{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"name\":\"serde_test\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", + "askama_0.15.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"askama_macros\",\"optional\":true,\"req\":\"=0.15.4\"},{\"kind\":\"dev\",\"name\":\"assert_matches\",\"req\":\"^1.5.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"name\":\"itoa\",\"req\":\"^1.0.11\"},{\"default_features\":false,\"name\":\"percent-encoding\",\"optional\":true,\"req\":\"^2.1.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"alloc\":[\"askama_macros?/alloc\",\"serde?/alloc\",\"serde_json?/alloc\",\"percent-encoding?/alloc\"],\"code-in-doc\":[\"askama_macros?/code-in-doc\"],\"config\":[\"askama_macros?/config\"],\"default\":[\"config\",\"derive\",\"std\",\"urlencode\"],\"derive\":[\"dep:askama_macros\",\"dep:askama_macros\"],\"full\":[\"default\",\"code-in-doc\",\"serde_json\"],\"nightly-spans\":[\"askama_macros/nightly-spans\"],\"serde_json\":[\"std\",\"askama_macros?/serde_json\",\"dep:serde\",\"dep:serde_json\"],\"std\":[\"alloc\",\"askama_macros?/std\",\"serde?/std\",\"serde_json?/std\",\"percent-encoding?/std\"],\"urlencode\":[\"askama_macros?/urlencode\",\"dep:percent-encoding\"]}}", + "askama_derive_0.15.4": "{\"dependencies\":[{\"name\":\"basic-toml\",\"optional\":true,\"req\":\"^0.1.1\"},{\"kind\":\"dev\",\"name\":\"console\",\"req\":\"^0.16.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"name\":\"memchr\",\"req\":\"^2\"},{\"name\":\"parser\",\"package\":\"askama_parser\",\"req\":\"=0.15.4\"},{\"kind\":\"dev\",\"name\":\"prettyplease\",\"req\":\"^0.2.20\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"pulldown-cmark\",\"optional\":true,\"req\":\"^0.13.0\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"rustc-hash\",\"req\":\"^2.0.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"similar\",\"req\":\"^2.6.0\"},{\"default_features\":false,\"features\":[\"clone-impls\",\"derive\",\"full\",\"parsing\",\"printing\"],\"name\":\"syn\",\"req\":\"^2.0.3\"}],\"features\":{\"alloc\":[],\"code-in-doc\":[\"dep:pulldown-cmark\"],\"config\":[\"external-sources\",\"dep:basic-toml\",\"dep:serde\",\"dep:serde_derive\",\"parser/config\"],\"default\":[\"alloc\",\"code-in-doc\",\"config\",\"external-sources\",\"proc-macro\",\"serde_json\",\"std\",\"urlencode\"],\"external-sources\":[],\"nightly-spans\":[],\"proc-macro\":[\"proc-macro2/proc-macro\"],\"serde_json\":[],\"std\":[\"alloc\"],\"urlencode\":[]}}", + "askama_macros_0.15.4": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"external-sources\",\"proc-macro\"],\"name\":\"askama_derive\",\"package\":\"askama_derive\",\"req\":\"=0.15.4\"}],\"features\":{\"alloc\":[\"askama_derive/alloc\"],\"code-in-doc\":[\"askama_derive/code-in-doc\"],\"config\":[\"askama_derive/config\"],\"default\":[\"config\",\"derive\",\"std\",\"urlencode\"],\"derive\":[],\"full\":[\"default\",\"code-in-doc\",\"serde_json\"],\"nightly-spans\":[\"askama_derive/nightly-spans\"],\"serde_json\":[\"askama_derive/serde_json\"],\"std\":[\"askama_derive/std\"],\"urlencode\":[\"askama_derive/urlencode\"]}}", + "askama_parser_0.15.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"name\":\"rustc-hash\",\"req\":\"^2.0.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"unicode-ident\",\"req\":\"^1.0.12\"},{\"features\":[\"simd\"],\"name\":\"winnow\",\"req\":\"^0.7.0\"}],\"features\":{\"config\":[\"dep:serde\",\"dep:serde_derive\"]}}", "asn1-rs-derive_0.6.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"name\":\"synstructure\",\"req\":\"^0.13\"}],\"features\":{}}", "asn1-rs-impl_0.2.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "asn1-rs_0.7.1": "{\"dependencies\":[{\"name\":\"asn1-rs-derive\",\"req\":\"^0.6\"},{\"name\":\"asn1-rs-impl\",\"req\":\"^0.2\"},{\"name\":\"bitvec\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"colored\",\"optional\":true,\"req\":\"^3.0\"},{\"kind\":\"dev\",\"name\":\"colored\",\"req\":\"^3.0\"},{\"name\":\"cookie-factory\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"displaydoc\",\"req\":\"^0.2.2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"nom\",\"req\":\"^7.0\"},{\"name\":\"num-bigint\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"num-traits\",\"req\":\"^0.2.14\"},{\"kind\":\"dev\",\"name\":\"pem\",\"req\":\"^3.0\"},{\"name\":\"rusticata-macros\",\"req\":\"^4.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0.0\"},{\"features\":[\"macros\",\"parsing\",\"formatting\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"}],\"features\":{\"bigint\":[\"num-bigint\"],\"bits\":[\"bitvec\"],\"datetime\":[\"time\"],\"debug\":[\"std\",\"colored\"],\"default\":[\"std\"],\"serialize\":[\"cookie-factory\"],\"std\":[],\"trace\":[\"debug\"]}}", @@ -671,6 +675,7 @@ "bytes_1.11.1": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"require-cas\"],\"name\":\"extra-platforms\",\"optional\":true,\"package\":\"portable-atomic\",\"req\":\"^1.3\"},{\"kind\":\"dev\",\"name\":\"loom\",\"req\":\"^0.7\",\"target\":\"cfg(loom)\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.60\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "bytestring_1.5.0": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"}],\"features\":{\"serde\":[\"dep:serde_core\"]}}", "bzip2-sys_0.1.13+1.0.8": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.9\"}],\"features\":{\"__disabled\":[],\"static\":[]}}", + "bzip2_0.4.4": "{\"dependencies\":[{\"name\":\"bzip2-sys\",\"req\":\"^0.1.11\"},{\"name\":\"futures\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"features\":[\"quickcheck\"],\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck6\",\"package\":\"quickcheck\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"tokio-core\",\"req\":\"^0.1\"},{\"name\":\"tokio-io\",\"optional\":true,\"req\":\"^0.1\"}],\"features\":{\"static\":[\"bzip2-sys/static\"],\"tokio\":[\"tokio-io\",\"futures\"]}}", "bzip2_0.5.2": "{\"dependencies\":[{\"name\":\"bzip2-sys\",\"optional\":true,\"req\":\"^0.1.13\"},{\"default_features\":false,\"features\":[\"rust-allocator\",\"semver-prefix\"],\"name\":\"libbz2-rs-sys\",\"optional\":true,\"req\":\"^0.1.3\"},{\"features\":[\"quickcheck1\"],\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.5.4\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"}],\"features\":{\"default\":[\"dep:bzip2-sys\"],\"libbz2-rs-sys\":[\"dep:libbz2-rs-sys\",\"bzip2-sys?/__disabled\"],\"static\":[\"bzip2-sys?/static\"]}}", "cached_0.56.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ahash\",\"optional\":true,\"req\":\"^0.8\"},{\"features\":[\"attributes\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.6\"},{\"name\":\"async-trait\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"cached_proc_macro\",\"optional\":true,\"req\":\"^0.25.0\"},{\"name\":\"cached_proc_macro_types\",\"optional\":true,\"req\":\"^0.1.1\"},{\"kind\":\"dev\",\"name\":\"copy_dir\",\"req\":\"^0.1.3\"},{\"name\":\"directories\",\"optional\":true,\"req\":\"^6.0\"},{\"default_features\":false,\"name\":\"futures\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"googletest\",\"req\":\"^0.11.0\"},{\"default_features\":false,\"features\":[\"inline-more\"],\"name\":\"hashbrown\",\"req\":\"^0.15\"},{\"name\":\"once_cell\",\"req\":\"^1\"},{\"name\":\"r2d2\",\"optional\":true,\"req\":\"^0.8\"},{\"features\":[\"r2d2\"],\"name\":\"redis\",\"optional\":true,\"req\":\"^0.32\"},{\"name\":\"rmp-serde\",\"optional\":true,\"req\":\"^1.1\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^3\"},{\"name\":\"sled\",\"optional\":true,\"req\":\"^0.34\"},{\"kind\":\"dev\",\"name\":\"smartstring\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.10.1\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"macros\",\"time\",\"sync\",\"parking_lot\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"web-time\",\"req\":\"^1.1.0\"}],\"features\":{\"ahash\":[\"dep:ahash\",\"hashbrown/default\"],\"async\":[\"futures\",\"tokio\",\"async-trait\"],\"async_tokio_rt_multi_thread\":[\"async\",\"tokio/rt-multi-thread\"],\"default\":[\"proc_macro\",\"ahash\"],\"disk_store\":[\"sled\",\"serde\",\"rmp-serde\",\"directories\"],\"proc_macro\":[\"cached_proc_macro\",\"cached_proc_macro_types\"],\"redis_ahash\":[\"redis_store\",\"redis/ahash\"],\"redis_async_std\":[\"redis_store\",\"async\",\"redis/aio\",\"redis/async-std-comp\",\"redis/tls\",\"redis/async-std-tls-comp\"],\"redis_connection_manager\":[\"redis_store\",\"redis/connection-manager\"],\"redis_store\":[\"redis\",\"r2d2\",\"serde\",\"serde_json\"],\"redis_tokio\":[\"redis_store\",\"async\",\"redis/aio\",\"redis/tokio-comp\",\"redis/tls\",\"redis/tokio-native-tls-comp\"],\"wasm\":[]}}", "cached_proc_macro_0.25.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.20.8\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.49\"},{\"name\":\"quote\",\"req\":\"^1.0.6\"},{\"name\":\"syn\",\"req\":\"^2.0.52\"}],\"features\":{}}", @@ -711,6 +716,7 @@ "const-oid_0.9.6": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"}],\"features\":{\"db\":[],\"std\":[]}}", "const_format_0.2.35": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"arrayvec\",\"req\":\"^0.7.0\"},{\"name\":\"const_format_proc_macros\",\"req\":\"=0.2.34\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"fastrand\",\"req\":\"^1.3.5\"},{\"default_features\":false,\"name\":\"konst\",\"optional\":true,\"req\":\"^0.2.13\"}],\"features\":{\"__debug\":[\"const_format_proc_macros/debug\"],\"__docsrs\":[],\"__inline_const_pat_tests\":[\"__test\",\"fmt\"],\"__only_new_tests\":[\"__test\"],\"__test\":[],\"all\":[\"fmt\",\"derive\",\"rust_1_64\",\"assert\"],\"assert\":[\"assertc\"],\"assertc\":[\"fmt\",\"assertcp\"],\"assertcp\":[\"rust_1_51\"],\"const_generics\":[\"rust_1_51\"],\"constant_time_as_str\":[\"fmt\"],\"default\":[],\"derive\":[\"fmt\",\"const_format_proc_macros/derive\"],\"fmt\":[\"rust_1_83\"],\"more_str_macros\":[\"rust_1_64\"],\"nightly_const_generics\":[\"const_generics\"],\"rust_1_51\":[],\"rust_1_64\":[\"rust_1_51\",\"konst\",\"konst/rust_1_64\"],\"rust_1_83\":[\"rust_1_64\"]}}", "const_format_proc_macros_0.2.34": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"fastrand\",\"req\":\"^1.3.4\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.19\"},{\"name\":\"quote\",\"req\":\"^1.0.7\"},{\"default_features\":false,\"features\":[\"parsing\",\"proc-macro\"],\"name\":\"syn\",\"optional\":true,\"req\":\"^1.0.38\"},{\"name\":\"unicode-xid\",\"req\":\"^0.2\"}],\"features\":{\"all\":[\"derive\"],\"debug\":[\"syn/extra-traits\"],\"default\":[],\"derive\":[\"syn\",\"syn/derive\",\"syn/printing\"]}}", + "constant_time_eq_0.1.5": "{\"dependencies\":[],\"features\":{}}", "constant_time_eq_0.3.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"count_instructions\",\"req\":\"^0.1.3\"},{\"features\":[\"cargo_bench_support\",\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"}],\"features\":{\"count_instructions_test\":[]}}", "convert_case_0.10.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"unicode-segmentation\",\"req\":\"^1.9.0\"}],\"features\":{}}", "convert_case_0.6.0": "{\"dependencies\":[{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"strum\",\"req\":\"^0.18.0\"},{\"kind\":\"dev\",\"name\":\"strum_macros\",\"req\":\"^0.18.0\"},{\"name\":\"unicode-segmentation\",\"req\":\"^1.9.0\"}],\"features\":{\"random\":[\"rand\"]}}", @@ -734,6 +740,8 @@ "crossterm_winapi_0.9.1": "{\"dependencies\":[{\"features\":[\"winbase\",\"consoleapi\",\"processenv\",\"handleapi\",\"synchapi\",\"impl-default\"],\"name\":\"winapi\",\"req\":\"^0.3.8\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "crunchy_0.2.4": "{\"dependencies\":[],\"features\":{\"default\":[\"limit_128\"],\"limit_1024\":[],\"limit_128\":[],\"limit_2048\":[],\"limit_256\":[],\"limit_512\":[],\"limit_64\":[],\"std\":[]}}", "crypto-common_0.1.7": "{\"dependencies\":[{\"features\":[\"more_lengths\"],\"name\":\"generic-array\",\"req\":\"=0.14.7\"},{\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"typenum\",\"req\":\"^1.14\"}],\"features\":{\"getrandom\":[\"rand_core/getrandom\"],\"std\":[]}}", + "cssparser-macros_0.6.1": "{\"dependencies\":[{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"full\",\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", + "cssparser_0.31.2": "{\"dependencies\":[{\"name\":\"cssparser-macros\",\"req\":\"^0.6.1\"},{\"kind\":\"dev\",\"name\":\"difference\",\"req\":\"^2.0\"},{\"name\":\"dtoa-short\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"encoding_rs\",\"req\":\"^0.8\"},{\"name\":\"itoa\",\"req\":\"^1.0\"},{\"features\":[\"macros\"],\"name\":\"phf\",\"req\":\">=0.8, <=0.11\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"smallvec\",\"req\":\"^1.0\"}],\"features\":{\"bench\":[],\"dummy_match_byte\":[]}}", "csv-core_0.1.13": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"arrayvec\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2\"}],\"features\":{\"default\":[],\"libc\":[\"memchr/libc\"]}}", "csv_1.4.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\",\"serde\"],\"kind\":\"dev\",\"name\":\"bstr\",\"req\":\"^1.7.0\"},{\"name\":\"csv-core\",\"req\":\"^0.1.11\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"ryu\",\"req\":\"^1\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.221\"},{\"name\":\"serde_core\",\"req\":\"^1.0.221\"}],\"features\":{}}", "ctor-proc-macro_0.0.7": "{\"dependencies\":[],\"features\":{\"default\":[]}}", @@ -766,6 +774,7 @@ "derive_arbitrary_1.4.2": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"derive\",\"parsing\",\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "derive_more-impl_1.0.0": "{\"dependencies\":[{\"name\":\"convert_case\",\"optional\":true,\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.13.0\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"syn\",\"req\":\"^2.0.45\"},{\"name\":\"unicode-xid\",\"optional\":true,\"req\":\"^0.2.2\"}],\"features\":{\"add\":[],\"add_assign\":[],\"as_ref\":[\"syn/extra-traits\",\"syn/visit\"],\"constructor\":[],\"debug\":[\"syn/extra-traits\",\"dep:unicode-xid\"],\"default\":[],\"deref\":[],\"deref_mut\":[],\"display\":[\"syn/extra-traits\",\"dep:unicode-xid\"],\"error\":[\"syn/extra-traits\"],\"from\":[\"syn/extra-traits\"],\"from_str\":[],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[],\"index_mut\":[],\"into\":[\"syn/extra-traits\"],\"into_iterator\":[],\"is_variant\":[\"dep:convert_case\"],\"mul\":[\"syn/extra-traits\"],\"mul_assign\":[\"syn/extra-traits\"],\"not\":[\"syn/extra-traits\"],\"sum\":[],\"testing-helpers\":[\"dep:rustc_version\"],\"try_from\":[],\"try_into\":[\"syn/extra-traits\"],\"try_unwrap\":[\"dep:convert_case\"],\"unwrap\":[\"dep:convert_case\"]}}", "derive_more-impl_2.1.1": "{\"dependencies\":[{\"name\":\"convert_case\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.14.0\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"req\":\"^0.4\"},{\"name\":\"syn\",\"req\":\"^2.0.45\"},{\"name\":\"unicode-xid\",\"optional\":true,\"req\":\"^0.2.2\"}],\"features\":{\"add\":[\"syn/extra-traits\",\"syn/visit\"],\"add_assign\":[\"syn/extra-traits\",\"syn/visit\"],\"as_ref\":[\"syn/extra-traits\",\"syn/visit\"],\"constructor\":[],\"debug\":[\"syn/extra-traits\",\"dep:unicode-xid\"],\"default\":[],\"deref\":[],\"deref_mut\":[],\"display\":[\"syn/extra-traits\",\"dep:unicode-xid\",\"dep:convert_case\"],\"eq\":[\"syn/extra-traits\",\"syn/visit\"],\"error\":[\"syn/extra-traits\"],\"from\":[\"syn/extra-traits\"],\"from_str\":[\"syn/full\",\"syn/visit\",\"dep:convert_case\"],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"eq\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[],\"index_mut\":[],\"into\":[\"syn/extra-traits\",\"syn/visit-mut\"],\"into_iterator\":[],\"is_variant\":[\"dep:convert_case\"],\"mul\":[\"syn/extra-traits\",\"syn/visit\"],\"mul_assign\":[\"syn/extra-traits\",\"syn/visit\"],\"not\":[\"syn/extra-traits\"],\"sum\":[],\"testing-helpers\":[\"syn/full\"],\"try_from\":[],\"try_into\":[\"syn/extra-traits\",\"syn/full\",\"syn/visit-mut\"],\"try_unwrap\":[\"dep:convert_case\"],\"unwrap\":[\"dep:convert_case\"]}}", + "derive_more_0.99.20": "{\"dependencies\":[{\"name\":\"convert_case\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"build\",\"name\":\"peg\",\"optional\":true,\"req\":\"^0.5\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"add\":[],\"add_assign\":[],\"as_mut\":[],\"as_ref\":[],\"constructor\":[],\"default\":[\"add_assign\",\"add\",\"as_mut\",\"as_ref\",\"constructor\",\"deref\",\"deref_mut\",\"display\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"iterator\",\"mul_assign\",\"mul\",\"not\",\"sum\",\"try_into\",\"is_variant\",\"unwrap\"],\"deref\":[],\"deref_mut\":[],\"display\":[\"syn/extra-traits\"],\"error\":[\"syn/extra-traits\"],\"from\":[\"syn/extra-traits\"],\"from_str\":[],\"generate-parsing-rs\":[\"peg\"],\"index\":[],\"index_mut\":[],\"into\":[\"syn/extra-traits\"],\"into_iterator\":[],\"is_variant\":[\"convert_case\"],\"iterator\":[],\"mul\":[\"syn/extra-traits\"],\"mul_assign\":[\"syn/extra-traits\"],\"nightly\":[],\"not\":[\"syn/extra-traits\"],\"sum\":[],\"testing-helpers\":[\"rustc_version\"],\"track-caller\":[],\"try_into\":[\"syn/extra-traits\"],\"unwrap\":[\"convert_case\",\"rustc_version\"]}}", "derive_more_1.0.0": "{\"dependencies\":[{\"name\":\"derive_more-impl\",\"req\":\"=1.0.0\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.56\"}],\"features\":{\"add\":[\"derive_more-impl/add\"],\"add_assign\":[\"derive_more-impl/add_assign\"],\"as_ref\":[\"derive_more-impl/as_ref\"],\"constructor\":[\"derive_more-impl/constructor\"],\"debug\":[\"derive_more-impl/debug\"],\"default\":[\"std\"],\"deref\":[\"derive_more-impl/deref\"],\"deref_mut\":[\"derive_more-impl/deref_mut\"],\"display\":[\"derive_more-impl/display\"],\"error\":[\"derive_more-impl/error\"],\"from\":[\"derive_more-impl/from\"],\"from_str\":[\"derive_more-impl/from_str\"],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[\"derive_more-impl/index\"],\"index_mut\":[\"derive_more-impl/index_mut\"],\"into\":[\"derive_more-impl/into\"],\"into_iterator\":[\"derive_more-impl/into_iterator\"],\"is_variant\":[\"derive_more-impl/is_variant\"],\"mul\":[\"derive_more-impl/mul\"],\"mul_assign\":[\"derive_more-impl/mul_assign\"],\"not\":[\"derive_more-impl/not\"],\"std\":[],\"sum\":[\"derive_more-impl/sum\"],\"testing-helpers\":[\"derive_more-impl/testing-helpers\",\"dep:rustc_version\"],\"try_from\":[\"derive_more-impl/try_from\"],\"try_into\":[\"derive_more-impl/try_into\"],\"try_unwrap\":[\"derive_more-impl/try_unwrap\"],\"unwrap\":[\"derive_more-impl/unwrap\"]}}", "derive_more_2.1.1": "{\"dependencies\":[{\"name\":\"derive_more-impl\",\"req\":\"=2.1.1\"},{\"kind\":\"build\",\"name\":\"rustc_version\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.56\"}],\"features\":{\"add\":[\"derive_more-impl/add\"],\"add_assign\":[\"derive_more-impl/add_assign\"],\"as_ref\":[\"derive_more-impl/as_ref\"],\"constructor\":[\"derive_more-impl/constructor\"],\"debug\":[\"derive_more-impl/debug\"],\"default\":[\"std\"],\"deref\":[\"derive_more-impl/deref\"],\"deref_mut\":[\"derive_more-impl/deref_mut\"],\"display\":[\"derive_more-impl/display\"],\"eq\":[\"derive_more-impl/eq\"],\"error\":[\"derive_more-impl/error\"],\"from\":[\"derive_more-impl/from\"],\"from_str\":[\"derive_more-impl/from_str\"],\"full\":[\"add\",\"add_assign\",\"as_ref\",\"constructor\",\"debug\",\"deref\",\"deref_mut\",\"display\",\"eq\",\"error\",\"from\",\"from_str\",\"index\",\"index_mut\",\"into\",\"into_iterator\",\"is_variant\",\"mul\",\"mul_assign\",\"not\",\"sum\",\"try_from\",\"try_into\",\"try_unwrap\",\"unwrap\"],\"index\":[\"derive_more-impl/index\"],\"index_mut\":[\"derive_more-impl/index_mut\"],\"into\":[\"derive_more-impl/into\"],\"into_iterator\":[\"derive_more-impl/into_iterator\"],\"is_variant\":[\"derive_more-impl/is_variant\"],\"mul\":[\"derive_more-impl/mul\"],\"mul_assign\":[\"derive_more-impl/mul_assign\"],\"not\":[\"derive_more-impl/not\"],\"std\":[],\"sum\":[\"derive_more-impl/sum\"],\"testing-helpers\":[\"derive_more-impl/testing-helpers\",\"dep:rustc_version\"],\"try_from\":[\"derive_more-impl/try_from\"],\"try_into\":[\"derive_more-impl/try_into\"],\"try_unwrap\":[\"derive_more-impl/try_unwrap\"],\"unwrap\":[\"derive_more-impl/unwrap\"]}}", "deunicode_1.6.2": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"alloc\"]}}", @@ -782,12 +791,15 @@ "displaydoc_0.2.5": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"name\":\"syn\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"thiserror\",\"req\":\"^1.0.24\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "dotenvy_0.15.7": "{\"dependencies\":[{\"name\":\"clap\",\"optional\":true,\"req\":\"^3.2\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.16.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.3.0\"}],\"features\":{\"cli\":[\"clap\"]}}", "downcast-rs_1.2.1": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", + "dtoa-short_0.3.5": "{\"dependencies\":[{\"name\":\"dtoa\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"float-cmp\",\"req\":\"^0.4\"}],\"features\":{}}", + "dtoa_1.0.11": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\",\"target\":\"cfg(not(miri))\"},{\"name\":\"no-panic\",\"optional\":true,\"req\":\"^0.1\"}],\"features\":{}}", "dtor-proc-macro_0.0.6": "{\"dependencies\":[],\"features\":{\"default\":[]}}", "dtor_0.1.1": "{\"dependencies\":[{\"name\":\"dtor-proc-macro\",\"optional\":true,\"req\":\"=0.0.6\"},{\"kind\":\"dev\",\"name\":\"libc-print\",\"req\":\"^0.1.20\"}],\"features\":{\"__no_warn_on_missing_unsafe\":[],\"default\":[\"proc_macro\",\"__no_warn_on_missing_unsafe\"],\"proc_macro\":[\"dep:dtor-proc-macro\"],\"used_linker\":[]}}", "dunce_1.0.5": "{\"dependencies\":[],\"features\":{}}", "dupe_0.9.1": "{\"dependencies\":[{\"name\":\"dupe_derive\",\"req\":\"=0.9.1\"}],\"features\":{}}", "dupe_derive_0.9.1": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0.3\"},{\"features\":[\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "dyn-clone_1.0.20": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.66\"}],\"features\":{}}", + "ego-tree_0.6.3": "{\"dependencies\":[],\"features\":{}}", "either_1.15.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\",\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.95\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[],\"use_std\":[\"std\"]}}", "ena_0.14.3": "{\"dependencies\":[{\"name\":\"dogged\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"log\",\"req\":\"^0.4\"}],\"features\":{\"bench\":[],\"persistent\":[\"dogged\"]}}", "encode_unicode_1.0.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ascii\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.0\",\"target\":\"cfg(unix)\"},{\"features\":[\"https-native\"],\"kind\":\"dev\",\"name\":\"minreq\",\"req\":\"^2.6\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", @@ -840,6 +852,7 @@ "form_urlencoded_1.2.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"percent-encoding\",\"req\":\"^2.3.0\"}],\"features\":{\"alloc\":[\"percent-encoding/alloc\"],\"default\":[\"std\"],\"std\":[\"alloc\",\"percent-encoding/std\"]}}", "fs_extra_1.3.0": "{\"dependencies\":[],\"features\":{}}", "fsevent-sys_4.1.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.68\"}],\"features\":{}}", + "futf_0.1.5": "{\"dependencies\":[{\"name\":\"mac\",\"req\":\"^0.1.0\"},{\"name\":\"new_debug_unreachable\",\"req\":\"^1.0.2\"}],\"features\":{}}", "futures-channel_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-sink\",\"optional\":true,\"req\":\"^0.3.31\"}],\"features\":{\"alloc\":[\"futures-core/alloc\"],\"cfg-target-has-atomic\":[],\"default\":[\"std\"],\"sink\":[\"futures-sink\"],\"std\":[\"alloc\",\"futures-core/std\"],\"unstable\":[]}}", "futures-core_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"require-cas\"],\"name\":\"portable-atomic\",\"optional\":true,\"req\":\"^1.3\"}],\"features\":{\"alloc\":[],\"cfg-target-has-atomic\":[],\"default\":[\"std\"],\"std\":[\"alloc\"],\"unstable\":[]}}", "futures-executor_0.3.31": "{\"dependencies\":[{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-task\",\"req\":\"^0.3.31\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3.31\"},{\"name\":\"num_cpus\",\"optional\":true,\"req\":\"^1.8.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[\"futures-core/std\",\"futures-task/std\",\"futures-util/std\"],\"thread-pool\":[\"std\",\"num_cpus\"]}}", @@ -869,6 +882,7 @@ "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=9200079d3b54a1ff51072e24d81fd354f085156f#9200079d3b54a1ff51072e24d81fd354f085156f_tungstenite": "{\"dependencies\":[{\"name\":\"bytes\"},{\"default_features\":true,\"features\":[],\"name\":\"data-encoding\",\"optional\":true},{\"default_features\":false,\"features\":[\"zlib\"],\"name\":\"flate2\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"headers\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"http\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"httparse\",\"optional\":true},{\"name\":\"log\"},{\"default_features\":true,\"features\":[],\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\"},{\"name\":\"rand\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"rustls\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"rustls-native-certs\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"rustls-pki-types\",\"optional\":true},{\"default_features\":true,\"features\":[],\"name\":\"sha1\",\"optional\":true},{\"name\":\"thiserror\"},{\"default_features\":true,\"features\":[],\"name\":\"url\",\"optional\":true},{\"name\":\"utf-8\"},{\"default_features\":true,\"features\":[],\"name\":\"webpki-roots\",\"optional\":true}],\"features\":{\"__rustls-tls\":[\"rustls\",\"rustls-pki-types\"],\"default\":[\"handshake\"],\"deflate\":[\"headers\",\"flate2\"],\"handshake\":[\"data-encoding\",\"headers\",\"httparse\",\"sha1\"],\"headers\":[\"http\",\"dep:headers\"],\"native-tls\":[\"native-tls-crate\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\"],\"proxy\":[\"handshake\"],\"rustls-tls-native-roots\":[\"__rustls-tls\",\"rustls-native-certs\"],\"rustls-tls-webpki-roots\":[\"__rustls-tls\",\"webpki-roots\"],\"url\":[\"dep:url\"]},\"strip_prefix\":\"\"}", "glob_0.3.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tempdir\",\"req\":\"^0.3\"}],\"features\":{}}", "globset_0.4.18": "{\"dependencies\":[{\"name\":\"aho-corasick\",\"req\":\"^1.1.1\"},{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.3.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"bstr\",\"req\":\"^1.6.2\"},{\"kind\":\"dev\",\"name\":\"glob\",\"req\":\"^0.3.1\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"default_features\":false,\"features\":[\"std\",\"perf\",\"syntax\",\"meta\",\"nfa\",\"hybrid\"],\"name\":\"regex-automata\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"regex-syntax\",\"req\":\"^0.8.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.188\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.107\"}],\"features\":{\"arbitrary\":[\"dep:arbitrary\"],\"default\":[\"log\"],\"serde1\":[\"serde\"],\"simd-accel\":[]}}", + "h2_0.3.27": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"name\":\"slab\",\"req\":\"^0.4.2\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.24\"},{\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^0.25\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", "h2_0.4.13": "{\"dependencies\":[{\"name\":\"atomic-waker\",\"req\":\"^1.0.0\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"http\",\"req\":\"^1\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"name\":\"slab\",\"req\":\"^0.4.2\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", "half_2.7.1": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.4.1\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"bytemuck\",\"optional\":true,\"req\":\"^1.4.1\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"crunchy\",\"req\":\"^0.2.2\",\"target\":\"cfg(target_arch = \\\"spirv\\\")\"},{\"kind\":\"dev\",\"name\":\"crunchy\",\"req\":\"^0.2.2\"},{\"default_features\":false,\"features\":[\"libm\"],\"name\":\"num-traits\",\"optional\":true,\"req\":\"^0.2.16\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"thread_rng\"],\"name\":\"rand\",\"optional\":true,\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9.0\"},{\"default_features\":false,\"name\":\"rand_distr\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"rkyv\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"derive\",\"simd\"],\"name\":\"zerocopy\",\"req\":\"^0.8.26\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"nightly\":[],\"rand_distr\":[\"dep:rand\",\"dep:rand_distr\"],\"std\":[\"alloc\"],\"use-intrinsics\":[],\"zerocopy\":[]}}", "hashbrown_0.12.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ahash\",\"optional\":true,\"req\":\"^0.7.0\"},{\"name\":\"alloc\",\"optional\":true,\"package\":\"rustc-std-workspace-alloc\",\"req\":\"^1.0.0\"},{\"name\":\"bumpalo\",\"optional\":true,\"req\":\"^3.5.0\"},{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.2\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.1\"},{\"kind\":\"dev\",\"name\":\"fnv\",\"req\":\"^1.0.7\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"}],\"features\":{\"ahash-compile-time-rng\":[\"ahash/compile-time-rng\"],\"default\":[\"ahash\",\"inline-more\"],\"inline-more\":[],\"nightly\":[],\"raw\":[],\"rustc-dep-of-std\":[\"nightly\",\"core\",\"compiler_builtins\",\"alloc\",\"rustc-internal-api\"],\"rustc-internal-api\":[]}}", @@ -888,7 +902,9 @@ "home_0.5.12": "{\"dependencies\":[{\"features\":[\"Win32_Foundation\",\"Win32_UI_Shell\",\"Win32_System_Com\"],\"name\":\"windows-sys\",\"req\":\"^0.61\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "hostname_0.4.2": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(any(unix, target_os = \\\"redox\\\"))\"},{\"kind\":\"dev\",\"name\":\"similar-asserts\",\"req\":\"^1.6.1\"},{\"kind\":\"dev\",\"name\":\"version-sync\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"windows-bindgen\",\"req\":\"^0.65\"},{\"name\":\"windows-link\",\"req\":\"^0.2\",\"target\":\"cfg(target_os = \\\"windows\\\")\"}],\"features\":{\"default\":[],\"set\":[]}}", "hound_3.5.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"cpal\",\"req\":\"^0.2.12\"}],\"features\":{}}", + "html5ever_0.26.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\",\"target\":\"cfg(bench)\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"mac\",\"req\":\"^0.1\"},{\"name\":\"markup5ever\",\"req\":\"^0.11\"},{\"kind\":\"build\",\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"kind\":\"build\",\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"extra-traits\",\"full\",\"fold\"],\"kind\":\"build\",\"name\":\"syn\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"typed-arena\",\"req\":\"^1.3.0\"}],\"features\":{}}", "http-body-util_0.1.3": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"macros\",\"rt\",\"sync\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"}],\"features\":{\"channel\":[\"dep:tokio\"],\"default\":[],\"full\":[\"channel\"]}}", + "http-body_0.4.6": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"macros\",\"rt\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"}],\"features\":{}}", "http-body_1.0.1": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"http\",\"req\":\"^1\"}],\"features\":{}}", "http-range-header_0.4.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.8.3\"}],\"features\":{}}", "http_0.2.12": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"kind\":\"dev\",\"name\":\"indexmap\",\"req\":\"<=1.8\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.7.0\"},{\"kind\":\"dev\",\"name\":\"seahash\",\"req\":\"^3.0.5\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{}}", @@ -897,8 +913,10 @@ "httpdate_1.0.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"}],\"features\":{}}", "hyper-rustls_0.27.7": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"cfg-if\",\"req\":\"^1\"},{\"name\":\"http\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"hyper\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"client-legacy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"server-auto\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.4\"},{\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"rustls\",\"req\":\"^0.23\"},{\"default_features\":false,\"features\":[\"tls12\"],\"kind\":\"dev\",\"name\":\"rustls\",\"req\":\"^0.23\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rustls-pemfile\",\"req\":\"^2\"},{\"name\":\"rustls-platform-verifier\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"tokio\",\"req\":\"^1.0\"},{\"features\":[\"io-std\",\"macros\",\"net\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"aws-lc-rs\":[\"rustls/aws_lc_rs\"],\"default\":[\"native-tokio\",\"http1\",\"tls12\",\"logging\",\"aws-lc-rs\"],\"fips\":[\"aws-lc-rs\",\"rustls/fips\"],\"http1\":[\"hyper-util/http1\"],\"http2\":[\"hyper-util/http2\"],\"logging\":[\"log\",\"tokio-rustls/logging\",\"rustls/logging\"],\"native-tokio\":[\"rustls-native-certs\"],\"ring\":[\"rustls/ring\"],\"tls12\":[\"tokio-rustls/tls12\",\"rustls/tls12\"],\"webpki-tokio\":[\"webpki-roots\"]}}", "hyper-timeout_0.5.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"name\":\"hyper\",\"req\":\"^1.1\"},{\"features\":[\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"hyper-tls\",\"req\":\"^0.6\"},{\"features\":[\"client-legacy\",\"http1\"],\"name\":\"hyper-util\",\"req\":\"^0.1.10\"},{\"features\":[\"client-legacy\",\"http1\",\"server\",\"server-graceful\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.10\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"name\":\"tokio\",\"req\":\"^1.35\"},{\"features\":[\"io-std\",\"io-util\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.35\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"}],\"features\":{}}", + "hyper-tls_0.5.0": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"tcp\",\"client\"],\"name\":\"hyper\",\"req\":\"^0.14.2\"},{\"default_features\":false,\"features\":[\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^0.14.2\"},{\"name\":\"native-tls\",\"req\":\"^0.2.1\"},{\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"io-std\",\"macros\",\"io-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0.0\"},{\"name\":\"tokio-native-tls\",\"req\":\"^0.3\"}],\"features\":{\"vendored\":[\"native-tls/vendored\"]}}", "hyper-tls_0.6.0": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"client-legacy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1.0\"},{\"features\":[\"http1\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.0\"},{\"name\":\"native-tls\",\"req\":\"^0.2.1\"},{\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"io-std\",\"macros\",\"io-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0.0\"},{\"name\":\"tokio-native-tls\",\"req\":\"^0.3\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"}],\"features\":{\"alpn\":[\"native-tls/alpn\"],\"vendored\":[\"native-tls/vendored\"]}}", "hyper-util_0.1.19": "{\"dependencies\":[{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"req\":\"^1.7.1\"},{\"kind\":\"dev\",\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.16\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.16\"},{\"name\":\"http\",\"req\":\"^1.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"req\":\"^1.8.0\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.4.0\"},{\"name\":\"ipnet\",\"optional\":true,\"req\":\"^2.9\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"percent-encoding\",\"optional\":true,\"req\":\"^2.3\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.4\"},{\"kind\":\"dev\",\"name\":\"pnet_datalink\",\"req\":\"^0.35.0\",\"target\":\"cfg(any(target_os = \\\"linux\\\", target_os = \\\"macos\\\"))\"},{\"kind\":\"dev\",\"name\":\"pretty_env_logger\",\"req\":\"^0.5\"},{\"features\":[\"all\"],\"name\":\"socket2\",\"optional\":true,\"req\":\">=0.5.9, <0.7\"},{\"name\":\"system-configuration\",\"optional\":true,\"req\":\">=0.5, <0.7\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"default_features\":false,\"name\":\"tokio\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"macros\",\"test-util\",\"signal\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"name\":\"tower-layer\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tower-test\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"windows-registry\",\"optional\":true,\"req\":\">=0.3, <0.7\",\"target\":\"cfg(windows)\"}],\"features\":{\"__internal_happy_eyeballs_tests\":[],\"client\":[\"hyper/client\",\"tokio/net\",\"dep:tracing\",\"dep:futures-channel\",\"dep:tower-service\"],\"client-legacy\":[\"client\",\"dep:socket2\",\"tokio/sync\",\"dep:libc\",\"dep:futures-util\"],\"client-pool\":[\"client\",\"dep:futures-util\",\"dep:tower-layer\"],\"client-proxy\":[\"client\",\"dep:base64\",\"dep:ipnet\",\"dep:percent-encoding\"],\"client-proxy-system\":[\"dep:system-configuration\",\"dep:windows-registry\"],\"default\":[],\"full\":[\"client\",\"client-legacy\",\"client-pool\",\"client-proxy\",\"client-proxy-system\",\"server\",\"server-auto\",\"server-graceful\",\"service\",\"http1\",\"http2\",\"tokio\",\"tracing\"],\"http1\":[\"hyper/http1\"],\"http2\":[\"hyper/http2\"],\"server\":[\"hyper/server\"],\"server-auto\":[\"server\",\"http1\",\"http2\"],\"server-graceful\":[\"server\",\"tokio/sync\"],\"service\":[\"dep:tower-service\"],\"tokio\":[\"dep:tokio\",\"tokio/rt\",\"tokio/time\"],\"tracing\":[\"dep:tracing\"]}}", + "hyper_0.14.32": "{\"dependencies\":[{\"name\":\"bytes\",\"req\":\"^1\"},{\"name\":\"futures-channel\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.3.24\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"name\":\"http-body\",\"req\":\"^0.4\"},{\"name\":\"httparse\",\"req\":\"^1.8\"},{\"name\":\"httpdate\",\"req\":\"^1.0\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"matches\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.4\"},{\"kind\":\"dev\",\"name\":\"pnet_datalink\",\"req\":\"^0.27.2\",\"target\":\"cfg(any(target_os = \\\"linux\\\", target_os = \\\"macos\\\"))\"},{\"kind\":\"dev\",\"name\":\"pretty_env_logger\",\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"all\"],\"name\":\"socket2\",\"optional\":true,\"req\":\">=0.4.7, <0.6.0\"},{\"kind\":\"dev\",\"name\":\"spmc\",\"req\":\"^0.3\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"req\":\"^1.27\"},{\"features\":[\"fs\",\"macros\",\"io-std\",\"io-util\",\"rt\",\"rt-multi-thread\",\"sync\",\"time\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.27\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"features\":[\"codec\"],\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"make\",\"util\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.4\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.2\"},{\"name\":\"want\",\"req\":\"^0.3\"}],\"features\":{\"__internal_happy_eyeballs_tests\":[],\"backports\":[],\"client\":[],\"default\":[],\"deprecated\":[],\"ffi\":[\"libc\"],\"full\":[\"client\",\"http1\",\"http2\",\"server\",\"stream\",\"runtime\"],\"http1\":[],\"http2\":[\"h2\"],\"nightly\":[],\"runtime\":[\"tcp\",\"tokio/rt\",\"tokio/time\"],\"server\":[],\"stream\":[],\"tcp\":[\"socket2\",\"tokio/net\",\"tokio/rt\",\"tokio/time\"]}}", "hyper_1.8.1": "{\"dependencies\":[{\"name\":\"atomic-waker\",\"optional\":true,\"req\":\"^1.1.2\"},{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"kind\":\"dev\",\"name\":\"form_urlencoded\",\"req\":\"^1\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\"},{\"features\":[\"sink\"],\"kind\":\"dev\",\"name\":\"futures-channel\",\"req\":\"^0.3\"},{\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3.31\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"alloc\",\"sink\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.4.2\"},{\"name\":\"http\",\"req\":\"^1\"},{\"name\":\"http-body\",\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"name\":\"httparse\",\"optional\":true,\"req\":\"^1.9\"},{\"name\":\"httpdate\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"itoa\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"pin-project-lite\",\"optional\":true,\"req\":\"^0.2.4\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.4\"},{\"name\":\"pin-utils\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"pretty_env_logger\",\"req\":\"^0.5\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"const_generics\",\"const_new\"],\"name\":\"smallvec\",\"optional\":true,\"req\":\"^1.12\"},{\"kind\":\"dev\",\"name\":\"spmc\",\"req\":\"^0.3\"},{\"features\":[\"sync\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"fs\",\"macros\",\"net\",\"io-std\",\"io-util\",\"rt\",\"rt-multi-thread\",\"sync\",\"time\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-test\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"tokio-util\",\"req\":\"^0.7.10\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"want\",\"optional\":true,\"req\":\"^0.3\"}],\"features\":{\"capi\":[],\"client\":[\"dep:want\",\"dep:pin-project-lite\",\"dep:smallvec\"],\"default\":[],\"ffi\":[\"dep:http-body-util\",\"dep:futures-util\"],\"full\":[\"client\",\"http1\",\"http2\",\"server\"],\"http1\":[\"dep:atomic-waker\",\"dep:futures-channel\",\"dep:futures-core\",\"dep:httparse\",\"dep:itoa\",\"dep:pin-utils\"],\"http2\":[\"dep:futures-channel\",\"dep:futures-core\",\"dep:h2\"],\"nightly\":[],\"server\":[\"dep:httpdate\",\"dep:pin-project-lite\",\"dep:smallvec\"],\"tracing\":[\"dep:tracing\"]}}", "i18n-config_0.4.8": "{\"dependencies\":[{\"name\":\"basic-toml\",\"req\":\"^0.1\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"features\":[\"serde\"],\"name\":\"unic-langid\",\"req\":\"^0.9\"}],\"features\":{}}", "i18n-embed-fl_0.9.4": "{\"dependencies\":[{\"name\":\"dashmap\",\"optional\":true,\"req\":\"^6.0\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"name\":\"find-crate\",\"req\":\"^0.6\"},{\"name\":\"fluent\",\"req\":\"^0.16\"},{\"name\":\"fluent-syntax\",\"req\":\"^0.11\"},{\"name\":\"i18n-config\",\"req\":\"^0.4.7\"},{\"features\":[\"fluent-system\",\"filesystem-assets\"],\"name\":\"i18n-embed\",\"req\":\"^0.15.4\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.4\"},{\"name\":\"proc-macro-error2\",\"req\":\"^2.0.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rust-embed\",\"req\":\"^8.0\"},{\"name\":\"strsim\",\"req\":\"^0.11\"},{\"features\":[\"derive\",\"proc-macro\",\"parsing\",\"printing\",\"extra-traits\",\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"name\":\"unic-langid\",\"req\":\"^0.9\"}],\"features\":{\"dashmap\":[\"dep:dashmap\"]}}", @@ -987,8 +1005,10 @@ "lsp-types_0.94.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^1.0.1\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0.34\"},{\"name\":\"serde_json\",\"req\":\"^1.0.50\"},{\"name\":\"serde_repr\",\"req\":\"^0.1\"},{\"features\":[\"serde\"],\"name\":\"url\",\"req\":\"^2.0.0\"}],\"features\":{\"default\":[],\"proposed\":[]}}", "lzma-rs_0.3.0": "{\"dependencies\":[{\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"name\":\"crc\",\"req\":\"^3.0.0\"},{\"name\":\"env_logger\",\"optional\":true,\"req\":\"^0.9.0\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"kind\":\"dev\",\"name\":\"rust-lzma\",\"req\":\"^0.5\"}],\"features\":{\"enable_logging\":[\"env_logger\",\"log\"],\"raw_decoder\":[],\"stream\":[]}}", "lzma-sys_0.1.20": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.34\"},{\"name\":\"libc\",\"req\":\"^0.2.51\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.14\"}],\"features\":{\"static\":[]}}", + "mac_0.1.1": "{\"dependencies\":[],\"features\":{}}", "mach2_0.4.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_os = \\\"macos\\\", target_os = \\\"ios\\\"))\"}],\"features\":{\"default\":[],\"unstable\":[]}}", "maplit_1.0.2": "{\"dependencies\":[],\"features\":{}}", + "markup5ever_0.11.0": "{\"dependencies\":[{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"phf\",\"req\":\"^0.10\"},{\"kind\":\"build\",\"name\":\"phf_codegen\",\"req\":\"^0.10\"},{\"name\":\"string_cache\",\"req\":\"^0.8\"},{\"kind\":\"build\",\"name\":\"string_cache_codegen\",\"req\":\"^0.5.1\"},{\"name\":\"tendril\",\"req\":\"^0.4\"}],\"features\":{}}", "matchers_0.2.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"syntax\",\"dfa-build\",\"dfa-search\"],\"name\":\"regex-automata\",\"req\":\"^0.4\"}],\"features\":{\"unicode\":[\"regex-automata/unicode\"]}}", "matchit_0.8.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"actix-router\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.4\"},{\"kind\":\"dev\",\"name\":\"gonzales\",\"req\":\"^0.0.3-beta\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"path-tree\",\"req\":\"^0.2.2\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.5.4\"},{\"kind\":\"dev\",\"name\":\"route-recognizer\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"routefinder\",\"req\":\"^0.5.2\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"make\",\"util\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.4\"}],\"features\":{\"__test_helpers\":[],\"default\":[]}}", "matchit_0.9.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"actix-router\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"gonzales\",\"req\":\"^0.0.3-beta\"},{\"kind\":\"dev\",\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"features\":[\"http1\",\"server\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"path-tree\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"route-recognizer\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"routefinder\",\"req\":\"^0.5\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"make\",\"util\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"kind\":\"dev\",\"name\":\"wayfind\",\"req\":\"^0.8\"}],\"features\":{\"__test_helpers\":[],\"default\":[]}}", @@ -1080,17 +1100,26 @@ "parking_2.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"easy-parallel\",\"req\":\"^3.0.0\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\",\"target\":\"cfg(loom)\"}],\"features\":{}}", "parking_lot_0.12.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"name\":\"lock_api\",\"req\":\"^0.4.14\"},{\"name\":\"parking_lot_core\",\"req\":\"^0.9.12\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"}],\"features\":{\"arc_lock\":[\"lock_api/arc_lock\"],\"deadlock_detection\":[\"parking_lot_core/deadlock_detection\"],\"default\":[],\"hardware-lock-elision\":[],\"nightly\":[\"parking_lot_core/nightly\",\"lock_api/nightly\"],\"owning_ref\":[\"lock_api/owning_ref\"],\"send_guard\":[],\"serde\":[\"lock_api/serde\"]}}", "parking_lot_core_0.9.12": "{\"dependencies\":[{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.60\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"libc\",\"req\":\"^0.2.95\",\"target\":\"cfg(unix)\"},{\"name\":\"petgraph\",\"optional\":true,\"req\":\"^0.6.0\"},{\"name\":\"redox_syscall\",\"req\":\"^0.5\",\"target\":\"cfg(target_os = \\\"redox\\\")\"},{\"name\":\"smallvec\",\"req\":\"^1.6.1\"},{\"name\":\"windows-link\",\"req\":\"^0.2.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"deadlock_detection\":[\"petgraph\",\"backtrace\"],\"nightly\":[]}}", + "password-hash_0.4.2": "{\"dependencies\":[{\"name\":\"base64ct\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"}],\"features\":{\"alloc\":[\"base64ct/alloc\"],\"default\":[\"rand_core\"],\"std\":[\"alloc\",\"base64ct/std\",\"rand_core/std\"]}}", "paste_1.0.15": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"paste-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.49\"}],\"features\":{}}", "pastey_0.2.1": "{\"dependencies\":[],\"features\":{}}", "path-absolutize_3.1.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"path-dedot\",\"req\":\"^3.1.1\"},{\"kind\":\"dev\",\"name\":\"slash-formatter\",\"req\":\"^3\",\"target\":\"cfg(windows)\"}],\"features\":{\"lazy_static_cache\":[\"path-dedot/lazy_static_cache\"],\"once_cell_cache\":[\"path-dedot/once_cell_cache\"],\"unsafe_cache\":[\"path-dedot/unsafe_cache\"],\"use_unix_paths_on_wasm\":[\"path-dedot/use_unix_paths_on_wasm\"]}}", "path-dedot_3.1.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"lazy_static\",\"optional\":true,\"req\":\"^1.4\"},{\"name\":\"once_cell\",\"req\":\"^1.4\"}],\"features\":{\"lazy_static_cache\":[\"lazy_static\"],\"once_cell_cache\":[],\"unsafe_cache\":[],\"use_unix_paths_on_wasm\":[]}}", "pathdiff_0.2.3": "{\"dependencies\":[{\"name\":\"camino\",\"optional\":true,\"req\":\"^1.0.5\"},{\"kind\":\"dev\",\"name\":\"cfg-if\",\"req\":\"^1.0.0\"}],\"features\":{}}", + "pbkdf2_0.11.0": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.3\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"hmac\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.2\"},{\"default_features\":false,\"name\":\"sha1\",\"optional\":true,\"package\":\"sha-1\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha1\",\"package\":\"sha-1\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"simple\"],\"parallel\":[\"rayon\",\"std\"],\"simple\":[\"hmac\",\"password-hash\",\"sha2\"],\"std\":[\"password-hash/std\"]}}", "pbkdf2_0.12.2": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"hmac\",\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.7\"},{\"default_features\":false,\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha1\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"streebog\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"hmac\"],\"parallel\":[\"rayon\",\"std\"],\"simple\":[\"hmac\",\"password-hash\",\"sha2\"],\"std\":[\"password-hash/std\"]}}", "pem-rfc7468_0.7.0": "{\"dependencies\":[{\"name\":\"base64ct\",\"req\":\"^1.4\"}],\"features\":{\"alloc\":[\"base64ct/alloc\"],\"std\":[\"alloc\",\"base64ct/std\"]}}", "pem_3.0.6": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"base64\",\"req\":\"^0.22.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"}],\"features\":{\"default\":[\"std\"],\"serde\":[\"dep:serde_core\"],\"std\":[\"base64/std\",\"serde_core?/std\"]}}", "percent-encoding_2.3.2": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "petgraph_0.6.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"kind\":\"dev\",\"name\":\"defmac\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"name\":\"fixedbitset\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2.1\"},{\"name\":\"indexmap\",\"req\":\"^2.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"odds\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.5.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.5.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"all\":[\"unstable\",\"quickcheck\",\"matrix_graph\",\"stable_graph\",\"graphmap\",\"rayon\"],\"default\":[\"graphmap\",\"stable_graph\",\"matrix_graph\"],\"generate\":[],\"graphmap\":[],\"matrix_graph\":[],\"rayon\":[\"dep:rayon\",\"indexmap/rayon\"],\"serde-1\":[\"serde\",\"serde_derive\"],\"stable_graph\":[],\"unstable\":[\"generate\"]}}", "petgraph_0.8.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"ahash\",\"req\":\"^0.7.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"kind\":\"dev\",\"name\":\"defmac\",\"req\":\"^0.2.1\"},{\"name\":\"dot-parser\",\"optional\":true,\"req\":\"^0.5.1\"},{\"name\":\"dot-parser-macros\",\"optional\":true,\"req\":\"^0.5.1\"},{\"default_features\":false,\"name\":\"fixedbitset\",\"req\":\"^0.5.7\"},{\"kind\":\"dev\",\"name\":\"fxhash\",\"req\":\"^0.2.1\"},{\"default_features\":false,\"features\":[\"default-hasher\",\"inline-more\"],\"name\":\"hashbrown\",\"req\":\"^0.15.0\"},{\"default_features\":false,\"name\":\"indexmap\",\"req\":\"^2.5.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.12.1\"},{\"kind\":\"dev\",\"name\":\"odds\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"name\":\"quickcheck\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.5.5\"},{\"name\":\"rayon\",\"optional\":true,\"req\":\"^1.5.3\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"all\":[\"unstable\",\"quickcheck\",\"matrix_graph\",\"stable_graph\",\"graphmap\",\"rayon\",\"dot_parser\"],\"default\":[\"std\",\"graphmap\",\"stable_graph\",\"matrix_graph\"],\"dot_parser\":[\"std\",\"dep:dot-parser\",\"dep:dot-parser-macros\"],\"generate\":[],\"graphmap\":[],\"matrix_graph\":[],\"quickcheck\":[\"std\",\"dep:quickcheck\",\"graphmap\",\"stable_graph\"],\"rayon\":[\"std\",\"dep:rayon\",\"indexmap/rayon\",\"hashbrown/rayon\"],\"serde-1\":[\"serde\",\"serde_derive\"],\"stable_graph\":[\"serde?/alloc\"],\"std\":[\"indexmap/std\"],\"unstable\":[\"generate\"]}}", + "phf_0.10.1": "{\"dependencies\":[{\"name\":\"phf_macros\",\"optional\":true,\"req\":\"^0.10.0\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.10.0\"},{\"name\":\"proc-macro-hack\",\"optional\":true,\"req\":\"^0.5.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"macros\":[\"phf_macros\",\"proc-macro-hack\"],\"std\":[\"phf_shared/std\"],\"uncased\":[\"phf_shared/uncased\"],\"unicase\":[\"phf_shared/unicase\"]}}", + "phf_0.11.3": "{\"dependencies\":[{\"name\":\"phf_macros\",\"optional\":true,\"req\":\"^0.11.3\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.11.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"macros\":[\"phf_macros\"],\"std\":[\"phf_shared/std\"],\"uncased\":[\"phf_shared/uncased\"],\"unicase\":[\"phf_macros?/unicase\",\"phf_shared/unicase\"]}}", + "phf_codegen_0.10.0": "{\"dependencies\":[{\"name\":\"phf_generator\",\"req\":\"^0.10.0\"},{\"name\":\"phf_shared\",\"req\":\"^0.10.0\"}],\"features\":{}}", + "phf_generator_0.10.0": "{\"dependencies\":[{\"name\":\"criterion\",\"optional\":true,\"req\":\"=0.3.4\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"=0.3.4\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.10.0\"},{\"features\":[\"small_rng\"],\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{}}", + "phf_generator_0.11.3": "{\"dependencies\":[{\"name\":\"criterion\",\"optional\":true,\"req\":\"^0.3.6\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.11.2\"},{\"default_features\":false,\"features\":[\"small_rng\"],\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{}}", + "phf_macros_0.11.3": "{\"dependencies\":[{\"name\":\"phf_generator\",\"req\":\"^0.11.1\"},{\"default_features\":false,\"name\":\"phf_shared\",\"req\":\"^0.11.2\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"},{\"name\":\"unicase_\",\"optional\":true,\"package\":\"unicase\",\"req\":\"^2.4.0\"}],\"features\":{\"unicase\":[\"unicase_\",\"phf_shared/unicase\"]}}", + "phf_shared_0.10.0": "{\"dependencies\":[{\"name\":\"siphasher\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9.6\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.4.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "phf_shared_0.11.3": "{\"dependencies\":[{\"name\":\"siphasher\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"uncased\",\"optional\":true,\"req\":\"^0.9.9\"},{\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.4.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "pin-project-internal_1.1.10": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"name\":\"quote\",\"req\":\"^1.0.25\"},{\"default_features\":false,\"features\":[\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\",\"full\",\"visit-mut\"],\"name\":\"syn\",\"req\":\"^2.0.1\"}],\"features\":{}}", "pin-project-lite_0.2.16": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1\"}],\"features\":{}}", @@ -1109,6 +1138,7 @@ "portable-pty_0.9.0": "{\"dependencies\":[{\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"bitflags\",\"req\":\"^1.3\",\"target\":\"cfg(windows)\"},{\"name\":\"downcast-rs\",\"req\":\"^1.0\"},{\"name\":\"filedescriptor\",\"req\":\"^0.8.3\"},{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"lazy_static\",\"req\":\"^1.4\",\"target\":\"cfg(windows)\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"features\":[\"term\",\"fs\"],\"name\":\"nix\",\"req\":\"^0.28\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serial2\",\"req\":\"^0.2\"},{\"name\":\"shared_library\",\"req\":\"^0.1\",\"target\":\"cfg(windows)\"},{\"name\":\"shell-words\",\"req\":\"^1.1\"},{\"kind\":\"dev\",\"name\":\"smol\",\"req\":\"^2.0\"},{\"features\":[\"winuser\",\"consoleapi\",\"handleapi\",\"fileapi\",\"namedpipeapi\",\"synchapi\"],\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"},{\"name\":\"winreg\",\"req\":\"^0.10\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[],\"serde_support\":[\"serde\",\"serde_derive\"]}}", "potential_utf_0.1.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"default_features\":false,\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.45\"},{\"default_features\":false,\"name\":\"writeable\",\"optional\":true,\"req\":\"^0.6.0\"},{\"default_features\":false,\"name\":\"zerovec\",\"optional\":true,\"req\":\"^0.11.3\"}],\"features\":{\"alloc\":[\"serde_core?/alloc\",\"writeable/alloc\",\"zerovec?/alloc\"],\"databake\":[\"dep:databake\"],\"default\":[\"alloc\"],\"serde\":[\"dep:serde_core\"],\"writeable\":[\"dep:writeable\"],\"zerovec\":[\"dep:zerovec\"]}}", "powerfmt_0.2.0": "{\"dependencies\":[{\"name\":\"powerfmt-macros\",\"optional\":true,\"req\":\"=0.1.0\"}],\"features\":{\"alloc\":[],\"default\":[\"std\",\"macros\"],\"macros\":[\"dep:powerfmt-macros\"],\"std\":[\"alloc\"]}}", + "ppt-rs_0.2.6": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"clock\",\"std\"],\"name\":\"chrono\",\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"name\":\"clap\",\"req\":\"^4.5\"},{\"name\":\"pulldown-cmark\",\"req\":\"^0.10\"},{\"name\":\"regex\",\"req\":\"^1.10\"},{\"features\":[\"blocking\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.11\"},{\"name\":\"scraper\",\"optional\":true,\"req\":\"^0.18\"},{\"name\":\"syntect\",\"req\":\"^5.2\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.5\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"req\":\"^1.0\"},{\"name\":\"xml-rs\",\"req\":\"^0.8\"},{\"name\":\"zip\",\"req\":\"^0.6\"}],\"features\":{\"default\":[\"web2ppt\"],\"web2ppt\":[\"reqwest\",\"scraper\",\"url\"]}}", "ppv-lite86_0.2.21": "{\"dependencies\":[{\"features\":[\"simd\"],\"name\":\"zerocopy\",\"req\":\"^0.8.23\"}],\"features\":{\"default\":[\"std\"],\"no_simd\":[],\"simd\":[],\"std\":[]}}", "precomputed-hash_0.1.1": "{\"dependencies\":[],\"features\":{}}", "predicates-core_1.0.9": "{\"dependencies\":[],\"features\":{}}", @@ -1175,6 +1205,7 @@ "regex-syntax_0.6.29": "{\"dependencies\":[],\"features\":{\"default\":[\"unicode\"],\"unicode\":[\"unicode-age\",\"unicode-bool\",\"unicode-case\",\"unicode-gencat\",\"unicode-perl\",\"unicode-script\",\"unicode-segment\"],\"unicode-age\":[],\"unicode-bool\":[],\"unicode-case\":[],\"unicode-gencat\":[],\"unicode-perl\":[],\"unicode-script\":[],\"unicode-segment\":[]}}", "regex-syntax_0.8.8": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.3.0\"}],\"features\":{\"arbitrary\":[\"dep:arbitrary\"],\"default\":[\"std\",\"unicode\"],\"std\":[],\"unicode\":[\"unicode-age\",\"unicode-bool\",\"unicode-case\",\"unicode-gencat\",\"unicode-perl\",\"unicode-script\",\"unicode-segment\"],\"unicode-age\":[],\"unicode-bool\":[],\"unicode-case\":[],\"unicode-gencat\":[],\"unicode-perl\":[],\"unicode-script\":[],\"unicode-segment\":[]}}", "regex_1.12.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aho-corasick\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.69\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"atty\",\"humantime\",\"termcolor\"],\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.9.3\"},{\"default_features\":false,\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.6.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"default_features\":false,\"features\":[\"alloc\",\"syntax\",\"meta\",\"nfa-pikevm\"],\"name\":\"regex-automata\",\"req\":\"^0.4.12\"},{\"default_features\":false,\"name\":\"regex-syntax\",\"req\":\"^0.8.5\"},{\"kind\":\"dev\",\"name\":\"regex-test\",\"req\":\"^0.1.0\"}],\"features\":{\"default\":[\"std\",\"perf\",\"unicode\",\"regex-syntax/default\"],\"logging\":[\"aho-corasick?/logging\",\"memchr?/logging\",\"regex-automata/logging\"],\"pattern\":[],\"perf\":[\"perf-cache\",\"perf-dfa\",\"perf-onepass\",\"perf-backtrack\",\"perf-inline\",\"perf-literal\"],\"perf-backtrack\":[\"regex-automata/nfa-backtrack\"],\"perf-cache\":[],\"perf-dfa\":[\"regex-automata/hybrid\"],\"perf-dfa-full\":[\"regex-automata/dfa-build\",\"regex-automata/dfa-search\"],\"perf-inline\":[\"regex-automata/perf-inline\"],\"perf-literal\":[\"dep:aho-corasick\",\"dep:memchr\",\"regex-automata/perf-literal\"],\"perf-onepass\":[\"regex-automata/dfa-onepass\"],\"std\":[\"aho-corasick?/std\",\"memchr?/std\",\"regex-automata/std\",\"regex-syntax/std\"],\"unicode\":[\"unicode-age\",\"unicode-bool\",\"unicode-case\",\"unicode-gencat\",\"unicode-perl\",\"unicode-script\",\"unicode-segment\",\"regex-automata/unicode\",\"regex-syntax/unicode\"],\"unicode-age\":[\"regex-automata/unicode-age\",\"regex-syntax/unicode-age\"],\"unicode-bool\":[\"regex-automata/unicode-bool\",\"regex-syntax/unicode-bool\"],\"unicode-case\":[\"regex-automata/unicode-case\",\"regex-syntax/unicode-case\"],\"unicode-gencat\":[\"regex-automata/unicode-gencat\",\"regex-syntax/unicode-gencat\"],\"unicode-perl\":[\"regex-automata/unicode-perl\",\"regex-automata/unicode-word-boundary\",\"regex-syntax/unicode-perl\"],\"unicode-script\":[\"regex-automata/unicode-script\",\"regex-syntax/unicode-script\"],\"unicode-segment\":[\"regex-automata/unicode-segment\",\"regex-syntax/unicode-segment\"],\"unstable\":[\"pattern\"],\"use_std\":[\"std\"]}}", + "reqwest_0.11.27": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"tokio\"],\"name\":\"async-compression\",\"optional\":true,\"req\":\"^0.4.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"base64\",\"req\":\"^0.21\"},{\"kind\":\"dev\",\"name\":\"brotli_crate\",\"package\":\"brotli\",\"req\":\"^3.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"bytes\",\"req\":\"^1.0\"},{\"name\":\"cookie_crate\",\"optional\":true,\"package\":\"cookie\",\"req\":\"^0.17.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"cookie_store\",\"optional\":true,\"req\":\"^0.20.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"encoding_rs\",\"req\":\"^0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"name\":\"futures-util\",\"req\":\"^0.3.0\"},{\"default_features\":false,\"features\":[\"std\",\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h2\",\"req\":\"^0.3.14\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3\",\"optional\":true,\"req\":\"^0.0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3-quinn\",\"optional\":true,\"req\":\"^0.0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"tokio-runtime\"],\"name\":\"hickory-resolver\",\"optional\":true,\"req\":\"^0.24\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http\",\"req\":\"^0.2\"},{\"name\":\"http-body\",\"req\":\"^0.4.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tcp\",\"http1\",\"http2\",\"client\",\"runtime\"],\"name\":\"hyper\",\"req\":\"^0.14.21\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tcp\",\"stream\",\"http1\",\"http2\",\"client\",\"server\",\"runtime\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^0.14\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"hyper-rustls\",\"optional\":true,\"req\":\"^0.24.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"hyper-tls\",\"optional\":true,\"req\":\"^0.5\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"ipnet\",\"req\":\"^2.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"js-sys\",\"req\":\"^0.3.45\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"libflate\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"log\",\"req\":\"^0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"mime\",\"req\":\"^0.3.16\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0\"},{\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"^0.2.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"once_cell\",\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tls-rustls\",\"ring\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"dangerous_configuration\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.21.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-pemfile\",\"optional\":true,\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde_json\",\"req\":\"^1.0\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_urlencoded\",\"req\":\"^0.7.1\"},{\"name\":\"sync_wrapper\",\"req\":\"^0.1.2\"},{\"name\":\"system-configuration\",\"req\":\"^0.5.1\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"default_features\":false,\"features\":[\"net\",\"time\"],\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.24\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-socks\",\"optional\":true,\"req\":\"^0.5.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"url\",\"req\":\"^2.2\"},{\"name\":\"wasm-bindgen\",\"req\":\"^0.2.68\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"serde-serialize\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen\",\"req\":\"^0.2.68\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-bindgen-futures\",\"req\":\"^0.4.18\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-streams\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"AbortController\",\"AbortSignal\",\"Headers\",\"Request\",\"RequestInit\",\"RequestMode\",\"Response\",\"Window\",\"FormData\",\"Blob\",\"BlobPropertyBag\",\"ServiceWorkerGlobalScope\",\"RequestCredentials\",\"File\",\"ReadableStream\"],\"name\":\"web-sys\",\"req\":\"^0.3.25\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^0.25\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"winreg\",\"req\":\"^0.50.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"__internal_proxy_sys_no_cache\":[],\"__rustls\":[\"hyper-rustls\",\"tokio-rustls\",\"rustls\",\"__tls\"],\"__tls\":[\"dep:rustls-pemfile\"],\"blocking\":[\"futures-util/io\",\"tokio/sync\"],\"brotli\":[\"async-compression\",\"async-compression/brotli\",\"tokio-util\"],\"cookies\":[\"cookie_crate\",\"cookie_store\"],\"default\":[\"default-tls\"],\"default-tls\":[\"hyper-tls\",\"native-tls-crate\",\"__tls\",\"tokio-native-tls\"],\"deflate\":[\"async-compression\",\"async-compression/zlib\",\"tokio-util\"],\"gzip\":[\"async-compression\",\"async-compression/gzip\",\"tokio-util\"],\"hickory-dns\":[\"hickory-resolver\"],\"http3\":[\"rustls-tls-manual-roots\",\"h3\",\"h3-quinn\",\"quinn\",\"futures-channel\"],\"json\":[\"serde_json\"],\"multipart\":[\"mime_guess\"],\"native-tls\":[\"default-tls\"],\"native-tls-alpn\":[\"native-tls\",\"native-tls-crate/alpn\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate/vendored\"],\"rustls-tls\":[\"rustls-tls-webpki-roots\"],\"rustls-tls-manual-roots\":[\"__rustls\"],\"rustls-tls-native-roots\":[\"rustls-native-certs\",\"__rustls\"],\"rustls-tls-webpki-roots\":[\"webpki-roots\",\"__rustls\"],\"socks\":[\"tokio-socks\"],\"stream\":[\"tokio/fs\",\"tokio-util\",\"wasm-streams\"],\"trust-dns\":[\"hickory-dns\"]}}", "reqwest_0.12.28": "{\"dependencies\":[{\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"brotli_crate\",\"package\":\"brotli\",\"req\":\"^8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"cookie_crate\",\"optional\":true,\"package\":\"cookie\",\"req\":\"^0.18.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"cookie_store\",\"optional\":true,\"req\":\"^0.22.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"encoding_rs\",\"optional\":true,\"req\":\"^0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0.13\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.28\"},{\"default_features\":false,\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.28\"},{\"default_features\":false,\"features\":[\"std\",\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.28\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3\",\"optional\":true,\"req\":\"^0.0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3-quinn\",\"optional\":true,\"req\":\"^0.0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"tokio\"],\"name\":\"hickory-resolver\",\"optional\":true,\"req\":\"^0.25\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http\",\"req\":\"^1.1\"},{\"name\":\"http-body\",\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.2\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"client\"],\"name\":\"hyper\",\"req\":\"^1.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"http1\",\"http2\",\"client\",\"server\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"http1\",\"tls12\"],\"name\":\"hyper-rustls\",\"optional\":true,\"req\":\"^0.27.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"hyper-tls\",\"optional\":true,\"req\":\"^0.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"client\",\"client-legacy\",\"client-proxy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1.12\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"http2\",\"client\",\"client-legacy\",\"server-auto\",\"server-graceful\",\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.12\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"js-sys\",\"req\":\"^0.3.77\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0\"},{\"name\":\"log\",\"req\":\"^0.4.17\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"mime\",\"optional\":true,\"req\":\"^0.3.16\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0\"},{\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"^0.2.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.18\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.11\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"rustls\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.11.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.23.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.8.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"std\"],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"^1.9.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde_json\",\"req\":\"^1.0\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_urlencoded\",\"req\":\"^0.7.1\"},{\"features\":[\"futures\"],\"name\":\"sync_wrapper\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"net\",\"time\"],\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tls12\"],\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.26\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"io\"],\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.9\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"retry\",\"timeout\",\"util\"],\"name\":\"tower\",\"req\":\"^0.5.2\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"limit\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"default_features\":false,\"features\":[\"follow-redirect\"],\"name\":\"tower-http\",\"req\":\"^0.6.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tower-service\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"url\",\"req\":\"^2.4\"},{\"name\":\"wasm-bindgen\",\"req\":\"^0.2.89\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"serde-serialize\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen\",\"req\":\"^0.2.89\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-bindgen-futures\",\"req\":\"^0.4.18\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-streams\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"AbortController\",\"AbortSignal\",\"Headers\",\"Request\",\"RequestInit\",\"RequestMode\",\"Response\",\"Window\",\"FormData\",\"Blob\",\"BlobPropertyBag\",\"ServiceWorkerGlobalScope\",\"RequestCredentials\",\"File\",\"ReadableStream\",\"RequestCache\"],\"name\":\"web-sys\",\"req\":\"^0.3.28\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"zstd_crate\",\"package\":\"zstd\",\"req\":\"^0.13\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"}],\"features\":{\"__rustls\":[\"dep:hyper-rustls\",\"dep:tokio-rustls\",\"dep:rustls\",\"__tls\"],\"__rustls-ring\":[\"hyper-rustls?/ring\",\"tokio-rustls?/ring\",\"rustls?/ring\",\"quinn?/ring\"],\"__tls\":[\"dep:rustls-pki-types\",\"tokio/io-util\"],\"blocking\":[\"dep:futures-channel\",\"futures-channel?/sink\",\"dep:futures-util\",\"futures-util?/io\",\"futures-util?/sink\",\"tokio/sync\"],\"brotli\":[\"tower-http/decompression-br\"],\"charset\":[\"dep:encoding_rs\",\"dep:mime\"],\"cookies\":[\"dep:cookie_crate\",\"dep:cookie_store\"],\"default\":[\"default-tls\",\"charset\",\"http2\",\"system-proxy\"],\"default-tls\":[\"dep:hyper-tls\",\"dep:native-tls-crate\",\"__tls\",\"dep:tokio-native-tls\"],\"deflate\":[\"tower-http/decompression-deflate\"],\"gzip\":[\"tower-http/decompression-gzip\"],\"hickory-dns\":[\"dep:hickory-resolver\",\"dep:once_cell\"],\"http2\":[\"h2\",\"hyper/http2\",\"hyper-util/http2\",\"hyper-rustls?/http2\"],\"http3\":[\"rustls-tls-manual-roots\",\"dep:h3\",\"dep:h3-quinn\",\"dep:quinn\",\"tokio/macros\"],\"json\":[\"dep:serde_json\"],\"macos-system-configuration\":[\"system-proxy\"],\"multipart\":[\"dep:mime_guess\",\"dep:futures-util\"],\"native-tls\":[\"default-tls\"],\"native-tls-alpn\":[\"native-tls\",\"native-tls-crate?/alpn\",\"hyper-tls?/alpn\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate?/vendored\"],\"rustls-tls\":[\"rustls-tls-webpki-roots\"],\"rustls-tls-manual-roots\":[\"rustls-tls-manual-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-manual-roots-no-provider\":[\"__rustls\"],\"rustls-tls-native-roots\":[\"rustls-tls-native-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-native-roots-no-provider\":[\"dep:rustls-native-certs\",\"hyper-rustls?/native-tokio\",\"__rustls\"],\"rustls-tls-no-provider\":[\"rustls-tls-manual-roots-no-provider\"],\"rustls-tls-webpki-roots\":[\"rustls-tls-webpki-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-webpki-roots-no-provider\":[\"dep:webpki-roots\",\"hyper-rustls?/webpki-tokio\",\"__rustls\"],\"socks\":[],\"stream\":[\"tokio/fs\",\"dep:futures-util\",\"dep:tokio-util\",\"dep:wasm-streams\"],\"system-proxy\":[\"hyper-util/client-proxy-system\"],\"trust-dns\":[],\"zstd\":[\"tower-http/decompression-zstd\"]}}", "resolv-conf_0.7.6": "{\"dependencies\":[],\"features\":{\"system\":[]}}", "ring_0.17.14": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.8\"},{\"default_features\":false,\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"getrandom\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(all(any(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), all(target_arch = \\\"arm\\\", target_endian = \\\"little\\\")), any(target_os = \\\"android\\\", target_os = \\\"linux\\\")))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_vendor = \\\"apple\\\", any(target_os = \\\"ios\\\", target_os = \\\"macos\\\", target_os = \\\"tvos\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\")))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_os = \\\"windows\\\"))\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\",\"dev_urandom_fallback\"],\"dev_urandom_fallback\":[],\"less-safe-getrandom-custom-or-rdrand\":[],\"less-safe-getrandom-espidf\":[],\"slow_tests\":[],\"std\":[\"alloc\"],\"test_logging\":[],\"unstable-testing-arm-no-hw\":[],\"unstable-testing-arm-no-neon\":[],\"wasm32_unknown_unknown_js\":[\"getrandom/js\"]}}", @@ -1193,6 +1224,7 @@ "rustix_0.38.44": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4.0\"},{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.49\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4\",\"target\":\"cfg(all(criterion, not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"itoa\",\"optional\":true,\"req\":\"^1.0.13\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.161\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.161\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.161\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(windows)\"},{\"default_features\":false,\"name\":\"libc_errno\",\"optional\":true,\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\"},{\"default_features\":false,\"features\":[\"general\",\"ioctl\",\"no_std\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.4.14\",\"target\":\"cfg(all(any(target_os = \\\"android\\\", target_os = \\\"linux\\\"), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"features\":[\"general\",\"errno\",\"ioctl\",\"no_std\",\"elf\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.4.14\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", target_arch = \\\"s390x\\\"), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"memoffset\",\"req\":\"^0.9.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.5.2\",\"target\":\"cfg(any(target_os = \\\"android\\\", target_os = \\\"linux\\\"))\"},{\"name\":\"rustc-std-workspace-alloc\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.5.0\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\",\"Win32_NetworkManagement_IpHelper\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <=0.59\",\"target\":\"cfg(windows)\"}],\"features\":{\"all-apis\":[\"event\",\"fs\",\"io_uring\",\"mm\",\"mount\",\"net\",\"param\",\"pipe\",\"process\",\"procfs\",\"pty\",\"rand\",\"runtime\",\"shm\",\"stdio\",\"system\",\"termios\",\"thread\",\"time\"],\"alloc\":[],\"cc\":[],\"default\":[\"std\",\"use-libc-auxv\"],\"event\":[],\"fs\":[],\"io_uring\":[\"event\",\"fs\",\"net\",\"linux-raw-sys/io_uring\"],\"libc-extra-traits\":[\"libc?/extra_traits\"],\"linux_4_11\":[],\"linux_latest\":[\"linux_4_11\"],\"mm\":[],\"mount\":[],\"net\":[\"linux-raw-sys/net\",\"linux-raw-sys/netlink\",\"linux-raw-sys/if_ether\",\"linux-raw-sys/xdp\"],\"param\":[\"fs\"],\"pipe\":[],\"process\":[\"linux-raw-sys/prctl\"],\"procfs\":[\"once_cell\",\"itoa\",\"fs\"],\"pty\":[\"itoa\",\"fs\"],\"rand\":[],\"runtime\":[\"linux-raw-sys/prctl\"],\"rustc-dep-of-std\":[\"core\",\"rustc-std-workspace-alloc\",\"compiler_builtins\",\"linux-raw-sys/rustc-dep-of-std\",\"bitflags/rustc-dep-of-std\",\"compiler_builtins?/rustc-dep-of-std\"],\"shm\":[\"fs\"],\"std\":[\"bitflags/std\",\"alloc\",\"libc?/std\",\"libc_errno?/std\",\"libc-extra-traits\"],\"stdio\":[],\"system\":[\"linux-raw-sys/system\"],\"termios\":[],\"thread\":[\"linux-raw-sys/prctl\"],\"time\":[],\"try_close\":[],\"use-explicitly-provided-auxv\":[],\"use-libc\":[\"libc_errno\",\"libc\",\"libc-extra-traits\"],\"use-libc-auxv\":[]}}", "rustix_1.1.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bitflags\",\"req\":\"^2.4.0\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4\",\"target\":\"cfg(all(criterion, not(any(target_os = \\\"emscripten\\\", target_os = \\\"wasi\\\"))))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.177\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc\",\"optional\":true,\"req\":\"^0.2.177\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.171\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(windows)\"},{\"default_features\":false,\"name\":\"libc_errno\",\"optional\":true,\"package\":\"errno\",\"req\":\"^0.3.10\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc_errno\",\"package\":\"errno\",\"req\":\"^0.3.10\"},{\"default_features\":false,\"features\":[\"general\",\"ioctl\",\"no_std\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.11.0\",\"target\":\"cfg(all(any(target_os = \\\"linux\\\", target_os = \\\"android\\\"), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\"},{\"default_features\":false,\"features\":[\"auxvec\",\"general\",\"errno\",\"ioctl\",\"no_std\",\"elf\"],\"name\":\"linux-raw-sys\",\"req\":\"^0.11.0\",\"target\":\"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\"},{\"kind\":\"dev\",\"name\":\"memoffset\",\"req\":\"^0.9.0\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.20.3\",\"target\":\"cfg(windows)\"},{\"name\":\"rustc-std-workspace-alloc\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^2.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.5.0\"},{\"features\":[\"Win32_Foundation\",\"Win32_Networking_WinSock\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <0.62\",\"target\":\"cfg(windows)\"}],\"features\":{\"all-apis\":[\"event\",\"fs\",\"io_uring\",\"mm\",\"mount\",\"net\",\"param\",\"pipe\",\"process\",\"pty\",\"rand\",\"runtime\",\"shm\",\"stdio\",\"system\",\"termios\",\"thread\",\"time\"],\"alloc\":[],\"default\":[\"std\"],\"event\":[],\"fs\":[],\"io_uring\":[\"event\",\"fs\",\"net\",\"thread\",\"linux-raw-sys/io_uring\"],\"linux_4_11\":[],\"linux_5_1\":[\"linux_4_11\"],\"linux_5_11\":[\"linux_5_1\"],\"linux_latest\":[\"linux_5_11\"],\"mm\":[],\"mount\":[],\"net\":[\"linux-raw-sys/net\",\"linux-raw-sys/netlink\",\"linux-raw-sys/if_ether\",\"linux-raw-sys/xdp\"],\"param\":[],\"pipe\":[],\"process\":[\"linux-raw-sys/prctl\"],\"pty\":[\"fs\"],\"rand\":[],\"runtime\":[\"linux-raw-sys/prctl\"],\"rustc-dep-of-std\":[\"core\",\"rustc-std-workspace-alloc\",\"linux-raw-sys/rustc-dep-of-std\",\"bitflags/rustc-dep-of-std\"],\"shm\":[\"fs\"],\"std\":[\"bitflags/std\",\"alloc\",\"libc?/std\",\"libc_errno?/std\"],\"stdio\":[],\"system\":[\"linux-raw-sys/system\"],\"termios\":[],\"thread\":[\"linux-raw-sys/prctl\"],\"time\":[],\"try_close\":[],\"use-explicitly-provided-auxv\":[],\"use-libc\":[\"libc_errno\",\"libc\"],\"use-libc-auxv\":[]}}", "rustls-native-certs_0.8.3": "{\"dependencies\":[{\"name\":\"openssl-probe\",\"req\":\"^0.2\",\"target\":\"cfg(all(unix, not(target_os = \\\"macos\\\")))\"},{\"features\":[\"std\"],\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.10\"},{\"kind\":\"dev\",\"name\":\"ring\",\"req\":\"^0.17\"},{\"kind\":\"dev\",\"name\":\"rustls\",\"req\":\"^0.23\"},{\"kind\":\"dev\",\"name\":\"rustls-webpki\",\"req\":\"^0.103\"},{\"name\":\"schannel\",\"req\":\"^0.1\",\"target\":\"cfg(windows)\"},{\"name\":\"security-framework\",\"req\":\"^3\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"kind\":\"dev\",\"name\":\"serial_test\",\"req\":\"^3\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.5\"},{\"kind\":\"dev\",\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.18\"}],\"features\":{}}", + "rustls-pemfile_1.0.4": "{\"dependencies\":[{\"name\":\"base64\",\"req\":\"^0.21\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"}],\"features\":{}}", "rustls-pki-types_1.14.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"crabgrind\",\"req\":\"=0.1.9\",\"target\":\"cfg(all(target_os = \\\"linux\\\", target_arch = \\\"x86_64\\\"))\"},{\"name\":\"web-time\",\"optional\":true,\"req\":\"^1\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"dep:zeroize\"],\"default\":[\"alloc\"],\"std\":[\"alloc\"],\"web\":[\"web-time\"]}}", "rustls-webpki_0.103.9": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.14\"},{\"kind\":\"dev\",\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"kind\":\"dev\",\"name\":\"bzip2\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.17.2\"},{\"default_features\":false,\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.12\"},{\"default_features\":false,\"features\":[\"aws_lc_rs\"],\"kind\":\"dev\",\"name\":\"rcgen\",\"req\":\"^0.14.2\"},{\"default_features\":false,\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"}],\"features\":{\"alloc\":[\"ring?/alloc\",\"pki-types/alloc\"],\"aws-lc-rs\":[\"dep:aws-lc-rs\",\"aws-lc-rs/aws-lc-sys\",\"aws-lc-rs/prebuilt-nasm\"],\"aws-lc-rs-fips\":[\"dep:aws-lc-rs\",\"aws-lc-rs/fips\"],\"aws-lc-rs-unstable\":[\"aws-lc-rs\",\"aws-lc-rs/unstable\"],\"default\":[\"std\"],\"ring\":[\"dep:ring\"],\"std\":[\"alloc\",\"pki-types/std\"]}}", "rustls_0.23.36": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.14\"},{\"kind\":\"dev\",\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"brotli\",\"optional\":true,\"req\":\"^8\"},{\"name\":\"brotli-decompressor\",\"optional\":true,\"req\":\"^5.0.0\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"default_features\":false,\"features\":[\"default-hasher\",\"inline-more\"],\"name\":\"hashbrown\",\"optional\":true,\"req\":\"^0.15\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.8\"},{\"kind\":\"dev\",\"name\":\"log\",\"req\":\"^0.4.8\"},{\"kind\":\"dev\",\"name\":\"macro_rules_attribute\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"num-bigint\",\"req\":\"^0.4.4\"},{\"default_features\":false,\"features\":[\"alloc\",\"race\"],\"name\":\"once_cell\",\"req\":\"^1.16\"},{\"features\":[\"alloc\"],\"name\":\"pki-types\",\"package\":\"rustls-pki-types\",\"req\":\"^1.12\"},{\"default_features\":false,\"features\":[\"pem\",\"aws_lc_rs\"],\"kind\":\"dev\",\"name\":\"rcgen\",\"req\":\"^0.14\"},{\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17\"},{\"kind\":\"build\",\"name\":\"rustversion\",\"optional\":true,\"req\":\"^1.0.6\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.5.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.6\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"webpki\",\"package\":\"rustls-webpki\",\"req\":\"^0.103.5\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.17\"},{\"name\":\"zeroize\",\"req\":\"^1.8\"},{\"name\":\"zlib-rs\",\"optional\":true,\"req\":\"^0.5\"}],\"features\":{\"aws-lc-rs\":[\"aws_lc_rs\"],\"aws_lc_rs\":[\"dep:aws-lc-rs\",\"webpki/aws-lc-rs\",\"aws-lc-rs/aws-lc-sys\",\"aws-lc-rs/prebuilt-nasm\"],\"brotli\":[\"dep:brotli\",\"dep:brotli-decompressor\",\"std\"],\"custom-provider\":[],\"default\":[\"aws_lc_rs\",\"logging\",\"prefer-post-quantum\",\"std\",\"tls12\"],\"fips\":[\"aws_lc_rs\",\"aws-lc-rs?/fips\",\"webpki/aws-lc-rs-fips\"],\"logging\":[\"log\"],\"prefer-post-quantum\":[\"aws_lc_rs\"],\"read_buf\":[\"rustversion\",\"std\"],\"ring\":[\"dep:ring\",\"webpki/ring\"],\"std\":[\"webpki/std\",\"pki-types/std\",\"once_cell/std\"],\"tls12\":[],\"zlib\":[\"dep:zlib-rs\"]}}", @@ -1213,6 +1245,7 @@ "schemars_derive_1.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1.2.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.74\"},{\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"name\":\"serde_derive_internals\",\"req\":\"^0.29.1\"},{\"name\":\"syn\",\"req\":\"^2.0.46\"},{\"features\":[\"extra-traits\"],\"kind\":\"dev\",\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "scoped-tls_1.0.1": "{\"dependencies\":[],\"features\":{}}", "scopeguard_1.2.0": "{\"dependencies\":[],\"features\":{\"default\":[\"use_std\"],\"use_std\":[]}}", + "scraper_0.18.1": "{\"dependencies\":[{\"name\":\"ahash\",\"req\":\"^0.8\"},{\"name\":\"cssparser\",\"req\":\"^0.31.0\"},{\"name\":\"ego-tree\",\"req\":\"^0.6.2\"},{\"name\":\"getopts\",\"optional\":true,\"req\":\"^0.2.21\"},{\"name\":\"html5ever\",\"req\":\"^0.26\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.0\"},{\"name\":\"selectors\",\"req\":\"^0.25.0\"},{\"name\":\"tendril\",\"req\":\"^0.4.3\"}],\"features\":{\"atomic\":[],\"default\":[\"main\",\"errors\"],\"deterministic\":[\"indexmap\"],\"errors\":[],\"main\":[\"getopts\"]}}", "scrypt_0.11.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.5\"},{\"features\":[\"rand_core\"],\"kind\":\"dev\",\"name\":\"password-hash\",\"req\":\"^0.5\"},{\"name\":\"pbkdf2\",\"req\":\"^0.12\"},{\"default_features\":false,\"name\":\"salsa20\",\"req\":\"^0.10.2\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"simple\",\"std\"],\"simple\":[\"password-hash\"],\"std\":[\"password-hash/std\"]}}", "sdd_3.0.10": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.6\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"}],\"features\":{}}", "seccompiler_0.5.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.153\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.27\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.9\"}],\"features\":{\"json\":[\"serde\",\"serde_json\"]}}", @@ -1221,6 +1254,7 @@ "security-framework-sys_2.15.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"name\":\"libc\",\"req\":\"^0.2.150\"}],\"features\":{\"OSX_10_10\":[\"OSX_10_9\"],\"OSX_10_11\":[\"OSX_10_10\"],\"OSX_10_12\":[\"OSX_10_11\"],\"OSX_10_13\":[\"OSX_10_12\"],\"OSX_10_14\":[\"OSX_10_13\"],\"OSX_10_15\":[\"OSX_10_14\"],\"OSX_10_9\":[],\"default\":[\"OSX_10_12\"]}}", "security-framework_2.11.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.6\"},{\"name\":\"core-foundation\",\"req\":\"^0.9.4\"},{\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"libc\",\"req\":\"^0.2.139\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"name\":\"num-bigint\",\"optional\":true,\"req\":\"^0.4.6\"},{\"default_features\":false,\"name\":\"security-framework-sys\",\"req\":\"^2.11.1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.3.0\"},{\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.17\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.16\"}],\"features\":{\"OSX_10_10\":[\"OSX_10_9\",\"security-framework-sys/OSX_10_10\"],\"OSX_10_11\":[\"OSX_10_10\",\"security-framework-sys/OSX_10_11\"],\"OSX_10_12\":[\"OSX_10_11\",\"security-framework-sys/OSX_10_12\"],\"OSX_10_13\":[\"OSX_10_12\",\"security-framework-sys/OSX_10_13\",\"alpn\",\"session-tickets\",\"serial-number-bigint\"],\"OSX_10_14\":[\"OSX_10_13\",\"security-framework-sys/OSX_10_14\"],\"OSX_10_15\":[\"OSX_10_14\",\"security-framework-sys/OSX_10_15\"],\"OSX_10_9\":[\"security-framework-sys/OSX_10_9\"],\"alpn\":[],\"default\":[\"OSX_10_12\"],\"job-bless\":[],\"nightly\":[],\"serial-number-bigint\":[\"dep:num-bigint\"],\"session-tickets\":[]}}", "security-framework_3.5.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2.6\"},{\"name\":\"core-foundation\",\"req\":\"^0.10\"},{\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"libc\",\"req\":\"^0.2.139\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"default_features\":false,\"name\":\"security-framework-sys\",\"req\":\"^2.15\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.12.0\"},{\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.23\"},{\"kind\":\"dev\",\"name\":\"x509-parser\",\"req\":\"^0.16\"}],\"features\":{\"OSX_10_12\":[\"security-framework-sys/OSX_10_12\"],\"OSX_10_13\":[\"OSX_10_12\",\"security-framework-sys/OSX_10_13\",\"alpn\",\"session-tickets\"],\"OSX_10_14\":[\"OSX_10_13\",\"security-framework-sys/OSX_10_14\"],\"OSX_10_15\":[\"OSX_10_14\",\"security-framework-sys/OSX_10_15\"],\"alpn\":[],\"default\":[\"OSX_10_12\"],\"job-bless\":[],\"nightly\":[],\"session-tickets\":[],\"sync-keychain\":[\"OSX_10_13\"]}}", + "selectors_0.25.0": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2\"},{\"name\":\"cssparser\",\"req\":\"^0.31\"},{\"default_features\":false,\"features\":[\"add\",\"add_assign\"],\"name\":\"derive_more\",\"req\":\"^0.99\"},{\"name\":\"fxhash\",\"req\":\"^0.2\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"new_debug_unreachable\",\"req\":\"^1\"},{\"name\":\"phf\",\"req\":\"^0.10\"},{\"kind\":\"build\",\"name\":\"phf_codegen\",\"req\":\"^0.10\"},{\"name\":\"precomputed-hash\",\"req\":\"^0.1\"},{\"name\":\"servo_arc\",\"req\":\"^0.3\"},{\"name\":\"smallvec\",\"req\":\"^1.0\"}],\"features\":{\"bench\":[]}}", "self_cell_0.10.3": "{\"dependencies\":[{\"name\":\"new_self_cell\",\"package\":\"self_cell\",\"req\":\"^1\"}],\"features\":{\"old_rust\":[\"new_self_cell/old_rust\"]}}", "self_cell_1.2.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"=1.1.0\"},{\"name\":\"rustversion\",\"optional\":true,\"req\":\">=1\"}],\"features\":{\"old_rust\":[\"rustversion\"]}}", "semver_1.0.27": "{\"dependencies\":[{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"package\":\"serde_core\",\"req\":\"^1.0.220\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.220\",\"target\":\"cfg(any())\"}],\"features\":{\"default\":[\"std\"],\"serde\":[\"dep:serde\"],\"std\":[]}}", @@ -1249,6 +1283,7 @@ "serial2_0.2.33": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert2\",\"req\":\"^0.3.11\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\",\"target\":\"cfg(unix)\"},{\"name\":\"libc\",\"req\":\"^0.2.109\",\"target\":\"cfg(unix)\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.108\"},{\"features\":[\"commapi\",\"fileapi\",\"handleapi\",\"ioapiset\",\"std\",\"synchapi\",\"winbase\",\"winerror\",\"winreg\"],\"name\":\"winapi\",\"req\":\"^0.3.9\",\"target\":\"cfg(windows)\"}],\"features\":{\"doc\":[],\"doc-cfg\":[],\"rs4xx\":[],\"serde\":[\"dep:serde\"],\"unix\":[],\"windows\":[]}}", "serial_test_3.3.1": "{\"dependencies\":[{\"name\":\"document-features\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"env_logger\",\"optional\":true,\"req\":\">=0.6.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"fslock\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-executor\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"use_std\"],\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\">=0.4\"},{\"name\":\"log\",\"optional\":true,\"req\":\">=0.4.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"once_cell\",\"req\":\"^1.19\"},{\"default_features\":false,\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"default_features\":false,\"name\":\"scc\",\"req\":\"^2\"},{\"name\":\"serial_test_derive\",\"req\":\"~3.3.1\"}],\"features\":{\"async\":[\"dep:futures-executor\",\"dep:futures-util\",\"serial_test_derive/async\"],\"default\":[\"logging\",\"async\"],\"docsrs\":[\"dep:document-features\"],\"file_locks\":[\"dep:fslock\"],\"logging\":[\"dep:log\"],\"test_logging\":[\"logging\",\"dep:env_logger\",\"serial_test_derive/test_logging\"]}}", "serial_test_derive_3.3.1": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\">=0.6.1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"prettyplease\",\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"proc-macro\"],\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"full\",\"printing\",\"parsing\",\"clone-impls\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"async\":[],\"default\":[],\"file_locks\":[],\"test_logging\":[]}}", + "servo_arc_0.3.0": "{\"dependencies\":[{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"stable_deref_trait\",\"req\":\"^1.0.0\"}],\"features\":{\"gecko_refcount_logging\":[],\"servo\":[\"serde\"]}}", "sha1_0.10.6": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"cpufeatures\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86\\\", target_arch = \\\"x86_64\\\"))\"},{\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"},{\"name\":\"sha1-asm\",\"optional\":true,\"req\":\"^0.5\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86\\\", target_arch = \\\"x86_64\\\"))\"}],\"features\":{\"asm\":[\"sha1-asm\"],\"compress\":[],\"default\":[\"std\"],\"force-soft\":[],\"loongarch64_asm\":[],\"oid\":[\"digest/oid\"],\"std\":[\"digest/std\"]}}", "sha1_smol_1.0.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"openssl\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", "sha2_0.10.9": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"cpufeatures\",\"req\":\"^0.2\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86_64\\\", target_arch = \\\"x86\\\"))\"},{\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"digest\",\"req\":\"^0.10.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"},{\"name\":\"sha2-asm\",\"optional\":true,\"req\":\"^0.6.1\",\"target\":\"cfg(any(target_arch = \\\"aarch64\\\", target_arch = \\\"x86_64\\\", target_arch = \\\"x86\\\"))\"}],\"features\":{\"asm\":[\"sha2-asm\"],\"asm-aarch64\":[\"asm\"],\"compress\":[],\"default\":[\"std\"],\"force-soft\":[],\"force-soft-compact\":[],\"loongarch64_asm\":[],\"oid\":[\"digest/oid\"],\"std\":[\"digest/std\"]}}", @@ -1263,6 +1298,7 @@ "simd-adler32_0.3.8": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"adler\",\"req\":\"^1.0.2\"},{\"kind\":\"dev\",\"name\":\"adler32\",\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"const-generics\":[],\"default\":[\"std\",\"const-generics\"],\"nightly\":[],\"std\":[]}}", "simdutf8_0.1.5": "{\"dependencies\":[],\"features\":{\"aarch64_neon\":[],\"aarch64_neon_prefetch\":[],\"default\":[\"std\"],\"hints\":[],\"public_imp\":[],\"std\":[]}}", "similar_2.7.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bstr\",\"optional\":true,\"req\":\"^1.5.0\"},{\"kind\":\"dev\",\"name\":\"console\",\"req\":\"^0.15.0\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.10.0\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.130\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.68\"},{\"name\":\"unicode-segmentation\",\"optional\":true,\"req\":\"^1.7.1\"},{\"name\":\"web-time\",\"optional\":true,\"req\":\"^1.1\"}],\"features\":{\"bytes\":[\"bstr\",\"text\"],\"default\":[\"text\"],\"inline\":[\"text\"],\"text\":[],\"unicode\":[\"text\",\"unicode-segmentation\",\"bstr?/unicode\",\"bstr?/std\"],\"wasm32_web_time\":[\"web-time\"]}}", + "siphasher_0.3.11": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde_no_std\":[\"serde/alloc\"],\"serde_std\":[\"std\",\"serde/std\"],\"std\":[]}}", "siphasher_1.0.2": "{\"dependencies\":[{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"serde_no_std\":[\"serde/alloc\"],\"serde_std\":[\"std\",\"serde/std\"],\"std\":[]}}", "slab_0.4.12": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.95\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "smallvec_1.15.1": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"name\":\"bincode\",\"optional\":true,\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"bincode1\",\"package\":\"bincode\",\"req\":\"^1.0.1\"},{\"kind\":\"dev\",\"name\":\"debugger_test\",\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"debugger_test_parser\",\"req\":\"^0.1.0\"},{\"default_features\":false,\"name\":\"malloc_size_of\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"name\":\"unty\",\"optional\":true,\"req\":\"^0.0.4\"}],\"features\":{\"const_generics\":[],\"const_new\":[\"const_generics\"],\"debugger_visualizer\":[],\"drain_filter\":[],\"drain_keep_rest\":[\"drain_filter\"],\"impl_bincode\":[\"bincode\",\"unty\"],\"may_dangle\":[],\"specialization\":[],\"union\":[],\"write\":[]}}", @@ -1289,6 +1325,7 @@ "stop-words_0.9.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"human_regex\",\"req\":\"^0.3.0\"},{\"kind\":\"build\",\"name\":\"serde_json\",\"req\":\"^1\"}],\"features\":{\"constructed\":[],\"default\":[\"iso\"],\"iso\":[],\"nltk\":[],\"unimplemented\":[]}}", "streaming-iterator_0.1.9": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", "string_cache_0.8.9": "{\"dependencies\":[{\"default_features\":false,\"name\":\"malloc_size_of\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"new_debug_unreachable\",\"req\":\"^1.0.2\"},{\"name\":\"parking_lot\",\"req\":\"^0.12\"},{\"name\":\"phf_shared\",\"req\":\"^0.11\"},{\"name\":\"precomputed-hash\",\"req\":\"^0.1\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"default\":[\"serde_support\"],\"serde_support\":[\"serde\"]}}", + "string_cache_codegen_0.5.4": "{\"dependencies\":[{\"name\":\"phf_generator\",\"req\":\"^0.11\"},{\"name\":\"phf_shared\",\"req\":\"^0.11\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"}],\"features\":{}}", "stringprep_0.1.5": "{\"dependencies\":[{\"name\":\"unicode-bidi\",\"req\":\"^0.3\"},{\"name\":\"unicode-normalization\",\"req\":\"^0.1\"},{\"name\":\"unicode-properties\",\"req\":\"^0.1.1\"}],\"features\":{}}", "strsim_0.10.0": "{\"dependencies\":[],\"features\":{}}", "strsim_0.11.1": "{\"dependencies\":[],\"features\":{}}", @@ -1301,14 +1338,18 @@ "supports-color_3.0.2": "{\"dependencies\":[{\"name\":\"is_ci\",\"req\":\"^1.2.0\"}],\"features\":{}}", "syn_1.0.109": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.46\"},{\"default_features\":false,\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"ref-cast\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.0\"},{\"features\":[\"blocking\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"syn-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"tar\",\"req\":\"^0.4.16\"},{\"kind\":\"dev\",\"name\":\"termcolor\",\"req\":\"^1.0\"},{\"name\":\"unicode-ident\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.1\"}],\"features\":{\"clone-impls\":[],\"default\":[\"derive\",\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\"],\"derive\":[],\"extra-traits\":[],\"fold\":[],\"full\":[],\"parsing\":[],\"printing\":[\"quote\"],\"proc-macro\":[\"proc-macro2/proc-macro\",\"quote/proc-macro\"],\"test\":[\"syn-test-suite/all-features\"],\"visit\":[],\"visit-mut\":[]}}", "syn_2.0.114": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"insta\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.91\"},{\"default_features\":false,\"name\":\"quote\",\"optional\":true,\"req\":\"^1.0.35\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"ref-cast\",\"req\":\"^1\"},{\"features\":[\"blocking\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.13\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"syn-test-suite\",\"req\":\"^0\"},{\"kind\":\"dev\",\"name\":\"tar\",\"req\":\"^0.4.16\",\"target\":\"cfg(not(miri))\"},{\"kind\":\"dev\",\"name\":\"termcolor\",\"req\":\"^1\"},{\"name\":\"unicode-ident\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\",\"target\":\"cfg(not(miri))\"}],\"features\":{\"clone-impls\":[],\"default\":[\"derive\",\"parsing\",\"printing\",\"clone-impls\",\"proc-macro\"],\"derive\":[],\"extra-traits\":[],\"fold\":[],\"full\":[],\"parsing\":[],\"printing\":[\"dep:quote\"],\"proc-macro\":[\"proc-macro2/proc-macro\",\"quote?/proc-macro\"],\"test\":[\"syn-test-suite/all-features\"],\"visit\":[],\"visit-mut\":[]}}", + "sync_wrapper_0.1.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"}],\"features\":{\"futures\":[\"futures-core\"]}}", "sync_wrapper_1.0.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"futures\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-core\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"}],\"features\":{\"futures\":[\"futures-core\"]}}", "synstructure_0.13.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.60\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"derive\",\"parsing\",\"printing\",\"clone-impls\",\"visit\",\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"synstructure_test_traits\",\"req\":\"^0.1\"}],\"features\":{\"default\":[\"proc-macro\"],\"proc-macro\":[\"proc-macro2/proc-macro\",\"syn/proc-macro\",\"quote/proc-macro\"]}}", "syntect_5.3.0": "{\"dependencies\":[{\"name\":\"bincode\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.3\"},{\"name\":\"fancy-regex\",\"optional\":true,\"req\":\"^0.16.2\"},{\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"fnv\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"getopts\",\"req\":\"^0.2\"},{\"name\":\"once_cell\",\"req\":\"^1.8\"},{\"default_features\":false,\"name\":\"onig\",\"optional\":true,\"req\":\"^6.5.1\"},{\"name\":\"plist\",\"optional\":true,\"req\":\"^1.3\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6\"},{\"kind\":\"dev\",\"name\":\"public-api\",\"req\":\"^0.50.1\"},{\"kind\":\"dev\",\"name\":\"rayon\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.0\"},{\"name\":\"regex-syntax\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rustdoc-json\",\"req\":\"^0.9.7\"},{\"kind\":\"dev\",\"name\":\"rustup-toolchain\",\"req\":\"^0.1.5\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0.12\"},{\"name\":\"walkdir\",\"req\":\"^2.0\"},{\"name\":\"yaml-rust\",\"optional\":true,\"req\":\"^0.4.5\"}],\"features\":{\"default\":[\"default-onig\"],\"default-fancy\":[\"parsing\",\"default-syntaxes\",\"default-themes\",\"html\",\"plist-load\",\"yaml-load\",\"dump-load\",\"dump-create\",\"regex-fancy\"],\"default-onig\":[\"parsing\",\"default-syntaxes\",\"default-themes\",\"html\",\"plist-load\",\"yaml-load\",\"dump-load\",\"dump-create\",\"regex-onig\"],\"default-syntaxes\":[\"parsing\",\"dump-load\"],\"default-themes\":[\"dump-load\"],\"dump-create\":[\"flate2\",\"bincode\"],\"dump-load\":[\"flate2\",\"bincode\"],\"html\":[\"parsing\"],\"metadata\":[\"parsing\",\"plist-load\",\"dep:serde_json\"],\"parsing\":[\"regex-syntax\",\"fnv\",\"dump-create\",\"dump-load\"],\"plist-load\":[\"plist\",\"dep:serde_json\"],\"regex-fancy\":[\"fancy-regex\"],\"regex-onig\":[\"onig\"],\"yaml-load\":[\"yaml-rust\",\"parsing\"]}}", "sys-locale_0.3.2": "{\"dependencies\":[{\"name\":\"js-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(target_os = \\\"android\\\")\"},{\"name\":\"wasm-bindgen\",\"optional\":true,\"req\":\"^0.2\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"},{\"features\":[\"Window\",\"WorkerGlobalScope\",\"Navigator\",\"WorkerNavigator\"],\"name\":\"web-sys\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", not(unix)))\"}],\"features\":{\"js\":[\"js-sys\",\"wasm-bindgen\",\"web-sys\"]}}", + "system-configuration-sys_0.5.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2.49\"}],\"features\":{}}", "system-configuration-sys_0.6.0": "{\"dependencies\":[{\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2.149\"}],\"features\":{}}", + "system-configuration_0.5.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^1\"},{\"name\":\"core-foundation\",\"req\":\"^0.9\"},{\"name\":\"system-configuration-sys\",\"req\":\"^0.5\"}],\"features\":{}}", "system-configuration_0.6.1": "{\"dependencies\":[{\"name\":\"bitflags\",\"req\":\"^2\"},{\"name\":\"core-foundation\",\"req\":\"^0.9\"},{\"name\":\"system-configuration-sys\",\"req\":\"^0.6\"}],\"features\":{}}", "tagptr_0.2.0": "{\"dependencies\":[],\"features\":{}}", "tempfile_3.24.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"fastrand\",\"req\":\"^2.1.1\"},{\"default_features\":false,\"name\":\"getrandom\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"once_cell\",\"req\":\"^1.19.0\"},{\"features\":[\"fs\"],\"name\":\"rustix\",\"req\":\"^1.1.3\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\"))\"},{\"features\":[\"Win32_Storage_FileSystem\",\"Win32_Foundation\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <0.62\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"getrandom\"],\"nightly\":[]}}", + "tendril_0.4.3": "{\"dependencies\":[{\"name\":\"encoding\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"encoding_rs\",\"optional\":true,\"req\":\"^0.8.12\"},{\"name\":\"futf\",\"req\":\"^0.1.5\"},{\"name\":\"mac\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.4\"},{\"name\":\"utf-8\",\"req\":\"^0.7\"}],\"features\":{\"bench\":[]}}", "term_0.7.0": "{\"dependencies\":[{\"name\":\"dirs-next\",\"req\":\"^2\"},{\"name\":\"rustversion\",\"req\":\"^1\",\"target\":\"cfg(windows)\"},{\"features\":[\"consoleapi\",\"wincon\",\"handleapi\",\"fileapi\"],\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[]}}", "termcolor_1.4.1": "{\"dependencies\":[{\"name\":\"winapi-util\",\"req\":\"^0.1.3\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "terminal_size_0.4.3": "{\"dependencies\":[{\"features\":[\"termios\"],\"name\":\"rustix\",\"req\":\"^1.0.1\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Console\"],\"name\":\"windows-sys\",\"req\":\"^0.60.0\",\"target\":\"cfg(windows)\"}],\"features\":{}}", @@ -1519,6 +1560,7 @@ "x25519-dalek_2.0.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"curve25519-dalek\",\"req\":\"^4\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"getrandom\"],\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"curve25519-dalek/alloc\",\"serde?/alloc\",\"zeroize?/alloc\"],\"default\":[\"alloc\",\"precomputed-tables\",\"zeroize\"],\"getrandom\":[\"rand_core/getrandom\"],\"precomputed-tables\":[\"curve25519-dalek/precomputed-tables\"],\"reusable_secrets\":[],\"serde\":[\"dep:serde\",\"curve25519-dalek/serde\"],\"static_secrets\":[],\"zeroize\":[\"dep:zeroize\",\"curve25519-dalek/zeroize\"]}}", "x509-parser_0.18.1": "{\"dependencies\":[{\"features\":[\"datetime\"],\"name\":\"asn1-rs\",\"req\":\"^0.7.0\"},{\"name\":\"aws-lc-rs\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"data-encoding\",\"req\":\"^2.2.1\"},{\"features\":[\"bigint\"],\"name\":\"der-parser\",\"req\":\"^10.0\"},{\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"name\":\"nom\",\"req\":\"^7.0\"},{\"features\":[\"crypto\",\"x509\",\"x962\"],\"name\":\"oid-registry\",\"req\":\"^0.8.1\"},{\"name\":\"ring\",\"optional\":true,\"req\":\"^0.17.12\"},{\"name\":\"rusticata-macros\",\"req\":\"^4.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0\"},{\"features\":[\"formatting\"],\"name\":\"time\",\"req\":\"^0.3.35\"}],\"features\":{\"default\":[],\"validate\":[],\"verify\":[\"ring\"],\"verify-aws\":[\"aws-lc-rs\"]}}", "xdg-home_1.3.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"features\":[\"Win32_Foundation\",\"Win32_UI_Shell\",\"Win32_System_Com\"],\"name\":\"windows-sys\",\"req\":\"^0.59\",\"target\":\"cfg(windows)\"}],\"features\":{}}", + "xml-rs_0.8.28": "{\"dependencies\":[],\"features\":{}}", "xz2_0.1.7": "{\"dependencies\":[{\"name\":\"futures\",\"optional\":true,\"req\":\"^0.1.26\"},{\"name\":\"lzma-sys\",\"req\":\"^0.1.18\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.0\"},{\"kind\":\"dev\",\"name\":\"tokio-core\",\"req\":\"^0.1.17\"},{\"name\":\"tokio-io\",\"optional\":true,\"req\":\"^0.1.12\"}],\"features\":{\"static\":[\"lzma-sys/static\"],\"tokio\":[\"tokio-io\",\"futures\"]}}", "yaml-rust_0.4.5": "{\"dependencies\":[{\"name\":\"linked-hash-map\",\"req\":\"^0.5.3\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^0.9\"}],\"features\":{}}", "yansi_1.0.1": "{\"dependencies\":[{\"name\":\"is-terminal\",\"optional\":true,\"req\":\"^0.4.11\"}],\"features\":{\"_nightly\":[],\"alloc\":[],\"default\":[\"std\"],\"detect-env\":[\"std\"],\"detect-tty\":[\"is-terminal\",\"std\"],\"hyperlink\":[\"std\"],\"std\":[\"alloc\"]}}", @@ -1537,11 +1579,14 @@ "zerotrie_0.2.3": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"litemap\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.220\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"yoke\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"name\":\"zerofrom\",\"optional\":true,\"req\":\"^0.1.3\"},{\"default_features\":false,\"name\":\"zerovec\",\"optional\":true,\"req\":\"^0.11.3\"}],\"features\":{\"alloc\":[],\"databake\":[\"dep:databake\",\"zerovec?/databake\"],\"default\":[],\"litemap\":[\"dep:litemap\",\"alloc\"],\"serde\":[\"dep:serde_core\",\"dep:litemap\",\"alloc\",\"litemap/serde\",\"zerovec?/serde\"],\"yoke\":[\"dep:yoke\"],\"zerofrom\":[\"dep:zerofrom\"]}}", "zerovec-derive_0.11.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0.61\"},{\"name\":\"quote\",\"req\":\"^1.0.28\"},{\"default_features\":false,\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.45\"},{\"features\":[\"extra-traits\"],\"name\":\"syn\",\"req\":\"^2.0.21\"}],\"features\":{}}", "zerovec_0.11.5": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.220\"},{\"default_features\":false,\"features\":[\"xxhash64\"],\"name\":\"twox-hash\",\"optional\":true,\"req\":\"^2.0.0\"},{\"default_features\":false,\"name\":\"yoke\",\"optional\":true,\"req\":\"^0.8.0\"},{\"default_features\":false,\"name\":\"zerofrom\",\"req\":\"^0.1.3\"},{\"default_features\":false,\"name\":\"zerovec-derive\",\"optional\":true,\"req\":\"^0.11.1\"}],\"features\":{\"alloc\":[\"serde?/alloc\"],\"databake\":[\"dep:databake\"],\"derive\":[\"dep:zerovec-derive\"],\"hashmap\":[\"dep:twox-hash\",\"alloc\"],\"serde\":[\"dep:serde\"],\"std\":[],\"yoke\":[\"dep:yoke\"]}}", + "zip_0.6.6": "{\"dependencies\":[{\"name\":\"aes\",\"optional\":true,\"req\":\"^0.8.2\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"byteorder\",\"req\":\"^1.4.3\"},{\"name\":\"bzip2\",\"optional\":true,\"req\":\"^0.4.3\"},{\"name\":\"constant_time_eq\",\"optional\":true,\"req\":\"^0.1.5\"},{\"name\":\"crc32fast\",\"req\":\"^1.3.2\"},{\"name\":\"crossbeam-utils\",\"req\":\"^0.8.8\",\"target\":\"cfg(any(all(target_arch = \\\"arm\\\", target_pointer_width = \\\"32\\\"), target_arch = \\\"mips\\\", target_arch = \\\"powerpc\\\"))\"},{\"default_features\":false,\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.0.23\"},{\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.2.5\"},{\"features\":[\"reset\"],\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12.1\"},{\"name\":\"pbkdf2\",\"optional\":true,\"req\":\"^0.11.0\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.7\"},{\"features\":[\"formatting\",\"macros\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.7\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"name\":\"zstd\",\"optional\":true,\"req\":\"^0.11.2\"}],\"features\":{\"aes-crypto\":[\"aes\",\"constant_time_eq\",\"hmac\",\"pbkdf2\",\"sha1\"],\"default\":[\"aes-crypto\",\"bzip2\",\"deflate\",\"time\",\"zstd\"],\"deflate\":[\"flate2/rust_backend\"],\"deflate-miniz\":[\"flate2/default\"],\"deflate-zlib\":[\"flate2/zlib\"],\"unreserved\":[]}}", "zip_2.4.2": "{\"dependencies\":[{\"name\":\"aes\",\"optional\":true,\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.95\"},{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"req\":\"^1.4.1\",\"target\":\"cfg(fuzzing)\"},{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.5\"},{\"name\":\"bzip2\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"=4.4.18\"},{\"name\":\"constant_time_eq\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"crc32fast\",\"req\":\"^1.4\"},{\"name\":\"crossbeam-utils\",\"req\":\"^0.8.21\",\"target\":\"cfg(any(all(target_arch = \\\"arm\\\", target_pointer_width = \\\"32\\\"), target_arch = \\\"mips\\\", target_arch = \\\"powerpc\\\"))\"},{\"name\":\"deflate64\",\"optional\":true,\"req\":\"^0.1.9\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"flate2\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"wasm_js\",\"std\"],\"name\":\"getrandom\",\"optional\":true,\"req\":\"^0.3.1\"},{\"features\":[\"wasm_js\",\"std\"],\"kind\":\"dev\",\"name\":\"getrandom\",\"req\":\"^0.3.1\"},{\"features\":[\"reset\"],\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"lzma-rs\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"memchr\",\"req\":\"^2.7\"},{\"default_features\":false,\"name\":\"nt-time\",\"optional\":true,\"req\":\"^0.10.6\"},{\"name\":\"pbkdf2\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.15\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3.37\"},{\"default_features\":false,\"features\":[\"formatting\",\"macros\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3.37\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.5\"},{\"name\":\"xz2\",\"optional\":true,\"req\":\"^0.1.7\"},{\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.8\"},{\"name\":\"zopfli\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"zstd\",\"optional\":true,\"req\":\"^0.13\"}],\"features\":{\"_all-features\":[],\"_deflate-any\":[],\"aes-crypto\":[\"aes\",\"constant_time_eq\",\"hmac\",\"pbkdf2\",\"sha1\",\"getrandom\",\"zeroize\"],\"chrono\":[\"chrono/default\"],\"default\":[\"aes-crypto\",\"bzip2\",\"deflate64\",\"deflate\",\"lzma\",\"time\",\"zstd\",\"xz\"],\"deflate\":[\"flate2/rust_backend\",\"deflate-zopfli\",\"deflate-flate2\"],\"deflate-flate2\":[\"_deflate-any\"],\"deflate-miniz\":[\"deflate\",\"deflate-flate2\"],\"deflate-zlib\":[\"flate2/zlib\",\"deflate-flate2\"],\"deflate-zlib-ng\":[\"flate2/zlib-ng\",\"deflate-flate2\"],\"deflate-zopfli\":[\"zopfli\",\"_deflate-any\"],\"lzma\":[\"lzma-rs/stream\"],\"nt-time\":[\"dep:nt-time\"],\"unreserved\":[],\"xz\":[\"dep:xz2\"]}}", "zmij_1.0.19": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\",\"target\":\"cfg(not(miri))\"},{\"name\":\"no-panic\",\"optional\":true,\"req\":\"^0.1.36\"},{\"kind\":\"dev\",\"name\":\"num-bigint\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"num-integer\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.8\"},{\"kind\":\"dev\",\"name\":\"opt-level\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"kind\":\"dev\",\"name\":\"ryu\",\"req\":\"^1\"}],\"features\":{}}", "zopfli_0.8.3": "{\"dependencies\":[{\"name\":\"bumpalo\",\"req\":\"^3.19.0\"},{\"default_features\":false,\"name\":\"crc32fast\",\"optional\":true,\"req\":\"^1.5.0\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.28\"},{\"kind\":\"dev\",\"name\":\"miniz_oxide\",\"req\":\"^0.8.9\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.7.0\"},{\"kind\":\"dev\",\"name\":\"proptest-derive\",\"req\":\"^0.6.0\"},{\"default_features\":false,\"name\":\"simd-adler32\",\"optional\":true,\"req\":\"^0.3.7\"}],\"features\":{\"default\":[\"gzip\",\"std\",\"zlib\"],\"gzip\":[\"dep:crc32fast\"],\"nightly\":[\"crc32fast?/nightly\"],\"std\":[\"crc32fast?/std\",\"dep:log\",\"simd-adler32?/std\"],\"zlib\":[\"dep:simd-adler32\"]}}", + "zstd-safe_5.0.2+zstd.1.5.2": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.21\"},{\"default_features\":false,\"name\":\"zstd-sys\",\"req\":\"^2.0.1\"}],\"features\":{\"arrays\":[],\"bindgen\":[\"zstd-sys/bindgen\"],\"debug\":[\"zstd-sys/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-sys/experimental\"],\"legacy\":[\"zstd-sys/legacy\"],\"no_asm\":[\"zstd-sys/no_asm\"],\"pkg-config\":[\"zstd-sys/pkg-config\"],\"std\":[\"zstd-sys/std\"],\"thin\":[\"zstd-sys/thin\"],\"zdict_builder\":[\"zstd-sys/zdict_builder\"],\"zstdmt\":[\"zstd-sys/zstdmt\"]}}", "zstd-safe_7.2.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"zstd-sys\",\"req\":\"^2.0.15\"}],\"features\":{\"arrays\":[],\"bindgen\":[\"zstd-sys/bindgen\"],\"debug\":[\"zstd-sys/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-sys/experimental\"],\"fat-lto\":[\"zstd-sys/fat-lto\"],\"legacy\":[\"zstd-sys/legacy\"],\"no_asm\":[\"zstd-sys/no_asm\"],\"pkg-config\":[\"zstd-sys/pkg-config\"],\"seekable\":[\"zstd-sys/seekable\"],\"std\":[\"zstd-sys/std\"],\"thin\":[\"zstd-sys/thin\"],\"thin-lto\":[\"zstd-sys/thin-lto\"],\"zdict_builder\":[\"zstd-sys/zdict_builder\"],\"zstdmt\":[\"zstd-sys/zstdmt\"]}}", "zstd-sys_2.0.16+zstd.1.5.7": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"runtime\"],\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.72\"},{\"features\":[\"parallel\"],\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.0.45\"},{\"kind\":\"build\",\"name\":\"pkg-config\",\"req\":\"^0.3.28\"}],\"features\":{\"debug\":[],\"default\":[\"legacy\",\"zdict_builder\",\"bindgen\"],\"experimental\":[],\"fat-lto\":[],\"legacy\":[],\"no_asm\":[],\"no_wasm_shim\":[],\"non-cargo\":[],\"pkg-config\":[],\"seekable\":[],\"std\":[],\"thin\":[],\"thin-lto\":[],\"zdict_builder\":[],\"zstdmt\":[]}}", + "zstd_0.11.2+zstd.1.5.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^3.0\"},{\"kind\":\"dev\",\"name\":\"humansize\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"zstd-safe\",\"req\":\"^5.0.1\"}],\"features\":{\"arrays\":[\"zstd-safe/arrays\"],\"bindgen\":[\"zstd-safe/bindgen\"],\"debug\":[\"zstd-safe/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-safe/experimental\"],\"legacy\":[\"zstd-safe/legacy\"],\"no_asm\":[\"zstd-safe/no_asm\"],\"pkg-config\":[\"zstd-safe/pkg-config\"],\"thin\":[\"zstd-safe/thin\"],\"wasm\":[],\"zdict_builder\":[\"zstd-safe/zdict_builder\"],\"zstdmt\":[\"zstd-safe/zstdmt\"]}}", "zstd_0.13.3": "{\"dependencies\":[{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^4.0\"},{\"kind\":\"dev\",\"name\":\"humansize\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"partial-io\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"zstd-safe\",\"req\":\"^7.1.0\"}],\"features\":{\"arrays\":[\"zstd-safe/arrays\"],\"bindgen\":[\"zstd-safe/bindgen\"],\"debug\":[\"zstd-safe/debug\"],\"default\":[\"legacy\",\"arrays\",\"zdict_builder\"],\"doc-cfg\":[],\"experimental\":[\"zstd-safe/experimental\"],\"fat-lto\":[\"zstd-safe/fat-lto\"],\"legacy\":[\"zstd-safe/legacy\"],\"no_asm\":[\"zstd-safe/no_asm\"],\"pkg-config\":[\"zstd-safe/pkg-config\"],\"thin\":[\"zstd-safe/thin\"],\"thin-lto\":[\"zstd-safe/thin-lto\"],\"wasm\":[],\"zdict_builder\":[\"zstd-safe/zdict_builder\"],\"zstdmt\":[\"zstd-safe/zstdmt\"]}}", "zune-core_0.4.12": "{\"dependencies\":[{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.52\"}],\"features\":{\"std\":[]}}", "zune-core_0.5.1": "{\"dependencies\":[{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"std\":[]}}", diff --git a/codex-rs/.cargo/config.toml b/codex-rs/.cargo/config.toml index f5107cf73e..5d5eb8fd6f 100644 --- a/codex-rs/.cargo/config.toml +++ b/codex-rs/.cargo/config.toml @@ -1,5 +1,11 @@ [target.'cfg(all(windows, target_env = "msvc"))'] rustflags = ["-C", "link-arg=/STACK:8388608"] +# MSVC emits a warning about code that may trip "Cortex-A53 MPCore processor bug #843419" (see +# https://developer.arm.com/documentation/epm048406/latest) which is sometimes emitted by LLVM. +# Since Arm64 Windows 10+ isn't supported on that processor, it's safe to disable the warning. +[target.aarch64-pc-windows-msvc] +rustflags = ["-C", "link-arg=/STACK:8388608", "-C", "link-arg=/arm64hazardfree"] + [target.'cfg(all(windows, target_env = "gnu"))'] rustflags = ["-C", "link-arg=-Wl,--stack,8388608"] diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 21f17fc691..d9ee0f608b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -480,6 +480,58 @@ dependencies = [ "term", ] +[[package]] +name = "askama" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08e1676b346cadfec169374f949d7490fd80a24193d37d2afce0c047cf695e57" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7661ff56517787343f376f75db037426facd7c8d3049cef8911f1e75016f3a37" +dependencies = [ + "askama_parser", + "basic-toml", + "memchr", + "proc-macro2", + "quote", + "rustc-hash 2.1.1", + "serde", + "serde_derive", + "syn 2.0.114", +] + +[[package]] +name = "askama_macros" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "713ee4dbfd1eb719c2dab859465b01fa1d21cb566684614a713a6b7a99a4e47b" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d62d674238a526418b30c0def480d5beadb9d8964e7f38d635b03bf639c704c" +dependencies = [ + "rustc-hash 2.1.1", + "serde", + "serde_derive", + "unicode-ident", + "winnow", +] + [[package]] name = "asn1-rs" version = "0.7.1" @@ -779,9 +831,9 @@ dependencies = [ "form_urlencoded", "futures-util", "http 1.4.0", - "http-body", + "http-body 1.0.1", "http-body-util", - "hyper", + "hyper 1.8.1", "hyper-util", "itoa", "matchit 0.8.4", @@ -793,7 +845,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sync_wrapper", + "sync_wrapper 1.0.2", "tokio", "tower", "tower-layer", @@ -810,11 +862,11 @@ dependencies = [ "bytes", "futures-core", "http 1.4.0", - "http-body", + "http-body 1.0.1", "http-body-util", "mime", "pin-project-lite", - "sync_wrapper", + "sync_wrapper 1.0.2", "tower-layer", "tower-service", "tracing", @@ -1044,6 +1096,16 @@ dependencies = [ "bytes", ] +[[package]] +name = "bzip2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8" +dependencies = [ + "bzip2-sys", + "libc", +] + [[package]] name = "bzip2" version = "0.5.2" @@ -1341,7 +1403,7 @@ dependencies = [ "http 1.4.0", "pretty_assertions", "regex-lite", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "thiserror 2.0.18", @@ -1372,10 +1434,10 @@ dependencies = [ "codex-chatgpt", "codex-cloud-requirements", "codex-core", - "codex-execpolicy", "codex-feedback", "codex-file-search", "codex-login", + "codex-otel", "codex-protocol", "codex-rmcp-client", "codex-shell-command", @@ -1386,7 +1448,6 @@ dependencies = [ "codex-utils-json-to-toml", "core_test_support", "futures", - "os_info", "owo-colors", "pretty_assertions", "rmcp", @@ -1421,6 +1482,7 @@ dependencies = [ "schemars 0.8.22", "serde", "serde_json", + "serde_with", "shlex", "similar", "strum_macros 0.27.2", @@ -1476,6 +1538,39 @@ dependencies = [ "tokio", ] +[[package]] +name = "codex-artifact-presentation" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "image", + "ppt-rs", + "pretty_assertions", + "reqwest 0.12.28", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.18", + "tiny_http", + "uuid", + "zip 2.4.2", +] + +[[package]] +name = "codex-artifact-spreadsheet" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "pretty_assertions", + "regex", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.18", + "uuid", + "zip 2.4.2", +] + [[package]] name = "codex-async-utils" version = "0.0.0" @@ -1495,7 +1590,7 @@ dependencies = [ "codex-core", "codex-protocol", "pretty_assertions", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", ] @@ -1551,6 +1646,7 @@ dependencies = [ "codex-protocol", "codex-responses-api-proxy", "codex-rmcp-client", + "codex-state", "codex-stdio-to-uds", "codex-tui", "codex-utils-cargo-bin", @@ -1562,6 +1658,7 @@ dependencies = [ "pretty_assertions", "regex-lite", "serde_json", + "sqlx", "supports-color 3.0.2", "tempfile", "tokio", @@ -1581,7 +1678,7 @@ dependencies = [ "opentelemetry", "opentelemetry_sdk", "rand 0.9.2", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "thiserror 2.0.18", @@ -1589,7 +1686,7 @@ dependencies = [ "tracing", "tracing-opentelemetry", "tracing-subscriber", - "zstd", + "zstd 0.13.3", ] [[package]] @@ -1633,7 +1730,7 @@ dependencies = [ "owo-colors", "pretty_assertions", "ratatui", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "supports-color 3.0.2", @@ -1688,6 +1785,7 @@ version = "0.0.0" dependencies = [ "anyhow", "arc-swap", + "askama", "assert_cmd", "assert_matches", "async-channel", @@ -1701,6 +1799,8 @@ dependencies = [ "codex-app-server-protocol", "codex-apply-patch", "codex-arg0", + "codex-artifact-presentation", + "codex-artifact-spreadsheet", "codex-async-utils", "codex-client", "codex-config", @@ -1738,6 +1838,7 @@ dependencies = [ "eventsource-stream", "futures", "http 1.4.0", + "iana-time-zone", "image", "indexmap 2.13.0", "insta", @@ -1754,7 +1855,7 @@ dependencies = [ "pretty_assertions", "rand 0.9.2", "regex-lite", - "reqwest", + "reqwest 0.12.28", "rmcp", "schemars 0.8.22", "seccompiler", @@ -1786,8 +1887,8 @@ dependencies = [ "wildmatch", "windows-sys 0.52.0", "wiremock", - "zip", - "zstd", + "zip 2.4.2", + "zstd 0.13.3", ] [[package]] @@ -1846,6 +1947,7 @@ version = "0.0.0" dependencies = [ "anyhow", "clap", + "codex-utils-absolute-path", "multimap", "pretty_assertions", "serde", @@ -1978,7 +2080,7 @@ name = "codex-lmstudio" version = "0.0.0" dependencies = [ "codex-core", - "reqwest", + "reqwest 0.12.28", "serde_json", "tokio", "tracing", @@ -1997,7 +2099,7 @@ dependencies = [ "codex-core", "core_test_support", "rand 0.9.2", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "sha2", @@ -2078,7 +2180,7 @@ dependencies = [ "codex-core", "futures", "pretty_assertions", - "reqwest", + "reqwest 0.12.28", "semver", "serde_json", "tokio", @@ -2105,7 +2207,7 @@ dependencies = [ "opentelemetry_sdk", "os_info", "pretty_assertions", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "strum_macros 0.27.2", @@ -2161,7 +2263,7 @@ dependencies = [ "codex-process-hardening", "ctor 0.6.3", "libc", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "tiny_http", @@ -2183,7 +2285,7 @@ dependencies = [ "keyring", "oauth2", "pretty_assertions", - "reqwest", + "reqwest 0.12.28", "rmcp", "schemars 0.8.22", "serde", @@ -2246,6 +2348,7 @@ dependencies = [ "anyhow", "async-trait", "clap", + "codex-protocol", "codex-utils-absolute-path", "libc", "pretty_assertions", @@ -2346,6 +2449,7 @@ dependencies = [ "codex-utils-pty", "codex-utils-sandbox-summary", "codex-utils-sleep-inhibitor", + "codex-utils-string", "codex-windows-sandbox", "color-eyre", "cpal", @@ -2367,7 +2471,7 @@ dependencies = [ "ratatui", "ratatui-macros", "regex-lite", - "reqwest", + "reqwest 0.12.28", "rmcp", "serde", "serde_json", @@ -2709,6 +2813,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "constant_time_eq" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" + [[package]] name = "constant_time_eq" version = "0.3.1" @@ -2784,7 +2894,7 @@ dependencies = [ "notify", "pretty_assertions", "regex-lite", - "reqwest", + "reqwest 0.12.28", "serde_json", "shlex", "tempfile", @@ -2792,7 +2902,7 @@ dependencies = [ "tokio-tungstenite", "walkdir", "wiremock", - "zstd", + "zstd 0.13.3", ] [[package]] @@ -2961,6 +3071,29 @@ dependencies = [ "typenum", ] +[[package]] +name = "cssparser" +version = "0.31.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3df4f93e5fbbe73ec01ec8d3f68bba73107993a5b1e7519273c32db9b0d5be" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.11.3", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.114", +] + [[package]] name = "csv" version = "1.4.0" @@ -3281,6 +3414,17 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + [[package]] name = "derive_more" version = "1.0.0" @@ -3450,6 +3594,21 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + [[package]] name = "dtor" version = "0.1.1" @@ -3497,6 +3656,12 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ego-tree" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12a0bb14ac04a9fcf170d0bbbef949b44cc492f4452bd20c095636956f653642" + [[package]] name = "either" version = "1.15.0" @@ -3960,6 +4125,16 @@ dependencies = [ "libc", ] +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + [[package]] name = "futures" version = "0.3.31" @@ -4188,6 +4363,25 @@ dependencies = [ "regex-syntax 0.8.8", ] +[[package]] +name = "h2" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap 2.13.0", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "h2" version = "0.4.13" @@ -4397,6 +4591,20 @@ version = "3.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" +[[package]] +name = "html5ever" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7" +dependencies = [ + "log", + "mac", + "markup5ever", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "http" version = "0.2.12" @@ -4418,6 +4626,17 @@ dependencies = [ "itoa", ] +[[package]] +name = "http-body" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +dependencies = [ + "bytes", + "http 0.2.12", + "pin-project-lite", +] + [[package]] name = "http-body" version = "1.0.1" @@ -4437,7 +4656,7 @@ dependencies = [ "bytes", "futures-core", "http 1.4.0", - "http-body", + "http-body 1.0.1", "pin-project-lite", ] @@ -4459,6 +4678,30 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hyper" +version = "0.14.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2 0.3.27", + "http 0.2.12", + "http-body 0.4.6", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2 0.5.10", + "tokio", + "tower-service", + "tracing", + "want", +] + [[package]] name = "hyper" version = "1.8.1" @@ -4469,9 +4712,9 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2", + "h2 0.4.13", "http 1.4.0", - "http-body", + "http-body 1.0.1", "httparse", "httpdate", "itoa", @@ -4489,7 +4732,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" dependencies = [ "http 1.4.0", - "hyper", + "hyper 1.8.1", "hyper-util", "rustls", "rustls-native-certs", @@ -4506,13 +4749,26 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper", + "hyper 1.8.1", "hyper-util", "pin-project-lite", "tokio", "tower-service", ] +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper 0.14.32", + "native-tls", + "tokio", + "tokio-native-tls", +] + [[package]] name = "hyper-tls" version = "0.6.0" @@ -4521,7 +4777,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", - "hyper", + "hyper 1.8.1", "hyper-util", "native-tls", "tokio", @@ -4541,14 +4797,14 @@ dependencies = [ "futures-core", "futures-util", "http 1.4.0", - "http-body", - "hyper", + "http-body 1.0.1", + "hyper 1.8.1", "ipnet", "libc", "percent-encoding", "pin-project-lite", "socket2 0.6.2", - "system-configuration", + "system-configuration 0.6.1", "tokio", "tower-service", "tracing", @@ -5456,6 +5712,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + [[package]] name = "mach2" version = "0.4.3" @@ -5471,6 +5733,20 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" +[[package]] +name = "markup5ever" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016" +dependencies = [ + "log", + "phf 0.10.1", + "phf_codegen", + "string_cache", + "string_cache_codegen", + "tendril", +] + [[package]] name = "matchers" version = "0.2.0" @@ -5968,7 +6244,7 @@ dependencies = [ "getrandom 0.2.17", "http 1.4.0", "rand 0.8.5", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "serde_path_to_error", @@ -6329,7 +6605,7 @@ dependencies = [ "bytes", "http 1.4.0", "opentelemetry", - "reqwest", + "reqwest 0.12.28", ] [[package]] @@ -6344,7 +6620,7 @@ dependencies = [ "opentelemetry-proto", "opentelemetry_sdk", "prost", - "reqwest", + "reqwest 0.12.28", "serde_json", "thiserror 2.0.18", "tokio", @@ -6473,6 +6749,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "paste" version = "1.0.15" @@ -6509,6 +6796,18 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" +[[package]] +name = "pbkdf2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +dependencies = [ + "digest", + "hmac", + "password-hash", + "sha2", +] + [[package]] name = "pbkdf2" version = "0.12.2" @@ -6565,13 +6864,84 @@ dependencies = [ "indexmap 2.13.0", ] +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_shared 0.10.0", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_codegen" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared 0.10.0", + "rand 0.8.5", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.5", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher 0.3.11", +] + [[package]] name = "phf_shared" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" dependencies = [ - "siphasher", + "siphasher 1.0.2", ] [[package]] @@ -6748,6 +7118,26 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppt-rs" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2135454fb8669ee8eef79c87a7e9ad6f5d563d13fb1041746e2d3e3e4d716749" +dependencies = [ + "chrono", + "clap", + "pulldown-cmark", + "regex", + "reqwest 0.11.27", + "scraper", + "syntect", + "thiserror 1.0.69", + "url", + "uuid", + "xml-rs", + "zip 0.6.6", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -7128,7 +7518,7 @@ version = "0.3.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3ff6a3c8ae690be8167e43777ba0bf6b0c8c2f6de165c538666affe2a32fd81" dependencies = [ - "h2", + "h2 0.4.13", "pin-project-lite", "rama-core", "rama-http", @@ -7200,7 +7590,7 @@ dependencies = [ "const_format", "fnv", "http 1.4.0", - "http-body", + "http-body 1.0.1", "http-body-util", "itoa", "memchr", @@ -7215,7 +7605,7 @@ dependencies = [ "rand 0.9.2", "serde", "serde_json", - "sync_wrapper", + "sync_wrapper 1.0.2", "tokio", ] @@ -7585,6 +7975,46 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" +[[package]] +name = "reqwest" +version = "0.11.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" +dependencies = [ + "base64 0.21.7", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2 0.3.27", + "http 0.2.12", + "http-body 0.4.6", + "hyper 0.14.32", + "hyper-tls 0.5.0", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper 0.1.2", + "system-configuration 0.5.1", + "tokio", + "tokio-native-tls", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "winreg 0.50.0", +] + [[package]] name = "reqwest" version = "0.12.28" @@ -7597,13 +8027,13 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2", + "h2 0.4.13", "http 1.4.0", - "http-body", + "http-body 1.0.1", "http-body-util", - "hyper", + "hyper 1.8.1", "hyper-rustls", - "hyper-tls", + "hyper-tls 0.6.0", "hyper-util", "js-sys", "log", @@ -7619,7 +8049,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper", + "sync_wrapper 1.0.2", "tokio", "tokio-native-tls", "tokio-rustls", @@ -7668,14 +8098,14 @@ dependencies = [ "chrono", "futures", "http 1.4.0", - "http-body", + "http-body 1.0.1", "http-body-util", "oauth2", "pastey", "pin-project-lite", "process-wrap", "rand 0.9.2", - "reqwest", + "reqwest 0.12.28", "rmcp-macros", "schemars 1.2.1", "serde", @@ -7863,6 +8293,15 @@ dependencies = [ "security-framework 3.5.1", ] +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.7", +] + [[package]] name = "rustls-pki-types" version = "1.14.0" @@ -8071,13 +8510,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scraper" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585480e3719b311b78a573db1c9d9c4c1f8010c2dee4cc59c2efe58ea4dbc3e1" +dependencies = [ + "ahash", + "cssparser", + "ego-tree", + "getopts", + "html5ever", + "once_cell", + "selectors", + "tendril", +] + [[package]] name = "scrypt" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" dependencies = [ - "pbkdf2", + "pbkdf2 0.12.2", "salsa20", "sha2", ] @@ -8161,6 +8616,25 @@ dependencies = [ "libc", ] +[[package]] +name = "selectors" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4eb30575f3638fc8f6815f448d50cb1a2e255b0897985c8c59f4d37b72a07b06" +dependencies = [ + "bitflags 2.10.0", + "cssparser", + "derive_more 0.99.20", + "fxhash", + "log", + "new_debug_unreachable", + "phf 0.10.1", + "phf_codegen", + "precomputed-hash", + "servo_arc", + "smallvec", +] + [[package]] name = "self_cell" version = "0.10.3" @@ -8190,7 +8664,7 @@ checksum = "2f925d575b468e88b079faf590a8dd0c9c99e2ec29e9bab663ceb8b45056312f" dependencies = [ "httpdate", "native-tls", - "reqwest", + "reqwest 0.12.28", "sentry-actix", "sentry-backtrace", "sentry-contexts", @@ -8495,6 +8969,15 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "servo_arc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d036d71a959e00c77a63538b90a6c2390969f9772b096ea837205c6bd0491a44" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "sha1" version = "0.10.6" @@ -8613,6 +9096,12 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + [[package]] name = "siphasher" version = "1.0.2" @@ -8899,7 +9388,7 @@ checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a" dependencies = [ "bytes", "futures-util", - "http-body", + "http-body 1.0.1", "http-body-util", "pin-project-lite", ] @@ -9029,8 +9518,21 @@ checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" dependencies = [ "new_debug_unreachable", "parking_lot", - "phf_shared", + "phf_shared 0.11.3", "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", ] [[package]] @@ -9143,6 +9645,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -9193,6 +9701,17 @@ dependencies = [ "libc", ] +[[package]] +name = "system-configuration" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "system-configuration-sys 0.5.0", +] + [[package]] name = "system-configuration" version = "0.6.1" @@ -9201,7 +9720,17 @@ checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ "bitflags 2.10.0", "core-foundation 0.9.4", - "system-configuration-sys", + "system-configuration-sys 0.6.0", +] + +[[package]] +name = "system-configuration-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +dependencies = [ + "core-foundation-sys", + "libc", ] [[package]] @@ -9233,6 +9762,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + [[package]] name = "term" version = "0.7.0" @@ -9684,15 +10224,15 @@ dependencies = [ "base64 0.22.1", "bytes", "http 1.4.0", - "http-body", + "http-body 1.0.1", "http-body-util", - "hyper", + "hyper 1.8.1", "hyper-timeout", "hyper-util", "percent-encoding", "pin-project", "rustls-native-certs", - "sync_wrapper", + "sync_wrapper 1.0.2", "tokio", "tokio-rustls", "tokio-stream", @@ -9724,7 +10264,7 @@ dependencies = [ "indexmap 2.13.0", "pin-project-lite", "slab", - "sync_wrapper", + "sync_wrapper 1.0.2", "tokio", "tokio-util", "tower-layer", @@ -9742,7 +10282,7 @@ dependencies = [ "bytes", "futures-util", "http 1.4.0", - "http-body", + "http-body 1.0.1", "iri-string", "pin-project-lite", "tower", @@ -11183,7 +11723,7 @@ dependencies = [ "futures", "http 1.4.0", "http-body-util", - "hyper", + "hyper 1.8.1", "hyper-util", "log", "once_cell", @@ -11282,6 +11822,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "xml-rs" +version = "0.8.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" + [[package]] name = "xz2" version = "0.1.7" @@ -11495,6 +12041,26 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "zip" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261" +dependencies = [ + "aes", + "byteorder", + "bzip2 0.4.4", + "constant_time_eq 0.1.5", + "crc32fast", + "crossbeam-utils", + "flate2", + "hmac", + "pbkdf2 0.11.0", + "sha1", + "time", + "zstd 0.11.2+zstd.1.5.2", +] + [[package]] name = "zip" version = "2.4.2" @@ -11503,8 +12069,8 @@ checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" dependencies = [ "aes", "arbitrary", - "bzip2", - "constant_time_eq", + "bzip2 0.5.2", + "constant_time_eq 0.3.1", "crc32fast", "crossbeam-utils", "deflate64", @@ -11515,14 +12081,14 @@ dependencies = [ "indexmap 2.13.0", "lzma-rs", "memchr", - "pbkdf2", + "pbkdf2 0.12.2", "sha1", "thiserror 2.0.18", "time", "xz2", "zeroize", "zopfli", - "zstd", + "zstd 0.13.3", ] [[package]] @@ -11543,13 +12109,32 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zstd" +version = "0.11.2+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" +dependencies = [ + "zstd-safe 5.0.2+zstd.1.5.2", +] + [[package]] name = "zstd" version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ - "zstd-safe", + "zstd-safe 7.2.4", +] + +[[package]] +name = "zstd-safe" +version = "5.0.2+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db" +dependencies = [ + "libc", + "zstd-sys", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 3bb436ef07..9ee05e21b6 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -33,6 +33,8 @@ members = [ "mcp-server", "network-proxy", "ollama", + "artifact-presentation", + "artifact-spreadsheet", "process-hardening", "protocol", "rmcp-client", @@ -109,6 +111,8 @@ codex-mcp-server = { path = "mcp-server" } codex-network-proxy = { path = "network-proxy" } codex-ollama = { path = "ollama" } codex-otel = { path = "otel" } +codex-artifact-presentation = { path = "artifact-presentation" } +codex-artifact-spreadsheet = { path = "artifact-spreadsheet" } codex-process-hardening = { path = "process-hardening" } codex-protocol = { path = "protocol" } codex-responses-api-proxy = { path = "responses-api-proxy" } @@ -118,8 +122,8 @@ codex-shell-command = { path = "shell-command" } codex-shell-escalation = { path = "shell-escalation" } codex-skills = { path = "skills" } codex-state = { path = "state" } -codex-test-macros = { path = "test-macros" } codex-stdio-to-uds = { path = "stdio-to-uds" } +codex-test-macros = { path = "test-macros" } codex-tui = { path = "tui" } codex-utils-absolute-path = { path = "utils/absolute-path" } codex-utils-approval-presets = { path = "utils/approval-presets" } @@ -137,8 +141,8 @@ codex-utils-readiness = { path = "utils/readiness" } codex-utils-rustls-provider = { path = "utils/rustls-provider" } codex-utils-sandbox-summary = { path = "utils/sandbox-summary" } codex-utils-sleep-inhibitor = { path = "utils/sleep-inhibitor" } -codex-utils-string = { path = "utils/string" } codex-utils-stream-parser = { path = "utils/stream-parser" } +codex-utils-string = { path = "utils/string" } codex-windows-sandbox = { path = "windows-sandbox-rs" } core_test_support = { path = "core/tests/common" } mcp_test_support = { path = "mcp-server/tests/common" } @@ -149,6 +153,7 @@ allocative = "0.3.3" ansi-to-tui = "7.0.0" anyhow = "1" arboard = { version = "3", features = ["wayland-data-control"] } +askama = "0.15.4" assert_cmd = "2" assert_matches = "1.5.0" async-channel = "2.3.1" @@ -164,8 +169,8 @@ clap = "4" clap_complete = "4" color-eyre = "0.6.3" crossbeam-channel = "0.5.15" -csv = "1.3.1" crossterm = "0.28.1" +csv = "1.3.1" ctor = "0.6.3" derive_more = "2" diffy = "0.4.2" @@ -177,14 +182,15 @@ env-flags = "0.1.1" env_logger = "0.11.9" eventsource-stream = "0.2.3" futures = { version = "0.3", default-features = false } -globset = "0.4" gethostname = "1.1.0" +globset = "0.4" http = "1.3.1" icu_decimal = "2.1" icu_locale_core = "2.1" icu_provider = { version = "2.1", features = ["sync"] } ignore = "0.4.23" image = { version = "^0.25.9", default-features = false } +iana-time-zone = "0.1.64" include_dir = "0.7.4" indexmap = "2.12.0" insta = "1.46.3" @@ -213,6 +219,7 @@ owo-colors = "4.3.0" path-absolutize = "3.1.1" pathdiff = "0.2" portable-pty = "0.9.0" +ppt-rs = "0.2.6" predicates = "3" pretty_assertions = "1.4.1" pulldown-cmark = "0.10" @@ -257,6 +264,7 @@ starlark = "0.13.0" strum = "0.27.2" strum_macros = "0.27.2" supports-color = "3.0.2" +syntect = "5" sys-locale = "0.3.2" tempfile = "3.23.0" test-log = "0.2.19" @@ -281,7 +289,6 @@ tracing-subscriber = "0.3.22" tracing-test = "0.2.5" tree-sitter = "0.25.10" tree-sitter-bash = "0.25" -syntect = "5" ts-rs = "11" tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] } uds_windows = "1.1.0" @@ -347,10 +354,12 @@ ignored = [ "openssl-sys", "codex-utils-readiness", "codex-secrets", + "codex-artifact-spreadsheet" ] [profile.release] lto = "fat" +split-debuginfo = "off" # Because we bundle some of these executables with the TypeScript CLI, we # remove everything to make the binary as small as possible. strip = "symbols" diff --git a/codex-rs/app-server-protocol/Cargo.toml b/codex-rs/app-server-protocol/Cargo.toml index f5df7af034..dc6823a4af 100644 --- a/codex-rs/app-server-protocol/Cargo.toml +++ b/codex-rs/app-server-protocol/Cargo.toml @@ -20,6 +20,7 @@ codex-utils-absolute-path = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } +serde_with = { workspace = true } shlex = { workspace = true } strum_macros = { workspace = true } thiserror = { workspace = true } diff --git a/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalResponse.json b/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalResponse.json index 37380f5988..84842fd194 100644 --- a/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalResponse.json +++ b/codex-rs/app-server-protocol/schema/json/ApplyPatchApprovalResponse.json @@ -59,7 +59,7 @@ "type": "object" }, { - "description": "User has approved this command and wants to automatically approve any future identical instances (`command` and `cwd` match exactly) for the remainder of the session.", + "description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", "enum": [ "approved_for_session" ], diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index b5b85d88a4..01790fb98f 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1340,7 +1340,7 @@ "type": "string" }, "output": { - "type": "string" + "$ref": "#/definitions/FunctionCallOutputPayload" }, "type": { "enum": [ @@ -1703,6 +1703,12 @@ } ] }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "Settings": { "description": "Settings for a collaboration mode.", "properties": { @@ -1933,6 +1939,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } @@ -2155,6 +2178,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } @@ -2299,6 +2339,23 @@ "string", "null" ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] } }, "type": "object" @@ -2314,6 +2371,17 @@ ], "type": "object" }, + "ThreadUnsubscribeParams": { + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "type": "object" + }, "TurnInterruptParams": { "properties": { "threadId": { @@ -2398,6 +2466,24 @@ ], "description": "Override the sandbox policy for this turn and subsequent turns." }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ], + "description": "Override the service tier for this turn and subsequent turns." + }, "summary": { "anyOf": [ { @@ -2805,6 +2891,30 @@ "title": "Thread/archiveRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/unsubscribe" + ], + "title": "Thread/unsubscribeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnsubscribeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/unsubscribeRequest", + "type": "object" + }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json index 2122ad6521..5a19a39281 100644 --- a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json @@ -1,11 +1,15 @@ { "$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" + }, "AdditionalFileSystemPermissions": { "properties": { "read": { "items": { - "type": "string" + "$ref": "#/definitions/AbsolutePathBuf" }, "type": [ "array", @@ -14,7 +18,7 @@ }, "write": { "items": { - "type": "string" + "$ref": "#/definitions/AbsolutePathBuf" }, "type": [ "array", @@ -202,6 +206,85 @@ } ] }, + "CommandExecutionApprovalDecision": { + "oneOf": [ + { + "description": "User approved the command.", + "enum": [ + "accept" + ], + "type": "string" + }, + { + "description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", + "enum": [ + "acceptForSession" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.", + "properties": { + "acceptWithExecpolicyAmendment": { + "properties": { + "execpolicy_amendment": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "execpolicy_amendment" + ], + "type": "object" + } + }, + "required": [ + "acceptWithExecpolicyAmendment" + ], + "title": "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision", + "type": "object" + }, + { + "additionalProperties": false, + "description": "User chose a persistent network policy rule (allow/deny) for this host.", + "properties": { + "applyNetworkPolicyAmendment": { + "properties": { + "network_policy_amendment": { + "$ref": "#/definitions/NetworkPolicyAmendment" + } + }, + "required": [ + "network_policy_amendment" + ], + "type": "object" + } + }, + "required": [ + "applyNetworkPolicyAmendment" + ], + "title": "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision", + "type": "object" + }, + { + "description": "User denied the command. The agent will continue the turn.", + "enum": [ + "decline" + ], + "type": "string" + }, + { + "description": "User denied the command. The turn will also be immediately interrupted.", + "enum": [ + "cancel" + ], + "type": "string" + } + ] + }, "MacOsAutomationValue": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalResponse.json b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalResponse.json index 04e914a390..0b7986fba9 100644 --- a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalResponse.json +++ b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalResponse.json @@ -11,7 +11,7 @@ "type": "string" }, { - "description": "User approved the command and future identical commands should run without prompting.", + "description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", "enum": [ "acceptForSession" ], diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index 5139e5da66..4258bf7c2c 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -500,6 +500,50 @@ ], "type": "object" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, "EventMsg": { "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", "oneOf": [ @@ -1094,6 +1138,16 @@ ], "description": "How to sandbox commands executed in the system" }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "session_id": { "$ref": "#/definitions/ThreadId" }, @@ -1631,6 +1685,16 @@ "null" ] }, + "available_decisions": { + "description": "Ordered list of decisions the client may present for this prompt.\n\nWhen absent, clients should derive the legacy default set from the other fields on this request.", + "items": { + "$ref": "#/definitions/ReviewDecision" + }, + "type": [ + "array", + "null" + ] + }, "call_id": { "description": "Identifier for the associated command execution item.", "type": "string" @@ -1778,26 +1842,66 @@ }, { "properties": { - "item_id": { + "arguments": { + "description": "Dynamic tool call arguments." + }, + "call_id": { + "description": "Identifier for the corresponding DynamicToolCallRequest.", "type": "string" }, - "skill_name": { + "content_items": { + "description": "Dynamic tool response content items.", + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the dynamic tool call." + }, + "error": { + "description": "Optional error text when the tool call failed before producing a response.", + "type": [ + "string", + "null" + ] + }, + "success": { + "description": "Whether the tool call succeeded.", + "type": "boolean" + }, + "tool": { + "description": "Dynamic tool name.", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this dynamic tool call belongs to.", "type": "string" }, "type": { "enum": [ - "skill_request_approval" + "dynamic_tool_call_response" ], - "title": "SkillRequestApprovalEventMsgType", + "title": "DynamicToolCallResponseEventMsgType", "type": "string" } }, "required": [ - "item_id", - "skill_name", + "arguments", + "call_id", + "content_items", + "duration", + "success", + "tool", + "turn_id", "type" ], - "title": "SkillRequestApprovalEventMsg", + "title": "DynamicToolCallResponseEventMsg", "type": "object" }, { @@ -3317,7 +3421,7 @@ "properties": { "read": { "items": { - "type": "string" + "$ref": "#/definitions/AbsolutePathBuf" }, "type": [ "array", @@ -3326,7 +3430,7 @@ }, "write": { "items": { - "type": "string" + "$ref": "#/definitions/AbsolutePathBuf" }, "type": [ "array", @@ -4140,8 +4244,14 @@ { "additionalProperties": false, "properties": { - "SessionCreated": { + "SessionUpdated": { "properties": { + "instructions": { + "type": [ + "string", + "null" + ] + }, "session_id": { "type": "string" } @@ -4152,27 +4262,6 @@ "type": "object" } }, - "required": [ - "SessionCreated" - ], - "title": "SessionCreatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "SessionUpdated": { - "properties": { - "backend_prompt": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - } - }, "required": [ "SessionUpdated" ], @@ -4203,6 +4292,40 @@ "title": "ConversationItemAddedRealtimeEvent", "type": "object" }, + { + "additionalProperties": false, + "properties": { + "ConversationItemDone": { + "properties": { + "item_id": { + "type": "string" + } + }, + "required": [ + "item_id" + ], + "type": "object" + } + }, + "required": [ + "ConversationItemDone" + ], + "title": "ConversationItemDoneRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "HandoffRequested": { + "$ref": "#/definitions/RealtimeHandoffRequested" + } + }, + "required": [ + "HandoffRequested" + ], + "title": "HandoffRequestedRealtimeEvent", + "type": "object" + }, { "additionalProperties": false, "properties": { @@ -4218,6 +4341,47 @@ } ] }, + "RealtimeHandoffMessage": { + "properties": { + "role": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "role", + "text" + ], + "type": "object" + }, + "RealtimeHandoffRequested": { + "properties": { + "handoff_id": { + "type": "string" + }, + "input_transcript": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "messages": { + "items": { + "$ref": "#/definitions/RealtimeHandoffMessage" + }, + "type": "array" + } + }, + "required": [ + "handoff_id", + "input_transcript", + "item_id", + "messages" + ], + "type": "object" + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ @@ -4728,7 +4892,7 @@ "type": "string" }, "output": { - "type": "string" + "$ref": "#/definitions/FunctionCallOutputPayload" }, "type": { "enum": [ @@ -4887,6 +5051,86 @@ ], "type": "object" }, + "ReviewDecision": { + "description": "User's decision in response to an ExecApprovalRequest.", + "oneOf": [ + { + "description": "User has approved this command and the agent should execute it.", + "enum": [ + "approved" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.", + "properties": { + "approved_execpolicy_amendment": { + "properties": { + "proposed_execpolicy_amendment": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "proposed_execpolicy_amendment" + ], + "type": "object" + } + }, + "required": [ + "approved_execpolicy_amendment" + ], + "title": "ApprovedExecpolicyAmendmentReviewDecision", + "type": "object" + }, + { + "description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", + "enum": [ + "approved_for_session" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.", + "properties": { + "network_policy_amendment": { + "properties": { + "network_policy_amendment": { + "$ref": "#/definitions/NetworkPolicyAmendment" + } + }, + "required": [ + "network_policy_amendment" + ], + "type": "object" + } + }, + "required": [ + "network_policy_amendment" + ], + "title": "NetworkPolicyAmendmentReviewDecision", + "type": "object" + }, + { + "description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.", + "enum": [ + "denied" + ], + "type": "string" + }, + { + "description": "User has denied this command and the agent should not do anything until the user's next command.", + "enum": [ + "abort" + ], + "type": "string" + } + ] + }, "ReviewFinding": { "description": "A single review finding describing an observed issue or recommendation.", "properties": { @@ -5176,6 +5420,12 @@ } ] }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "SessionNetworkProxyRuntime": { "properties": { "admin_addr": { @@ -6520,6 +6770,16 @@ ], "description": "How to sandbox commands executed in the system" }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "session_id": { "$ref": "#/definitions/ThreadId" }, @@ -7057,6 +7317,16 @@ "null" ] }, + "available_decisions": { + "description": "Ordered list of decisions the client may present for this prompt.\n\nWhen absent, clients should derive the legacy default set from the other fields on this request.", + "items": { + "$ref": "#/definitions/ReviewDecision" + }, + "type": [ + "array", + "null" + ] + }, "call_id": { "description": "Identifier for the associated command execution item.", "type": "string" @@ -7204,26 +7474,66 @@ }, { "properties": { - "item_id": { + "arguments": { + "description": "Dynamic tool call arguments." + }, + "call_id": { + "description": "Identifier for the corresponding DynamicToolCallRequest.", "type": "string" }, - "skill_name": { + "content_items": { + "description": "Dynamic tool response content items.", + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the dynamic tool call." + }, + "error": { + "description": "Optional error text when the tool call failed before producing a response.", + "type": [ + "string", + "null" + ] + }, + "success": { + "description": "Whether the tool call succeeded.", + "type": "boolean" + }, + "tool": { + "description": "Dynamic tool name.", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this dynamic tool call belongs to.", "type": "string" }, "type": { "enum": [ - "skill_request_approval" + "dynamic_tool_call_response" ], - "title": "SkillRequestApprovalEventMsgType", + "title": "DynamicToolCallResponseEventMsgType", "type": "string" } }, "required": [ - "item_id", - "skill_name", + "arguments", + "call_id", + "content_items", + "duration", + "success", + "tool", + "turn_id", "type" ], - "title": "SkillRequestApprovalEventMsg", + "title": "DynamicToolCallResponseEventMsg", "type": "object" }, { diff --git a/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalResponse.json b/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalResponse.json index ac15f23658..baedafa403 100644 --- a/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalResponse.json +++ b/codex-rs/app-server-protocol/schema/json/ExecCommandApprovalResponse.json @@ -59,7 +59,7 @@ "type": "object" }, { - "description": "User has approved this command and wants to automatically approve any future identical instances (`command` and `cwd` match exactly) for the remainder of the session.", + "description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", "enum": [ "approved_for_session" ], diff --git a/codex-rs/app-server-protocol/schema/json/JSONRPCMessage.json b/codex-rs/app-server-protocol/schema/json/JSONRPCMessage.json index b2f6c31011..27b78b90c9 100644 --- a/codex-rs/app-server-protocol/schema/json/JSONRPCMessage.json +++ b/codex-rs/app-server-protocol/schema/json/JSONRPCMessage.json @@ -70,7 +70,18 @@ "method": { "type": "string" }, - "params": true + "params": true, + "trace": { + "anyOf": [ + { + "$ref": "#/definitions/W3cTraceContext" + }, + { + "type": "null" + } + ], + "description": "Optional W3C Trace Context for distributed tracing." + } }, "required": [ "id", @@ -102,6 +113,23 @@ "type": "integer" } ] + }, + "W3cTraceContext": { + "properties": { + "traceparent": { + "type": [ + "string", + "null" + ] + }, + "tracestate": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" } }, "description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.", diff --git a/codex-rs/app-server-protocol/schema/json/JSONRPCRequest.json b/codex-rs/app-server-protocol/schema/json/JSONRPCRequest.json index cc7a16f1ba..e4ea7c206b 100644 --- a/codex-rs/app-server-protocol/schema/json/JSONRPCRequest.json +++ b/codex-rs/app-server-protocol/schema/json/JSONRPCRequest.json @@ -11,6 +11,23 @@ "type": "integer" } ] + }, + "W3cTraceContext": { + "properties": { + "traceparent": { + "type": [ + "string", + "null" + ] + }, + "tracestate": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" } }, "description": "A request that expects a response.", @@ -21,7 +38,18 @@ "method": { "type": "string" }, - "params": true + "params": true, + "trace": { + "anyOf": [ + { + "$ref": "#/definitions/W3cTraceContext" + }, + { + "type": "null" + } + ], + "description": "Optional W3C Trace Context for distributed tracing." + } }, "required": [ "id", diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 47cdc64723..28df2574b2 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -46,6 +46,16 @@ "type": "null" } ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/PlanType" + }, + { + "type": "null" + } + ] } }, "type": "object" @@ -778,6 +788,58 @@ ], "type": "object" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "ErrorNotification": { "properties": { "error": { @@ -1370,6 +1432,32 @@ ], "type": "object" }, + "RequestId": { + "anyOf": [ + { + "type": "string" + }, + { + "format": "int64", + "type": "integer" + } + ] + }, + "ServerRequestResolvedNotification": { + "properties": { + "requestId": { + "$ref": "#/definitions/RequestId" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "requestId", + "threadId" + ], + "type": "object" + }, "SessionSource": { "oneOf": [ { @@ -1577,6 +1665,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -1646,6 +1738,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -1674,6 +1767,17 @@ ], "type": "object" }, + "ThreadClosedNotification": { + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "type": "object" + }, "ThreadId": { "type": "string" }, @@ -1965,6 +2069,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { @@ -3025,6 +3182,26 @@ "title": "Thread/unarchivedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "thread/closed" + ], + "title": "Thread/closedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadClosedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/closedNotification", + "type": "object" + }, { "properties": { "method": { @@ -3286,6 +3463,26 @@ "title": "Item/fileChange/outputDeltaNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "serverRequest/resolved" + ], + "title": "ServerRequest/resolvedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ServerRequestResolvedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ServerRequest/resolvedNotification", + "type": "object" + }, { "properties": { "method": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index ba94b889cf..9138440548 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -1,11 +1,15 @@ { "$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" + }, "AdditionalFileSystemPermissions": { "properties": { "read": { "items": { - "type": "string" + "$ref": "#/definitions/AbsolutePathBuf" }, "type": [ "array", @@ -14,7 +18,7 @@ }, "write": { "items": { - "type": "string" + "$ref": "#/definitions/AbsolutePathBuf" }, "type": [ "array", @@ -268,6 +272,85 @@ } ] }, + "CommandExecutionApprovalDecision": { + "oneOf": [ + { + "description": "User approved the command.", + "enum": [ + "accept" + ], + "type": "string" + }, + { + "description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", + "enum": [ + "acceptForSession" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.", + "properties": { + "acceptWithExecpolicyAmendment": { + "properties": { + "execpolicy_amendment": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "execpolicy_amendment" + ], + "type": "object" + } + }, + "required": [ + "acceptWithExecpolicyAmendment" + ], + "title": "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision", + "type": "object" + }, + { + "additionalProperties": false, + "description": "User chose a persistent network policy rule (allow/deny) for this host.", + "properties": { + "applyNetworkPolicyAmendment": { + "properties": { + "network_policy_amendment": { + "$ref": "#/definitions/NetworkPolicyAmendment" + } + }, + "required": [ + "network_policy_amendment" + ], + "type": "object" + } + }, + "required": [ + "applyNetworkPolicyAmendment" + ], + "title": "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision", + "type": "object" + }, + { + "description": "User denied the command. The agent will continue the turn.", + "enum": [ + "decline" + ], + "type": "string" + }, + { + "description": "User denied the command. The turn will also be immediately interrupted.", + "enum": [ + "cancel" + ], + "type": "string" + } + ] + }, "CommandExecutionRequestApprovalParams": { "properties": { "approvalId": { @@ -722,21 +805,6 @@ } ] }, - "SkillRequestApprovalParams": { - "properties": { - "itemId": { - "type": "string" - }, - "skillName": { - "type": "string" - } - }, - "required": [ - "itemId", - "skillName" - ], - "type": "object" - }, "ThreadId": { "type": "string" }, @@ -898,30 +966,6 @@ "title": "Item/tool/requestUserInputRequest", "type": "object" }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "skill/requestApproval" - ], - "title": "Skill/requestApprovalRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SkillRequestApprovalParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "Skill/requestApprovalRequest", - "type": "object" - }, { "description": "Execute a dynamic tool call on the client.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/SkillRequestApprovalResponse.json b/codex-rs/app-server-protocol/schema/json/SkillRequestApprovalResponse.json deleted file mode 100644 index 0bea163ccb..0000000000 --- a/codex-rs/app-server-protocol/schema/json/SkillRequestApprovalResponse.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "SkillApprovalDecision": { - "enum": [ - "approve", - "decline" - ], - "type": "string" - } - }, - "properties": { - "decision": { - "$ref": "#/definitions/SkillApprovalDecision" - } - }, - "required": [ - "decision" - ], - "title": "SkillRequestApprovalResponse", - "type": "object" -} \ No newline at end of file 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 4bceb1d98d..ddeee0ce73 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 @@ -5,7 +5,7 @@ "properties": { "read": { "items": { - "type": "string" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -14,7 +14,7 @@ }, "write": { "items": { - "type": "string" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -357,7 +357,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -382,7 +382,7 @@ "description": "NEW APIs", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -406,7 +406,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -430,7 +430,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -454,7 +454,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -478,7 +478,31 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "thread/unsubscribe" + ], + "title": "Thread/unsubscribeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadUnsubscribeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/unsubscribeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -502,7 +526,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -526,7 +550,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -550,7 +574,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -574,7 +598,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -598,7 +622,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -622,7 +646,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -646,7 +670,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -670,7 +694,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -694,7 +718,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -718,7 +742,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -742,7 +766,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -766,7 +790,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -790,7 +814,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -814,7 +838,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -838,7 +862,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -862,7 +886,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -886,7 +910,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -910,7 +934,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -934,7 +958,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -957,7 +981,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -981,7 +1005,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1005,7 +1029,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1029,7 +1053,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1053,7 +1077,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1076,7 +1100,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1099,7 +1123,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1124,7 +1148,7 @@ "description": "Execute a command (argv vector) under the server's sandbox.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1148,7 +1172,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1172,7 +1196,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1196,7 +1220,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1220,7 +1244,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1244,7 +1268,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1268,7 +1292,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1291,7 +1315,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1315,7 +1339,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -1358,7 +1382,7 @@ "thread_id": { "allOf": [ { - "$ref": "#/definitions/ThreadId" + "$ref": "#/definitions/v2/ThreadId" } ], "description": "Thread ID of the receiver/new agent." @@ -1396,7 +1420,7 @@ "thread_id": { "allOf": [ { - "$ref": "#/definitions/ThreadId" + "$ref": "#/definitions/v2/ThreadId" } ], "description": "Thread ID of the receiver/new agent." @@ -1418,7 +1442,7 @@ "type": "string" }, { - "description": "User approved the command and future identical commands should run without prompting.", + "description": "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", "enum": [ "acceptForSession" ], @@ -1640,50 +1664,6 @@ ], "type": "object" }, - "DynamicToolCallOutputContentItem": { - "oneOf": [ - { - "properties": { - "text": { - "type": "string" - }, - "type": { - "enum": [ - "inputText" - ], - "title": "InputTextDynamicToolCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "text", - "type" - ], - "title": "InputTextDynamicToolCallOutputContentItem", - "type": "object" - }, - { - "properties": { - "imageUrl": { - "type": "string" - }, - "type": { - "enum": [ - "inputImage" - ], - "title": "InputImageDynamicToolCallOutputContentItemType", - "type": "string" - } - }, - "required": [ - "imageUrl", - "type" - ], - "title": "InputImageDynamicToolCallOutputContentItem", - "type": "object" - } - ] - }, "DynamicToolCallParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -1716,7 +1696,7 @@ "properties": { "contentItems": { "items": { - "$ref": "#/definitions/DynamicToolCallOutputContentItem" + "$ref": "#/definitions/v2/DynamicToolCallOutputContentItem" }, "type": "array" }, @@ -2326,6 +2306,16 @@ ], "description": "How to sandbox commands executed in the system" }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, "session_id": { "$ref": "#/definitions/v2/ThreadId" }, @@ -2863,6 +2853,16 @@ "null" ] }, + "available_decisions": { + "description": "Ordered list of decisions the client may present for this prompt.\n\nWhen absent, clients should derive the legacy default set from the other fields on this request.", + "items": { + "$ref": "#/definitions/ReviewDecision" + }, + "type": [ + "array", + "null" + ] + }, "call_id": { "description": "Identifier for the associated command execution item.", "type": "string" @@ -3010,32 +3010,72 @@ }, { "properties": { - "item_id": { + "arguments": { + "description": "Dynamic tool call arguments." + }, + "call_id": { + "description": "Identifier for the corresponding DynamicToolCallRequest.", "type": "string" }, - "skill_name": { + "content_items": { + "description": "Dynamic tool response content items.", + "items": { + "$ref": "#/definitions/v2/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the dynamic tool call." + }, + "error": { + "description": "Optional error text when the tool call failed before producing a response.", + "type": [ + "string", + "null" + ] + }, + "success": { + "description": "Whether the tool call succeeded.", + "type": "boolean" + }, + "tool": { + "description": "Dynamic tool name.", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this dynamic tool call belongs to.", "type": "string" }, "type": { "enum": [ - "skill_request_approval" + "dynamic_tool_call_response" ], - "title": "SkillRequestApprovalEventMsgType", + "title": "DynamicToolCallResponseEventMsgType", "type": "string" } }, "required": [ - "item_id", - "skill_name", + "arguments", + "call_id", + "content_items", + "duration", + "success", + "tool", + "turn_id", "type" ], - "title": "SkillRequestApprovalEventMsg", + "title": "DynamicToolCallResponseEventMsg", "type": "object" }, { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "message": { "type": "string" @@ -4692,7 +4732,7 @@ "properties": { "read": { "items": { - "type": "string" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -4701,7 +4741,7 @@ }, "write": { "items": { - "type": "string" + "$ref": "#/definitions/v2/AbsolutePathBuf" }, "type": [ "array", @@ -4913,7 +4953,7 @@ "$ref": "#/definitions/JSONRPCErrorError" }, "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" } }, "required": [ @@ -4981,12 +5021,23 @@ "description": "A request that expects a response.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "type": "string" }, - "params": true + "params": true, + "trace": { + "anyOf": [ + { + "$ref": "#/definitions/W3cTraceContext" + }, + { + "type": "null" + } + ], + "description": "Optional W3C Trace Context for distributed tracing." + } }, "required": [ "id", @@ -5000,7 +5051,7 @@ "description": "A successful (non-error) response to a request.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "result": true }, @@ -5413,8 +5464,14 @@ { "additionalProperties": false, "properties": { - "SessionCreated": { + "SessionUpdated": { "properties": { + "instructions": { + "type": [ + "string", + "null" + ] + }, "session_id": { "type": "string" } @@ -5425,27 +5482,6 @@ "type": "object" } }, - "required": [ - "SessionCreated" - ], - "title": "SessionCreatedRealtimeEvent", - "type": "object" - }, - { - "additionalProperties": false, - "properties": { - "SessionUpdated": { - "properties": { - "backend_prompt": { - "type": [ - "string", - "null" - ] - } - }, - "type": "object" - } - }, "required": [ "SessionUpdated" ], @@ -5476,6 +5512,40 @@ "title": "ConversationItemAddedRealtimeEvent", "type": "object" }, + { + "additionalProperties": false, + "properties": { + "ConversationItemDone": { + "properties": { + "item_id": { + "type": "string" + } + }, + "required": [ + "item_id" + ], + "type": "object" + } + }, + "required": [ + "ConversationItemDone" + ], + "title": "ConversationItemDoneRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "HandoffRequested": { + "$ref": "#/definitions/RealtimeHandoffRequested" + } + }, + "required": [ + "HandoffRequested" + ], + "title": "HandoffRequestedRealtimeEvent", + "type": "object" + }, { "additionalProperties": false, "properties": { @@ -5491,6 +5561,47 @@ } ] }, + "RealtimeHandoffMessage": { + "properties": { + "role": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "role", + "text" + ], + "type": "object" + }, + "RealtimeHandoffRequested": { + "properties": { + "handoff_id": { + "type": "string" + }, + "input_transcript": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "messages": { + "items": { + "$ref": "#/definitions/RealtimeHandoffMessage" + }, + "type": "array" + } + }, + "required": [ + "handoff_id", + "input_transcript", + "item_id", + "messages" + ], + "type": "object" + }, "RejectConfig": { "properties": { "mcp_elicitations": { @@ -5514,6 +5625,7 @@ "type": "object" }, "RequestId": { + "$schema": "http://json-schema.org/draft-07/schema#", "anyOf": [ { "type": "string" @@ -5523,7 +5635,7 @@ "type": "integer" } ], - "description": "ID of a request, which can be either a string or an integer." + "title": "RequestId" }, "RequestUserInputQuestion": { "properties": { @@ -5656,7 +5768,7 @@ "type": "object" }, { - "description": "User has approved this command and wants to automatically approve any future identical instances (`command` and `cwd` match exactly) for the remainder of the session.", + "description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", "enum": [ "approved_for_session" ], @@ -5883,6 +5995,26 @@ "title": "Thread/unarchivedNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "thread/closed" + ], + "title": "Thread/closedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadClosedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/closedNotification", + "type": "object" + }, { "properties": { "method": { @@ -6144,6 +6276,26 @@ "title": "Item/fileChange/outputDeltaNotification", "type": "object" }, + { + "properties": { + "method": { + "enum": [ + "serverRequest/resolved" + ], + "title": "ServerRequest/resolvedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ServerRequestResolvedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ServerRequest/resolvedNotification", + "type": "object" + }, { "properties": { "method": { @@ -6597,7 +6749,7 @@ "description": "NEW APIs Sent when approval is requested for a specific command execution. This request is used for Turns started via turn/start.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6622,7 +6774,7 @@ "description": "Sent when approval is requested for a specific file change. This request is used for Turns started via turn/start.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6647,7 +6799,7 @@ "description": "EXPERIMENTAL - Request input from the user for a tool call.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6668,35 +6820,11 @@ "title": "Item/tool/requestUserInputRequest", "type": "object" }, - { - "properties": { - "id": { - "$ref": "#/definitions/RequestId" - }, - "method": { - "enum": [ - "skill/requestApproval" - ], - "title": "Skill/requestApprovalRequestMethod", - "type": "string" - }, - "params": { - "$ref": "#/definitions/SkillRequestApprovalParams" - } - }, - "required": [ - "id", - "method", - "params" - ], - "title": "Skill/requestApprovalRequest", - "type": "object" - }, { "description": "Execute a dynamic tool call on the client.", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6720,7 +6848,7 @@ { "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6745,7 +6873,7 @@ "description": "DEPRECATED APIs below Request to approve a patch. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6770,7 +6898,7 @@ "description": "Request to exec a command. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).", "properties": { "id": { - "$ref": "#/definitions/RequestId" + "$ref": "#/definitions/v2/RequestId" }, "method": { "enum": [ @@ -6813,43 +6941,6 @@ ], "type": "object" }, - "SkillApprovalDecision": { - "enum": [ - "approve", - "decline" - ], - "type": "string" - }, - "SkillRequestApprovalParams": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "itemId": { - "type": "string" - }, - "skillName": { - "type": "string" - } - }, - "required": [ - "itemId", - "skillName" - ], - "title": "SkillRequestApprovalParams", - "type": "object" - }, - "SkillRequestApprovalResponse": { - "$schema": "http://json-schema.org/draft-07/schema#", - "properties": { - "decision": { - "$ref": "#/definitions/SkillApprovalDecision" - } - }, - "required": [ - "decision" - ], - "title": "SkillRequestApprovalResponse", - "type": "object" - }, "StepStatus": { "enum": [ "pending", @@ -7040,7 +7131,7 @@ "properties": { "content": { "items": { - "$ref": "#/definitions/UserInput" + "$ref": "#/definitions/v2/UserInput" }, "type": "array" }, @@ -7078,7 +7169,7 @@ "phase": { "anyOf": [ { - "$ref": "#/definitions/MessagePhase" + "$ref": "#/definitions/v2/MessagePhase" }, { "type": "null" @@ -7163,7 +7254,7 @@ { "properties": { "action": { - "$ref": "#/definitions/WebSearchAction" + "$ref": "#/definitions/v2/WebSearchAction" }, "id": { "type": "string" @@ -7210,6 +7301,23 @@ } ] }, + "W3cTraceContext": { + "properties": { + "traceparent": { + "type": [ + "string", + "null" + ] + }, + "tracestate": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, "v2": { "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.", @@ -7309,6 +7417,16 @@ "type": "null" } ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/v2/PlanType" + }, + { + "type": "null" + } + ] } }, "title": "AccountUpdatedNotification", @@ -8086,14 +8204,8 @@ "type": "object" }, "CollaborationModeMask": { - "description": "A mask for collaboration mode settings, allowing partial updates. All fields except `name` are optional, enabling selective updates.", + "description": "EXPERIMENTAL - collaboration mode preset metadata for clients.", "properties": { - "developer_instructions": { - "type": [ - "string", - "null" - ] - }, "mode": { "anyOf": [ { @@ -8493,6 +8605,16 @@ } ] }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, "tools": { "anyOf": [ { @@ -9094,6 +9216,58 @@ "title": "DeprecationNoticeNotification", "type": "object" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "DynamicToolSpec": { "properties": { "description": { @@ -10190,6 +10364,16 @@ }, "Model": { "properties": { + "availabilityNux": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ModelAvailabilityNux" + }, + { + "type": "null" + } + ] + }, "defaultReasoningEffort": { "$ref": "#/definitions/v2/ReasoningEffort" }, @@ -10236,6 +10420,16 @@ "string", "null" ] + }, + "upgradeInfo": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ModelUpgradeInfo" + }, + { + "type": "null" + } + ] } }, "required": [ @@ -10250,6 +10444,17 @@ ], "type": "object" }, + "ModelAvailabilityNux": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, "ModelListParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -10338,6 +10543,35 @@ "title": "ModelReroutedNotification", "type": "object" }, + "ModelUpgradeInfo": { + "properties": { + "migrationMarkdown": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": "string" + }, + "modelLink": { + "type": [ + "string", + "null" + ] + }, + "upgradeCopy": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "model" + ], + "type": "object" + }, "NetworkAccess": { "enum": [ "restricted", @@ -10631,6 +10865,16 @@ } ] }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, "web_search": { "anyOf": [ { @@ -11015,6 +11259,17 @@ ], "type": "object" }, + "RequestId": { + "anyOf": [ + { + "type": "string" + }, + { + "format": "int64", + "type": "integer" + } + ] + }, "ResidencyRequirement": { "enum": [ "us" @@ -11347,7 +11602,7 @@ "type": "string" }, "output": { - "type": "string" + "$ref": "#/definitions/v2/FunctionCallOutputPayload" }, "type": { "enum": [ @@ -11754,6 +12009,29 @@ }, "type": "object" }, + "ServerRequestResolvedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "requestId": { + "$ref": "#/definitions/v2/RequestId" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "requestId", + "threadId" + ], + "title": "ServerRequestResolvedNotification", + "type": "object" + }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "SessionSource": { "oneOf": [ { @@ -12354,6 +12632,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -12423,6 +12705,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -12471,6 +12754,19 @@ "title": "ThreadArchivedNotification", "type": "object" }, + "ThreadClosedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadClosedNotification", + "type": "object" + }, "ThreadCompactStartParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -12551,6 +12847,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } @@ -12589,6 +12902,16 @@ "sandbox": { "$ref": "#/definitions/v2/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/v2/Thread" } @@ -12895,6 +13218,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/v2/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/v2/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { @@ -13481,6 +13857,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } @@ -13519,6 +13912,16 @@ "sandbox": { "$ref": "#/definitions/v2/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/v2/Thread" } @@ -13697,6 +14100,23 @@ "string", "null" ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] } }, "title": "ThreadStartParams", @@ -13730,6 +14150,16 @@ "sandbox": { "$ref": "#/definitions/v2/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/v2/Thread" } @@ -13932,6 +14362,40 @@ "title": "ThreadUnarchivedNotification", "type": "object" }, + "ThreadUnsubscribeParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnsubscribeParams", + "type": "object" + }, + "ThreadUnsubscribeResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/v2/ThreadUnsubscribeStatus" + } + }, + "required": [ + "status" + ], + "title": "ThreadUnsubscribeResponse", + "type": "object" + }, + "ThreadUnsubscribeStatus": { + "enum": [ + "notLoaded", + "notSubscribed", + "unsubscribed" + ], + "type": "string" + }, "TokenUsageBreakdown": { "properties": { "cachedInputTokens": { @@ -14263,6 +14727,24 @@ ], "description": "Override the sandbox policy for this turn and subsequent turns." }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/v2/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ], + "description": "Override the service tier for this turn and subsequent turns." + }, "summary": { "anyOf": [ { 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 new file mode 100644 index 0000000000..1bd5733364 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -0,0 +1,14093 @@ +{ + "$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" + }, + "Account": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "apiKey" + ], + "title": "ApiKeyAccountType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ApiKeyAccount", + "type": "object" + }, + { + "properties": { + "email": { + "type": "string" + }, + "planType": { + "$ref": "#/definitions/PlanType" + }, + "type": { + "enum": [ + "chatgpt" + ], + "title": "ChatgptAccountType", + "type": "string" + } + }, + "required": [ + "email", + "planType", + "type" + ], + "title": "ChatgptAccount", + "type": "object" + } + ] + }, + "AccountLoginCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, + "loginId": { + "type": [ + "string", + "null" + ] + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "success" + ], + "title": "AccountLoginCompletedNotification", + "type": "object" + }, + "AccountRateLimitsUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "rateLimits": { + "$ref": "#/definitions/RateLimitSnapshot" + } + }, + "required": [ + "rateLimits" + ], + "title": "AccountRateLimitsUpdatedNotification", + "type": "object" + }, + "AccountUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "authMode": { + "anyOf": [ + { + "$ref": "#/definitions/AuthMode" + }, + { + "type": "null" + } + ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/PlanType" + }, + { + "type": "null" + } + ] + } + }, + "title": "AccountUpdatedNotification", + "type": "object" + }, + "AgentMessageContent": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "Text" + ], + "title": "TextAgentMessageContentType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextAgentMessageContent", + "type": "object" + } + ] + }, + "AgentMessageDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "AgentMessageDeltaNotification", + "type": "object" + }, + "AgentStatus": { + "description": "Agent lifecycle status, derived from emitted events.", + "oneOf": [ + { + "description": "Agent is waiting for initialization.", + "enum": [ + "pending_init" + ], + "type": "string" + }, + { + "description": "Agent is currently running.", + "enum": [ + "running" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "Agent is done. Contains the final assistant message.", + "properties": { + "completed": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "completed" + ], + "title": "CompletedAgentStatus", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Agent encountered an error.", + "properties": { + "errored": { + "type": "string" + } + }, + "required": [ + "errored" + ], + "title": "ErroredAgentStatus", + "type": "object" + }, + { + "description": "Agent has been shutdown.", + "enum": [ + "shutdown" + ], + "type": "string" + }, + { + "description": "Agent is not found.", + "enum": [ + "not_found" + ], + "type": "string" + } + ] + }, + "AnalyticsConfig": { + "additionalProperties": true, + "properties": { + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "AppBranding": { + "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", + "properties": { + "category": { + "type": [ + "string", + "null" + ] + }, + "developer": { + "type": [ + "string", + "null" + ] + }, + "isDiscoverableApp": { + "type": "boolean" + }, + "privacyPolicy": { + "type": [ + "string", + "null" + ] + }, + "termsOfService": { + "type": [ + "string", + "null" + ] + }, + "website": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "isDiscoverableApp" + ], + "type": "object" + }, + "AppConfig": { + "properties": { + "default_tools_approval_mode": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolApproval" + }, + { + "type": "null" + } + ] + }, + "default_tools_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "destructive_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "type": [ + "boolean", + "null" + ] + }, + "tools": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolsConfig" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "AppInfo": { + "description": "EXPERIMENTAL - app metadata returned by app-list APIs.", + "properties": { + "appMetadata": { + "anyOf": [ + { + "$ref": "#/definitions/AppMetadata" + }, + { + "type": "null" + } + ] + }, + "branding": { + "anyOf": [ + { + "$ref": "#/definitions/AppBranding" + }, + { + "type": "null" + } + ] + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "distributionChannel": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string" + }, + "installUrl": { + "type": [ + "string", + "null" + ] + }, + "isAccessible": { + "default": false, + "type": "boolean" + }, + "isEnabled": { + "default": true, + "description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + "type": "boolean" + }, + "labels": { + "additionalProperties": { + "type": "string" + }, + "type": [ + "object", + "null" + ] + }, + "logoUrl": { + "type": [ + "string", + "null" + ] + }, + "logoUrlDark": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "AppListUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - notification emitted when the app list changes.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/AppInfo" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "AppListUpdatedNotification", + "type": "object" + }, + "AppMetadata": { + "properties": { + "categories": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "developer": { + "type": [ + "string", + "null" + ] + }, + "firstPartyRequiresInstall": { + "type": [ + "boolean", + "null" + ] + }, + "firstPartyType": { + "type": [ + "string", + "null" + ] + }, + "review": { + "anyOf": [ + { + "$ref": "#/definitions/AppReview" + }, + { + "type": "null" + } + ] + }, + "screenshots": { + "items": { + "$ref": "#/definitions/AppScreenshot" + }, + "type": [ + "array", + "null" + ] + }, + "seoDescription": { + "type": [ + "string", + "null" + ] + }, + "showInComposerWhenUnlinked": { + "type": [ + "boolean", + "null" + ] + }, + "subCategories": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "version": { + "type": [ + "string", + "null" + ] + }, + "versionId": { + "type": [ + "string", + "null" + ] + }, + "versionNotes": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "AppReview": { + "properties": { + "status": { + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "AppScreenshot": { + "properties": { + "fileId": { + "type": [ + "string", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "userPrompt": { + "type": "string" + } + }, + "required": [ + "userPrompt" + ], + "type": "object" + }, + "AppToolApproval": { + "enum": [ + "auto", + "prompt", + "approve" + ], + "type": "string" + }, + "AppToolConfig": { + "properties": { + "approval_mode": { + "anyOf": [ + { + "$ref": "#/definitions/AppToolApproval" + }, + { + "type": "null" + } + ] + }, + "enabled": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "AppToolsConfig": { + "type": "object" + }, + "AppsConfig": { + "properties": { + "_default": { + "anyOf": [ + { + "$ref": "#/definitions/AppsDefaultConfig" + }, + { + "type": "null" + } + ], + "default": null + } + }, + "type": "object" + }, + "AppsDefaultConfig": { + "properties": { + "destructive_enabled": { + "default": true, + "type": "boolean" + }, + "enabled": { + "default": true, + "type": "boolean" + }, + "open_world_enabled": { + "default": true, + "type": "boolean" + } + }, + "type": "object" + }, + "AppsListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - list available apps/connectors.", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "forceRefetch": { + "description": "When true, bypass app caches and fetch the latest data from sources.", + "type": "boolean" + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "threadId": { + "description": "Optional thread id used to evaluate app feature gating from that thread's config.", + "type": [ + "string", + "null" + ] + } + }, + "title": "AppsListParams", + "type": "object" + }, + "AppsListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - app list response.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/AppInfo" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "AppsListResponse", + "type": "object" + }, + "AskForApproval": { + "oneOf": [ + { + "enum": [ + "untrusted", + "on-failure", + "on-request", + "never" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "reject": { + "properties": { + "mcp_elicitations": { + "type": "boolean" + }, + "rules": { + "type": "boolean" + }, + "sandbox_approval": { + "type": "boolean" + } + }, + "required": [ + "mcp_elicitations", + "rules", + "sandbox_approval" + ], + "type": "object" + } + }, + "required": [ + "reject" + ], + "title": "RejectAskForApproval", + "type": "object" + } + ] + }, + "AuthMode": { + "description": "Authentication mode for OpenAI-backed providers.", + "oneOf": [ + { + "description": "OpenAI API key provided by the caller and stored by Codex.", + "enum": [ + "apikey" + ], + "type": "string" + }, + { + "description": "ChatGPT OAuth managed by Codex (tokens persisted and refreshed by Codex).", + "enum": [ + "chatgpt" + ], + "type": "string" + }, + { + "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE.\n\nChatGPT auth tokens are supplied by an external host app and are only stored in memory. Token refresh must be handled by the external host app.", + "enum": [ + "chatgptAuthTokens" + ], + "type": "string" + } + ] + }, + "ByteRange": { + "properties": { + "end": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "start": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "CallToolResult": { + "description": "The server's response to a tool call.", + "properties": { + "_meta": true, + "content": { + "items": true, + "type": "array" + }, + "isError": { + "type": [ + "boolean", + "null" + ] + }, + "structuredContent": true + }, + "required": [ + "content" + ], + "type": "object" + }, + "CancelLoginAccountParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "loginId": { + "type": "string" + } + }, + "required": [ + "loginId" + ], + "title": "CancelLoginAccountParams", + "type": "object" + }, + "CancelLoginAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/CancelLoginAccountStatus" + } + }, + "required": [ + "status" + ], + "title": "CancelLoginAccountResponse", + "type": "object" + }, + "CancelLoginAccountStatus": { + "enum": [ + "canceled", + "notFound" + ], + "type": "string" + }, + "ClientInfo": { + "properties": { + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "version": { + "type": "string" + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, + "ClientRequest": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Request from the client to the server.", + "oneOf": [ + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "initialize" + ], + "title": "InitializeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/InitializeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "InitializeRequest", + "type": "object" + }, + { + "description": "NEW APIs", + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/start" + ], + "title": "Thread/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/resume" + ], + "title": "Thread/resumeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadResumeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/resumeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/fork" + ], + "title": "Thread/forkRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadForkParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/forkRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/archive" + ], + "title": "Thread/archiveRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadArchiveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/archiveRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/unsubscribe" + ], + "title": "Thread/unsubscribeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnsubscribeParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/unsubscribeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/name/set" + ], + "title": "Thread/name/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadSetNameParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/name/setRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/unarchive" + ], + "title": "Thread/unarchiveRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnarchiveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/unarchiveRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/compact/start" + ], + "title": "Thread/compact/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadCompactStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/compact/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/rollback" + ], + "title": "Thread/rollbackRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRollbackParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/rollbackRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/list" + ], + "title": "Thread/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/loaded/list" + ], + "title": "Thread/loaded/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadLoadedListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/loaded/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/read" + ], + "title": "Thread/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/list" + ], + "title": "Skills/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/remote/list" + ], + "title": "Skills/remote/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsRemoteReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/remote/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/remote/export" + ], + "title": "Skills/remote/exportRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsRemoteWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/remote/exportRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "app/list" + ], + "title": "App/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AppsListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "App/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/config/write" + ], + "title": "Skills/config/writeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsConfigWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/config/writeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "turn/start" + ], + "title": "Turn/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Turn/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "turn/steer" + ], + "title": "Turn/steerRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnSteerParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Turn/steerRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "turn/interrupt" + ], + "title": "Turn/interruptRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnInterruptParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Turn/interruptRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "review/start" + ], + "title": "Review/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReviewStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Review/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "model/list" + ], + "title": "Model/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ModelListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Model/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "experimentalFeature/list" + ], + "title": "ExperimentalFeature/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ExperimentalFeatureListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "ExperimentalFeature/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "mcpServer/oauth/login" + ], + "title": "McpServer/oauth/loginRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/McpServerOauthLoginParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "McpServer/oauth/loginRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/mcpServer/reload" + ], + "title": "Config/mcpServer/reloadRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "Config/mcpServer/reloadRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "mcpServerStatus/list" + ], + "title": "McpServerStatus/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ListMcpServerStatusParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "McpServerStatus/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "windowsSandbox/setupStart" + ], + "title": "WindowsSandbox/setupStartRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WindowsSandboxSetupStartParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "WindowsSandbox/setupStartRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/login/start" + ], + "title": "Account/login/startRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/LoginAccountParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Account/login/startRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/login/cancel" + ], + "title": "Account/login/cancelRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CancelLoginAccountParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Account/login/cancelRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/logout" + ], + "title": "Account/logoutRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "Account/logoutRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/rateLimits/read" + ], + "title": "Account/rateLimits/readRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "Account/rateLimits/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "feedback/upload" + ], + "title": "Feedback/uploadRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FeedbackUploadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Feedback/uploadRequest", + "type": "object" + }, + { + "description": "Execute a command (argv vector) under the server's sandbox.", + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "command/exec" + ], + "title": "Command/execRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CommandExecParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Command/execRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/read" + ], + "title": "Config/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigReadParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Config/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "externalAgentConfig/detect" + ], + "title": "ExternalAgentConfig/detectRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ExternalAgentConfigDetectParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "ExternalAgentConfig/detectRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "externalAgentConfig/import" + ], + "title": "ExternalAgentConfig/importRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ExternalAgentConfigImportParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "ExternalAgentConfig/importRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/value/write" + ], + "title": "Config/value/writeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigValueWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Config/value/writeRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "config/batchWrite" + ], + "title": "Config/batchWriteRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigBatchWriteParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Config/batchWriteRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "configRequirements/read" + ], + "title": "ConfigRequirements/readRequestMethod", + "type": "string" + }, + "params": { + "type": "null" + } + }, + "required": [ + "id", + "method" + ], + "title": "ConfigRequirements/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "account/read" + ], + "title": "Account/readRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/GetAccountParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Account/readRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "fuzzyFileSearch" + ], + "title": "FuzzyFileSearchRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FuzzyFileSearchParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "FuzzyFileSearchRequest", + "type": "object" + } + ], + "title": "ClientRequest" + }, + "CodexErrorInfo": { + "description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", + "oneOf": [ + { + "enum": [ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "httpConnectionFailed": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "httpConnectionFailed" + ], + "title": "HttpConnectionFailedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Failed to connect to the response SSE stream.", + "properties": { + "responseStreamConnectionFailed": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseStreamConnectionFailed" + ], + "title": "ResponseStreamConnectionFailedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "The response SSE stream disconnected in the middle of a turn before completion.", + "properties": { + "responseStreamDisconnected": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseStreamDisconnected" + ], + "title": "ResponseStreamDisconnectedCodexErrorInfo", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Reached the retry limit for responses.", + "properties": { + "responseTooManyFailedAttempts": { + "properties": { + "httpStatusCode": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + } + }, + "required": [ + "responseTooManyFailedAttempts" + ], + "title": "ResponseTooManyFailedAttemptsCodexErrorInfo", + "type": "object" + } + ] + }, + "CollabAgentRef": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "thread_id" + ], + "type": "object" + }, + "CollabAgentState": { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/definitions/CollabAgentStatus" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "CollabAgentStatus": { + "enum": [ + "pendingInit", + "running", + "completed", + "errored", + "shutdown", + "notFound" + ], + "type": "string" + }, + "CollabAgentStatusEntry": { + "properties": { + "agent_nickname": { + "description": "Optional nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the agent." + }, + "thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver/new agent." + } + }, + "required": [ + "status", + "thread_id" + ], + "type": "object" + }, + "CollabAgentTool": { + "enum": [ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent" + ], + "type": "string" + }, + "CollabAgentToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "CollaborationMode": { + "description": "Collaboration mode for a Codex session.", + "properties": { + "mode": { + "$ref": "#/definitions/ModeKind" + }, + "settings": { + "$ref": "#/definitions/Settings" + } + }, + "required": [ + "mode", + "settings" + ], + "type": "object" + }, + "CollaborationModeMask": { + "description": "EXPERIMENTAL - collaboration mode preset metadata for clients.", + "properties": { + "mode": { + "anyOf": [ + { + "$ref": "#/definitions/ModeKind" + }, + { + "type": "null" + } + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "reasoning_effort": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "CommandAction": { + "oneOf": [ + { + "properties": { + "command": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "read" + ], + "title": "ReadCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "name", + "path", + "type" + ], + "title": "ReadCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "listFiles" + ], + "title": "ListFilesCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "ListFilesCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "SearchCommandAction", + "type": "object" + }, + { + "properties": { + "command": { + "type": "string" + }, + "type": { + "enum": [ + "unknown" + ], + "title": "UnknownCommandActionType", + "type": "string" + } + }, + "required": [ + "command", + "type" + ], + "title": "UnknownCommandAction", + "type": "object" + } + ] + }, + "CommandExecParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "command": { + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "sandboxPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxPolicy" + }, + { + "type": "null" + } + ] + }, + "timeoutMs": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "command" + ], + "title": "CommandExecParams", + "type": "object" + }, + "CommandExecResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "exitCode": { + "format": "int32", + "type": "integer" + }, + "stderr": { + "type": "string" + }, + "stdout": { + "type": "string" + } + }, + "required": [ + "exitCode", + "stderr", + "stdout" + ], + "title": "CommandExecResponse", + "type": "object" + }, + "CommandExecutionOutputDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "CommandExecutionOutputDeltaNotification", + "type": "object" + }, + "CommandExecutionStatus": { + "enum": [ + "inProgress", + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "Config": { + "additionalProperties": true, + "properties": { + "analytics": { + "anyOf": [ + { + "$ref": "#/definitions/AnalyticsConfig" + }, + { + "type": "null" + } + ] + }, + "approval_policy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "compact_prompt": { + "type": [ + "string", + "null" + ] + }, + "developer_instructions": { + "type": [ + "string", + "null" + ] + }, + "forced_chatgpt_workspace_id": { + "type": [ + "string", + "null" + ] + }, + "forced_login_method": { + "anyOf": [ + { + "$ref": "#/definitions/ForcedLoginMethod" + }, + { + "type": "null" + } + ] + }, + "instructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "model_auto_compact_token_limit": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "model_context_window": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "model_provider": { + "type": [ + "string", + "null" + ] + }, + "model_reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "model_reasoning_summary": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningSummary" + }, + { + "type": "null" + } + ] + }, + "model_verbosity": { + "anyOf": [ + { + "$ref": "#/definitions/Verbosity" + }, + { + "type": "null" + } + ] + }, + "profile": { + "type": [ + "string", + "null" + ] + }, + "profiles": { + "additionalProperties": { + "$ref": "#/definitions/ProfileV2" + }, + "default": {}, + "type": "object" + }, + "review_model": { + "type": [ + "string", + "null" + ] + }, + "sandbox_mode": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "sandbox_workspace_write": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxWorkspaceWrite" + }, + { + "type": "null" + } + ] + }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + "tools": { + "anyOf": [ + { + "$ref": "#/definitions/ToolsV2" + }, + { + "type": "null" + } + ] + }, + "web_search": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchMode" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "ConfigBatchWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "edits": { + "items": { + "$ref": "#/definitions/ConfigEdit" + }, + "type": "array" + }, + "expectedVersion": { + "type": [ + "string", + "null" + ] + }, + "filePath": { + "description": "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "edits" + ], + "title": "ConfigBatchWriteParams", + "type": "object" + }, + "ConfigEdit": { + "properties": { + "keyPath": { + "type": "string" + }, + "mergeStrategy": { + "$ref": "#/definitions/MergeStrategy" + }, + "value": true + }, + "required": [ + "keyPath", + "mergeStrategy", + "value" + ], + "type": "object" + }, + "ConfigLayer": { + "properties": { + "config": true, + "disabledReason": { + "type": [ + "string", + "null" + ] + }, + "name": { + "$ref": "#/definitions/ConfigLayerSource" + }, + "version": { + "type": "string" + } + }, + "required": [ + "config", + "name", + "version" + ], + "type": "object" + }, + "ConfigLayerMetadata": { + "properties": { + "name": { + "$ref": "#/definitions/ConfigLayerSource" + }, + "version": { + "type": "string" + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, + "ConfigLayerSource": { + "oneOf": [ + { + "description": "Managed preferences layer delivered by MDM (macOS only).", + "properties": { + "domain": { + "type": "string" + }, + "key": { + "type": "string" + }, + "type": { + "enum": [ + "mdm" + ], + "title": "MdmConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "domain", + "key", + "type" + ], + "title": "MdmConfigLayerSource", + "type": "object" + }, + { + "description": "Managed config layer from a file (usually `managed_config.toml`).", + "properties": { + "file": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "This is the path to the system config.toml file, though it is not guaranteed to exist." + }, + "type": { + "enum": [ + "system" + ], + "title": "SystemConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "file", + "type" + ], + "title": "SystemConfigLayerSource", + "type": "object" + }, + { + "description": "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory", + "properties": { + "file": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "This is the path to the user's config.toml file, though it is not guaranteed to exist." + }, + "type": { + "enum": [ + "user" + ], + "title": "UserConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "file", + "type" + ], + "title": "UserConfigLayerSource", + "type": "object" + }, + { + "description": "Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.", + "properties": { + "dotCodexFolder": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "project" + ], + "title": "ProjectConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "dotCodexFolder", + "type" + ], + "title": "ProjectConfigLayerSource", + "type": "object" + }, + { + "description": "Session-layer overrides supplied via `-c`/`--config`.", + "properties": { + "type": { + "enum": [ + "sessionFlags" + ], + "title": "SessionFlagsConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SessionFlagsConfigLayerSource", + "type": "object" + }, + { + "description": "`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a \"best effort\" while we phase out `managed_config.toml` in favor of `requirements.toml`.", + "properties": { + "file": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "legacyManagedConfigTomlFromFile" + ], + "title": "LegacyManagedConfigTomlFromFileConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "file", + "type" + ], + "title": "LegacyManagedConfigTomlFromFileConfigLayerSource", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "legacyManagedConfigTomlFromMdm" + ], + "title": "LegacyManagedConfigTomlFromMdmConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "LegacyManagedConfigTomlFromMdmConfigLayerSource", + "type": "object" + } + ] + }, + "ConfigReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cwd": { + "description": "Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).", + "type": [ + "string", + "null" + ] + }, + "includeLayers": { + "default": false, + "type": "boolean" + } + }, + "title": "ConfigReadParams", + "type": "object" + }, + "ConfigReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "config": { + "$ref": "#/definitions/Config" + }, + "layers": { + "items": { + "$ref": "#/definitions/ConfigLayer" + }, + "type": [ + "array", + "null" + ] + }, + "origins": { + "additionalProperties": { + "$ref": "#/definitions/ConfigLayerMetadata" + }, + "type": "object" + } + }, + "required": [ + "config", + "origins" + ], + "title": "ConfigReadResponse", + "type": "object" + }, + "ConfigRequirements": { + "properties": { + "allowedApprovalPolicies": { + "items": { + "$ref": "#/definitions/AskForApproval" + }, + "type": [ + "array", + "null" + ] + }, + "allowedSandboxModes": { + "items": { + "$ref": "#/definitions/SandboxMode" + }, + "type": [ + "array", + "null" + ] + }, + "allowedWebSearchModes": { + "items": { + "$ref": "#/definitions/WebSearchMode" + }, + "type": [ + "array", + "null" + ] + }, + "enforceResidency": { + "anyOf": [ + { + "$ref": "#/definitions/ResidencyRequirement" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "ConfigRequirementsReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "requirements": { + "anyOf": [ + { + "$ref": "#/definitions/ConfigRequirements" + }, + { + "type": "null" + } + ], + "description": "Null if no requirements are configured (e.g. no requirements.toml/MDM entries)." + } + }, + "title": "ConfigRequirementsReadResponse", + "type": "object" + }, + "ConfigValueWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "expectedVersion": { + "type": [ + "string", + "null" + ] + }, + "filePath": { + "description": "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + "type": [ + "string", + "null" + ] + }, + "keyPath": { + "type": "string" + }, + "mergeStrategy": { + "$ref": "#/definitions/MergeStrategy" + }, + "value": true + }, + "required": [ + "keyPath", + "mergeStrategy", + "value" + ], + "title": "ConfigValueWriteParams", + "type": "object" + }, + "ConfigWarningNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "details": { + "description": "Optional extra guidance or error details.", + "type": [ + "string", + "null" + ] + }, + "path": { + "description": "Optional path to the config file that triggered the warning.", + "type": [ + "string", + "null" + ] + }, + "range": { + "anyOf": [ + { + "$ref": "#/definitions/TextRange" + }, + { + "type": "null" + } + ], + "description": "Optional range for the error location inside the config file." + }, + "summary": { + "description": "Concise summary of the warning.", + "type": "string" + } + }, + "required": [ + "summary" + ], + "title": "ConfigWarningNotification", + "type": "object" + }, + "ConfigWriteResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "filePath": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "Canonical path to the config file that was written." + }, + "overriddenMetadata": { + "anyOf": [ + { + "$ref": "#/definitions/OverriddenMetadata" + }, + { + "type": "null" + } + ] + }, + "status": { + "$ref": "#/definitions/WriteStatus" + }, + "version": { + "type": "string" + } + }, + "required": [ + "filePath", + "status", + "version" + ], + "title": "ConfigWriteResponse", + "type": "object" + }, + "ContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "input_text" + ], + "title": "InputTextContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextContentItem", + "type": "object" + }, + { + "properties": { + "image_url": { + "type": "string" + }, + "type": { + "enum": [ + "input_image" + ], + "title": "InputImageContentItemType", + "type": "string" + } + }, + "required": [ + "image_url", + "type" + ], + "title": "InputImageContentItem", + "type": "object" + }, + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "output_text" + ], + "title": "OutputTextContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "OutputTextContentItem", + "type": "object" + } + ] + }, + "ContextCompactedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Deprecated: Use `ContextCompaction` item type instead.", + "properties": { + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "threadId", + "turnId" + ], + "title": "ContextCompactedNotification", + "type": "object" + }, + "CreditsSnapshot": { + "properties": { + "balance": { + "type": [ + "string", + "null" + ] + }, + "hasCredits": { + "type": "boolean" + }, + "unlimited": { + "type": "boolean" + } + }, + "required": [ + "hasCredits", + "unlimited" + ], + "type": "object" + }, + "CustomPrompt": { + "properties": { + "argument_hint": { + "type": [ + "string", + "null" + ] + }, + "content": { + "type": "string" + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "content", + "name", + "path" + ], + "type": "object" + }, + "DeprecationNoticeNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "details": { + "description": "Optional extra guidance, such as migration steps or rationale.", + "type": [ + "string", + "null" + ] + }, + "summary": { + "description": "Concise summary of what is deprecated.", + "type": "string" + } + }, + "required": [ + "summary" + ], + "title": "DeprecationNoticeNotification", + "type": "object" + }, + "Duration": { + "properties": { + "nanos": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "secs": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "nanos", + "secs" + ], + "type": "object" + }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "DynamicToolSpec": { + "properties": { + "description": { + "type": "string" + }, + "inputSchema": true, + "name": { + "type": "string" + } + }, + "required": [ + "description", + "inputSchema", + "name" + ], + "type": "object" + }, + "ErrorNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "$ref": "#/definitions/TurnError" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + }, + "willRetry": { + "type": "boolean" + } + }, + "required": [ + "error", + "threadId", + "turnId", + "willRetry" + ], + "title": "ErrorNotification", + "type": "object" + }, + "EventMsg": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Response event from the agent NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen.", + "oneOf": [ + { + "description": "Error while executing a submission", + "properties": { + "codex_error_info": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ], + "default": null + }, + "message": { + "type": "string" + }, + "type": { + "enum": [ + "error" + ], + "title": "ErrorEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "ErrorEventMsg", + "type": "object" + }, + { + "description": "Warning issued while processing a submission. Unlike `Error`, this indicates the turn continued but the user should still be notified.", + "properties": { + "message": { + "type": "string" + }, + "type": { + "enum": [ + "warning" + ], + "title": "WarningEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "WarningEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle start event.", + "properties": { + "session_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_started" + ], + "title": "RealtimeConversationStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationStartedEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation streaming payload event.", + "properties": { + "payload": { + "$ref": "#/definitions/RealtimeEvent" + }, + "type": { + "enum": [ + "realtime_conversation_realtime" + ], + "title": "RealtimeConversationRealtimeEventMsgType", + "type": "string" + } + }, + "required": [ + "payload", + "type" + ], + "title": "RealtimeConversationRealtimeEventMsg", + "type": "object" + }, + { + "description": "Realtime conversation lifecycle close event.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "realtime_conversation_closed" + ], + "title": "RealtimeConversationClosedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RealtimeConversationClosedEventMsg", + "type": "object" + }, + { + "description": "Model routing changed from the requested model to a different model.", + "properties": { + "from_model": { + "type": "string" + }, + "reason": { + "$ref": "#/definitions/ModelRerouteReason" + }, + "to_model": { + "type": "string" + }, + "type": { + "enum": [ + "model_reroute" + ], + "title": "ModelRerouteEventMsgType", + "type": "string" + } + }, + "required": [ + "from_model", + "reason", + "to_model", + "type" + ], + "title": "ModelRerouteEventMsg", + "type": "object" + }, + { + "description": "Conversation history was compacted (either automatically or manually).", + "properties": { + "type": { + "enum": [ + "context_compacted" + ], + "title": "ContextCompactedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ContextCompactedEventMsg", + "type": "object" + }, + { + "description": "Conversation history was rolled back by dropping the last N user turns.", + "properties": { + "num_turns": { + "description": "Number of user turns that were removed from context.", + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "type": { + "enum": [ + "thread_rolled_back" + ], + "title": "ThreadRolledBackEventMsgType", + "type": "string" + } + }, + "required": [ + "num_turns", + "type" + ], + "title": "ThreadRolledBackEventMsg", + "type": "object" + }, + { + "description": "Agent has started a turn. v1 wire format uses `task_started`; accept `turn_started` for v2 interop.", + "properties": { + "collaboration_mode_kind": { + "allOf": [ + { + "$ref": "#/definitions/ModeKind" + } + ], + "default": "default" + }, + "model_context_window": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "task_started" + ], + "title": "TaskStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "turn_id", + "type" + ], + "title": "TaskStartedEventMsg", + "type": "object" + }, + { + "description": "Agent has completed all actions. v1 wire format uses `task_complete`; accept `turn_complete` for v2 interop.", + "properties": { + "last_agent_message": { + "type": [ + "string", + "null" + ] + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "task_complete" + ], + "title": "TaskCompleteEventMsgType", + "type": "string" + } + }, + "required": [ + "turn_id", + "type" + ], + "title": "TaskCompleteEventMsg", + "type": "object" + }, + { + "description": "Usage update for the current session, including totals and last turn. Optional means unknown — UIs should not display when `None`.", + "properties": { + "info": { + "anyOf": [ + { + "$ref": "#/definitions/TokenUsageInfo" + }, + { + "type": "null" + } + ] + }, + "rate_limits": { + "anyOf": [ + { + "$ref": "#/definitions/RateLimitSnapshot" + }, + { + "type": "null" + } + ] + }, + "type": { + "enum": [ + "token_count" + ], + "title": "TokenCountEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "TokenCountEventMsg", + "type": "object" + }, + { + "description": "Agent text output message", + "properties": { + "message": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, + "type": { + "enum": [ + "agent_message" + ], + "title": "AgentMessageEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "AgentMessageEventMsg", + "type": "object" + }, + { + "description": "User/system input message (what was sent to the model)", + "properties": { + "images": { + "description": "Image URLs sourced from `UserInput::Image`. These are safe to replay in legacy UI history events and correspond to images sent to the model.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "local_images": { + "default": [], + "description": "Local file paths sourced from `UserInput::LocalImage`. These are kept so the UI can reattach images when editing history, and should not be sent to the model or treated as API-ready URLs.", + "items": { + "type": "string" + }, + "type": "array" + }, + "message": { + "type": "string" + }, + "text_elements": { + "default": [], + "description": "UI-defined spans within `message` used to render or persist special elements.", + "items": { + "$ref": "#/definitions/TextElement" + }, + "type": "array" + }, + "type": { + "enum": [ + "user_message" + ], + "title": "UserMessageEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "UserMessageEventMsg", + "type": "object" + }, + { + "description": "Agent text output delta message", + "properties": { + "delta": { + "type": "string" + }, + "type": { + "enum": [ + "agent_message_delta" + ], + "title": "AgentMessageDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "type" + ], + "title": "AgentMessageDeltaEventMsg", + "type": "object" + }, + { + "description": "Reasoning event from agent.", + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning" + ], + "title": "AgentReasoningEventMsgType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "AgentReasoningEventMsg", + "type": "object" + }, + { + "description": "Agent reasoning delta event from agent.", + "properties": { + "delta": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning_delta" + ], + "title": "AgentReasoningDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "type" + ], + "title": "AgentReasoningDeltaEventMsg", + "type": "object" + }, + { + "description": "Raw chain-of-thought from agent.", + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning_raw_content" + ], + "title": "AgentReasoningRawContentEventMsgType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "AgentReasoningRawContentEventMsg", + "type": "object" + }, + { + "description": "Agent reasoning content delta event from agent.", + "properties": { + "delta": { + "type": "string" + }, + "type": { + "enum": [ + "agent_reasoning_raw_content_delta" + ], + "title": "AgentReasoningRawContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "type" + ], + "title": "AgentReasoningRawContentDeltaEventMsg", + "type": "object" + }, + { + "description": "Signaled when the model begins a new reasoning summary section (e.g., a new titled block).", + "properties": { + "item_id": { + "default": "", + "type": "string" + }, + "summary_index": { + "default": 0, + "format": "int64", + "type": "integer" + }, + "type": { + "enum": [ + "agent_reasoning_section_break" + ], + "title": "AgentReasoningSectionBreakEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AgentReasoningSectionBreakEventMsg", + "type": "object" + }, + { + "description": "Ack the client's configure message.", + "properties": { + "approval_policy": { + "allOf": [ + { + "$ref": "#/definitions/AskForApproval" + } + ], + "description": "When to escalate for approval for execution" + }, + "cwd": { + "description": "Working directory that should be treated as the *root* of the session.", + "type": "string" + }, + "forked_from_id": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadId" + }, + { + "type": "null" + } + ] + }, + "history_entry_count": { + "description": "Current number of entries in the history log.", + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "history_log_id": { + "description": "Identifier of the history log file (inode on Unix, 0 otherwise).", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "initial_messages": { + "description": "Optional initial messages (as events) for resumed sessions. When present, UIs can use these to seed the history.", + "items": { + "$ref": "#/definitions/EventMsg" + }, + "type": [ + "array", + "null" + ] + }, + "model": { + "description": "Tell the client what model is being queried.", + "type": "string" + }, + "model_provider_id": { + "type": "string" + }, + "network_proxy": { + "anyOf": [ + { + "$ref": "#/definitions/SessionNetworkProxyRuntime" + }, + { + "type": "null" + } + ], + "description": "Runtime proxy bind addresses, when the managed proxy was started for this session." + }, + "reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ], + "description": "The effort the model is putting into reasoning about the user's request." + }, + "rollout_path": { + "description": "Path in which the rollout is stored. Can be `None` for ephemeral threads", + "type": [ + "string", + "null" + ] + }, + "sandbox_policy": { + "allOf": [ + { + "$ref": "#/definitions/SandboxPolicy" + } + ], + "description": "How to sandbox commands executed in the system" + }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + "session_id": { + "$ref": "#/definitions/ThreadId" + }, + "thread_name": { + "description": "Optional user-facing thread name (may be unset).", + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "session_configured" + ], + "title": "SessionConfiguredEventMsgType", + "type": "string" + } + }, + "required": [ + "approval_policy", + "cwd", + "history_entry_count", + "history_log_id", + "model", + "model_provider_id", + "sandbox_policy", + "session_id", + "type" + ], + "title": "SessionConfiguredEventMsg", + "type": "object" + }, + { + "description": "Updated session metadata (e.g., thread name changes).", + "properties": { + "thread_id": { + "$ref": "#/definitions/ThreadId" + }, + "thread_name": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "thread_name_updated" + ], + "title": "ThreadNameUpdatedEventMsgType", + "type": "string" + } + }, + "required": [ + "thread_id", + "type" + ], + "title": "ThreadNameUpdatedEventMsg", + "type": "object" + }, + { + "description": "Incremental MCP startup progress updates.", + "properties": { + "server": { + "description": "Server name being started.", + "type": "string" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/McpStartupStatus" + } + ], + "description": "Current startup status." + }, + "type": { + "enum": [ + "mcp_startup_update" + ], + "title": "McpStartupUpdateEventMsgType", + "type": "string" + } + }, + "required": [ + "server", + "status", + "type" + ], + "title": "McpStartupUpdateEventMsg", + "type": "object" + }, + { + "description": "Aggregate MCP startup completion summary.", + "properties": { + "cancelled": { + "items": { + "type": "string" + }, + "type": "array" + }, + "failed": { + "items": { + "$ref": "#/definitions/McpStartupFailure" + }, + "type": "array" + }, + "ready": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "mcp_startup_complete" + ], + "title": "McpStartupCompleteEventMsgType", + "type": "string" + } + }, + "required": [ + "cancelled", + "failed", + "ready", + "type" + ], + "title": "McpStartupCompleteEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Identifier so this can be paired with the McpToolCallEnd event.", + "type": "string" + }, + "invocation": { + "$ref": "#/definitions/McpInvocation" + }, + "type": { + "enum": [ + "mcp_tool_call_begin" + ], + "title": "McpToolCallBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "invocation", + "type" + ], + "title": "McpToolCallBeginEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Identifier for the corresponding McpToolCallBegin that finished.", + "type": "string" + }, + "duration": { + "$ref": "#/definitions/Duration" + }, + "invocation": { + "$ref": "#/definitions/McpInvocation" + }, + "result": { + "allOf": [ + { + "$ref": "#/definitions/Result_of_CallToolResult_or_String" + } + ], + "description": "Result of the tool call. Note this could be an error." + }, + "type": { + "enum": [ + "mcp_tool_call_end" + ], + "title": "McpToolCallEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "duration", + "invocation", + "result", + "type" + ], + "title": "McpToolCallEndEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "type": { + "enum": [ + "web_search_begin" + ], + "title": "WebSearchBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "type" + ], + "title": "WebSearchBeginEventMsg", + "type": "object" + }, + { + "properties": { + "action": { + "$ref": "#/definitions/WebSearchAction" + }, + "call_id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "web_search_end" + ], + "title": "WebSearchEndEventMsgType", + "type": "string" + } + }, + "required": [ + "action", + "call_id", + "query", + "type" + ], + "title": "WebSearchEndEventMsg", + "type": "object" + }, + { + "description": "Notification that the server is about to execute a command.", + "properties": { + "call_id": { + "description": "Identifier so this can be paired with the ExecCommandEnd event.", + "type": "string" + }, + "command": { + "description": "The command to be executed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory if not the default cwd for the agent.", + "type": "string" + }, + "interaction_input": { + "description": "Raw input sent to a unified exec session (if this is an interaction event).", + "type": [ + "string", + "null" + ] + }, + "parsed_cmd": { + "items": { + "$ref": "#/definitions/ParsedCommand" + }, + "type": "array" + }, + "process_id": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/ExecCommandSource" + } + ], + "default": "agent", + "description": "Where the command originated. Defaults to Agent for backward compatibility." + }, + "turn_id": { + "description": "Turn ID that this command belongs to.", + "type": "string" + }, + "type": { + "enum": [ + "exec_command_begin" + ], + "title": "ExecCommandBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "command", + "cwd", + "parsed_cmd", + "turn_id", + "type" + ], + "title": "ExecCommandBeginEventMsg", + "type": "object" + }, + { + "description": "Incremental chunk of output from a running command.", + "properties": { + "call_id": { + "description": "Identifier for the ExecCommandBegin that produced this chunk.", + "type": "string" + }, + "chunk": { + "description": "Raw bytes from the stream (may not be valid UTF-8).", + "type": "string" + }, + "stream": { + "allOf": [ + { + "$ref": "#/definitions/ExecOutputStream" + } + ], + "description": "Which stream produced this chunk." + }, + "type": { + "enum": [ + "exec_command_output_delta" + ], + "title": "ExecCommandOutputDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "chunk", + "stream", + "type" + ], + "title": "ExecCommandOutputDeltaEventMsg", + "type": "object" + }, + { + "description": "Terminal interaction for an in-progress command (stdin sent and stdout observed).", + "properties": { + "call_id": { + "description": "Identifier for the ExecCommandBegin that produced this chunk.", + "type": "string" + }, + "process_id": { + "description": "Process id associated with the running command.", + "type": "string" + }, + "stdin": { + "description": "Stdin sent to the running session.", + "type": "string" + }, + "type": { + "enum": [ + "terminal_interaction" + ], + "title": "TerminalInteractionEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "process_id", + "stdin", + "type" + ], + "title": "TerminalInteractionEventMsg", + "type": "object" + }, + { + "properties": { + "aggregated_output": { + "default": "", + "description": "Captured aggregated output", + "type": "string" + }, + "call_id": { + "description": "Identifier for the ExecCommandBegin that finished.", + "type": "string" + }, + "command": { + "description": "The command that was executed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory if not the default cwd for the agent.", + "type": "string" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the command execution." + }, + "exit_code": { + "description": "The command's exit code.", + "format": "int32", + "type": "integer" + }, + "formatted_output": { + "description": "Formatted output from the command, as seen by the model.", + "type": "string" + }, + "interaction_input": { + "description": "Raw input sent to a unified exec session (if this is an interaction event).", + "type": [ + "string", + "null" + ] + }, + "parsed_cmd": { + "items": { + "$ref": "#/definitions/ParsedCommand" + }, + "type": "array" + }, + "process_id": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/ExecCommandSource" + } + ], + "default": "agent", + "description": "Where the command originated. Defaults to Agent for backward compatibility." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/ExecCommandStatus" + } + ], + "description": "Completion status for this command execution." + }, + "stderr": { + "description": "Captured stderr", + "type": "string" + }, + "stdout": { + "description": "Captured stdout", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this command belongs to.", + "type": "string" + }, + "type": { + "enum": [ + "exec_command_end" + ], + "title": "ExecCommandEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "command", + "cwd", + "duration", + "exit_code", + "formatted_output", + "parsed_cmd", + "status", + "stderr", + "stdout", + "turn_id", + "type" + ], + "title": "ExecCommandEndEventMsg", + "type": "object" + }, + { + "description": "Notification that the agent attached a local image via the view_image tool.", + "properties": { + "call_id": { + "description": "Identifier for the originating tool call.", + "type": "string" + }, + "path": { + "description": "Local filesystem path provided to the tool.", + "type": "string" + }, + "type": { + "enum": [ + "view_image_tool_call" + ], + "title": "ViewImageToolCallEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "path", + "type" + ], + "title": "ViewImageToolCallEventMsg", + "type": "object" + }, + { + "properties": { + "additional_permissions": { + "anyOf": [ + { + "$ref": "#/definitions/PermissionProfile" + }, + { + "type": "null" + } + ], + "description": "Optional additional filesystem permissions requested for this command." + }, + "approval_id": { + "description": "Identifier for this specific approval callback.\n\nWhen absent, the approval is for the command item itself (`call_id`). This is present for subcommand approvals (via execve intercept).", + "type": [ + "string", + "null" + ] + }, + "available_decisions": { + "description": "Ordered list of decisions the client may present for this prompt.\n\nWhen absent, clients should derive the legacy default set from the other fields on this request.", + "items": { + "$ref": "#/definitions/ReviewDecision" + }, + "type": [ + "array", + "null" + ] + }, + "call_id": { + "description": "Identifier for the associated command execution item.", + "type": "string" + }, + "command": { + "description": "The command to be executed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory.", + "type": "string" + }, + "network_approval_context": { + "anyOf": [ + { + "$ref": "#/definitions/NetworkApprovalContext" + }, + { + "type": "null" + } + ], + "description": "Optional network context for a blocked request that can be approved." + }, + "parsed_cmd": { + "items": { + "$ref": "#/definitions/ParsedCommand" + }, + "type": "array" + }, + "proposed_execpolicy_amendment": { + "description": "Proposed execpolicy amendment that can be applied to allow future runs.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "proposed_network_policy_amendments": { + "description": "Proposed network policy amendments (for example allow/deny this host in future).", + "items": { + "$ref": "#/definitions/NetworkPolicyAmendment" + }, + "type": [ + "array", + "null" + ] + }, + "reason": { + "description": "Optional human-readable reason for the approval (e.g. retry without sandbox).", + "type": [ + "string", + "null" + ] + }, + "turn_id": { + "default": "", + "description": "Turn ID that this command belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "exec_approval_request" + ], + "title": "ExecApprovalRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "command", + "cwd", + "parsed_cmd", + "type" + ], + "title": "ExecApprovalRequestEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Responses API call id for the associated tool call, if available.", + "type": "string" + }, + "questions": { + "items": { + "$ref": "#/definitions/RequestUserInputQuestion" + }, + "type": "array" + }, + "turn_id": { + "default": "", + "description": "Turn ID that this request belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "request_user_input" + ], + "title": "RequestUserInputEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "questions", + "type" + ], + "title": "RequestUserInputEventMsg", + "type": "object" + }, + { + "properties": { + "arguments": true, + "callId": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "turnId": { + "type": "string" + }, + "type": { + "enum": [ + "dynamic_tool_call_request" + ], + "title": "DynamicToolCallRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "arguments", + "callId", + "tool", + "turnId", + "type" + ], + "title": "DynamicToolCallRequestEventMsg", + "type": "object" + }, + { + "properties": { + "arguments": { + "description": "Dynamic tool call arguments." + }, + "call_id": { + "description": "Identifier for the corresponding DynamicToolCallRequest.", + "type": "string" + }, + "content_items": { + "description": "Dynamic tool response content items.", + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": "array" + }, + "duration": { + "allOf": [ + { + "$ref": "#/definitions/Duration" + } + ], + "description": "The duration of the dynamic tool call." + }, + "error": { + "description": "Optional error text when the tool call failed before producing a response.", + "type": [ + "string", + "null" + ] + }, + "success": { + "description": "Whether the tool call succeeded.", + "type": "boolean" + }, + "tool": { + "description": "Dynamic tool name.", + "type": "string" + }, + "turn_id": { + "description": "Turn ID that this dynamic tool call belongs to.", + "type": "string" + }, + "type": { + "enum": [ + "dynamic_tool_call_response" + ], + "title": "DynamicToolCallResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "arguments", + "call_id", + "content_items", + "duration", + "success", + "tool", + "turn_id", + "type" + ], + "title": "DynamicToolCallResponseEventMsg", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "message": { + "type": "string" + }, + "server_name": { + "type": "string" + }, + "type": { + "enum": [ + "elicitation_request" + ], + "title": "ElicitationRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "id", + "message", + "server_name", + "type" + ], + "title": "ElicitationRequestEventMsg", + "type": "object" + }, + { + "properties": { + "call_id": { + "description": "Responses API call id for the associated patch apply call, if available.", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/definitions/FileChange" + }, + "type": "object" + }, + "grant_root": { + "description": "When set, the agent is asking the user to allow writes under this root for the remainder of the session.", + "type": [ + "string", + "null" + ] + }, + "reason": { + "description": "Optional explanatory reason (e.g. request for extra write access).", + "type": [ + "string", + "null" + ] + }, + "turn_id": { + "default": "", + "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility with older senders.", + "type": "string" + }, + "type": { + "enum": [ + "apply_patch_approval_request" + ], + "title": "ApplyPatchApprovalRequestEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "changes", + "type" + ], + "title": "ApplyPatchApprovalRequestEventMsg", + "type": "object" + }, + { + "description": "Notification advising the user that something they are using has been deprecated and should be phased out.", + "properties": { + "details": { + "description": "Optional extra guidance, such as migration steps or rationale.", + "type": [ + "string", + "null" + ] + }, + "summary": { + "description": "Concise summary of what is deprecated.", + "type": "string" + }, + "type": { + "enum": [ + "deprecation_notice" + ], + "title": "DeprecationNoticeEventMsgType", + "type": "string" + } + }, + "required": [ + "summary", + "type" + ], + "title": "DeprecationNoticeEventMsg", + "type": "object" + }, + { + "properties": { + "message": { + "type": "string" + }, + "type": { + "enum": [ + "background_event" + ], + "title": "BackgroundEventEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "BackgroundEventEventMsg", + "type": "object" + }, + { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "undo_started" + ], + "title": "UndoStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UndoStartedEventMsg", + "type": "object" + }, + { + "properties": { + "message": { + "type": [ + "string", + "null" + ] + }, + "success": { + "type": "boolean" + }, + "type": { + "enum": [ + "undo_completed" + ], + "title": "UndoCompletedEventMsgType", + "type": "string" + } + }, + "required": [ + "success", + "type" + ], + "title": "UndoCompletedEventMsg", + "type": "object" + }, + { + "description": "Notification that a model stream experienced an error or disconnect and the system is handling it (e.g., retrying with backoff).", + "properties": { + "additional_details": { + "default": null, + "description": "Optional details about the underlying stream failure (often the same human-readable message that is surfaced as the terminal error if retries are exhausted).", + "type": [ + "string", + "null" + ] + }, + "codex_error_info": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ], + "default": null + }, + "message": { + "type": "string" + }, + "type": { + "enum": [ + "stream_error" + ], + "title": "StreamErrorEventMsgType", + "type": "string" + } + }, + "required": [ + "message", + "type" + ], + "title": "StreamErrorEventMsg", + "type": "object" + }, + { + "description": "Notification that the agent is about to apply a code patch. Mirrors `ExecCommandBegin` so front‑ends can show progress indicators.", + "properties": { + "auto_approved": { + "description": "If true, there was no ApplyPatchApprovalRequest for this patch.", + "type": "boolean" + }, + "call_id": { + "description": "Identifier so this can be paired with the PatchApplyEnd event.", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/definitions/FileChange" + }, + "description": "The changes to be applied.", + "type": "object" + }, + "turn_id": { + "default": "", + "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "patch_apply_begin" + ], + "title": "PatchApplyBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "auto_approved", + "call_id", + "changes", + "type" + ], + "title": "PatchApplyBeginEventMsg", + "type": "object" + }, + { + "description": "Notification that a patch application has finished.", + "properties": { + "call_id": { + "description": "Identifier for the PatchApplyBegin that finished.", + "type": "string" + }, + "changes": { + "additionalProperties": { + "$ref": "#/definitions/FileChange" + }, + "default": {}, + "description": "The changes that were applied (mirrors PatchApplyBeginEvent::changes).", + "type": "object" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/PatchApplyStatus" + } + ], + "description": "Completion status for this patch application." + }, + "stderr": { + "description": "Captured stderr (parser errors, IO failures, etc.).", + "type": "string" + }, + "stdout": { + "description": "Captured stdout (summary printed by apply_patch).", + "type": "string" + }, + "success": { + "description": "Whether the patch was applied successfully.", + "type": "boolean" + }, + "turn_id": { + "default": "", + "description": "Turn ID that this patch belongs to. Uses `#[serde(default)]` for backwards compatibility.", + "type": "string" + }, + "type": { + "enum": [ + "patch_apply_end" + ], + "title": "PatchApplyEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "status", + "stderr", + "stdout", + "success", + "type" + ], + "title": "PatchApplyEndEventMsg", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "turn_diff" + ], + "title": "TurnDiffEventMsgType", + "type": "string" + }, + "unified_diff": { + "type": "string" + } + }, + "required": [ + "type", + "unified_diff" + ], + "title": "TurnDiffEventMsg", + "type": "object" + }, + { + "description": "Response to GetHistoryEntryRequest.", + "properties": { + "entry": { + "anyOf": [ + { + "$ref": "#/definitions/HistoryEntry" + }, + { + "type": "null" + } + ], + "description": "The entry at the requested offset, if available and parseable." + }, + "log_id": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, + "offset": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "type": { + "enum": [ + "get_history_entry_response" + ], + "title": "GetHistoryEntryResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "log_id", + "offset", + "type" + ], + "title": "GetHistoryEntryResponseEventMsg", + "type": "object" + }, + { + "description": "List of MCP tools available to the agent.", + "properties": { + "auth_statuses": { + "additionalProperties": { + "$ref": "#/definitions/McpAuthStatus" + }, + "description": "Authentication status for each configured MCP server.", + "type": "object" + }, + "resource_templates": { + "additionalProperties": { + "items": { + "$ref": "#/definitions/ResourceTemplate" + }, + "type": "array" + }, + "description": "Known resource templates grouped by server name.", + "type": "object" + }, + "resources": { + "additionalProperties": { + "items": { + "$ref": "#/definitions/Resource" + }, + "type": "array" + }, + "description": "Known resources grouped by server name.", + "type": "object" + }, + "tools": { + "additionalProperties": { + "$ref": "#/definitions/Tool" + }, + "description": "Fully qualified tool name -> tool definition.", + "type": "object" + }, + "type": { + "enum": [ + "mcp_list_tools_response" + ], + "title": "McpListToolsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "auth_statuses", + "resource_templates", + "resources", + "tools", + "type" + ], + "title": "McpListToolsResponseEventMsg", + "type": "object" + }, + { + "description": "List of custom prompts available to the agent.", + "properties": { + "custom_prompts": { + "items": { + "$ref": "#/definitions/CustomPrompt" + }, + "type": "array" + }, + "type": { + "enum": [ + "list_custom_prompts_response" + ], + "title": "ListCustomPromptsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "custom_prompts", + "type" + ], + "title": "ListCustomPromptsResponseEventMsg", + "type": "object" + }, + { + "description": "List of skills available to the agent.", + "properties": { + "skills": { + "items": { + "$ref": "#/definitions/SkillsListEntry" + }, + "type": "array" + }, + "type": { + "enum": [ + "list_skills_response" + ], + "title": "ListSkillsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "skills", + "type" + ], + "title": "ListSkillsResponseEventMsg", + "type": "object" + }, + { + "description": "List of remote skills available to the agent.", + "properties": { + "skills": { + "items": { + "$ref": "#/definitions/RemoteSkillSummary" + }, + "type": "array" + }, + "type": { + "enum": [ + "list_remote_skills_response" + ], + "title": "ListRemoteSkillsResponseEventMsgType", + "type": "string" + } + }, + "required": [ + "skills", + "type" + ], + "title": "ListRemoteSkillsResponseEventMsg", + "type": "object" + }, + { + "description": "Remote skill downloaded to local cache.", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "remote_skill_downloaded" + ], + "title": "RemoteSkillDownloadedEventMsgType", + "type": "string" + } + }, + "required": [ + "id", + "name", + "path", + "type" + ], + "title": "RemoteSkillDownloadedEventMsg", + "type": "object" + }, + { + "description": "Notification that skill data may have been updated and clients may want to reload.", + "properties": { + "type": { + "enum": [ + "skills_update_available" + ], + "title": "SkillsUpdateAvailableEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SkillsUpdateAvailableEventMsg", + "type": "object" + }, + { + "properties": { + "explanation": { + "default": null, + "description": "Arguments for the `update_plan` todo/checklist tool (not plan mode).", + "type": [ + "string", + "null" + ] + }, + "plan": { + "items": { + "$ref": "#/definitions/PlanItemArg" + }, + "type": "array" + }, + "type": { + "enum": [ + "plan_update" + ], + "title": "PlanUpdateEventMsgType", + "type": "string" + } + }, + "required": [ + "plan", + "type" + ], + "title": "PlanUpdateEventMsg", + "type": "object" + }, + { + "properties": { + "reason": { + "$ref": "#/definitions/TurnAbortReason" + }, + "turn_id": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "turn_aborted" + ], + "title": "TurnAbortedEventMsgType", + "type": "string" + } + }, + "required": [ + "reason", + "type" + ], + "title": "TurnAbortedEventMsg", + "type": "object" + }, + { + "description": "Notification that the agent is shutting down.", + "properties": { + "type": { + "enum": [ + "shutdown_complete" + ], + "title": "ShutdownCompleteEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ShutdownCompleteEventMsg", + "type": "object" + }, + { + "description": "Entered review mode.", + "properties": { + "target": { + "$ref": "#/definitions/ReviewTarget" + }, + "type": { + "enum": [ + "entered_review_mode" + ], + "title": "EnteredReviewModeEventMsgType", + "type": "string" + }, + "user_facing_hint": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "target", + "type" + ], + "title": "EnteredReviewModeEventMsg", + "type": "object" + }, + { + "description": "Exited review mode with an optional final result to apply.", + "properties": { + "review_output": { + "anyOf": [ + { + "$ref": "#/definitions/ReviewOutputEvent" + }, + { + "type": "null" + } + ] + }, + "type": { + "enum": [ + "exited_review_mode" + ], + "title": "ExitedReviewModeEventMsgType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ExitedReviewModeEventMsg", + "type": "object" + }, + { + "properties": { + "item": { + "$ref": "#/definitions/ResponseItem" + }, + "type": { + "enum": [ + "raw_response_item" + ], + "title": "RawResponseItemEventMsgType", + "type": "string" + } + }, + "required": [ + "item", + "type" + ], + "title": "RawResponseItemEventMsg", + "type": "object" + }, + { + "properties": { + "item": { + "$ref": "#/definitions/TurnItem" + }, + "thread_id": { + "$ref": "#/definitions/ThreadId" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "item_started" + ], + "title": "ItemStartedEventMsgType", + "type": "string" + } + }, + "required": [ + "item", + "thread_id", + "turn_id", + "type" + ], + "title": "ItemStartedEventMsg", + "type": "object" + }, + { + "properties": { + "item": { + "$ref": "#/definitions/TurnItem" + }, + "thread_id": { + "$ref": "#/definitions/ThreadId" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "item_completed" + ], + "title": "ItemCompletedEventMsgType", + "type": "string" + } + }, + "required": [ + "item", + "thread_id", + "turn_id", + "type" + ], + "title": "ItemCompletedEventMsg", + "type": "object" + }, + { + "properties": { + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "agent_message_content_delta" + ], + "title": "AgentMessageContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "AgentMessageContentDeltaEventMsg", + "type": "object" + }, + { + "properties": { + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "plan_delta" + ], + "title": "PlanDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "PlanDeltaEventMsg", + "type": "object" + }, + { + "properties": { + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "summary_index": { + "default": 0, + "format": "int64", + "type": "integer" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "reasoning_content_delta" + ], + "title": "ReasoningContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "ReasoningContentDeltaEventMsg", + "type": "object" + }, + { + "properties": { + "content_index": { + "default": 0, + "format": "int64", + "type": "integer" + }, + "delta": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "thread_id": { + "type": "string" + }, + "turn_id": { + "type": "string" + }, + "type": { + "enum": [ + "reasoning_raw_content_delta" + ], + "title": "ReasoningRawContentDeltaEventMsgType", + "type": "string" + } + }, + "required": [ + "delta", + "item_id", + "thread_id", + "turn_id", + "type" + ], + "title": "ReasoningRawContentDeltaEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent spawn begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_agent_spawn_begin" + ], + "title": "CollabAgentSpawnBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "sender_thread_id", + "type" + ], + "title": "CollabAgentSpawnBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent spawn end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "new_agent_nickname": { + "description": "Optional nickname assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_agent_role": { + "description": "Optional role assigned to the new agent.", + "type": [ + "string", + "null" + ] + }, + "new_thread_id": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadId" + }, + { + "type": "null" + } + ], + "description": "Thread ID of the newly spawned agent, if it was created." + }, + "prompt": { + "description": "Initial prompt sent to the agent. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the new agent reported to the sender agent." + }, + "type": { + "enum": [ + "collab_agent_spawn_end" + ], + "title": "CollabAgentSpawnEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabAgentSpawnEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent interaction begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_agent_interaction_begin" + ], + "title": "CollabAgentInteractionBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "receiver_thread_id", + "sender_thread_id", + "type" + ], + "title": "CollabAgentInteractionBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: agent interaction end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt sent from the sender to the receiver. Can be empty to prevent CoT leaking at the beginning.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the receiver agent reported to the sender agent." + }, + "type": { + "enum": [ + "collab_agent_interaction_end" + ], + "title": "CollabAgentInteractionEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "prompt", + "receiver_thread_id", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabAgentInteractionEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: waiting begin.", + "properties": { + "call_id": { + "description": "ID of the waiting call.", + "type": "string" + }, + "receiver_agents": { + "description": "Optional nicknames/roles for receivers.", + "items": { + "$ref": "#/definitions/CollabAgentRef" + }, + "type": "array" + }, + "receiver_thread_ids": { + "description": "Thread ID of the receivers.", + "items": { + "$ref": "#/definitions/ThreadId" + }, + "type": "array" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_waiting_begin" + ], + "title": "CollabWaitingBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_ids", + "sender_thread_id", + "type" + ], + "title": "CollabWaitingBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: waiting end.", + "properties": { + "agent_statuses": { + "description": "Optional receiver metadata paired with final statuses.", + "items": { + "$ref": "#/definitions/CollabAgentStatusEntry" + }, + "type": "array" + }, + "call_id": { + "description": "ID of the waiting call.", + "type": "string" + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "statuses": { + "additionalProperties": { + "$ref": "#/definitions/AgentStatus" + }, + "description": "Last known status of the receiver agents reported to the sender agent.", + "type": "object" + }, + "type": { + "enum": [ + "collab_waiting_end" + ], + "title": "CollabWaitingEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "sender_thread_id", + "statuses", + "type" + ], + "title": "CollabWaitingEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: close begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_close_begin" + ], + "title": "CollabCloseBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "type" + ], + "title": "CollabCloseBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: close end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the receiver agent reported to the sender agent before the close." + }, + "type": { + "enum": [ + "collab_close_end" + ], + "title": "CollabCloseEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabCloseEndEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: resume begin.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "type": { + "enum": [ + "collab_resume_begin" + ], + "title": "CollabResumeBeginEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "type" + ], + "title": "CollabResumeBeginEventMsg", + "type": "object" + }, + { + "description": "Collab interaction: resume end.", + "properties": { + "call_id": { + "description": "Identifier for the collab tool call.", + "type": "string" + }, + "receiver_agent_nickname": { + "description": "Optional nickname assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_agent_role": { + "description": "Optional role assigned to the receiver agent.", + "type": [ + "string", + "null" + ] + }, + "receiver_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the receiver." + }, + "sender_thread_id": { + "allOf": [ + { + "$ref": "#/definitions/ThreadId" + } + ], + "description": "Thread ID of the sender." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/AgentStatus" + } + ], + "description": "Last known status of the receiver agent reported to the sender agent after resume." + }, + "type": { + "enum": [ + "collab_resume_end" + ], + "title": "CollabResumeEndEventMsgType", + "type": "string" + } + }, + "required": [ + "call_id", + "receiver_thread_id", + "sender_thread_id", + "status", + "type" + ], + "title": "CollabResumeEndEventMsg", + "type": "object" + } + ], + "title": "EventMsg" + }, + "ExecCommandSource": { + "enum": [ + "agent", + "user_shell", + "unified_exec_startup", + "unified_exec_interaction" + ], + "type": "string" + }, + "ExecCommandStatus": { + "enum": [ + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "ExecOutputStream": { + "enum": [ + "stdout", + "stderr" + ], + "type": "string" + }, + "ExperimentalFeature": { + "properties": { + "announcement": { + "description": "Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.", + "type": [ + "string", + "null" + ] + }, + "defaultEnabled": { + "description": "Whether this feature is enabled by default.", + "type": "boolean" + }, + "description": { + "description": "Short summary describing what the feature does. Null when this feature is not in beta.", + "type": [ + "string", + "null" + ] + }, + "displayName": { + "description": "User-facing display name shown in the experimental features UI. Null when this feature is not in beta.", + "type": [ + "string", + "null" + ] + }, + "enabled": { + "description": "Whether this feature is currently enabled in the loaded config.", + "type": "boolean" + }, + "name": { + "description": "Stable key used in config.toml and CLI flag toggles.", + "type": "string" + }, + "stage": { + "allOf": [ + { + "$ref": "#/definitions/ExperimentalFeatureStage" + } + ], + "description": "Lifecycle stage of this feature flag." + } + }, + "required": [ + "defaultEnabled", + "enabled", + "name", + "stage" + ], + "type": "object" + }, + "ExperimentalFeatureListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ExperimentalFeatureListParams", + "type": "object" + }, + "ExperimentalFeatureListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/ExperimentalFeature" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ExperimentalFeatureListResponse", + "type": "object" + }, + "ExperimentalFeatureStage": { + "oneOf": [ + { + "description": "Feature is available for user testing and feedback.", + "enum": [ + "beta" + ], + "type": "string" + }, + { + "description": "Feature is still being built and not ready for broad use.", + "enum": [ + "underDevelopment" + ], + "type": "string" + }, + { + "description": "Feature is production-ready.", + "enum": [ + "stable" + ], + "type": "string" + }, + { + "description": "Feature is deprecated and should be avoided.", + "enum": [ + "deprecated" + ], + "type": "string" + }, + { + "description": "Feature flag is retained only for backwards compatibility.", + "enum": [ + "removed" + ], + "type": "string" + } + ] + }, + "ExternalAgentConfigDetectParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cwds": { + "description": "Zero or more working directories to include for repo-scoped detection.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "includeHome": { + "description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).", + "type": "boolean" + } + }, + "title": "ExternalAgentConfigDetectParams", + "type": "object" + }, + "ExternalAgentConfigDetectResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "items": { + "items": { + "$ref": "#/definitions/ExternalAgentConfigMigrationItem" + }, + "type": "array" + } + }, + "required": [ + "items" + ], + "title": "ExternalAgentConfigDetectResponse", + "type": "object" + }, + "ExternalAgentConfigImportParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "migrationItems": { + "items": { + "$ref": "#/definitions/ExternalAgentConfigMigrationItem" + }, + "type": "array" + } + }, + "required": [ + "migrationItems" + ], + "title": "ExternalAgentConfigImportParams", + "type": "object" + }, + "ExternalAgentConfigImportResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ExternalAgentConfigImportResponse", + "type": "object" + }, + "ExternalAgentConfigMigrationItem": { + "properties": { + "cwd": { + "description": "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + "type": [ + "string", + "null" + ] + }, + "description": { + "type": "string" + }, + "itemType": { + "$ref": "#/definitions/ExternalAgentConfigMigrationItemType" + } + }, + "required": [ + "description", + "itemType" + ], + "type": "object" + }, + "ExternalAgentConfigMigrationItemType": { + "enum": [ + "AGENTS_MD", + "CONFIG", + "SKILLS", + "MCP_SERVER_CONFIG" + ], + "type": "string" + }, + "FeedbackUploadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "classification": { + "type": "string" + }, + "extraLogFiles": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "includeLogs": { + "type": "boolean" + }, + "reason": { + "type": [ + "string", + "null" + ] + }, + "threadId": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "classification", + "includeLogs" + ], + "title": "FeedbackUploadParams", + "type": "object" + }, + "FeedbackUploadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "FeedbackUploadResponse", + "type": "object" + }, + "FileChange": { + "oneOf": [ + { + "properties": { + "content": { + "type": "string" + }, + "type": { + "enum": [ + "add" + ], + "title": "AddFileChangeType", + "type": "string" + } + }, + "required": [ + "content", + "type" + ], + "title": "AddFileChange", + "type": "object" + }, + { + "properties": { + "content": { + "type": "string" + }, + "type": { + "enum": [ + "delete" + ], + "title": "DeleteFileChangeType", + "type": "string" + } + }, + "required": [ + "content", + "type" + ], + "title": "DeleteFileChange", + "type": "object" + }, + { + "properties": { + "move_path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "update" + ], + "title": "UpdateFileChangeType", + "type": "string" + }, + "unified_diff": { + "type": "string" + } + }, + "required": [ + "type", + "unified_diff" + ], + "title": "UpdateFileChange", + "type": "object" + } + ] + }, + "FileChangeOutputDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "FileChangeOutputDeltaNotification", + "type": "object" + }, + "FileSystemPermissions": { + "properties": { + "read": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": [ + "array", + "null" + ] + }, + "write": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, + "FileUpdateChange": { + "properties": { + "diff": { + "type": "string" + }, + "kind": { + "$ref": "#/definitions/PatchChangeKind" + }, + "path": { + "type": "string" + } + }, + "required": [ + "diff", + "kind", + "path" + ], + "type": "object" + }, + "ForcedLoginMethod": { + "enum": [ + "chatgpt", + "api" + ], + "type": "string" + }, + "FunctionCallOutputBody": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "$ref": "#/definitions/FunctionCallOutputContentItem" + }, + "type": "array" + } + ] + }, + "FunctionCallOutputContentItem": { + "description": "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "input_text" + ], + "title": "InputTextFunctionCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextFunctionCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "image_url": { + "type": "string" + }, + "type": { + "enum": [ + "input_image" + ], + "title": "InputImageFunctionCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "image_url", + "type" + ], + "title": "InputImageFunctionCallOutputContentItem", + "type": "object" + } + ] + }, + "FunctionCallOutputPayload": { + "description": "The payload we send back to OpenAI when reporting a tool call result.\n\n`body` serializes directly as the wire value for `function_call_output.output`. `success` remains internal metadata for downstream handling.", + "properties": { + "body": { + "$ref": "#/definitions/FunctionCallOutputBody" + }, + "success": { + "type": [ + "boolean", + "null" + ] + } + }, + "required": [ + "body" + ], + "type": "object" + }, + "FuzzyFileSearchParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cancellationToken": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": "string" + }, + "roots": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "query", + "roots" + ], + "title": "FuzzyFileSearchParams", + "type": "object" + }, + "FuzzyFileSearchResult": { + "description": "Superset of [`codex_file_search::FileMatch`]", + "properties": { + "file_name": { + "type": "string" + }, + "indices": { + "items": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "type": [ + "array", + "null" + ] + }, + "path": { + "type": "string" + }, + "root": { + "type": "string" + }, + "score": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "file_name", + "path", + "root", + "score" + ], + "type": "object" + }, + "FuzzyFileSearchSessionCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "sessionId": { + "type": "string" + } + }, + "required": [ + "sessionId" + ], + "title": "FuzzyFileSearchSessionCompletedNotification", + "type": "object" + }, + "FuzzyFileSearchSessionUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "files": { + "items": { + "$ref": "#/definitions/FuzzyFileSearchResult" + }, + "type": "array" + }, + "query": { + "type": "string" + }, + "sessionId": { + "type": "string" + } + }, + "required": [ + "files", + "query", + "sessionId" + ], + "title": "FuzzyFileSearchSessionUpdatedNotification", + "type": "object" + }, + "GetAccountParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "refreshToken": { + "default": false, + "description": "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.", + "type": "boolean" + } + }, + "title": "GetAccountParams", + "type": "object" + }, + "GetAccountRateLimitsResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "rateLimits": { + "allOf": [ + { + "$ref": "#/definitions/RateLimitSnapshot" + } + ], + "description": "Backward-compatible single-bucket view; mirrors the historical payload." + }, + "rateLimitsByLimitId": { + "additionalProperties": { + "$ref": "#/definitions/RateLimitSnapshot" + }, + "description": "Multi-bucket view keyed by metered `limit_id` (for example, `codex`).", + "type": [ + "object", + "null" + ] + } + }, + "required": [ + "rateLimits" + ], + "title": "GetAccountRateLimitsResponse", + "type": "object" + }, + "GetAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "account": { + "anyOf": [ + { + "$ref": "#/definitions/Account" + }, + { + "type": "null" + } + ] + }, + "requiresOpenaiAuth": { + "type": "boolean" + } + }, + "required": [ + "requiresOpenaiAuth" + ], + "title": "GetAccountResponse", + "type": "object" + }, + "GhostCommit": { + "description": "Details of a ghost commit created from a repository state.", + "properties": { + "id": { + "type": "string" + }, + "parent": { + "type": [ + "string", + "null" + ] + }, + "preexisting_untracked_dirs": { + "items": { + "type": "string" + }, + "type": "array" + }, + "preexisting_untracked_files": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "id", + "preexisting_untracked_dirs", + "preexisting_untracked_files" + ], + "type": "object" + }, + "GitInfo": { + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "originUrl": { + "type": [ + "string", + "null" + ] + }, + "sha": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "HazelnutScope": { + "enum": [ + "example", + "workspace-shared", + "all-shared", + "personal" + ], + "type": "string" + }, + "HistoryEntry": { + "properties": { + "conversation_id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "ts": { + "format": "uint64", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "conversation_id", + "text", + "ts" + ], + "type": "object" + }, + "InitializeCapabilities": { + "description": "Client-declared capabilities negotiated during initialize.", + "properties": { + "experimentalApi": { + "default": false, + "description": "Opt into receiving experimental API methods and fields.", + "type": "boolean" + }, + "optOutNotificationMethods": { + "description": "Exact notification method names that should be suppressed for this connection (for example `codex/event/session_configured`).", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + } + }, + "type": "object" + }, + "InitializeParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "capabilities": { + "anyOf": [ + { + "$ref": "#/definitions/InitializeCapabilities" + }, + { + "type": "null" + } + ] + }, + "clientInfo": { + "$ref": "#/definitions/ClientInfo" + } + }, + "required": [ + "clientInfo" + ], + "title": "InitializeParams", + "type": "object" + }, + "InputModality": { + "description": "Canonical user-input modality tags advertised by a model.", + "oneOf": [ + { + "description": "Plain text turns and tool payloads.", + "enum": [ + "text" + ], + "type": "string" + }, + { + "description": "Image attachments included in user turns.", + "enum": [ + "image" + ], + "type": "string" + } + ] + }, + "ItemCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "item": { + "$ref": "#/definitions/ThreadItem" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId", + "turnId" + ], + "title": "ItemCompletedNotification", + "type": "object" + }, + "ItemStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "item": { + "$ref": "#/definitions/ThreadItem" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId", + "turnId" + ], + "title": "ItemStartedNotification", + "type": "object" + }, + "ListMcpServerStatusParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a server-defined value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ListMcpServerStatusParams", + "type": "object" + }, + "ListMcpServerStatusResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/McpServerStatus" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ListMcpServerStatusResponse", + "type": "object" + }, + "LocalShellAction": { + "oneOf": [ + { + "properties": { + "command": { + "items": { + "type": "string" + }, + "type": "array" + }, + "env": { + "additionalProperties": { + "type": "string" + }, + "type": [ + "object", + "null" + ] + }, + "timeout_ms": { + "format": "uint64", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "exec" + ], + "title": "ExecLocalShellActionType", + "type": "string" + }, + "user": { + "type": [ + "string", + "null" + ] + }, + "working_directory": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "command", + "type" + ], + "title": "ExecLocalShellAction", + "type": "object" + } + ] + }, + "LocalShellStatus": { + "enum": [ + "completed", + "in_progress", + "incomplete" + ], + "type": "string" + }, + "LoginAccountParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "oneOf": [ + { + "properties": { + "apiKey": { + "type": "string" + }, + "type": { + "enum": [ + "apiKey" + ], + "title": "ApiKeyv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "apiKey", + "type" + ], + "title": "ApiKeyv2::LoginAccountParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "chatgpt" + ], + "title": "Chatgptv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "Chatgptv2::LoginAccountParams", + "type": "object" + }, + { + "description": "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.", + "properties": { + "accessToken": { + "description": "Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.", + "type": "string" + }, + "chatgptAccountId": { + "description": "Workspace/account identifier supplied by the client.", + "type": "string" + }, + "chatgptPlanType": { + "description": "Optional plan type supplied by the client.\n\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.", + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "chatgptAuthTokens" + ], + "title": "ChatgptAuthTokensv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "accessToken", + "chatgptAccountId", + "type" + ], + "title": "ChatgptAuthTokensv2::LoginAccountParams", + "type": "object" + } + ], + "title": "LoginAccountParams" + }, + "LoginAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "apiKey" + ], + "title": "ApiKeyv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ApiKeyv2::LoginAccountResponse", + "type": "object" + }, + { + "properties": { + "authUrl": { + "description": "URL the client should open in a browser to initiate the OAuth flow.", + "type": "string" + }, + "loginId": { + "type": "string" + }, + "type": { + "enum": [ + "chatgpt" + ], + "title": "Chatgptv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "authUrl", + "loginId", + "type" + ], + "title": "Chatgptv2::LoginAccountResponse", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "chatgptAuthTokens" + ], + "title": "ChatgptAuthTokensv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ChatgptAuthTokensv2::LoginAccountResponse", + "type": "object" + } + ], + "title": "LoginAccountResponse" + }, + "LogoutAccountResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "LogoutAccountResponse", + "type": "object" + }, + "MacOsAutomationValue": { + "anyOf": [ + { + "type": "boolean" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ] + }, + "MacOsPermissions": { + "properties": { + "accessibility": { + "type": [ + "boolean", + "null" + ] + }, + "automations": { + "anyOf": [ + { + "$ref": "#/definitions/MacOsAutomationValue" + }, + { + "type": "null" + } + ] + }, + "calendar": { + "type": [ + "boolean", + "null" + ] + }, + "preferences": { + "anyOf": [ + { + "$ref": "#/definitions/MacOsPreferencesValue" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "MacOsPreferencesValue": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string" + } + ] + }, + "McpAuthStatus": { + "enum": [ + "unsupported", + "notLoggedIn", + "bearerToken", + "oAuth" + ], + "type": "string" + }, + "McpInvocation": { + "properties": { + "arguments": { + "description": "Arguments to the tool call." + }, + "server": { + "description": "Name of the MCP server as defined in the config.", + "type": "string" + }, + "tool": { + "description": "Name of the tool as given by the MCP server.", + "type": "string" + } + }, + "required": [ + "server", + "tool" + ], + "type": "object" + }, + "McpServerOauthLoginCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "name", + "success" + ], + "title": "McpServerOauthLoginCompletedNotification", + "type": "object" + }, + "McpServerOauthLoginParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "name": { + "type": "string" + }, + "scopes": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "timeoutSecs": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "name" + ], + "title": "McpServerOauthLoginParams", + "type": "object" + }, + "McpServerOauthLoginResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "authorizationUrl": { + "type": "string" + } + }, + "required": [ + "authorizationUrl" + ], + "title": "McpServerOauthLoginResponse", + "type": "object" + }, + "McpServerRefreshResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "McpServerRefreshResponse", + "type": "object" + }, + "McpServerStatus": { + "properties": { + "authStatus": { + "$ref": "#/definitions/McpAuthStatus" + }, + "name": { + "type": "string" + }, + "resourceTemplates": { + "items": { + "$ref": "#/definitions/ResourceTemplate" + }, + "type": "array" + }, + "resources": { + "items": { + "$ref": "#/definitions/Resource" + }, + "type": "array" + }, + "tools": { + "additionalProperties": { + "$ref": "#/definitions/Tool" + }, + "type": "object" + } + }, + "required": [ + "authStatus", + "name", + "resourceTemplates", + "resources", + "tools" + ], + "type": "object" + }, + "McpStartupFailure": { + "properties": { + "error": { + "type": "string" + }, + "server": { + "type": "string" + } + }, + "required": [ + "error", + "server" + ], + "type": "object" + }, + "McpStartupStatus": { + "oneOf": [ + { + "properties": { + "state": { + "enum": [ + "starting" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "title": "StartingMcpStartupStatus", + "type": "object" + }, + { + "properties": { + "state": { + "enum": [ + "ready" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "title": "ReadyMcpStartupStatus", + "type": "object" + }, + { + "properties": { + "error": { + "type": "string" + }, + "state": { + "enum": [ + "failed" + ], + "type": "string" + } + }, + "required": [ + "error", + "state" + ], + "type": "object" + }, + { + "properties": { + "state": { + "enum": [ + "cancelled" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "title": "CancelledMcpStartupStatus", + "type": "object" + } + ] + }, + "McpToolCallError": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "McpToolCallProgressNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "itemId": { + "type": "string" + }, + "message": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "itemId", + "message", + "threadId", + "turnId" + ], + "title": "McpToolCallProgressNotification", + "type": "object" + }, + "McpToolCallResult": { + "properties": { + "content": { + "items": true, + "type": "array" + }, + "structuredContent": true + }, + "required": [ + "content" + ], + "type": "object" + }, + "McpToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, + "MergeStrategy": { + "enum": [ + "replace", + "upsert" + ], + "type": "string" + }, + "MessagePhase": { + "description": "Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.", + "oneOf": [ + { + "description": "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.", + "enum": [ + "commentary" + ], + "type": "string" + }, + { + "description": "The assistant's terminal answer text for the current turn.", + "enum": [ + "final_answer" + ], + "type": "string" + } + ] + }, + "ModeKind": { + "description": "Initial collaboration mode to use when the TUI starts.", + "enum": [ + "plan", + "default" + ], + "type": "string" + }, + "Model": { + "properties": { + "availabilityNux": { + "anyOf": [ + { + "$ref": "#/definitions/ModelAvailabilityNux" + }, + { + "type": "null" + } + ] + }, + "defaultReasoningEffort": { + "$ref": "#/definitions/ReasoningEffort" + }, + "description": { + "type": "string" + }, + "displayName": { + "type": "string" + }, + "hidden": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "inputModalities": { + "default": [ + "text", + "image" + ], + "items": { + "$ref": "#/definitions/InputModality" + }, + "type": "array" + }, + "isDefault": { + "type": "boolean" + }, + "model": { + "type": "string" + }, + "supportedReasoningEfforts": { + "items": { + "$ref": "#/definitions/ReasoningEffortOption" + }, + "type": "array" + }, + "supportsPersonality": { + "default": false, + "type": "boolean" + }, + "upgrade": { + "type": [ + "string", + "null" + ] + }, + "upgradeInfo": { + "anyOf": [ + { + "$ref": "#/definitions/ModelUpgradeInfo" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "defaultReasoningEffort", + "description", + "displayName", + "hidden", + "id", + "isDefault", + "model", + "supportedReasoningEfforts" + ], + "type": "object" + }, + "ModelAvailabilityNux": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "ModelListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "includeHidden": { + "description": "When true, include models that are hidden from the default picker list.", + "type": [ + "boolean", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ModelListParams", + "type": "object" + }, + "ModelListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/Model" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ModelListResponse", + "type": "object" + }, + "ModelRerouteReason": { + "enum": [ + "highRiskCyberActivity" + ], + "type": "string" + }, + "ModelReroutedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "fromModel": { + "type": "string" + }, + "reason": { + "$ref": "#/definitions/ModelRerouteReason" + }, + "threadId": { + "type": "string" + }, + "toModel": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "fromModel", + "reason", + "threadId", + "toModel", + "turnId" + ], + "title": "ModelReroutedNotification", + "type": "object" + }, + "ModelUpgradeInfo": { + "properties": { + "migrationMarkdown": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": "string" + }, + "modelLink": { + "type": [ + "string", + "null" + ] + }, + "upgradeCopy": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "NetworkAccess": { + "enum": [ + "restricted", + "enabled" + ], + "type": "string" + }, + "NetworkApprovalContext": { + "properties": { + "host": { + "type": "string" + }, + "protocol": { + "$ref": "#/definitions/NetworkApprovalProtocol" + } + }, + "required": [ + "host", + "protocol" + ], + "type": "object" + }, + "NetworkApprovalProtocol": { + "enum": [ + "http", + "https", + "socks5Tcp", + "socks5Udp" + ], + "type": "string" + }, + "NetworkPolicyAmendment": { + "properties": { + "action": { + "$ref": "#/definitions/NetworkPolicyRuleAction" + }, + "host": { + "type": "string" + } + }, + "required": [ + "action", + "host" + ], + "type": "object" + }, + "NetworkPolicyRuleAction": { + "enum": [ + "allow", + "deny" + ], + "type": "string" + }, + "NetworkRequirements": { + "properties": { + "allowLocalBinding": { + "type": [ + "boolean", + "null" + ] + }, + "allowUnixSockets": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "allowUpstreamProxy": { + "type": [ + "boolean", + "null" + ] + }, + "allowedDomains": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "dangerouslyAllowAllUnixSockets": { + "type": [ + "boolean", + "null" + ] + }, + "dangerouslyAllowNonLoopbackAdmin": { + "type": [ + "boolean", + "null" + ] + }, + "dangerouslyAllowNonLoopbackProxy": { + "type": [ + "boolean", + "null" + ] + }, + "deniedDomains": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "enabled": { + "type": [ + "boolean", + "null" + ] + }, + "httpPort": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "socksPort": { + "format": "uint16", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, + "OverriddenMetadata": { + "properties": { + "effectiveValue": true, + "message": { + "type": "string" + }, + "overridingLayer": { + "$ref": "#/definitions/ConfigLayerMetadata" + } + }, + "required": [ + "effectiveValue", + "message", + "overridingLayer" + ], + "type": "object" + }, + "ParsedCommand": { + "oneOf": [ + { + "properties": { + "cmd": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "description": "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", + "type": "string" + }, + "type": { + "enum": [ + "read" + ], + "title": "ReadParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "name", + "path", + "type" + ], + "title": "ReadParsedCommand", + "type": "object" + }, + { + "properties": { + "cmd": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "list_files" + ], + "title": "ListFilesParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "type" + ], + "title": "ListFilesParsedCommand", + "type": "object" + }, + { + "properties": { + "cmd": { + "type": "string" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "type" + ], + "title": "SearchParsedCommand", + "type": "object" + }, + { + "properties": { + "cmd": { + "type": "string" + }, + "type": { + "enum": [ + "unknown" + ], + "title": "UnknownParsedCommandType", + "type": "string" + } + }, + "required": [ + "cmd", + "type" + ], + "title": "UnknownParsedCommand", + "type": "object" + } + ] + }, + "PatchApplyStatus": { + "enum": [ + "inProgress", + "completed", + "failed", + "declined" + ], + "type": "string" + }, + "PatchChangeKind": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "add" + ], + "title": "AddPatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AddPatchChangeKind", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "delete" + ], + "title": "DeletePatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DeletePatchChangeKind", + "type": "object" + }, + { + "properties": { + "move_path": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "update" + ], + "title": "UpdatePatchChangeKindType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UpdatePatchChangeKind", + "type": "object" + } + ] + }, + "PermissionProfile": { + "properties": { + "file_system": { + "anyOf": [ + { + "$ref": "#/definitions/FileSystemPermissions" + }, + { + "type": "null" + } + ] + }, + "macos": { + "anyOf": [ + { + "$ref": "#/definitions/MacOsPermissions" + }, + { + "type": "null" + } + ] + }, + "network": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "Personality": { + "enum": [ + "none", + "friendly", + "pragmatic" + ], + "type": "string" + }, + "PlanDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "PlanDeltaNotification", + "type": "object" + }, + "PlanItemArg": { + "additionalProperties": false, + "properties": { + "status": { + "$ref": "#/definitions/StepStatus" + }, + "step": { + "type": "string" + } + }, + "required": [ + "status", + "step" + ], + "type": "object" + }, + "PlanType": { + "enum": [ + "free", + "go", + "plus", + "pro", + "team", + "business", + "enterprise", + "edu", + "unknown" + ], + "type": "string" + }, + "ProductSurface": { + "enum": [ + "chatgpt", + "codex", + "api", + "atlas" + ], + "type": "string" + }, + "ProfileV2": { + "additionalProperties": true, + "properties": { + "approval_policy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "chatgpt_base_url": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "model_provider": { + "type": [ + "string", + "null" + ] + }, + "model_reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "model_reasoning_summary": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningSummary" + }, + { + "type": "null" + } + ] + }, + "model_verbosity": { + "anyOf": [ + { + "$ref": "#/definitions/Verbosity" + }, + { + "type": "null" + } + ] + }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + "web_search": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchMode" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "RateLimitSnapshot": { + "properties": { + "credits": { + "anyOf": [ + { + "$ref": "#/definitions/CreditsSnapshot" + }, + { + "type": "null" + } + ] + }, + "limitId": { + "type": [ + "string", + "null" + ] + }, + "limitName": { + "type": [ + "string", + "null" + ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/PlanType" + }, + { + "type": "null" + } + ] + }, + "primary": { + "anyOf": [ + { + "$ref": "#/definitions/RateLimitWindow" + }, + { + "type": "null" + } + ] + }, + "secondary": { + "anyOf": [ + { + "$ref": "#/definitions/RateLimitWindow" + }, + { + "type": "null" + } + ] + } + }, + "type": "object" + }, + "RateLimitWindow": { + "properties": { + "resetsAt": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "usedPercent": { + "format": "int32", + "type": "integer" + }, + "windowDurationMins": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "usedPercent" + ], + "type": "object" + }, + "RawResponseItemCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "item": { + "$ref": "#/definitions/ResponseItem" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId", + "turnId" + ], + "title": "RawResponseItemCompletedNotification", + "type": "object" + }, + "ReadOnlyAccess": { + "oneOf": [ + { + "properties": { + "includePlatformDefaults": { + "default": true, + "type": "boolean" + }, + "readableRoots": { + "default": [], + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedReadOnlyAccessType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "RestrictedReadOnlyAccess", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "fullAccess" + ], + "title": "FullAccessReadOnlyAccessType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "FullAccessReadOnlyAccess", + "type": "object" + } + ] + }, + "RealtimeAudioFrame": { + "properties": { + "data": { + "type": "string" + }, + "num_channels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sample_rate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samples_per_channel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "num_channels", + "sample_rate" + ], + "type": "object" + }, + "RealtimeEvent": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "SessionUpdated": { + "properties": { + "instructions": { + "type": [ + "string", + "null" + ] + }, + "session_id": { + "type": "string" + } + }, + "required": [ + "session_id" + ], + "type": "object" + } + }, + "required": [ + "SessionUpdated" + ], + "title": "SessionUpdatedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "AudioOut": { + "$ref": "#/definitions/RealtimeAudioFrame" + } + }, + "required": [ + "AudioOut" + ], + "title": "AudioOutRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemAdded": true + }, + "required": [ + "ConversationItemAdded" + ], + "title": "ConversationItemAddedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "ConversationItemDone": { + "properties": { + "item_id": { + "type": "string" + } + }, + "required": [ + "item_id" + ], + "type": "object" + } + }, + "required": [ + "ConversationItemDone" + ], + "title": "ConversationItemDoneRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "HandoffRequested": { + "$ref": "#/definitions/RealtimeHandoffRequested" + } + }, + "required": [ + "HandoffRequested" + ], + "title": "HandoffRequestedRealtimeEvent", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "Error": { + "type": "string" + } + }, + "required": [ + "Error" + ], + "title": "ErrorRealtimeEvent", + "type": "object" + } + ] + }, + "RealtimeHandoffMessage": { + "properties": { + "role": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "role", + "text" + ], + "type": "object" + }, + "RealtimeHandoffRequested": { + "properties": { + "handoff_id": { + "type": "string" + }, + "input_transcript": { + "type": "string" + }, + "item_id": { + "type": "string" + }, + "messages": { + "items": { + "$ref": "#/definitions/RealtimeHandoffMessage" + }, + "type": "array" + } + }, + "required": [ + "handoff_id", + "input_transcript", + "item_id", + "messages" + ], + "type": "object" + }, + "ReasoningEffort": { + "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", + "enum": [ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh" + ], + "type": "string" + }, + "ReasoningEffortOption": { + "properties": { + "description": { + "type": "string" + }, + "reasoningEffort": { + "$ref": "#/definitions/ReasoningEffort" + } + }, + "required": [ + "description", + "reasoningEffort" + ], + "type": "object" + }, + "ReasoningItemContent": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "reasoning_text" + ], + "title": "ReasoningTextReasoningItemContentType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "ReasoningTextReasoningItemContent", + "type": "object" + }, + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "text" + ], + "title": "TextReasoningItemContentType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextReasoningItemContent", + "type": "object" + } + ] + }, + "ReasoningItemReasoningSummary": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "summary_text" + ], + "title": "SummaryTextReasoningItemReasoningSummaryType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "SummaryTextReasoningItemReasoningSummary", + "type": "object" + } + ] + }, + "ReasoningSummary": { + "description": "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", + "oneOf": [ + { + "enum": [ + "auto", + "concise", + "detailed" + ], + "type": "string" + }, + { + "description": "Option to disable reasoning summaries.", + "enum": [ + "none" + ], + "type": "string" + } + ] + }, + "ReasoningSummaryPartAddedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "itemId": { + "type": "string" + }, + "summaryIndex": { + "format": "int64", + "type": "integer" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "itemId", + "summaryIndex", + "threadId", + "turnId" + ], + "title": "ReasoningSummaryPartAddedNotification", + "type": "object" + }, + "ReasoningSummaryTextDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "summaryIndex": { + "format": "int64", + "type": "integer" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "delta", + "itemId", + "summaryIndex", + "threadId", + "turnId" + ], + "title": "ReasoningSummaryTextDeltaNotification", + "type": "object" + }, + "ReasoningTextDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "contentIndex": { + "format": "int64", + "type": "integer" + }, + "delta": { + "type": "string" + }, + "itemId": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "contentIndex", + "delta", + "itemId", + "threadId", + "turnId" + ], + "title": "ReasoningTextDeltaNotification", + "type": "object" + }, + "RemoteSkillSummary": { + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "description", + "id", + "name" + ], + "type": "object" + }, + "RequestId": { + "anyOf": [ + { + "type": "string" + }, + { + "format": "int64", + "type": "integer" + } + ] + }, + "RequestUserInputQuestion": { + "properties": { + "header": { + "type": "string" + }, + "id": { + "type": "string" + }, + "isOther": { + "default": false, + "type": "boolean" + }, + "isSecret": { + "default": false, + "type": "boolean" + }, + "options": { + "items": { + "$ref": "#/definitions/RequestUserInputQuestionOption" + }, + "type": [ + "array", + "null" + ] + }, + "question": { + "type": "string" + } + }, + "required": [ + "header", + "id", + "question" + ], + "type": "object" + }, + "RequestUserInputQuestionOption": { + "properties": { + "description": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "description", + "label" + ], + "type": "object" + }, + "ResidencyRequirement": { + "enum": [ + "us" + ], + "type": "string" + }, + "Resource": { + "description": "A known resource that the server is capable of reading.", + "properties": { + "_meta": true, + "annotations": true, + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "mimeType": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "size": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "uri": { + "type": "string" + } + }, + "required": [ + "name", + "uri" + ], + "type": "object" + }, + "ResourceTemplate": { + "description": "A template description for resources available on the server.", + "properties": { + "annotations": true, + "description": { + "type": [ + "string", + "null" + ] + }, + "mimeType": { + "type": [ + "string", + "null" + ] + }, + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "uriTemplate": { + "type": "string" + } + }, + "required": [ + "name", + "uriTemplate" + ], + "type": "object" + }, + "ResponseItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/ContentItem" + }, + "type": "array" + }, + "end_turn": { + "type": [ + "boolean", + "null" + ] + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ] + }, + "role": { + "type": "string" + }, + "type": { + "enum": [ + "message" + ], + "title": "MessageResponseItemType", + "type": "string" + } + }, + "required": [ + "content", + "role", + "type" + ], + "title": "MessageResponseItem", + "type": "object" + }, + { + "properties": { + "content": { + "default": null, + "items": { + "$ref": "#/definitions/ReasoningItemContent" + }, + "type": [ + "array", + "null" + ] + }, + "encrypted_content": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string", + "writeOnly": true + }, + "summary": { + "items": { + "$ref": "#/definitions/ReasoningItemReasoningSummary" + }, + "type": "array" + }, + "type": { + "enum": [ + "reasoning" + ], + "title": "ReasoningResponseItemType", + "type": "string" + } + }, + "required": [ + "id", + "summary", + "type" + ], + "title": "ReasoningResponseItem", + "type": "object" + }, + { + "properties": { + "action": { + "$ref": "#/definitions/LocalShellAction" + }, + "call_id": { + "description": "Set when using the Responses API.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Legacy id field retained for compatibility with older payloads.", + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "status": { + "$ref": "#/definitions/LocalShellStatus" + }, + "type": { + "enum": [ + "local_shell_call" + ], + "title": "LocalShellCallResponseItemType", + "type": "string" + } + }, + "required": [ + "action", + "status", + "type" + ], + "title": "LocalShellCallResponseItem", + "type": "object" + }, + { + "properties": { + "arguments": { + "type": "string" + }, + "call_id": { + "type": "string" + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "name": { + "type": "string" + }, + "type": { + "enum": [ + "function_call" + ], + "title": "FunctionCallResponseItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "call_id", + "name", + "type" + ], + "title": "FunctionCallResponseItem", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "output": { + "$ref": "#/definitions/FunctionCallOutputPayload" + }, + "type": { + "enum": [ + "function_call_output" + ], + "title": "FunctionCallOutputResponseItemType", + "type": "string" + } + }, + "required": [ + "call_id", + "output", + "type" + ], + "title": "FunctionCallOutputResponseItem", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "input": { + "type": "string" + }, + "name": { + "type": "string" + }, + "status": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "custom_tool_call" + ], + "title": "CustomToolCallResponseItemType", + "type": "string" + } + }, + "required": [ + "call_id", + "input", + "name", + "type" + ], + "title": "CustomToolCallResponseItem", + "type": "object" + }, + { + "properties": { + "call_id": { + "type": "string" + }, + "output": { + "$ref": "#/definitions/FunctionCallOutputPayload" + }, + "type": { + "enum": [ + "custom_tool_call_output" + ], + "title": "CustomToolCallOutputResponseItemType", + "type": "string" + } + }, + "required": [ + "call_id", + "output", + "type" + ], + "title": "CustomToolCallOutputResponseItem", + "type": "object" + }, + { + "properties": { + "action": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchAction" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": [ + "string", + "null" + ], + "writeOnly": true + }, + "status": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "web_search_call" + ], + "title": "WebSearchCallResponseItemType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "WebSearchCallResponseItem", + "type": "object" + }, + { + "properties": { + "ghost_commit": { + "$ref": "#/definitions/GhostCommit" + }, + "type": { + "enum": [ + "ghost_snapshot" + ], + "title": "GhostSnapshotResponseItemType", + "type": "string" + } + }, + "required": [ + "ghost_commit", + "type" + ], + "title": "GhostSnapshotResponseItem", + "type": "object" + }, + { + "properties": { + "encrypted_content": { + "type": "string" + }, + "type": { + "enum": [ + "compaction" + ], + "title": "CompactionResponseItemType", + "type": "string" + } + }, + "required": [ + "encrypted_content", + "type" + ], + "title": "CompactionResponseItem", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "other" + ], + "title": "OtherResponseItemType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "OtherResponseItem", + "type": "object" + } + ] + }, + "Result_of_CallToolResult_or_String": { + "oneOf": [ + { + "properties": { + "Ok": { + "$ref": "#/definitions/CallToolResult" + } + }, + "required": [ + "Ok" + ], + "title": "OkResult_of_CallToolResult_or_String", + "type": "object" + }, + { + "properties": { + "Err": { + "type": "string" + } + }, + "required": [ + "Err" + ], + "title": "ErrResult_of_CallToolResult_or_String", + "type": "object" + } + ] + }, + "ReviewCodeLocation": { + "description": "Location of the code related to a review finding.", + "properties": { + "absolute_file_path": { + "type": "string" + }, + "line_range": { + "$ref": "#/definitions/ReviewLineRange" + } + }, + "required": [ + "absolute_file_path", + "line_range" + ], + "type": "object" + }, + "ReviewDecision": { + "description": "User's decision in response to an ExecApprovalRequest.", + "oneOf": [ + { + "description": "User has approved this command and the agent should execute it.", + "enum": [ + "approved" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.", + "properties": { + "approved_execpolicy_amendment": { + "properties": { + "proposed_execpolicy_amendment": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "proposed_execpolicy_amendment" + ], + "type": "object" + } + }, + "required": [ + "approved_execpolicy_amendment" + ], + "title": "ApprovedExecpolicyAmendmentReviewDecision", + "type": "object" + }, + { + "description": "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", + "enum": [ + "approved_for_session" + ], + "type": "string" + }, + { + "additionalProperties": false, + "description": "User chose to persist a network policy rule (allow/deny) for future requests to the same host.", + "properties": { + "network_policy_amendment": { + "properties": { + "network_policy_amendment": { + "$ref": "#/definitions/NetworkPolicyAmendment" + } + }, + "required": [ + "network_policy_amendment" + ], + "type": "object" + } + }, + "required": [ + "network_policy_amendment" + ], + "title": "NetworkPolicyAmendmentReviewDecision", + "type": "object" + }, + { + "description": "User has denied this command and the agent should not execute it, but it should continue the session and try something else.", + "enum": [ + "denied" + ], + "type": "string" + }, + { + "description": "User has denied this command and the agent should not do anything until the user's next command.", + "enum": [ + "abort" + ], + "type": "string" + } + ] + }, + "ReviewDelivery": { + "enum": [ + "inline", + "detached" + ], + "type": "string" + }, + "ReviewFinding": { + "description": "A single review finding describing an observed issue or recommendation.", + "properties": { + "body": { + "type": "string" + }, + "code_location": { + "$ref": "#/definitions/ReviewCodeLocation" + }, + "confidence_score": { + "format": "float", + "type": "number" + }, + "priority": { + "format": "int32", + "type": "integer" + }, + "title": { + "type": "string" + } + }, + "required": [ + "body", + "code_location", + "confidence_score", + "priority", + "title" + ], + "type": "object" + }, + "ReviewLineRange": { + "description": "Inclusive line range in a file associated with the finding.", + "properties": { + "end": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "start": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "ReviewOutputEvent": { + "description": "Structured review result produced by a child review session.", + "properties": { + "findings": { + "items": { + "$ref": "#/definitions/ReviewFinding" + }, + "type": "array" + }, + "overall_confidence_score": { + "format": "float", + "type": "number" + }, + "overall_correctness": { + "type": "string" + }, + "overall_explanation": { + "type": "string" + } + }, + "required": [ + "findings", + "overall_confidence_score", + "overall_correctness", + "overall_explanation" + ], + "type": "object" + }, + "ReviewStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "delivery": { + "anyOf": [ + { + "$ref": "#/definitions/ReviewDelivery" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`)." + }, + "target": { + "$ref": "#/definitions/ReviewTarget" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "target", + "threadId" + ], + "title": "ReviewStartParams", + "type": "object" + }, + "ReviewStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "reviewThreadId": { + "description": "Identifies the thread where the review runs.\n\nFor inline reviews, this is the original thread id. For detached reviews, this is the id of the new review thread.", + "type": "string" + }, + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "reviewThreadId", + "turn" + ], + "title": "ReviewStartResponse", + "type": "object" + }, + "ReviewTarget": { + "oneOf": [ + { + "description": "Review the working tree: staged, unstaged, and untracked files.", + "properties": { + "type": { + "enum": [ + "uncommittedChanges" + ], + "title": "UncommittedChangesReviewTargetType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UncommittedChangesReviewTarget", + "type": "object" + }, + { + "description": "Review changes between the current branch and the given base branch.", + "properties": { + "branch": { + "type": "string" + }, + "type": { + "enum": [ + "baseBranch" + ], + "title": "BaseBranchReviewTargetType", + "type": "string" + } + }, + "required": [ + "branch", + "type" + ], + "title": "BaseBranchReviewTarget", + "type": "object" + }, + { + "description": "Review the changes introduced by a specific commit.", + "properties": { + "sha": { + "type": "string" + }, + "title": { + "description": "Optional human-readable label (e.g., commit subject) for UIs.", + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "commit" + ], + "title": "CommitReviewTargetType", + "type": "string" + } + }, + "required": [ + "sha", + "type" + ], + "title": "CommitReviewTarget", + "type": "object" + }, + { + "description": "Arbitrary instructions, equivalent to the old free-form prompt.", + "properties": { + "instructions": { + "type": "string" + }, + "type": { + "enum": [ + "custom" + ], + "title": "CustomReviewTargetType", + "type": "string" + } + }, + "required": [ + "instructions", + "type" + ], + "title": "CustomReviewTarget", + "type": "object" + } + ] + }, + "SandboxMode": { + "enum": [ + "read-only", + "workspace-write", + "danger-full-access" + ], + "type": "string" + }, + "SandboxPolicy": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "dangerFullAccess" + ], + "title": "DangerFullAccessSandboxPolicyType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DangerFullAccessSandboxPolicy", + "type": "object" + }, + { + "properties": { + "access": { + "allOf": [ + { + "$ref": "#/definitions/ReadOnlyAccess" + } + ], + "default": { + "type": "fullAccess" + } + }, + "type": { + "enum": [ + "readOnly" + ], + "title": "ReadOnlySandboxPolicyType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ReadOnlySandboxPolicy", + "type": "object" + }, + { + "properties": { + "networkAccess": { + "allOf": [ + { + "$ref": "#/definitions/NetworkAccess" + } + ], + "default": "restricted" + }, + "type": { + "enum": [ + "externalSandbox" + ], + "title": "ExternalSandboxSandboxPolicyType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ExternalSandboxSandboxPolicy", + "type": "object" + }, + { + "properties": { + "excludeSlashTmp": { + "default": false, + "type": "boolean" + }, + "excludeTmpdirEnvVar": { + "default": false, + "type": "boolean" + }, + "networkAccess": { + "default": false, + "type": "boolean" + }, + "readOnlyAccess": { + "allOf": [ + { + "$ref": "#/definitions/ReadOnlyAccess" + } + ], + "default": { + "type": "fullAccess" + } + }, + "type": { + "enum": [ + "workspaceWrite" + ], + "title": "WorkspaceWriteSandboxPolicyType", + "type": "string" + }, + "writableRoots": { + "default": [], + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + } + }, + "required": [ + "type" + ], + "title": "WorkspaceWriteSandboxPolicy", + "type": "object" + } + ] + }, + "SandboxWorkspaceWrite": { + "properties": { + "exclude_slash_tmp": { + "default": false, + "type": "boolean" + }, + "exclude_tmpdir_env_var": { + "default": false, + "type": "boolean" + }, + "network_access": { + "default": false, + "type": "boolean" + }, + "writable_roots": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "ServerNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification sent from the server to the client.", + "oneOf": [ + { + "description": "NEW NOTIFICATIONS", + "properties": { + "method": { + "enum": [ + "error" + ], + "title": "ErrorNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ErrorNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ErrorNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/started" + ], + "title": "Thread/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/status/changed" + ], + "title": "Thread/status/changedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadStatusChangedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/status/changedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/archived" + ], + "title": "Thread/archivedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadArchivedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/archivedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/unarchived" + ], + "title": "Thread/unarchivedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadUnarchivedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/unarchivedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/closed" + ], + "title": "Thread/closedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadClosedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/closedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/name/updated" + ], + "title": "Thread/name/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadNameUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/name/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/tokenUsage/updated" + ], + "title": "Thread/tokenUsage/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadTokenUsageUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/tokenUsage/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/started" + ], + "title": "Turn/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/completed" + ], + "title": "Turn/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/completedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/diff/updated" + ], + "title": "Turn/diff/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnDiffUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/diff/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "turn/plan/updated" + ], + "title": "Turn/plan/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TurnPlanUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Turn/plan/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/started" + ], + "title": "Item/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ItemStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/completed" + ], + "title": "Item/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ItemCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/completedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/agentMessage/delta" + ], + "title": "Item/agentMessage/deltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AgentMessageDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/agentMessage/deltaNotification", + "type": "object" + }, + { + "description": "EXPERIMENTAL - proposed plan streaming deltas for plan items.", + "properties": { + "method": { + "enum": [ + "item/plan/delta" + ], + "title": "Item/plan/deltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/PlanDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/plan/deltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/commandExecution/outputDelta" + ], + "title": "Item/commandExecution/outputDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/CommandExecutionOutputDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/commandExecution/outputDeltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/commandExecution/terminalInteraction" + ], + "title": "Item/commandExecution/terminalInteractionNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/TerminalInteractionNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/commandExecution/terminalInteractionNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/fileChange/outputDelta" + ], + "title": "Item/fileChange/outputDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FileChangeOutputDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/fileChange/outputDeltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "serverRequest/resolved" + ], + "title": "ServerRequest/resolvedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ServerRequestResolvedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ServerRequest/resolvedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/mcpToolCall/progress" + ], + "title": "Item/mcpToolCall/progressNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/McpToolCallProgressNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/mcpToolCall/progressNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "mcpServer/oauthLogin/completed" + ], + "title": "McpServer/oauthLogin/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/McpServerOauthLoginCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "McpServer/oauthLogin/completedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "account/updated" + ], + "title": "Account/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AccountUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Account/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "account/rateLimits/updated" + ], + "title": "Account/rateLimits/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AccountRateLimitsUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Account/rateLimits/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "app/list/updated" + ], + "title": "App/list/updatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AppListUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "App/list/updatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/reasoning/summaryTextDelta" + ], + "title": "Item/reasoning/summaryTextDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReasoningSummaryTextDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/reasoning/summaryTextDeltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/reasoning/summaryPartAdded" + ], + "title": "Item/reasoning/summaryPartAddedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReasoningSummaryPartAddedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/reasoning/summaryPartAddedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "item/reasoning/textDelta" + ], + "title": "Item/reasoning/textDeltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ReasoningTextDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Item/reasoning/textDeltaNotification", + "type": "object" + }, + { + "description": "Deprecated: Use `ContextCompaction` item type instead.", + "properties": { + "method": { + "enum": [ + "thread/compacted" + ], + "title": "Thread/compactedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ContextCompactedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/compactedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "model/rerouted" + ], + "title": "Model/reroutedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ModelReroutedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Model/reroutedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "deprecationNotice" + ], + "title": "DeprecationNoticeNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeprecationNoticeNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "DeprecationNoticeNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "configWarning" + ], + "title": "ConfigWarningNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ConfigWarningNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "ConfigWarningNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "fuzzyFileSearch/sessionUpdated" + ], + "title": "FuzzyFileSearch/sessionUpdatedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FuzzyFileSearchSessionUpdatedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "FuzzyFileSearch/sessionUpdatedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "fuzzyFileSearch/sessionCompleted" + ], + "title": "FuzzyFileSearch/sessionCompletedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/FuzzyFileSearchSessionCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "FuzzyFileSearch/sessionCompletedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/started" + ], + "title": "Thread/realtime/startedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeStartedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/startedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/itemAdded" + ], + "title": "Thread/realtime/itemAddedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeItemAddedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/itemAddedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/outputAudio/delta" + ], + "title": "Thread/realtime/outputAudio/deltaNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeOutputAudioDeltaNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/outputAudio/deltaNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/error" + ], + "title": "Thread/realtime/errorNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeErrorNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/errorNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "thread/realtime/closed" + ], + "title": "Thread/realtime/closedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadRealtimeClosedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Thread/realtime/closedNotification", + "type": "object" + }, + { + "description": "Notifies the user of world-writable directories on Windows, which cannot be protected by the sandbox.", + "properties": { + "method": { + "enum": [ + "windows/worldWritableWarning" + ], + "title": "Windows/worldWritableWarningNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WindowsWorldWritableWarningNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Windows/worldWritableWarningNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "windowsSandbox/setupCompleted" + ], + "title": "WindowsSandbox/setupCompletedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WindowsSandboxSetupCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "WindowsSandbox/setupCompletedNotification", + "type": "object" + }, + { + "properties": { + "method": { + "enum": [ + "account/login/completed" + ], + "title": "Account/login/completedNotificationMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/AccountLoginCompletedNotification" + } + }, + "required": [ + "method", + "params" + ], + "title": "Account/login/completedNotification", + "type": "object" + } + ], + "title": "ServerNotification" + }, + "ServerRequestResolvedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "requestId": { + "$ref": "#/definitions/RequestId" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "requestId", + "threadId" + ], + "title": "ServerRequestResolvedNotification", + "type": "object" + }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, + "SessionNetworkProxyRuntime": { + "properties": { + "admin_addr": { + "type": "string" + }, + "http_addr": { + "type": "string" + }, + "socks_addr": { + "type": "string" + } + }, + "required": [ + "admin_addr", + "http_addr", + "socks_addr" + ], + "type": "object" + }, + "SessionSource": { + "oneOf": [ + { + "enum": [ + "cli", + "vscode", + "exec", + "appServer", + "unknown" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "subAgent": { + "$ref": "#/definitions/SubAgentSource" + } + }, + "required": [ + "subAgent" + ], + "title": "SubAgentSessionSource", + "type": "object" + } + ] + }, + "Settings": { + "description": "Settings for a collaboration mode.", + "properties": { + "developer_instructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": "string" + }, + "reasoning_effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "model" + ], + "type": "object" + }, + "SkillDependencies": { + "properties": { + "tools": { + "items": { + "$ref": "#/definitions/SkillToolDependency" + }, + "type": "array" + } + }, + "required": [ + "tools" + ], + "type": "object" + }, + "SkillErrorInfo": { + "properties": { + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "message", + "path" + ], + "type": "object" + }, + "SkillInterface": { + "properties": { + "brandColor": { + "type": [ + "string", + "null" + ] + }, + "defaultPrompt": { + "type": [ + "string", + "null" + ] + }, + "displayName": { + "type": [ + "string", + "null" + ] + }, + "iconLarge": { + "type": [ + "string", + "null" + ] + }, + "iconSmall": { + "type": [ + "string", + "null" + ] + }, + "shortDescription": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "SkillMetadata": { + "properties": { + "dependencies": { + "anyOf": [ + { + "$ref": "#/definitions/SkillDependencies" + }, + { + "type": "null" + } + ] + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "interface": { + "anyOf": [ + { + "$ref": "#/definitions/SkillInterface" + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "scope": { + "$ref": "#/definitions/SkillScope" + }, + "shortDescription": { + "description": "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "description", + "enabled", + "name", + "path", + "scope" + ], + "type": "object" + }, + "SkillScope": { + "enum": [ + "user", + "repo", + "system", + "admin" + ], + "type": "string" + }, + "SkillToolDependency": { + "properties": { + "command": { + "type": [ + "string", + "null" + ] + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "transport": { + "type": [ + "string", + "null" + ] + }, + "type": { + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "value": { + "type": "string" + } + }, + "required": [ + "type", + "value" + ], + "type": "object" + }, + "SkillsConfigWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "enabled": { + "type": "boolean" + }, + "path": { + "type": "string" + } + }, + "required": [ + "enabled", + "path" + ], + "title": "SkillsConfigWriteParams", + "type": "object" + }, + "SkillsConfigWriteResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "effectiveEnabled": { + "type": "boolean" + } + }, + "required": [ + "effectiveEnabled" + ], + "title": "SkillsConfigWriteResponse", + "type": "object" + }, + "SkillsListEntry": { + "properties": { + "cwd": { + "type": "string" + }, + "errors": { + "items": { + "$ref": "#/definitions/SkillErrorInfo" + }, + "type": "array" + }, + "skills": { + "items": { + "$ref": "#/definitions/SkillMetadata" + }, + "type": "array" + } + }, + "required": [ + "cwd", + "errors", + "skills" + ], + "type": "object" + }, + "SkillsListExtraRootsForCwd": { + "properties": { + "cwd": { + "type": "string" + }, + "extraUserRoots": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "cwd", + "extraUserRoots" + ], + "type": "object" + }, + "SkillsListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cwds": { + "description": "When empty, defaults to the current session working directory.", + "items": { + "type": "string" + }, + "type": "array" + }, + "forceReload": { + "description": "When true, bypass the skills cache and re-scan skills from disk.", + "type": "boolean" + }, + "perCwdExtraUserRoots": { + "default": null, + "description": "Optional per-cwd extra roots to scan as user-scoped skills.", + "items": { + "$ref": "#/definitions/SkillsListExtraRootsForCwd" + }, + "type": [ + "array", + "null" + ] + } + }, + "title": "SkillsListParams", + "type": "object" + }, + "SkillsListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/SkillsListEntry" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "SkillsListResponse", + "type": "object" + }, + "SkillsRemoteReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "enabled": { + "default": false, + "type": "boolean" + }, + "hazelnutScope": { + "allOf": [ + { + "$ref": "#/definitions/HazelnutScope" + } + ], + "default": "example" + }, + "productSurface": { + "allOf": [ + { + "$ref": "#/definitions/ProductSurface" + } + ], + "default": "codex" + } + }, + "title": "SkillsRemoteReadParams", + "type": "object" + }, + "SkillsRemoteReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/RemoteSkillSummary" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "SkillsRemoteReadResponse", + "type": "object" + }, + "SkillsRemoteWriteParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "hazelnutId": { + "type": "string" + } + }, + "required": [ + "hazelnutId" + ], + "title": "SkillsRemoteWriteParams", + "type": "object" + }, + "SkillsRemoteWriteResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "id", + "path" + ], + "title": "SkillsRemoteWriteResponse", + "type": "object" + }, + "StepStatus": { + "enum": [ + "pending", + "in_progress", + "completed" + ], + "type": "string" + }, + "SubAgentSource": { + "oneOf": [ + { + "enum": [ + "review", + "compact", + "memory_consolidation" + ], + "type": "string" + }, + { + "additionalProperties": false, + "properties": { + "thread_spawn": { + "properties": { + "agent_nickname": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "agent_role": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "depth": { + "format": "int32", + "type": "integer" + }, + "parent_thread_id": { + "$ref": "#/definitions/ThreadId" + } + }, + "required": [ + "depth", + "parent_thread_id" + ], + "type": "object" + } + }, + "required": [ + "thread_spawn" + ], + "title": "ThreadSpawnSubAgentSource", + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "other": { + "type": "string" + } + }, + "required": [ + "other" + ], + "title": "OtherSubAgentSource", + "type": "object" + } + ] + }, + "TerminalInteractionNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "itemId": { + "type": "string" + }, + "processId": { + "type": "string" + }, + "stdin": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "itemId", + "processId", + "stdin", + "threadId", + "turnId" + ], + "title": "TerminalInteractionNotification", + "type": "object" + }, + "TextElement": { + "properties": { + "byteRange": { + "allOf": [ + { + "$ref": "#/definitions/ByteRange" + } + ], + "description": "Byte range in the parent `text` buffer that this element occupies." + }, + "placeholder": { + "description": "Optional human-readable placeholder for the element, displayed in the UI.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "byteRange" + ], + "type": "object" + }, + "TextPosition": { + "properties": { + "column": { + "description": "1-based column number (in Unicode scalar values).", + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "line": { + "description": "1-based line number.", + "format": "uint", + "minimum": 0.0, + "type": "integer" + } + }, + "required": [ + "column", + "line" + ], + "type": "object" + }, + "TextRange": { + "properties": { + "end": { + "$ref": "#/definitions/TextPosition" + }, + "start": { + "$ref": "#/definitions/TextPosition" + } + }, + "required": [ + "end", + "start" + ], + "type": "object" + }, + "Thread": { + "properties": { + "agentNickname": { + "description": "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "agentRole": { + "description": "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + "type": [ + "string", + "null" + ] + }, + "cliVersion": { + "description": "Version of the CLI that created the thread.", + "type": "string" + }, + "createdAt": { + "description": "Unix timestamp (in seconds) when the thread was created.", + "format": "int64", + "type": "integer" + }, + "cwd": { + "description": "Working directory captured for the thread.", + "type": "string" + }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, + "gitInfo": { + "anyOf": [ + { + "$ref": "#/definitions/GitInfo" + }, + { + "type": "null" + } + ], + "description": "Optional Git metadata captured when the thread was created." + }, + "id": { + "type": "string" + }, + "modelProvider": { + "description": "Model provider used for this thread (for example, 'openai').", + "type": "string" + }, + "name": { + "description": "Optional user-facing thread title.", + "type": [ + "string", + "null" + ] + }, + "path": { + "description": "[UNSTABLE] Path to the thread on disk.", + "type": [ + "string", + "null" + ] + }, + "preview": { + "description": "Usually the first user message in the thread, if available.", + "type": "string" + }, + "source": { + "allOf": [ + { + "$ref": "#/definitions/SessionSource" + } + ], + "description": "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.)." + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/ThreadStatus" + } + ], + "description": "Current runtime status for the thread." + }, + "turns": { + "description": "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + "items": { + "$ref": "#/definitions/Turn" + }, + "type": "array" + }, + "updatedAt": { + "description": "Unix timestamp (in seconds) when the thread was last updated.", + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cliVersion", + "createdAt", + "cwd", + "ephemeral", + "id", + "modelProvider", + "preview", + "source", + "status", + "turns", + "updatedAt" + ], + "type": "object" + }, + "ThreadActiveFlag": { + "enum": [ + "waitingOnApproval", + "waitingOnUserInput" + ], + "type": "string" + }, + "ThreadArchiveParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadArchiveParams", + "type": "object" + }, + "ThreadArchiveResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ThreadArchiveResponse", + "type": "object" + }, + "ThreadArchivedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadArchivedNotification", + "type": "object" + }, + "ThreadClosedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadClosedNotification", + "type": "object" + }, + "ThreadCompactStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadCompactStartParams", + "type": "object" + }, + "ThreadCompactStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ThreadCompactStartResponse", + "type": "object" + }, + "ThreadForkParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "baseInstructions": { + "type": [ + "string", + "null" + ] + }, + "config": { + "additionalProperties": true, + "type": [ + "object", + "null" + ] + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "developerInstructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "description": "Configuration overrides for the forked thread, if any.", + "type": [ + "string", + "null" + ] + }, + "modelProvider": { + "type": [ + "string", + "null" + ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadForkParams", + "type": "object" + }, + "ThreadForkResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "$ref": "#/definitions/AskForApproval" + }, + "cwd": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelProvider": { + "type": "string" + }, + "reasoningEffort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "$ref": "#/definitions/SandboxPolicy" + }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "approvalPolicy", + "cwd", + "model", + "modelProvider", + "sandbox", + "thread" + ], + "title": "ThreadForkResponse", + "type": "object" + }, + "ThreadId": { + "type": "string" + }, + "ThreadItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "type": { + "enum": [ + "userMessage" + ], + "title": "UserMessageThreadItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "UserMessageThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "agentMessage" + ], + "title": "AgentMessageThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "AgentMessageThreadItem", + "type": "object" + }, + { + "description": "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "plan" + ], + "title": "PlanThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "PlanThreadItem", + "type": "object" + }, + { + "properties": { + "content": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "summary": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "reasoning" + ], + "title": "ReasoningThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ReasoningThreadItem", + "type": "object" + }, + { + "properties": { + "aggregatedOutput": { + "description": "The command's output, aggregated from stdout and stderr.", + "type": [ + "string", + "null" + ] + }, + "command": { + "description": "The command to be executed.", + "type": "string" + }, + "commandActions": { + "description": "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + "items": { + "$ref": "#/definitions/CommandAction" + }, + "type": "array" + }, + "cwd": { + "description": "The command's working directory.", + "type": "string" + }, + "durationMs": { + "description": "The duration of the command execution in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "exitCode": { + "description": "The command's exit code.", + "format": "int32", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "processId": { + "description": "Identifier for the underlying PTY process (when available).", + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/definitions/CommandExecutionStatus" + }, + "type": { + "enum": [ + "commandExecution" + ], + "title": "CommandExecutionThreadItemType", + "type": "string" + } + }, + "required": [ + "command", + "commandActions", + "cwd", + "id", + "status", + "type" + ], + "title": "CommandExecutionThreadItem", + "type": "object" + }, + { + "properties": { + "changes": { + "items": { + "$ref": "#/definitions/FileUpdateChange" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/PatchApplyStatus" + }, + "type": { + "enum": [ + "fileChange" + ], + "title": "FileChangeThreadItemType", + "type": "string" + } + }, + "required": [ + "changes", + "id", + "status", + "type" + ], + "title": "FileChangeThreadItem", + "type": "object" + }, + { + "properties": { + "arguments": true, + "durationMs": { + "description": "The duration of the MCP tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "error": { + "anyOf": [ + { + "$ref": "#/definitions/McpToolCallError" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "result": { + "anyOf": [ + { + "$ref": "#/definitions/McpToolCallResult" + }, + { + "type": "null" + } + ] + }, + "server": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/McpToolCallStatus" + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "mcpToolCall" + ], + "title": "McpToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "server", + "status", + "tool", + "type" + ], + "title": "McpToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "agentsStates": { + "additionalProperties": { + "$ref": "#/definitions/CollabAgentState" + }, + "description": "Last known status of the target agents, when available.", + "type": "object" + }, + "id": { + "description": "Unique identifier for this collab tool call.", + "type": "string" + }, + "prompt": { + "description": "Prompt text sent as part of the collab tool call, when available.", + "type": [ + "string", + "null" + ] + }, + "receiverThreadIds": { + "description": "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + "items": { + "type": "string" + }, + "type": "array" + }, + "senderThreadId": { + "description": "Thread ID of the agent issuing the collab request.", + "type": "string" + }, + "status": { + "allOf": [ + { + "$ref": "#/definitions/CollabAgentToolCallStatus" + } + ], + "description": "Current status of the collab tool call." + }, + "tool": { + "allOf": [ + { + "$ref": "#/definitions/CollabAgentTool" + } + ], + "description": "Name of the collab tool that was invoked." + }, + "type": { + "enum": [ + "collabAgentToolCall" + ], + "title": "CollabAgentToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "agentsStates", + "id", + "receiverThreadIds", + "senderThreadId", + "status", + "tool", + "type" + ], + "title": "CollabAgentToolCallThreadItem", + "type": "object" + }, + { + "properties": { + "action": { + "anyOf": [ + { + "$ref": "#/definitions/WebSearchAction" + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "webSearch" + ], + "title": "WebSearchThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "query", + "type" + ], + "title": "WebSearchThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "imageView" + ], + "title": "ImageViewThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "path", + "type" + ], + "title": "ImageViewThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "review": { + "type": "string" + }, + "type": { + "enum": [ + "enteredReviewMode" + ], + "title": "EnteredReviewModeThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "review", + "type" + ], + "title": "EnteredReviewModeThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "review": { + "type": "string" + }, + "type": { + "enum": [ + "exitedReviewMode" + ], + "title": "ExitedReviewModeThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "review", + "type" + ], + "title": "ExitedReviewModeThreadItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "type": { + "enum": [ + "contextCompaction" + ], + "title": "ContextCompactionThreadItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ContextCompactionThreadItem", + "type": "object" + } + ] + }, + "ThreadListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "archived": { + "description": "Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.", + "type": [ + "boolean", + "null" + ] + }, + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "cwd": { + "description": "Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to a reasonable server-side value.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "modelProviders": { + "description": "Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "searchTerm": { + "description": "Optional substring filter for the extracted thread title.", + "type": [ + "string", + "null" + ] + }, + "sortKey": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadSortKey" + }, + { + "type": "null" + } + ], + "description": "Optional sort key; defaults to created_at." + }, + "sourceKinds": { + "description": "Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.", + "items": { + "$ref": "#/definitions/ThreadSourceKind" + }, + "type": [ + "array", + "null" + ] + } + }, + "title": "ThreadListParams", + "type": "object" + }, + "ThreadListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/Thread" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ThreadListResponse", + "type": "object" + }, + "ThreadLoadedListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cursor": { + "description": "Opaque pagination cursor returned by a previous call.", + "type": [ + "string", + "null" + ] + }, + "limit": { + "description": "Optional page size; defaults to no limit.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "title": "ThreadLoadedListParams", + "type": "object" + }, + "ThreadLoadedListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "data": { + "description": "Thread ids for sessions currently loaded in memory.", + "items": { + "type": "string" + }, + "type": "array" + }, + "nextCursor": { + "description": "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "title": "ThreadLoadedListResponse", + "type": "object" + }, + "ThreadNameUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "threadName": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "threadId" + ], + "title": "ThreadNameUpdatedNotification", + "type": "object" + }, + "ThreadReadParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "includeTurns": { + "default": false, + "description": "When true, include turns and their items from rollout history.", + "type": "boolean" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadReadParams", + "type": "object" + }, + "ThreadReadResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadReadResponse", + "type": "object" + }, + "ThreadRealtimeAudioChunk": { + "description": "EXPERIMENTAL - thread realtime audio chunk.", + "properties": { + "data": { + "type": "string" + }, + "numChannels": { + "format": "uint16", + "minimum": 0.0, + "type": "integer" + }, + "sampleRate": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "samplesPerChannel": { + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "data", + "numChannels", + "sampleRate" + ], + "type": "object" + }, + "ThreadRealtimeClosedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - emitted when thread realtime transport closes.", + "properties": { + "reason": { + "type": [ + "string", + "null" + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadRealtimeClosedNotification", + "type": "object" + }, + "ThreadRealtimeErrorNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - emitted when thread realtime encounters an error.", + "properties": { + "message": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "message", + "threadId" + ], + "title": "ThreadRealtimeErrorNotification", + "type": "object" + }, + "ThreadRealtimeItemAddedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.", + "properties": { + "item": true, + "threadId": { + "type": "string" + } + }, + "required": [ + "item", + "threadId" + ], + "title": "ThreadRealtimeItemAddedNotification", + "type": "object" + }, + "ThreadRealtimeOutputAudioDeltaNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - streamed output audio emitted by thread realtime.", + "properties": { + "audio": { + "$ref": "#/definitions/ThreadRealtimeAudioChunk" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "audio", + "threadId" + ], + "title": "ThreadRealtimeOutputAudioDeltaNotification", + "type": "object" + }, + "ThreadRealtimeStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "EXPERIMENTAL - emitted when thread realtime startup is accepted.", + "properties": { + "sessionId": { + "type": [ + "string", + "null" + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadRealtimeStartedNotification", + "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\nThe precedence is: history > path > thread_id. If using history or path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "baseInstructions": { + "type": [ + "string", + "null" + ] + }, + "config": { + "additionalProperties": true, + "type": [ + "object", + "null" + ] + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "developerInstructions": { + "type": [ + "string", + "null" + ] + }, + "model": { + "description": "Configuration overrides for the resumed thread, if any.", + "type": [ + "string", + "null" + ] + }, + "modelProvider": { + "type": [ + "string", + "null" + ] + }, + "personality": { + "anyOf": [ + { + "$ref": "#/definitions/Personality" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadResumeParams", + "type": "object" + }, + "ThreadResumeResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "$ref": "#/definitions/AskForApproval" + }, + "cwd": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelProvider": { + "type": "string" + }, + "reasoningEffort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "$ref": "#/definitions/SandboxPolicy" + }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "approvalPolicy", + "cwd", + "model", + "modelProvider", + "sandbox", + "thread" + ], + "title": "ThreadResumeResponse", + "type": "object" + }, + "ThreadRollbackParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "numTurns": { + "description": "The number of turns to drop from the end of the thread. Must be >= 1.\n\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.", + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "numTurns", + "threadId" + ], + "title": "ThreadRollbackParams", + "type": "object" + }, + "ThreadRollbackResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "allOf": [ + { + "$ref": "#/definitions/Thread" + } + ], + "description": "The updated thread after applying the rollback, with `turns` populated.\n\nThe ThreadItems stored in each Turn are lossy since we explicitly do not persist all agent interactions, such as command executions. This is the same behavior as `thread/resume`." + } + }, + "required": [ + "thread" + ], + "title": "ThreadRollbackResponse", + "type": "object" + }, + "ThreadSetNameParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "name": { + "type": "string" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "name", + "threadId" + ], + "title": "ThreadSetNameParams", + "type": "object" + }, + "ThreadSetNameResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ThreadSetNameResponse", + "type": "object" + }, + "ThreadSortKey": { + "enum": [ + "created_at", + "updated_at" + ], + "type": "string" + }, + "ThreadSourceKind": { + "enum": [ + "cli", + "vscode", + "exec", + "appServer", + "subAgent", + "subAgentReview", + "subAgentCompact", + "subAgentThreadSpawn", + "subAgentOther", + "unknown" + ], + "type": "string" + }, + "ThreadStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ] + }, + "baseInstructions": { + "type": [ + "string", + "null" + ] + }, + "config": { + "additionalProperties": true, + "type": [ + "object", + "null" + ] + }, + "cwd": { + "type": [ + "string", + "null" + ] + }, + "developerInstructions": { + "type": [ + "string", + "null" + ] + }, + "ephemeral": { + "type": [ + "boolean", + "null" + ] + }, + "model": { + "type": [ + "string", + "null" + ] + }, + "modelProvider": { + "type": [ + "string", + "null" + ] + }, + "personality": { + "anyOf": [ + { + "$ref": "#/definitions/Personality" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxMode" + }, + { + "type": "null" + } + ] + }, + "serviceName": { + "type": [ + "string", + "null" + ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + } + }, + "title": "ThreadStartParams", + "type": "object" + }, + "ThreadStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "$ref": "#/definitions/AskForApproval" + }, + "cwd": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelProvider": { + "type": "string" + }, + "reasoningEffort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ] + }, + "sandbox": { + "$ref": "#/definitions/SandboxPolicy" + }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "approvalPolicy", + "cwd", + "model", + "modelProvider", + "sandbox", + "thread" + ], + "title": "ThreadStartResponse", + "type": "object" + }, + "ThreadStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadStartedNotification", + "type": "object" + }, + "ThreadStatus": { + "oneOf": [ + { + "properties": { + "type": { + "enum": [ + "notLoaded" + ], + "title": "NotLoadedThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "NotLoadedThreadStatus", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "idle" + ], + "title": "IdleThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "IdleThreadStatus", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "systemError" + ], + "title": "SystemErrorThreadStatusType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SystemErrorThreadStatus", + "type": "object" + }, + { + "properties": { + "activeFlags": { + "items": { + "$ref": "#/definitions/ThreadActiveFlag" + }, + "type": "array" + }, + "type": { + "enum": [ + "active" + ], + "title": "ActiveThreadStatusType", + "type": "string" + } + }, + "required": [ + "activeFlags", + "type" + ], + "title": "ActiveThreadStatus", + "type": "object" + } + ] + }, + "ThreadStatusChangedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/ThreadStatus" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "status", + "threadId" + ], + "title": "ThreadStatusChangedNotification", + "type": "object" + }, + "ThreadTokenUsage": { + "properties": { + "last": { + "$ref": "#/definitions/TokenUsageBreakdown" + }, + "modelContextWindow": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "total": { + "$ref": "#/definitions/TokenUsageBreakdown" + } + }, + "required": [ + "last", + "total" + ], + "type": "object" + }, + "ThreadTokenUsageUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "tokenUsage": { + "$ref": "#/definitions/ThreadTokenUsage" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "threadId", + "tokenUsage", + "turnId" + ], + "title": "ThreadTokenUsageUpdatedNotification", + "type": "object" + }, + "ThreadUnarchiveParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnarchiveParams", + "type": "object" + }, + "ThreadUnarchiveResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "thread": { + "$ref": "#/definitions/Thread" + } + }, + "required": [ + "thread" + ], + "title": "ThreadUnarchiveResponse", + "type": "object" + }, + "ThreadUnarchivedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnarchivedNotification", + "type": "object" + }, + "ThreadUnsubscribeParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnsubscribeParams", + "type": "object" + }, + "ThreadUnsubscribeResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "status": { + "$ref": "#/definitions/ThreadUnsubscribeStatus" + } + }, + "required": [ + "status" + ], + "title": "ThreadUnsubscribeResponse", + "type": "object" + }, + "ThreadUnsubscribeStatus": { + "enum": [ + "notLoaded", + "notSubscribed", + "unsubscribed" + ], + "type": "string" + }, + "TokenUsage": { + "properties": { + "cached_input_tokens": { + "format": "int64", + "type": "integer" + }, + "input_tokens": { + "format": "int64", + "type": "integer" + }, + "output_tokens": { + "format": "int64", + "type": "integer" + }, + "reasoning_output_tokens": { + "format": "int64", + "type": "integer" + }, + "total_tokens": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cached_input_tokens", + "input_tokens", + "output_tokens", + "reasoning_output_tokens", + "total_tokens" + ], + "type": "object" + }, + "TokenUsageBreakdown": { + "properties": { + "cachedInputTokens": { + "format": "int64", + "type": "integer" + }, + "inputTokens": { + "format": "int64", + "type": "integer" + }, + "outputTokens": { + "format": "int64", + "type": "integer" + }, + "reasoningOutputTokens": { + "format": "int64", + "type": "integer" + }, + "totalTokens": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "cachedInputTokens", + "inputTokens", + "outputTokens", + "reasoningOutputTokens", + "totalTokens" + ], + "type": "object" + }, + "TokenUsageInfo": { + "properties": { + "last_token_usage": { + "$ref": "#/definitions/TokenUsage" + }, + "model_context_window": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "total_token_usage": { + "$ref": "#/definitions/TokenUsage" + } + }, + "required": [ + "last_token_usage", + "total_token_usage" + ], + "type": "object" + }, + "Tool": { + "description": "Definition for a tool the client can call.", + "properties": { + "_meta": true, + "annotations": true, + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "inputSchema": true, + "name": { + "type": "string" + }, + "outputSchema": true, + "title": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "inputSchema", + "name" + ], + "type": "object" + }, + "ToolsV2": { + "properties": { + "view_image": { + "type": [ + "boolean", + "null" + ] + }, + "web_search": { + "type": [ + "boolean", + "null" + ] + } + }, + "type": "object" + }, + "Turn": { + "properties": { + "error": { + "anyOf": [ + { + "$ref": "#/definitions/TurnError" + }, + { + "type": "null" + } + ], + "description": "Only populated when the Turn's status is failed." + }, + "id": { + "type": "string" + }, + "items": { + "description": "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + "items": { + "$ref": "#/definitions/ThreadItem" + }, + "type": "array" + }, + "status": { + "$ref": "#/definitions/TurnStatus" + } + }, + "required": [ + "id", + "items", + "status" + ], + "type": "object" + }, + "TurnAbortReason": { + "enum": [ + "interrupted", + "replaced", + "review_ended" + ], + "type": "string" + }, + "TurnCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "threadId", + "turn" + ], + "title": "TurnCompletedNotification", + "type": "object" + }, + "TurnDiffUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.", + "properties": { + "diff": { + "type": "string" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "diff", + "threadId", + "turnId" + ], + "title": "TurnDiffUpdatedNotification", + "type": "object" + }, + "TurnError": { + "properties": { + "additionalDetails": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "codexErrorInfo": { + "anyOf": [ + { + "$ref": "#/definitions/CodexErrorInfo" + }, + { + "type": "null" + } + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "TurnInterruptParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "threadId", + "turnId" + ], + "title": "TurnInterruptParams", + "type": "object" + }, + "TurnInterruptResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "TurnInterruptResponse", + "type": "object" + }, + "TurnItem": { + "oneOf": [ + { + "properties": { + "content": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "type": { + "enum": [ + "UserMessage" + ], + "title": "UserMessageTurnItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "UserMessageTurnItem", + "type": "object" + }, + { + "description": "Assistant-authored message payload used in turn-item streams.\n\n`phase` is optional because not all providers/models emit it. Consumers should use it when present, but retain legacy completion semantics when it is `None`.", + "properties": { + "content": { + "items": { + "$ref": "#/definitions/AgentMessageContent" + }, + "type": "array" + }, + "id": { + "type": "string" + }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "description": "Optional phase metadata carried through from `ResponseItem::Message`.\n\nThis is currently used by TUI rendering to distinguish mid-turn commentary from a final answer and avoid status-indicator jitter." + }, + "type": { + "enum": [ + "AgentMessage" + ], + "title": "AgentMessageTurnItemType", + "type": "string" + } + }, + "required": [ + "content", + "id", + "type" + ], + "title": "AgentMessageTurnItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "type": { + "enum": [ + "Plan" + ], + "title": "PlanTurnItemType", + "type": "string" + } + }, + "required": [ + "id", + "text", + "type" + ], + "title": "PlanTurnItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "raw_content": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "summary_text": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "enum": [ + "Reasoning" + ], + "title": "ReasoningTurnItemType", + "type": "string" + } + }, + "required": [ + "id", + "summary_text", + "type" + ], + "title": "ReasoningTurnItem", + "type": "object" + }, + { + "properties": { + "action": { + "$ref": "#/definitions/WebSearchAction" + }, + "id": { + "type": "string" + }, + "query": { + "type": "string" + }, + "type": { + "enum": [ + "WebSearch" + ], + "title": "WebSearchTurnItemType", + "type": "string" + } + }, + "required": [ + "action", + "id", + "query", + "type" + ], + "title": "WebSearchTurnItem", + "type": "object" + }, + { + "properties": { + "id": { + "type": "string" + }, + "type": { + "enum": [ + "ContextCompaction" + ], + "title": "ContextCompactionTurnItemType", + "type": "string" + } + }, + "required": [ + "id", + "type" + ], + "title": "ContextCompactionTurnItem", + "type": "object" + } + ] + }, + "TurnPlanStep": { + "properties": { + "status": { + "$ref": "#/definitions/TurnPlanStepStatus" + }, + "step": { + "type": "string" + } + }, + "required": [ + "status", + "step" + ], + "type": "object" + }, + "TurnPlanStepStatus": { + "enum": [ + "pending", + "inProgress", + "completed" + ], + "type": "string" + }, + "TurnPlanUpdatedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "explanation": { + "type": [ + "string", + "null" + ] + }, + "plan": { + "items": { + "$ref": "#/definitions/TurnPlanStep" + }, + "type": "array" + }, + "threadId": { + "type": "string" + }, + "turnId": { + "type": "string" + } + }, + "required": [ + "plan", + "threadId", + "turnId" + ], + "title": "TurnPlanUpdatedNotification", + "type": "object" + }, + "TurnStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "approvalPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/AskForApproval" + }, + { + "type": "null" + } + ], + "description": "Override the approval policy for this turn and subsequent turns." + }, + "cwd": { + "description": "Override the working directory for this turn and subsequent turns.", + "type": [ + "string", + "null" + ] + }, + "effort": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningEffort" + }, + { + "type": "null" + } + ], + "description": "Override the reasoning effort for this turn and subsequent turns." + }, + "input": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "model": { + "description": "Override the model for this turn and subsequent turns.", + "type": [ + "string", + "null" + ] + }, + "outputSchema": { + "description": "Optional JSON Schema used to constrain the final assistant message for this turn." + }, + "personality": { + "anyOf": [ + { + "$ref": "#/definitions/Personality" + }, + { + "type": "null" + } + ], + "description": "Override the personality for this turn and subsequent turns." + }, + "sandboxPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/SandboxPolicy" + }, + { + "type": "null" + } + ], + "description": "Override the sandbox policy for this turn and subsequent turns." + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ], + "description": "Override the service tier for this turn and subsequent turns." + }, + "summary": { + "anyOf": [ + { + "$ref": "#/definitions/ReasoningSummary" + }, + { + "type": "null" + } + ], + "description": "Override the reasoning summary for this turn and subsequent turns." + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "input", + "threadId" + ], + "title": "TurnStartParams", + "type": "object" + }, + "TurnStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "turn" + ], + "title": "TurnStartResponse", + "type": "object" + }, + "TurnStartedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + }, + "turn": { + "$ref": "#/definitions/Turn" + } + }, + "required": [ + "threadId", + "turn" + ], + "title": "TurnStartedNotification", + "type": "object" + }, + "TurnStatus": { + "enum": [ + "completed", + "interrupted", + "failed", + "inProgress" + ], + "type": "string" + }, + "TurnSteerParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "expectedTurnId": { + "description": "Required active turn id precondition. The request fails when it does not match the currently active turn.", + "type": "string" + }, + "input": { + "items": { + "$ref": "#/definitions/UserInput" + }, + "type": "array" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "expectedTurnId", + "input", + "threadId" + ], + "title": "TurnSteerParams", + "type": "object" + }, + "TurnSteerResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "turnId": { + "type": "string" + } + }, + "required": [ + "turnId" + ], + "title": "TurnSteerResponse", + "type": "object" + }, + "UserInput": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "text_elements": { + "default": [], + "description": "UI-defined spans within `text` used to render or persist special elements.", + "items": { + "$ref": "#/definitions/TextElement" + }, + "type": "array" + }, + "type": { + "enum": [ + "text" + ], + "title": "TextUserInputType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "TextUserInput", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "image" + ], + "title": "ImageUserInputType", + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "type", + "url" + ], + "title": "ImageUserInput", + "type": "object" + }, + { + "properties": { + "path": { + "type": "string" + }, + "type": { + "enum": [ + "localImage" + ], + "title": "LocalImageUserInputType", + "type": "string" + } + }, + "required": [ + "path", + "type" + ], + "title": "LocalImageUserInput", + "type": "object" + }, + { + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "skill" + ], + "title": "SkillUserInputType", + "type": "string" + } + }, + "required": [ + "name", + "path", + "type" + ], + "title": "SkillUserInput", + "type": "object" + }, + { + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "enum": [ + "mention" + ], + "title": "MentionUserInputType", + "type": "string" + } + }, + "required": [ + "name", + "path", + "type" + ], + "title": "MentionUserInput", + "type": "object" + } + ] + }, + "Verbosity": { + "description": "Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.", + "enum": [ + "low", + "medium", + "high" + ], + "type": "string" + }, + "WebSearchAction": { + "oneOf": [ + { + "properties": { + "queries": { + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "query": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "search" + ], + "title": "SearchWebSearchActionType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SearchWebSearchAction", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "open_page" + ], + "title": "OpenPageWebSearchActionType", + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "type" + ], + "title": "OpenPageWebSearchAction", + "type": "object" + }, + { + "properties": { + "pattern": { + "type": [ + "string", + "null" + ] + }, + "type": { + "enum": [ + "find_in_page" + ], + "title": "FindInPageWebSearchActionType", + "type": "string" + }, + "url": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "type" + ], + "title": "FindInPageWebSearchAction", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "other" + ], + "title": "OtherWebSearchActionType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "OtherWebSearchAction", + "type": "object" + } + ] + }, + "WebSearchMode": { + "enum": [ + "disabled", + "cached", + "live" + ], + "type": "string" + }, + "WindowsSandboxSetupCompletedNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, + "mode": { + "$ref": "#/definitions/WindowsSandboxSetupMode" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "mode", + "success" + ], + "title": "WindowsSandboxSetupCompletedNotification", + "type": "object" + }, + "WindowsSandboxSetupMode": { + "enum": [ + "elevated", + "unelevated" + ], + "type": "string" + }, + "WindowsSandboxSetupStartParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "mode": { + "$ref": "#/definitions/WindowsSandboxSetupMode" + } + }, + "required": [ + "mode" + ], + "title": "WindowsSandboxSetupStartParams", + "type": "object" + }, + "WindowsSandboxSetupStartResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "started": { + "type": "boolean" + } + }, + "required": [ + "started" + ], + "title": "WindowsSandboxSetupStartResponse", + "type": "object" + }, + "WindowsWorldWritableWarningNotification": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "extraCount": { + "format": "uint", + "minimum": 0.0, + "type": "integer" + }, + "failedScan": { + "type": "boolean" + }, + "samplePaths": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "extraCount", + "failedScan", + "samplePaths" + ], + "title": "WindowsWorldWritableWarningNotification", + "type": "object" + }, + "WriteStatus": { + "enum": [ + "ok", + "okOverridden" + ], + "type": "string" + } + }, + "title": "CodexAppServerProtocolV2", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/AccountUpdatedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/AccountUpdatedNotification.json index d95d737060..8348b774ca 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/AccountUpdatedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/AccountUpdatedNotification.json @@ -26,6 +26,20 @@ "type": "string" } ] + }, + "PlanType": { + "enum": [ + "free", + "go", + "plus", + "pro", + "team", + "business", + "enterprise", + "edu", + "unknown" + ], + "type": "string" } }, "properties": { @@ -38,6 +52,16 @@ "type": "null" } ] + }, + "planType": { + "anyOf": [ + { + "$ref": "#/definitions/PlanType" + }, + { + "type": "null" + } + ] } }, "title": "AccountUpdatedNotification", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index 4511515d17..626db8daeb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -323,6 +323,16 @@ } ] }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "tools": { "anyOf": [ { @@ -608,6 +618,16 @@ } ] }, + "service_tier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "web_search": { "anyOf": [ { @@ -685,6 +705,12 @@ }, "type": "object" }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "ToolsV2": { "properties": { "view_image": { 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 98d8a631e9..c8824f560e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json @@ -185,6 +185,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -633,6 +685,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { 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 ee10e470e0..04dbc07389 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json @@ -185,6 +185,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -633,6 +685,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json index 2afa018dc5..4023f76b51 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json @@ -22,6 +22,16 @@ }, "Model": { "properties": { + "availabilityNux": { + "anyOf": [ + { + "$ref": "#/definitions/ModelAvailabilityNux" + }, + { + "type": "null" + } + ] + }, "defaultReasoningEffort": { "$ref": "#/definitions/ReasoningEffort" }, @@ -68,6 +78,16 @@ "string", "null" ] + }, + "upgradeInfo": { + "anyOf": [ + { + "$ref": "#/definitions/ModelUpgradeInfo" + }, + { + "type": "null" + } + ] } }, "required": [ @@ -82,6 +102,46 @@ ], "type": "object" }, + "ModelAvailabilityNux": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, + "ModelUpgradeInfo": { + "properties": { + "migrationMarkdown": { + "type": [ + "string", + "null" + ] + }, + "model": { + "type": "string" + }, + "modelLink": { + "type": [ + "string", + "null" + ] + }, + "upgradeCopy": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "model" + ], + "type": "object" + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json index 748eeaab46..4717ff266b 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json @@ -565,7 +565,7 @@ "type": "string" }, "output": { - "type": "string" + "$ref": "#/definitions/FunctionCallOutputPayload" }, "type": { "enum": [ 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 760477095f..61449aa785 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -747,6 +799,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ServerRequestResolvedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ServerRequestResolvedNotification.json new file mode 100644 index 0000000000..18a5e76079 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ServerRequestResolvedNotification.json @@ -0,0 +1,30 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "RequestId": { + "anyOf": [ + { + "type": "string" + }, + { + "format": "int64", + "type": "integer" + } + ] + } + }, + "properties": { + "requestId": { + "$ref": "#/definitions/RequestId" + }, + "threadId": { + "type": "string" + } + }, + "required": [ + "requestId", + "threadId" + ], + "title": "ServerRequestResolvedNotification", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/SkillRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadClosedNotification.json similarity index 52% rename from codex-rs/app-server-protocol/schema/json/SkillRequestApprovalParams.json rename to codex-rs/app-server-protocol/schema/json/v2/ThreadClosedNotification.json index eebe6570b2..13e7f57748 100644 --- a/codex-rs/app-server-protocol/schema/json/SkillRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadClosedNotification.json @@ -1,17 +1,13 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { - "itemId": { - "type": "string" - }, - "skillName": { + "threadId": { "type": "string" } }, "required": [ - "itemId", - "skillName" + "threadId" ], - "title": "SkillRequestApprovalParams", + "title": "ThreadClosedNotification", "type": "object" } \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json index 2b832d5bf1..ff0bf3f044 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json @@ -50,6 +50,12 @@ "danger-full-access" ], "type": "string" + }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" } }, "description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", @@ -112,6 +118,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } 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 71f9da2f3b..3e4dca5b1c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -345,6 +345,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -686,6 +738,12 @@ } ] }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "SessionSource": { "oneOf": [ { @@ -830,6 +888,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -899,6 +961,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -1207,6 +1270,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { @@ -1796,6 +1912,16 @@ "sandbox": { "$ref": "#/definitions/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/Thread" } 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 5907d13cea..2cf3b940f3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -603,6 +655,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -672,6 +728,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -980,6 +1037,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { 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 9944457c3e..b2398692fd 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -603,6 +655,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -672,6 +728,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -980,6 +1037,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { 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 29d6fbc6d7..353bda693d 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -615,7 +615,7 @@ "type": "string" }, "output": { - "type": "string" + "$ref": "#/definitions/FunctionCallOutputPayload" }, "type": { "enum": [ @@ -738,6 +738,12 @@ ], "type": "string" }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "WebSearchAction": { "oneOf": [ { @@ -910,6 +916,23 @@ } ] }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] + }, "threadId": { "type": "string" } 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 7778773a16..d9fbc0d02c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -345,6 +345,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -686,6 +738,12 @@ } ] }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "SessionSource": { "oneOf": [ { @@ -830,6 +888,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -899,6 +961,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -1207,6 +1270,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { @@ -1796,6 +1912,16 @@ "sandbox": { "$ref": "#/definitions/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/Thread" } 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 c4bcdf7092..4ac54973de 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -603,6 +655,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -672,6 +728,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -980,6 +1037,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json index 5f2dda11a1..311b7b40cd 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -75,6 +75,12 @@ "danger-full-access" ], "type": "string" + }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" } }, "properties": { @@ -156,6 +162,23 @@ "string", "null" ] + }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ] } }, "title": "ThreadStartParams", 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 6b3d2ebc58..ee8b384998 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -345,6 +345,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -686,6 +738,12 @@ } ] }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "SessionSource": { "oneOf": [ { @@ -830,6 +888,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -899,6 +961,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -1207,6 +1270,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { @@ -1796,6 +1912,16 @@ "sandbox": { "$ref": "#/definitions/SandboxPolicy" }, + "serviceTier": { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, "thread": { "$ref": "#/definitions/Thread" } 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 2fbd9538f3..c46d4d7bb0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -603,6 +655,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -672,6 +728,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -980,6 +1037,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { 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 df3e7beee5..eabd614028 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -603,6 +655,10 @@ "description": "Working directory captured for the thread.", "type": "string" }, + "ephemeral": { + "description": "Whether the thread is ephemeral and should not be materialized on disk.", + "type": "boolean" + }, "gitInfo": { "anyOf": [ { @@ -672,6 +728,7 @@ "cliVersion", "createdAt", "cwd", + "ephemeral", "id", "modelProvider", "preview", @@ -980,6 +1037,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnsubscribeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnsubscribeParams.json new file mode 100644 index 0000000000..dec3670cc2 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnsubscribeParams.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadUnsubscribeParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnsubscribeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnsubscribeResponse.json new file mode 100644 index 0000000000..2e545dbf9f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnsubscribeResponse.json @@ -0,0 +1,23 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadUnsubscribeStatus": { + "enum": [ + "notLoaded", + "notSubscribed", + "unsubscribed" + ], + "type": "string" + } + }, + "properties": { + "status": { + "$ref": "#/definitions/ThreadUnsubscribeStatus" + } + }, + "required": [ + "status" + ], + "title": "ThreadUnsubscribeResponse", + "type": "object" +} \ No newline at end of file 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 2c8eec7f90..84bb60c8e8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -747,6 +799,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { 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 bc15473cc0..0a769c3525 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -299,6 +299,12 @@ } ] }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "Settings": { "description": "Settings for a collaboration mode.", "properties": { @@ -539,6 +545,24 @@ ], "description": "Override the sandbox policy for this turn and subsequent turns." }, + "serviceTier": { + "anyOf": [ + { + "anyOf": [ + { + "$ref": "#/definitions/ServiceTier" + }, + { + "type": "null" + } + ] + }, + { + "type": "null" + } + ], + "description": "Override the service tier for this turn and subsequent turns." + }, "summary": { "anyOf": [ { 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 5585cd455a..863814e1b4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -747,6 +799,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { 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 4462c314d2..aba5d973ab 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json @@ -299,6 +299,58 @@ ], "type": "string" }, + "DynamicToolCallOutputContentItem": { + "oneOf": [ + { + "properties": { + "text": { + "type": "string" + }, + "type": { + "enum": [ + "inputText" + ], + "title": "InputTextDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "title": "InputTextDynamicToolCallOutputContentItem", + "type": "object" + }, + { + "properties": { + "imageUrl": { + "type": "string" + }, + "type": { + "enum": [ + "inputImage" + ], + "title": "InputImageDynamicToolCallOutputContentItemType", + "type": "string" + } + }, + "required": [ + "imageUrl", + "type" + ], + "title": "InputImageDynamicToolCallOutputContentItem", + "type": "object" + } + ] + }, + "DynamicToolCallStatus": { + "enum": [ + "inProgress", + "completed", + "failed" + ], + "type": "string" + }, "FileUpdateChange": { "properties": { "diff": { @@ -747,6 +799,59 @@ "title": "McpToolCallThreadItem", "type": "object" }, + { + "properties": { + "arguments": true, + "contentItems": { + "items": { + "$ref": "#/definitions/DynamicToolCallOutputContentItem" + }, + "type": [ + "array", + "null" + ] + }, + "durationMs": { + "description": "The duration of the dynamic tool call in milliseconds.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "id": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/DynamicToolCallStatus" + }, + "success": { + "type": [ + "boolean", + "null" + ] + }, + "tool": { + "type": "string" + }, + "type": { + "enum": [ + "dynamicToolCall" + ], + "title": "DynamicToolCallThreadItemType", + "type": "string" + } + }, + "required": [ + "arguments", + "id", + "status", + "tool", + "type" + ], + "title": "DynamicToolCallThreadItem", + "type": "object" + }, { "properties": { "agentsStates": { diff --git a/codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts b/codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts deleted file mode 100644 index 17cb442fe0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/AuthStatusChangeNotification.ts +++ /dev/null @@ -1,9 +0,0 @@ -// 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 { AuthMode } from "./AuthMode"; - -/** - * Deprecated notification. Use AccountUpdatedNotification instead. - */ -export type AuthStatusChangeNotification = { authMethod: AuthMode | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index 4e80690467..f6df83b6e4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -1,26 +1,12 @@ // 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 { AddConversationListenerParams } from "./AddConversationListenerParams"; -import type { ArchiveConversationParams } from "./ArchiveConversationParams"; -import type { CancelLoginChatGptParams } from "./CancelLoginChatGptParams"; -import type { ExecOneOffCommandParams } from "./ExecOneOffCommandParams"; -import type { ForkConversationParams } from "./ForkConversationParams"; import type { FuzzyFileSearchParams } from "./FuzzyFileSearchParams"; import type { GetAuthStatusParams } from "./GetAuthStatusParams"; import type { GetConversationSummaryParams } from "./GetConversationSummaryParams"; import type { GitDiffToRemoteParams } from "./GitDiffToRemoteParams"; import type { InitializeParams } from "./InitializeParams"; -import type { InterruptConversationParams } from "./InterruptConversationParams"; -import type { ListConversationsParams } from "./ListConversationsParams"; -import type { LoginApiKeyParams } from "./LoginApiKeyParams"; -import type { NewConversationParams } from "./NewConversationParams"; -import type { RemoveConversationListenerParams } from "./RemoveConversationListenerParams"; import type { RequestId } from "./RequestId"; -import type { ResumeConversationParams } from "./ResumeConversationParams"; -import type { SendUserMessageParams } from "./SendUserMessageParams"; -import type { SendUserTurnParams } from "./SendUserTurnParams"; -import type { SetDefaultModelParams } from "./SetDefaultModelParams"; import type { AppsListParams } from "./v2/AppsListParams"; import type { CancelLoginAccountParams } from "./v2/CancelLoginAccountParams"; import type { CommandExecParams } from "./v2/CommandExecParams"; @@ -52,6 +38,7 @@ import type { ThreadRollbackParams } from "./v2/ThreadRollbackParams"; import type { ThreadSetNameParams } from "./v2/ThreadSetNameParams"; import type { ThreadStartParams } from "./v2/ThreadStartParams"; import type { ThreadUnarchiveParams } from "./v2/ThreadUnarchiveParams"; +import type { ThreadUnsubscribeParams } from "./v2/ThreadUnsubscribeParams"; import type { TurnInterruptParams } from "./v2/TurnInterruptParams"; import type { TurnStartParams } from "./v2/TurnStartParams"; import type { TurnSteerParams } from "./v2/TurnSteerParams"; @@ -60,4 +47,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/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "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": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/remote/list", id: RequestId, params: SkillsRemoteReadParams, } | { "method": "skills/remote/export", id: RequestId, params: SkillsRemoteWriteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "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": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "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": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "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": "newConversation", id: RequestId, params: NewConversationParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "listConversations", id: RequestId, params: ListConversationsParams, } | { "method": "resumeConversation", id: RequestId, params: ResumeConversationParams, } | { "method": "forkConversation", id: RequestId, params: ForkConversationParams, } | { "method": "archiveConversation", id: RequestId, params: ArchiveConversationParams, } | { "method": "sendUserMessage", id: RequestId, params: SendUserMessageParams, } | { "method": "sendUserTurn", id: RequestId, params: SendUserTurnParams, } | { "method": "interruptConversation", id: RequestId, params: InterruptConversationParams, } | { "method": "addConversationListener", id: RequestId, params: AddConversationListenerParams, } | { "method": "removeConversationListener", id: RequestId, params: RemoveConversationListenerParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "loginApiKey", id: RequestId, params: LoginApiKeyParams, } | { "method": "loginChatGpt", id: RequestId, params: undefined, } | { "method": "cancelLoginChatGpt", id: RequestId, params: CancelLoginChatGptParams, } | { "method": "logoutChatGpt", id: RequestId, params: undefined, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "getUserSavedConfig", id: RequestId, params: undefined, } | { "method": "setDefaultModel", id: RequestId, params: SetDefaultModelParams, } | { "method": "getUserAgent", id: RequestId, params: undefined, } | { "method": "userInfo", id: RequestId, params: undefined, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, } | { "method": "execOneOffCommand", id: RequestId, params: ExecOneOffCommandParams, }; +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/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "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": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/remote/list", id: RequestId, params: SkillsRemoteReadParams, } | { "method": "skills/remote/export", id: RequestId, params: SkillsRemoteWriteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "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": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "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": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "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/CollaborationModeMask.ts b/codex-rs/app-server-protocol/schema/typescript/CollaborationModeMask.ts deleted file mode 100644 index 05902676d7..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/CollaborationModeMask.ts +++ /dev/null @@ -1,11 +0,0 @@ -// 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 { ModeKind } from "./ModeKind"; -import type { ReasoningEffort } from "./ReasoningEffort"; - -/** - * A mask for collaboration mode settings, allowing partial updates. - * All fields except `name` are optional, enabling selective updates. - */ -export type CollaborationModeMask = { name: string, mode: ModeKind | null, model: string | null, reasoning_effort: ReasoningEffort | null | null, developer_instructions: string | null | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts similarity index 55% rename from codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts rename to codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.ts index 3d257a1c5e..8f432109d1 100644 --- a/codex-rs/app-server-protocol/schema/typescript/UserInfoResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallOutputContentItem.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 UserInfoResponse = { allegedUserEmail: string | null, }; +export type DynamicToolCallOutputContentItem = { "type": "inputText", text: string, } | { "type": "inputImage", imageUrl: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts new file mode 100644 index 0000000000..442c0ce6f3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/DynamicToolCallResponseEvent.ts @@ -0,0 +1,39 @@ +// 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 { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; +import type { JsonValue } from "./serde_json/JsonValue"; + +export type DynamicToolCallResponseEvent = { +/** + * Identifier for the corresponding DynamicToolCallRequest. + */ +call_id: string, +/** + * Turn ID that this dynamic tool call belongs to. + */ +turn_id: string, +/** + * Dynamic tool name. + */ +tool: string, +/** + * Dynamic tool call arguments. + */ +arguments: JsonValue, +/** + * Dynamic tool response content items. + */ +content_items: Array, +/** + * Whether the tool call succeeded. + */ +success: boolean, +/** + * Optional error text when the tool call failed before producing a response. + */ +error: string | null, +/** + * The duration of the dynamic tool call. + */ +duration: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts index cc1009bfd5..5ccbe1e697 100644 --- a/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts +++ b/codex-rs/app-server-protocol/schema/typescript/EventMsg.ts @@ -24,6 +24,7 @@ import type { CollabWaitingEndEvent } from "./CollabWaitingEndEvent"; import type { ContextCompactedEvent } from "./ContextCompactedEvent"; import type { DeprecationNoticeEvent } from "./DeprecationNoticeEvent"; import type { DynamicToolCallRequest } from "./DynamicToolCallRequest"; +import type { DynamicToolCallResponseEvent } from "./DynamicToolCallResponseEvent"; import type { ElicitationRequestEvent } from "./ElicitationRequestEvent"; import type { ErrorEvent } from "./ErrorEvent"; import type { ExecApprovalRequestEvent } from "./ExecApprovalRequestEvent"; @@ -56,7 +57,6 @@ import type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; import type { RequestUserInputEvent } from "./RequestUserInputEvent"; import type { ReviewRequest } from "./ReviewRequest"; import type { SessionConfiguredEvent } from "./SessionConfiguredEvent"; -import type { SkillRequestApprovalEvent } from "./SkillRequestApprovalEvent"; import type { StreamErrorEvent } from "./StreamErrorEvent"; import type { TerminalInteractionEvent } from "./TerminalInteractionEvent"; import type { ThreadNameUpdatedEvent } from "./ThreadNameUpdatedEvent"; @@ -79,4 +79,4 @@ import type { WebSearchEndEvent } from "./WebSearchEndEvent"; * Response event from the agent * NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen. */ -export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "realtime_conversation_started" } & RealtimeConversationStartedEvent | { "type": "realtime_conversation_realtime" } & RealtimeConversationRealtimeEvent | { "type": "realtime_conversation_closed" } & RealtimeConversationClosedEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "skill_request_approval" } & SkillRequestApprovalEvent | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent; +export type EventMsg = { "type": "error" } & ErrorEvent | { "type": "warning" } & WarningEvent | { "type": "realtime_conversation_started" } & RealtimeConversationStartedEvent | { "type": "realtime_conversation_realtime" } & RealtimeConversationRealtimeEvent | { "type": "realtime_conversation_closed" } & RealtimeConversationClosedEvent | { "type": "model_reroute" } & ModelRerouteEvent | { "type": "context_compacted" } & ContextCompactedEvent | { "type": "thread_rolled_back" } & ThreadRolledBackEvent | { "type": "task_started" } & TurnStartedEvent | { "type": "task_complete" } & TurnCompleteEvent | { "type": "token_count" } & TokenCountEvent | { "type": "agent_message" } & AgentMessageEvent | { "type": "user_message" } & UserMessageEvent | { "type": "agent_message_delta" } & AgentMessageDeltaEvent | { "type": "agent_reasoning" } & AgentReasoningEvent | { "type": "agent_reasoning_delta" } & AgentReasoningDeltaEvent | { "type": "agent_reasoning_raw_content" } & AgentReasoningRawContentEvent | { "type": "agent_reasoning_raw_content_delta" } & AgentReasoningRawContentDeltaEvent | { "type": "agent_reasoning_section_break" } & AgentReasoningSectionBreakEvent | { "type": "session_configured" } & SessionConfiguredEvent | { "type": "thread_name_updated" } & ThreadNameUpdatedEvent | { "type": "mcp_startup_update" } & McpStartupUpdateEvent | { "type": "mcp_startup_complete" } & McpStartupCompleteEvent | { "type": "mcp_tool_call_begin" } & McpToolCallBeginEvent | { "type": "mcp_tool_call_end" } & McpToolCallEndEvent | { "type": "web_search_begin" } & WebSearchBeginEvent | { "type": "web_search_end" } & WebSearchEndEvent | { "type": "exec_command_begin" } & ExecCommandBeginEvent | { "type": "exec_command_output_delta" } & ExecCommandOutputDeltaEvent | { "type": "terminal_interaction" } & TerminalInteractionEvent | { "type": "exec_command_end" } & ExecCommandEndEvent | { "type": "view_image_tool_call" } & ViewImageToolCallEvent | { "type": "exec_approval_request" } & ExecApprovalRequestEvent | { "type": "request_user_input" } & RequestUserInputEvent | { "type": "dynamic_tool_call_request" } & DynamicToolCallRequest | { "type": "dynamic_tool_call_response" } & DynamicToolCallResponseEvent | { "type": "elicitation_request" } & ElicitationRequestEvent | { "type": "apply_patch_approval_request" } & ApplyPatchApprovalRequestEvent | { "type": "deprecation_notice" } & DeprecationNoticeEvent | { "type": "background_event" } & BackgroundEventEvent | { "type": "undo_started" } & UndoStartedEvent | { "type": "undo_completed" } & UndoCompletedEvent | { "type": "stream_error" } & StreamErrorEvent | { "type": "patch_apply_begin" } & PatchApplyBeginEvent | { "type": "patch_apply_end" } & PatchApplyEndEvent | { "type": "turn_diff" } & TurnDiffEvent | { "type": "get_history_entry_response" } & GetHistoryEntryResponseEvent | { "type": "mcp_list_tools_response" } & McpListToolsResponseEvent | { "type": "list_custom_prompts_response" } & ListCustomPromptsResponseEvent | { "type": "list_skills_response" } & ListSkillsResponseEvent | { "type": "list_remote_skills_response" } & ListRemoteSkillsResponseEvent | { "type": "remote_skill_downloaded" } & RemoteSkillDownloadedEvent | { "type": "skills_update_available" } | { "type": "plan_update" } & UpdatePlanArgs | { "type": "turn_aborted" } & TurnAbortedEvent | { "type": "shutdown_complete" } | { "type": "entered_review_mode" } & ReviewRequest | { "type": "exited_review_mode" } & ExitedReviewModeEvent | { "type": "raw_response_item" } & RawResponseItemEvent | { "type": "item_started" } & ItemStartedEvent | { "type": "item_completed" } & ItemCompletedEvent | { "type": "agent_message_content_delta" } & AgentMessageContentDeltaEvent | { "type": "plan_delta" } & PlanDeltaEvent | { "type": "reasoning_content_delta" } & ReasoningContentDeltaEvent | { "type": "reasoning_raw_content_delta" } & ReasoningRawContentDeltaEvent | { "type": "collab_agent_spawn_begin" } & CollabAgentSpawnBeginEvent | { "type": "collab_agent_spawn_end" } & CollabAgentSpawnEndEvent | { "type": "collab_agent_interaction_begin" } & CollabAgentInteractionBeginEvent | { "type": "collab_agent_interaction_end" } & CollabAgentInteractionEndEvent | { "type": "collab_waiting_begin" } & CollabWaitingBeginEvent | { "type": "collab_waiting_end" } & CollabWaitingEndEvent | { "type": "collab_close_begin" } & CollabCloseBeginEvent | { "type": "collab_close_end" } & CollabCloseEndEvent | { "type": "collab_resume_begin" } & CollabResumeBeginEvent | { "type": "collab_resume_end" } & CollabResumeEndEvent; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts b/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts index 5144dab6e6..cc13400900 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ExecApprovalRequestEvent.ts @@ -6,6 +6,7 @@ import type { NetworkApprovalContext } from "./NetworkApprovalContext"; import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; import type { ParsedCommand } from "./ParsedCommand"; import type { PermissionProfile } from "./PermissionProfile"; +import type { ReviewDecision } from "./ReviewDecision"; export type ExecApprovalRequestEvent = { /** @@ -51,4 +52,11 @@ proposed_network_policy_amendments?: Array, /** * Optional additional filesystem permissions requested for this command. */ -additional_permissions?: PermissionProfile, parsed_cmd: Array, }; +additional_permissions?: PermissionProfile, +/** + * Ordered list of decisions the client may present for this prompt. + * + * When absent, clients should derive the legacy default set from the + * other fields on this request. + */ +available_decisions?: Array, parsed_cmd: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts b/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts deleted file mode 100644 index ca28ad775c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { SandboxPolicy } from "./SandboxPolicy"; - -export type ExecOneOffCommandParams = { command: Array, timeoutMs: bigint | null, cwd: string | null, sandboxPolicy: SandboxPolicy | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts deleted file mode 100644 index ff43ec4ca2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ExecOneOffCommandResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 ExecOneOffCommandResponse = { exitCode: number, stdout: string, stderr: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts index 9e03768df3..aedf84de80 100644 --- a/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts +++ b/codex-rs/app-server-protocol/schema/typescript/FileSystemPermissions.ts @@ -1,5 +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 FileSystemPermissions = { read: Array | null, write: Array | null, }; +export type FileSystemPermissions = { read: Array | null, write: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts deleted file mode 100644 index 4ca548fbff..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ForkConversationParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// 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 { NewConversationParams } from "./NewConversationParams"; -import type { ThreadId } from "./ThreadId"; - -export type ForkConversationParams = { path: string | null, conversationId: ThreadId | null, overrides: NewConversationParams | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts deleted file mode 100644 index 80d6e7947c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ForkConversationResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -// 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 { EventMsg } from "./EventMsg"; -import type { ThreadId } from "./ThreadId"; - -export type ForkConversationResponse = { conversationId: ThreadId, model: string, initialMessages: Array | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts b/codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts deleted file mode 100644 index f8dcf2e67c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/GetUserSavedConfigResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { UserSavedConfig } from "./UserSavedConfig"; - -export type GetUserSavedConfigResponse = { config: UserSavedConfig, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InputItem.ts b/codex-rs/app-server-protocol/schema/typescript/InputItem.ts deleted file mode 100644 index 3ac72d31d8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/InputItem.ts +++ /dev/null @@ -1,10 +0,0 @@ -// 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 { TextElement } from "./TextElement"; - -export type InputItem = { "type": "text", "data": { text: string, -/** - * UI-defined spans within `text` used to render or persist special elements. - */ -text_elements: Array, } } | { "type": "image", "data": { image_url: string, } } | { "type": "localImage", "data": { path: string, } }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts deleted file mode 100644 index 8db162c97c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { ThreadId } from "./ThreadId"; - -export type InterruptConversationParams = { conversationId: ThreadId, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts deleted file mode 100644 index 375604eef3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/InterruptConversationResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { TurnAbortReason } from "./TurnAbortReason"; - -export type InterruptConversationResponse = { abortReason: TurnAbortReason, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts b/codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts deleted file mode 100644 index 27c9f3172a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListConversationsParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 ListConversationsParams = { pageSize: number | null, cursor: string | null, modelProviders: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts deleted file mode 100644 index 0e26443a5f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ListConversationsResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { ConversationSummary } from "./ConversationSummary"; - -export type ListConversationsResponse = { items: Array, nextCursor: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts b/codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts deleted file mode 100644 index 82c07bfa2d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptCompleteNotification.ts +++ /dev/null @@ -1,8 +0,0 @@ -// 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. - -/** - * Deprecated in favor of AccountLoginCompletedNotification. - */ -export type LoginChatGptCompleteNotification = { loginId: string, success: boolean, error: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts b/codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts deleted file mode 100644 index 4147280117..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LoginChatGptResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 LoginChatGptResponse = { loginId: string, authUrl: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts b/codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts deleted file mode 100644 index ad5dbd9105..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/LogoutChatGptResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 LogoutChatGptResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts deleted file mode 100644 index e1113c27e2..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NewConversationParams.ts +++ /dev/null @@ -1,8 +0,0 @@ -// 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 { AskForApproval } from "./AskForApproval"; -import type { SandboxMode } from "./SandboxMode"; -import type { JsonValue } from "./serde_json/JsonValue"; - -export type NewConversationParams = { model: string | null, modelProvider: string | null, profile: string | null, cwd: string | null, approvalPolicy: AskForApproval | null, sandbox: SandboxMode | null, config: { [key in string]?: JsonValue } | null, baseInstructions: string | null, developerInstructions: string | null, compactPrompt: string | null, includeApplyPatchTool: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts deleted file mode 100644 index 608c2ac110..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/NewConversationResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -// 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 { ReasoningEffort } from "./ReasoningEffort"; -import type { ThreadId } from "./ThreadId"; - -export type NewConversationResponse = { conversationId: ThreadId, model: string, reasoningEffort: ReasoningEffort | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/Profile.ts b/codex-rs/app-server-protocol/schema/typescript/Profile.ts deleted file mode 100644 index 53d16e4a33..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/Profile.ts +++ /dev/null @@ -1,9 +0,0 @@ -// 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 { AskForApproval } from "./AskForApproval"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ReasoningSummary } from "./ReasoningSummary"; -import type { Verbosity } from "./Verbosity"; - -export type Profile = { model: string | null, modelProvider: string | null, approvalPolicy: AskForApproval | null, modelReasoningEffort: ReasoningEffort | null, modelReasoningSummary: ReasoningSummary | null, modelVerbosity: Verbosity | null, chatgptBaseUrl: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts index 6297beebef..8286f34cad 100644 --- a/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeEvent.ts @@ -2,6 +2,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { RealtimeAudioFrame } from "./RealtimeAudioFrame"; +import type { RealtimeHandoffRequested } from "./RealtimeHandoffRequested"; import type { JsonValue } from "./serde_json/JsonValue"; -export type RealtimeEvent = { "SessionCreated": { session_id: string, } } | { "SessionUpdated": { backend_prompt: string | null, } } | { "AudioOut": RealtimeAudioFrame } | { "ConversationItemAdded": JsonValue } | { "Error": string }; +export type RealtimeEvent = { "SessionUpdated": { session_id: string, instructions: string | null, } } | { "AudioOut": RealtimeAudioFrame } | { "ConversationItemAdded": JsonValue } | { "ConversationItemDone": { item_id: string, } } | { "HandoffRequested": RealtimeHandoffRequested } | { "Error": string }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts similarity index 68% rename from codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts rename to codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.ts index 004e6f8ea2..39b77cfdf1 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffMessage.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 CancelLoginChatGptResponse = Record; +export type RealtimeHandoffMessage = { role: string, text: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.ts new file mode 100644 index 0000000000..f3426706aa --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/RealtimeHandoffRequested.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 { RealtimeHandoffMessage } from "./RealtimeHandoffMessage"; + +export type RealtimeHandoffRequested = { handoff_id: string, item_id: string, input_transcript: string, messages: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts b/codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts deleted file mode 100644 index e9628b6341..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationListenerParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 RemoveConversationListenerParams = { subscriptionId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts b/codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts deleted file mode 100644 index 8053d7e4b4..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/RemoveConversationSubscriptionResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 RemoveConversationSubscriptionResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts b/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts index 611c7fb22d..dd7621f01d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts @@ -15,4 +15,4 @@ export type ResponseItem = { "type": "message", role: string, content: Array | null, overrides: NewConversationParams | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts deleted file mode 100644 index 1af5b68599..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/ResumeConversationResponse.ts +++ /dev/null @@ -1,7 +0,0 @@ -// 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 { EventMsg } from "./EventMsg"; -import type { ThreadId } from "./ThreadId"; - -export type ResumeConversationResponse = { conversationId: ThreadId, model: string, initialMessages: Array | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts deleted file mode 100644 index b8cf4326b9..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SandboxMode.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SandboxMode = "read-only" | "workspace-write" | "danger-full-access"; diff --git a/codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts b/codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts deleted file mode 100644 index 94139b0e5d..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SandboxSettings.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 SandboxSettings = { writableRoots: Array, networkAccess: boolean | null, excludeTmpdirEnvVar: boolean | null, excludeSlashTmp: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts deleted file mode 100644 index 6aee538eb0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageParams.ts +++ /dev/null @@ -1,7 +0,0 @@ -// 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 { InputItem } from "./InputItem"; -import type { ThreadId } from "./ThreadId"; - -export type SendUserMessageParams = { conversationId: ThreadId, items: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts deleted file mode 100644 index 1a03e043a6..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserMessageResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SendUserMessageResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts deleted file mode 100644 index dc4cfba8f5..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnParams.ts +++ /dev/null @@ -1,16 +0,0 @@ -// 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 { AskForApproval } from "./AskForApproval"; -import type { InputItem } from "./InputItem"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ReasoningSummary } from "./ReasoningSummary"; -import type { SandboxPolicy } from "./SandboxPolicy"; -import type { ThreadId } from "./ThreadId"; -import type { JsonValue } from "./serde_json/JsonValue"; - -export type SendUserTurnParams = { conversationId: ThreadId, items: Array, cwd: string, approvalPolicy: AskForApproval, sandboxPolicy: SandboxPolicy, model: string, effort: ReasoningEffort | null, summary: ReasoningSummary, -/** - * Optional JSON Schema used to constrain the final assistant message for this turn. - */ -outputSchema: JsonValue | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts b/codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts deleted file mode 100644 index cffd0ac398..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SendUserTurnResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SendUserTurnResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts index 92fecbfccd..d7f70d3558 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts @@ -1,11 +1,8 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { AuthStatusChangeNotification } from "./AuthStatusChangeNotification"; import type { FuzzyFileSearchSessionCompletedNotification } from "./FuzzyFileSearchSessionCompletedNotification"; import type { FuzzyFileSearchSessionUpdatedNotification } from "./FuzzyFileSearchSessionUpdatedNotification"; -import type { LoginChatGptCompleteNotification } from "./LoginChatGptCompleteNotification"; -import type { SessionConfiguredNotification } from "./SessionConfiguredNotification"; import type { AccountLoginCompletedNotification } from "./v2/AccountLoginCompletedNotification"; import type { AccountRateLimitsUpdatedNotification } from "./v2/AccountRateLimitsUpdatedNotification"; import type { AccountUpdatedNotification } from "./v2/AccountUpdatedNotification"; @@ -27,8 +24,10 @@ import type { RawResponseItemCompletedNotification } from "./v2/RawResponseItemC import type { ReasoningSummaryPartAddedNotification } from "./v2/ReasoningSummaryPartAddedNotification"; import type { ReasoningSummaryTextDeltaNotification } from "./v2/ReasoningSummaryTextDeltaNotification"; import type { ReasoningTextDeltaNotification } from "./v2/ReasoningTextDeltaNotification"; +import type { ServerRequestResolvedNotification } from "./v2/ServerRequestResolvedNotification"; import type { TerminalInteractionNotification } from "./v2/TerminalInteractionNotification"; import type { ThreadArchivedNotification } from "./v2/ThreadArchivedNotification"; +import type { ThreadClosedNotification } from "./v2/ThreadClosedNotification"; import type { ThreadNameUpdatedNotification } from "./v2/ThreadNameUpdatedNotification"; import type { ThreadRealtimeClosedNotification } from "./v2/ThreadRealtimeClosedNotification"; import type { ThreadRealtimeErrorNotification } from "./v2/ThreadRealtimeErrorNotification"; @@ -49,4 +48,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW /** * Notification sent from the server to the client. */ -export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification } | { "method": "authStatusChange", "params": AuthStatusChangeNotification } | { "method": "loginChatGptComplete", "params": LoginChatGptCompleteNotification } | { "method": "sessionConfigured", "params": SessionConfiguredNotification }; +export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts index 1f1bc2c77e..17c66959aa 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts @@ -8,10 +8,9 @@ import type { ChatgptAuthTokensRefreshParams } from "./v2/ChatgptAuthTokensRefre import type { CommandExecutionRequestApprovalParams } from "./v2/CommandExecutionRequestApprovalParams"; import type { DynamicToolCallParams } from "./v2/DynamicToolCallParams"; import type { FileChangeRequestApprovalParams } from "./v2/FileChangeRequestApprovalParams"; -import type { SkillRequestApprovalParams } from "./v2/SkillRequestApprovalParams"; import type { ToolRequestUserInputParams } from "./v2/ToolRequestUserInputParams"; /** * Request initiated from the server and sent to the client. */ -export type ServerRequest = { "method": "item/commandExecution/requestApproval", id: RequestId, params: CommandExecutionRequestApprovalParams, } | { "method": "item/fileChange/requestApproval", id: RequestId, params: FileChangeRequestApprovalParams, } | { "method": "item/tool/requestUserInput", id: RequestId, params: ToolRequestUserInputParams, } | { "method": "skill/requestApproval", id: RequestId, params: SkillRequestApprovalParams, } | { "method": "item/tool/call", id: RequestId, params: DynamicToolCallParams, } | { "method": "account/chatgptAuthTokens/refresh", id: RequestId, params: ChatgptAuthTokensRefreshParams, } | { "method": "applyPatchApproval", id: RequestId, params: ApplyPatchApprovalParams, } | { "method": "execCommandApproval", id: RequestId, params: ExecCommandApprovalParams, }; +export type ServerRequest = { "method": "item/commandExecution/requestApproval", id: RequestId, params: CommandExecutionRequestApprovalParams, } | { "method": "item/fileChange/requestApproval", id: RequestId, params: FileChangeRequestApprovalParams, } | { "method": "item/tool/requestUserInput", id: RequestId, params: ToolRequestUserInputParams, } | { "method": "item/tool/call", id: RequestId, params: DynamicToolCallParams, } | { "method": "account/chatgptAuthTokens/refresh", id: RequestId, params: ChatgptAuthTokensRefreshParams, } | { "method": "applyPatchApproval", id: RequestId, params: ApplyPatchApprovalParams, } | { "method": "execCommandApproval", id: RequestId, params: ExecCommandApprovalParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts b/codex-rs/app-server-protocol/schema/typescript/ServiceTier.ts similarity index 74% rename from codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts rename to codex-rs/app-server-protocol/schema/typescript/ServiceTier.ts index 3638553d3e..bb2b5103e6 100644 --- a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServiceTier.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 LoginApiKeyParams = { apiKey: string, }; +export type ServiceTier = "fast"; diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts index d964f44451..b4696a0e4c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredEvent.ts @@ -5,6 +5,7 @@ import type { AskForApproval } from "./AskForApproval"; import type { EventMsg } from "./EventMsg"; import type { ReasoningEffort } from "./ReasoningEffort"; import type { SandboxPolicy } from "./SandboxPolicy"; +import type { ServiceTier } from "./ServiceTier"; import type { SessionNetworkProxyRuntime } from "./SessionNetworkProxyRuntime"; import type { ThreadId } from "./ThreadId"; @@ -16,7 +17,7 @@ thread_name?: string, /** * Tell the client what model is being queried. */ -model: string, model_provider_id: string, +model: string, model_provider_id: string, service_tier: ServiceTier | null, /** * When to escalate for approval for execution */ diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts b/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts deleted file mode 100644 index 3dee74aa3a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SessionConfiguredNotification.ts +++ /dev/null @@ -1,8 +0,0 @@ -// 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 { EventMsg } from "./EventMsg"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ThreadId } from "./ThreadId"; - -export type SessionConfiguredNotification = { sessionId: ThreadId, model: string, reasoningEffort: ReasoningEffort | null, historyLogId: bigint, historyEntryCount: number, initialMessages: Array | null, rolloutPath: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts b/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts deleted file mode 100644 index b9e4e7d901..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelParams.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { ReasoningEffort } from "./ReasoningEffort"; - -export type SetDefaultModelParams = { model: string | null, reasoningEffort: ReasoningEffort | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts b/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts deleted file mode 100644 index 1639601e0c..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SetDefaultModelResponse.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SetDefaultModelResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/SkillRequestApprovalEvent.ts b/codex-rs/app-server-protocol/schema/typescript/SkillRequestApprovalEvent.ts deleted file mode 100644 index 6699eadac3..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/SkillRequestApprovalEvent.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SkillRequestApprovalEvent = { item_id: string, skill_name: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/TextElement.ts b/codex-rs/app-server-protocol/schema/typescript/TextElement.ts index 8841d00499..3dcd369d82 100644 --- a/codex-rs/app-server-protocol/schema/typescript/TextElement.ts +++ b/codex-rs/app-server-protocol/schema/typescript/TextElement.ts @@ -7,7 +7,7 @@ export type TextElement = { /** * Byte range in the parent `text` buffer that this element occupies. */ -byteRange: ByteRange, +byte_range: ByteRange, /** * Optional human-readable placeholder for the element, displayed in the UI. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/Tools.ts b/codex-rs/app-server-protocol/schema/typescript/Tools.ts deleted file mode 100644 index 0387022966..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/Tools.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 Tools = { webSearch: boolean | null, viewImage: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts b/codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts deleted file mode 100644 index e70107f31e..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/UserSavedConfig.ts +++ /dev/null @@ -1,14 +0,0 @@ -// 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 { AskForApproval } from "./AskForApproval"; -import type { ForcedLoginMethod } from "./ForcedLoginMethod"; -import type { Profile } from "./Profile"; -import type { ReasoningEffort } from "./ReasoningEffort"; -import type { ReasoningSummary } from "./ReasoningSummary"; -import type { SandboxMode } from "./SandboxMode"; -import type { SandboxSettings } from "./SandboxSettings"; -import type { Tools } from "./Tools"; -import type { Verbosity } from "./Verbosity"; - -export type UserSavedConfig = { approvalPolicy: AskForApproval | null, sandboxMode: SandboxMode | null, sandboxSettings: SandboxSettings | null, forcedChatgptWorkspaceId: string | null, forcedLoginMethod: ForcedLoginMethod | null, model: string | null, modelReasoningEffort: ReasoningEffort | null, modelReasoningSummary: ReasoningSummary | null, modelVerbosity: Verbosity | null, tools: Tools | null, profile: string | null, profiles: { [key in string]?: Profile }, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index cc323e963d..adaeb4c26c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -1,8 +1,6 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! export type { AbsolutePathBuf } from "./AbsolutePathBuf"; -export type { AddConversationListenerParams } from "./AddConversationListenerParams"; -export type { AddConversationSubscriptionResponse } from "./AddConversationSubscriptionResponse"; export type { AgentMessageContent } from "./AgentMessageContent"; export type { AgentMessageContentDeltaEvent } from "./AgentMessageContentDeltaEvent"; export type { AgentMessageDeltaEvent } from "./AgentMessageDeltaEvent"; @@ -17,16 +15,11 @@ export type { AgentStatus } from "./AgentStatus"; export type { ApplyPatchApprovalParams } from "./ApplyPatchApprovalParams"; export type { ApplyPatchApprovalRequestEvent } from "./ApplyPatchApprovalRequestEvent"; export type { ApplyPatchApprovalResponse } from "./ApplyPatchApprovalResponse"; -export type { ArchiveConversationParams } from "./ArchiveConversationParams"; -export type { ArchiveConversationResponse } from "./ArchiveConversationResponse"; export type { AskForApproval } from "./AskForApproval"; export type { AuthMode } from "./AuthMode"; -export type { AuthStatusChangeNotification } from "./AuthStatusChangeNotification"; export type { BackgroundEventEvent } from "./BackgroundEventEvent"; export type { ByteRange } from "./ByteRange"; export type { CallToolResult } from "./CallToolResult"; -export type { CancelLoginChatGptParams } from "./CancelLoginChatGptParams"; -export type { CancelLoginChatGptResponse } from "./CancelLoginChatGptResponse"; export type { ClientInfo } from "./ClientInfo"; export type { ClientNotification } from "./ClientNotification"; export type { ClientRequest } from "./ClientRequest"; @@ -44,7 +37,6 @@ export type { CollabResumeEndEvent } from "./CollabResumeEndEvent"; export type { CollabWaitingBeginEvent } from "./CollabWaitingBeginEvent"; export type { CollabWaitingEndEvent } from "./CollabWaitingEndEvent"; export type { CollaborationMode } from "./CollaborationMode"; -export type { CollaborationModeMask } from "./CollaborationModeMask"; export type { ContentItem } from "./ContentItem"; export type { ContextCompactedEvent } from "./ContextCompactedEvent"; export type { ContextCompactionItem } from "./ContextCompactionItem"; @@ -53,7 +45,9 @@ export type { ConversationSummary } from "./ConversationSummary"; export type { CreditsSnapshot } from "./CreditsSnapshot"; export type { CustomPrompt } from "./CustomPrompt"; export type { DeprecationNoticeEvent } from "./DeprecationNoticeEvent"; +export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; export type { DynamicToolCallRequest } from "./DynamicToolCallRequest"; +export type { DynamicToolCallResponseEvent } from "./DynamicToolCallResponseEvent"; export type { ElicitationRequestEvent } from "./ElicitationRequestEvent"; export type { ErrorEvent } from "./ErrorEvent"; export type { EventMsg } from "./EventMsg"; @@ -65,16 +59,12 @@ export type { ExecCommandEndEvent } from "./ExecCommandEndEvent"; export type { ExecCommandOutputDeltaEvent } from "./ExecCommandOutputDeltaEvent"; export type { ExecCommandSource } from "./ExecCommandSource"; export type { ExecCommandStatus } from "./ExecCommandStatus"; -export type { ExecOneOffCommandParams } from "./ExecOneOffCommandParams"; -export type { ExecOneOffCommandResponse } from "./ExecOneOffCommandResponse"; export type { ExecOutputStream } from "./ExecOutputStream"; export type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; export type { ExitedReviewModeEvent } from "./ExitedReviewModeEvent"; export type { FileChange } from "./FileChange"; export type { FileSystemPermissions } from "./FileSystemPermissions"; export type { ForcedLoginMethod } from "./ForcedLoginMethod"; -export type { ForkConversationParams } from "./ForkConversationParams"; -export type { ForkConversationResponse } from "./ForkConversationResponse"; export type { FunctionCallOutputBody } from "./FunctionCallOutputBody"; export type { FunctionCallOutputContentItem } from "./FunctionCallOutputContentItem"; export type { FunctionCallOutputPayload } from "./FunctionCallOutputPayload"; @@ -88,8 +78,6 @@ export type { GetAuthStatusResponse } from "./GetAuthStatusResponse"; export type { GetConversationSummaryParams } from "./GetConversationSummaryParams"; export type { GetConversationSummaryResponse } from "./GetConversationSummaryResponse"; export type { GetHistoryEntryResponseEvent } from "./GetHistoryEntryResponseEvent"; -export type { GetUserAgentResponse } from "./GetUserAgentResponse"; -export type { GetUserSavedConfigResponse } from "./GetUserSavedConfigResponse"; export type { GhostCommit } from "./GhostCommit"; export type { GitDiffToRemoteParams } from "./GitDiffToRemoteParams"; export type { GitDiffToRemoteResponse } from "./GitDiffToRemoteResponse"; @@ -98,25 +86,15 @@ export type { HistoryEntry } from "./HistoryEntry"; export type { InitializeCapabilities } from "./InitializeCapabilities"; export type { InitializeParams } from "./InitializeParams"; export type { InitializeResponse } from "./InitializeResponse"; -export type { InputItem } from "./InputItem"; export type { InputModality } from "./InputModality"; -export type { InterruptConversationParams } from "./InterruptConversationParams"; -export type { InterruptConversationResponse } from "./InterruptConversationResponse"; export type { ItemCompletedEvent } from "./ItemCompletedEvent"; export type { ItemStartedEvent } from "./ItemStartedEvent"; -export type { ListConversationsParams } from "./ListConversationsParams"; -export type { ListConversationsResponse } from "./ListConversationsResponse"; export type { ListCustomPromptsResponseEvent } from "./ListCustomPromptsResponseEvent"; export type { ListRemoteSkillsResponseEvent } from "./ListRemoteSkillsResponseEvent"; export type { ListSkillsResponseEvent } from "./ListSkillsResponseEvent"; export type { LocalShellAction } from "./LocalShellAction"; export type { LocalShellExecAction } from "./LocalShellExecAction"; export type { LocalShellStatus } from "./LocalShellStatus"; -export type { LoginApiKeyParams } from "./LoginApiKeyParams"; -export type { LoginApiKeyResponse } from "./LoginApiKeyResponse"; -export type { LoginChatGptCompleteNotification } from "./LoginChatGptCompleteNotification"; -export type { LoginChatGptResponse } from "./LoginChatGptResponse"; -export type { LogoutChatGptResponse } from "./LogoutChatGptResponse"; export type { MacOsAutomationValue } from "./MacOsAutomationValue"; export type { MacOsPermissions } from "./MacOsPermissions"; export type { MacOsPreferencesValue } from "./MacOsPreferencesValue"; @@ -138,8 +116,6 @@ export type { NetworkApprovalContext } from "./NetworkApprovalContext"; export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; export type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; export type { NetworkPolicyRuleAction } from "./NetworkPolicyRuleAction"; -export type { NewConversationParams } from "./NewConversationParams"; -export type { NewConversationResponse } from "./NewConversationResponse"; export type { ParsedCommand } from "./ParsedCommand"; export type { PatchApplyBeginEvent } from "./PatchApplyBeginEvent"; export type { PatchApplyEndEvent } from "./PatchApplyEndEvent"; @@ -150,7 +126,6 @@ export type { PlanDeltaEvent } from "./PlanDeltaEvent"; export type { PlanItem } from "./PlanItem"; export type { PlanItemArg } from "./PlanItemArg"; export type { PlanType } from "./PlanType"; -export type { Profile } from "./Profile"; export type { RateLimitSnapshot } from "./RateLimitSnapshot"; export type { RateLimitWindow } from "./RateLimitWindow"; export type { RawResponseItemEvent } from "./RawResponseItemEvent"; @@ -160,6 +135,8 @@ export type { RealtimeConversationClosedEvent } from "./RealtimeConversationClos export type { RealtimeConversationRealtimeEvent } from "./RealtimeConversationRealtimeEvent"; export type { RealtimeConversationStartedEvent } from "./RealtimeConversationStartedEvent"; export type { RealtimeEvent } from "./RealtimeEvent"; +export type { RealtimeHandoffMessage } from "./RealtimeHandoffMessage"; +export type { RealtimeHandoffRequested } from "./RealtimeHandoffRequested"; export type { ReasoningContentDeltaEvent } from "./ReasoningContentDeltaEvent"; export type { ReasoningEffort } from "./ReasoningEffort"; export type { ReasoningItem } from "./ReasoningItem"; @@ -170,8 +147,6 @@ export type { ReasoningSummary } from "./ReasoningSummary"; export type { RejectConfig } from "./RejectConfig"; export type { RemoteSkillDownloadedEvent } from "./RemoteSkillDownloadedEvent"; export type { RemoteSkillSummary } from "./RemoteSkillSummary"; -export type { RemoveConversationListenerParams } from "./RemoveConversationListenerParams"; -export type { RemoveConversationSubscriptionResponse } from "./RemoveConversationSubscriptionResponse"; export type { RequestId } from "./RequestId"; export type { RequestUserInputEvent } from "./RequestUserInputEvent"; export type { RequestUserInputQuestion } from "./RequestUserInputQuestion"; @@ -179,8 +154,6 @@ export type { RequestUserInputQuestionOption } from "./RequestUserInputQuestionO export type { Resource } from "./Resource"; export type { ResourceTemplate } from "./ResourceTemplate"; export type { ResponseItem } from "./ResponseItem"; -export type { ResumeConversationParams } from "./ResumeConversationParams"; -export type { ResumeConversationResponse } from "./ResumeConversationResponse"; export type { ReviewCodeLocation } from "./ReviewCodeLocation"; export type { ReviewDecision } from "./ReviewDecision"; export type { ReviewFinding } from "./ReviewFinding"; @@ -188,27 +161,18 @@ export type { ReviewLineRange } from "./ReviewLineRange"; export type { ReviewOutputEvent } from "./ReviewOutputEvent"; export type { ReviewRequest } from "./ReviewRequest"; export type { ReviewTarget } from "./ReviewTarget"; -export type { SandboxMode } from "./SandboxMode"; export type { SandboxPolicy } from "./SandboxPolicy"; -export type { SandboxSettings } from "./SandboxSettings"; -export type { SendUserMessageParams } from "./SendUserMessageParams"; -export type { SendUserMessageResponse } from "./SendUserMessageResponse"; -export type { SendUserTurnParams } from "./SendUserTurnParams"; -export type { SendUserTurnResponse } from "./SendUserTurnResponse"; export type { ServerNotification } from "./ServerNotification"; export type { ServerRequest } from "./ServerRequest"; +export type { ServiceTier } from "./ServiceTier"; export type { SessionConfiguredEvent } from "./SessionConfiguredEvent"; -export type { SessionConfiguredNotification } from "./SessionConfiguredNotification"; export type { SessionNetworkProxyRuntime } from "./SessionNetworkProxyRuntime"; export type { SessionSource } from "./SessionSource"; -export type { SetDefaultModelParams } from "./SetDefaultModelParams"; -export type { SetDefaultModelResponse } from "./SetDefaultModelResponse"; export type { Settings } from "./Settings"; export type { SkillDependencies } from "./SkillDependencies"; export type { SkillErrorInfo } from "./SkillErrorInfo"; export type { SkillInterface } from "./SkillInterface"; export type { SkillMetadata } from "./SkillMetadata"; -export type { SkillRequestApprovalEvent } from "./SkillRequestApprovalEvent"; export type { SkillScope } from "./SkillScope"; export type { SkillToolDependency } from "./SkillToolDependency"; export type { SkillsListEntry } from "./SkillsListEntry"; @@ -224,7 +188,6 @@ export type { TokenCountEvent } from "./TokenCountEvent"; export type { TokenUsage } from "./TokenUsage"; export type { TokenUsageInfo } from "./TokenUsageInfo"; export type { Tool } from "./Tool"; -export type { Tools } from "./Tools"; export type { TurnAbortReason } from "./TurnAbortReason"; export type { TurnAbortedEvent } from "./TurnAbortedEvent"; export type { TurnCompleteEvent } from "./TurnCompleteEvent"; @@ -234,11 +197,9 @@ export type { TurnStartedEvent } from "./TurnStartedEvent"; export type { UndoCompletedEvent } from "./UndoCompletedEvent"; export type { UndoStartedEvent } from "./UndoStartedEvent"; export type { UpdatePlanArgs } from "./UpdatePlanArgs"; -export type { UserInfoResponse } from "./UserInfoResponse"; export type { UserInput } from "./UserInput"; export type { UserMessageEvent } from "./UserMessageEvent"; export type { UserMessageItem } from "./UserMessageItem"; -export type { UserSavedConfig } from "./UserSavedConfig"; export type { Verbosity } from "./Verbosity"; export type { ViewImageToolCallEvent } from "./ViewImageToolCallEvent"; export type { WarningEvent } from "./WarningEvent"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AccountUpdatedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AccountUpdatedNotification.ts index eacb815412..84bf626e0d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AccountUpdatedNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AccountUpdatedNotification.ts @@ -2,5 +2,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AuthMode } from "../AuthMode"; +import type { PlanType } from "../PlanType"; -export type AccountUpdatedNotification = { authMode: AuthMode | null, }; +export type AccountUpdatedNotification = { authMode: AuthMode | null, planType: PlanType | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalFileSystemPermissions.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalFileSystemPermissions.ts index fb45464f99..0ed8a1b12f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalFileSystemPermissions.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AdditionalFileSystemPermissions.ts @@ -1,5 +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 AdditionalFileSystemPermissions = { read: Array | null, write: Array | null, }; +export type AdditionalFileSystemPermissions = { read: Array | null, write: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CollaborationModeMask.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CollaborationModeMask.ts new file mode 100644 index 0000000000..83adc6446f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CollaborationModeMask.ts @@ -0,0 +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 { ModeKind } from "../ModeKind"; +import type { ReasoningEffort } from "../ReasoningEffort"; + +/** + * EXPERIMENTAL - collaboration mode preset metadata for clients. + */ +export type CollaborationModeMask = { name: string, mode: ModeKind | null, model: string | null, reasoning_effort: ReasoningEffort | null | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts index 70cb8e1521..8fb6375e69 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts @@ -3,6 +3,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AdditionalPermissionProfile } from "./AdditionalPermissionProfile"; import type { CommandAction } from "./CommandAction"; +import type { CommandExecutionApprovalDecision } from "./CommandExecutionApprovalDecision"; import type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; import type { NetworkApprovalContext } from "./NetworkApprovalContext"; import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; @@ -49,4 +50,8 @@ proposedExecpolicyAmendment?: ExecPolicyAmendment | null, /** * Optional proposed network policy amendments (allow/deny host) for future requests. */ -proposedNetworkPolicyAmendments?: Array | null, }; +proposedNetworkPolicyAmendments?: Array | null, +/** + * Ordered list of decisions the client may present for this prompt. + */ +availableDecisions?: Array | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts index aee0ac3383..fb5d6ecbb9 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Config.ts @@ -4,6 +4,7 @@ import type { ForcedLoginMethod } from "../ForcedLoginMethod"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ReasoningSummary } from "../ReasoningSummary"; +import type { ServiceTier } from "../ServiceTier"; import type { Verbosity } from "../Verbosity"; import type { WebSearchMode } from "../WebSearchMode"; import type { JsonValue } from "../serde_json/JsonValue"; @@ -14,4 +15,4 @@ import type { SandboxMode } from "./SandboxMode"; import type { SandboxWorkspaceWrite } from "./SandboxWorkspaceWrite"; import type { ToolsV2 } from "./ToolsV2"; -export type Config = {model: string | null, review_model: string | null, model_context_window: bigint | null, model_auto_compact_token_limit: bigint | null, model_provider: string | null, approval_policy: AskForApproval | null, sandbox_mode: SandboxMode | null, sandbox_workspace_write: SandboxWorkspaceWrite | null, forced_chatgpt_workspace_id: string | null, forced_login_method: ForcedLoginMethod | null, web_search: WebSearchMode | null, tools: ToolsV2 | null, profile: string | null, profiles: { [key in string]?: ProfileV2 }, instructions: string | null, developer_instructions: string | null, compact_prompt: string | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, analytics: AnalyticsConfig | null} & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); +export type Config = {model: string | null, review_model: string | null, model_context_window: bigint | null, model_auto_compact_token_limit: bigint | null, model_provider: string | null, approval_policy: AskForApproval | null, sandbox_mode: SandboxMode | null, sandbox_workspace_write: SandboxWorkspaceWrite | null, forced_chatgpt_workspace_id: string | null, forced_login_method: ForcedLoginMethod | null, web_search: WebSearchMode | null, tools: ToolsV2 | null, profile: string | null, profiles: { [key in string]?: ProfileV2 }, instructions: string | null, developer_instructions: string | null, compact_prompt: string | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, service_tier: ServiceTier | null, analytics: AnalyticsConfig | null} & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); diff --git a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallStatus.ts similarity index 67% rename from codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallStatus.ts index 24900592b2..04f44ec0a8 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DynamicToolCallStatus.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 ArchiveConversationResponse = Record; +export type DynamicToolCallStatus = "inProgress" | "completed" | "failed"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts index de7b240173..cd99108190 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts @@ -3,6 +3,8 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { InputModality } from "../InputModality"; import type { ReasoningEffort } from "../ReasoningEffort"; +import type { ModelAvailabilityNux } from "./ModelAvailabilityNux"; +import type { ModelUpgradeInfo } from "./ModelUpgradeInfo"; import type { ReasoningEffortOption } from "./ReasoningEffortOption"; -export type Model = { id: string, model: string, upgrade: string | null, displayName: string, description: string, hidden: boolean, supportedReasoningEfforts: Array, defaultReasoningEffort: ReasoningEffort, inputModalities: Array, supportsPersonality: boolean, isDefault: boolean, }; +export type Model = { id: string, model: string, upgrade: string | null, upgradeInfo: ModelUpgradeInfo | null, availabilityNux: ModelAvailabilityNux | null, displayName: string, description: string, hidden: boolean, supportedReasoningEfforts: Array, defaultReasoningEffort: ReasoningEffort, inputModalities: Array, supportsPersonality: boolean, isDefault: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ModelAvailabilityNux.ts similarity index 72% rename from codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/ModelAvailabilityNux.ts index a67347aeb7..7254aaec9b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/LoginApiKeyResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ModelAvailabilityNux.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 LoginApiKeyResponse = Record; +export type ModelAvailabilityNux = { message: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ModelUpgradeInfo.ts similarity index 52% rename from codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/ModelUpgradeInfo.ts index 61fbcc9fc8..82d73e9d06 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ArchiveConversationParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ModelUpgradeInfo.ts @@ -1,6 +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. -import type { ThreadId } from "./ThreadId"; -export type ArchiveConversationParams = { conversationId: ThreadId, rolloutPath: string, }; +export type ModelUpgradeInfo = { model: string, upgradeCopy: string | null, modelLink: string | null, migrationMarkdown: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ProfileV2.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ProfileV2.ts index 56428ba7ab..81d20993cb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ProfileV2.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ProfileV2.ts @@ -3,9 +3,10 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ReasoningEffort } from "../ReasoningEffort"; import type { ReasoningSummary } from "../ReasoningSummary"; +import type { ServiceTier } from "../ServiceTier"; import type { Verbosity } from "../Verbosity"; import type { WebSearchMode } from "../WebSearchMode"; import type { JsonValue } from "../serde_json/JsonValue"; import type { AskForApproval } from "./AskForApproval"; -export type ProfileV2 = { model: string | null, model_provider: string | null, approval_policy: AskForApproval | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, web_search: WebSearchMode | null, chatgpt_base_url: string | null, } & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); +export type ProfileV2 = { model: string | null, model_provider: string | null, approval_policy: AskForApproval | null, service_tier: ServiceTier | null, model_reasoning_effort: ReasoningEffort | null, model_reasoning_summary: ReasoningSummary | null, model_verbosity: Verbosity | null, web_search: WebSearchMode | null, chatgpt_base_url: string | null, } & ({ [key in string]?: number | string | boolean | Array | { [key in string]?: JsonValue } | null }); diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ServerRequestResolvedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ServerRequestResolvedNotification.ts new file mode 100644 index 0000000000..56c53cc445 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ServerRequestResolvedNotification.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 { RequestId } from "../RequestId"; + +export type ServerRequestResolvedNotification = { threadId: string, requestId: RequestId, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillApprovalDecision.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillApprovalDecision.ts deleted file mode 100644 index 6773b0f1e0..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SkillApprovalDecision.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SkillApprovalDecision = "approve" | "decline"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillRequestApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillRequestApprovalParams.ts deleted file mode 100644 index 3f70fea595..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SkillRequestApprovalParams.ts +++ /dev/null @@ -1,5 +0,0 @@ -// 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 SkillRequestApprovalParams = { itemId: string, skillName: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillRequestApprovalResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillRequestApprovalResponse.ts deleted file mode 100644 index 9ce454ff4f..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SkillRequestApprovalResponse.ts +++ /dev/null @@ -1,6 +0,0 @@ -// 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 { SkillApprovalDecision } from "./SkillApprovalDecision"; - -export type SkillRequestApprovalResponse = { decision: SkillApprovalDecision, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts index ee07081dca..56c5688495 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Thread.ts @@ -11,6 +11,10 @@ export type Thread = { id: string, * Usually the first user message in the thread, if available. */ preview: string, +/** + * Whether the thread is ephemeral and should not be materialized on disk. + */ +ephemeral: boolean, /** * Model provider used for this thread (for example, 'openai'). */ diff --git a/codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadClosedNotification.ts similarity index 71% rename from codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/ThreadClosedNotification.ts index a74aba5da6..ed5bf546ca 100644 --- a/codex-rs/app-server-protocol/schema/typescript/GetUserAgentResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadClosedNotification.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 GetUserAgentResponse = { userAgent: string, }; +export type ThreadClosedNotification = { threadId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts index 742e4d7032..b071bc8526 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts @@ -1,6 +1,7 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxMode } from "./SandboxMode"; @@ -21,7 +22,7 @@ export type ThreadForkParams = {threadId: string, /** path?: string | null, /** * Configuration overrides for the forked thread, if any. */ -model?: string | null, modelProvider?: string | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, /** +model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, /** * If true, persist additional rollout EventMsg variants required to * reconstruct a richer thread history on subsequent resume/fork/read. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts index a46480cb7b..6125448c08 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts @@ -2,8 +2,9 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ReasoningEffort } from "../ReasoningEffort"; +import type { ServiceTier } from "../ServiceTier"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { Thread } from "./Thread"; -export type ThreadForkResponse = { thread: Thread, model: string, modelProvider: string, cwd: string, approvalPolicy: AskForApproval, sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null, }; +export type ThreadForkResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval, sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null, }; 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 dee39cd5db..d937d53b44 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts @@ -8,6 +8,8 @@ import type { CollabAgentTool } from "./CollabAgentTool"; import type { CollabAgentToolCallStatus } from "./CollabAgentToolCallStatus"; import type { CommandAction } from "./CommandAction"; import type { CommandExecutionStatus } from "./CommandExecutionStatus"; +import type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; +import type { DynamicToolCallStatus } from "./DynamicToolCallStatus"; import type { FileUpdateChange } from "./FileUpdateChange"; import type { McpToolCallError } from "./McpToolCallError"; import type { McpToolCallResult } from "./McpToolCallResult"; @@ -50,6 +52,10 @@ durationMs: number | null, } | { "type": "fileChange", id: string, changes: Arra /** * The duration of the MCP tool call in milliseconds. */ +durationMs: number | null, } | { "type": "dynamicToolCall", id: string, tool: string, arguments: JsonValue, status: DynamicToolCallStatus, contentItems: Array | null, success: boolean | null, +/** + * The duration of the dynamic tool call in milliseconds. + */ durationMs: number | null, } | { "type": "collabAgentToolCall", /** * Unique identifier for this collab tool call. diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts index e79c748cc7..cc12020bd0 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts @@ -3,6 +3,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { Personality } from "../Personality"; import type { ResponseItem } from "../ResponseItem"; +import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxMode } from "./SandboxMode"; @@ -30,7 +31,7 @@ history?: Array | null, /** path?: string | null, /** * Configuration overrides for the resumed thread, if any. */ -model?: string | null, modelProvider?: string | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, /** +model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, /** * If true, persist additional rollout EventMsg variants required to * reconstruct a richer thread history on subsequent resume/fork/read. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts index 6d7a70a6a9..91ca82419b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts @@ -2,8 +2,9 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ReasoningEffort } from "../ReasoningEffort"; +import type { ServiceTier } from "../ServiceTier"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { Thread } from "./Thread"; -export type ThreadResumeResponse = { thread: Thread, model: string, modelProvider: string, cwd: string, approvalPolicy: AskForApproval, sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null, }; +export type ThreadResumeResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval, sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts index 5f34f6198c..db73763e40 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts @@ -2,11 +2,12 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { Personality } from "../Personality"; +import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxMode } from "./SandboxMode"; -export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, /** +export type ThreadStartParams = {model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, /** * If true, opt into emitting raw Responses API items on the event stream. * This is for internal use only (e.g. Codex Cloud). */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts index 4a76f9af20..f4882ce6fb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts @@ -2,8 +2,9 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ReasoningEffort } from "../ReasoningEffort"; +import type { ServiceTier } from "../ServiceTier"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { Thread } from "./Thread"; -export type ThreadStartResponse = { thread: Thread, model: string, modelProvider: string, cwd: string, approvalPolicy: AskForApproval, sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null, }; +export type ThreadStartResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: string, approvalPolicy: AskForApproval, sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeParams.ts similarity index 71% rename from codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeParams.ts index dae8e8c784..3d5f3a04cd 100644 --- a/codex-rs/app-server-protocol/schema/typescript/CancelLoginChatGptParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeParams.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 CancelLoginChatGptParams = { loginId: string, }; +export type ThreadUnsubscribeParams = { threadId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeResponse.ts similarity index 50% rename from codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeResponse.ts index 6441bed68a..6f8f66b226 100644 --- a/codex-rs/app-server-protocol/schema/typescript/AddConversationListenerParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeResponse.ts @@ -1,6 +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 { ThreadId } from "./ThreadId"; +import type { ThreadUnsubscribeStatus } from "./ThreadUnsubscribeStatus"; -export type AddConversationListenerParams = { conversationId: ThreadId, experimentalRawEvents: boolean, }; +export type ThreadUnsubscribeResponse = { status: ThreadUnsubscribeStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeStatus.ts similarity index 64% rename from codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeStatus.ts index f7e34ef658..2970598dc1 100644 --- a/codex-rs/app-server-protocol/schema/typescript/AddConversationSubscriptionResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadUnsubscribeStatus.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 AddConversationSubscriptionResponse = { subscriptionId: string, }; +export type ThreadUnsubscribeStatus = "notLoaded" | "notSubscribed" | "unsubscribed"; 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 d595035dda..940aaa700d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts @@ -5,6 +5,7 @@ import type { CollaborationMode } from "../CollaborationMode"; import type { Personality } from "../Personality"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ReasoningSummary } from "../ReasoningSummary"; +import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { AskForApproval } from "./AskForApproval"; import type { SandboxPolicy } from "./SandboxPolicy"; @@ -23,6 +24,9 @@ sandboxPolicy?: SandboxPolicy | null, /** * Override the model for this turn and subsequent turns. */ model?: string | null, /** + * Override the service tier for this turn and subsequent turns. + */ +serviceTier?: ServiceTier | null | null, /** * Override the reasoning effort for this turn and subsequent turns. */ effort?: ReasoningEffort | 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 3f9041dcfe..757eb72893 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -34,6 +34,7 @@ export type { CollabAgentState } from "./CollabAgentState"; export type { CollabAgentStatus } from "./CollabAgentStatus"; export type { CollabAgentTool } from "./CollabAgentTool"; export type { CollabAgentToolCallStatus } from "./CollabAgentToolCallStatus"; +export type { CollaborationModeMask } from "./CollaborationModeMask"; export type { CommandAction } from "./CommandAction"; export type { CommandExecParams } from "./CommandExecParams"; export type { CommandExecResponse } from "./CommandExecResponse"; @@ -61,6 +62,7 @@ export type { DeprecationNoticeNotification } from "./DeprecationNoticeNotificat export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; export type { DynamicToolCallParams } from "./DynamicToolCallParams"; export type { DynamicToolCallResponse } from "./DynamicToolCallResponse"; +export type { DynamicToolCallStatus } from "./DynamicToolCallStatus"; export type { DynamicToolSpec } from "./DynamicToolSpec"; export type { ErrorNotification } from "./ErrorNotification"; export type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; @@ -105,10 +107,12 @@ export type { McpToolCallResult } from "./McpToolCallResult"; export type { McpToolCallStatus } from "./McpToolCallStatus"; export type { MergeStrategy } from "./MergeStrategy"; export type { Model } from "./Model"; +export type { ModelAvailabilityNux } from "./ModelAvailabilityNux"; export type { ModelListParams } from "./ModelListParams"; export type { ModelListResponse } from "./ModelListResponse"; export type { ModelRerouteReason } from "./ModelRerouteReason"; export type { ModelReroutedNotification } from "./ModelReroutedNotification"; +export type { ModelUpgradeInfo } from "./ModelUpgradeInfo"; export type { NetworkAccess } from "./NetworkAccess"; export type { NetworkApprovalContext } from "./NetworkApprovalContext"; export type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol"; @@ -138,14 +142,12 @@ export type { ReviewTarget } from "./ReviewTarget"; export type { SandboxMode } from "./SandboxMode"; export type { SandboxPolicy } from "./SandboxPolicy"; export type { SandboxWorkspaceWrite } from "./SandboxWorkspaceWrite"; +export type { ServerRequestResolvedNotification } from "./ServerRequestResolvedNotification"; export type { SessionSource } from "./SessionSource"; -export type { SkillApprovalDecision } from "./SkillApprovalDecision"; export type { SkillDependencies } from "./SkillDependencies"; export type { SkillErrorInfo } from "./SkillErrorInfo"; export type { SkillInterface } from "./SkillInterface"; export type { SkillMetadata } from "./SkillMetadata"; -export type { SkillRequestApprovalParams } from "./SkillRequestApprovalParams"; -export type { SkillRequestApprovalResponse } from "./SkillRequestApprovalResponse"; export type { SkillScope } from "./SkillScope"; export type { SkillToolDependency } from "./SkillToolDependency"; export type { SkillsConfigWriteParams } from "./SkillsConfigWriteParams"; @@ -167,6 +169,7 @@ export type { ThreadActiveFlag } from "./ThreadActiveFlag"; export type { ThreadArchiveParams } from "./ThreadArchiveParams"; export type { ThreadArchiveResponse } from "./ThreadArchiveResponse"; export type { ThreadArchivedNotification } from "./ThreadArchivedNotification"; +export type { ThreadClosedNotification } from "./ThreadClosedNotification"; export type { ThreadCompactStartParams } from "./ThreadCompactStartParams"; export type { ThreadCompactStartResponse } from "./ThreadCompactStartResponse"; export type { ThreadForkParams } from "./ThreadForkParams"; @@ -203,6 +206,9 @@ export type { ThreadTokenUsageUpdatedNotification } from "./ThreadTokenUsageUpda export type { ThreadUnarchiveParams } from "./ThreadUnarchiveParams"; export type { ThreadUnarchiveResponse } from "./ThreadUnarchiveResponse"; export type { ThreadUnarchivedNotification } from "./ThreadUnarchivedNotification"; +export type { ThreadUnsubscribeParams } from "./ThreadUnsubscribeParams"; +export type { ThreadUnsubscribeResponse } from "./ThreadUnsubscribeResponse"; +export type { ThreadUnsubscribeStatus } from "./ThreadUnsubscribeStatus"; export type { TokenUsageBreakdown } from "./TokenUsageBreakdown"; export type { ToolRequestUserInputAnswer } from "./ToolRequestUserInputAnswer"; export type { ToolRequestUserInputOption } from "./ToolRequestUserInputOption"; diff --git a/codex-rs/app-server-protocol/src/bin/export.rs b/codex-rs/app-server-protocol/src/bin/export.rs index d029ecbffa..10541d1fcb 100644 --- a/codex-rs/app-server-protocol/src/bin/export.rs +++ b/codex-rs/app-server-protocol/src/bin/export.rs @@ -14,9 +14,21 @@ struct Args { /// Optional Prettier executable path to format generated TypeScript files #[arg(short = 'p', long = "prettier", value_name = "PRETTIER_BIN")] prettier: Option, + + /// Include experimental API methods and fields in generated output. + #[arg(long = "experimental")] + experimental: bool, } fn main() -> Result<()> { let args = Args::parse(); - codex_app_server_protocol::generate_types(&args.out_dir, args.prettier.as_deref()) + codex_app_server_protocol::generate_ts_with_options( + &args.out_dir, + args.prettier.as_deref(), + codex_app_server_protocol::GenerateTsOptions { + experimental_api: args.experimental, + ..codex_app_server_protocol::GenerateTsOptions::default() + }, + )?; + codex_app_server_protocol::generate_json_with_experimental(&args.out_dir, args.experimental) } diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index b48651c03c..aad5ab7233 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -37,36 +37,17 @@ use ts_rs::TS; const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n"; const IGNORED_DEFINITIONS: &[&str] = &["Option<()>"]; const JSON_V1_ALLOWLIST: &[&str] = &["InitializeParams", "InitializeResponse"]; -const V1_CLIENT_REQUEST_METHODS: &[&str] = &[ - "newConversation", - "getConversationSummary", - "listConversations", - "resumeConversation", - "forkConversation", - "archiveConversation", - "sendUserMessage", - "sendUserTurn", - "interruptConversation", - "addConversationListener", - "removeConversationListener", - "gitDiffToRemote", - "loginApiKey", - "loginChatGpt", - "cancelLoginChatGpt", - "logoutChatGpt", - "getAuthStatus", - "getUserSavedConfig", - "setDefaultModel", - "getUserAgent", - "userInfo", - "execOneOffCommand", -]; -const EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON: &[&str] = &[ - "authStatusChange", - "loginChatGptComplete", - "sessionConfigured", - "rawResponseItem/completed", +const SPECIAL_DEFINITIONS: &[&str] = &[ + "ClientNotification", + "ClientRequest", + "EventMsg", + "ServerNotification", + "ServerRequest", ]; +const FLAT_V2_SHARED_DEFINITIONS: &[&str] = &["ClientRequest", "EventMsg", "ServerNotification"]; +const V1_CLIENT_REQUEST_METHODS: &[&str] = + &["getConversationSummary", "gitDiffToRemote", "getAuthStatus"]; +const EXCLUDED_SERVER_NOTIFICATION_METHODS_FOR_JSON: &[&str] = &["rawResponseItem/completed"]; #[derive(Clone)] pub struct GeneratedSchema { @@ -136,6 +117,7 @@ pub fn generate_ts_with_options( ServerRequest::export_all_to(out_dir)?; export_server_responses(out_dir)?; ServerNotification::export_all_to(out_dir)?; + EventMsg::export_all_to(out_dir)?; if !options.experimental_api { filter_experimental_ts(out_dir)?; @@ -223,6 +205,11 @@ pub fn generate_json_with_experimental(out_dir: &Path, experimental_api: bool) - out_dir.join("codex_app_server_protocol.schemas.json"), &bundle, )?; + let flat_v2_bundle = build_flat_v2_schema(&bundle)?; + write_pretty_json( + out_dir.join("codex_app_server_protocol.v2.schemas.json"), + &flat_v2_bundle, + )?; if !experimental_api { filter_experimental_json_files(out_dir)?; @@ -870,14 +857,6 @@ impl Depth { } fn build_schema_bundle(schemas: Vec) -> Result { - const SPECIAL_DEFINITIONS: &[&str] = &[ - "ClientNotification", - "ClientRequest", - "EventMsg", - "ServerNotification", - "ServerRequest", - ]; - let namespaced_types = collect_namespaced_types(&schemas); let mut definitions = Map::new(); @@ -895,6 +874,8 @@ fn build_schema_bundle(schemas: Vec) -> Result { if let Some(ref ns) = namespace { rewrite_refs_to_namespace(&mut value, ns); + } else { + rewrite_refs_to_known_namespaces(&mut value, &namespaced_types); } let mut forced_namespace_refs: Vec<(String, String)> = Vec::new(); @@ -958,6 +939,210 @@ fn build_schema_bundle(schemas: Vec) -> Result { Ok(Value::Object(root)) } +/// Build a datamodel-code-generator-friendly v2 bundle from the mixed export. +/// +/// The full bundle keeps v2 schemas nested under `definitions.v2`, plus a few +/// shared root definitions like `ClientRequest`, `EventMsg`, and +/// `ServerNotification`. Python codegen only walks one definitions map level, so +/// a direct feed would treat `v2` itself as a schema and miss unreferenced v2 +/// leaves. This helper flattens all v2 definitions to the root definitions map, +/// then pulls in the shared root schemas and any non-v2 transitive deps they +/// still reference. Keep the shared root unions intact here: some valid +/// request/notification/event variants are inline or only reference shared root +/// helpers, so filtering them by the presence of a `#/definitions/v2/` ref +/// would silently drop real API surface from the flat bundle. +fn build_flat_v2_schema(bundle: &Value) -> Result { + let Value::Object(root) = bundle else { + return Err(anyhow!("expected bundle root to be an object")); + }; + let definitions = root + .get("definitions") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("expected bundle definitions map"))?; + let v2_definitions = definitions + .get("v2") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("expected v2 namespace in bundle definitions"))?; + + let mut flat_root = root.clone(); + let title = root + .get("title") + .and_then(Value::as_str) + .unwrap_or("CodexAppServerProtocol"); + let mut flat_definitions = v2_definitions.clone(); + let mut shared_definitions = Map::new(); + let mut non_v2_refs = HashSet::new(); + + for shared in FLAT_V2_SHARED_DEFINITIONS { + let Some(shared_schema) = definitions.get(*shared) else { + continue; + }; + let shared_schema = shared_schema.clone(); + non_v2_refs.extend(collect_non_v2_refs(&shared_schema)); + shared_definitions.insert((*shared).to_string(), shared_schema); + } + + for name in collect_definition_dependencies(definitions, non_v2_refs) { + if name == "v2" || flat_definitions.contains_key(&name) { + continue; + } + if let Some(schema) = definitions.get(&name) { + flat_definitions.insert(name, schema.clone()); + } + } + + flat_definitions.extend(shared_definitions); + flat_root.insert("title".to_string(), Value::String(format!("{title}V2"))); + flat_root.insert("definitions".to_string(), Value::Object(flat_definitions)); + let mut flat_bundle = Value::Object(flat_root); + rewrite_ref_prefix(&mut flat_bundle, "#/definitions/v2/", "#/definitions/"); + ensure_no_ref_prefix(&flat_bundle, "#/definitions/v2/", "flat v2")?; + ensure_referenced_definitions_present(&flat_bundle, "flat v2")?; + Ok(flat_bundle) +} + +fn collect_non_v2_refs(value: &Value) -> HashSet { + let mut refs = HashSet::new(); + collect_non_v2_refs_inner(value, &mut refs); + refs +} + +fn collect_non_v2_refs_inner(value: &Value, refs: &mut HashSet) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get("$ref") + && let Some(name) = reference.strip_prefix("#/definitions/") + && !reference.starts_with("#/definitions/v2/") + { + refs.insert(name.to_string()); + } + for child in obj.values() { + collect_non_v2_refs_inner(child, refs); + } + } + Value::Array(items) => { + for child in items { + collect_non_v2_refs_inner(child, refs); + } + } + _ => {} + } +} + +fn collect_definition_dependencies( + definitions: &Map, + names: HashSet, +) -> HashSet { + let mut seen = HashSet::new(); + let mut to_process: Vec = names.into_iter().collect(); + while let Some(name) = to_process.pop() { + if !seen.insert(name.clone()) { + continue; + } + let Some(schema) = definitions.get(&name) else { + continue; + }; + for dep in collect_non_v2_refs(schema) { + if !seen.contains(&dep) { + to_process.push(dep); + } + } + } + seen +} + +fn rewrite_ref_prefix(value: &mut Value, prefix: &str, replacement: &str) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get_mut("$ref") { + *reference = reference.replace(prefix, replacement); + } + for child in obj.values_mut() { + rewrite_ref_prefix(child, prefix, replacement); + } + } + Value::Array(items) => { + for child in items { + rewrite_ref_prefix(child, prefix, replacement); + } + } + _ => {} + } +} + +fn ensure_no_ref_prefix(value: &Value, prefix: &str, label: &str) -> Result<()> { + if let Some(reference) = first_ref_with_prefix(value, prefix) { + return Err(anyhow!( + "{label} schema still references namespaced definitions; found {reference}" + )); + } + Ok(()) +} + +fn first_ref_with_prefix(value: &Value, prefix: &str) -> Option { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get("$ref") + && reference.starts_with(prefix) + { + return Some(reference.clone()); + } + obj.values() + .find_map(|child| first_ref_with_prefix(child, prefix)) + } + Value::Array(items) => items + .iter() + .find_map(|child| first_ref_with_prefix(child, prefix)), + _ => None, + } +} + +fn ensure_referenced_definitions_present(schema: &Value, label: &str) -> Result<()> { + let definitions = schema + .get("definitions") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("expected definitions map in {label} schema"))?; + let mut missing = HashSet::new(); + collect_missing_definitions(schema, definitions, &mut missing); + if missing.is_empty() { + return Ok(()); + } + let mut missing_names: Vec = missing.into_iter().collect(); + missing_names.sort(); + Err(anyhow!( + "{label} schema missing definitions: {}", + missing_names.join(", ") + )) +} + +fn collect_missing_definitions( + value: &Value, + definitions: &Map, + missing: &mut HashSet, +) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get("$ref") + && let Some(name) = reference.strip_prefix("#/definitions/") + { + let name = name.split('/').next().unwrap_or(name); + if !definitions.contains_key(name) { + missing.insert(name.to_string()); + } + } + for child in obj.values() { + collect_missing_definitions(child, definitions, missing); + } + } + Value::Array(items) => { + for child in items { + collect_missing_definitions(child, definitions, missing); + } + } + _ => {} + } +} + fn insert_into_namespace( definitions: &mut Map, namespace: &str, @@ -1230,6 +1415,43 @@ fn rewrite_refs_to_namespace(value: &mut Value, ns: &str) { } } +/// Recursively rewrite bare root definition refs to the namespace that owns the +/// referenced type in the bundle. +/// +/// The mixed export contains shared root helper schemas that are intentionally +/// left outside the `v2` namespace, but some of their extracted child +/// definitions still contain refs like `#/definitions/ThreadId`. When the real +/// schema only exists under `#/definitions/v2/ThreadId`, those refs become +/// dangling and downstream codegen falls back to placeholder `Any` models. This +/// rewrite keeps the shared helpers at the root while retargeting their refs to +/// the namespaced definitions that actually exist. +fn rewrite_refs_to_known_namespaces(value: &mut Value, types: &HashMap) { + match value { + Value::Object(obj) => { + if let Some(Value::String(reference)) = obj.get_mut("$ref") + && let Some(suffix) = reference.strip_prefix("#/definitions/") + { + let (name, tail) = suffix + .split_once('/') + .map_or((suffix, None), |(name, tail)| (name, Some(tail))); + if let Some(ns) = namespace_for_definition(name, types) { + let tail = tail.map_or(String::new(), |rest| format!("/{rest}")); + *reference = format!("#/definitions/{ns}/{name}{tail}"); + } + } + for v in obj.values_mut() { + rewrite_refs_to_known_namespaces(v, types); + } + } + Value::Array(items) => { + for v in items.iter_mut() { + rewrite_refs_to_known_namespaces(v, types); + } + } + _ => {} + } +} + fn collect_namespaced_types(schemas: &[GeneratedSchema]) -> HashMap { let mut types = HashMap::new(); for schema in schemas { @@ -1689,6 +1911,7 @@ mod tests { client_request_ts.contains("MockExperimentalMethodParams"), false ); + assert_eq!(output_dir.join("EventMsg.ts").exists(), true); let thread_start_ts = fs::read_to_string(output_dir.join("v2").join("ThreadStartParams.ts"))?; assert_eq!(thread_start_ts.contains("mockExperimentalField"), false); @@ -1986,6 +2209,284 @@ mod tests { Ok(()) } + #[test] + fn build_schema_bundle_rewrites_root_helper_refs_to_namespaced_defs() -> Result<()> { + let bundle = build_schema_bundle(vec![ + GeneratedSchema { + namespace: None, + logical_name: "LegacyEnvelope".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "LegacyEnvelope", + "type": "object", + "properties": { + "current_thread": { "$ref": "#/definitions/ThreadId" }, + "turn_item": { "$ref": "#/definitions/TurnItem" } + }, + "definitions": { + "TurnItem": { + "type": "object", + "properties": { + "thread_id": { "$ref": "#/definitions/ThreadId" }, + "phase": { "$ref": "#/definitions/MessagePhase" }, + "content": { + "type": "array", + "items": { "$ref": "#/definitions/UserInput" } + } + } + } + } + }), + }, + GeneratedSchema { + namespace: Some("v2".to_string()), + logical_name: "ThreadId".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "ThreadId", + "type": "string" + }), + }, + GeneratedSchema { + namespace: Some("v2".to_string()), + logical_name: "MessagePhase".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "MessagePhase", + "type": "string" + }), + }, + GeneratedSchema { + namespace: Some("v2".to_string()), + logical_name: "UserInput".to_string(), + in_v1_dir: false, + value: serde_json::json!({ + "title": "UserInput", + "type": "string" + }), + }, + ])?; + + assert_eq!( + bundle["definitions"]["LegacyEnvelope"]["properties"]["current_thread"]["$ref"], + serde_json::json!("#/definitions/v2/ThreadId") + ); + assert_eq!( + bundle["definitions"]["LegacyEnvelope"]["properties"]["turn_item"]["$ref"], + serde_json::json!("#/definitions/TurnItem") + ); + assert_eq!( + bundle["definitions"]["TurnItem"]["properties"]["thread_id"]["$ref"], + serde_json::json!("#/definitions/v2/ThreadId") + ); + assert_eq!( + bundle["definitions"]["TurnItem"]["properties"]["phase"]["$ref"], + serde_json::json!("#/definitions/v2/MessagePhase") + ); + assert_eq!( + bundle["definitions"]["TurnItem"]["properties"]["content"]["items"]["$ref"], + serde_json::json!("#/definitions/v2/UserInput") + ); + + Ok(()) + } + + #[test] + fn build_flat_v2_schema_keeps_shared_root_schemas_and_dependencies() -> Result<()> { + let bundle = serde_json::json!({ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "CodexAppServerProtocol", + "type": "object", + "definitions": { + "ClientRequest": { + "oneOf": [ + { + "title": "StartRequest", + "type": "object", + "properties": { + "params": { "$ref": "#/definitions/v2/ThreadStartParams" }, + "shared": { "$ref": "#/definitions/SharedHelper" } + } + }, + { + "title": "InitializeRequest", + "type": "object", + "properties": { + "params": { "$ref": "#/definitions/InitializeParams" } + } + }, + { + "title": "LogoutRequest", + "type": "object", + "properties": { + "params": { "type": "null" } + } + } + ] + }, + "EventMsg": { + "oneOf": [ + { "$ref": "#/definitions/v2/ThreadStartedEventMsg" }, + { + "title": "WarningEventMsg", + "type": "object", + "properties": { + "message": { "type": "string" }, + "type": { + "enum": ["warning"], + "type": "string" + } + }, + "required": ["message", "type"] + } + ] + }, + "ServerNotification": { + "oneOf": [ + { "$ref": "#/definitions/v2/ThreadStartedNotification" }, + { + "title": "ServerRequestResolvedNotification", + "type": "object", + "properties": { + "params": { "$ref": "#/definitions/ServerRequestResolvedNotificationPayload" } + } + } + ] + }, + "SharedHelper": { + "type": "object", + "properties": { + "leaf": { "$ref": "#/definitions/SharedLeaf" } + } + }, + "SharedLeaf": { + "title": "SharedLeaf", + "type": "string" + }, + "InitializeParams": { + "title": "InitializeParams", + "type": "string" + }, + "ServerRequestResolvedNotificationPayload": { + "title": "ServerRequestResolvedNotificationPayload", + "type": "string" + }, + "v2": { + "ThreadStartParams": { + "title": "ThreadStartParams", + "type": "object", + "properties": { + "cwd": { "type": "string" } + } + }, + "ThreadStartResponse": { + "title": "ThreadStartResponse", + "type": "object", + "properties": { + "ok": { "type": "boolean" } + } + }, + "ThreadStartedEventMsg": { + "title": "ThreadStartedEventMsg", + "type": "object", + "properties": { + "thread_id": { "type": "string" } + } + }, + "ThreadStartedNotification": { + "title": "ThreadStartedNotification", + "type": "object", + "properties": { + "thread_id": { "type": "string" } + } + } + } + } + }); + + let flat_bundle = build_flat_v2_schema(&bundle)?; + let definitions = flat_bundle["definitions"] + .as_object() + .expect("flat v2 schema should include definitions"); + + assert_eq!( + flat_bundle["title"], + serde_json::json!("CodexAppServerProtocolV2") + ); + assert_eq!(definitions.contains_key("v2"), false); + assert_eq!(definitions.contains_key("ThreadStartParams"), true); + assert_eq!(definitions.contains_key("ThreadStartResponse"), true); + assert_eq!(definitions.contains_key("ThreadStartedEventMsg"), true); + assert_eq!(definitions.contains_key("ThreadStartedNotification"), true); + assert_eq!(definitions.contains_key("SharedHelper"), true); + assert_eq!(definitions.contains_key("SharedLeaf"), true); + assert_eq!(definitions.contains_key("InitializeParams"), true); + assert_eq!( + definitions.contains_key("ServerRequestResolvedNotificationPayload"), + true + ); + let client_request_titles: BTreeSet = definitions["ClientRequest"]["oneOf"] + .as_array() + .expect("ClientRequest should remain a oneOf") + .iter() + .map(|variant| { + variant["title"] + .as_str() + .expect("ClientRequest variant should have a title") + .to_string() + }) + .collect(); + assert_eq!( + client_request_titles, + BTreeSet::from([ + "InitializeRequest".to_string(), + "LogoutRequest".to_string(), + "StartRequest".to_string(), + ]) + ); + let event_titles: BTreeSet = definitions["EventMsg"]["oneOf"] + .as_array() + .expect("EventMsg should remain a oneOf") + .iter() + .map(|variant| { + variant + .get("title") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }) + .collect(); + assert_eq!( + event_titles, + BTreeSet::from(["".to_string(), "WarningEventMsg".to_string(),]) + ); + let notification_titles: BTreeSet = definitions["ServerNotification"]["oneOf"] + .as_array() + .expect("ServerNotification should remain a oneOf") + .iter() + .map(|variant| { + variant + .get("title") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }) + .collect(); + assert_eq!( + notification_titles, + BTreeSet::from([ + "".to_string(), + "ServerRequestResolvedNotification".to_string(), + ]) + ); + assert_eq!( + first_ref_with_prefix(&flat_bundle, "#/definitions/v2/").is_none(), + true + ); + + Ok(()) + } + #[test] fn experimental_type_fields_ts_filter_handles_interface_shape() -> Result<()> { let output_dir = std::env::temp_dir().join(format!("codex_ts_filter_{}", Uuid::now_v7())); @@ -2114,6 +2615,99 @@ export type Config = { stableField: Keep, unstableField: string | null } & ({ [k bundle_json.contains("MockExperimentalMethodResponse"), false ); + let flat_v2_bundle_json = + fs::read_to_string(output_dir.join("codex_app_server_protocol.v2.schemas.json"))?; + assert_eq!(flat_v2_bundle_json.contains("mockExperimentalField"), false); + assert_eq!(flat_v2_bundle_json.contains("additionalPermissions"), false); + assert_eq!( + flat_v2_bundle_json.contains("MockExperimentalMethodParams"), + false + ); + assert_eq!( + flat_v2_bundle_json.contains("MockExperimentalMethodResponse"), + false + ); + assert_eq!(flat_v2_bundle_json.contains("#/definitions/v2/"), false); + assert_eq!( + flat_v2_bundle_json.contains("\"title\": \"CodexAppServerProtocolV2\""), + true + ); + let flat_v2_bundle = + read_json_value(&output_dir.join("codex_app_server_protocol.v2.schemas.json"))?; + let definitions = flat_v2_bundle["definitions"] + .as_object() + .expect("flat v2 bundle should include definitions"); + let client_request_methods: BTreeSet = definitions["ClientRequest"]["oneOf"] + .as_array() + .expect("flat v2 ClientRequest should remain a oneOf") + .iter() + .filter_map(|variant| { + variant["properties"]["method"]["enum"] + .as_array() + .and_then(|values| values.first()) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect(); + let missing_client_request_methods: Vec = [ + "account/logout", + "account/rateLimits/read", + "config/mcpServer/reload", + "configRequirements/read", + "fuzzyFileSearch", + "initialize", + ] + .into_iter() + .filter(|method| !client_request_methods.contains(*method)) + .map(str::to_string) + .collect(); + assert_eq!(missing_client_request_methods, Vec::::new()); + let server_notification_methods: BTreeSet = + definitions["ServerNotification"]["oneOf"] + .as_array() + .expect("flat v2 ServerNotification should remain a oneOf") + .iter() + .filter_map(|variant| { + variant["properties"]["method"]["enum"] + .as_array() + .and_then(|values| values.first()) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect(); + let missing_server_notification_methods: Vec = [ + "fuzzyFileSearch/sessionCompleted", + "fuzzyFileSearch/sessionUpdated", + "serverRequest/resolved", + ] + .into_iter() + .filter(|method| !server_notification_methods.contains(*method)) + .map(str::to_string) + .collect(); + assert_eq!(missing_server_notification_methods, Vec::::new()); + let event_types: BTreeSet = definitions["EventMsg"]["oneOf"] + .as_array() + .expect("flat v2 EventMsg should remain a oneOf") + .iter() + .filter_map(|variant| { + variant["properties"]["type"]["enum"] + .as_array() + .and_then(|values| values.first()) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect(); + let missing_event_types: Vec = [ + "agent_message_delta", + "task_complete", + "warning", + "web_search_begin", + ] + .into_iter() + .filter(|event_type| !event_types.contains(*event_type)) + .map(str::to_string) + .collect(); + assert_eq!(missing_event_types, Vec::::new()); assert_eq!( output_dir .join("v2") diff --git a/codex-rs/app-server-protocol/src/jsonrpc_lite.rs b/codex-rs/app-server-protocol/src/jsonrpc_lite.rs index 65ffa2a005..13d3e0cc9a 100644 --- a/codex-rs/app-server-protocol/src/jsonrpc_lite.rs +++ b/codex-rs/app-server-protocol/src/jsonrpc_lite.rs @@ -1,6 +1,7 @@ //! We do not do true JSON-RPC 2.0, as we neither send nor expect the //! "jsonrpc": "2.0" field. +use codex_protocol::protocol::W3cTraceContext; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -8,7 +9,9 @@ use ts_rs::TS; pub const JSONRPC_VERSION: &str = "2.0"; -#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Hash, Eq, JsonSchema, TS)] +#[derive( + Debug, Clone, PartialEq, PartialOrd, Ord, Deserialize, Serialize, Hash, Eq, JsonSchema, TS, +)] #[serde(untagged)] pub enum RequestId { String(String), @@ -36,6 +39,10 @@ pub struct JSONRPCRequest { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub params: Option, + /// Optional W3C Trace Context for distributed tracing. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub trace: Option, } /// A notification which does not expect a response. diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 7a918ada09..98efcdd290 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -203,6 +203,10 @@ client_request_definitions! { params: v2::ThreadArchiveParams, response: v2::ThreadArchiveResponse, }, + ThreadUnsubscribe => "thread/unsubscribe" { + params: v2::ThreadUnsubscribeParams, + response: v2::ThreadUnsubscribeResponse, + }, ThreadSetName => "thread/name/set" { params: v2::ThreadSetNameParams, response: v2::ThreadSetNameResponse, @@ -399,95 +403,19 @@ client_request_definitions! { }, /// DEPRECATED APIs below - NewConversation { - params: v1::NewConversationParams, - response: v1::NewConversationResponse, - }, GetConversationSummary { params: v1::GetConversationSummaryParams, response: v1::GetConversationSummaryResponse, }, - /// List recorded Codex conversations (rollouts) with optional pagination and search. - ListConversations { - params: v1::ListConversationsParams, - response: v1::ListConversationsResponse, - }, - /// Resume a recorded Codex conversation from a rollout file. - ResumeConversation { - params: v1::ResumeConversationParams, - response: v1::ResumeConversationResponse, - }, - /// Fork a recorded Codex conversation into a new session. - ForkConversation { - params: v1::ForkConversationParams, - response: v1::ForkConversationResponse, - }, - ArchiveConversation { - params: v1::ArchiveConversationParams, - response: v1::ArchiveConversationResponse, - }, - SendUserMessage { - params: v1::SendUserMessageParams, - response: v1::SendUserMessageResponse, - }, - SendUserTurn { - params: v1::SendUserTurnParams, - response: v1::SendUserTurnResponse, - }, - InterruptConversation { - params: v1::InterruptConversationParams, - response: v1::InterruptConversationResponse, - }, - AddConversationListener { - params: v1::AddConversationListenerParams, - response: v1::AddConversationSubscriptionResponse, - }, - RemoveConversationListener { - params: v1::RemoveConversationListenerParams, - response: v1::RemoveConversationSubscriptionResponse, - }, GitDiffToRemote { params: v1::GitDiffToRemoteParams, response: v1::GitDiffToRemoteResponse, }, - LoginApiKey { - params: v1::LoginApiKeyParams, - response: v1::LoginApiKeyResponse, - }, - LoginChatGpt { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::LoginChatGptResponse, - }, - // DEPRECATED in favor of CancelLoginAccount - CancelLoginChatGpt { - params: v1::CancelLoginChatGptParams, - response: v1::CancelLoginChatGptResponse, - }, - LogoutChatGpt { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::LogoutChatGptResponse, - }, /// DEPRECATED in favor of GetAccount GetAuthStatus { params: v1::GetAuthStatusParams, response: v1::GetAuthStatusResponse, }, - GetUserSavedConfig { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::GetUserSavedConfigResponse, - }, - SetDefaultModel { - params: v1::SetDefaultModelParams, - response: v1::SetDefaultModelResponse, - }, - GetUserAgent { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::GetUserAgentResponse, - }, - UserInfo { - params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: v1::UserInfoResponse, - }, FuzzyFileSearch { params: FuzzyFileSearchParams, response: FuzzyFileSearchResponse, @@ -507,11 +435,6 @@ client_request_definitions! { params: FuzzyFileSearchSessionStopParams, response: FuzzyFileSearchSessionStopResponse, }, - /// Execute a command (argv vector) under the server's sandbox. - ExecOneOffCommand { - params: v1::ExecOneOffCommandParams, - response: v1::ExecOneOffCommandResponse, - }, } /// Generates an `enum ServerRequest` where each variant is a request that the @@ -544,6 +467,14 @@ macro_rules! server_request_definitions { )* } + impl ServerRequest { + pub fn id(&self) -> &RequestId { + match self { + $(Self::$variant { request_id, .. } => request_id,)* + } + } + } + #[derive(Debug, Clone, PartialEq, JsonSchema)] #[allow(clippy::large_enum_variant)] pub enum ServerRequestPayload { @@ -711,11 +642,6 @@ server_request_definitions! { response: v2::ToolRequestUserInputResponse, }, - SkillRequestApproval => "skill/requestApproval" { - params: v2::SkillRequestApprovalParams, - response: v2::SkillRequestApprovalResponse, - }, - /// Execute a dynamic tool call on the client. DynamicToolCall => "item/tool/call" { params: v2::DynamicToolCallParams, @@ -822,6 +748,7 @@ server_notification_definitions! { ThreadStatusChanged => "thread/status/changed" (v2::ThreadStatusChangedNotification), ThreadArchived => "thread/archived" (v2::ThreadArchivedNotification), ThreadUnarchived => "thread/unarchived" (v2::ThreadUnarchivedNotification), + ThreadClosed => "thread/closed" (v2::ThreadClosedNotification), ThreadNameUpdated => "thread/name/updated" (v2::ThreadNameUpdatedNotification), ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification), TurnStarted => "turn/started" (v2::TurnStartedNotification), @@ -838,6 +765,7 @@ server_notification_definitions! { CommandExecutionOutputDelta => "item/commandExecution/outputDelta" (v2::CommandExecutionOutputDeltaNotification), TerminalInteraction => "item/commandExecution/terminalInteraction" (v2::TerminalInteractionNotification), FileChangeOutputDelta => "item/fileChange/outputDelta" (v2::FileChangeOutputDeltaNotification), + ServerRequestResolved => "serverRequest/resolved" (v2::ServerRequestResolvedNotification), McpToolCallProgress => "item/mcpToolCall/progress" (v2::McpToolCallProgressNotification), McpServerOauthLoginCompleted => "mcpServer/oauthLogin/completed" (v2::McpServerOauthLoginCompletedNotification), AccountUpdated => "account/updated" (v2::AccountUpdatedNotification), @@ -873,12 +801,6 @@ server_notification_definitions! { #[strum(serialize = "account/login/completed")] AccountLoginCompleted(v2::AccountLoginCompletedNotification), - /// DEPRECATED NOTIFICATIONS below - AuthStatusChange(v1::AuthStatusChangeNotification), - - /// Deprecated: use `account/login/completed` instead. - LoginChatGptComplete(v1::LoginChatGptCompleteNotification), - SessionConfigured(v1::SessionConfiguredNotification), } client_notification_definitions! { @@ -892,43 +814,29 @@ mod tests { use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::parse_command::ParsedCommand; - use codex_protocol::protocol::AskForApproval; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use serde_json::json; use std::path::PathBuf; + fn absolute_path(path: &str) -> AbsolutePathBuf { + AbsolutePathBuf::from_absolute_path(path).expect("absolute path") + } + #[test] - fn serialize_new_conversation() -> Result<()> { - let request = ClientRequest::NewConversation { + fn serialize_get_conversation_summary() -> Result<()> { + let request = ClientRequest::GetConversationSummary { request_id: RequestId::Integer(42), - params: v1::NewConversationParams { - model: Some("gpt-5.1-codex-max".to_string()), - model_provider: None, - profile: None, - cwd: None, - approval_policy: Some(AskForApproval::OnRequest), - sandbox: None, - config: None, - base_instructions: None, - developer_instructions: None, - compact_prompt: None, - include_apply_patch_tool: None, + params: v1::GetConversationSummaryParams::ThreadId { + conversation_id: ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")?, }, }; assert_eq!( json!({ - "method": "newConversation", + "method": "getConversationSummary", "id": 42, "params": { - "model": "gpt-5.1-codex-max", - "modelProvider": null, - "profile": null, - "cwd": null, - "approvalPolicy": "on-request", - "sandbox": null, - "config": null, - "baseInstructions": null, - "includeApplyPatchTool": null + "conversationId": "67e55044-10b1-426f-9247-bb680e5fe0c8" } }), serde_json::to_value(&request)?, @@ -1101,6 +1009,7 @@ mod tests { ); let payload = ServerRequestPayload::ExecCommandApproval(params); + assert_eq!(request.id(), &RequestId::Integer(7)); assert_eq!(payload.request_with_id(RequestId::Integer(7)), request); Ok(()) } @@ -1533,13 +1442,14 @@ mod tests { additional_permissions: Some(v2::AdditionalPermissionProfile { network: None, file_system: Some(v2::AdditionalFileSystemPermissions { - read: Some(vec![std::path::PathBuf::from("/tmp/allowed")]), + read: Some(vec![absolute_path("/tmp/allowed")]), write: None, }), macos: None, }), proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, + available_decisions: None, }; let reason = crate::experimental_api::ExperimentalApi::experimental_reason(¶ms); assert_eq!( diff --git a/codex-rs/app-server-protocol/src/protocol/mod.rs b/codex-rs/app-server-protocol/src/protocol/mod.rs index e269332438..1e0410f4b9 100644 --- a/codex-rs/app-server-protocol/src/protocol/mod.rs +++ b/codex-rs/app-server-protocol/src/protocol/mod.rs @@ -3,6 +3,7 @@ pub mod common; mod mappers; +mod serde_helpers; pub mod thread_history; pub mod v1; pub mod v2; diff --git a/codex-rs/app-server-protocol/src/protocol/serde_helpers.rs b/codex-rs/app-server-protocol/src/protocol/serde_helpers.rs new file mode 100644 index 0000000000..0e35ebdba7 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/serde_helpers.rs @@ -0,0 +1,23 @@ +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::Serializer; + +pub fn deserialize_double_option<'de, T, D>(deserializer: D) -> Result>, D::Error> +where + T: Deserialize<'de>, + D: Deserializer<'de>, +{ + serde_with::rust::double_option::deserialize(deserializer) +} + +pub fn serialize_double_option( + value: &Option>, + serializer: S, +) -> Result +where + T: Serialize, + S: Serializer, +{ + serde_with::rust::double_option::serialize(value, serializer) +} 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 c6d0cc00fe..111bab84ce 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -3,6 +3,8 @@ use crate::protocol::v2::CollabAgentTool; use crate::protocol::v2::CollabAgentToolCallStatus; use crate::protocol::v2::CommandAction; use crate::protocol::v2::CommandExecutionStatus; +use crate::protocol::v2::DynamicToolCallOutputContentItem; +use crate::protocol::v2::DynamicToolCallStatus; use crate::protocol::v2::FileUpdateChange; use crate::protocol::v2::McpToolCallError; use crate::protocol::v2::McpToolCallResult; @@ -20,8 +22,10 @@ use codex_protocol::models::MessagePhase; use codex_protocol::protocol::AgentReasoningEvent; use codex_protocol::protocol::AgentReasoningRawContentEvent; use codex_protocol::protocol::AgentStatus; +use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; use codex_protocol::protocol::CompactedItem; use codex_protocol::protocol::ContextCompactedEvent; +use codex_protocol::protocol::DynamicToolCallResponseEvent; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ExecCommandBeginEvent; @@ -123,8 +127,17 @@ impl ThreadHistoryBuilder { EventMsg::WebSearchEnd(payload) => self.handle_web_search_end(payload), EventMsg::ExecCommandBegin(payload) => self.handle_exec_command_begin(payload), EventMsg::ExecCommandEnd(payload) => self.handle_exec_command_end(payload), + EventMsg::ApplyPatchApprovalRequest(payload) => { + self.handle_apply_patch_approval_request(payload) + } EventMsg::PatchApplyBegin(payload) => self.handle_patch_apply_begin(payload), EventMsg::PatchApplyEnd(payload) => self.handle_patch_apply_end(payload), + EventMsg::DynamicToolCallRequest(payload) => { + self.handle_dynamic_tool_call_request(payload) + } + EventMsg::DynamicToolCallResponse(payload) => { + self.handle_dynamic_tool_call_response(payload) + } EventMsg::McpToolCallBegin(payload) => self.handle_mcp_tool_call_begin(payload), EventMsg::McpToolCallEnd(payload) => self.handle_mcp_tool_call_end(payload), EventMsg::ViewImageToolCall(payload) => self.handle_view_image_tool_call(payload), @@ -355,6 +368,19 @@ impl ThreadHistoryBuilder { self.upsert_item_in_turn_id(&payload.turn_id, item); } + fn handle_apply_patch_approval_request(&mut self, payload: &ApplyPatchApprovalRequestEvent) { + let item = ThreadItem::FileChange { + id: payload.call_id.clone(), + changes: convert_patch_changes(&payload.changes), + status: PatchApplyStatus::InProgress, + }; + if payload.turn_id.is_empty() { + self.upsert_item_in_current_turn(item); + } else { + self.upsert_item_in_turn_id(&payload.turn_id, item); + } + } + fn handle_patch_apply_begin(&mut self, payload: &PatchApplyBeginEvent) { let item = ThreadItem::FileChange { id: payload.call_id.clone(), @@ -382,6 +408,49 @@ impl ThreadHistoryBuilder { } } + fn handle_dynamic_tool_call_request( + &mut self, + payload: &codex_protocol::dynamic_tools::DynamicToolCallRequest, + ) { + let item = ThreadItem::DynamicToolCall { + id: payload.call_id.clone(), + tool: payload.tool.clone(), + arguments: payload.arguments.clone(), + status: DynamicToolCallStatus::InProgress, + content_items: None, + success: None, + duration_ms: None, + }; + if payload.turn_id.is_empty() { + self.upsert_item_in_current_turn(item); + } else { + self.upsert_item_in_turn_id(&payload.turn_id, item); + } + } + + fn handle_dynamic_tool_call_response(&mut self, payload: &DynamicToolCallResponseEvent) { + let status = if payload.success { + DynamicToolCallStatus::Completed + } else { + DynamicToolCallStatus::Failed + }; + let duration_ms = i64::try_from(payload.duration.as_millis()).ok(); + let item = ThreadItem::DynamicToolCall { + id: payload.call_id.clone(), + tool: payload.tool.clone(), + arguments: payload.arguments.clone(), + status, + content_items: Some(convert_dynamic_tool_content_items(&payload.content_items)), + success: Some(payload.success), + duration_ms, + }; + if payload.turn_id.is_empty() { + self.upsert_item_in_current_turn(item); + } else { + self.upsert_item_in_turn_id(&payload.turn_id, item); + } + } + fn handle_mcp_tool_call_begin(&mut self, payload: &McpToolCallBeginEvent) { let item = ThreadItem::McpToolCall { id: payload.call_id.clone(), @@ -913,6 +982,23 @@ pub fn convert_patch_changes( converted } +fn convert_dynamic_tool_content_items( + items: &[codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem], +) -> Vec { + items + .iter() + .cloned() + .map(|item| match item { + codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem::InputText { text } => { + DynamicToolCallOutputContentItem::InputText { text } + } + codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem::InputImage { + image_url, + } => DynamicToolCallOutputContentItem::InputImage { image_url }, + }) + .collect() +} + fn map_patch_change_kind(change: &codex_protocol::protocol::FileChange) -> PatchChangeKind { match change { codex_protocol::protocol::FileChange::Add { .. } => PatchChangeKind::Add, @@ -1002,6 +1088,7 @@ impl From<&PendingTurn> for Turn { mod tests { use super::*; use codex_protocol::ThreadId; + use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; use codex_protocol::items::TurnItem as CoreTurnItem; use codex_protocol::items::UserMessageItem as CoreUserMessageItem; use codex_protocol::models::MessagePhase as CoreMessagePhase; @@ -1010,13 +1097,16 @@ mod tests { use codex_protocol::protocol::AgentMessageEvent; use codex_protocol::protocol::AgentReasoningEvent; use codex_protocol::protocol::AgentReasoningRawContentEvent; + use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::CompactedItem; + use codex_protocol::protocol::DynamicToolCallResponseEvent; use codex_protocol::protocol::ExecCommandEndEvent; use codex_protocol::protocol::ExecCommandSource; use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::McpInvocation; use codex_protocol::protocol::McpToolCallEndEvent; + use codex_protocol::protocol::PatchApplyBeginEvent; use codex_protocol::protocol::ThreadRolledBackEvent; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnAbortedEvent; @@ -1606,6 +1696,65 @@ mod tests { ); } + #[test] + fn reconstructs_dynamic_tool_items_from_request_and_response_events() { + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-1".into(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::UserMessage(UserMessageEvent { + message: "run dynamic tool".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + }), + EventMsg::DynamicToolCallRequest( + codex_protocol::dynamic_tools::DynamicToolCallRequest { + call_id: "dyn-1".into(), + turn_id: "turn-1".into(), + tool: "lookup_ticket".into(), + arguments: serde_json::json!({"id":"ABC-123"}), + }, + ), + EventMsg::DynamicToolCallResponse(DynamicToolCallResponseEvent { + call_id: "dyn-1".into(), + turn_id: "turn-1".into(), + tool: "lookup_ticket".into(), + arguments: serde_json::json!({"id":"ABC-123"}), + content_items: vec![CoreDynamicToolCallOutputContentItem::InputText { + text: "Ticket is open".into(), + }], + success: true, + error: None, + duration: Duration::from_millis(42), + }), + ]; + + 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.len(), 2); + assert_eq!( + turns[0].items[1], + ThreadItem::DynamicToolCall { + id: "dyn-1".into(), + tool: "lookup_ticket".into(), + arguments: serde_json::json!({"id":"ABC-123"}), + status: DynamicToolCallStatus::Completed, + content_items: Some(vec![DynamicToolCallOutputContentItem::InputText { + text: "Ticket is open".into(), + }]), + success: Some(true), + duration_ms: Some(42), + } + ); + } + #[test] fn reconstructs_declined_exec_and_patch_items() { let events = vec![ @@ -1850,6 +1999,133 @@ mod tests { ); } + #[test] + fn patch_apply_begin_updates_active_turn_snapshot_with_file_change() { + let turn_id = "turn-1"; + let mut builder = ThreadHistoryBuilder::new(); + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::UserMessage(UserMessageEvent { + message: "apply patch".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + }), + EventMsg::PatchApplyBegin(PatchApplyBeginEvent { + call_id: "patch-call".into(), + turn_id: turn_id.to_string(), + auto_approved: false, + changes: [( + PathBuf::from("README.md"), + codex_protocol::protocol::FileChange::Add { + content: "hello\n".into(), + }, + )] + .into_iter() + .collect(), + }), + ]; + + for event in &events { + builder.handle_event(event); + } + + let snapshot = builder + .active_turn_snapshot() + .expect("active turn snapshot"); + assert_eq!(snapshot.id, turn_id); + assert_eq!(snapshot.status, TurnStatus::InProgress); + assert_eq!( + snapshot.items, + vec![ + ThreadItem::UserMessage { + id: "item-1".into(), + content: vec![UserInput::Text { + text: "apply patch".into(), + text_elements: Vec::new(), + }], + }, + ThreadItem::FileChange { + id: "patch-call".into(), + changes: vec![FileUpdateChange { + path: "README.md".into(), + kind: PatchChangeKind::Add, + diff: "hello\n".into(), + }], + status: PatchApplyStatus::InProgress, + }, + ] + ); + } + + #[test] + fn apply_patch_approval_request_updates_active_turn_snapshot_with_file_change() { + let turn_id = "turn-1"; + let mut builder = ThreadHistoryBuilder::new(); + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.to_string(), + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::UserMessage(UserMessageEvent { + message: "apply patch".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + }), + EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { + call_id: "patch-call".into(), + turn_id: turn_id.to_string(), + changes: [( + PathBuf::from("README.md"), + codex_protocol::protocol::FileChange::Add { + content: "hello\n".into(), + }, + )] + .into_iter() + .collect(), + reason: None, + grant_root: None, + }), + ]; + + for event in &events { + builder.handle_event(event); + } + + let snapshot = builder + .active_turn_snapshot() + .expect("active turn snapshot"); + assert_eq!(snapshot.id, turn_id); + assert_eq!(snapshot.status, TurnStatus::InProgress); + assert_eq!( + snapshot.items, + vec![ + ThreadItem::UserMessage { + id: "item-1".into(), + content: vec![UserInput::Text { + text: "apply patch".into(), + text_elements: Vec::new(), + }], + }, + ThreadItem::FileChange { + id: "patch-call".into(), + changes: vec![FileUpdateChange { + path: "README.md".into(), + kind: PatchChangeKind::Add, + diff: "hello\n".into(), + }], + status: PatchApplyStatus::InProgress, + }, + ] + ); + } + #[test] fn late_turn_complete_does_not_close_active_turn() { let events = vec![ diff --git a/codex-rs/app-server-protocol/src/protocol/v1.rs b/codex-rs/app-server-protocol/src/protocol/v1.rs index 976f4e69d8..d393f97f72 100644 --- a/codex-rs/app-server-protocol/src/protocol/v1.rs +++ b/codex-rs/app-server-protocol/src/protocol/v1.rs @@ -5,6 +5,7 @@ use codex_protocol::ThreadId; use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Verbosity; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; @@ -419,6 +420,13 @@ pub struct SendUserTurnParams { pub approval_policy: AskForApproval, pub sandbox_policy: SandboxPolicy, pub model: String, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + pub service_tier: Option>, pub effort: Option, pub summary: ReasoningSummary, /// Optional JSON Schema used to constrain the final assistant message for this turn. @@ -429,6 +437,55 @@ pub struct SendUserTurnParams { #[serde(rename_all = "camelCase")] pub struct SendUserTurnResponse {} +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use std::path::PathBuf; + + #[test] + fn send_user_turn_params_preserve_explicit_null_service_tier() { + let params = SendUserTurnParams { + conversation_id: ThreadId::new(), + items: vec![], + cwd: PathBuf::from("/tmp"), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: "gpt-4.1".to_string(), + service_tier: Some(None), + effort: None, + summary: ReasoningSummary::Auto, + output_schema: None, + }; + + let serialized = serde_json::to_value(¶ms).expect("params should serialize"); + assert_eq!( + serialized.get("serviceTier"), + Some(&serde_json::Value::Null) + ); + + let roundtrip: SendUserTurnParams = + serde_json::from_value(serialized).expect("params should deserialize"); + assert_eq!(roundtrip.service_tier, Some(None)); + + let without_override = SendUserTurnParams { + conversation_id: ThreadId::new(), + items: vec![], + cwd: PathBuf::from("/tmp"), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: "gpt-4.1".to_string(), + service_tier: None, + effort: None, + summary: ReasoningSummary::Auto, + output_schema: None, + }; + let serialized_without_override = + serde_json::to_value(&without_override).expect("params should serialize"); + assert_eq!(serialized_without_override.get("serviceTier"), None); + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] pub struct InterruptConversationParams { @@ -531,32 +588,11 @@ impl From for CoreTextElement { } } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -/// Deprecated in favor of AccountLoginCompletedNotification. -pub struct LoginChatGptCompleteNotification { - #[schemars(with = "String")] - pub login_id: Uuid, - pub success: bool, - pub error: Option, -} - -#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -pub struct SessionConfiguredNotification { - pub session_id: ThreadId, - pub model: String, - pub reasoning_effort: Option, - pub history_log_id: u64, - #[ts(type = "number")] - pub history_entry_count: usize, - pub initial_messages: Option>, - pub rollout_path: PathBuf, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -/// Deprecated notification. Use AccountUpdatedNotification instead. -pub struct AuthStatusChangeNotification { - pub auth_method: Option, +impl InputItem { + pub fn text_char_count(&self) -> usize { + match self { + InputItem::Text { text, .. } => text.chars().count(), + InputItem::Image { .. } | InputItem::LocalImage { .. } => 0, + } + } } diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 1e4e5d0c31..8f0b37beef 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::path::PathBuf; +use crate::RequestId; use crate::protocol::common::AuthMode; use codex_experimental_api_macros::ExperimentalApi; use codex_protocol::account::PlanType; @@ -10,11 +11,13 @@ use codex_protocol::approvals::NetworkApprovalProtocol as CoreNetworkApprovalPro use codex_protocol::approvals::NetworkPolicyAmendment as CoreNetworkPolicyAmendment; use codex_protocol::approvals::NetworkPolicyRuleAction as CoreNetworkPolicyRuleAction; use codex_protocol::config_types::CollaborationMode; -use codex_protocol::config_types::CollaborationModeMask; +use codex_protocol::config_types::CollaborationModeMask as CoreCollaborationModeMask; use codex_protocol::config_types::ForcedLoginMethod; +use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode as CoreSandboxMode; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; use codex_protocol::items::AgentMessageContent as CoreAgentMessageContent; @@ -30,6 +33,7 @@ use codex_protocol::models::MessagePhase; use codex_protocol::models::PermissionProfile as CorePermissionProfile; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::InputModality; +use codex_protocol::openai_models::ModelAvailabilityNux as CoreModelAvailabilityNux; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::openai_models::default_input_modalities; use codex_protocol::parse_command::ParsedCommand as CoreParsedCommand; @@ -48,6 +52,7 @@ use codex_protocol::protocol::RateLimitWindow as CoreRateLimitWindow; use codex_protocol::protocol::ReadOnlyAccess as CoreReadOnlyAccess; use codex_protocol::protocol::RealtimeAudioFrame as CoreRealtimeAudioFrame; use codex_protocol::protocol::RejectConfig as CoreRejectConfig; +use codex_protocol::protocol::ReviewDecision as CoreReviewDecision; use codex_protocol::protocol::SessionSource as CoreSessionSource; use codex_protocol::protocol::SkillDependencies as CoreSkillDependencies; use codex_protocol::protocol::SkillErrorInfo as CoreSkillErrorInfo; @@ -388,6 +393,7 @@ pub struct ProfileV2 { pub model: Option, pub model_provider: Option, pub approval_policy: Option, + pub service_tier: Option, pub model_reasoning_effort: Option, pub model_reasoning_summary: Option, pub model_verbosity: Option, @@ -499,6 +505,7 @@ pub struct Config { pub model_reasoning_effort: Option, pub model_reasoning_summary: Option, pub model_verbosity: Option, + pub service_tier: Option, pub analytics: Option, #[experimental("config/read.apps")] #[serde(default)] @@ -740,7 +747,8 @@ pub struct ConfigEdit { pub enum CommandExecutionApprovalDecision { /// User approved the command. Accept, - /// User approved the command and future identical commands should run without prompting. + /// User approved the command and future prompts in the same session-scoped + /// approval cache should run without prompting. AcceptForSession, /// User approved the command, and wants to apply the proposed execpolicy amendment so future /// matching commands can run without prompting. @@ -757,6 +765,27 @@ pub enum CommandExecutionApprovalDecision { Cancel, } +impl From for CommandExecutionApprovalDecision { + fn from(value: CoreReviewDecision) -> Self { + match value { + CoreReviewDecision::Approved => Self::Accept, + CoreReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment, + } => Self::AcceptWithExecpolicyAmendment { + execpolicy_amendment: proposed_execpolicy_amendment.into(), + }, + CoreReviewDecision::ApprovedForSession => Self::AcceptForSession, + CoreReviewDecision::NetworkPolicyAmendment { + network_policy_amendment, + } => Self::ApplyNetworkPolicyAmendment { + network_policy_amendment: network_policy_amendment.into(), + }, + CoreReviewDecision::Abort => Self::Cancel, + CoreReviewDecision::Denied => Self::Decline, + } + } +} + v2_enum_from_core! { pub enum NetworkApprovalProtocol from CoreNetworkApprovalProtocol { Http, @@ -787,8 +816,8 @@ impl From for NetworkApprovalContext { #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct AdditionalFileSystemPermissions { - pub read: Option>, - pub write: Option>, + pub read: Option>, + pub write: Option>, } impl From for AdditionalFileSystemPermissions { @@ -1365,6 +1394,21 @@ pub struct ModelListParams { pub include_hidden: Option, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ModelAvailabilityNux { + pub message: String, +} + +impl From for ModelAvailabilityNux { + fn from(value: CoreModelAvailabilityNux) -> Self { + Self { + message: value.message, + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -1372,6 +1416,8 @@ pub struct Model { pub id: String, pub model: String, pub upgrade: Option, + pub upgrade_info: Option, + pub availability_nux: Option, pub display_name: String, pub description: String, pub hidden: bool, @@ -1385,6 +1431,16 @@ pub struct Model { pub is_default: bool, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ModelUpgradeInfo { + pub model: String, + pub upgrade_copy: Option, + pub model_link: Option, + pub migration_markdown: Option, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -1409,6 +1465,30 @@ pub struct ModelListResponse { #[ts(export_to = "v2/")] pub struct CollaborationModeListParams {} +/// EXPERIMENTAL - collaboration mode preset metadata for clients. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct CollaborationModeMask { + pub name: String, + pub mode: Option, + pub model: Option, + #[serde(rename = "reasoning_effort")] + #[ts(rename = "reasoning_effort")] + pub reasoning_effort: Option>, +} + +impl From for CollaborationModeMask { + fn from(value: CoreCollaborationModeMask) -> Self { + Self { + name: value.name, + mode: value.mode, + model: value.model, + reasoning_effort: value.reasoning_effort, + } + } +} + /// EXPERIMENTAL - collaboration mode presets response. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] @@ -1711,6 +1791,14 @@ pub struct ThreadStartParams { pub model: Option, #[ts(optional = nullable)] pub model_provider: Option, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + #[ts(optional = nullable)] + pub service_tier: Option>, #[ts(optional = nullable)] pub cwd: Option, #[ts(optional = nullable)] @@ -1773,6 +1861,7 @@ pub struct ThreadStartResponse { pub thread: Thread, pub model: String, pub model_provider: String, + pub service_tier: Option, pub cwd: PathBuf, pub approval_policy: AskForApproval, pub sandbox: SandboxPolicy, @@ -1814,6 +1903,14 @@ pub struct ThreadResumeParams { pub model: Option, #[ts(optional = nullable)] pub model_provider: Option, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + #[ts(optional = nullable)] + pub service_tier: Option>, #[ts(optional = nullable)] pub cwd: Option, #[ts(optional = nullable)] @@ -1842,6 +1939,7 @@ pub struct ThreadResumeResponse { pub thread: Thread, pub model: String, pub model_provider: String, + pub service_tier: Option, pub cwd: PathBuf, pub approval_policy: AskForApproval, pub sandbox: SandboxPolicy, @@ -1874,6 +1972,14 @@ pub struct ThreadForkParams { pub model: Option, #[ts(optional = nullable)] pub model_provider: Option, + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + #[ts(optional = nullable)] + pub service_tier: Option>, #[ts(optional = nullable)] pub cwd: Option, #[ts(optional = nullable)] @@ -1900,6 +2006,7 @@ pub struct ThreadForkResponse { pub thread: Thread, pub model: String, pub model_provider: String, + pub service_tier: Option, pub cwd: PathBuf, pub approval_policy: AskForApproval, pub sandbox: SandboxPolicy, @@ -1918,6 +2025,29 @@ pub struct ThreadArchiveParams { #[ts(export_to = "v2/")] pub struct ThreadArchiveResponse {} +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadUnsubscribeParams { + pub thread_id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadUnsubscribeResponse { + pub status: ThreadUnsubscribeStatus, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum ThreadUnsubscribeStatus { + NotLoaded, + NotSubscribed, + Unsubscribed, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -2417,6 +2547,8 @@ pub struct Thread { pub id: String, /// Usually the first user message in the thread, if available. pub preview: String, + /// Whether the thread is ephemeral and should not be materialized on disk. + pub ephemeral: bool, /// Model provider used for this thread (for example, 'openai'). pub model_provider: String, /// Unix timestamp (in seconds) when the thread was created. @@ -2455,6 +2587,7 @@ pub struct Thread { #[ts(export_to = "v2/")] pub struct AccountUpdatedNotification { pub auth_mode: Option, + pub plan_type: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -2734,6 +2867,15 @@ pub struct TurnStartParams { /// Override the model for this turn and subsequent turns. #[ts(optional = nullable)] pub model: Option, + /// Override the service tier for this turn and subsequent turns. + #[serde( + default, + deserialize_with = "super::serde_helpers::deserialize_double_option", + serialize_with = "super::serde_helpers::serialize_double_option", + skip_serializing_if = "Option::is_none" + )] + #[ts(optional = nullable)] + pub service_tier: Option>, /// Override the reasoning effort for this turn and subsequent turns. #[ts(optional = nullable)] pub effort: Option, @@ -2981,6 +3123,18 @@ impl From for UserInput { } } +impl UserInput { + pub fn text_char_count(&self) -> usize { + match self { + UserInput::Text { text, .. } => text.chars().count(), + UserInput::Image { .. } + | UserInput::LocalImage { .. } + | UserInput::Skill { .. } + | UserInput::Mention { .. } => 0, + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(tag = "type", rename_all = "camelCase")] #[ts(tag = "type")] @@ -3057,6 +3211,19 @@ pub enum ThreadItem { }, #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] + DynamicToolCall { + id: String, + tool: String, + arguments: JsonValue, + status: DynamicToolCallStatus, + content_items: Option>, + success: Option, + /// The duration of the dynamic tool call in milliseconds. + #[ts(type = "number | null")] + duration_ms: Option, + }, + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] CollabAgentToolCall { /// Unique identifier for this collab tool call. id: String, @@ -3105,6 +3272,7 @@ impl ThreadItem { | ThreadItem::CommandExecution { id, .. } | ThreadItem::FileChange { id, .. } | ThreadItem::McpToolCall { id, .. } + | ThreadItem::DynamicToolCall { id, .. } | ThreadItem::CollabAgentToolCall { id, .. } | ThreadItem::WebSearch { id, .. } | ThreadItem::ImageView { id, .. } @@ -3285,6 +3453,15 @@ pub enum McpToolCallStatus { Failed, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum DynamicToolCallStatus { + InProgress, + Completed, + Failed, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -3396,6 +3573,13 @@ pub struct ThreadUnarchivedNotification { pub thread_id: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadClosedNotification { + pub thread_id: String, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -3604,6 +3788,14 @@ pub struct FileChangeOutputDeltaNotification { pub delta: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ServerRequestResolvedNotification { + pub thread_id: String, + pub request_id: RequestId, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -3724,6 +3916,11 @@ pub struct CommandExecutionRequestApprovalParams { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional = nullable)] pub proposed_network_policy_amendments: Option>, + /// Ordered list of decisions the client may present for this prompt. + #[experimental("item/commandExecution/requestApproval.availableDecisions")] + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub available_decisions: Option>, } impl CommandExecutionRequestApprovalParams { @@ -3764,29 +3961,6 @@ pub struct FileChangeRequestApprovalResponse { pub decision: FileChangeApprovalDecision, } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)] -#[serde(rename_all = "camelCase")] -#[ts(export_to = "v2/")] -pub struct SkillRequestApprovalParams { - pub item_id: String, - pub skill_name: String, -} - -#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -#[ts(export_to = "v2/")] -pub enum SkillApprovalDecision { - Approve, - Decline, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -#[ts(export_to = "v2/")] -pub struct SkillRequestApprovalResponse { - pub decision: SkillApprovalDecision, -} - #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -4047,6 +4221,37 @@ mod tests { AbsolutePathBuf::from_absolute_path(path).expect("path must be absolute") } + #[test] + fn command_execution_request_approval_rejects_relative_additional_permission_paths() { + let err = serde_json::from_value::(json!({ + "threadId": "thr_123", + "turnId": "turn_123", + "itemId": "call_123", + "command": "cat file", + "cwd": "/tmp", + "commandActions": null, + "reason": null, + "networkApprovalContext": null, + "additionalPermissions": { + "network": null, + "fileSystem": { + "read": ["relative/path"], + "write": null + }, + "macos": null + }, + "proposedExecpolicyAmendment": null, + "proposedNetworkPolicyAmendments": null, + "availableDecisions": null + })) + .expect_err("relative additional permission paths should fail"); + assert!( + err.to_string() + .contains("AbsolutePathBuf deserialized without a base path"), + "unexpected error: {err}" + ); + } + #[test] fn sandbox_policy_round_trips_external_sandbox_network_access() { let v2_policy = SandboxPolicy::ExternalSandbox { @@ -4400,4 +4605,56 @@ mod tests { }) ); } + + #[test] + fn thread_start_params_preserve_explicit_null_service_tier() { + let params: ThreadStartParams = serde_json::from_value(json!({ "serviceTier": null })) + .expect("params should deserialize"); + assert_eq!(params.service_tier, Some(None)); + + let serialized = serde_json::to_value(¶ms).expect("params should serialize"); + assert_eq!( + serialized.get("serviceTier"), + Some(&serde_json::Value::Null) + ); + + let serialized_without_override = + serde_json::to_value(ThreadStartParams::default()).expect("params should serialize"); + assert_eq!(serialized_without_override.get("serviceTier"), None); + } + + #[test] + fn turn_start_params_preserve_explicit_null_service_tier() { + let params: TurnStartParams = serde_json::from_value(json!({ + "threadId": "thread_123", + "input": [], + "serviceTier": null + })) + .expect("params should deserialize"); + assert_eq!(params.service_tier, Some(None)); + + let serialized = serde_json::to_value(¶ms).expect("params should serialize"); + assert_eq!( + serialized.get("serviceTier"), + Some(&serde_json::Value::Null) + ); + + let without_override = TurnStartParams { + thread_id: "thread_123".to_string(), + input: vec![], + cwd: None, + approval_policy: None, + sandbox_policy: None, + model: None, + service_tier: None, + effort: None, + summary: None, + output_schema: None, + collaboration_mode: None, + personality: None, + }; + let serialized_without_override = + serde_json::to_value(&without_override).expect("params should serialize"); + assert_eq!(serialized_without_override.get("serviceTier"), None); + } } diff --git a/codex-rs/app-server-test-client/README.md b/codex-rs/app-server-test-client/README.md index ab11f12353..9a55391327 100644 --- a/codex-rs/app-server-test-client/README.md +++ b/codex-rs/app-server-test-client/README.md @@ -18,6 +18,15 @@ cargo run -p codex-app-server-test-client -- \ cargo run -p codex-app-server-test-client -- model-list ``` +## Watching Raw Inbound Traffic + +Initialize a connection, then print every inbound JSON-RPC message until you stop it with +`Ctrl+C`: + +```bash +cargo run -p codex-app-server-test-client -- watch +``` + ## Testing Thread Rejoin Behavior Build and start an app server using commands above. The app-server log is written to `/tmp/codex-app-server-test-client/app-server.log` diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index a9225b0426..7baad9be66 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -15,6 +15,7 @@ use std::process::Command; use std::process::Stdio; use std::thread; use std::time::Duration; +use std::time::SystemTime; use anyhow::Context; use anyhow::Result; @@ -22,8 +23,7 @@ use anyhow::bail; use clap::ArgAction; use clap::Parser; use clap::Subcommand; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; +use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientRequest; @@ -39,27 +39,18 @@ use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeParams; use codex_app_server_protocol::InitializeResponse; -use codex_app_server_protocol::InputItem; 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::LoginChatGptCompleteNotification; -use codex_app_server_protocol::LoginChatGptResponse; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::ReadOnlyAccess; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SandboxPolicy; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::SkillApprovalDecision; -use codex_app_server_protocol::SkillRequestApprovalParams; -use codex_app_server_protocol::SkillRequestApprovalResponse; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadListResponse; @@ -71,9 +62,7 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; -use codex_protocol::ThreadId; -use codex_protocol::protocol::Event; -use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::W3cTraceContext; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::Value; @@ -107,6 +96,8 @@ const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[ "item/reasoning/summaryTextDelta", "item/reasoning/textDelta", ]; +const APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); +const APP_SERVER_GRACEFUL_SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100); /// Minimal launcher that initializes the Codex app-server and logs the handshake. #[derive(Parser)] @@ -191,6 +182,10 @@ enum CliCommand { /// Existing thread id to resume. thread_id: String, }, + /// Initialize the app-server and dump all inbound messages until interrupted. + /// + /// This command does not auto-exit; stop it with SIGINT/SIGTERM/SIGKILL. + Watch, /// Start a V2 turn that elicits an ExecCommand approval. #[command(name = "trigger-cmd-approval")] TriggerCmdApproval { @@ -294,6 +289,11 @@ pub fn run() -> Result<()> { let endpoint = resolve_endpoint(codex_bin, url)?; thread_resume_follow(&endpoint, &config_overrides, thread_id) } + CliCommand::Watch => { + ensure_dynamic_tools_unused(&dynamic_tools, "watch")?; + let endpoint = resolve_endpoint(codex_bin, url)?; + watch(&endpoint, &config_overrides) + } CliCommand::TriggerCmdApproval { user_message } => { let endpoint = resolve_endpoint(codex_bin, url)?; trigger_cmd_approval(&endpoint, &config_overrides, user_message, &dynamic_tools) @@ -492,25 +492,16 @@ fn send_message( config_overrides: &[String], user_message: String, ) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; - - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); - - let conversation = client.start_thread()?; - println!("< newConversation response: {conversation:?}"); - - let subscription = client.add_conversation_listener(&conversation.conversation_id)?; - println!("< addConversationListener response: {subscription:?}"); - - let send_response = client.send_user_message(&conversation.conversation_id, &user_message)?; - println!("< sendUserMessage response: {send_response:?}"); - - client.stream_conversation(&conversation.conversation_id)?; - - client.remove_thread_listener(subscription.subscription_id)?; - - Ok(()) + let dynamic_tools = None; + send_message_v2_with_policies( + endpoint, + config_overrides, + user_message, + false, + None, + None, + &dynamic_tools, + ) } pub fn send_message_v2( @@ -568,82 +559,85 @@ fn trigger_zsh_fork_multi_cmd_approval( let default_prompt = "Run this exact command using shell command execution without rewriting or splitting it: /usr/bin/true && /usr/bin/true"; let message = user_message.unwrap_or_else(|| default_prompt.to_string()); - let mut client = CodexClient::connect(endpoint, config_overrides)?; - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let thread_response = client.thread_start(ThreadStartParams { - dynamic_tools: dynamic_tools.clone(), - ..Default::default() - })?; - println!("< thread/start response: {thread_response:?}"); + let thread_response = client.thread_start(ThreadStartParams { + dynamic_tools: dynamic_tools.clone(), + ..Default::default() + })?; + println!("< thread/start response: {thread_response:?}"); - client.command_approval_behavior = match abort_on { - Some(index) => CommandApprovalBehavior::AbortOn(index), - None => CommandApprovalBehavior::AlwaysAccept, - }; - client.command_approval_count = 0; - client.command_approval_item_ids.clear(); - client.command_execution_statuses.clear(); - client.last_turn_status = None; + client.command_approval_behavior = match abort_on { + Some(index) => CommandApprovalBehavior::AbortOn(index), + None => CommandApprovalBehavior::AlwaysAccept, + }; + client.command_approval_count = 0; + client.command_approval_item_ids.clear(); + client.command_execution_statuses.clear(); + client.last_turn_status = None; - let mut turn_params = TurnStartParams { - thread_id: thread_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: message, - text_elements: Vec::new(), - }], - ..Default::default() - }; - turn_params.approval_policy = Some(AskForApproval::OnRequest); - turn_params.sandbox_policy = Some(SandboxPolicy::ReadOnly { - access: ReadOnlyAccess::FullAccess, - }); + let mut turn_params = TurnStartParams { + thread_id: thread_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: message, + text_elements: Vec::new(), + }], + ..Default::default() + }; + turn_params.approval_policy = Some(AskForApproval::OnRequest); + turn_params.sandbox_policy = Some(SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::FullAccess, + }); - let turn_response = client.turn_start(turn_params)?; - println!("< turn/start response: {turn_response:?}"); - client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; + let turn_response = client.turn_start(turn_params)?; + println!("< turn/start response: {turn_response:?}"); + client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; - if client.command_approval_count < min_approvals { - bail!( - "expected at least {min_approvals} command approvals, got {}", - client.command_approval_count - ); - } - let mut approvals_per_item = std::collections::BTreeMap::new(); - for item_id in &client.command_approval_item_ids { - *approvals_per_item.entry(item_id.clone()).or_insert(0usize) += 1; - } - let max_approvals_for_one_item = approvals_per_item.values().copied().max().unwrap_or(0); - if max_approvals_for_one_item < min_approvals { - bail!( - "expected at least {min_approvals} approvals for one command item, got max {max_approvals_for_one_item} with map {approvals_per_item:?}" - ); - } - - let last_command_status = client.command_execution_statuses.last(); - if abort_on.is_none() { - if last_command_status != Some(&CommandExecutionStatus::Completed) { - bail!("expected completed command execution, got {last_command_status:?}"); - } - if client.last_turn_status != Some(TurnStatus::Completed) { + if client.command_approval_count < min_approvals { bail!( - "expected completed turn in all-accept flow, got {:?}", - client.last_turn_status + "expected at least {min_approvals} command approvals, got {}", + client.command_approval_count ); } - } else if last_command_status == Some(&CommandExecutionStatus::Completed) { - bail!( - "expected non-completed command execution in mixed approval/decline flow, got {last_command_status:?}" + let mut approvals_per_item = std::collections::BTreeMap::new(); + for item_id in &client.command_approval_item_ids { + *approvals_per_item.entry(item_id.clone()).or_insert(0usize) += 1; + } + let max_approvals_for_one_item = approvals_per_item.values().copied().max().unwrap_or(0); + if max_approvals_for_one_item < min_approvals { + bail!( + "expected at least {min_approvals} approvals for one command item, got max {max_approvals_for_one_item} with map {approvals_per_item:?}" + ); + } + + let last_command_status = client.command_execution_statuses.last(); + if abort_on.is_none() { + if last_command_status != Some(&CommandExecutionStatus::Completed) { + bail!("expected completed command execution, got {last_command_status:?}"); + } + if client.last_turn_status != Some(TurnStatus::Completed) { + bail!( + "expected completed turn in all-accept flow, got {:?}", + client.last_turn_status + ); + } + } else if last_command_status == Some(&CommandExecutionStatus::Completed) { + bail!( + "expected non-completed command execution in mixed approval/decline flow, got {last_command_status:?}" + ); + } + + println!( + "[zsh-fork multi-approval summary] approvals={}, approvals_per_item={approvals_per_item:?}, command_statuses={:?}, turn_status={:?}", + client.command_approval_count, + client.command_execution_statuses, + client.last_turn_status ); - } - println!( - "[zsh-fork multi-approval summary] approvals={}, approvals_per_item={approvals_per_item:?}, command_statuses={:?}, turn_status={:?}", - client.command_approval_count, client.command_execution_statuses, client.last_turn_status - ); - - Ok(()) + Ok(()) + }) } fn resume_message_v2( @@ -655,30 +649,30 @@ fn resume_message_v2( ) -> Result<()> { ensure_dynamic_tools_unused(dynamic_tools, "resume-message-v2")?; - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + let resume_response = client.thread_resume(ThreadResumeParams { + thread_id, + ..Default::default() + })?; + println!("< thread/resume response: {resume_response:?}"); - let resume_response = client.thread_resume(ThreadResumeParams { - thread_id, - ..Default::default() - })?; - println!("< thread/resume response: {resume_response:?}"); + let turn_response = client.turn_start(TurnStartParams { + thread_id: resume_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: user_message, + text_elements: Vec::new(), + }], + ..Default::default() + })?; + println!("< turn/start response: {turn_response:?}"); - let turn_response = client.turn_start(TurnStartParams { - thread_id: resume_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: user_message, - text_elements: Vec::new(), - }], - ..Default::default() - })?; - println!("< turn/start response: {turn_response:?}"); + client.stream_turn(&resume_response.thread.id, &turn_response.turn.id)?; - client.stream_turn(&resume_response.thread.id, &turn_response.turn.id)?; - - Ok(()) + Ok(()) + }) } fn thread_resume_follow( @@ -701,6 +695,16 @@ fn thread_resume_follow( client.stream_notifications_forever() } +fn watch(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { + let mut client = CodexClient::connect(endpoint, config_overrides)?; + + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); + println!("< streaming inbound messages until process is terminated"); + + client.stream_notifications_forever() +} + fn trigger_cmd_approval( endpoint: &Endpoint, config_overrides: &[String], @@ -771,34 +775,34 @@ fn send_message_v2_with_policies( sandbox_policy: Option, dynamic_tools: &Option>, ) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize_with_experimental_api(experimental_api)?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize_with_experimental_api(experimental_api)?; - println!("< initialize response: {initialize:?}"); + let thread_response = client.thread_start(ThreadStartParams { + dynamic_tools: dynamic_tools.clone(), + ..Default::default() + })?; + println!("< thread/start response: {thread_response:?}"); + let mut turn_params = TurnStartParams { + thread_id: thread_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: user_message, + // Test client sends plain text without UI element ranges. + text_elements: Vec::new(), + }], + ..Default::default() + }; + turn_params.approval_policy = approval_policy; + turn_params.sandbox_policy = sandbox_policy; - let thread_response = client.thread_start(ThreadStartParams { - dynamic_tools: dynamic_tools.clone(), - ..Default::default() - })?; - println!("< thread/start response: {thread_response:?}"); - let mut turn_params = TurnStartParams { - thread_id: thread_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: user_message, - // Test client sends plain text without UI element ranges. - text_elements: Vec::new(), - }], - ..Default::default() - }; - turn_params.approval_policy = approval_policy; - turn_params.sandbox_policy = sandbox_policy; + let turn_response = client.turn_start(turn_params)?; + println!("< turn/start response: {turn_response:?}"); - let turn_response = client.turn_start(turn_params)?; - println!("< turn/start response: {turn_response:?}"); + client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; - client.stream_turn(&thread_response.thread.id, &turn_response.turn.id)?; - - Ok(()) + Ok(()) + }) } fn send_follow_up_v2( @@ -808,119 +812,130 @@ fn send_follow_up_v2( follow_up_message: String, dynamic_tools: &Option>, ) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + let thread_response = client.thread_start(ThreadStartParams { + dynamic_tools: dynamic_tools.clone(), + ..Default::default() + })?; + println!("< thread/start response: {thread_response:?}"); - let thread_response = client.thread_start(ThreadStartParams { - dynamic_tools: dynamic_tools.clone(), - ..Default::default() - })?; - println!("< thread/start response: {thread_response:?}"); + let first_turn_params = TurnStartParams { + thread_id: thread_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: first_message, + // Test client sends plain text without UI element ranges. + text_elements: Vec::new(), + }], + ..Default::default() + }; + let first_turn_response = client.turn_start(first_turn_params)?; + println!("< turn/start response (initial): {first_turn_response:?}"); + client.stream_turn(&thread_response.thread.id, &first_turn_response.turn.id)?; - let first_turn_params = TurnStartParams { - thread_id: thread_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: first_message, - // Test client sends plain text without UI element ranges. - text_elements: Vec::new(), - }], - ..Default::default() - }; - let first_turn_response = client.turn_start(first_turn_params)?; - println!("< turn/start response (initial): {first_turn_response:?}"); - client.stream_turn(&thread_response.thread.id, &first_turn_response.turn.id)?; + let follow_up_params = TurnStartParams { + thread_id: thread_response.thread.id.clone(), + input: vec![V2UserInput::Text { + text: follow_up_message, + // Test client sends plain text without UI element ranges. + text_elements: Vec::new(), + }], + ..Default::default() + }; + let follow_up_response = client.turn_start(follow_up_params)?; + println!("< turn/start response (follow-up): {follow_up_response:?}"); + client.stream_turn(&thread_response.thread.id, &follow_up_response.turn.id)?; - let follow_up_params = TurnStartParams { - thread_id: thread_response.thread.id.clone(), - input: vec![V2UserInput::Text { - text: follow_up_message, - // Test client sends plain text without UI element ranges. - text_elements: Vec::new(), - }], - ..Default::default() - }; - let follow_up_response = client.turn_start(follow_up_params)?; - println!("< turn/start response (follow-up): {follow_up_response:?}"); - client.stream_turn(&thread_response.thread.id, &follow_up_response.turn.id)?; - - Ok(()) + Ok(()) + }) } fn test_login(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + let login_response = client.login_account_chatgpt()?; + println!("< account/login/start response: {login_response:?}"); + let LoginAccountResponse::Chatgpt { login_id, auth_url } = login_response else { + bail!("expected chatgpt login response"); + }; + println!("Open the following URL in your browser to continue:\n{auth_url}"); - let login_response = client.login_chat_gpt()?; - println!("< loginChatGpt response: {login_response:?}"); - println!( - "Open the following URL in your browser to continue:\n{}", - login_response.auth_url - ); + let completion = client.wait_for_account_login_completion(&login_id)?; + println!("< account/login/completed notification: {completion:?}"); - let completion = client.wait_for_login_completion(&login_response.login_id)?; - println!("< loginChatGptComplete notification: {completion:?}"); - - if completion.success { - println!("Login succeeded."); - Ok(()) - } else { - bail!( - "login failed: {}", - completion - .error - .as_deref() - .unwrap_or("unknown error from loginChatGptComplete") - ); - } + if completion.success { + println!("Login succeeded."); + Ok(()) + } else { + bail!( + "login failed: {}", + completion + .error + .as_deref() + .unwrap_or("unknown error from account/login/completed") + ); + } + }) } fn get_account_rate_limits(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + let response = client.get_account_rate_limits()?; + println!("< account/rateLimits/read response: {response:?}"); - let response = client.get_account_rate_limits()?; - println!("< account/rateLimits/read response: {response:?}"); - - Ok(()) + Ok(()) + }) } fn model_list(endpoint: &Endpoint, config_overrides: &[String]) -> Result<()> { - let mut client = CodexClient::connect(endpoint, config_overrides)?; + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); + let response = client.model_list(ModelListParams::default())?; + println!("< model/list response: {response:?}"); - let response = client.model_list(ModelListParams::default())?; - println!("< model/list response: {response:?}"); - - Ok(()) + Ok(()) + }) } fn thread_list(endpoint: &Endpoint, config_overrides: &[String], limit: u32) -> Result<()> { + with_client(endpoint, config_overrides, |client| { + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); + + let response = client.thread_list(ThreadListParams { + cursor: None, + limit: Some(limit), + sort_key: None, + model_providers: None, + source_kinds: None, + archived: None, + cwd: None, + search_term: None, + })?; + println!("< thread/list response: {response:?}"); + + Ok(()) + }) +} + +fn with_client( + endpoint: &Endpoint, + config_overrides: &[String], + f: impl FnOnce(&mut CodexClient) -> Result, +) -> Result { let mut client = CodexClient::connect(endpoint, config_overrides)?; - - let initialize = client.initialize()?; - println!("< initialize response: {initialize:?}"); - - let response = client.thread_list(ThreadListParams { - cursor: None, - limit: Some(limit), - sort_key: None, - model_providers: None, - source_kinds: None, - archived: None, - cwd: None, - search_term: None, - })?; - println!("< thread/list response: {response:?}"); - - Ok(()) + let result = f(&mut client); + client.print_trace_summary(); + result } fn ensure_dynamic_tools_unused( @@ -977,6 +992,8 @@ struct CodexClient { command_approval_item_ids: Vec, command_execution_statuses: Vec, last_turn_status: Option, + trace_id: String, + trace_root_span_id: String, } #[derive(Debug, Clone, Copy)] @@ -1036,6 +1053,8 @@ impl CodexClient { command_approval_item_ids: Vec::new(), command_execution_statuses: Vec::new(), last_turn_status: None, + trace_id: generate_trace_id(), + trace_root_span_id: generate_parent_span_id(), }) } @@ -1057,6 +1076,8 @@ impl CodexClient { command_approval_item_ids: Vec::new(), command_execution_statuses: Vec::new(), last_turn_status: None, + trace_id: generate_trace_id(), + trace_root_span_id: generate_parent_span_id(), }) } @@ -1101,69 +1122,6 @@ impl CodexClient { Ok(response) } - fn start_thread(&mut self) -> Result { - let request_id = self.request_id(); - let request = ClientRequest::NewConversation { - request_id: request_id.clone(), - params: NewConversationParams::default(), - }; - - self.send_request(request, request_id, "newConversation") - } - - fn add_conversation_listener( - &mut self, - conversation_id: &ThreadId, - ) -> Result { - let request_id = self.request_id(); - let request = ClientRequest::AddConversationListener { - request_id: request_id.clone(), - params: AddConversationListenerParams { - conversation_id: *conversation_id, - experimental_raw_events: false, - }, - }; - - self.send_request(request, request_id, "addConversationListener") - } - - fn remove_thread_listener(&mut self, subscription_id: Uuid) -> Result<()> { - let request_id = self.request_id(); - let request = ClientRequest::RemoveConversationListener { - request_id: request_id.clone(), - params: codex_app_server_protocol::RemoveConversationListenerParams { subscription_id }, - }; - - self.send_request::( - request, - request_id, - "removeConversationListener", - )?; - - Ok(()) - } - - fn send_user_message( - &mut self, - conversation_id: &ThreadId, - message: &str, - ) -> Result { - let request_id = self.request_id(); - let request = ClientRequest::SendUserMessage { - request_id: request_id.clone(), - params: SendUserMessageParams { - conversation_id: *conversation_id, - items: vec![InputItem::Text { - text: message.to_string(), - // Test client sends plain text without UI element ranges. - text_elements: Vec::new(), - }], - }, - }; - - self.send_request(request, request_id, "sendUserMessage") - } - fn thread_start(&mut self, params: ThreadStartParams) -> Result { let request_id = self.request_id(); let request = ClientRequest::ThreadStart { @@ -1194,14 +1152,14 @@ impl CodexClient { self.send_request(request, request_id, "turn/start") } - fn login_chat_gpt(&mut self) -> Result { + fn login_account_chatgpt(&mut self) -> Result { let request_id = self.request_id(); - let request = ClientRequest::LoginChatGpt { + let request = ClientRequest::LoginAccount { request_id: request_id.clone(), - params: None, + params: codex_app_server_protocol::LoginAccountParams::Chatgpt, }; - self.send_request(request, request_id, "loginChatGpt") + self.send_request(request, request_id, "account/login/start") } fn get_account_rate_limits(&mut self) -> Result { @@ -1234,77 +1192,31 @@ impl CodexClient { self.send_request(request, request_id, "thread/list") } - fn stream_conversation(&mut self, conversation_id: &ThreadId) -> Result<()> { - loop { - let notification = self.next_notification()?; - - if !notification.method.starts_with("codex/event/") { - continue; - } - - if let Some(event) = self.extract_event(notification, conversation_id)? { - match &event.msg { - EventMsg::AgentMessage(event) => { - println!("{}", event.message); - } - EventMsg::AgentMessageDelta(event) => { - print!("{}", event.delta); - std::io::stdout().flush().ok(); - } - EventMsg::TurnComplete(event) => { - println!("\n[task complete: {event:?}]"); - break; - } - EventMsg::TurnAborted(event) => { - println!("\n[turn aborted: {:?}]", event.reason); - break; - } - EventMsg::Error(event) => { - println!("[error] {event:?}"); - } - _ => { - println!("[UNKNOWN EVENT] {:?}", event.msg); - } - } - } - } - - Ok(()) - } - - fn wait_for_login_completion( + fn wait_for_account_login_completion( &mut self, - expected_login_id: &Uuid, - ) -> Result { + expected_login_id: &str, + ) -> Result { loop { let notification = self.next_notification()?; if let Ok(server_notification) = ServerNotification::try_from(notification) { match server_notification { - ServerNotification::LoginChatGptComplete(completion) => { - if &completion.login_id == expected_login_id { + ServerNotification::AccountLoginCompleted(completion) => { + if completion.login_id.as_deref() == Some(expected_login_id) { return Ok(completion); } println!( - "[ignoring loginChatGptComplete for unexpected login_id: {}]", + "[ignoring account/login/completed for unexpected login_id: {:?}]", completion.login_id ); } - ServerNotification::AuthStatusChange(status) => { - println!("< authStatusChange notification: {status:?}"); - } ServerNotification::AccountRateLimitsUpdated(snapshot) => { println!("< accountRateLimitsUpdated notification: {snapshot:?}"); } - ServerNotification::SessionConfigured(_) => { - // SessionConfigured notifications are unrelated to login; skip. - } _ => {} } } - - // Not a server notification (likely a conversation event); keep waiting. } } @@ -1378,36 +1290,6 @@ impl CodexClient { } } - fn extract_event( - &self, - notification: JSONRPCNotification, - conversation_id: &ThreadId, - ) -> Result> { - let params = notification - .params - .context("event notification missing params")?; - - let mut map = match params { - Value::Object(map) => map, - other => bail!("unexpected params shape: {other:?}"), - }; - - let conversation_value = map - .remove("conversationId") - .context("event missing conversationId")?; - let notification_conversation: ThreadId = serde_json::from_value(conversation_value) - .context("conversationId was not a valid UUID")?; - - if ¬ification_conversation != conversation_id { - return Ok(None); - } - - let event_value = Value::Object(map); - let event: Event = - serde_json::from_value(event_value).context("failed to decode event payload")?; - Ok(Some(event)) - } - fn send_request( &mut self, request: ClientRequest, @@ -1422,12 +1304,32 @@ impl CodexClient { } fn write_request(&mut self, request: &ClientRequest) -> Result<()> { - let request_json = serde_json::to_string(request)?; - let request_pretty = serde_json::to_string_pretty(request)?; + let request = self.jsonrpc_request_with_trace(request)?; + let request_json = serde_json::to_string(&request)?; + let request_pretty = serde_json::to_string_pretty(&request)?; print_multiline_with_prefix("> ", &request_pretty); self.write_payload(&request_json) } + fn jsonrpc_request_with_trace(&self, request: &ClientRequest) -> Result { + let request_value = serde_json::to_value(request)?; + let mut request: JSONRPCRequest = serde_json::from_value(request_value) + .context("client request was not a valid JSON-RPC request")?; + request.trace = Some(W3cTraceContext { + traceparent: Some(format!( + "00-{}-{}-01", + self.trace_id, self.trace_root_span_id + )), + tracestate: None, + }); + Ok(request) + } + + fn print_trace_summary(&self) { + println!("\n[Datadog trace]"); + println!("go/trace/{}\n", self.trace_id); + } + fn wait_for_response(&mut self, request_id: RequestId, method: &str) -> Result where T: DeserializeOwned, @@ -1511,9 +1413,6 @@ impl CodexClient { ServerRequest::FileChangeRequestApproval { request_id, params } => { self.approve_file_change_request(request_id, params)?; } - ServerRequest::SkillRequestApproval { request_id, params } => { - self.approve_skill_request(request_id, params)?; - } other => { bail!("received unsupported server request: {other:?}"); } @@ -1540,6 +1439,7 @@ impl CodexClient { additional_permissions, proposed_execpolicy_amendment, proposed_network_policy_amendments, + available_decisions, } = params; println!( @@ -1554,6 +1454,9 @@ impl CodexClient { if let Some(network_approval_context) = network_approval_context.as_ref() { println!("< network approval context: {network_approval_context:?}"); } + if let Some(available_decisions) = available_decisions.as_ref() { + println!("< available decisions: {available_decisions:?}"); + } if let Some(command) = command.as_deref() { println!("< command: {command}"); } @@ -1593,22 +1496,6 @@ impl CodexClient { Ok(()) } - fn approve_skill_request( - &mut self, - request_id: RequestId, - params: SkillRequestApprovalParams, - ) -> Result<()> { - println!( - "\n< skill approval requested for item {}, skill {}", - params.item_id, params.skill_name - ); - let response = SkillRequestApprovalResponse { - decision: SkillApprovalDecision::Approve, - }; - self.send_server_request_response(request_id, &response)?; - Ok(()) - } - fn approve_file_change_request( &mut self, request_id: RequestId, @@ -1708,6 +1595,15 @@ impl CodexClient { } } +fn generate_trace_id() -> String { + Uuid::new_v4().simple().to_string() +} + +fn generate_parent_span_id() -> String { + let uuid = Uuid::new_v4().simple().to_string(); + uuid[..16].to_string() +} + fn print_multiline_with_prefix(prefix: &str, payload: &str) { for line in payload.lines() { println!("{prefix}{line}"); @@ -1727,11 +1623,18 @@ impl Drop for CodexClient { return; } - thread::sleep(Duration::from_millis(100)); + let deadline = SystemTime::now() + APP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT; + loop { + if let Ok(Some(status)) = child.try_wait() { + println!("[codex app-server exited: {status}]"); + return; + } - if let Ok(Some(status)) = child.try_wait() { - println!("[codex app-server exited: {status}]"); - return; + if SystemTime::now() >= deadline { + break; + } + + thread::sleep(APP_SERVER_GRACEFUL_SHUTDOWN_POLL_INTERVAL); } let _ = child.kill(); diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index eebaaba107..ba2355f675 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -21,6 +21,7 @@ async-trait = { workspace = true } codex-arg0 = { workspace = true } codex-cloud-requirements = { workspace = true } codex-core = { workspace = true } +codex-otel = { workspace = true } codex-shell-command = { workspace = true } codex-utils-cli = { workspace = true } codex-backend-client = { workspace = true } @@ -31,6 +32,7 @@ codex-protocol = { workspace = true } codex-app-server-protocol = { workspace = true } codex-feedback = { workspace = true } codex-rmcp-client = { workspace = true } +codex-state = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-json-to-toml = { workspace = true } chrono = { workspace = true } @@ -63,11 +65,9 @@ axum = { workspace = true, default-features = false, features = [ "tokio", ] } base64 = { workspace = true } -codex-execpolicy = { workspace = true } core_test_support = { workspace = true } codex-state = { workspace = true } codex-utils-cargo-bin = { workspace = true } -os_info = { workspace = true } pretty_assertions = { workspace = true } rmcp = { workspace = true, default-features = false, features = [ "server", diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 08b7c8df0d..9ec4821e8d 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -62,7 +62,8 @@ Use the thread APIs to create, list, or archive conversations. Drive a conversat - Initialize once per connection: Immediately after opening a transport connection, send an `initialize` request with your client metadata, then emit an `initialized` notification. Any other request on that connection before this handshake gets rejected. - Start (or resume) a thread: Call `thread/start` to open a fresh conversation. The response returns the thread object and you’ll also get a `thread/started` notification. If you’re continuing an existing conversation, call `thread/resume` with its ID instead. If you want to branch from an existing conversation, call `thread/fork` to create a new thread id with copied history. -- Begin a turn: To send user input, call `turn/start` with the target `threadId` and the user's input. Optional fields let you override model, cwd, sandbox policy, etc. This immediately returns the new turn object and triggers a `turn/started` notification. + The returned `thread.ephemeral` flag tells you whether the session is intentionally in-memory only; when it is `true`, `thread.path` is `null`. +- Begin a turn: To send user input, call `turn/start` with the target `threadId` and the user's input. Optional fields let you override model, cwd, sandbox policy, etc. This immediately returns the new turn object. The app-server emits `turn/started` when that turn actually begins running. - Stream events: After `turn/start`, keep reading JSON-RPC notifications on stdout. You’ll see `item/started`, `item/completed`, deltas like `item/agentMessage/delta`, tool progress, etc. These represent streaming model output plus any side effects (commands, tool calls, reasoning notes). - Finish the turn: When the model is done (or the turn is interrupted via making the `turn/interrupt` call), the server sends `turn/completed` with the final turn state and token usage. @@ -119,15 +120,16 @@ Example with notification opt-out: ## API Overview -- `thread/start` — create a new thread; emits `thread/started` and auto-subscribes you to turn/item events for that thread. +- `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. - `thread/resume` — reopen an existing thread by id so subsequent `turn/start` calls append to it. -- `thread/fork` — fork an existing thread into a new thread id by copying the stored history; emits `thread/started` and auto-subscribes you to turn/item events for the new thread. +- `thread/fork` — fork an existing thread into a new thread id by copying the stored history; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for the new thread. - `thread/list` — page through stored rollouts; supports cursor-based pagination and optional `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filters. Each returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded. - `thread/loaded/list` — list the thread ids currently loaded in memory. - `thread/read` — read a stored thread by id without resuming it; optionally include turns via `includeTurns`. The returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded. - `thread/status/changed` — notification emitted when a loaded thread’s status changes (`threadId` + new `status`). - `thread/archive` — move a thread’s rollout file into the archived directory; returns `{}` on success and emits `thread/archived`. -- `thread/name/set` — set or update a thread’s user-facing name; returns `{}` on success. Thread names are not required to be unique; name lookups resolve to the most recently updated thread. +- `thread/unsubscribe` — unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server shuts down and unloads the thread, then emits `thread/closed`. +- `thread/name/set` — set or update a thread’s user-facing name for either a loaded thread or a persisted rollout; returns `{}` on success. Thread names are not required to be unique; name lookups resolve to the most recently updated thread. - `thread/unarchive` — move an archived rollout file back into the sessions directory; returns the restored `thread` on success and emits `thread/unarchived`. - `thread/compact/start` — trigger conversation history compaction for a thread; returns `{}` immediately while progress streams through standard turn/item notifications. - `thread/backgroundTerminals/clean` — terminate all running background terminals for a thread (experimental; requires `capabilities.experimentalApi`); returns `{}` when the cleanup request is accepted. @@ -141,9 +143,9 @@ Example with notification opt-out: - `thread/realtime/stop` — stop the active realtime session for the thread (experimental); returns `{}`. - `review/start` — kick off Codex’s automated reviewer for a thread; responds like `turn/start` and emits `item/started`/`item/completed` notifications with `enteredReviewMode` and `exitedReviewMode` items, plus a final assistant `agentMessage` containing the review. - `command/exec` — run a single command under the server sandbox without starting a thread/turn (handy for utilities and validation). -- `model/list` — list available models (set `includeHidden: true` to include entries with `hidden: true`), with reasoning effort options and optional `upgrade` model ids. +- `model/list` — list available models (set `includeHidden: true` to include entries with `hidden: true`), with reasoning effort options, optional legacy `upgrade` model ids, optional `upgradeInfo` metadata (`model`, `upgradeCopy`, `modelLink`, `migrationMarkdown`), and optional `availabilityNux` metadata. - `experimentalFeature/list` — list feature flags with stage metadata (`beta`, `underDevelopment`, `stable`, etc.), enabled/default-enabled state, and cursor pagination. For non-beta flags, `displayName`/`description`/`announcement` are `null`. -- `collaborationMode/list` — list available collaboration mode presets (experimental, no pagination). +- `collaborationMode/list` — list available collaboration mode presets (experimental, no pagination). This response omits built-in developer instructions; clients should either pass `settings.developer_instructions: null` when setting a mode to use Codex's built-in instructions, or provide their own instructions explicitly. - `skills/list` — list skills for one or more `cwd` values (optional `forceReload`). - `skills/remote/list` — list public remote skills (**under development; do not call from production clients yet**). - `skills/remote/export` — download a remote skill by `hazelnutId` into `skills` under `codex_home` (**under development; do not call from production clients yet**). @@ -271,10 +273,11 @@ When `nextCursor` is `null`, you’ve reached the final page. ### Example: Track thread status changes -`thread/status/changed` is emitted whenever a loaded thread's status changes: +`thread/status/changed` is emitted whenever a loaded thread's status changes after it has already been introduced to the client: - Includes `threadId` and the new `status`. - Status can be `notLoaded`, `idle`, `systemError`, or `active` (with `activeFlags`; `active` implies running). +- `thread/start`, `thread/fork`, and detached review threads do not emit a separate initial `thread/status/changed`; their `thread/started` notification already carries the current `thread.status`. ```json { "method": "thread/status/changed", "params": { @@ -283,6 +286,26 @@ When `nextCursor` is `null`, you’ve reached the final page. } } ``` +### Example: Unsubscribe from a loaded thread + +`thread/unsubscribe` removes the current connection's subscription to a thread. The response status is one of: + +- `unsubscribed` when the connection was subscribed and is now removed. +- `notSubscribed` when the connection was not subscribed to that thread. +- `notLoaded` when the thread is not loaded. + +If this was the last subscriber, the server unloads the thread and emits `thread/closed` and a `thread/status/changed` transition to `notLoaded`. + +```json +{ "method": "thread/unsubscribe", "id": 22, "params": { "threadId": "thr_123" } } +{ "id": 22, "result": { "status": "unsubscribed" } } +{ "method": "thread/status/changed", "params": { + "threadId": "thr_123", + "status": { "type": "notLoaded" } +} } +{ "method": "thread/closed", "params": { "threadId": "thr_123" } } +``` + ### Example: Read a thread Use `thread/read` to fetch a stored thread by id without resuming it. Pass `includeTurns` when you want the rollout history loaded into `thread.turns`. The returned thread includes `agentNickname` and `agentRole` for AgentControl-spawned thread sub-agents when available. @@ -555,7 +578,7 @@ Notes: ## Events -Event notifications are the server-initiated event stream for thread lifecycles, turn lifecycles, and the items within them. After you start or resume a thread, keep reading stdout for `thread/started`, `thread/archived`, `thread/unarchived`, `turn/*`, and `item/*` notifications. +Event notifications are the server-initiated event stream for thread lifecycles, turn lifecycles, and the items within them. After you start or resume a thread, keep reading stdout for `thread/started`, `thread/archived`, `thread/unarchived`, `thread/closed`, `turn/*`, and `item/*` notifications. Thread realtime uses a separate thread-scoped notification surface. `thread/realtime/*` notifications are ephemeral transport events, not `ThreadItem`s, and are not returned by `thread/read`, `thread/resume`, or `thread/fork`. @@ -598,7 +621,7 @@ Because audio is intentionally separate from `ThreadItem`, clients can opt out o ### Turn events -The app-server streams JSON-RPC notifications while a turn is running. Each turn starts with `turn/started` (initial `turn`) and ends with `turn/completed` (final `turn` status). Token usage events stream separately via `thread/tokenUsage/updated`. Clients subscribe to the events they care about, rendering each item incrementally as updates arrive. The per-item lifecycle is always: `item/started` → zero or more item-specific deltas → `item/completed`. +The app-server streams JSON-RPC notifications while a turn is running. Each turn emits `turn/started` when it begins running and ends with `turn/completed` (final `turn` status). Token usage events stream separately via `thread/tokenUsage/updated`. Clients subscribe to the events they care about, rendering each item incrementally as updates arrive. The per-item lifecycle is always: `item/started` → zero or more item-specific deltas → `item/completed`. - `turn/started` — `{ turn }` with the turn id, empty `items`, and `status: "inProgress"`. - `turn/completed` — `{ turn }` where `turn.status` is `completed`, `interrupted`, or `failed`; failures carry `{ error: { message, codexErrorInfo?, additionalDetails? } }`. @@ -689,9 +712,10 @@ Certain actions (shell commands or modifying files) may require explicit user ap Order of messages: 1. `item/started` — shows the pending `commandExecution` item with `command`, `cwd`, and other fields so you can render the proposed action. -2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. +2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted. 3. Client response — for example `{ "decision": "accept" }`, `{ "decision": "acceptForSession" }`, `{ "decision": { "acceptWithExecpolicyAmendment": { "execpolicy_amendment": [...] } } }`, `{ "decision": { "applyNetworkPolicyAmendment": { "network_policy_amendment": { "host": "example.com", "action": "allow" } } } }`, `{ "decision": "decline" }`, or `{ "decision": "cancel" }`. -4. `item/completed` — final `commandExecution` item with `status: "completed" | "failed" | "declined"` and execution output. Render this as the authoritative result. +4. `serverRequest/resolved` — `{ threadId, requestId }` confirms the pending request has been resolved or cleared, including lifecycle cleanup on turn start/complete/interrupt. +5. `item/completed` — final `commandExecution` item with `status: "completed" | "failed" | "declined"` and execution output. Render this as the authoritative result. ### File change approvals @@ -700,10 +724,15 @@ Order of messages: 1. `item/started` — emits a `fileChange` item with `changes` (diff chunk summaries) and `status: "inProgress"`. Show the proposed edits and paths to the user. 2. `item/fileChange/requestApproval` (request) — includes `itemId`, `threadId`, `turnId`, and an optional `reason`. 3. Client response — `{ "decision": "accept" }` or `{ "decision": "decline" }`. -4. `item/completed` — returns the same `fileChange` item with `status` updated to `completed`, `failed`, or `declined` after the patch attempt. Rely on this to show success/failure and finalize the diff state in your UI. +4. `serverRequest/resolved` — `{ threadId, requestId }` confirms the pending request has been resolved or cleared, including lifecycle cleanup on turn start/complete/interrupt. +5. `item/completed` — returns the same `fileChange` item with `status` updated to `completed`, `failed`, or `declined` after the patch attempt. Rely on this to show success/failure and finalize the diff state in your UI. UI guidance for IDEs: surface an approval dialog as soon as the request arrives. The turn will proceed after the server receives a response to the approval request. The terminal `item/completed` notification will be sent with the appropriate status. +### request_user_input + +When the client responds to `item/tool/requestUserInput`, the server emits `serverRequest/resolved` with `{ threadId, requestId }`. If the pending request is cleared by turn start, turn completion, or turn interruption before the client answers, the server emits the same notification for that cleanup. + ### Dynamic tool calls (experimental) `dynamicTools` on `thread/start` and the corresponding `item/tool/call` request/response flow are experimental APIs. To enable them, set `initialize.params.capabilities.experimentalApi = true`. @@ -724,6 +753,13 @@ When a dynamic tool is invoked during a turn, the server sends an `item/tool/cal } ``` +The server also emits item lifecycle notifications around the request: + +1. `item/started` with `item.type = "dynamicToolCall"`, `status = "inProgress"`, plus `tool` and `arguments`. +2. `item/tool/call` request. +3. Client response. +4. `item/completed` with `item.type = "dynamicToolCall"`, final `status`, and the returned `contentItems`/`success`. + The client must respond with content items. Use `inputText` for text and `inputImage` for image URLs/data URLs: ```json @@ -917,7 +953,7 @@ The JSON-RPC auth/account surface exposes request/response methods plus server-i ### Authentication modes -Codex supports these authentication modes. The current mode is surfaced in `account/updated` (`authMode`) and can be inferred from `account/read`. +Codex supports these authentication modes. The current mode is surfaced in `account/updated` (`authMode`), which also includes the current ChatGPT `planType` when available, and can be inferred from `account/read`. - **API key (`apiKey`)**: Caller supplies an OpenAI API key via `account/login/start` with `type: "apiKey"`. The API key is saved and used for API requests. - **ChatGPT managed (`chatgpt`)** (recommended): Codex owns the ChatGPT OAuth flow and refresh tokens. Start via `account/login/start` with `type: "chatgpt"`; Codex persists tokens to disk and refreshes them automatically. @@ -929,7 +965,7 @@ Codex supports these authentication modes. The current mode is surfaced in `acco - `account/login/completed` (notify) — emitted when a login attempt finishes (success or error). - `account/login/cancel` — cancel a pending ChatGPT login by `loginId`. - `account/logout` — sign out; triggers `account/updated`. -- `account/updated` (notify) — emitted whenever auth mode changes (`authMode`: `apikey`, `chatgpt`, or `null`). +- `account/updated` (notify) — emitted whenever auth mode changes (`authMode`: `apikey`, `chatgpt`, or `null`) and includes the current ChatGPT `planType` when available. - `account/rateLimits/read` — fetch ChatGPT rate limits; updates arrive via `account/rateLimits/updated` (notify). - `account/rateLimits/updated` (notify) — emitted whenever a user's ChatGPT rate limits change. - `mcpServer/oauthLogin/completed` (notify) — emitted after a `mcpServer/oauth/login` flow finishes for a server; payload includes `{ name, success, error? }`. @@ -973,7 +1009,7 @@ Field notes: 3. Notifications: ```json { "method": "account/login/completed", "params": { "loginId": null, "success": true, "error": null } } - { "method": "account/updated", "params": { "authMode": "apikey" } } + { "method": "account/updated", "params": { "authMode": "apikey", "planType": null } } ``` ### 3) Log in with ChatGPT (browser flow) @@ -987,7 +1023,7 @@ Field notes: 3. Wait for notifications: ```json { "method": "account/login/completed", "params": { "loginId": "", "success": true, "error": null } } - { "method": "account/updated", "params": { "authMode": "chatgpt" } } + { "method": "account/updated", "params": { "authMode": "chatgpt", "planType": "plus" } } ``` ### 4) Cancel a ChatGPT login @@ -1002,7 +1038,7 @@ Field notes: ```json { "method": "account/logout", "id": 5 } { "id": 5, "result": {} } -{ "method": "account/updated", "params": { "authMode": null } } +{ "method": "account/updated", "params": { "authMode": null, "planType": null } } ``` ### 6) Rate limits (ChatGPT) diff --git a/codex-rs/app-server/src/app_server_tracing.rs b/codex-rs/app-server/src/app_server_tracing.rs new file mode 100644 index 0000000000..779cef9671 --- /dev/null +++ b/codex-rs/app-server/src/app_server_tracing.rs @@ -0,0 +1,101 @@ +use crate::message_processor::ConnectionSessionState; +use crate::outgoing_message::ConnectionId; +use crate::transport::AppServerTransport; +use codex_app_server_protocol::InitializeParams; +use codex_app_server_protocol::JSONRPCRequest; +use codex_otel::set_parent_from_context; +use codex_otel::set_parent_from_w3c_trace_context; +use codex_otel::traceparent_context_from_env; +use codex_protocol::protocol::W3cTraceContext; +use tracing::Span; +use tracing::field; +use tracing::info_span; + +pub(crate) fn request_span( + request: &JSONRPCRequest, + transport: AppServerTransport, + connection_id: ConnectionId, + session: &ConnectionSessionState, +) -> Span { + let span = info_span!( + "app_server.request", + otel.kind = "server", + otel.name = request.method.as_str(), + rpc.system = "jsonrpc", + rpc.method = request.method.as_str(), + rpc.transport = transport_name(transport), + rpc.request_id = ?request.id, + app_server.connection_id = ?connection_id, + app_server.api_version = "v2", + app_server.client_name = field::Empty, + app_server.client_version = field::Empty, + ); + + let initialize_client_info = initialize_client_info(request); + if let Some(client_name) = client_name(initialize_client_info.as_ref(), session) { + span.record("app_server.client_name", client_name); + } + if let Some(client_version) = client_version(initialize_client_info.as_ref(), session) { + span.record("app_server.client_version", client_version); + } + + if let Some(traceparent) = request + .trace + .as_ref() + .and_then(|trace| trace.traceparent.as_deref()) + { + let trace = W3cTraceContext { + traceparent: Some(traceparent.to_string()), + tracestate: request + .trace + .as_ref() + .and_then(|value| value.tracestate.clone()), + }; + if !set_parent_from_w3c_trace_context(&span, &trace) { + tracing::warn!( + rpc_method = request.method.as_str(), + rpc_request_id = ?request.id, + "ignoring invalid inbound request trace carrier" + ); + } + } else if let Some(context) = traceparent_context_from_env() { + set_parent_from_context(&span, context); + } + + span +} + +fn transport_name(transport: AppServerTransport) -> &'static str { + match transport { + AppServerTransport::Stdio => "stdio", + AppServerTransport::WebSocket { .. } => "websocket", + } +} + +fn client_name<'a>( + initialize_client_info: Option<&'a InitializeParams>, + session: &'a ConnectionSessionState, +) -> Option<&'a str> { + if let Some(params) = initialize_client_info { + return Some(params.client_info.name.as_str()); + } + session.app_server_client_name.as_deref() +} + +fn client_version<'a>( + initialize_client_info: Option<&'a InitializeParams>, + session: &'a ConnectionSessionState, +) -> Option<&'a str> { + if let Some(params) = initialize_client_info { + return Some(params.client_info.version.as_str()); + } + session.client_version.as_deref() +} + +fn initialize_client_info(request: &JSONRPCRequest) -> Option { + if request.method != "initialize" { + return None; + } + let params = request.params.clone()?; + serde_json::from_value(params).ok() +} diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 56e55823c8..2f293c9347 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -6,6 +6,8 @@ use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::outgoing_message::ClientRequestResult; use crate::outgoing_message::ThreadScopedOutgoingMessageSender; +use crate::server_request_error::is_turn_transition_server_request_error; +use crate::thread_state::ThreadListenerCommand; use crate::thread_state::ThreadState; use crate::thread_state::TurnSummary; use crate::thread_status::ThreadWatchActiveGuard; @@ -27,7 +29,9 @@ use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; use codex_app_server_protocol::CommandExecutionStatus; use codex_app_server_protocol::ContextCompactedNotification; use codex_app_server_protocol::DeprecationNoticeNotification; +use codex_app_server_protocol::DynamicToolCallOutputContentItem; use codex_app_server_protocol::DynamicToolCallParams; +use codex_app_server_protocol::DynamicToolCallStatus; use codex_app_server_protocol::ErrorNotification; use codex_app_server_protocol::ExecCommandApprovalParams; use codex_app_server_protocol::ExecCommandApprovalResponse; @@ -54,11 +58,9 @@ use codex_app_server_protocol::RawResponseItemCompletedNotification; use codex_app_server_protocol::ReasoningSummaryPartAddedNotification; use codex_app_server_protocol::ReasoningSummaryTextDeltaNotification; use codex_app_server_protocol::ReasoningTextDeltaNotification; +use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; -use codex_app_server_protocol::SkillApprovalDecision as V2SkillApprovalDecision; -use codex_app_server_protocol::SkillRequestApprovalParams; -use codex_app_server_protocol::SkillRequestApprovalResponse; use codex_app_server_protocol::TerminalInteractionNotification; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadNameUpdatedNotification; @@ -81,6 +83,7 @@ use codex_app_server_protocol::TurnError; use codex_app_server_protocol::TurnInterruptResponse; use codex_app_server_protocol::TurnPlanStep; use codex_app_server_protocol::TurnPlanUpdatedNotification; +use codex_app_server_protocol::TurnStartedNotification; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::build_turns_from_rollout_items; use codex_app_server_protocol::convert_patch_changes; @@ -109,7 +112,6 @@ use codex_protocol::protocol::TokenCountEvent; use codex_protocol::protocol::TurnDiffEvent; use codex_protocol::request_user_input::RequestUserInputAnswer as CoreRequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputResponse as CoreRequestUserInputResponse; -use codex_protocol::skill_approval::SkillApprovalResponse as CoreSkillApprovalResponse; use codex_shell_command::parse_command::shlex_join; use std::collections::HashMap; use std::convert::TryFrom; @@ -134,6 +136,38 @@ struct CommandExecutionCompletionItem { command_actions: Vec, } +async fn resolve_server_request_on_thread_listener( + thread_state: &Arc>, + request_id: RequestId, +) { + let (completion_tx, completion_rx) = oneshot::channel(); + let listener_command_tx = { + let state = thread_state.lock().await; + state.listener_command_tx() + }; + let Some(listener_command_tx) = listener_command_tx else { + error!("failed to remove pending client request: thread listener is not running"); + return; + }; + + if listener_command_tx + .send(ThreadListenerCommand::ResolveServerRequest { + request_id, + completion_tx, + }) + .is_err() + { + error!( + "failed to remove pending client request: thread listener command channel is closed" + ); + return; + } + + if let Err(err) = completion_rx.await { + error!("failed to remove pending client request: {err}"); + } +} + #[allow(clippy::too_many_arguments)] pub(crate) async fn apply_bespoke_event_handling( event: Event, @@ -152,12 +186,34 @@ pub(crate) async fn apply_bespoke_event_handling( msg, } = event; match msg { - EventMsg::TurnStarted(_) => { + EventMsg::TurnStarted(payload) => { + // While not technically necessary as it was already done on TurnComplete, be extra cautios and abort any pending server requests. + outgoing.abort_pending_server_requests().await; thread_watch_manager .note_turn_started(&conversation_id.to_string()) .await; + if let ApiVersion::V2 = api_version { + let turn = { + let state = thread_state.lock().await; + state.active_turn_snapshot().unwrap_or_else(|| Turn { + id: payload.turn_id.clone(), + items: Vec::new(), + error: None, + status: TurnStatus::InProgress, + }) + }; + let notification = TurnStartedNotification { + thread_id: conversation_id.to_string(), + turn, + }; + outgoing + .send_server_notification(ServerNotification::TurnStarted(notification)) + .await; + } } EventMsg::TurnComplete(_ev) => { + // All per-thread requests are bound to a turn, so abort them. + outgoing.abort_pending_server_requests().await; let turn_failed = thread_state.lock().await.turn_summary.last_error.is_some(); thread_watch_manager .note_turn_completed(&conversation_id.to_string(), turn_failed) @@ -195,7 +251,6 @@ pub(crate) async fn apply_bespoke_event_handling( EventMsg::RealtimeConversationRealtime(event) => { if let ApiVersion::V2 = api_version { match event.payload { - RealtimeEvent::SessionCreated { .. } => {} RealtimeEvent::SessionUpdated { .. } => {} RealtimeEvent::AudioOut(audio) => { let notification = ThreadRealtimeOutputAudioDeltaNotification { @@ -219,6 +274,24 @@ pub(crate) async fn apply_bespoke_event_handling( )) .await; } + RealtimeEvent::ConversationItemDone { .. } => {} + RealtimeEvent::HandoffRequested(handoff) => { + let notification = ThreadRealtimeItemAddedNotification { + thread_id: conversation_id.to_string(), + item: serde_json::json!({ + "type": "handoff_request", + "handoff_id": handoff.handoff_id, + "item_id": handoff.item_id, + "input_transcript": handoff.input_transcript, + "messages": handoff.messages, + }), + }; + outgoing + .send_server_notification(ServerNotification::ThreadRealtimeItemAdded( + notification, + )) + .await; + } RealtimeEvent::Error(message) => { let notification = ThreadRealtimeErrorNotification { thread_id: conversation_id.to_string(), @@ -265,7 +338,7 @@ pub(crate) async fn apply_bespoke_event_handling( reason, grant_root, }; - let rx = outgoing + let (_pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::ApplyPatchApproval(params)) .await; tokio::spawn(async move { @@ -309,7 +382,7 @@ pub(crate) async fn apply_bespoke_event_handling( reason, grant_root, }; - let rx = outgoing + let (pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::FileChangeRequestApproval(params)) .await; tokio::spawn(async move { @@ -318,6 +391,7 @@ pub(crate) async fn apply_bespoke_event_handling( conversation_id, item_id, patch_changes, + pending_request_id, rx, conversation, outgoing, @@ -334,6 +408,11 @@ pub(crate) async fn apply_bespoke_event_handling( .note_permission_requested(&conversation_id.to_string()) .await; let approval_id_for_op = ev.effective_approval_id(); + let available_decisions = ev + .effective_available_decisions() + .into_iter() + .map(CommandExecutionApprovalDecision::from) + .collect::>(); let ExecApprovalRequestEvent { call_id, approval_id, @@ -359,7 +438,7 @@ pub(crate) async fn apply_bespoke_event_handling( reason, parsed_cmd, }; - let rx = outgoing + let (_pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::ExecCommandApproval(params)) .await; tokio::spawn(async move { @@ -430,8 +509,9 @@ pub(crate) async fn apply_bespoke_event_handling( additional_permissions, proposed_execpolicy_amendment: proposed_execpolicy_amendment_v2, proposed_network_policy_amendments: proposed_network_policy_amendments_v2, + available_decisions: Some(available_decisions), }; - let rx = outgoing + let (pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::CommandExecutionRequestApproval( params, )) @@ -443,6 +523,7 @@ pub(crate) async fn apply_bespoke_event_handling( approval_id, call_id, completion_item, + pending_request_id, rx, conversation, outgoing, @@ -485,14 +566,16 @@ pub(crate) async fn apply_bespoke_event_handling( item_id: request.call_id, questions, }; - let rx = outgoing + let (pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::ToolRequestUserInput(params)) .await; tokio::spawn(async move { on_request_user_input_response( event_turn_id, + pending_request_id, rx, conversation, + thread_state, user_input_guard, ) .await; @@ -516,48 +599,37 @@ pub(crate) async fn apply_bespoke_event_handling( } } } - EventMsg::SkillRequestApproval(request) => { - if matches!(api_version, ApiVersion::V2) { - let item_id = request.item_id; - let skill_name = request.skill_name; - let params = SkillRequestApprovalParams { - item_id: item_id.clone(), - skill_name, - }; - let rx = outgoing - .send_request(ServerRequestPayload::SkillRequestApproval(params)) - .await; - tokio::spawn(async move { - let approved = match rx.await { - Ok(Ok(value)) => { - serde_json::from_value::(value) - .map(|response| { - matches!(response.decision, V2SkillApprovalDecision::Approve) - }) - .unwrap_or(false) - } - _ => false, - }; - let _ = conversation - .submit(Op::SkillApproval { - id: item_id, - response: CoreSkillApprovalResponse { approved }, - }) - .await; - }); - } - } EventMsg::DynamicToolCallRequest(request) => { if matches!(api_version, ApiVersion::V2) { let call_id = request.call_id; + let turn_id = request.turn_id; + let tool = request.tool; + let arguments = request.arguments; + let item = ThreadItem::DynamicToolCall { + id: call_id.clone(), + tool: tool.clone(), + arguments: arguments.clone(), + status: DynamicToolCallStatus::InProgress, + content_items: None, + success: None, + duration_ms: None, + }; + let notification = ItemStartedNotification { + thread_id: conversation_id.to_string(), + turn_id: turn_id.clone(), + item, + }; + outgoing + .send_server_notification(ServerNotification::ItemStarted(notification)) + .await; let params = DynamicToolCallParams { thread_id: conversation_id.to_string(), - turn_id: request.turn_id, + turn_id: turn_id.clone(), call_id: call_id.clone(), - tool: request.tool, - arguments: request.arguments, + tool: tool.clone(), + arguments: arguments.clone(), }; - let rx = outgoing + let (_pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::DynamicToolCall(params)) .await; tokio::spawn(async move { @@ -582,6 +654,46 @@ pub(crate) async fn apply_bespoke_event_handling( .await; } } + EventMsg::DynamicToolCallResponse(response) => { + if matches!(api_version, ApiVersion::V2) { + let status = if response.success { + DynamicToolCallStatus::Completed + } else { + DynamicToolCallStatus::Failed + }; + let duration_ms = i64::try_from(response.duration.as_millis()).ok(); + let item = ThreadItem::DynamicToolCall { + id: response.call_id, + tool: response.tool, + arguments: response.arguments, + status, + content_items: Some( + response + .content_items + .into_iter() + .map(|item| match item { + CoreDynamicToolCallOutputContentItem::InputText { text } => { + DynamicToolCallOutputContentItem::InputText { text } + } + CoreDynamicToolCallOutputContentItem::InputImage { image_url } => { + DynamicToolCallOutputContentItem::InputImage { image_url } + } + }) + .collect(), + ), + success: Some(response.success), + duration_ms, + }; + let notification = ItemCompletedNotification { + thread_id: conversation_id.to_string(), + turn_id: response.turn_id, + item, + }; + outgoing + .send_server_notification(ServerNotification::ItemCompleted(notification)) + .await; + } + } // TODO(celia): properly construct McpToolCall TurnItem in core. EventMsg::McpToolCallBegin(begin_event) => { let notification = construct_mcp_tool_call_notification( @@ -1103,6 +1215,7 @@ pub(crate) async fn apply_bespoke_event_handling( // Until we migrate the core to be aware of a first class FileChangeItem // and emit the corresponding EventMsg, we repurpose the call_id as the item_id. let item_id = patch_begin_event.call_id.clone(); + let changes = convert_patch_changes(&patch_begin_event.changes); let first_start = { let mut state = thread_state.lock().await; @@ -1114,7 +1227,7 @@ pub(crate) async fn apply_bespoke_event_handling( if first_start { let item = ThreadItem::FileChange { id: item_id.clone(), - changes: convert_patch_changes(&patch_begin_event.changes), + changes, status: PatchApplyStatus::InProgress, }; let notification = ItemStartedNotification { @@ -1296,6 +1409,8 @@ pub(crate) async fn apply_bespoke_event_handling( } // If this is a TurnAborted, reply to any pending interrupt requests. EventMsg::TurnAborted(turn_aborted_event) => { + // All per-thread requests are bound to a turn, so abort them. + outgoing.abort_pending_server_requests().await; let pending = { let mut state = thread_state.lock().await; std::mem::take(&mut state.pending_interrupts) @@ -1692,6 +1807,7 @@ async fn on_patch_approval_response( let response = receiver.await; let value = match response { Ok(Ok(value)) => value, + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { error!("request failed with client error: {err:?}"); if let Err(submit_err) = codex @@ -1748,6 +1864,7 @@ async fn on_exec_approval_response( let response = receiver.await; let value = match response { Ok(Ok(value)) => value, + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { error!("request failed with client error: {err:?}"); return; @@ -1783,14 +1900,18 @@ async fn on_exec_approval_response( async fn on_request_user_input_response( event_turn_id: String, + pending_request_id: RequestId, receiver: oneshot::Receiver, conversation: Arc, + thread_state: Arc>, user_input_guard: ThreadWatchActiveGuard, ) { let response = receiver.await; + resolve_server_request_on_thread_listener(&thread_state, pending_request_id).await; drop(user_input_guard); let value = match response { Ok(Ok(value)) => value, + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { error!("request failed with client error: {err:?}"); let empty = CoreRequestUserInputResponse { @@ -1901,6 +2022,7 @@ async fn on_file_change_request_approval_response( conversation_id: ThreadId, item_id: String, changes: Vec, + pending_request_id: RequestId, receiver: oneshot::Receiver, codex: Arc, outgoing: ThreadScopedOutgoingMessageSender, @@ -1908,6 +2030,7 @@ async fn on_file_change_request_approval_response( permission_guard: ThreadWatchActiveGuard, ) { let response = receiver.await; + resolve_server_request_on_thread_listener(&thread_state, pending_request_id).await; drop(permission_guard); let (decision, completion_status) = match response { Ok(Ok(value)) => { @@ -1925,6 +2048,7 @@ async fn on_file_change_request_approval_response( // Only short-circuit on declines/cancels/failures. (decision, completion_status) } + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { error!("request failed with client error: {err:?}"); (ReviewDecision::Denied, Some(PatchApplyStatus::Failed)) @@ -1966,6 +2090,7 @@ async fn on_command_execution_request_approval_response( approval_id: Option, item_id: String, completion_item: Option, + pending_request_id: RequestId, receiver: oneshot::Receiver, conversation: Arc, outgoing: ThreadScopedOutgoingMessageSender, @@ -1973,6 +2098,7 @@ async fn on_command_execution_request_approval_response( permission_guard: ThreadWatchActiveGuard, ) { let response = receiver.await; + resolve_server_request_on_thread_listener(&thread_state, pending_request_id).await; drop(permission_guard); let (decision, completion_status) = match response { Ok(Ok(value)) => { @@ -2024,6 +2150,7 @@ async fn on_command_execution_request_approval_response( }; (decision, completion_status) } + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { error!("request failed with client error: {err:?}"); (ReviewDecision::Denied, Some(CommandExecutionStatus::Failed)) @@ -2328,7 +2455,11 @@ mod tests { let event_turn_id = "complete1".to_string(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); let thread_state = new_thread_state(); handle_turn_complete( @@ -2369,7 +2500,11 @@ mod tests { .await; let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); handle_turn_interrupted( conversation_id, @@ -2409,7 +2544,11 @@ mod tests { .await; let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); handle_turn_complete( conversation_id, @@ -2443,7 +2582,11 @@ mod tests { async fn test_handle_turn_plan_update_emits_notification_for_v2() -> Result<()> { let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); let update = UpdatePlanArgs { explanation: Some("need plan".to_string()), plan: vec![ @@ -2493,7 +2636,11 @@ mod tests { let turn_id = "turn-123".to_string(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); let info = TokenUsageInfo { total_token_usage: TokenUsage { @@ -2577,7 +2724,11 @@ mod tests { let turn_id = "turn-456".to_string(); let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); handle_token_count_event( conversation_id, @@ -2644,7 +2795,11 @@ mod tests { let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); // Turn 1 on conversation A let a_turn1 = "a_turn1".to_string(); @@ -2867,7 +3022,11 @@ mod tests { async fn test_handle_turn_diff_emits_v2_notification() -> Result<()> { let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); let unified_diff = "--- a\n+++ b\n".to_string(); let conversation_id = ThreadId::new(); @@ -2901,7 +3060,11 @@ mod tests { async fn test_handle_turn_diff_is_noop_for_v1() -> Result<()> { let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); let outgoing = Arc::new(OutgoingMessageSender::new(tx)); - let outgoing = ThreadScopedOutgoingMessageSender::new(outgoing, vec![ConnectionId(1)]); + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing, + vec![ConnectionId(1)], + ThreadId::new(), + ); let conversation_id = ThreadId::new(); handle_turn_diff( diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 66e8b7cebc..1e5798af12 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1,5 +1,7 @@ use crate::bespoke_event_handling::apply_bespoke_event_handling; +use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE; use crate::error_code::INTERNAL_ERROR_CODE; +use crate::error_code::INVALID_PARAMS_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::fuzzy_file_search::FuzzyFileSearchSession; use crate::fuzzy_file_search::run_fuzzy_file_search; @@ -18,21 +20,15 @@ use chrono::Utc; use codex_app_server_protocol::Account; use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AccountUpdatedNotification; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; use codex_app_server_protocol::AppInfo; use codex_app_server_protocol::AppListUpdatedNotification; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::ArchiveConversationParams; -use codex_app_server_protocol::ArchiveConversationResponse; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::AuthMode; -use codex_app_server_protocol::AuthStatusChangeNotification; use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::CancelLoginAccountResponse; use codex_app_server_protocol::CancelLoginAccountStatus; -use codex_app_server_protocol::CancelLoginChatGptResponse; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::CollaborationModeListParams; use codex_app_server_protocol::CollaborationModeListResponse; @@ -47,8 +43,6 @@ use codex_app_server_protocol::ExperimentalFeatureListResponse; use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatureStage; use codex_app_server_protocol::FeedbackUploadParams; use codex_app_server_protocol::FeedbackUploadResponse; -use codex_app_server_protocol::ForkConversationParams; -use codex_app_server_protocol::ForkConversationResponse; use codex_app_server_protocol::FuzzyFileSearchParams; use codex_app_server_protocol::FuzzyFileSearchResponse; use codex_app_server_protocol::FuzzyFileSearchSessionStartParams; @@ -64,26 +58,16 @@ use codex_app_server_protocol::GetAuthStatusParams; use codex_app_server_protocol::GetAuthStatusResponse; use codex_app_server_protocol::GetConversationSummaryParams; use codex_app_server_protocol::GetConversationSummaryResponse; -use codex_app_server_protocol::GetUserAgentResponse; -use codex_app_server_protocol::GetUserSavedConfigResponse; use codex_app_server_protocol::GitDiffToRemoteResponse; use codex_app_server_protocol::GitInfo as ApiGitInfo; use codex_app_server_protocol::HazelnutScope as ApiHazelnutScope; -use codex_app_server_protocol::InputItem as WireInputItem; -use codex_app_server_protocol::InterruptConversationParams; use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::ListConversationsParams; -use codex_app_server_protocol::ListConversationsResponse; use codex_app_server_protocol::ListMcpServerStatusParams; use codex_app_server_protocol::ListMcpServerStatusResponse; use codex_app_server_protocol::LoginAccountParams; use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::LoginApiKeyParams; -use codex_app_server_protocol::LoginApiKeyResponse; -use codex_app_server_protocol::LoginChatGptCompleteNotification; -use codex_app_server_protocol::LoginChatGptResponse; use codex_app_server_protocol::LogoutAccountResponse; -use codex_app_server_protocol::LogoutChatGptResponse; use codex_app_server_protocol::McpServerOauthLoginCompletedNotification; use codex_app_server_protocol::McpServerOauthLoginParams; use codex_app_server_protocol::McpServerOauthLoginResponse; @@ -93,26 +77,15 @@ use codex_app_server_protocol::MockExperimentalMethodParams; use codex_app_server_protocol::MockExperimentalMethodResponse; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::ProductSurface as ApiProductSurface; -use codex_app_server_protocol::RemoveConversationListenerParams; -use codex_app_server_protocol::RemoveConversationSubscriptionResponse; -use codex_app_server_protocol::ResumeConversationParams; -use codex_app_server_protocol::ResumeConversationResponse; +use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ReviewDelivery as ApiReviewDelivery; use codex_app_server_protocol::ReviewStartParams; use codex_app_server_protocol::ReviewStartResponse; use codex_app_server_protocol::ReviewTarget as ApiReviewTarget; use codex_app_server_protocol::SandboxMode; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_app_server_protocol::SendUserTurnParams; -use codex_app_server_protocol::SendUserTurnResponse; use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionConfiguredNotification; -use codex_app_server_protocol::SetDefaultModelParams; -use codex_app_server_protocol::SetDefaultModelResponse; +use codex_app_server_protocol::ServerRequestResolvedNotification; use codex_app_server_protocol::SkillsConfigWriteParams; use codex_app_server_protocol::SkillsConfigWriteResponse; use codex_app_server_protocol::SkillsListParams; @@ -127,6 +100,7 @@ use codex_app_server_protocol::ThreadArchiveResponse; use codex_app_server_protocol::ThreadArchivedNotification; use codex_app_server_protocol::ThreadBackgroundTerminalsCleanParams; use codex_app_server_protocol::ThreadBackgroundTerminalsCleanResponse; +use codex_app_server_protocol::ThreadClosedNotification; use codex_app_server_protocol::ThreadCompactStartParams; use codex_app_server_protocol::ThreadCompactStartResponse; use codex_app_server_protocol::ThreadForkParams; @@ -136,6 +110,7 @@ use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadListResponse; use codex_app_server_protocol::ThreadLoadedListParams; use codex_app_server_protocol::ThreadLoadedListResponse; +use codex_app_server_protocol::ThreadNameUpdatedNotification; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadReadResponse; use codex_app_server_protocol::ThreadRealtimeAppendAudioParams; @@ -160,17 +135,17 @@ use codex_app_server_protocol::ThreadStatus; use codex_app_server_protocol::ThreadUnarchiveParams; use codex_app_server_protocol::ThreadUnarchiveResponse; use codex_app_server_protocol::ThreadUnarchivedNotification; +use codex_app_server_protocol::ThreadUnsubscribeParams; +use codex_app_server_protocol::ThreadUnsubscribeResponse; +use codex_app_server_protocol::ThreadUnsubscribeStatus; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; -use codex_app_server_protocol::TurnStartedNotification; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::TurnSteerParams; use codex_app_server_protocol::TurnSteerResponse; -use codex_app_server_protocol::UserInfoResponse; use codex_app_server_protocol::UserInput as V2UserInput; -use codex_app_server_protocol::UserSavedConfig; use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification; use codex_app_server_protocol::WindowsSandboxSetupMode; use codex_app_server_protocol::WindowsSandboxSetupStartParams; @@ -197,13 +172,11 @@ use codex_core::auth::login_with_api_key; use codex_core::auth::login_with_chatgpt_auth_tokens; use codex_core::config::Config; use codex_core::config::ConfigOverrides; -use codex_core::config::ConfigService; use codex_core::config::NetworkProxyAuditMetadata; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::types::McpServerTransportConfig; use codex_core::config_loader::CloudRequirementsLoader; -use codex_core::default_client::get_codex_user_agent; use codex_core::default_client::set_default_client_residency_requirement; use codex_core::error::CodexErr; use codex_core::exec::ExecParams; @@ -218,6 +191,7 @@ use codex_core::find_thread_path_by_id_str; use codex_core::git_info::git_diff_to_remote; use codex_core::mcp::collect_mcp_snapshot; use codex_core::mcp::group_tools_by_server; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::parse_cursor; use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; @@ -262,8 +236,10 @@ use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::USER_MESSAGE_BEGIN; +use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use codex_protocol::user_input::UserInput as CoreInputItem; use codex_rmcp_client::perform_oauth_login_return_url; +use codex_state::log_db::LogDbLayer; use codex_utils_json_to_toml::json_to_toml; use std::collections::HashMap; use std::collections::HashSet; @@ -289,8 +265,12 @@ use tracing::info; use tracing::warn; use uuid::Uuid; +#[cfg(test)] +use codex_app_server_protocol::ServerRequest; + use crate::filters::compute_source_filters; use crate::filters::source_kind_matches; +use crate::thread_state::ThreadListenerCommand; use crate::thread_state::ThreadState; use crate::thread_state::ThreadStateManager; @@ -315,7 +295,7 @@ struct ActiveLogin { #[derive(Clone, Copy, Debug)] enum CancelLoginError { - NotFound(Uuid), + NotFound, } enum AppListLoadResult { @@ -323,6 +303,12 @@ enum AppListLoadResult { Directory(Result, String>), } +enum ThreadShutdownResult { + Complete, + SubmitFailed, + TimedOut, +} + fn convert_remote_scope(scope: ApiHazelnutScope) -> RemoteSkillHazelnutScope { match scope { ApiHazelnutScope::WorkspaceShared => RemoteSkillHazelnutScope::WorkspaceShared, @@ -354,24 +340,42 @@ pub(crate) struct CodexMessageProcessor { outgoing: Arc, arg0_paths: Arg0DispatchPaths, config: Arc, - single_client_mode: bool, cli_overrides: Vec<(String, TomlValue)>, cloud_requirements: Arc>, active_login: Arc>>, + pending_thread_unloads: Arc>>, thread_state_manager: ThreadStateManager, thread_watch_manager: ThreadWatchManager, pending_fuzzy_searches: Arc>>>, fuzzy_search_sessions: Arc>>, feedback: CodexFeedback, + log_db: Option, } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub(crate) enum ApiVersion { + #[allow(dead_code)] V1, #[default] V2, } +#[derive(Clone)] +struct ListenerTaskContext { + thread_manager: Arc, + thread_state_manager: ThreadStateManager, + outgoing: Arc, + thread_watch_manager: ThreadWatchManager, + fallback_model_provider: String, + codex_home: PathBuf, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum EnsureConversationListenerResult { + Attached, + ConnectionClosed, +} + pub(crate) struct CodexMessageProcessorArgs { pub(crate) auth_manager: Arc, pub(crate) thread_manager: Arc, @@ -380,11 +384,19 @@ pub(crate) struct CodexMessageProcessorArgs { pub(crate) config: Arc, pub(crate) cli_overrides: Vec<(String, TomlValue)>, pub(crate) cloud_requirements: Arc>, - pub(crate) single_client_mode: bool, pub(crate) feedback: CodexFeedback, + pub(crate) log_db: Option, } impl CodexMessageProcessor { + fn current_account_updated_notification(&self) -> AccountUpdatedNotification { + let auth = self.auth_manager.auth_cached(); + AccountUpdatedNotification { + auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), + plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), + } + } + async fn load_thread( &self, thread_id: &str, @@ -417,8 +429,8 @@ impl CodexMessageProcessor { config, cli_overrides, cloud_requirements, - single_client_mode, feedback, + log_db, } = args; Self { auth_manager, @@ -426,15 +438,16 @@ impl CodexMessageProcessor { outgoing: outgoing.clone(), arg0_paths, config, - single_client_mode, cli_overrides, cloud_requirements, active_login: Arc::new(Mutex::new(None)), + pending_thread_unloads: Arc::new(Mutex::new(HashSet::new())), thread_state_manager: ThreadStateManager::new(), thread_watch_manager: ThreadWatchManager::new_with_outgoing(outgoing), pending_fuzzy_searches: Arc::new(Mutex::new(HashMap::new())), fuzzy_search_sessions: Arc::new(Mutex::new(HashMap::new())), feedback, + log_db, } } @@ -467,11 +480,13 @@ impl CodexMessageProcessor { fn normalize_turn_start_collaboration_mode( &self, mut collaboration_mode: CollaborationMode, + collaboration_modes_config: CollaborationModesConfig, ) -> CollaborationMode { if collaboration_mode.settings.developer_instructions.is_none() && let Some(instructions) = self .thread_manager - .list_collaboration_modes() + .get_models_manager() + .list_collaboration_modes_for_config(collaboration_modes_config) .into_iter() .find(|preset| preset.mode == Some(collaboration_mode.mode)) .and_then(|preset| preset.developer_instructions.flatten()) @@ -542,7 +557,12 @@ impl CodexMessageProcessor { Ok((review_request, hint)) } - pub async fn process_request(&mut self, connection_id: ConnectionId, request: ClientRequest) { + pub async fn process_request( + &mut self, + connection_id: ConnectionId, + request: ClientRequest, + app_server_client_name: Option, + ) { let to_connection_request_id = |request_id| ConnectionRequestId { connection_id, request_id, @@ -557,6 +577,10 @@ impl CodexMessageProcessor { self.thread_start(to_connection_request_id(request_id), params) .await; } + ClientRequest::ThreadUnsubscribe { request_id, params } => { + self.thread_unsubscribe(to_connection_request_id(request_id), params) + .await; + } ClientRequest::ThreadResume { request_id, params } => { self.thread_resume(to_connection_request_id(request_id), params) .await; @@ -625,8 +649,12 @@ impl CodexMessageProcessor { .await; } ClientRequest::TurnStart { request_id, params } => { - self.turn_start(to_connection_request_id(request_id), params) - .await; + self.turn_start( + to_connection_request_id(request_id), + params, + app_server_client_name.clone(), + ) + .await; } ClientRequest::TurnSteer { request_id, params } => { self.turn_steer(to_connection_request_id(request_id), params) @@ -656,21 +684,10 @@ impl CodexMessageProcessor { self.review_start(to_connection_request_id(request_id), params) .await; } - ClientRequest::NewConversation { request_id, params } => { - // Do not tokio::spawn() to process new_conversation() - // asynchronously because we need to ensure the conversation is - // created before processing any subsequent messages. - self.process_new_conversation(to_connection_request_id(request_id), params) - .await; - } ClientRequest::GetConversationSummary { request_id, params } => { self.get_thread_summary(to_connection_request_id(request_id), params) .await; } - ClientRequest::ListConversations { request_id, params } => { - self.handle_list_conversations(to_connection_request_id(request_id), params) - .await; - } ClientRequest::ModelList { request_id, params } => { let outgoing = self.outgoing.clone(); let thread_manager = self.thread_manager.clone(); @@ -732,92 +749,14 @@ impl CodexMessageProcessor { self.get_account(to_connection_request_id(request_id), params) .await; } - ClientRequest::ResumeConversation { request_id, params } => { - self.handle_resume_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::ForkConversation { request_id, params } => { - self.handle_fork_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::ArchiveConversation { request_id, params } => { - self.archive_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::SendUserMessage { request_id, params } => { - self.send_user_message(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::SendUserTurn { request_id, params } => { - self.send_user_turn(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::InterruptConversation { request_id, params } => { - self.interrupt_conversation(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::AddConversationListener { request_id, params } => { - self.add_conversation_listener(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::RemoveConversationListener { request_id, params } => { - self.remove_thread_listener(to_connection_request_id(request_id), params) - .await; - } ClientRequest::GitDiffToRemote { request_id, params } => { self.git_diff_to_origin(to_connection_request_id(request_id), params.cwd) .await; } - ClientRequest::LoginApiKey { request_id, params } => { - self.login_api_key_v1(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::LoginChatGpt { - request_id, - params: _, - } => { - self.login_chatgpt_v1(to_connection_request_id(request_id)) - .await; - } - ClientRequest::CancelLoginChatGpt { request_id, params } => { - self.cancel_login_chatgpt(to_connection_request_id(request_id), params.login_id) - .await; - } - ClientRequest::LogoutChatGpt { - request_id, - params: _, - } => { - self.logout_v1(to_connection_request_id(request_id)).await; - } ClientRequest::GetAuthStatus { request_id, params } => { self.get_auth_status(to_connection_request_id(request_id), params) .await; } - ClientRequest::GetUserSavedConfig { - request_id, - params: _, - } => { - self.get_user_saved_config(to_connection_request_id(request_id)) - .await; - } - ClientRequest::SetDefaultModel { request_id, params } => { - self.set_default_model(to_connection_request_id(request_id), params) - .await; - } - ClientRequest::GetUserAgent { - request_id, - params: _, - } => { - self.get_user_agent(to_connection_request_id(request_id)) - .await; - } - ClientRequest::UserInfo { - request_id, - params: _, - } => { - self.get_user_info(to_connection_request_id(request_id)) - .await; - } ClientRequest::FuzzyFileSearch { request_id, params } => { self.fuzzy_file_search(to_connection_request_id(request_id), params) .await; @@ -838,10 +777,6 @@ impl CodexMessageProcessor { self.exec_one_off_command(to_connection_request_id(request_id), params) .await; } - ClientRequest::ExecOneOffCommand { request_id, params } => { - self.exec_one_off_command(to_connection_request_id(request_id), params.into()) - .await; - } ClientRequest::ConfigRead { .. } | ClientRequest::ConfigValueWrite { .. } | ClientRequest::ConfigBatchWrite { .. } => { @@ -946,34 +881,6 @@ impl CodexMessageProcessor { } } - async fn login_api_key_v1( - &mut self, - request_id: ConnectionRequestId, - params: LoginApiKeyParams, - ) { - match self.login_api_key_common(¶ms).await { - Ok(()) => { - self.outgoing - .send_response(request_id, LoginApiKeyResponse {}) - .await; - - let payload = AuthStatusChangeNotification { - auth_method: self - .auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode), - }; - self.outgoing - .send_server_notification(ServerNotification::AuthStatusChange(payload)) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn login_api_key_v2( &mut self, request_id: ConnectionRequestId, @@ -995,15 +902,10 @@ impl CodexMessageProcessor { )) .await; - let payload_v2 = AccountUpdatedNotification { - auth_mode: self - .auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode), - }; self.outgoing - .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) + .send_server_notification(ServerNotification::AccountUpdated( + self.current_account_updated_notification(), + )) .await; } Err(error) => { @@ -1041,115 +943,6 @@ impl CodexMessageProcessor { }) } - // Deprecated in favor of login_chatgpt_v2. - async fn login_chatgpt_v1(&mut self, request_id: ConnectionRequestId) { - match self.login_chatgpt_common().await { - Ok(opts) => match run_login_server(opts) { - Ok(server) => { - let login_id = Uuid::new_v4(); - let shutdown_handle = server.cancel_handle(); - - // Replace active login if present. - { - let mut guard = self.active_login.lock().await; - if let Some(existing) = guard.take() { - drop(existing); - } - *guard = Some(ActiveLogin { - shutdown_handle: shutdown_handle.clone(), - login_id, - }); - } - - // Spawn background task to monitor completion. - let outgoing_clone = self.outgoing.clone(); - let active_login = self.active_login.clone(); - let auth_manager = self.auth_manager.clone(); - let cloud_requirements = self.cloud_requirements.clone(); - let chatgpt_base_url = self.config.chatgpt_base_url.clone(); - let codex_home = self.config.codex_home.clone(); - let cli_overrides = self.cli_overrides.clone(); - let auth_url = server.auth_url.clone(); - tokio::spawn(async move { - let (success, error_msg) = match tokio::time::timeout( - LOGIN_CHATGPT_TIMEOUT, - server.block_until_done(), - ) - .await - { - Ok(Ok(())) => (true, None), - Ok(Err(err)) => (false, Some(format!("Login server error: {err}"))), - Err(_elapsed) => { - shutdown_handle.shutdown(); - (false, Some("Login timed out".to_string())) - } - }; - - let payload = LoginChatGptCompleteNotification { - login_id, - success, - error: error_msg.clone(), - }; - outgoing_clone - .send_server_notification(ServerNotification::LoginChatGptComplete( - payload, - )) - .await; - - if success { - auth_manager.reload(); - replace_cloud_requirements_loader( - cloud_requirements.as_ref(), - auth_manager.clone(), - chatgpt_base_url, - codex_home, - ); - sync_default_client_residency_requirement( - &cli_overrides, - cloud_requirements.as_ref(), - ) - .await; - - // Notify clients with the actual current auth mode. - let current_auth_method = auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode); - let payload = AuthStatusChangeNotification { - auth_method: current_auth_method, - }; - outgoing_clone - .send_server_notification(ServerNotification::AuthStatusChange( - payload, - )) - .await; - } - - // Clear the active login if it matches this attempt. It may have been replaced or cancelled. - let mut guard = active_login.lock().await; - if guard.as_ref().map(|l| l.login_id) == Some(login_id) { - *guard = None; - } - }); - - let response = LoginChatGptResponse { login_id, auth_url }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to start login server: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - }, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - } - } - } - async fn login_chatgpt_v2(&mut self, request_id: ConnectionRequestId) { match self.login_chatgpt_common().await { Ok(opts) => match run_login_server(opts) { @@ -1219,12 +1012,10 @@ impl CodexMessageProcessor { .await; // Notify clients with the actual current auth mode. - let current_auth_method = auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode); + let auth = auth_manager.auth_cached(); let payload_v2 = AccountUpdatedNotification { - auth_mode: current_auth_method, + auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), + plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), }; outgoing_clone .send_server_notification(ServerNotification::AccountUpdated( @@ -1272,25 +1063,7 @@ impl CodexMessageProcessor { } Ok(()) } else { - Err(CancelLoginError::NotFound(login_id)) - } - } - - async fn cancel_login_chatgpt(&mut self, request_id: ConnectionRequestId, login_id: Uuid) { - match self.cancel_login_chatgpt_common(login_id).await { - Ok(()) => { - self.outgoing - .send_response(request_id, CancelLoginChatGptResponse {}) - .await; - } - Err(CancelLoginError::NotFound(missing_login_id)) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("login id not found: {missing_login_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } + Err(CancelLoginError::NotFound) } } @@ -1304,7 +1077,7 @@ impl CodexMessageProcessor { Ok(uuid) => { let status = match self.cancel_login_chatgpt_common(uuid).await { Ok(()) => CancelLoginAccountStatus::Canceled, - Err(CancelLoginError::NotFound(_)) => CancelLoginAccountStatus::NotFound, + Err(CancelLoginError::NotFound) => CancelLoginAccountStatus::NotFound, }; let response = CancelLoginAccountResponse { status }; self.outgoing.send_response(request_id, response).await; @@ -1405,11 +1178,10 @@ impl CodexMessageProcessor { )) .await; - let payload_v2 = AccountUpdatedNotification { - auth_mode: self.auth_manager.get_api_auth_mode(), - }; self.outgoing - .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) + .send_server_notification(ServerNotification::AccountUpdated( + self.current_account_updated_notification(), + )) .await; } @@ -1438,26 +1210,6 @@ impl CodexMessageProcessor { .map(CodexAuth::api_auth_mode)) } - async fn logout_v1(&mut self, request_id: ConnectionRequestId) { - match self.logout_common().await { - Ok(current_auth_method) => { - self.outgoing - .send_response(request_id, LogoutChatGptResponse {}) - .await; - - let payload = AuthStatusChangeNotification { - auth_method: current_auth_method, - }; - self.outgoing - .send_server_notification(ServerNotification::AuthStatusChange(payload)) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn logout_v2(&mut self, request_id: ConnectionRequestId) { match self.logout_common().await { Ok(current_auth_method) => { @@ -1467,6 +1219,7 @@ impl CodexMessageProcessor { let payload_v2 = AccountUpdatedNotification { auth_mode: current_auth_method, + plan_type: None, }; self.outgoing .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) @@ -1588,12 +1341,6 @@ impl CodexMessageProcessor { self.outgoing.send_response(request_id, response).await; } - async fn get_user_agent(&self, request_id: ConnectionRequestId) { - let user_agent = get_codex_user_agent(); - let response = GetUserAgentResponse { user_agent }; - self.outgoing.send_response(request_id, response).await; - } - async fn get_account_rate_limits(&self, request_id: ConnectionRequestId) { match self.fetch_account_rate_limits().await { Ok((rate_limits, rate_limits_by_limit_id)) => { @@ -1683,69 +1430,6 @@ impl CodexMessageProcessor { Ok((primary, rate_limits_by_limit_id)) } - async fn get_user_saved_config(&self, request_id: ConnectionRequestId) { - let service = ConfigService::new_with_defaults(self.config.codex_home.clone()); - let user_saved_config: UserSavedConfig = match service.load_user_saved_config().await { - Ok(config) => config, - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err.to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let response = GetUserSavedConfigResponse { - config: user_saved_config, - }; - self.outgoing.send_response(request_id, response).await; - } - - async fn get_user_info(&self, request_id: ConnectionRequestId) { - // Read alleged user email from cached auth (best-effort; not verified). - let alleged_user_email = self - .auth_manager - .auth_cached() - .and_then(|a| a.get_account_email()); - - let response = UserInfoResponse { alleged_user_email }; - self.outgoing.send_response(request_id, response).await; - } - - async fn set_default_model( - &self, - request_id: ConnectionRequestId, - params: SetDefaultModelParams, - ) { - let SetDefaultModelParams { - model, - reasoning_effort, - } = params; - - match ConfigEditsBuilder::new(&self.config.codex_home) - .with_profile(self.config.active_profile.as_deref()) - .set_model(model.as_deref(), reasoning_effort) - .apply() - .await - { - Ok(()) => { - let response = SetDefaultModelResponse {}; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to persist model selection: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn exec_one_off_command( &self, request_id: ConnectionRequestId, @@ -1797,10 +1481,8 @@ impl CodexMessageProcessor { None => None, }; let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config); - let command = params.command; let exec_params = ExecParams { - original_command: command.join(" "), - command, + command: params.command, cwd, expiration: timeout_ms.into(), env, @@ -1869,123 +1551,11 @@ impl CodexMessageProcessor { }); } - async fn process_new_conversation( - &mut self, - request_id: ConnectionRequestId, - params: NewConversationParams, - ) { - let NewConversationParams { - model, - model_provider, - profile, - cwd, - approval_policy, - sandbox: sandbox_mode, - config: request_overrides, - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - } = params; - - let typesafe_overrides = ConfigOverrides { - model, - config_profile: profile, - cwd: cwd.clone().map(PathBuf::from), - approval_policy, - sandbox_mode, - model_provider, - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - ..Default::default() - }; - - // Persist Windows sandbox mode. - // TODO: persist default config in general. - let mut request_overrides = request_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - request_overrides - .insert("windows.sandbox".to_string(), serde_json::json!("elevated")); - } - WindowsSandboxLevel::RestrictedToken => { - request_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} - } - } - - let cloud_requirements = self.current_cloud_requirements(); - let config = match derive_config_from_params( - &self.cli_overrides, - Some(request_overrides), - typesafe_overrides, - &cloud_requirements, - ) - .await - { - Ok(config) => config, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("error deriving config: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - match self.thread_manager.start_thread(config).await { - Ok(new_thread) => { - let NewThread { - thread_id, - session_configured, - .. - } = new_thread; - let rollout_path = match session_configured.rollout_path { - Some(path) => path, - None => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "rollout path missing for v1 conversation".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let response = NewConversationResponse { - conversation_id: thread_id, - model: session_configured.model, - reasoning_effort: session_configured.reasoning_effort, - rollout_path, - }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("error creating conversation: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - - async fn thread_start(&mut self, request_id: ConnectionRequestId, params: ThreadStartParams) { + async fn thread_start(&self, request_id: ConnectionRequestId, params: ThreadStartParams) { let ThreadStartParams { model, model_provider, + service_tier, cwd, approval_policy, sandbox, @@ -2003,6 +1573,7 @@ impl CodexMessageProcessor { let mut typesafe_overrides = self.build_thread_config_overrides( model, model_provider, + service_tier, cwd, approval_policy, sandbox, @@ -2011,11 +1582,50 @@ impl CodexMessageProcessor { personality, ); typesafe_overrides.ephemeral = ephemeral; - + let cli_overrides = self.cli_overrides.clone(); let cloud_requirements = self.current_cloud_requirements(); + let listener_task_context = ListenerTaskContext { + thread_manager: Arc::clone(&self.thread_manager), + thread_state_manager: self.thread_state_manager.clone(), + outgoing: Arc::clone(&self.outgoing), + thread_watch_manager: self.thread_watch_manager.clone(), + fallback_model_provider: self.config.model_provider_id.clone(), + codex_home: self.config.codex_home.clone(), + }; + + tokio::spawn(async move { + Self::thread_start_task( + listener_task_context, + cli_overrides, + cloud_requirements, + request_id, + config, + typesafe_overrides, + dynamic_tools, + persist_extended_history, + service_name, + experimental_raw_events, + ) + .await; + }); + } + + #[allow(clippy::too_many_arguments)] + async fn thread_start_task( + listener_task_context: ListenerTaskContext, + cli_overrides: Vec<(String, TomlValue)>, + cloud_requirements: CloudRequirementsLoader, + request_id: ConnectionRequestId, + config_overrides: Option>, + typesafe_overrides: ConfigOverrides, + dynamic_tools: Option>, + persist_extended_history: bool, + service_name: Option, + experimental_raw_events: bool, + ) { let config = match derive_config_from_params( - &self.cli_overrides, - config, + &cli_overrides, + config_overrides, typesafe_overrides, &cloud_requirements, ) @@ -2028,7 +1638,10 @@ impl CodexMessageProcessor { message: format!("error deriving config: {err}"), data: None, }; - self.outgoing.send_error(request_id, error).await; + listener_task_context + .outgoing + .send_error(request_id, error) + .await; return; } }; @@ -2043,7 +1656,10 @@ impl CodexMessageProcessor { message, data: None, }; - self.outgoing.send_error(request_id, error).await; + listener_task_context + .outgoing + .send_error(request_id, error) + .await; return; } dynamic_tools @@ -2056,7 +1672,7 @@ impl CodexMessageProcessor { .collect() }; - match self + match listener_task_context .thread_manager .start_thread_with_tools_and_service_name( config, @@ -2081,29 +1697,28 @@ impl CodexMessageProcessor { ); // Auto-attach a thread listener when starting a thread. - // Use the same behavior as the v1 API, with opt-in support for raw item events. - if let Err(err) = self - .ensure_conversation_listener( + Self::log_listener_attach_result( + Self::ensure_conversation_listener_task( + listener_task_context.clone(), thread_id, request_id.connection_id, experimental_raw_events, ApiVersion::V2, ) - .await - { - tracing::warn!( - "failed to attach listener for thread {}: {}", - thread_id, - err.message - ); - } + .await, + thread_id, + request_id.connection_id, + "thread", + ); - self.thread_watch_manager - .upsert_thread(thread.clone()) + listener_task_context + .thread_watch_manager + .upsert_thread_silently(thread.clone()) .await; thread.status = resolve_thread_status( - self.thread_watch_manager + listener_task_context + .thread_watch_manager .loaded_status_for_thread(&thread.id) .await, false, @@ -2113,16 +1728,21 @@ impl CodexMessageProcessor { thread: thread.clone(), model: config_snapshot.model, model_provider: config_snapshot.model_provider_id, + service_tier: config_snapshot.service_tier, cwd: config_snapshot.cwd, approval_policy: config_snapshot.approval_policy.into(), sandbox: config_snapshot.sandbox_policy.into(), reasoning_effort: config_snapshot.reasoning_effort, }; - self.outgoing.send_response(request_id, response).await; + listener_task_context + .outgoing + .send_response(request_id, response) + .await; let notif = ThreadStartedNotification { thread }; - self.outgoing + listener_task_context + .outgoing .send_server_notification(ServerNotification::ThreadStarted(notif)) .await; } @@ -2132,7 +1752,10 @@ impl CodexMessageProcessor { message: format!("error creating thread: {err}"), data: None, }; - self.outgoing.send_error(request_id, error).await; + listener_task_context + .outgoing + .send_error(request_id, error) + .await; } } } @@ -2142,6 +1765,7 @@ impl CodexMessageProcessor { &self, model: Option, model_provider: Option, + service_tier: Option>, cwd: Option, approval_policy: Option, sandbox: Option, @@ -2152,6 +1776,7 @@ impl CodexMessageProcessor { ConfigOverrides { model, model_provider, + service_tier, cwd: cwd.map(PathBuf::from), approval_policy: approval_policy .map(codex_app_server_protocol::AskForApproval::to_core), @@ -2228,6 +1853,14 @@ impl CodexMessageProcessor { async fn thread_set_name(&self, request_id: ConnectionRequestId, params: ThreadSetNameParams) { let ThreadSetNameParams { thread_id, name } = params; + let thread_id = match ThreadId::from_string(&thread_id) { + Ok(id) => id, + Err(err) => { + self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) + .await; + return; + } + }; let Some(name) = codex_core::util::normalize_thread_name(&name) else { self.send_invalid_request_error( request_id, @@ -2237,15 +1870,43 @@ impl CodexMessageProcessor { return; }; - let (_, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; + if let Ok(thread) = self.thread_manager.get_thread(thread_id).await { + if let Err(err) = thread.submit(Op::SetThreadName { name }).await { + self.send_internal_error(request_id, format!("failed to set thread name: {err}")) + .await; return; } - }; - if let Err(err) = thread.submit(Op::SetThreadName { name }).await { + self.outgoing + .send_response(request_id, ThreadSetNameResponse {}) + .await; + return; + } + + let thread_exists = + match find_thread_path_by_id_str(&self.config.codex_home, &thread_id.to_string()).await + { + Ok(Some(_)) => true, + Ok(None) => false, + Err(err) => { + self.send_invalid_request_error( + request_id, + format!("failed to locate thread id {thread_id}: {err}"), + ) + .await; + return; + } + }; + + if !thread_exists { + self.send_invalid_request_error(request_id, format!("thread not found: {thread_id}")) + .await; + return; + } + + if let Err(err) = + codex_core::append_thread_name(&self.config.codex_home, thread_id, &name).await + { self.send_internal_error(request_id, format!("failed to set thread name: {err}")) .await; return; @@ -2254,6 +1915,13 @@ impl CodexMessageProcessor { self.outgoing .send_response(request_id, ThreadSetNameResponse {}) .await; + let notification = ThreadNameUpdatedNotification { + thread_id: thread_id.to_string(), + thread_name: Some(name), + }; + self.outgoing + .send_server_notification(ServerNotification::ThreadNameUpdated(notification)) + .await; } async fn thread_unarchive( @@ -2472,7 +2140,7 @@ impl CodexMessageProcessor { let request = request_id.clone(); let rollback_already_in_progress = { - let thread_state = self.thread_state_manager.thread_state(thread_id); + let thread_state = self.thread_state_manager.thread_state(thread_id).await; let mut thread_state = thread_state.lock().await; if thread_state.pending_rollbacks.is_some() { true @@ -2493,7 +2161,7 @@ impl CodexMessageProcessor { if let Err(err) = thread.submit(Op::ThreadRollback { num_turns }).await { // No ThreadRollback event will arrive if an error occurs. // Clean up and reply immediately. - let thread_state = self.thread_state_manager.thread_state(thread_id); + let thread_state = self.thread_state_manager.thread_state(thread_id).await; let mut thread_state = thread_state.lock().await; thread_state.pending_rollbacks = None; drop(thread_state); @@ -2839,6 +2507,12 @@ impl CodexMessageProcessor { self.thread_manager.subscribe_thread_created() } + pub(crate) async fn connection_initialized(&self, connection_id: ConnectionId) { + self.thread_state_manager + .connection_initialized(connection_id) + .await; + } + pub(crate) async fn connection_closed(&mut self, connection_id: ConnectionId) { self.thread_state_manager .remove_connection(connection_id) @@ -2863,19 +2537,34 @@ impl CodexMessageProcessor { } for connection_id in connection_ids { - if let Err(err) = self - .ensure_conversation_listener(thread_id, connection_id, false, ApiVersion::V2) - .await - { - warn!( - "failed to auto-attach listener for thread {thread_id}: {message}", - message = err.message - ); - } + Self::log_listener_attach_result( + self.ensure_conversation_listener(thread_id, connection_id, false, ApiVersion::V2) + .await, + thread_id, + connection_id, + "thread", + ); } } async fn thread_resume(&mut self, request_id: ConnectionRequestId, params: ThreadResumeParams) { + if let Ok(thread_id) = ThreadId::from_string(¶ms.thread_id) + && self + .pending_thread_unloads + .lock() + .await + .contains(&thread_id) + { + self.send_invalid_request_error( + request_id, + format!( + "thread {thread_id} is closing; retry thread/resume after the thread is closed" + ), + ) + .await; + return; + } + if self .resume_running_thread(request_id.clone(), ¶ms) .await @@ -2889,6 +2578,7 @@ impl CodexMessageProcessor { path, model, model_provider, + service_tier, cwd, approval_policy, sandbox, @@ -2921,6 +2611,7 @@ impl CodexMessageProcessor { let typesafe_overrides = self.build_thread_config_overrides( model, model_provider, + service_tier, cwd, approval_policy, sandbox, @@ -2979,21 +2670,18 @@ impl CodexMessageProcessor { return; }; // Auto-attach a thread listener when resuming a thread. - if let Err(err) = self - .ensure_conversation_listener( + Self::log_listener_attach_result( + self.ensure_conversation_listener( thread_id, request_id.connection_id, false, ApiVersion::V2, ) - .await - { - tracing::warn!( - "failed to attach listener for thread {}: {}", - thread_id, - err.message - ); - } + .await, + thread_id, + request_id.connection_id, + "thread", + ); let Some(mut thread) = self .load_thread_from_rollout_or_send_internal( @@ -3022,6 +2710,7 @@ impl CodexMessageProcessor { thread, model: session_configured.model, model_provider: session_configured.model_provider_id, + service_tier: session_configured.service_tier, cwd: session_configured.cwd, approval_policy: session_configured.approval_policy.into(), sandbox: session_configured.sandbox_policy.into(), @@ -3131,7 +2820,10 @@ impl CodexMessageProcessor { return true; } - let thread_state = self.thread_state_manager.thread_state(existing_thread_id); + let thread_state = self + .thread_state_manager + .thread_state(existing_thread_id) + .await; self.ensure_listener_task_running( existing_thread_id, existing_thread.clone(), @@ -3167,11 +2859,11 @@ impl CodexMessageProcessor { }; let command = crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse( - crate::thread_state::PendingThreadResumeRequest { + Box::new(crate::thread_state::PendingThreadResumeRequest { request_id: request_id.clone(), rollout_path, config_snapshot, - }, + }), ); if listener_command_tx.send(command).is_err() { let err = JSONRPCErrorError { @@ -3326,6 +3018,7 @@ impl CodexMessageProcessor { path, model, model_provider, + service_tier, cwd, approval_policy, sandbox, @@ -3406,6 +3099,7 @@ impl CodexMessageProcessor { let typesafe_overrides = self.build_thread_config_overrides( model, model_provider, + service_tier, cwd, approval_policy, sandbox, @@ -3482,21 +3176,18 @@ impl CodexMessageProcessor { return; }; // Auto-attach a conversation listener when forking a thread. - if let Err(err) = self - .ensure_conversation_listener( + Self::log_listener_attach_result( + self.ensure_conversation_listener( thread_id, request_id.connection_id, false, ApiVersion::V2, ) - .await - { - tracing::warn!( - "failed to attach listener for thread {}: {}", - thread_id, - err.message - ); - } + .await, + thread_id, + request_id.connection_id, + "thread", + ); let mut thread = match read_summary_from_rollout( rollout_path.as_path(), @@ -3536,7 +3227,7 @@ impl CodexMessageProcessor { } self.thread_watch_manager - .upsert_thread(thread.clone()) + .upsert_thread_silently(thread.clone()) .await; thread.status = resolve_thread_status( @@ -3550,6 +3241,7 @@ impl CodexMessageProcessor { thread: thread.clone(), model: session_configured.model, model_provider: session_configured.model_provider_id, + service_tier: session_configured.service_tier, cwd: session_configured.cwd, approval_policy: session_configured.approval_policy.into(), sandbox: session_configured.sandbox_policy.into(), @@ -3630,45 +3322,6 @@ impl CodexMessageProcessor { } } - async fn handle_list_conversations( - &self, - request_id: ConnectionRequestId, - params: ListConversationsParams, - ) { - let ListConversationsParams { - page_size, - cursor, - model_providers, - } = params; - let requested_page_size = page_size - .unwrap_or(THREAD_LIST_DEFAULT_LIMIT) - .clamp(1, THREAD_LIST_MAX_LIMIT); - - match self - .list_threads_common( - requested_page_size, - cursor, - CoreThreadSortKey::UpdatedAt, - ThreadListFilters { - model_providers, - source_kinds: None, - archived: false, - cwd: None, - search_term: None, - }, - ) - .await - { - Ok((items, next_cursor)) => { - let response = ListConversationsResponse { items, next_cursor }; - self.outgoing.send_response(request_id, response).await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - }; - } - async fn list_threads_common( &self, requested_page_size: usize, @@ -3878,7 +3531,11 @@ impl CodexMessageProcessor { params: CollaborationModeListParams, ) { let CollaborationModeListParams {} = params; - let items = thread_manager.list_collaboration_modes(); + let items = thread_manager + .list_collaboration_modes() + .into_iter() + .map(Into::into) + .collect(); let response = CollaborationModeListResponse { data: items }; outgoing.send_response(request_id, response).await; } @@ -4012,7 +3669,11 @@ impl CodexMessageProcessor { } }; - let mcp_servers = match serde_json::to_value(config.mcp_servers.get()) { + let configured_servers = self + .thread_manager + .mcp_manager() + .configured_servers(&config); + let mcp_servers = match serde_json::to_value(configured_servers) { Ok(value) => value, Err(err) => { let error = JSONRPCErrorError { @@ -4073,7 +3734,11 @@ impl CodexMessageProcessor { timeout_secs, } = params; - let Some(server) = config.mcp_servers.get().get(&name) else { + let configured_servers = self + .thread_manager + .mcp_manager() + .configured_servers(&config); + let Some(server) = configured_servers.get(&name) else { let error = JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, message: format!("No MCP server named '{name}' found."), @@ -4111,6 +3776,7 @@ impl CodexMessageProcessor { http_headers, env_http_headers, scopes.as_deref().unwrap_or_default(), + server.oauth_resource.as_deref(), timeout_secs, config.mcp_oauth_callback_port, config.mcp_oauth_callback_url.as_deref(), @@ -4256,438 +3922,6 @@ impl CodexMessageProcessor { outgoing.send_response(request_id, response).await; } - async fn handle_resume_conversation( - &self, - request_id: ConnectionRequestId, - params: ResumeConversationParams, - ) { - let ResumeConversationParams { - path, - conversation_id, - history, - overrides, - } = params; - - let thread_history = if let Some(path) = path { - match RolloutRecorder::get_rollout_history(&path).await { - Ok(initial_history) => initial_history, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to load rollout `{}`: {err}", path.display()), - ) - .await; - return; - } - } - } else if let Some(conversation_id) = conversation_id { - match find_thread_path_by_id_str(&self.config.codex_home, &conversation_id.to_string()) - .await - { - Ok(Some(found_path)) => { - match RolloutRecorder::get_rollout_history(&found_path).await { - Ok(initial_history) => initial_history, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!( - "failed to load rollout `{}` for conversation {conversation_id}: {err}", - found_path.display() - ), - ).await; - return; - } - } - } - Ok(None) => { - self.send_invalid_request_error( - request_id, - format!("no rollout found for conversation id {conversation_id}"), - ) - .await; - return; - } - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to locate conversation id {conversation_id}: {err}"), - ) - .await; - return; - } - } - } else { - match history { - Some(history) if !history.is_empty() => InitialHistory::Forked( - history.into_iter().map(RolloutItem::ResponseItem).collect(), - ), - Some(_) | None => { - self.send_invalid_request_error( - request_id, - "either path, conversation id or non empty history must be provided" - .to_string(), - ) - .await; - return; - } - } - }; - - let history_cwd = thread_history.session_cwd(); - let (typesafe_overrides, request_overrides) = match overrides { - Some(overrides) => { - let NewConversationParams { - model, - model_provider, - profile, - cwd, - approval_policy, - sandbox: sandbox_mode, - config: request_overrides, - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - } = overrides; - - // Persist Windows sandbox mode. - let mut request_overrides = request_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - request_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("elevated"), - ); - } - WindowsSandboxLevel::RestrictedToken => { - request_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} - } - } - - let typesafe_overrides = ConfigOverrides { - model, - config_profile: profile, - cwd: cwd.map(PathBuf::from), - approval_policy, - sandbox_mode, - model_provider, - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - ..Default::default() - }; - (typesafe_overrides, Some(request_overrides)) - } - None => ( - ConfigOverrides { - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - ..Default::default() - }, - None, - ), - }; - - let cloud_requirements = self.current_cloud_requirements(); - let config = match derive_config_for_cwd( - &self.cli_overrides, - request_overrides, - typesafe_overrides, - history_cwd, - &cloud_requirements, - ) - .await - { - Ok(cfg) => cfg, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("error deriving config: {err}"), - ) - .await; - return; - } - }; - - match self - .thread_manager - .resume_thread_with_history(config, thread_history, self.auth_manager.clone(), false) - .await - { - Ok(NewThread { - thread_id, - session_configured, - .. - }) => { - let rollout_path = match session_configured.rollout_path.clone() { - Some(path) => path, - None => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "rollout path missing for resumed conversation".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - self.outgoing - .send_server_notification(ServerNotification::SessionConfigured( - SessionConfiguredNotification { - session_id: session_configured.session_id, - model: session_configured.model.clone(), - reasoning_effort: session_configured.reasoning_effort, - history_log_id: session_configured.history_log_id, - history_entry_count: session_configured.history_entry_count, - initial_messages: session_configured.initial_messages.clone(), - rollout_path: rollout_path.clone(), - }, - )) - .await; - let initial_messages = session_configured - .initial_messages - .map(|msgs| msgs.into_iter().collect()); - - // Reply with thread id + model and initial messages (when present) - let response = ResumeConversationResponse { - conversation_id: thread_id, - model: session_configured.model.clone(), - initial_messages, - rollout_path, - }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("error resuming conversation: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - - async fn handle_fork_conversation( - &self, - request_id: ConnectionRequestId, - params: ForkConversationParams, - ) { - let ForkConversationParams { - path, - conversation_id, - overrides, - } = params; - - // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let (rollout_path, source_thread_id) = if let Some(path) = path { - (path, None) - } else if let Some(conversation_id) = conversation_id { - match find_thread_path_by_id_str(&self.config.codex_home, &conversation_id.to_string()) - .await - { - Ok(Some(found_path)) => (found_path, Some(conversation_id)), - Ok(None) => { - self.send_invalid_request_error( - request_id, - format!("no rollout found for conversation id {conversation_id}"), - ) - .await; - return; - } - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to locate conversation id {conversation_id}: {err}"), - ) - .await; - return; - } - } - } else { - self.send_invalid_request_error( - request_id, - "either path or conversation id must be provided".to_string(), - ) - .await; - return; - }; - - let history_cwd = - read_history_cwd_from_state_db(&self.config, source_thread_id, rollout_path.as_path()) - .await; - - let (typesafe_overrides, request_overrides) = match overrides { - Some(overrides) => { - let NewConversationParams { - model, - model_provider, - profile, - cwd, - approval_policy, - sandbox: sandbox_mode, - config: cli_overrides, - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - } = overrides; - - // Persist Windows sandbox mode. - let mut cli_overrides = cli_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - cli_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("elevated"), - ); - } - WindowsSandboxLevel::RestrictedToken => { - cli_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} - } - } - let request_overrides = if cli_overrides.is_empty() { - None - } else { - Some(cli_overrides) - }; - - let overrides = ConfigOverrides { - model, - config_profile: profile, - cwd: cwd.map(PathBuf::from), - approval_policy, - sandbox_mode, - model_provider, - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - base_instructions, - developer_instructions, - compact_prompt, - include_apply_patch_tool, - ..Default::default() - }; - - (overrides, request_overrides) - } - None => ( - ConfigOverrides { - codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(), - main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(), - ..Default::default() - }, - None, - ), - }; - - let cloud_requirements = self.current_cloud_requirements(); - let config = match derive_config_for_cwd( - &self.cli_overrides, - request_overrides, - typesafe_overrides, - history_cwd, - &cloud_requirements, - ) - .await - { - Ok(cfg) => cfg, - Err(err) => { - self.send_invalid_request_error( - request_id, - format!("error deriving config: {err}"), - ) - .await; - return; - } - }; - - let NewThread { - thread_id, - session_configured, - .. - } = match self - .thread_manager - .fork_thread(usize::MAX, config, rollout_path.clone(), false) - .await - { - Ok(thread) => thread, - Err(err) => { - let (code, message) = match err { - CodexErr::Io(_) | CodexErr::Json(_) => ( - INVALID_REQUEST_ERROR_CODE, - format!("failed to load rollout `{}`: {err}", rollout_path.display()), - ), - CodexErr::InvalidRequest(message) => (INVALID_REQUEST_ERROR_CODE, message), - _ => ( - INTERNAL_ERROR_CODE, - format!("error forking conversation: {err}"), - ), - }; - let error = JSONRPCErrorError { - code, - message, - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let rollout_path = match session_configured.rollout_path.clone() { - Some(path) => path, - None => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "rollout path missing for forked conversation".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - self.outgoing - .send_server_notification(ServerNotification::SessionConfigured( - SessionConfiguredNotification { - session_id: session_configured.session_id, - model: session_configured.model.clone(), - reasoning_effort: session_configured.reasoning_effort, - history_log_id: session_configured.history_log_id, - history_entry_count: session_configured.history_entry_count, - initial_messages: session_configured.initial_messages.clone(), - rollout_path: rollout_path.clone(), - }, - )) - .await; - let initial_messages = session_configured - .initial_messages - .map(|msgs| msgs.into_iter().collect()); - - // Reply with conversation id + model and initial messages (when present) - let response = ForkConversationResponse { - conversation_id: thread_id, - model: session_configured.model.clone(), - initial_messages, - rollout_path, - }; - self.outgoing.send_response(request_id, response).await; - } - async fn send_invalid_request_error(&self, request_id: ConnectionRequestId, message: String) { let error = JSONRPCErrorError { code: INVALID_REQUEST_ERROR_CODE, @@ -4697,6 +3931,28 @@ impl CodexMessageProcessor { self.outgoing.send_error(request_id, error).await; } + fn input_too_large_error(actual_chars: usize) -> JSONRPCErrorError { + JSONRPCErrorError { + code: INVALID_PARAMS_ERROR_CODE, + message: format!( + "Input exceeds the maximum length of {MAX_USER_INPUT_TEXT_CHARS} characters." + ), + data: Some(serde_json::json!({ + "input_error_code": INPUT_TOO_LARGE_ERROR_CODE, + "max_chars": MAX_USER_INPUT_TEXT_CHARS, + "actual_chars": actual_chars, + })), + } + } + + fn validate_v2_input_limit(items: &[V2UserInput]) -> Result<(), JSONRPCErrorError> { + let actual_chars: usize = items.iter().map(V2UserInput::text_char_count).sum(); + if actual_chars > MAX_USER_INPUT_TEXT_CHARS { + return Err(Self::input_too_large_error(actual_chars)); + } + Ok(()) + } + async fn send_internal_error(&self, request_id: ConnectionRequestId, message: String) { let error = JSONRPCErrorError { code: INTERNAL_ERROR_CODE, @@ -4706,27 +3962,152 @@ impl CodexMessageProcessor { self.outgoing.send_error(request_id, error).await; } - async fn archive_conversation( + async fn wait_for_thread_shutdown(thread: &Arc) -> ThreadShutdownResult { + match thread.submit(Op::Shutdown).await { + Ok(_) => { + let wait_for_shutdown = async { + loop { + if matches!(thread.agent_status().await, AgentStatus::Shutdown) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }; + if tokio::time::timeout(Duration::from_secs(10), wait_for_shutdown) + .await + .is_err() + { + ThreadShutdownResult::TimedOut + } else { + ThreadShutdownResult::Complete + } + } + Err(_) => ThreadShutdownResult::SubmitFailed, + } + } + + async fn finalize_thread_teardown(&mut self, thread_id: ThreadId) { + self.pending_thread_unloads.lock().await.remove(&thread_id); + self.outgoing + .cancel_requests_for_thread(thread_id, None) + .await; + self.thread_state_manager + .remove_thread_state(thread_id) + .await; + self.thread_watch_manager + .remove_thread(&thread_id.to_string()) + .await; + } + + async fn thread_unsubscribe( &mut self, request_id: ConnectionRequestId, - params: ArchiveConversationParams, + params: ThreadUnsubscribeParams, ) { - let ArchiveConversationParams { - conversation_id: thread_id, - rollout_path, - } = params; - - match self.archive_thread_common(thread_id, &rollout_path).await { - Ok(()) => { - tracing::info!("thread/archive succeeded for {thread_id}"); - let response = ArchiveConversationResponse {}; - self.outgoing.send_response(request_id, response).await; - } + let thread_id = match ThreadId::from_string(¶ms.thread_id) { + Ok(id) => id, Err(err) => { - tracing::warn!("thread/archive failed for {thread_id}: {}", err.message); - self.outgoing.send_error(request_id, err).await; + self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) + .await; + return; } + }; + + let Ok(thread) = self.thread_manager.get_thread(thread_id).await else { + // Reconcile stale app-server bookkeeping when the thread has already been + // removed from the core manager. This keeps loaded-status/subscription state + // consistent with the source of truth before reporting NotLoaded. + self.finalize_thread_teardown(thread_id).await; + self.outgoing + .send_response( + request_id, + ThreadUnsubscribeResponse { + status: ThreadUnsubscribeStatus::NotLoaded, + }, + ) + .await; + return; + }; + + let was_subscribed = self + .thread_state_manager + .unsubscribe_connection_from_thread(thread_id, request_id.connection_id) + .await; + if !was_subscribed { + self.outgoing + .send_response( + request_id, + ThreadUnsubscribeResponse { + status: ThreadUnsubscribeStatus::NotSubscribed, + }, + ) + .await; + return; } + + if !self.thread_state_manager.has_subscribers(thread_id).await { + // This connection was the last subscriber. Only now do we unload the thread. + info!("thread {thread_id} has no subscribers; shutting down"); + self.pending_thread_unloads.lock().await.insert(thread_id); + // Any pending app-server -> client requests for this thread can no longer be + // answered; cancel their callbacks before shutdown/unload. + self.outgoing + .cancel_requests_for_thread(thread_id, None) + .await; + self.thread_state_manager + .remove_thread_state(thread_id) + .await; + + let outgoing = self.outgoing.clone(); + let pending_thread_unloads = self.pending_thread_unloads.clone(); + let thread_manager = self.thread_manager.clone(); + let thread_watch_manager = self.thread_watch_manager.clone(); + tokio::spawn(async move { + match Self::wait_for_thread_shutdown(&thread).await { + ThreadShutdownResult::Complete => { + if thread_manager.remove_thread(&thread_id).await.is_none() { + info!( + "thread {thread_id} was already removed before unsubscribe finalized" + ); + thread_watch_manager + .remove_thread(&thread_id.to_string()) + .await; + pending_thread_unloads.lock().await.remove(&thread_id); + return; + } + thread_watch_manager + .remove_thread(&thread_id.to_string()) + .await; + let notification = ThreadClosedNotification { + thread_id: thread_id.to_string(), + }; + outgoing + .send_server_notification(ServerNotification::ThreadClosed( + notification, + )) + .await; + pending_thread_unloads.lock().await.remove(&thread_id); + } + ThreadShutdownResult::SubmitFailed => { + pending_thread_unloads.lock().await.remove(&thread_id); + warn!("failed to submit Shutdown to thread {thread_id}"); + } + ThreadShutdownResult::TimedOut => { + pending_thread_unloads.lock().await.remove(&thread_id); + warn!("thread {thread_id} shutdown timed out; leaving thread loaded"); + } + } + }); + } + + self.outgoing + .send_response( + request_id, + ThreadUnsubscribeResponse { + status: ThreadUnsubscribeStatus::Unsubscribed, + }, + ) + .await; } async fn archive_thread_common( @@ -4800,37 +4181,19 @@ impl CodexMessageProcessor { state_db_ctx = Some(ctx); } info!("thread {thread_id} was active; shutting down"); - // Request shutdown. - match conversation.submit(Op::Shutdown).await { - Ok(_) => { - // Poll agent status rather than consuming events so attached listeners do not block shutdown. - let wait_for_shutdown = async { - loop { - if matches!(conversation.agent_status().await, AgentStatus::Shutdown) { - break; - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - }; - if tokio::time::timeout(Duration::from_secs(10), wait_for_shutdown) - .await - .is_err() - { - warn!("thread {thread_id} shutdown timed out; proceeding with archive"); - } + match Self::wait_for_thread_shutdown(&conversation).await { + ThreadShutdownResult::Complete => {} + ThreadShutdownResult::SubmitFailed => { + error!( + "failed to submit Shutdown to thread {thread_id}; proceeding with archive" + ); } - Err(err) => { - error!("failed to submit Shutdown to thread {thread_id}: {err}"); + ThreadShutdownResult::TimedOut => { + warn!("thread {thread_id} shutdown timed out; proceeding with archive"); } } - self.thread_state_manager - .remove_thread_state(thread_id) - .await; } - - self.thread_watch_manager - .remove_thread(&thread_id.to_string()) - .await; + self.finalize_thread_teardown(thread_id).await; if state_db_ctx.is_none() { state_db_ctx = get_state_db(&self.config, None).await; @@ -4861,112 +4224,6 @@ impl CodexMessageProcessor { }) } - async fn send_user_message( - &self, - request_id: ConnectionRequestId, - params: SendUserMessageParams, - ) { - let SendUserMessageParams { - conversation_id, - items, - } = params; - let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("conversation not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - }; - - let mapped_items: Vec = items - .into_iter() - .map(|item| match item { - WireInputItem::Text { - text, - text_elements, - } => CoreInputItem::Text { - text, - text_elements: text_elements.into_iter().map(Into::into).collect(), - }, - WireInputItem::Image { image_url } => CoreInputItem::Image { image_url }, - WireInputItem::LocalImage { path } => CoreInputItem::LocalImage { path }, - }) - .collect(); - - // Submit user input to the conversation. - let _ = conversation - .submit(Op::UserInput { - items: mapped_items, - final_output_json_schema: None, - }) - .await; - - // Acknowledge with an empty result. - self.outgoing - .send_response(request_id, SendUserMessageResponse {}) - .await; - } - - async fn send_user_turn(&self, request_id: ConnectionRequestId, params: SendUserTurnParams) { - let SendUserTurnParams { - conversation_id, - items, - cwd, - approval_policy, - sandbox_policy, - model, - effort, - summary, - output_schema, - } = params; - - let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("conversation not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - }; - - let mapped_items: Vec = items - .into_iter() - .map(|item| match item { - WireInputItem::Text { - text, - text_elements, - } => CoreInputItem::Text { - text, - text_elements: text_elements.into_iter().map(Into::into).collect(), - }, - WireInputItem::Image { image_url } => CoreInputItem::Image { image_url }, - WireInputItem::LocalImage { path } => CoreInputItem::LocalImage { path }, - }) - .collect(); - - let _ = conversation - .submit(Op::UserTurn { - items: mapped_items, - cwd, - approval_policy, - sandbox_policy, - model, - effort, - summary, - final_output_json_schema: output_schema, - collaboration_mode: None, - personality: None, - }) - .await; - - self.outgoing - .send_response(request_id, SendUserTurnResponse {}) - .await; - } - async fn apps_list(&self, request_id: ConnectionRequestId, params: AppsListParams) { let mut config = match self.load_latest_config().await { Ok(config) => config, @@ -5044,6 +4301,7 @@ impl CodexMessageProcessor { connectors::list_cached_accessible_connectors_from_mcp_tools(&config), connectors::list_cached_all_connectors(&config) ); + let cached_all_connectors = all_connectors.clone(); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); @@ -5070,6 +4328,25 @@ impl CodexMessageProcessor { let app_list_deadline = tokio::time::Instant::now() + APP_LIST_LOAD_TIMEOUT; let mut accessible_loaded = false; let mut all_loaded = false; + let mut last_notified_apps = None; + + if accessible_connectors.is_some() || all_connectors.is_some() { + let merged = connectors::with_app_enabled_state( + Self::merge_loaded_apps( + all_connectors.as_deref(), + accessible_connectors.as_deref(), + ), + &config, + ); + if Self::should_send_app_list_updated_notification( + merged.as_slice(), + accessible_loaded, + all_loaded, + ) { + Self::send_app_list_updated_notification(&outgoing, merged.clone()).await; + last_notified_apps = Some(merged); + } + } loop { let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await { @@ -5126,14 +4403,35 @@ impl CodexMessageProcessor { } } + let showing_interim_force_refetch = force_refetch && !(accessible_loaded && all_loaded); + let all_connectors_for_update = + if showing_interim_force_refetch && cached_all_connectors.is_some() { + cached_all_connectors.as_deref() + } else { + all_connectors.as_deref() + }; + let accessible_connectors_for_update = + if showing_interim_force_refetch && !accessible_loaded { + None + } else { + accessible_connectors.as_deref() + }; let merged = connectors::with_app_enabled_state( Self::merge_loaded_apps( - all_connectors.as_deref(), - accessible_connectors.as_deref(), + all_connectors_for_update, + accessible_connectors_for_update, ), &config, ); - Self::send_app_list_updated_notification(&outgoing, merged.clone()).await; + if Self::should_send_app_list_updated_notification( + merged.as_slice(), + accessible_loaded, + all_loaded, + ) && last_notified_apps.as_ref() != Some(&merged) + { + Self::send_app_list_updated_notification(&outgoing, merged.clone()).await; + last_notified_apps = Some(merged.clone()); + } if accessible_loaded && all_loaded { match Self::paginate_apps(merged.as_slice(), start, limit) { @@ -5160,6 +4458,15 @@ impl CodexMessageProcessor { connectors::merge_connectors_with_accessible(all, accessible, all_connectors_loaded) } + fn should_send_app_list_updated_notification( + connectors: &[AppInfo], + accessible_loaded: bool, + all_loaded: bool, + ) -> bool { + connectors.iter().any(|connector| connector.is_accessible) + || (accessible_loaded && all_loaded) + } + fn paginate_apps( connectors: &[AppInfo], start: usize, @@ -5371,38 +4678,16 @@ impl CodexMessageProcessor { } } - async fn interrupt_conversation( - &mut self, + async fn turn_start( + &self, request_id: ConnectionRequestId, - params: InterruptConversationParams, + params: TurnStartParams, + app_server_client_name: Option, ) { - let InterruptConversationParams { conversation_id } = params; - let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("conversation not found: {conversation_id}"), - data: None, - }; + if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { self.outgoing.send_error(request_id, error).await; return; - }; - - let request = request_id.clone(); - - // Record the pending interrupt so we can reply when TurnAborted arrives. - { - let pending_interrupts = self.thread_state_manager.thread_state(conversation_id); - let mut thread_state = pending_interrupts.lock().await; - thread_state - .pending_interrupts - .push((request, ApiVersion::V1)); } - - // Submit the interrupt; we'll respond upon TurnAborted. - let _ = conversation.submit(Op::Interrupt).await; - } - - async fn turn_start(&self, request_id: ConnectionRequestId, params: TurnStartParams) { let (_, thread) = match self.load_thread(¶ms.thread_id).await { Ok(v) => v, Err(error) => { @@ -5410,10 +4695,19 @@ impl CodexMessageProcessor { return; } }; + if let Err(error) = + Self::set_app_server_client_name(thread.as_ref(), app_server_client_name).await + { + self.outgoing.send_error(request_id, error).await; + return; + } - let collaboration_mode = params - .collaboration_mode - .map(|mode| self.normalize_turn_start_collaboration_mode(mode)); + let collaboration_modes_config = CollaborationModesConfig { + default_mode_request_user_input: thread.enabled(Feature::DefaultModeRequestUserInput), + }; + let collaboration_mode = params.collaboration_mode.map(|mode| { + self.normalize_turn_start_collaboration_mode(mode, collaboration_modes_config) + }); // Map v2 input items to core input items. let mapped_items: Vec = params @@ -5426,6 +4720,7 @@ impl CodexMessageProcessor { || params.approval_policy.is_some() || params.sandbox_policy.is_some() || params.model.is_some() + || params.service_tier.is_some() || params.effort.is_some() || params.summary.is_some() || collaboration_mode.is_some() @@ -5442,6 +4737,7 @@ impl CodexMessageProcessor { model: params.model, effort: params.effort.map(Some), summary: params.summary, + service_tier: params.service_tier, collaboration_mode, personality: params.personality, }) @@ -5469,17 +4765,8 @@ impl CodexMessageProcessor { status: TurnStatus::InProgress, }; - let response = TurnStartResponse { turn: turn.clone() }; + let response = TurnStartResponse { turn }; self.outgoing.send_response(request_id, response).await; - - // Emit v2 turn/started notification. - let notif = TurnStartedNotification { - thread_id: params.thread_id, - turn, - }; - self.outgoing - .send_server_notification(ServerNotification::TurnStarted(notif)) - .await; } Err(err) => { let error = JSONRPCErrorError { @@ -5492,6 +4779,20 @@ impl CodexMessageProcessor { } } + async fn set_app_server_client_name( + thread: &CodexThread, + app_server_client_name: Option, + ) -> Result<(), JSONRPCErrorError> { + thread + .set_app_server_client_name(app_server_client_name) + .await + .map_err(|err| JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("failed to set app server client name: {err}"), + data: None, + }) + } + async fn turn_steer(&self, request_id: ConnectionRequestId, params: TurnSteerParams) { let (_, thread) = match self.load_thread(¶ms.thread_id).await { Ok(v) => v, @@ -5509,6 +4810,10 @@ impl CodexMessageProcessor { .await; return; } + if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { + self.outgoing.send_error(request_id, error).await; + return; + } let mapped_items: Vec = params .input @@ -5562,7 +4867,7 @@ impl CodexMessageProcessor { } }; - if let Err(error) = self + match self .ensure_conversation_listener( thread_id, request_id.connection_id, @@ -5571,8 +4876,14 @@ impl CodexMessageProcessor { ) .await { - self.outgoing.send_error(request_id, error).await; - return None; + Ok(EnsureConversationListenerResult::Attached) => {} + Ok(EnsureConversationListenerResult::ConnectionClosed) => { + return None; + } + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return None; + } } if !thread.enabled(Feature::RealtimeConversation) { @@ -5746,24 +5057,15 @@ impl CodexMessageProcessor { &self, request_id: &ConnectionRequestId, turn: Turn, - parent_thread_id: String, review_thread_id: String, ) { let response = ReviewStartResponse { - turn: turn.clone(), + turn, review_thread_id, }; self.outgoing .send_response(request_id.clone(), response) .await; - - let notif = TurnStartedNotification { - thread_id: parent_thread_id, - turn, - }; - self.outgoing - .send_server_notification(ServerNotification::TurnStarted(notif)) - .await; } async fn start_inline_review( @@ -5779,13 +5081,8 @@ impl CodexMessageProcessor { match turn_id { Ok(turn_id) => { let turn = Self::build_review_turn(turn_id, display_text); - self.emit_review_started( - request_id, - turn, - parent_thread_id.clone(), - parent_thread_id, - ) - .await; + self.emit_review_started(request_id, turn, parent_thread_id) + .await; Ok(()) } Err(err) => Err(JSONRPCErrorError { @@ -5841,21 +5138,18 @@ impl CodexMessageProcessor { data: None, })?; - if let Err(err) = self - .ensure_conversation_listener( + Self::log_listener_attach_result( + self.ensure_conversation_listener( thread_id, request_id.connection_id, false, ApiVersion::V2, ) - .await - { - tracing::warn!( - "failed to attach listener for review thread {}: {}", - thread_id, - err.message - ); - } + .await, + thread_id, + request_id.connection_id, + "review thread", + ); let fallback_provider = self.config.model_provider_id.as_str(); if let Some(rollout_path) = review_thread.rollout_path() { @@ -5863,7 +5157,7 @@ impl CodexMessageProcessor { Ok(summary) => { let mut thread = summary_to_thread(summary); self.thread_watch_manager - .upsert_thread(thread.clone()) + .upsert_thread_silently(thread.clone()) .await; thread.status = resolve_thread_status( self.thread_watch_manager @@ -5902,7 +5196,7 @@ impl CodexMessageProcessor { let turn = Self::build_review_turn(turn_id, display_text); let review_thread_id = thread_id.to_string(); - self.emit_review_started(request_id, turn, review_thread_id.clone(), review_thread_id) + self.emit_review_started(request_id, turn, review_thread_id) .await; Ok(()) @@ -5982,7 +5276,7 @@ impl CodexMessageProcessor { // Record the pending interrupt so we can reply when TurnAborted arrives. { - let thread_state = self.thread_state_manager.thread_state(thread_uuid); + let thread_state = self.thread_state_manager.thread_state(thread_uuid).await; let mut thread_state = thread_state.lock().await; thread_state .pending_interrupts @@ -5993,84 +5287,42 @@ impl CodexMessageProcessor { let _ = thread.submit(Op::Interrupt).await; } - async fn add_conversation_listener( - &mut self, - request_id: ConnectionRequestId, - params: AddConversationListenerParams, - ) { - let AddConversationListenerParams { - conversation_id, - experimental_raw_events, - } = params; - let conversation = match self.thread_manager.get_thread(conversation_id).await { - Ok(conv) => conv, - Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("thread not found: {conversation_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let subscription_id = Uuid::new_v4(); - let thread_state = self - .thread_state_manager - .set_listener( - subscription_id, - conversation_id, - request_id.connection_id, - experimental_raw_events, - ) - .await; - self.ensure_listener_task_running( - conversation_id, - conversation, - thread_state, - ApiVersion::V1, - ) - .await; - - let response = AddConversationSubscriptionResponse { subscription_id }; - self.outgoing.send_response(request_id, response).await; - } - - async fn remove_thread_listener( - &mut self, - request_id: ConnectionRequestId, - params: RemoveConversationListenerParams, - ) { - let RemoveConversationListenerParams { subscription_id } = params; - match self - .thread_state_manager - .remove_listener(subscription_id) - .await - { - Some(thread_id) => { - info!("removed listener for thread {thread_id}"); - let response = RemoveConversationSubscriptionResponse {}; - self.outgoing.send_response(request_id, response).await; - } - None => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("subscription not found: {subscription_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } - } - async fn ensure_conversation_listener( - &mut self, + &self, conversation_id: ThreadId, connection_id: ConnectionId, raw_events_enabled: bool, api_version: ApiVersion, - ) -> Result<(), JSONRPCErrorError> { - let conversation = match self.thread_manager.get_thread(conversation_id).await { + ) -> Result { + Self::ensure_conversation_listener_task( + ListenerTaskContext { + thread_manager: Arc::clone(&self.thread_manager), + thread_state_manager: self.thread_state_manager.clone(), + outgoing: Arc::clone(&self.outgoing), + thread_watch_manager: self.thread_watch_manager.clone(), + fallback_model_provider: self.config.model_provider_id.clone(), + codex_home: self.config.codex_home.clone(), + }, + conversation_id, + connection_id, + raw_events_enabled, + api_version, + ) + .await + } + + async fn ensure_conversation_listener_task( + listener_task_context: ListenerTaskContext, + conversation_id: ThreadId, + connection_id: ConnectionId, + raw_events_enabled: bool, + api_version: ApiVersion, + ) -> Result { + let conversation = match listener_task_context + .thread_manager + .get_thread(conversation_id) + .await + { Ok(conv) => conv, Err(_) => { return Err(JSONRPCErrorError { @@ -6080,13 +5332,46 @@ impl CodexMessageProcessor { }); } }; - let thread_state = self + let Some(thread_state) = listener_task_context .thread_state_manager - .ensure_connection_subscribed(conversation_id, connection_id, raw_events_enabled) - .await; - self.ensure_listener_task_running(conversation_id, conversation, thread_state, api_version) - .await; - Ok(()) + .try_ensure_connection_subscribed(conversation_id, connection_id, raw_events_enabled) + .await + else { + return Ok(EnsureConversationListenerResult::ConnectionClosed); + }; + Self::ensure_listener_task_running_task( + listener_task_context, + conversation_id, + conversation, + thread_state, + api_version, + ) + .await; + Ok(EnsureConversationListenerResult::Attached) + } + + fn log_listener_attach_result( + result: Result, + thread_id: ThreadId, + connection_id: ConnectionId, + thread_kind: &'static str, + ) { + match result { + Ok(EnsureConversationListenerResult::Attached) => {} + Ok(EnsureConversationListenerResult::ConnectionClosed) => { + tracing::debug!( + thread_id = %thread_id, + connection_id = ?connection_id, + "skipping auto-attach for closed connection" + ); + } + Err(err) => { + tracing::warn!( + "failed to attach listener for {thread_kind} {thread_id}: {message}", + message = err.message + ); + } + } } async fn ensure_listener_task_running( @@ -6095,6 +5380,30 @@ impl CodexMessageProcessor { conversation: Arc, thread_state: Arc>, api_version: ApiVersion, + ) { + Self::ensure_listener_task_running_task( + ListenerTaskContext { + thread_manager: Arc::clone(&self.thread_manager), + thread_state_manager: self.thread_state_manager.clone(), + outgoing: Arc::clone(&self.outgoing), + thread_watch_manager: self.thread_watch_manager.clone(), + fallback_model_provider: self.config.model_provider_id.clone(), + codex_home: self.config.codex_home.clone(), + }, + conversation_id, + conversation, + thread_state, + api_version, + ) + .await; + } + + async fn ensure_listener_task_running_task( + listener_task_context: ListenerTaskContext, + conversation_id: ThreadId, + conversation: Arc, + thread_state: Arc>, + api_version: ApiVersion, ) { let (cancel_tx, mut cancel_rx) = oneshot::channel(); let (mut listener_command_rx, listener_generation) = { @@ -6104,12 +5413,15 @@ impl CodexMessageProcessor { } thread_state.set_listener(cancel_tx, &conversation) }; - let outgoing_for_task = self.outgoing.clone(); - let thread_manager = self.thread_manager.clone(); - let thread_watch_manager = self.thread_watch_manager.clone(); - let fallback_model_provider = self.config.model_provider_id.clone(); - let single_client_mode = self.single_client_mode; - let codex_home = self.config.codex_home.clone(); + let ListenerTaskContext { + outgoing, + thread_manager, + thread_state_manager, + thread_watch_manager, + fallback_model_provider, + codex_home, + } = listener_task_context; + let outgoing_for_task = Arc::clone(&outgoing); tokio::spawn(async move { loop { tokio::select! { @@ -6155,16 +5467,14 @@ impl CodexMessageProcessor { "conversationId".to_string(), conversation_id.to_string().into(), ); - let (subscribed_connection_ids, raw_events_enabled) = { + let raw_events_enabled = { let mut thread_state = thread_state.lock().await; - if !single_client_mode { - thread_state.track_current_turn_event(&event.msg); - } - ( - thread_state.subscribed_connection_ids(), - thread_state.experimental_raw_events, - ) + thread_state.track_current_turn_event(&event.msg); + thread_state.experimental_raw_events }; + let subscribed_connection_ids = thread_state_manager + .subscribed_connection_ids(conversation_id) + .await; if let EventMsg::RawResponseItem(_) = &event.msg && !raw_events_enabled { continue; } @@ -6184,6 +5494,7 @@ impl CodexMessageProcessor { let thread_outgoing = ThreadScopedOutgoingMessageSender::new( outgoing_for_task.clone(), subscribed_connection_ids, + conversation_id, ); apply_bespoke_event_handling( event.clone(), @@ -6203,21 +5514,16 @@ impl CodexMessageProcessor { let Some(listener_command) = listener_command else { break; }; - match listener_command { - crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse( - resume_request, - ) => { - handle_pending_thread_resume_request( - conversation_id, - codex_home.as_path(), - &thread_state, - &thread_watch_manager, - &outgoing_for_task, - resume_request, - ) - .await; - } - } + handle_thread_listener_command( + conversation_id, + codex_home.as_path(), + &thread_state_manager, + &thread_state, + &thread_watch_manager, + &outgoing_for_task, + listener_command, + ) + .await; } } } @@ -6413,6 +5719,30 @@ impl CodexMessageProcessor { let snapshot = self.feedback.snapshot(conversation_id); let thread_id = snapshot.thread_id.clone(); + let sqlite_feedback_logs = if include_logs { + if let Some(log_db) = self.log_db.as_ref() { + log_db.flush().await; + } + let state_db_ctx = get_state_db(&self.config, None).await; + match (state_db_ctx.as_ref(), conversation_id) { + (Some(state_db_ctx), Some(conversation_id)) => { + let thread_id_text = conversation_id.to_string(); + match state_db_ctx.query_feedback_logs(&thread_id_text).await { + Ok(logs) if logs.is_empty() => None, + Ok(logs) => Some(logs), + Err(err) => { + warn!( + "failed to query feedback logs from sqlite for thread_id={thread_id_text}: {err}" + ); + None + } + } + } + _ => None, + } + } else { + None + }; let validated_rollout_path = if include_logs { match conversation_id { @@ -6436,6 +5766,7 @@ impl CodexMessageProcessor { include_logs, &attachment_paths, Some(session_source), + sqlite_feedback_logs, ) }) .await; @@ -6486,10 +5817,8 @@ impl CodexMessageProcessor { WindowsSandboxSetupMode::Unelevated => CoreWindowsSandboxSetupMode::Unelevated, }; let config = Arc::clone(&self.config); - let outgoing = ThreadScopedOutgoingMessageSender::new( - Arc::clone(&self.outgoing), - vec![request_id.connection_id], - ); + let outgoing = Arc::clone(&self.outgoing); + let connection_id = request_id.connection_id; tokio::spawn(async move { let setup_request = WindowsSandboxSetupRequest { @@ -6512,9 +5841,10 @@ impl CodexMessageProcessor { error: setup_result.err().map(|err| err.to_string()), }; outgoing - .send_server_notification(ServerNotification::WindowsSandboxSetupCompleted( - notification, - )) + .send_server_notification_to_connections( + &[connection_id], + ServerNotification::WindowsSandboxSetupCompleted(notification), + ) .await; }); } @@ -6527,9 +5857,48 @@ impl CodexMessageProcessor { } } +async fn handle_thread_listener_command( + conversation_id: ThreadId, + codex_home: &Path, + thread_state_manager: &ThreadStateManager, + thread_state: &Arc>, + thread_watch_manager: &ThreadWatchManager, + outgoing: &Arc, + listener_command: ThreadListenerCommand, +) { + match listener_command { + ThreadListenerCommand::SendThreadResumeResponse(resume_request) => { + handle_pending_thread_resume_request( + conversation_id, + codex_home, + thread_state_manager, + thread_state, + thread_watch_manager, + outgoing, + *resume_request, + ) + .await; + } + ThreadListenerCommand::ResolveServerRequest { + request_id, + completion_tx, + } => { + resolve_pending_server_request( + conversation_id, + thread_state_manager, + outgoing, + request_id, + ) + .await; + let _ = completion_tx.send(()); + } + } +} + async fn handle_pending_thread_resume_request( conversation_id: ThreadId, codex_home: &Path, + thread_state_manager: &ThreadStateManager, thread_state: &Arc>, thread_watch_manager: &ThreadWatchManager, outgoing: &Arc, @@ -6599,6 +5968,7 @@ async fn handle_pending_thread_resume_request( let ThreadConfigSnapshot { model, model_provider_id, + service_tier, approval_policy, sandbox_policy, cwd, @@ -6609,13 +5979,44 @@ async fn handle_pending_thread_resume_request( thread, model, model_provider: model_provider_id, + service_tier, cwd, approval_policy: approval_policy.into(), sandbox: sandbox_policy.into(), reasoning_effort, }; outgoing.send_response(request_id, response).await; - thread_state.lock().await.add_connection(connection_id); + outgoing + .replay_requests_to_connection_for_thread(connection_id, conversation_id) + .await; + let _attached = thread_state_manager + .try_add_connection_to_thread(conversation_id, connection_id) + .await; +} + +async fn resolve_pending_server_request( + conversation_id: ThreadId, + thread_state_manager: &ThreadStateManager, + outgoing: &Arc, + request_id: RequestId, +) { + let thread_id = conversation_id.to_string(); + let subscribed_connection_ids = thread_state_manager + .subscribed_connection_ids(conversation_id) + .await; + let outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing.clone(), + subscribed_connection_ids, + conversation_id, + ); + outgoing + .send_server_notification(ServerNotification::ServerRequestResolved( + ServerRequestResolvedNotification { + thread_id, + request_id, + }, + )) + .await; } async fn load_thread_for_running_resume_response( @@ -7305,6 +6706,7 @@ fn build_thread_from_snapshot( Thread { id: thread_id.to_string(), preview: String::new(), + ephemeral: config_snapshot.ephemeral, model_provider: config_snapshot.model_provider_id.clone(), created_at: now, updated_at: now, @@ -7346,6 +6748,7 @@ pub(crate) fn summary_to_thread(summary: ConversationSummary) -> Thread { Thread { id: conversation_id.to_string(), preview, + ephemeral: false, model_provider, created_at: created_at.map(|dt| dt.timestamp()).unwrap_or(0), updated_at: updated_at.map(|dt| dt.timestamp()).unwrap_or(0), @@ -7365,7 +6768,11 @@ pub(crate) fn summary_to_thread(summary: ConversationSummary) -> Thread { #[cfg(test)] mod tests { use super::*; + use crate::outgoing_message::OutgoingEnvelope; + use crate::outgoing_message::OutgoingMessage; use anyhow::Result; + use codex_app_server_protocol::ServerRequestPayload; + use codex_app_server_protocol::ToolRequestUserInputParams; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use pretty_assertions::assert_eq; @@ -7415,7 +6822,7 @@ mod tests { "role": "user", "content": [{ "type": "input_text", - "text": "\n\n".to_string(), + "text": "# AGENTS.md instructions for project\n\n\n\n".to_string(), }], }), json!({ @@ -7559,6 +6966,65 @@ mod tests { Ok(()) } + #[tokio::test] + async fn aborting_pending_request_clears_pending_state() -> Result<()> { + let thread_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; + let connection_id = ConnectionId(7); + + let (outgoing_tx, mut outgoing_rx) = tokio::sync::mpsc::channel(8); + let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); + let thread_outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing.clone(), + vec![connection_id], + thread_id, + ); + + let (request_id, client_request_rx) = thread_outgoing + .send_request(ServerRequestPayload::ToolRequestUserInput( + ToolRequestUserInputParams { + thread_id: thread_id.to_string(), + turn_id: "turn-1".to_string(), + item_id: "call-1".to_string(), + questions: vec![], + }, + )) + .await; + thread_outgoing.abort_pending_server_requests().await; + + let request_message = outgoing_rx.recv().await.expect("request should be sent"); + let OutgoingEnvelope::ToConnection { + connection_id: request_connection_id, + message: + OutgoingMessage::Request(ServerRequest::ToolRequestUserInput { + request_id: sent_request_id, + .. + }), + } = request_message + else { + panic!("expected tool request to be sent to the subscribed connection"); + }; + assert_eq!(request_connection_id, connection_id); + assert_eq!(sent_request_id, request_id); + + let response = client_request_rx + .await + .expect("callback should be resolved"); + let error = response.expect_err("request should be aborted during cleanup"); + assert_eq!( + error.message, + "client request resolved because the turn state was changed" + ); + assert_eq!(error.data, Some(json!({ "reason": "turnTransition" }))); + assert!( + outgoing + .pending_requests_for_thread(thread_id) + .await + .is_empty() + ); + assert!(outgoing_rx.try_recv().is_err()); + Ok(()) + } + #[test] fn summary_from_state_db_metadata_preserves_agent_nickname() -> Result<()> { let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; @@ -7594,147 +7060,20 @@ mod tests { Ok(()) } - #[tokio::test] - async fn removing_listeners_retains_thread_listener_when_last_subscriber_leaves() -> Result<()> - { - let mut manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener_a = Uuid::new_v4(); - let listener_b = Uuid::new_v4(); - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - let (cancel_tx, mut cancel_rx) = oneshot::channel(); - - manager - .set_listener(listener_a, thread_id, connection_a, false) - .await; - manager - .set_listener(listener_b, thread_id, connection_b, false) - .await; - { - let state = manager.thread_state(thread_id); - state.lock().await.cancel_tx = Some(cancel_tx); - } - - assert_eq!(manager.remove_listener(listener_a).await, Some(thread_id)); - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - assert_eq!(manager.remove_listener(listener_b).await, Some(thread_id)); - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - let state = manager.thread_state(thread_id); - assert!(state.lock().await.subscribed_connection_ids().is_empty()); - Ok(()) - } - - #[tokio::test] - async fn removing_listener_unsubscribes_its_connection() -> Result<()> { - let mut manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener_a = Uuid::new_v4(); - let listener_b = Uuid::new_v4(); - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - - manager - .set_listener(listener_a, thread_id, connection_a, false) - .await; - manager - .set_listener(listener_b, thread_id, connection_b, false) - .await; - - assert_eq!(manager.remove_listener(listener_a).await, Some(thread_id)); - let state = manager.thread_state(thread_id); - let subscribed_connection_ids = state.lock().await.subscribed_connection_ids(); - assert_eq!(subscribed_connection_ids, vec![connection_b]); - Ok(()) - } - - #[tokio::test] - async fn set_listener_uses_last_write_for_raw_events() -> Result<()> { - let mut manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener_a = Uuid::new_v4(); - let listener_b = Uuid::new_v4(); - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - - manager - .set_listener(listener_a, thread_id, connection_a, true) - .await; - { - let state = manager.thread_state(thread_id); - assert!(state.lock().await.experimental_raw_events); - } - manager - .set_listener(listener_b, thread_id, connection_b, false) - .await; - let state = manager.thread_state(thread_id); - assert!(!state.lock().await.experimental_raw_events); - Ok(()) - } - - #[tokio::test] - async fn removing_connection_retains_listener_and_active_turn_when_last_subscriber_disconnects() - -> Result<()> { - let mut manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let listener = Uuid::new_v4(); - let connection = ConnectionId(1); - let (cancel_tx, mut cancel_rx) = oneshot::channel(); - - manager - .set_listener(listener, thread_id, connection, false) - .await; - { - let state = manager.thread_state(thread_id); - let mut state = state.lock().await; - state.cancel_tx = Some(cancel_tx); - state.track_current_turn_event(&EventMsg::TurnStarted( - codex_protocol::protocol::TurnStartedEvent { - turn_id: "turn-1".to_string(), - model_context_window: None, - collaboration_mode_kind: Default::default(), - }, - )); - } - - manager.remove_connection(connection).await; - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - assert_eq!(manager.remove_listener(listener).await, None); - - let state = manager.thread_state(thread_id); - let state = state.lock().await; - assert!(state.subscribed_connection_ids().is_empty()); - assert!(state.cancel_tx.is_some()); - let active_turn = state.active_turn_snapshot().expect("active turn snapshot"); - assert_eq!(active_turn.id, "turn-1"); - assert_eq!(active_turn.status, TurnStatus::InProgress); - Ok(()) - } - #[tokio::test] async fn removing_thread_state_clears_listener_and_active_turn_history() -> Result<()> { - let mut manager = ThreadStateManager::new(); + let manager = ThreadStateManager::new(); let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; let connection = ConnectionId(1); let (cancel_tx, cancel_rx) = oneshot::channel(); + manager.connection_initialized(connection).await; manager - .ensure_connection_subscribed(thread_id, connection, false) - .await; + .try_ensure_connection_subscribed(thread_id, connection, false) + .await + .expect("connection should be live"); { - let state = manager.thread_state(thread_id); + let state = manager.thread_state(thread_id).await; let mut state = state.lock().await; state.cancel_tx = Some(cancel_tx); state.track_current_turn_event(&EventMsg::TurnStarted( @@ -7749,9 +7088,14 @@ mod tests { manager.remove_thread_state(thread_id).await; assert_eq!(cancel_rx.await, Ok(())); - let state = manager.thread_state(thread_id); + let state = manager.thread_state(thread_id).await; let state = state.lock().await; - assert!(state.subscribed_connection_ids().is_empty()); + assert!( + manager + .subscribed_connection_ids(thread_id) + .await + .is_empty() + ); assert!(state.cancel_tx.is_none()); assert!(state.active_turn_snapshot().is_none()); Ok(()) @@ -7760,20 +7104,24 @@ mod tests { #[tokio::test] async fn removing_auto_attached_connection_preserves_listener_for_other_connections() -> Result<()> { - let mut manager = ThreadStateManager::new(); + let manager = ThreadStateManager::new(); let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; let connection_a = ConnectionId(1); let connection_b = ConnectionId(2); let (cancel_tx, mut cancel_rx) = oneshot::channel(); + manager.connection_initialized(connection_a).await; + manager.connection_initialized(connection_b).await; manager - .ensure_connection_subscribed(thread_id, connection_a, false) - .await; + .try_ensure_connection_subscribed(thread_id, connection_a, false) + .await + .expect("connection_a should be live"); manager - .ensure_connection_subscribed(thread_id, connection_b, false) - .await; + .try_ensure_connection_subscribed(thread_id, connection_b, false) + .await + .expect("connection_b should be live"); { - let state = manager.thread_state(thread_id); + let state = manager.thread_state(thread_id).await; state.lock().await.cancel_tx = Some(cancel_tx); } @@ -7784,11 +7132,29 @@ mod tests { .is_err() ); - let state = manager.thread_state(thread_id); assert_eq!( - state.lock().await.subscribed_connection_ids(), + manager.subscribed_connection_ids(thread_id).await, vec![connection_b] ); Ok(()) } + + #[tokio::test] + async fn closed_connection_cannot_be_reintroduced_by_auto_subscribe() -> Result<()> { + let manager = ThreadStateManager::new(); + let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; + let connection = ConnectionId(1); + + manager.connection_initialized(connection).await; + manager.remove_connection(connection).await; + + assert!( + manager + .try_ensure_connection_subscribed(thread_id, connection, false) + .await + .is_none() + ); + assert!(!manager.has_subscribers(thread_id).await); + Ok(()) + } } diff --git a/codex-rs/app-server/src/dynamic_tools.rs b/codex-rs/app-server/src/dynamic_tools.rs index 31374d80b6..c5e7550d9f 100644 --- a/codex-rs/app-server/src/dynamic_tools.rs +++ b/codex-rs/app-server/src/dynamic_tools.rs @@ -1,3 +1,4 @@ +use codex_app_server_protocol::DynamicToolCallOutputContentItem; use codex_app_server_protocol::DynamicToolCallResponse; use codex_core::CodexThread; use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; @@ -8,6 +9,7 @@ use tokio::sync::oneshot; use tracing::error; use crate::outgoing_message::ClientRequestResult; +use crate::server_request_error::is_turn_transition_server_request_error; pub(crate) async fn on_call_response( call_id: String, @@ -15,65 +17,24 @@ pub(crate) async fn on_call_response( conversation: Arc, ) { let response = receiver.await; - let value = match response { - Ok(Ok(value)) => value, + let (response, _error) = match response { + Ok(Ok(value)) => decode_response(value), + Ok(Err(err)) if is_turn_transition_server_request_error(&err) => return, Ok(Err(err)) => { error!("request failed with client error: {err:?}"); - let fallback = CoreDynamicToolResponse { - content_items: vec![CoreDynamicToolCallOutputContentItem::InputText { - text: "dynamic tool request failed".to_string(), - }], - success: false, - }; - if let Err(err) = conversation - .submit(Op::DynamicToolResponse { - id: call_id.clone(), - response: fallback, - }) - .await - { - error!("failed to submit DynamicToolResponse: {err}"); - } - return; + fallback_response("dynamic tool request failed") } Err(err) => { error!("request failed: {err:?}"); - let fallback = CoreDynamicToolResponse { - content_items: vec![CoreDynamicToolCallOutputContentItem::InputText { - text: "dynamic tool request failed".to_string(), - }], - success: false, - }; - if let Err(err) = conversation - .submit(Op::DynamicToolResponse { - id: call_id.clone(), - response: fallback, - }) - .await - { - error!("failed to submit DynamicToolResponse: {err}"); - } - return; + fallback_response("dynamic tool request failed") } }; - let response = serde_json::from_value::(value).unwrap_or_else(|err| { - error!("failed to deserialize DynamicToolCallResponse: {err}"); - DynamicToolCallResponse { - content_items: vec![ - codex_app_server_protocol::DynamicToolCallOutputContentItem::InputText { - text: "dynamic tool response was invalid".to_string(), - }, - ], - success: false, - } - }); - let DynamicToolCallResponse { content_items, success, - } = response; - let response = CoreDynamicToolResponse { + } = response.clone(); + let core_response = CoreDynamicToolResponse { content_items: content_items .into_iter() .map(CoreDynamicToolCallOutputContentItem::from) @@ -82,11 +43,33 @@ pub(crate) async fn on_call_response( }; if let Err(err) = conversation .submit(Op::DynamicToolResponse { - id: call_id, - response, + id: call_id.clone(), + response: core_response, }) .await { error!("failed to submit DynamicToolResponse: {err}"); } } + +fn decode_response(value: serde_json::Value) -> (DynamicToolCallResponse, Option) { + match serde_json::from_value::(value) { + Ok(response) => (response, None), + Err(err) => { + error!("failed to deserialize DynamicToolCallResponse: {err}"); + fallback_response("dynamic tool response was invalid") + } + } +} + +fn fallback_response(message: &str) -> (DynamicToolCallResponse, Option) { + ( + DynamicToolCallResponse { + content_items: vec![DynamicToolCallOutputContentItem::InputText { + text: message.to_string(), + }], + success: false, + }, + Some(message.to_string()), + ) +} diff --git a/codex-rs/app-server/src/error_code.rs b/codex-rs/app-server/src/error_code.rs index ca93b2f2d3..924a7086ae 100644 --- a/codex-rs/app-server/src/error_code.rs +++ b/codex-rs/app-server/src/error_code.rs @@ -1,3 +1,5 @@ pub(crate) const INVALID_REQUEST_ERROR_CODE: i64 = -32600; +pub const INVALID_PARAMS_ERROR_CODE: i64 = -32602; pub(crate) const INTERNAL_ERROR_CODE: i64 = -32603; pub(crate) const OVERLOADED_ERROR_CODE: i64 = -32001; +pub const INPUT_TOO_LARGE_ERROR_CODE: &str = "input_too_large"; diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 206435592b..580282d5d3 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -38,20 +38,25 @@ use codex_core::ExecPolicyError; use codex_core::check_execpolicy_for_warnings; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::TextRange as CoreTextRange; +use codex_core::features::Feature; use codex_feedback::CodexFeedback; +use codex_state::log_db; use tokio::sync::mpsc; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use toml::Value as TomlValue; +use tracing::Level; use tracing::error; use tracing::info; use tracing::warn; use tracing_subscriber::EnvFilter; use tracing_subscriber::Layer; +use tracing_subscriber::filter::Targets; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::registry::Registry; use tracing_subscriber::util::SubscriberInitExt; +mod app_server_tracing; mod bespoke_event_handling; mod codex_message_processor; mod config_api; @@ -63,10 +68,13 @@ mod fuzzy_file_search; mod message_processor; mod models; mod outgoing_message; +mod server_request_error; mod thread_state; mod thread_status; mod transport; +pub use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE; +pub use crate::error_code::INVALID_PARAMS_ERROR_CODE; pub use crate::transport::AppServerTransport; const LOG_FORMAT_ENV_VAR: &str = "LOG_FORMAT"; @@ -444,7 +452,7 @@ pub async fn run_main_with_transport( let otel = codex_core::otel_init::build_provider( &config, env!("CARGO_PKG_VERSION"), - Some("codex_app_server"), + Some("codex-app-server"), default_analytics_enabled, ) .map_err(|e| { @@ -473,6 +481,21 @@ pub async fn run_main_with_transport( let feedback_layer = feedback.logger_layer(); let feedback_metadata_layer = feedback.metadata_layer(); + let log_db = if config.features.enabled(Feature::Sqlite) { + codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.model_provider_id.clone(), + None, + ) + .await + .ok() + .map(log_db::start) + } else { + None + }; + let log_db_layer = log_db + .clone() + .map(|layer| layer.with_filter(Targets::new().with_default(Level::TRACE))); let otel_logger_layer = otel.as_ref().and_then(|o| o.logger_layer()); let otel_tracing_layer = otel.as_ref().and_then(|o| o.tracing_layer()); @@ -480,6 +503,7 @@ pub async fn run_main_with_transport( .with(stderr_fmt) .with(feedback_layer) .with(feedback_metadata_layer) + .with(log_db_layer) .with(otel_logger_layer) .with(otel_tracing_layer) .try_init(); @@ -554,11 +578,11 @@ pub async fn run_main_with_transport( outgoing: outgoing_message_sender, arg0_paths, config: Arc::new(config), - single_client_mode, cli_overrides, loader_overrides, cloud_requirements: cloud_requirements.clone(), feedback: feedback.clone(), + log_db, config_warnings, }); let mut thread_created_rx = processor.thread_created_receiver(); @@ -672,6 +696,7 @@ pub async fn run_main_with_transport( .process_request( connection_id, request, + transport, &mut connection_state.session, &connection_state.outbound_initialized, ) diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 252705724d..f56e12467f 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -12,6 +12,7 @@ use crate::external_agent_config_api::ExternalAgentConfigApi; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::ConnectionRequestId; use crate::outgoing_message::OutgoingMessageSender; +use crate::transport::AppServerTransport; use async_trait::async_trait; use codex_app_server_protocol::ChatgptAuthTokensRefreshParams; use codex_app_server_protocol::ChatgptAuthTokensRefreshReason; @@ -49,15 +50,18 @@ use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; use codex_core::default_client::set_default_client_residency_requirement; use codex_core::default_client::set_default_originator; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_feedback::CodexFeedback; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; +use codex_state::log_db::LogDbLayer; use futures::FutureExt; use tokio::sync::broadcast; use tokio::sync::watch; use tokio::time::Duration; use tokio::time::timeout; use toml::Value as TomlValue; +use tracing::Instrument; const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10); @@ -87,7 +91,7 @@ impl ExternalAuthRefresher for ExternalAuthRefreshBridge { let (request_id, rx) = self .outgoing - .send_request_with_id(ServerRequestPayload::ChatgptAuthTokensRefresh(params)) + .send_request(ServerRequestPayload::ChatgptAuthTokensRefresh(params)) .await; let result = match timeout(EXTERNAL_AUTH_REFRESH_TIMEOUT, rx).await { @@ -139,17 +143,19 @@ pub(crate) struct ConnectionSessionState { pub(crate) initialized: bool, pub(crate) experimental_api_enabled: bool, pub(crate) opted_out_notification_methods: HashSet, + pub(crate) app_server_client_name: Option, + pub(crate) client_version: Option, } pub(crate) struct MessageProcessorArgs { pub(crate) outgoing: Arc, pub(crate) arg0_paths: Arg0DispatchPaths, pub(crate) config: Arc, - pub(crate) single_client_mode: bool, pub(crate) cli_overrides: Vec<(String, TomlValue)>, pub(crate) loader_overrides: LoaderOverrides, pub(crate) cloud_requirements: CloudRequirementsLoader, pub(crate) feedback: CodexFeedback, + pub(crate) log_db: Option, pub(crate) config_warnings: Vec, } @@ -161,11 +167,11 @@ impl MessageProcessor { outgoing, arg0_paths, config, - single_client_mode, cli_overrides, loader_overrides, cloud_requirements, feedback, + log_db, config_warnings, } = args; let auth_manager = AuthManager::shared( @@ -182,6 +188,11 @@ impl MessageProcessor { auth_manager.clone(), SessionSource::VSCode, config.model_catalog.clone(), + CollaborationModesConfig { + default_mode_request_user_input: config + .features + .enabled(codex_core::features::Feature::DefaultModeRequestUserInput), + }, )); let cloud_requirements = Arc::new(RwLock::new(cloud_requirements)); let codex_message_processor = CodexMessageProcessor::new(CodexMessageProcessorArgs { @@ -192,8 +203,8 @@ impl MessageProcessor { config: Arc::clone(&config), cli_overrides: cli_overrides.clone(), cloud_requirements: cloud_requirements.clone(), - single_client_mode, feedback, + log_db, }); let config_api = ConfigApi::new( config.codex_home.clone(), @@ -217,46 +228,50 @@ impl MessageProcessor { &mut self, connection_id: ConnectionId, request: JSONRPCRequest, + transport: AppServerTransport, session: &mut ConnectionSessionState, outbound_initialized: &AtomicBool, ) { - let request_method = request.method.as_str(); - tracing::trace!( - ?connection_id, - request_id = ?request.id, - "app-server request: {request_method}" - ); - let request_id = ConnectionRequestId { - connection_id, - request_id: request.id.clone(), - }; - let request_json = match serde_json::to_value(&request) { - Ok(request_json) => request_json, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("Invalid request: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let request_span = + crate::app_server_tracing::request_span(&request, transport, connection_id, session); + async { + let request_method = request.method.as_str(); + tracing::trace!( + ?connection_id, + request_id = ?request.id, + "app-server request: {request_method}" + ); + let request_id = ConnectionRequestId { + connection_id, + request_id: request.id.clone(), + }; + let request_json = match serde_json::to_value(&request) { + Ok(request_json) => request_json, + Err(err) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("Invalid request: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; - let codex_request = match serde_json::from_value::(request_json) { - Ok(codex_request) => codex_request, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("Invalid request: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let codex_request = match serde_json::from_value::(request_json) { + Ok(codex_request) => codex_request, + Err(err) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("Invalid request: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; - match codex_request { + match codex_request { // Handle Initialize internally so CodexMessageProcessor does not have to concern // itself with the `initialized` bool. ClientRequest::Initialize { request_id, params } => { @@ -297,6 +312,8 @@ impl MessageProcessor { title: _title, version, } = params.client_info; + session.app_server_client_name = Some(name.clone()); + session.client_version = Some(version.clone()); if let Err(error) = set_default_originator(name.clone()) { match error { SetOriginatorError::InvalidHeaderValue => { @@ -330,6 +347,9 @@ impl MessageProcessor { session.initialized = true; outbound_initialized.store(true, Ordering::Release); + self.codex_message_processor + .connection_initialized(connection_id) + .await; return; } } @@ -344,91 +364,97 @@ impl MessageProcessor { return; } } - } + } + if let Some(reason) = codex_request.experimental_reason() + && !session.experimental_api_enabled + { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: experimental_required_message(reason), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } - if let Some(reason) = codex_request.experimental_reason() - && !session.experimental_api_enabled - { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: experimental_required_message(reason), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - - match codex_request { - ClientRequest::ConfigRead { request_id, params } => { - self.handle_config_read( - ConnectionRequestId { - connection_id, - request_id, - }, - params, - ) - .await; - } - ClientRequest::ExternalAgentConfigDetect { request_id, params } => { - self.handle_external_agent_config_detect( - ConnectionRequestId { - connection_id, - request_id, - }, - params, - ) - .await; - } - ClientRequest::ExternalAgentConfigImport { request_id, params } => { - self.handle_external_agent_config_import( - ConnectionRequestId { - connection_id, - request_id, - }, - params, - ) - .await; - } - ClientRequest::ConfigValueWrite { request_id, params } => { - self.handle_config_value_write( - ConnectionRequestId { - connection_id, - request_id, - }, - params, - ) - .await; - } - ClientRequest::ConfigBatchWrite { request_id, params } => { - self.handle_config_batch_write( - ConnectionRequestId { - connection_id, - request_id, - }, - params, - ) - .await; - } - ClientRequest::ConfigRequirementsRead { - request_id, - params: _, - } => { - self.handle_config_requirements_read(ConnectionRequestId { - connection_id, - request_id, - }) - .await; - } - other => { - // Box the delegated future so this wrapper's async state machine does not - // inline the full `CodexMessageProcessor::process_request` future, which - // can otherwise push worker-thread stack usage over the edge. - self.codex_message_processor - .process_request(connection_id, other) - .boxed() + match codex_request { + ClientRequest::ConfigRead { request_id, params } => { + self.handle_config_read( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + ) .await; + } + ClientRequest::ExternalAgentConfigDetect { request_id, params } => { + self.handle_external_agent_config_detect( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + ) + .await; + } + ClientRequest::ExternalAgentConfigImport { request_id, params } => { + self.handle_external_agent_config_import( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + ) + .await; + } + ClientRequest::ConfigValueWrite { request_id, params } => { + self.handle_config_value_write( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + ) + .await; + } + ClientRequest::ConfigBatchWrite { request_id, params } => { + self.handle_config_batch_write( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + ) + .await; + } + ClientRequest::ConfigRequirementsRead { + request_id, + params: _, + } => { + self.handle_config_requirements_read(ConnectionRequestId { + connection_id, + request_id, + }) + .await; + } + other => { + // Box the delegated future so this wrapper's async state machine does not + // inline the full `CodexMessageProcessor::process_request` future, which + // can otherwise push worker-thread stack usage over the edge. + self.codex_message_processor + .process_request( + connection_id, + other, + session.app_server_client_name.clone(), + ) + .boxed() + .await; + } } } + .instrument(request_span) + .await; } pub(crate) async fn process_notification(&self, notification: JSONRPCNotification) { diff --git a/codex-rs/app-server/src/models.rs b/codex-rs/app-server/src/models.rs index 1594c66229..6dbe77455f 100644 --- a/codex-rs/app-server/src/models.rs +++ b/codex-rs/app-server/src/models.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use codex_app_server_protocol::Model; +use codex_app_server_protocol::ModelUpgradeInfo; use codex_app_server_protocol::ReasoningEffortOption; use codex_core::ThreadManager; use codex_core::models_manager::manager::RefreshStrategy; @@ -24,7 +25,14 @@ fn model_from_preset(preset: ModelPreset) -> Model { Model { id: preset.id.to_string(), model: preset.model.to_string(), - upgrade: preset.upgrade.map(|upgrade| upgrade.id), + upgrade: preset.upgrade.as_ref().map(|upgrade| upgrade.id.clone()), + upgrade_info: preset.upgrade.as_ref().map(|upgrade| ModelUpgradeInfo { + model: upgrade.id.clone(), + upgrade_copy: upgrade.upgrade_copy.clone(), + model_link: upgrade.model_link.clone(), + migration_markdown: upgrade.migration_markdown.clone(), + }), + availability_nux: preset.availability_nux.map(Into::into), display_name: preset.display_name.to_string(), description: preset.description.to_string(), hidden: !preset.show_in_picker, diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index fe8f755883..368d5d21a0 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -9,6 +9,7 @@ use codex_app_server_protocol::Result; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ServerRequestPayload; +use codex_protocol::ThreadId; use serde::Serialize; use tokio::sync::Mutex; use tokio::sync::mpsc; @@ -16,6 +17,7 @@ use tokio::sync::oneshot; use tracing::warn; use crate::error_code::INTERNAL_ERROR_CODE; +use crate::server_request_error::TURN_TRANSITION_PENDING_REQUEST_ERROR_REASON; #[cfg(test)] use codex_protocol::account::PlanType; @@ -48,36 +50,45 @@ pub(crate) enum OutgoingEnvelope { pub(crate) struct OutgoingMessageSender { next_server_request_id: AtomicI64, sender: mpsc::Sender, - request_id_to_callback: Mutex>>, + request_id_to_callback: Mutex>, } #[derive(Clone)] pub(crate) struct ThreadScopedOutgoingMessageSender { outgoing: Arc, connection_ids: Arc>, + thread_id: ThreadId, +} + +struct PendingCallbackEntry { + callback: oneshot::Sender, + thread_id: Option, + request: ServerRequest, } impl ThreadScopedOutgoingMessageSender { pub(crate) fn new( outgoing: Arc, connection_ids: Vec, + thread_id: ThreadId, ) -> Self { Self { outgoing, connection_ids: Arc::new(connection_ids), + thread_id, } } pub(crate) async fn send_request( &self, payload: ServerRequestPayload, - ) -> oneshot::Receiver { - if self.connection_ids.is_empty() { - let (_tx, rx) = oneshot::channel(); - return rx; - } + ) -> (RequestId, oneshot::Receiver) { self.outgoing - .send_request_to_connections(self.connection_ids.as_slice(), payload) + .send_request_to_connections( + Some(self.connection_ids.as_slice()), + payload, + Some(self.thread_id), + ) .await } @@ -90,6 +101,20 @@ impl ThreadScopedOutgoingMessageSender { .await; } + pub(crate) async fn abort_pending_server_requests(&self) { + self.outgoing + .cancel_requests_for_thread( + self.thread_id, + Some(JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: "client request resolved because the turn state was changed" + .to_string(), + data: Some(serde_json::json!({ "reason": TURN_TRANSITION_PENDING_REQUEST_ERROR_REASON })), + }), + ) + .await + } + pub(crate) async fn send_response( &self, request_id: ConnectionRequestId, @@ -116,63 +141,68 @@ impl OutgoingMessageSender { } } - pub(crate) async fn send_request_to_connections( - &self, - connection_ids: &[ConnectionId], - request: ServerRequestPayload, - ) -> oneshot::Receiver { - let (_id, rx) = self - .send_request_with_id_to_connections(connection_ids, request) - .await; - rx - } - - pub(crate) async fn send_request_with_id( + pub(crate) async fn send_request( &self, request: ServerRequestPayload, ) -> (RequestId, oneshot::Receiver) { - self.send_request_with_id_to_connections(&[], request).await + self.send_request_to_connections(None, request, None).await } - async fn send_request_with_id_to_connections( + fn next_request_id(&self) -> RequestId { + RequestId::Integer(self.next_server_request_id.fetch_add(1, Ordering::Relaxed)) + } + + async fn send_request_to_connections( &self, - connection_ids: &[ConnectionId], + connection_ids: Option<&[ConnectionId]>, request: ServerRequestPayload, + thread_id: Option, ) -> (RequestId, oneshot::Receiver) { - let id = RequestId::Integer(self.next_server_request_id.fetch_add(1, Ordering::Relaxed)); + let id = self.next_request_id(); let outgoing_message_id = id.clone(); + let request = request.request_with_id(outgoing_message_id.clone()); + let (tx_approve, rx_approve) = oneshot::channel(); { let mut request_id_to_callback = self.request_id_to_callback.lock().await; - request_id_to_callback.insert(id, tx_approve); + request_id_to_callback.insert( + id, + PendingCallbackEntry { + callback: tx_approve, + thread_id, + request: request.clone(), + }, + ); } - let outgoing_message = - OutgoingMessage::Request(request.request_with_id(outgoing_message_id.clone())); - let send_result = if connection_ids.is_empty() { - self.sender - .send(OutgoingEnvelope::Broadcast { - message: outgoing_message, - }) - .await - } else { - let mut send_error = None; - for connection_id in connection_ids { - if let Err(err) = self - .sender - .send(OutgoingEnvelope::ToConnection { - connection_id: *connection_id, - message: outgoing_message.clone(), + let outgoing_message = OutgoingMessage::Request(request); + let send_result = match connection_ids { + None => { + self.sender + .send(OutgoingEnvelope::Broadcast { + message: outgoing_message, }) .await - { - send_error = Some(err); - break; - } } - match send_error { - Some(err) => Err(err), - None => Ok(()), + Some(connection_ids) => { + let mut send_error = None; + for connection_id in connection_ids { + if let Err(err) = self + .sender + .send(OutgoingEnvelope::ToConnection { + connection_id: *connection_id, + message: outgoing_message.clone(), + }) + .await + { + send_error = Some(err); + break; + } + } + match send_error { + Some(err) => Err(err), + None => Ok(()), + } } }; @@ -184,15 +214,32 @@ impl OutgoingMessageSender { (outgoing_message_id, rx_approve) } + pub(crate) async fn replay_requests_to_connection_for_thread( + &self, + connection_id: ConnectionId, + thread_id: ThreadId, + ) { + let requests = self.pending_requests_for_thread(thread_id).await; + for request in requests { + if let Err(err) = self + .sender + .send(OutgoingEnvelope::ToConnection { + connection_id, + message: OutgoingMessage::Request(request), + }) + .await + { + warn!("failed to resend request to client: {err:?}"); + } + } + } + pub(crate) async fn notify_client_response(&self, id: RequestId, result: Result) { - let entry = { - let mut request_id_to_callback = self.request_id_to_callback.lock().await; - request_id_to_callback.remove_entry(&id) - }; + let entry = self.take_request_callback(&id).await; match entry { - Some((id, sender)) => { - if let Err(err) = sender.send(Ok(result)) { + Some((id, entry)) => { + if let Err(err) = entry.callback.send(Ok(result)) { warn!("could not notify callback for {id:?} due to: {err:?}"); } } @@ -203,15 +250,12 @@ impl OutgoingMessageSender { } pub(crate) async fn notify_client_error(&self, id: RequestId, error: JSONRPCErrorError) { - let entry = { - let mut request_id_to_callback = self.request_id_to_callback.lock().await; - request_id_to_callback.remove_entry(&id) - }; + let entry = self.take_request_callback(&id).await; match entry { - Some((id, sender)) => { + Some((id, entry)) => { warn!("client responded with error for {id:?}: {error:?}"); - if let Err(err) = sender.send(Err(error)) { + if let Err(err) = entry.callback.send(Err(error)) { warn!("could not notify callback for {id:?} due to: {err:?}"); } } @@ -222,11 +266,63 @@ impl OutgoingMessageSender { } pub(crate) async fn cancel_request(&self, id: &RequestId) -> bool { - let entry = { + self.take_request_callback(id).await.is_some() + } + + async fn take_request_callback( + &self, + id: &RequestId, + ) -> Option<(RequestId, PendingCallbackEntry)> { + let mut request_id_to_callback = self.request_id_to_callback.lock().await; + request_id_to_callback.remove_entry(id) + } + + pub(crate) async fn pending_requests_for_thread( + &self, + thread_id: ThreadId, + ) -> Vec { + let request_id_to_callback = self.request_id_to_callback.lock().await; + let mut requests = request_id_to_callback + .iter() + .filter_map(|(_, entry)| { + (entry.thread_id == Some(thread_id)).then_some(entry.request.clone()) + }) + .collect::>(); + requests.sort_by(|left, right| left.id().cmp(right.id())); + requests + } + + pub(crate) async fn cancel_requests_for_thread( + &self, + thread_id: ThreadId, + error: Option, + ) { + let entries = { let mut request_id_to_callback = self.request_id_to_callback.lock().await; - request_id_to_callback.remove_entry(id) + let request_ids = request_id_to_callback + .iter() + .filter_map(|(request_id, entry)| { + (entry.thread_id == Some(thread_id)).then_some(request_id.clone()) + }) + .collect::>(); + + let mut entries = Vec::with_capacity(request_ids.len()); + for request_id in request_ids { + if let Some(entry) = request_id_to_callback.remove(&request_id) { + entries.push(entry); + } + } + entries }; - entry.is_some() + + if let Some(error) = error { + for entry in entries { + if let Err(err) = entry.callback.send(Err(error.clone())) { + let request_id = entry.request.id(); + warn!("could not notify callback for {request_id:?} due to: {err:?}",); + } + } + } } pub(crate) async fn send_response( @@ -402,14 +498,17 @@ mod tests { use codex_app_server_protocol::ApplyPatchApprovalParams; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::ConfigWarningNotification; - use codex_app_server_protocol::LoginChatGptCompleteNotification; + use codex_app_server_protocol::DynamicToolCallParams; + use codex_app_server_protocol::FileChangeRequestApprovalParams; use codex_app_server_protocol::ModelRerouteReason; use codex_app_server_protocol::ModelReroutedNotification; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RateLimitWindow; + use codex_app_server_protocol::ToolRequestUserInputParams; use codex_protocol::ThreadId; use pretty_assertions::assert_eq; use serde_json::json; + use std::sync::Arc; use tokio::time::timeout; use uuid::Uuid; @@ -418,8 +517,8 @@ mod tests { #[test] fn verify_server_notification_serialization() { let notification = - ServerNotification::LoginChatGptComplete(LoginChatGptCompleteNotification { - login_id: Uuid::nil(), + ServerNotification::AccountLoginCompleted(AccountLoginCompletedNotification { + login_id: Some(Uuid::nil().to_string()), success: true, error: None, }); @@ -427,9 +526,9 @@ mod tests { let jsonrpc_notification = OutgoingMessage::AppServerNotification(notification); assert_eq!( json!({ - "method": "loginChatGptComplete", + "method": "account/login/completed", "params": { - "loginId": Uuid::nil(), + "loginId": Uuid::nil().to_string(), "success": true, "error": null, }, @@ -512,6 +611,7 @@ mod tests { fn verify_account_updated_notification_serialization() { let notification = ServerNotification::AccountUpdated(AccountUpdatedNotification { auth_mode: Some(AuthMode::ApiKey), + plan_type: None, }); let jsonrpc_notification = OutgoingMessage::AppServerNotification(notification); @@ -519,7 +619,8 @@ mod tests { json!({ "method": "account/updated", "params": { - "authMode": "apikey" + "authMode": "apikey", + "planType": null }, }), serde_json::to_value(jsonrpc_notification) @@ -657,7 +758,7 @@ mod tests { let outgoing = OutgoingMessageSender::new(tx); let (request_id, wait_for_result) = outgoing - .send_request_with_id(ServerRequestPayload::ApplyPatchApproval( + .send_request(ServerRequestPayload::ApplyPatchApproval( ApplyPatchApprovalParams { conversation_id: ThreadId::new(), call_id: "call-id".to_string(), @@ -684,4 +785,121 @@ mod tests { .expect("waiter should receive a callback"); assert_eq!(result, Err(error)); } + + #[tokio::test] + async fn pending_requests_for_thread_returns_thread_requests_in_request_id_order() { + let (tx, _rx) = mpsc::channel::(8); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); + let thread_id = ThreadId::new(); + let thread_outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing.clone(), + vec![ConnectionId(1)], + thread_id, + ); + + let (dynamic_tool_request_id, _dynamic_tool_waiter) = thread_outgoing + .send_request(ServerRequestPayload::DynamicToolCall( + DynamicToolCallParams { + thread_id: thread_id.to_string(), + turn_id: "turn-1".to_string(), + call_id: "call-0".to_string(), + tool: "tool".to_string(), + arguments: json!({}), + }, + )) + .await; + let (first_request_id, _first_waiter) = thread_outgoing + .send_request(ServerRequestPayload::ToolRequestUserInput( + ToolRequestUserInputParams { + thread_id: thread_id.to_string(), + turn_id: "turn-1".to_string(), + item_id: "call-1".to_string(), + questions: vec![], + }, + )) + .await; + let (second_request_id, _second_waiter) = thread_outgoing + .send_request(ServerRequestPayload::FileChangeRequestApproval( + FileChangeRequestApprovalParams { + thread_id: thread_id.to_string(), + turn_id: "turn-1".to_string(), + item_id: "call-2".to_string(), + reason: None, + grant_root: None, + }, + )) + .await; + let pending_requests = outgoing.pending_requests_for_thread(thread_id).await; + assert_eq!( + pending_requests + .iter() + .map(ServerRequest::id) + .collect::>(), + vec![ + &dynamic_tool_request_id, + &first_request_id, + &second_request_id + ] + ); + } + + #[tokio::test] + async fn cancel_requests_for_thread_cancels_all_thread_requests() { + let (tx, _rx) = mpsc::channel::(8); + let outgoing = Arc::new(OutgoingMessageSender::new(tx)); + let thread_id = ThreadId::new(); + let thread_outgoing = ThreadScopedOutgoingMessageSender::new( + outgoing.clone(), + vec![ConnectionId(1)], + thread_id, + ); + + let (_dynamic_tool_request_id, dynamic_tool_waiter) = thread_outgoing + .send_request(ServerRequestPayload::DynamicToolCall( + DynamicToolCallParams { + thread_id: thread_id.to_string(), + turn_id: "turn-1".to_string(), + call_id: "call-0".to_string(), + tool: "tool".to_string(), + arguments: json!({}), + }, + )) + .await; + let (_request_id, user_input_waiter) = thread_outgoing + .send_request(ServerRequestPayload::ToolRequestUserInput( + ToolRequestUserInputParams { + thread_id: thread_id.to_string(), + turn_id: "turn-1".to_string(), + item_id: "call-1".to_string(), + questions: vec![], + }, + )) + .await; + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: "tracked request cancelled".to_string(), + data: None, + }; + + outgoing + .cancel_requests_for_thread(thread_id, Some(error.clone())) + .await; + + let dynamic_tool_result = timeout(Duration::from_secs(1), dynamic_tool_waiter) + .await + .expect("dynamic tool waiter should resolve") + .expect("dynamic tool waiter should receive a callback"); + let user_input_result = timeout(Duration::from_secs(1), user_input_waiter) + .await + .expect("user input waiter should resolve") + .expect("user input waiter should receive a callback"); + assert_eq!(dynamic_tool_result, Err(error.clone())); + assert_eq!(user_input_result, Err(error)); + assert!( + outgoing + .pending_requests_for_thread(thread_id) + .await + .is_empty() + ); + } } diff --git a/codex-rs/app-server/src/server_request_error.rs b/codex-rs/app-server/src/server_request_error.rs new file mode 100644 index 0000000000..524b50e44b --- /dev/null +++ b/codex-rs/app-server/src/server_request_error.rs @@ -0,0 +1,42 @@ +use codex_app_server_protocol::JSONRPCErrorError; + +pub(crate) const TURN_TRANSITION_PENDING_REQUEST_ERROR_REASON: &str = "turnTransition"; + +pub(crate) fn is_turn_transition_server_request_error(error: &JSONRPCErrorError) -> bool { + error + .data + .as_ref() + .and_then(|data| data.get("reason")) + .and_then(serde_json::Value::as_str) + == Some(TURN_TRANSITION_PENDING_REQUEST_ERROR_REASON) +} + +#[cfg(test)] +mod tests { + use super::is_turn_transition_server_request_error; + use codex_app_server_protocol::JSONRPCErrorError; + use pretty_assertions::assert_eq; + use serde_json::json; + + #[test] + fn turn_transition_error_is_detected() { + let error = JSONRPCErrorError { + code: -1, + message: "client request resolved because the turn state was changed".to_string(), + data: Some(json!({ "reason": "turnTransition" })), + }; + + assert_eq!(is_turn_transition_server_request_error(&error), true); + } + + #[test] + fn unrelated_error_is_not_detected() { + let error = JSONRPCErrorError { + code: -1, + message: "boom".to_string(), + data: Some(json!({ "reason": "other" })), + }; + + assert_eq!(is_turn_transition_server_request_error(&error), false); + } +} diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 19bb025de0..915cc0fd77 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -1,5 +1,6 @@ use crate::outgoing_message::ConnectionId; use crate::outgoing_message::ConnectionRequestId; +use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError; @@ -15,7 +16,6 @@ use std::sync::Weak; use tokio::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::oneshot; -use uuid::Uuid; type PendingInterruptQueue = Vec<( ConnectionRequestId, @@ -28,8 +28,16 @@ pub(crate) struct PendingThreadResumeRequest { pub(crate) config_snapshot: ThreadConfigSnapshot, } +// ThreadListenerCommand is used to perform operations in the context of the thread listener, for serialization purposes. pub(crate) enum ThreadListenerCommand { - SendThreadResumeResponse(PendingThreadResumeRequest), + // SendThreadResumeResponse is used to resume an already running thread by sending the thread's history to the client and atomically subscribing for new updates. + SendThreadResumeResponse(Box), + // ResolveServerRequest is used to notify the client that the request has been resolved. + // It is executed in the thread listener's context to ensure that the resolved notification is ordered with regard to the request itself. + ResolveServerRequest { + request_id: RequestId, + completion_tx: oneshot::Sender<()>, + }, } /// Per-conversation accumulation of the latest states e.g. error message while a turn runs. @@ -51,7 +59,6 @@ pub(crate) struct ThreadState { listener_command_tx: Option>, current_turn_history: ThreadHistoryBuilder, listener_thread: Option>, - subscribed_connections: HashSet, } impl ThreadState { @@ -86,18 +93,6 @@ impl ThreadState { self.listener_thread = None; } - pub(crate) fn add_connection(&mut self, connection_id: ConnectionId) { - self.subscribed_connections.insert(connection_id); - } - - pub(crate) fn remove_connection(&mut self, connection_id: ConnectionId) { - self.subscribed_connections.remove(&connection_id); - } - - pub(crate) fn subscribed_connection_ids(&self) -> Vec { - self.subscribed_connections.iter().copied().collect() - } - pub(crate) fn set_experimental_raw_events(&mut self, enabled: bool) { self.experimental_raw_events = enabled; } @@ -120,75 +115,74 @@ impl ThreadState { } } -#[derive(Clone, Copy)] -struct SubscriptionState { - thread_id: ThreadId, - connection_id: ConnectionId, +struct ThreadEntry { + state: Arc>, + connection_ids: HashSet, +} + +impl Default for ThreadEntry { + fn default() -> Self { + Self { + state: Arc::new(Mutex::new(ThreadState::default())), + connection_ids: HashSet::new(), + } + } } #[derive(Default)] -pub(crate) struct ThreadStateManager { - thread_states: HashMap>>, - subscription_state_by_id: HashMap, +struct ThreadStateManagerInner { + live_connections: HashSet, + threads: HashMap, thread_ids_by_connection: HashMap>, } +#[derive(Clone, Default)] +pub(crate) struct ThreadStateManager { + state: Arc>, +} + impl ThreadStateManager { pub(crate) fn new() -> Self { Self::default() } - pub(crate) fn thread_state(&mut self, thread_id: ThreadId) -> Arc> { - self.thread_states - .entry(thread_id) - .or_insert_with(|| Arc::new(Mutex::new(ThreadState::default()))) - .clone() + pub(crate) async fn connection_initialized(&self, connection_id: ConnectionId) { + self.state + .lock() + .await + .live_connections + .insert(connection_id); } - pub(crate) async fn remove_listener(&mut self, subscription_id: Uuid) -> Option { - let subscription_state = self.subscription_state_by_id.remove(&subscription_id)?; - let thread_id = subscription_state.thread_id; + pub(crate) async fn subscribed_connection_ids(&self, thread_id: ThreadId) -> Vec { + let state = self.state.lock().await; + state + .threads + .get(&thread_id) + .map(|thread_entry| thread_entry.connection_ids.iter().copied().collect()) + .unwrap_or_default() + } - let connection_still_subscribed_to_thread = - self.subscription_state_by_id.values().any(|state| { - state.thread_id == thread_id - && state.connection_id == subscription_state.connection_id - }); - if !connection_still_subscribed_to_thread { - let mut remove_connection_entry = false; - if let Some(thread_ids) = self - .thread_ids_by_connection - .get_mut(&subscription_state.connection_id) - { + pub(crate) async fn thread_state(&self, thread_id: ThreadId) -> Arc> { + let mut state = self.state.lock().await; + state.threads.entry(thread_id).or_default().state.clone() + } + + pub(crate) async fn remove_thread_state(&self, thread_id: ThreadId) { + let thread_state = { + let mut state = self.state.lock().await; + let thread_state = state + .threads + .remove(&thread_id) + .map(|thread_entry| thread_entry.state); + state.thread_ids_by_connection.retain(|_, thread_ids| { thread_ids.remove(&thread_id); - remove_connection_entry = thread_ids.is_empty(); - } - if remove_connection_entry { - self.thread_ids_by_connection - .remove(&subscription_state.connection_id); - } - } + !thread_ids.is_empty() + }); + thread_state + }; - if let Some(thread_state) = self.thread_states.get(&thread_id) { - let mut thread_state = thread_state.lock().await; - if !connection_still_subscribed_to_thread { - thread_state.remove_connection(subscription_state.connection_id); - } - if thread_state.subscribed_connection_ids().is_empty() { - tracing::debug!( - thread_id = %thread_id, - subscription_id = %subscription_id, - connection_id = ?subscription_state.connection_id, - listener_generation = thread_state.listener_generation, - "retaining thread listener after last subscription removed" - ); - } - } - Some(thread_id) - } - - pub(crate) async fn remove_thread_state(&mut self, thread_id: ThreadId) { - if let Some(thread_state) = self.thread_states.remove(&thread_id) { + if let Some(thread_state) = thread_state { let mut thread_state = thread_state.lock().await; tracing::debug!( thread_id = %thread_id, @@ -199,98 +193,147 @@ impl ThreadStateManager { ); thread_state.clear_listener(); } - self.subscription_state_by_id - .retain(|_, state| state.thread_id != thread_id); - self.thread_ids_by_connection.retain(|_, thread_ids| { - thread_ids.remove(&thread_id); - !thread_ids.is_empty() - }); } - pub(crate) async fn set_listener( - &mut self, - subscription_id: Uuid, + pub(crate) async fn unsubscribe_connection_from_thread( + &self, + thread_id: ThreadId, + connection_id: ConnectionId, + ) -> bool { + { + let mut state = self.state.lock().await; + if !state.threads.contains_key(&thread_id) { + return false; + } + + if !state + .thread_ids_by_connection + .get(&connection_id) + .is_some_and(|thread_ids| thread_ids.contains(&thread_id)) + { + return false; + } + + if let Some(thread_ids) = state.thread_ids_by_connection.get_mut(&connection_id) { + thread_ids.remove(&thread_id); + if thread_ids.is_empty() { + state.thread_ids_by_connection.remove(&connection_id); + } + } + if let Some(thread_entry) = state.threads.get_mut(&thread_id) { + thread_entry.connection_ids.remove(&connection_id); + } + }; + + true + } + + pub(crate) async fn has_subscribers(&self, thread_id: ThreadId) -> bool { + self.state + .lock() + .await + .threads + .get(&thread_id) + .is_some_and(|thread_entry| !thread_entry.connection_ids.is_empty()) + } + + pub(crate) async fn try_ensure_connection_subscribed( + &self, thread_id: ThreadId, connection_id: ConnectionId, experimental_raw_events: bool, - ) -> Arc> { - self.subscription_state_by_id.insert( - subscription_id, - SubscriptionState { - thread_id, - connection_id, - }, - ); - self.thread_ids_by_connection - .entry(connection_id) - .or_default() - .insert(thread_id); - let thread_state = self.thread_state(thread_id); + ) -> Option>> { + let thread_state = { + let mut state = self.state.lock().await; + if !state.live_connections.contains(&connection_id) { + return None; + } + state + .thread_ids_by_connection + .entry(connection_id) + .or_default() + .insert(thread_id); + let thread_entry = state.threads.entry(thread_id).or_default(); + thread_entry.connection_ids.insert(connection_id); + thread_entry.state.clone() + }; { let mut thread_state_guard = thread_state.lock().await; - thread_state_guard.add_connection(connection_id); - thread_state_guard.set_experimental_raw_events(experimental_raw_events); - } - thread_state - } - - pub(crate) async fn ensure_connection_subscribed( - &mut self, - thread_id: ThreadId, - connection_id: ConnectionId, - experimental_raw_events: bool, - ) -> Arc> { - self.thread_ids_by_connection - .entry(connection_id) - .or_default() - .insert(thread_id); - let thread_state = self.thread_state(thread_id); - { - let mut thread_state_guard = thread_state.lock().await; - thread_state_guard.add_connection(connection_id); if experimental_raw_events { thread_state_guard.set_experimental_raw_events(true); } } - thread_state + Some(thread_state) } - pub(crate) async fn remove_connection(&mut self, connection_id: ConnectionId) { - let thread_ids = self - .thread_ids_by_connection - .remove(&connection_id) - .unwrap_or_default(); - self.subscription_state_by_id - .retain(|_, state| state.connection_id != connection_id); - - if thread_ids.is_empty() { - for thread_state in self.thread_states.values() { - let mut thread_state = thread_state.lock().await; - thread_state.remove_connection(connection_id); - if thread_state.subscribed_connection_ids().is_empty() { - tracing::debug!( - connection_id = ?connection_id, - listener_generation = thread_state.listener_generation, - "retaining thread listener after connection disconnect left zero subscribers" - ); - } - } - return; + pub(crate) async fn try_add_connection_to_thread( + &self, + thread_id: ThreadId, + connection_id: ConnectionId, + ) -> bool { + let mut state = self.state.lock().await; + if !state.live_connections.contains(&connection_id) { + return false; } + state + .thread_ids_by_connection + .entry(connection_id) + .or_default() + .insert(thread_id); + state + .threads + .entry(thread_id) + .or_default() + .connection_ids + .insert(connection_id); + true + } - for thread_id in thread_ids { - if let Some(thread_state) = self.thread_states.get(&thread_id) { - let mut thread_state = thread_state.lock().await; - thread_state.remove_connection(connection_id); - if thread_state.subscribed_connection_ids().is_empty() { - tracing::debug!( - thread_id = %thread_id, - connection_id = ?connection_id, - listener_generation = thread_state.listener_generation, - "retaining thread listener after connection disconnect left zero subscribers" - ); + pub(crate) async fn remove_connection(&self, connection_id: ConnectionId) { + let thread_states = { + let mut state = self.state.lock().await; + state.live_connections.remove(&connection_id); + let thread_ids = state + .thread_ids_by_connection + .remove(&connection_id) + .unwrap_or_default(); + for thread_id in &thread_ids { + if let Some(thread_entry) = state.threads.get_mut(thread_id) { + thread_entry.connection_ids.remove(&connection_id); } } + thread_ids + .into_iter() + .map(|thread_id| { + ( + thread_id, + state + .threads + .get(&thread_id) + .is_none_or(|thread_entry| thread_entry.connection_ids.is_empty()), + state + .threads + .get(&thread_id) + .map(|thread_entry| thread_entry.state.clone()), + ) + }) + .collect::>() + }; + + for (thread_id, no_subscribers, thread_state) in thread_states { + if !no_subscribers { + continue; + } + let Some(thread_state) = thread_state else { + continue; + }; + let listener_generation = thread_state.lock().await.listener_generation; + tracing::debug!( + thread_id = %thread_id, + connection_id = ?connection_id, + listener_generation, + "retaining thread listener after connection disconnect left zero subscribers" + ); } } } diff --git a/codex-rs/app-server/src/thread_status.rs b/codex-rs/app-server/src/thread_status.rs index 2eb1d8d036..d366089a7c 100644 --- a/codex-rs/app-server/src/thread_status.rs +++ b/codex-rs/app-server/src/thread_status.rs @@ -91,7 +91,12 @@ impl ThreadWatchManager { } pub(crate) async fn upsert_thread(&self, thread: Thread) { - self.mutate_and_publish(move |state| state.upsert_thread(thread.id)) + self.mutate_and_publish(move |state| state.upsert_thread(thread.id, true)) + .await; + } + + pub(crate) async fn upsert_thread_silently(&self, thread: Thread) { + self.mutate_and_publish(move |state| state.upsert_thread(thread.id, false)) .await; } @@ -289,19 +294,35 @@ struct ThreadWatchState { } impl ThreadWatchState { - fn upsert_thread(&mut self, thread_id: String) -> Option { + fn upsert_thread( + &mut self, + thread_id: String, + emit_notification: bool, + ) -> Option { let previous_status = self.status_for(&thread_id); let runtime = self .runtime_by_thread_id .entry(thread_id.clone()) .or_default(); runtime.is_loaded = true; - self.status_changed_notification(thread_id, previous_status) + if emit_notification { + self.status_changed_notification(thread_id, previous_status) + } else { + None + } } fn remove_thread(&mut self, thread_id: &str) -> Option { + let previous_status = self.status_for(thread_id); self.runtime_by_thread_id.remove(thread_id); - None + if previous_status.is_some() && previous_status != Some(ThreadStatus::NotLoaded) { + Some(ThreadStatusChangedNotification { + thread_id: thread_id.to_string(), + status: ThreadStatus::NotLoaded, + }) + } else { + None + } } fn update_runtime( @@ -673,6 +694,54 @@ mod tests { }, }, ); + + manager.remove_thread(INTERACTIVE_THREAD_ID).await; + assert_eq!( + recv_status_changed_notification(&mut outgoing_rx).await, + ThreadStatusChangedNotification { + thread_id: INTERACTIVE_THREAD_ID.to_string(), + status: ThreadStatus::NotLoaded, + }, + ); + } + + #[tokio::test] + async fn silent_upsert_skips_initial_notification() { + let (outgoing_tx, mut outgoing_rx) = mpsc::channel(8); + let manager = ThreadWatchManager::new_with_outgoing(Arc::new(OutgoingMessageSender::new( + outgoing_tx, + ))); + + manager + .upsert_thread_silently(test_thread( + INTERACTIVE_THREAD_ID, + codex_app_server_protocol::SessionSource::Cli, + )) + .await; + + assert_eq!( + manager + .loaded_status_for_thread(INTERACTIVE_THREAD_ID) + .await, + ThreadStatus::Idle, + ); + assert!( + timeout(Duration::from_millis(100), outgoing_rx.recv()) + .await + .is_err(), + "silent upsert should not emit thread/status/changed" + ); + + manager.note_turn_started(INTERACTIVE_THREAD_ID).await; + assert_eq!( + recv_status_changed_notification(&mut outgoing_rx).await, + ThreadStatusChangedNotification { + thread_id: INTERACTIVE_THREAD_ID.to_string(), + status: ThreadStatus::Active { + active_flags: vec![], + }, + }, + ); } async fn wait_for_status( @@ -716,6 +785,7 @@ mod tests { Thread { id: thread_id.to_string(), preview: String::new(), + ephemeral: false, model_provider: "mock-provider".to_string(), created_at: 0, updated_at: 0, diff --git a/codex-rs/app-server/src/transport.rs b/codex-rs/app-server/src/transport.rs index 8c36df9822..019d00e45e 100644 --- a/codex-rs/app-server/src/transport.rs +++ b/codex-rs/app-server/src/transport.rs @@ -671,12 +671,17 @@ pub(crate) async fn route_outgoing_envelope( mod tests { use super::*; use crate::error_code::OVERLOADED_ERROR_CODE; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use serde_json::json; use std::path::PathBuf; use tokio::time::Duration; use tokio::time::timeout; + fn absolute_path(path: &str) -> AbsolutePathBuf { + AbsolutePathBuf::from_absolute_path(path).expect("absolute path") + } + #[test] fn app_server_transport_parses_stdio_listen_url() { let transport = AppServerTransport::from_listen_url(AppServerTransport::DEFAULT_LISTEN_URL) @@ -739,6 +744,7 @@ mod tests { id: codex_app_server_protocol::RequestId::Integer(7), method: "config/read".to_string(), params: Some(json!({ "includeLayers": false })), + trace: None, }); assert!( enqueue_incoming_message(&transport_event_tx, &writer_tx, connection_id, request).await @@ -880,6 +886,7 @@ mod tests { id: codex_app_server_protocol::RequestId::Integer(7), method: "config/read".to_string(), params: Some(json!({ "includeLayers": false })), + trace: None, }); let enqueue_result = tokio::time::timeout( @@ -977,7 +984,7 @@ mod tests { network: None, file_system: Some( codex_app_server_protocol::AdditionalFileSystemPermissions { - read: Some(vec![PathBuf::from("/tmp/allowed")]), + read: Some(vec![absolute_path("/tmp/allowed")]), write: None, }, ), @@ -986,6 +993,7 @@ mod tests { ), proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, + available_decisions: None, }, }), }, @@ -1038,7 +1046,7 @@ mod tests { network: None, file_system: Some( codex_app_server_protocol::AdditionalFileSystemPermissions { - read: Some(vec![PathBuf::from("/tmp/allowed")]), + read: Some(vec![absolute_path("/tmp/allowed")]), write: None, }, ), @@ -1047,6 +1055,7 @@ mod tests { ), proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, + available_decisions: None, }, }), }, @@ -1058,12 +1067,13 @@ mod tests { .await .expect("request should be delivered to the connection"); let json = serde_json::to_value(message).expect("request should serialize"); + let allowed_path = absolute_path("/tmp/allowed").to_string_lossy().into_owned(); assert_eq!( json["params"]["additionalPermissions"], json!({ "network": null, "fileSystem": { - "read": ["/tmp/allowed"], + "read": [allowed_path], "write": null, }, "macos": null, diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index f1917add85..4b525878b8 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -11,11 +11,8 @@ use tokio::process::ChildStdin; use tokio::process::ChildStdout; use anyhow::Context; -use codex_app_server_protocol::AddConversationListenerParams; use codex_app_server_protocol::AppsListParams; -use codex_app_server_protocol::ArchiveConversationParams; use codex_app_server_protocol::CancelLoginAccountParams; -use codex_app_server_protocol::CancelLoginChatGptParams; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientNotification; use codex_app_server_protocol::CollaborationModeListParams; @@ -24,32 +21,23 @@ use codex_app_server_protocol::ConfigReadParams; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::ExperimentalFeatureListParams; use codex_app_server_protocol::FeedbackUploadParams; -use codex_app_server_protocol::ForkConversationParams; use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAuthStatusParams; +use codex_app_server_protocol::GetConversationSummaryParams; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::InterruptConversationParams; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCErrorError; 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::ListConversationsParams; use codex_app_server_protocol::LoginAccountParams; -use codex_app_server_protocol::LoginApiKeyParams; use codex_app_server_protocol::MockExperimentalMethodParams; use codex_app_server_protocol::ModelListParams; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::RemoveConversationListenerParams; use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; use codex_app_server_protocol::ReviewStartParams; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserTurnParams; use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::SetDefaultModelParams; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::ThreadArchiveParams; use codex_app_server_protocol::ThreadCompactStartParams; @@ -66,6 +54,7 @@ use codex_app_server_protocol::ThreadRollbackParams; use codex_app_server_protocol::ThreadSetNameParams; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadUnarchiveParams; +use codex_app_server_protocol::ThreadUnsubscribeParams; use codex_app_server_protocol::TurnCompletedNotification; use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnStartParams; @@ -242,71 +231,6 @@ impl McpProcess { } } - /// Send a `newConversation` JSON-RPC request. - pub async fn send_new_conversation_request( - &mut self, - params: NewConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("newConversation", params).await - } - - /// Send an `archiveConversation` JSON-RPC request. - pub async fn send_archive_conversation_request( - &mut self, - params: ArchiveConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("archiveConversation", params).await - } - - /// Send an `addConversationListener` JSON-RPC request. - pub async fn send_add_conversation_listener_request( - &mut self, - params: AddConversationListenerParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("addConversationListener", params).await - } - - /// Send a `sendUserMessage` JSON-RPC request with a single text item. - pub async fn send_send_user_message_request( - &mut self, - params: SendUserMessageParams, - ) -> anyhow::Result { - // Wire format expects variants in camelCase; text item uses external tagging. - let params = Some(serde_json::to_value(params)?); - self.send_request("sendUserMessage", params).await - } - - /// Send a `removeConversationListener` JSON-RPC request. - pub async fn send_remove_thread_listener_request( - &mut self, - params: RemoveConversationListenerParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("removeConversationListener", params) - .await - } - - /// Send a `sendUserTurn` JSON-RPC request. - pub async fn send_send_user_turn_request( - &mut self, - params: SendUserTurnParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("sendUserTurn", params).await - } - - /// Send a `interruptConversation` JSON-RPC request. - pub async fn send_interrupt_conversation_request( - &mut self, - params: InterruptConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("interruptConversation", params).await - } - /// Send a `getAuthStatus` JSON-RPC request. pub async fn send_get_auth_status_request( &mut self, @@ -316,14 +240,13 @@ impl McpProcess { self.send_request("getAuthStatus", params).await } - /// Send a `getUserSavedConfig` JSON-RPC request. - pub async fn send_get_user_saved_config_request(&mut self) -> anyhow::Result { - self.send_request("getUserSavedConfig", None).await - } - - /// Send a `getUserAgent` JSON-RPC request. - pub async fn send_get_user_agent_request(&mut self) -> anyhow::Result { - self.send_request("getUserAgent", None).await + /// Send a `getConversationSummary` JSON-RPC request. + pub async fn send_get_conversation_summary_request( + &mut self, + params: GetConversationSummaryParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("getConversationSummary", params).await } /// Send an `account/rateLimits/read` JSON-RPC request. @@ -365,29 +288,6 @@ impl McpProcess { self.send_request("feedback/upload", params).await } - /// Send a `userInfo` JSON-RPC request. - pub async fn send_user_info_request(&mut self) -> anyhow::Result { - self.send_request("userInfo", None).await - } - - /// Send a `setDefaultModel` JSON-RPC request. - pub async fn send_set_default_model_request( - &mut self, - params: SetDefaultModelParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("setDefaultModel", params).await - } - - /// Send a `listConversations` JSON-RPC request. - pub async fn send_list_conversations_request( - &mut self, - params: ListConversationsParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("listConversations", params).await - } - /// Send a `thread/start` JSON-RPC request. pub async fn send_thread_start_request( &mut self, @@ -433,6 +333,15 @@ impl McpProcess { self.send_request("thread/name/set", params).await } + /// Send a `thread/unsubscribe` JSON-RPC request. + pub async fn send_thread_unsubscribe_request( + &mut self, + params: ThreadUnsubscribeParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("thread/unsubscribe", params).await + } + /// Send a `thread/unarchive` JSON-RPC request. pub async fn send_thread_unarchive_request( &mut self, @@ -538,38 +447,6 @@ impl McpProcess { self.send_request("mock/experimentalMethod", params).await } - /// Send a `resumeConversation` JSON-RPC request. - pub async fn send_resume_conversation_request( - &mut self, - params: ResumeConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("resumeConversation", params).await - } - - /// Send a `forkConversation` JSON-RPC request. - pub async fn send_fork_conversation_request( - &mut self, - params: ForkConversationParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("forkConversation", params).await - } - - /// Send a `loginApiKey` JSON-RPC request. - pub async fn send_login_api_key_request( - &mut self, - params: LoginApiKeyParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("loginApiKey", params).await - } - - /// Send a `loginChatGpt` JSON-RPC request. - pub async fn send_login_chat_gpt_request(&mut self) -> anyhow::Result { - self.send_request("loginChatGpt", None).await - } - /// Send a `turn/start` JSON-RPC request (v2). pub async fn send_turn_start_request( &mut self, @@ -709,20 +586,6 @@ impl McpProcess { self.send_request("windowsSandbox/setupStart", params).await } - /// Send a `cancelLoginChatGpt` JSON-RPC request. - pub async fn send_cancel_login_chat_gpt_request( - &mut self, - params: CancelLoginChatGptParams, - ) -> anyhow::Result { - let params = Some(serde_json::to_value(params)?); - self.send_request("cancelLoginChatGpt", params).await - } - - /// Send a `logoutChatGpt` JSON-RPC request. - pub async fn send_logout_chat_gpt_request(&mut self) -> anyhow::Result { - self.send_request("logoutChatGpt", None).await - } - pub async fn send_config_read_request( &mut self, params: ConfigReadParams, @@ -881,6 +744,7 @@ impl McpProcess { id: RequestId::Integer(request_id), method: method.to_string(), params, + trace: None, }); self.send_jsonrpc_message(message).await?; Ok(request_id) diff --git a/codex-rs/app-server/tests/common/models_cache.rs b/codex-rs/app-server/tests/common/models_cache.rs index 218a1d0e40..0de8fda5f2 100644 --- a/codex-rs/app-server/tests/common/models_cache.rs +++ b/codex-rs/app-server/tests/common/models_cache.rs @@ -1,6 +1,7 @@ use chrono::DateTime; use chrono::Utc; use codex_core::test_support::all_model_presets; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelPreset; @@ -30,8 +31,10 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo { base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, diff --git a/codex-rs/app-server/tests/common/rollout.rs b/codex-rs/app-server/tests/common/rollout.rs index 8122e7cd01..8146f7ae93 100644 --- a/codex-rs/app-server/tests/common/rollout.rs +++ b/codex-rs/app-server/tests/common/rollout.rs @@ -84,6 +84,7 @@ pub fn create_fake_rollout_with_source( model_provider: model_provider.map(str::to_string), base_instructions: None, dynamic_tools: None, + memory_mode: None, }; let payload = serde_json::to_value(SessionMetaLine { meta, @@ -165,6 +166,7 @@ pub fn create_fake_rollout_with_text_elements( model_provider: model_provider.map(str::to_string), base_instructions: None, dynamic_tools: None, + memory_mode: None, }; let payload = serde_json::to_value(SessionMetaLine { meta, diff --git a/codex-rs/app-server/tests/suite/archive_thread.rs b/codex-rs/app-server/tests/suite/archive_thread.rs deleted file mode 100644 index a47b247bfd..0000000000 --- a/codex-rs/app-server/tests/suite/archive_thread.rs +++ /dev/null @@ -1,154 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_mock_responses_server_repeating_assistant; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::ArchiveConversationParams; -use codex_app_server_protocol::ArchiveConversationResponse; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_core::ARCHIVED_SESSIONS_SUBDIR; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn archive_conversation_moves_rollout_into_archived_directory() -> 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 mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_request_id = mcp - .send_new_conversation_request(NewConversationParams { - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - let new_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_request_id)), - ) - .await??; - - let NewConversationResponse { - conversation_id, - rollout_path, - .. - } = to_response::(new_response)?; - - assert!( - !rollout_path.exists(), - "expected rollout path {} to be deferred until first user message", - rollout_path.display() - ); - - let add_listener_request_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_request_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::(add_listener_response)?; - - let send_request_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: "materialize".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_request_id)), - ) - .await??; - let _: SendUserMessageResponse = to_response::(send_response)?; - let _: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - assert!( - rollout_path.exists(), - "expected rollout path {} to exist after first user message", - rollout_path.display() - ); - - let archive_request_id = mcp - .send_archive_conversation_request(ArchiveConversationParams { - conversation_id, - rollout_path: rollout_path.clone(), - }) - .await?; - let archive_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(archive_request_id)), - ) - .await??; - - let _: ArchiveConversationResponse = - to_response::(archive_response)?; - - let archived_directory = codex_home.path().join(ARCHIVED_SESSIONS_SUBDIR); - let archived_rollout_path = - archived_directory.join(rollout_path.file_name().unwrap_or_else(|| { - panic!("rollout path {} missing file name", rollout_path.display()) - })); - - assert!( - !rollout_path.exists(), - "expected rollout path {} to be moved", - rollout_path.display() - ); - assert!( - archived_rollout_path.exists(), - "expected archived rollout path {} to exist", - archived_rollout_path.display() - ); - - Ok(()) -} - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write(config_toml, config_contents(server_uri)) -} - -fn config_contents(server_uri: &str) -> String { - format!( - r#"model = "mock-model" -approval_policy = "never" -sandbox_mode = "read-only" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ) -} diff --git a/codex-rs/app-server/tests/suite/auth.rs b/codex-rs/app-server/tests/suite/auth.rs index 4693158611..2bbdeff400 100644 --- a/codex-rs/app-server/tests/suite/auth.rs +++ b/codex-rs/app-server/tests/suite/auth.rs @@ -6,8 +6,7 @@ use codex_app_server_protocol::GetAuthStatusParams; use codex_app_server_protocol::GetAuthStatusResponse; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginApiKeyParams; -use codex_app_server_protocol::LoginApiKeyResponse; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::RequestId; use pretty_assertions::assert_eq; use std::path::Path; @@ -72,18 +71,15 @@ forced_login_method = "{forced_method}" } async fn login_with_api_key_via_request(mcp: &mut McpProcess, api_key: &str) -> Result<()> { - let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: api_key.to_string(), - }) - .await?; + let request_id = mcp.send_login_account_api_key_request(api_key).await?; let resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; - let _: LoginApiKeyResponse = to_response(resp)?; + let response: LoginAccountResponse = to_response(resp)?; + assert_eq!(response, LoginAccountResponse::ApiKey {}); Ok(()) } @@ -211,9 +207,7 @@ async fn login_api_key_rejected_when_forced_chatgpt() -> Result<()> { timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: "sk-test-key".to_string(), - }) + .send_login_account_api_key_request("sk-test-key") .await?; let err: JSONRPCError = timeout( diff --git a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs deleted file mode 100644 index f6d3b9efb9..0000000000 --- a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs +++ /dev/null @@ -1,547 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::create_mock_responses_server_sequence; -use app_test_support::create_shell_command_sse_response; -use app_test_support::format_with_current_shell; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::ExecCommandApprovalParams; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RemoveConversationListenerParams; -use codex_app_server_protocol::RemoveConversationSubscriptionResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_app_server_protocol::SendUserTurnParams; -use codex_app_server_protocol::SendUserTurnResponse; -use codex_app_server_protocol::ServerRequest; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::SandboxMode; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::parse_command::ParsedCommand; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::Event; -use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::SandboxPolicy; -use pretty_assertions::assert_eq; -use std::env; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn test_codex_jsonrpc_conversation_flow() -> Result<()> { - if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } - - let tmp = TempDir::new()?; - // Temporary Codex home with config pointing at the mock server. - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let working_directory = tmp.path().join("workdir"); - std::fs::create_dir(&working_directory)?; - - // Create a mock model server that immediately ends each turn. - // Two turns are expected: initial session configure + one user message. - let responses = vec![ - create_shell_command_sse_response( - vec!["ls".to_string()], - Some(&working_directory), - Some(5000), - "call1234", - )?, - create_final_assistant_message_sse_response("Enjoy your new git repo!")?, - ]; - let server = create_mock_responses_server_sequence(responses).await; - create_config_toml(&codex_home, &server.uri())?; - - // Start MCP server and initialize. - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // 1) newConversation - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(working_directory.to_string_lossy().into_owned()), - sandbox: Some(SandboxMode::DangerFullAccess), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let new_conv_resp = to_response::(new_conv_resp)?; - let NewConversationResponse { - conversation_id, - model, - reasoning_effort: _, - rollout_path: _, - } = new_conv_resp; - assert_eq!(model, "mock-model"); - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id } = - to_response::(add_listener_resp)?; - - // Drop any buffered events from conversation setup to avoid - // matching an earlier task_complete. - mcp.clear_message_buffer(); - - // 3) sendUserMessage (should trigger notifications; we only validate an OK response) - let send_user_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "text".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_user_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), - ) - .await??; - let SendUserMessageResponse {} = to_response::(send_user_resp)?; - - let task_started_notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_started"), - ) - .await??; - let task_started_event: Event = serde_json::from_value( - task_started_notification - .params - .clone() - .expect("task_started should have params"), - ) - .expect("task_started should deserialize to Event"); - - // Verify the task_finished notification for this turn is received. - // Note this also ensures that the final request to the server was made. - let task_finished_notification: JSONRPCNotification = loop { - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - let event: Event = serde_json::from_value( - notification - .params - .clone() - .expect("task_complete should have params"), - ) - .expect("task_complete should deserialize to Event"); - if event.id == task_started_event.id { - break notification; - } - }; - let serde_json::Value::Object(map) = task_finished_notification - .params - .expect("notification should have params") - else { - panic!("task_finished_notification should have params"); - }; - assert_eq!( - map.get("conversationId") - .expect("should have conversationId"), - &serde_json::Value::String(conversation_id.to_string()) - ); - - // 4) removeConversationListener - let remove_listener_id = mcp - .send_remove_thread_listener_request(RemoveConversationListenerParams { subscription_id }) - .await?; - let remove_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(remove_listener_id)), - ) - .await??; - let RemoveConversationSubscriptionResponse {} = to_response(remove_listener_resp)?; - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn test_send_user_turn_changes_approval_policy_behavior() -> Result<()> { - if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } - - let tmp = TempDir::new()?; - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let working_directory = tmp.path().join("workdir"); - std::fs::create_dir(&working_directory)?; - - // Mock server will request a python shell call for the first and second turn, then finish. - let responses = vec![ - create_shell_command_sse_response( - vec![ - "python3".to_string(), - "-c".to_string(), - "print(42)".to_string(), - ], - Some(&working_directory), - Some(5000), - "call1", - )?, - create_final_assistant_message_sse_response("done 1")?, - create_shell_command_sse_response( - vec![ - "python3".to_string(), - "-c".to_string(), - "print(42)".to_string(), - ], - Some(&working_directory), - Some(5000), - "call2", - )?, - create_final_assistant_message_sse_response("done 2")?, - ]; - let server = create_mock_responses_server_sequence(responses).await; - create_config_toml(&codex_home, &server.uri())?; - - // Start MCP server and initialize. - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // 1) Start conversation with approval_policy=untrusted - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(working_directory.to_string_lossy().into_owned()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let _: AddConversationSubscriptionResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??, - )?; - - // 3) sendUserMessage triggers a shell call; approval policy is Untrusted so we should get an elicitation - let send_user_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "run python".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let _send_user_resp: SendUserMessageResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), - ) - .await??, - )?; - - // Expect an ExecCommandApproval request (elicitation) - let request = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_request_message(), - ) - .await??; - let ServerRequest::ExecCommandApproval { request_id, params } = request else { - panic!("expected ExecCommandApproval request, got: {request:?}"); - }; - - assert_eq!( - ExecCommandApprovalParams { - conversation_id, - call_id: "call1".to_string(), - approval_id: None, - command: format_with_current_shell("python3 -c 'print(42)'"), - cwd: working_directory.clone(), - reason: None, - parsed_cmd: vec![ParsedCommand::Unknown { - cmd: "python3 -c 'print(42)'".to_string() - }], - }, - params - ); - - // Approve so the first turn can complete - mcp.send_response( - request_id, - serde_json::json!({ "decision": codex_protocol::protocol::ReviewDecision::Approved }), - ) - .await?; - - // Wait for first TurnComplete - let _ = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - // 4) sendUserTurn with approval_policy=never should run without elicitation - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "run python again".to_string(), - text_elements: Vec::new(), - }], - cwd: working_directory.clone(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - output_schema: None, - }) - .await?; - // Acknowledge sendUserTurn - let _send_turn_resp: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id)), - ) - .await??, - )?; - - // Ensure we do NOT receive an ExecCommandApproval request before the task completes. - // If any Request is seen while waiting for task_complete, the helper will error and the test fails. - let _ = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - Ok(()) -} - -// Helper: minimal config.toml pointing at mock provider. - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn test_send_user_turn_updates_sandbox_and_cwd_between_turns() -> Result<()> { - if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } - - let tmp = TempDir::new()?; - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let workspace_root = tmp.path().join("workspace"); - std::fs::create_dir(&workspace_root)?; - let first_cwd = workspace_root.join("turn1"); - let second_cwd = workspace_root.join("turn2"); - std::fs::create_dir(&first_cwd)?; - std::fs::create_dir(&second_cwd)?; - - let responses = vec![ - create_shell_command_sse_response( - vec!["echo".to_string(), "first".to_string(), "turn".to_string()], - None, - Some(5000), - "call-first", - )?, - create_final_assistant_message_sse_response("done first")?, - create_shell_command_sse_response( - vec!["echo".to_string(), "second".to_string(), "turn".to_string()], - None, - Some(5000), - "call-second", - )?, - create_final_assistant_message_sse_response("done second")?, - ]; - let server = create_mock_responses_server_sequence(responses).await; - create_config_toml(&codex_home, &server.uri())?; - - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(first_cwd.to_string_lossy().into_owned()), - approval_policy: Some(AskForApproval::Never), - sandbox: Some(SandboxMode::WorkspaceWrite), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, - model, - .. - } = to_response::(new_conv_resp)?; - - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - - let first_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "first turn".to_string(), - text_elements: Vec::new(), - }], - cwd: first_cwd.clone(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::WorkspaceWrite { - writable_roots: vec![first_cwd.try_into()?], - read_only_access: Default::default(), - network_access: false, - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - }, - model: model.clone(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - output_schema: None, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(first_turn_id)), - ) - .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - mcp.clear_message_buffer(); - - let second_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "second turn".to_string(), - text_elements: Vec::new(), - }], - cwd: second_cwd.clone(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: model.clone(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - output_schema: None, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(second_turn_id)), - ) - .await??; - - let exec_begin_notification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/exec_command_begin"), - ) - .await??; - let params = exec_begin_notification - .params - .clone() - .expect("exec_command_begin params"); - let event: Event = serde_json::from_value(params).expect("deserialize exec begin event"); - let exec_begin = match event.msg { - EventMsg::ExecCommandBegin(exec_begin) => exec_begin, - other => panic!("expected ExecCommandBegin event, got {other:?}"), - }; - assert_eq!( - exec_begin.cwd, second_cwd, - "exec turn should run from updated cwd" - ); - let expected_command = format_with_current_shell("echo second turn"); - assert_eq!( - exec_begin.command, expected_command, - "exec turn should run expected command" - ); - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - Ok(()) -} - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "untrusted" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/config.rs b/codex-rs/app-server/tests/suite/config.rs deleted file mode 100644 index 27a44ef550..0000000000 --- a/codex-rs/app-server/tests/suite/config.rs +++ /dev/null @@ -1,158 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::test_tmp_path; -use app_test_support::to_response; -use codex_app_server_protocol::GetUserSavedConfigResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::Profile; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SandboxSettings; -use codex_app_server_protocol::Tools; -use codex_app_server_protocol::UserSavedConfig; -use codex_protocol::config_types::ForcedLoginMethod; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::SandboxMode; -use codex_protocol::config_types::Verbosity; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use pretty_assertions::assert_eq; -use std::collections::HashMap; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { - let writable_root = test_tmp_path(); - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "gpt-5.1-codex-max" -approval_policy = "on-request" -sandbox_mode = "workspace-write" -model_reasoning_summary = "detailed" -model_reasoning_effort = "high" -model_verbosity = "medium" -profile = "test" -forced_chatgpt_workspace_id = "12345678-0000-0000-0000-000000000000" -forced_login_method = "chatgpt" - -[sandbox_workspace_write] -writable_roots = [{}] -network_access = true -exclude_tmpdir_env_var = true -exclude_slash_tmp = true - -[tools] -web_search = false -view_image = true - -[profiles.test] -model = "gpt-4o" -approval_policy = "on-request" -model_reasoning_effort = "high" -model_reasoning_summary = "detailed" -model_verbosity = "medium" -model_provider = "openai" -chatgpt_base_url = "https://api.chatgpt.com" -"#, - serde_json::json!(writable_root) - ), - ) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn get_config_toml_parses_all_fields() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_get_user_saved_config_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let config: GetUserSavedConfigResponse = to_response(resp)?; - let writable_root = test_tmp_path(); - let expected = GetUserSavedConfigResponse { - config: UserSavedConfig { - approval_policy: Some(AskForApproval::OnRequest), - sandbox_mode: Some(SandboxMode::WorkspaceWrite), - sandbox_settings: Some(SandboxSettings { - writable_roots: vec![writable_root], - network_access: Some(true), - exclude_tmpdir_env_var: Some(true), - exclude_slash_tmp: Some(true), - }), - forced_chatgpt_workspace_id: Some("12345678-0000-0000-0000-000000000000".into()), - forced_login_method: Some(ForcedLoginMethod::Chatgpt), - model: Some("gpt-5.1-codex-max".into()), - model_reasoning_effort: Some(ReasoningEffort::High), - model_reasoning_summary: Some(ReasoningSummary::Detailed), - model_verbosity: Some(Verbosity::Medium), - tools: Some(Tools { - web_search: Some(false), - view_image: Some(true), - }), - profile: Some("test".to_string()), - profiles: HashMap::from([( - "test".into(), - Profile { - model: Some("gpt-4o".into()), - approval_policy: Some(AskForApproval::OnRequest), - model_reasoning_effort: Some(ReasoningEffort::High), - model_reasoning_summary: Some(ReasoningSummary::Detailed), - model_verbosity: Some(Verbosity::Medium), - model_provider: Some("openai".into()), - chatgpt_base_url: Some("https://api.chatgpt.com".into()), - }, - )]), - }, - }; - - assert_eq!(config, expected); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn get_config_toml_empty() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_get_user_saved_config_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let config: GetUserSavedConfigResponse = to_response(resp)?; - let expected = GetUserSavedConfigResponse { - config: UserSavedConfig { - approval_policy: None, - sandbox_mode: None, - sandbox_settings: None, - forced_chatgpt_workspace_id: None, - forced_login_method: None, - model: None, - model_reasoning_effort: None, - model_reasoning_summary: None, - model_verbosity: None, - tools: None, - profile: None, - profiles: HashMap::new(), - }, - }; - - assert_eq!(config, expected); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/conversation_summary.rs b/codex-rs/app-server/tests/suite/conversation_summary.rs new file mode 100644 index 0000000000..31108a8455 --- /dev/null +++ b/codex-rs/app-server/tests/suite/conversation_summary.rs @@ -0,0 +1,113 @@ +use anyhow::Result; +use app_test_support::McpProcess; +use app_test_support::create_fake_rollout; +use app_test_support::rollout_path; +use app_test_support::to_response; +use codex_app_server_protocol::ConversationSummary; +use codex_app_server_protocol::GetConversationSummaryParams; +use codex_app_server_protocol::GetConversationSummaryResponse; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionSource; +use pretty_assertions::assert_eq; +use std::path::PathBuf; +use tempfile::TempDir; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const FILENAME_TS: &str = "2025-01-02T12-00-00"; +const META_RFC3339: &str = "2025-01-02T12:00:00Z"; +const PREVIEW: &str = "Summarize this conversation"; +const MODEL_PROVIDER: &str = "openai"; + +fn expected_summary(conversation_id: ThreadId, path: PathBuf) -> ConversationSummary { + ConversationSummary { + conversation_id, + path, + preview: PREVIEW.to_string(), + timestamp: Some(META_RFC3339.to_string()), + updated_at: Some(META_RFC3339.to_string()), + model_provider: MODEL_PROVIDER.to_string(), + cwd: PathBuf::from("/"), + cli_version: "0.0.0".to_string(), + source: SessionSource::Cli, + git_info: None, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn get_conversation_summary_by_thread_id_reads_rollout() -> Result<()> { + let codex_home = TempDir::new()?; + let conversation_id = create_fake_rollout( + codex_home.path(), + FILENAME_TS, + META_RFC3339, + PREVIEW, + Some(MODEL_PROVIDER), + None, + )?; + let thread_id = ThreadId::from_string(&conversation_id)?; + let expected = expected_summary( + thread_id, + std::fs::canonicalize(rollout_path( + codex_home.path(), + FILENAME_TS, + &conversation_id, + ))?, + ); + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_get_conversation_summary_request(GetConversationSummaryParams::ThreadId { + conversation_id: thread_id, + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: GetConversationSummaryResponse = to_response(response)?; + + assert_eq!(received.summary, expected); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn get_conversation_summary_by_relative_rollout_path_resolves_from_codex_home() -> Result<()> +{ + let codex_home = TempDir::new()?; + let conversation_id = create_fake_rollout( + codex_home.path(), + FILENAME_TS, + META_RFC3339, + PREVIEW, + Some(MODEL_PROVIDER), + None, + )?; + let thread_id = ThreadId::from_string(&conversation_id)?; + let rollout_path = rollout_path(codex_home.path(), FILENAME_TS, &conversation_id); + let relative_path = rollout_path.strip_prefix(codex_home.path())?.to_path_buf(); + let expected = expected_summary(thread_id, std::fs::canonicalize(rollout_path)?); + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_get_conversation_summary_request(GetConversationSummaryParams::RolloutPath { + rollout_path: relative_path, + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: GetConversationSummaryResponse = to_response(response)?; + + assert_eq!(received.summary, expected); + Ok(()) +} diff --git a/codex-rs/app-server/tests/suite/create_thread.rs b/codex-rs/app-server/tests/suite/create_thread.rs deleted file mode 100644 index 8ad3342539..0000000000 --- a/codex-rs/app-server/tests/suite/create_thread.rs +++ /dev/null @@ -1,142 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_conversation_create_and_send_message_ok() -> Result<()> { - // Mock server – we won't strictly rely on it, but provide one to satisfy any model wiring. - let response_body = create_final_assistant_message_sse_response("Done")?; - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence(&server, vec![response_body]).await; - - // Temporary Codex home with config pointing at the mock server. - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - // Start MCP server process and initialize. - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // Create a conversation via the new JSON-RPC API. - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, - model, - reasoning_effort: _, - rollout_path: _, - } = to_response::(new_conv_resp)?; - assert_eq!(model, "o3"); - - // Add a listener so we receive notifications for this conversation (not strictly required for this test). - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let _sub: AddConversationSubscriptionResponse = - to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??, - )?; - - // Now send a user message via the wire API and expect an OK (empty object) result. - let send_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_id)), - ) - .await??; - let _ok: SendUserMessageResponse = to_response::(send_resp)?; - - // Avoid race condition by waiting for the mock server to receive the responses request. - let deadline = std::time::Instant::now() + DEFAULT_READ_TIMEOUT; - let requests = loop { - let requests = response_mock.requests(); - if !requests.is_empty() { - break requests; - } - if std::time::Instant::now() >= deadline { - panic!("mock server did not receive the responses request in time"); - } - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - }; - - // Verify the outbound request body matches expectations for Responses. - let request = requests - .first() - .expect("mock server should have received at least one request"); - let body = request.body_json(); - assert_eq!(body["model"], json!("o3")); - let user_texts = request.message_input_texts("user"); - assert!( - user_texts.iter().any(|text| text == "Hello"), - "expected user input to include Hello, got {user_texts:?}" - ); - - drop(server); - Ok(()) -} - -// Helper to create a config.toml pointing at the mock model server. -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/fork_thread.rs b/codex-rs/app-server/tests/suite/fork_thread.rs deleted file mode 100644 index ec282be4a1..0000000000 --- a/codex-rs/app-server/tests/suite/fork_thread.rs +++ /dev/null @@ -1,140 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_fake_rollout; -use app_test_support::to_response; -use codex_app_server_protocol::ForkConversationParams; -use codex_app_server_protocol::ForkConversationResponse; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; // reused for overrides shape -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionConfiguredNotification; -use codex_protocol::protocol::EventMsg; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn fork_conversation_creates_new_rollout() -> Result<()> { - let codex_home = TempDir::new()?; - - let preview = "Hello A"; - let conversation_id = create_fake_rollout( - codex_home.path(), - "2025-01-02T12-00-00", - "2025-01-02T12:00:00Z", - preview, - Some("openai"), - None, - )?; - - let original_path = codex_home - .path() - .join("sessions") - .join("2025") - .join("01") - .join("02") - .join(format!( - "rollout-2025-01-02T12-00-00-{conversation_id}.jsonl" - )); - assert!( - original_path.exists(), - "expected original rollout to exist at {}", - original_path.display() - ); - let original_contents = std::fs::read_to_string(&original_path)?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let fork_req_id = mcp - .send_fork_conversation_request(ForkConversationParams { - path: Some(original_path.clone()), - conversation_id: None, - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - - // Expect a sessionConfigured notification for the forked session. - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - session_id, - rollout_path, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - - assert_eq!(model, "o3"); - assert_ne!( - session_id.to_string(), - conversation_id, - "expected a new conversation id when forking" - ); - assert_ne!( - rollout_path, original_path, - "expected a new rollout path when forking" - ); - assert!( - rollout_path.exists(), - "expected forked rollout to exist at {}", - rollout_path.display() - ); - - let session_initial_messages = - session_initial_messages.expect("expected initial messages when forking from rollout"); - match session_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, preview); - } - other => panic!("unexpected initial messages from rollout fork: {other:#?}"), - } - - // Then the response for forkConversation. - let fork_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(fork_req_id)), - ) - .await??; - let ForkConversationResponse { - conversation_id: forked_id, - model: forked_model, - initial_messages: response_initial_messages, - rollout_path: response_rollout_path, - } = to_response::(fork_resp)?; - - assert_eq!(forked_model, "o3"); - assert_eq!(response_rollout_path, rollout_path); - assert_ne!(forked_id.to_string(), conversation_id); - - let response_initial_messages = - response_initial_messages.expect("expected initial messages in fork response"); - match response_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, preview); - } - other => panic!("unexpected initial messages in fork response: {other:#?}"), - } - - let after_contents = std::fs::read_to_string(&original_path)?; - assert_eq!( - after_contents, original_contents, - "fork should not mutate the original rollout file" - ); - - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/interrupt.rs b/codex-rs/app-server/tests/suite/interrupt.rs deleted file mode 100644 index dd09b832f8..0000000000 --- a/codex-rs/app-server/tests/suite/interrupt.rs +++ /dev/null @@ -1,163 +0,0 @@ -#![cfg(unix)] -// Support code lives in the `app_test_support` crate under tests/common. - -use std::path::Path; - -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::InterruptConversationParams; -use codex_app_server_protocol::InterruptConversationResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_protocol::protocol::TurnAbortReason; -use core_test_support::skip_if_no_network; -use tempfile::TempDir; -use tokio::time::timeout; - -use app_test_support::McpProcess; -use app_test_support::create_mock_responses_server_sequence; -use app_test_support::create_shell_command_sse_response; -use app_test_support::to_response; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_shell_command_interruption() { - skip_if_no_network!(); - - if let Err(err) = shell_command_interruption().await { - panic!("failure: {err}"); - } -} - -async fn shell_command_interruption() -> anyhow::Result<()> { - // Use a cross-platform blocking command. On Windows plain `sleep` is not guaranteed to exist - // (MSYS/GNU coreutils may be absent) and the failure causes the tool call to finish immediately, - // which triggers a second model request before the test sends the explicit follow-up. That - // prematurely consumes the second mocked SSE response and leads to a third POST (panic: no response for 2). - // Powershell Start-Sleep is always available on Windows runners. On Unix we keep using `sleep`. - #[cfg(target_os = "windows")] - let shell_command = vec![ - "powershell".to_string(), - "-Command".to_string(), - "Start-Sleep -Seconds 10".to_string(), - ]; - #[cfg(not(target_os = "windows"))] - let shell_command = vec!["sleep".to_string(), "10".to_string()]; - - let tmp = TempDir::new()?; - // Temporary Codex home with config pointing at the mock server. - let codex_home = tmp.path().join("codex_home"); - std::fs::create_dir(&codex_home)?; - let working_directory = tmp.path().join("workdir"); - std::fs::create_dir(&working_directory)?; - - // Create mock server with a single SSE response: the long sleep command - let server = create_mock_responses_server_sequence(vec![create_shell_command_sse_response( - shell_command.clone(), - Some(&working_directory), - Some(10_000), // 10 seconds timeout in ms - "call_sleep", - )?]) - .await; - create_config_toml(&codex_home, server.uri())?; - - // Start MCP server and initialize. - let mut mcp = McpProcess::new(&codex_home).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // 1) newConversation - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - cwd: Some(working_directory.to_string_lossy().into_owned()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let new_conv_resp = to_response::(new_conv_resp)?; - let NewConversationResponse { - conversation_id, .. - } = new_conv_resp; - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let _add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - - // 3) sendUserMessage (should trigger notifications; we only validate an OK response) - let send_user_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![codex_app_server_protocol::InputItem::Text { - text: "run first sleep command".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - let send_user_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), - ) - .await??; - let SendUserMessageResponse {} = to_response::(send_user_resp)?; - - // Give the command a moment to start - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - - // 4) send interrupt request - let interrupt_id = mcp - .send_interrupt_conversation_request(InterruptConversationParams { conversation_id }) - .await?; - let interrupt_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(interrupt_id)), - ) - .await??; - let InterruptConversationResponse { abort_reason } = - to_response::(interrupt_resp)?; - assert_eq!(TurnAbortReason::Interrupted, abort_reason); - - Ok(()) -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -fn create_config_toml(codex_home: &Path, server_uri: String) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/list_resume.rs b/codex-rs/app-server/tests/suite/list_resume.rs deleted file mode 100644 index 97c8f41d11..0000000000 --- a/codex-rs/app-server/tests/suite/list_resume.rs +++ /dev/null @@ -1,440 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_fake_rollout; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::ListConversationsParams; -use codex_app_server_protocol::ListConversationsResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; -use codex_app_server_protocol::ResumeConversationResponse; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::SessionConfiguredNotification; -use codex_protocol::models::ContentItem; -use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::EventMsg; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn test_list_and_resume_conversations() -> Result<()> { - // Prepare a temporary CODEX_HOME with a few fake rollout files. - let codex_home = TempDir::new()?; - create_fake_rollout( - codex_home.path(), - "2025-01-02T12-00-00", - "2025-01-02T12:00:00Z", - "Hello A", - Some("openai"), - None, - )?; - create_fake_rollout( - codex_home.path(), - "2025-01-01T13-00-00", - "2025-01-01T13:00:00Z", - "Hello B", - Some("openai"), - None, - )?; - create_fake_rollout( - codex_home.path(), - "2025-01-01T12-00-00", - "2025-01-01T12:00:00Z", - "Hello C", - None, - None, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // Request first page with size 2 - let req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(2), - cursor: None, - model_providers: None, - }) - .await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id)), - ) - .await??; - let ListConversationsResponse { items, next_cursor } = - to_response::(resp)?; - - assert_eq!(items.len(), 2); - // Newest first; preview text should match - assert_eq!(items[0].preview, "Hello A"); - assert_eq!(items[1].preview, "Hello B"); - assert_eq!(items[0].model_provider, "openai"); - assert_eq!(items[1].model_provider, "openai"); - assert!(items[0].path.is_absolute()); - assert!(next_cursor.is_some()); - - // Request the next page using the cursor - let req_id2 = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(2), - cursor: next_cursor, - model_providers: None, - }) - .await?; - let resp2: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id2)), - ) - .await??; - let ListConversationsResponse { - items: items2, - next_cursor: next2, - .. - } = to_response::(resp2)?; - assert_eq!(items2.len(), 1); - assert_eq!(items2[0].preview, "Hello C"); - assert_eq!(items2[0].model_provider, "openai"); - assert_eq!(next2, None); - - // Add a conversation with an explicit non-OpenAI provider for filter tests. - create_fake_rollout( - codex_home.path(), - "2025-01-01T11-30-00", - "2025-01-01T11:30:00Z", - "Hello TP", - Some("test-provider"), - None, - )?; - - // Filtering by model provider should return only matching sessions. - let filter_req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(10), - cursor: None, - model_providers: Some(vec!["test-provider".to_string()]), - }) - .await?; - let filter_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(filter_req_id)), - ) - .await??; - let ListConversationsResponse { - items: filtered_items, - next_cursor: filtered_next, - } = to_response::(filter_resp)?; - assert_eq!(filtered_items.len(), 1); - assert_eq!(filtered_next, None); - assert_eq!(filtered_items[0].preview, "Hello TP"); - assert_eq!(filtered_items[0].model_provider, "test-provider"); - - // Empty filter should include every session regardless of provider metadata. - let unfiltered_req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(10), - cursor: None, - model_providers: Some(Vec::new()), - }) - .await?; - let unfiltered_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(unfiltered_req_id)), - ) - .await??; - let ListConversationsResponse { - items: unfiltered_items, - next_cursor: unfiltered_next, - } = to_response::(unfiltered_resp)?; - assert_eq!(unfiltered_items.len(), 4); - assert!(unfiltered_next.is_none()); - - let empty_req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(10), - cursor: None, - model_providers: Some(vec!["other".to_string()]), - }) - .await?; - let empty_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(empty_req_id)), - ) - .await??; - let ListConversationsResponse { - items: empty_items, - next_cursor: empty_next, - } = to_response::(empty_resp)?; - assert!(empty_items.is_empty()); - assert!(empty_next.is_none()); - - let first_item = &items[0]; - - // Now resume one of the sessions from an explicit rollout path. - let resume_req_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: Some(first_item.path.clone()), - conversation_id: None, - history: None, - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - - // Expect a codex/event notification with msg.type == sessionConfigured - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - rollout_path, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - assert_eq!(model, "o3"); - assert_eq!(rollout_path, first_item.path.clone()); - let session_initial_messages = session_initial_messages - .expect("expected initial messages when resuming from rollout path"); - match session_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => panic!("unexpected initial messages from rollout resume: {other:#?}"), - } - - // Then the response for resumeConversation - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_req_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id, - model: resume_model, - initial_messages: response_initial_messages, - .. - } = to_response::(resume_resp)?; - // conversation id should be a valid UUID - assert!(!conversation_id.to_string().is_empty()); - assert_eq!(resume_model, "o3"); - let response_initial_messages = - response_initial_messages.expect("expected initial messages in resume response"); - match response_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => panic!("unexpected initial messages in resume response: {other:#?}"), - } - - // Resuming with only a conversation id should locate the rollout automatically. - let resume_by_id_req_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: None, - conversation_id: Some(first_item.conversation_id), - history: None, - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - rollout_path, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - assert_eq!(model, "o3"); - assert_eq!(rollout_path, first_item.path.clone()); - let session_initial_messages = session_initial_messages - .expect("expected initial messages when resuming from conversation id"); - match session_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => panic!("unexpected initial messages from conversation id resume: {other:#?}"), - } - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_by_id_req_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id: by_id_conversation_id, - model: by_id_model, - initial_messages: by_id_initial_messages, - .. - } = to_response::(resume_resp)?; - assert!(!by_id_conversation_id.to_string().is_empty()); - assert_eq!(by_id_model, "o3"); - let by_id_initial_messages = by_id_initial_messages - .expect("expected initial messages when resuming from conversation id response"); - match by_id_initial_messages.as_slice() { - [EventMsg::UserMessage(message)] => { - assert_eq!(message.message, first_item.preview.clone()); - } - other => { - panic!("unexpected initial messages in conversation id resume response: {other:#?}") - } - } - - // Resuming with explicit history should succeed even without a stored rollout. - let fork_history_text = "Hello from history"; - let history = vec![ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: fork_history_text.to_string(), - }], - end_turn: None, - phase: None, - }]; - let resume_with_history_req_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: None, - conversation_id: None, - history: Some(history), - overrides: Some(NewConversationParams { - model: Some("o3".to_string()), - ..Default::default() - }), - }) - .await?; - let notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let session_configured: ServerNotification = notification.try_into()?; - let ServerNotification::SessionConfigured(SessionConfiguredNotification { - model, - initial_messages: session_initial_messages, - .. - }) = session_configured - else { - unreachable!("expected sessionConfigured notification"); - }; - assert_eq!(model, "o3"); - assert!( - session_initial_messages.as_ref().is_none_or(Vec::is_empty), - "expected no initial messages when resuming from explicit history but got {session_initial_messages:#?}" - ); - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_with_history_req_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id: history_conversation_id, - model: history_model, - initial_messages: history_initial_messages, - .. - } = to_response::(resume_resp)?; - assert!(!history_conversation_id.to_string().is_empty()); - assert_eq!(history_model, "o3"); - assert!( - history_initial_messages.as_ref().is_none_or(Vec::is_empty), - "expected no initial messages in resume response when history is provided but got {history_initial_messages:#?}" - ); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn list_conversations_fetches_through_filtered_pages() -> Result<()> { - let codex_home = TempDir::new()?; - - // Only the last 3 conversations match the provider filter; request 3 and - // ensure pagination keeps fetching past non-matching pages. - let cases = [ - ( - "2025-03-04T12-00-00", - "2025-03-04T12:00:00Z", - "skip_provider", - ), - ( - "2025-03-03T12-00-00", - "2025-03-03T12:00:00Z", - "skip_provider", - ), - ( - "2025-03-02T12-00-00", - "2025-03-02T12:00:00Z", - "target_provider", - ), - ( - "2025-03-01T12-00-00", - "2025-03-01T12:00:00Z", - "target_provider", - ), - ( - "2025-02-28T12-00-00", - "2025-02-28T12:00:00Z", - "target_provider", - ), - ]; - - for (ts_file, ts_rfc, provider) in cases { - create_fake_rollout( - codex_home.path(), - ts_file, - ts_rfc, - "Hello", - Some(provider), - None, - )?; - } - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let req_id = mcp - .send_list_conversations_request(ListConversationsParams { - page_size: Some(3), - cursor: None, - model_providers: Some(vec!["target_provider".to_string()]), - }) - .await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id)), - ) - .await??; - let ListConversationsResponse { items, next_cursor } = - to_response::(resp)?; - - assert_eq!( - items.len(), - 3, - "should fetch across pages to satisfy the limit" - ); - assert!( - items - .iter() - .all(|item| item.model_provider == "target_provider") - ); - assert_eq!(next_cursor, None); - - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/login.rs b/codex-rs/app-server/tests/suite/login.rs deleted file mode 100644 index afc69787eb..0000000000 --- a/codex-rs/app-server/tests/suite/login.rs +++ /dev/null @@ -1,161 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::GetAuthStatusParams; -use codex_app_server_protocol::GetAuthStatusResponse; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginChatGptResponse; -use codex_app_server_protocol::LogoutChatGptResponse; -use codex_app_server_protocol::RequestId; -use codex_core::auth::AuthCredentialsStoreMode; -use codex_login::login_with_api_key; -use serial_test::serial; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -// Helper to create a config.toml; mirrors create_conversation.rs -fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "http://127.0.0.1:0/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"#, - ) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn logout_chatgpt_removes_auth() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path())?; - login_with_api_key( - codex_home.path(), - "sk-test-key", - AuthCredentialsStoreMode::File, - )?; - assert!(codex_home.path().join("auth.json").exists()); - - let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let id = mcp.send_logout_chat_gpt_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(id)), - ) - .await??; - let _ok: LogoutChatGptResponse = to_response(resp)?; - - assert!( - !codex_home.path().join("auth.json").exists(), - "auth.json should be deleted" - ); - - // Verify status reflects signed-out state. - let status_id = mcp - .send_get_auth_status_request(GetAuthStatusParams { - include_token: Some(true), - refresh_token: Some(false), - }) - .await?; - let status_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(status_id)), - ) - .await??; - let status: GetAuthStatusResponse = to_response(status_resp)?; - assert_eq!(status.auth_method, None); - assert_eq!(status.auth_token, None); - Ok(()) -} - -fn create_config_toml_forced_login(codex_home: &Path, forced_method: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - let contents = format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" -forced_login_method = "{forced_method}" -"# - ); - std::fs::write(config_toml, contents) -} - -fn create_config_toml_forced_workspace( - codex_home: &Path, - workspace_id: &str, -) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - let contents = format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" -forced_chatgpt_workspace_id = "{workspace_id}" -"# - ); - std::fs::write(config_toml, contents) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn login_chatgpt_rejected_when_forced_api() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml_forced_login(codex_home.path(), "api")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_login_chat_gpt_request().await?; - let err: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!( - err.error.message, - "ChatGPT login is disabled. Use API key login instead." - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -// Serialize tests that launch the login server since it binds to a fixed port. -#[serial(login_port)] -async fn login_chatgpt_includes_forced_workspace_query_param() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml_forced_workspace(codex_home.path(), "ws-forced")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_login_chat_gpt_request().await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let login: LoginChatGptResponse = to_response(resp)?; - assert!( - login.auth_url.contains("allowed_workspace_id=ws-forced"), - "auth URL should include forced workspace" - ); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/mod.rs b/codex-rs/app-server/tests/suite/mod.rs index ae7e0cb438..c60f4a32a1 100644 --- a/codex-rs/app-server/tests/suite/mod.rs +++ b/codex-rs/app-server/tests/suite/mod.rs @@ -1,16 +1,4 @@ -mod archive_thread; mod auth; -mod codex_message_processor_flow; -mod config; -mod create_thread; -mod fork_thread; +mod conversation_summary; mod fuzzy_file_search; -mod interrupt; -mod list_resume; -mod login; -mod output_schema; -mod send_message; -mod set_default_model; -mod user_agent; -mod user_info; mod v2; diff --git a/codex-rs/app-server/tests/suite/output_schema.rs b/codex-rs/app-server/tests/suite/output_schema.rs deleted file mode 100644 index 3d83bec7dd..0000000000 --- a/codex-rs/app-server/tests/suite/output_schema.rs +++ /dev/null @@ -1,285 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendUserTurnParams; -use codex_app_server_protocol::SendUserTurnResponse; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SandboxPolicy; -use core_test_support::responses; -use core_test_support::skip_if_no_network; -use pretty_assertions::assert_eq; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test] -async fn send_user_turn_accepts_output_schema_v1() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let response_mock = responses::mount_sse_once(&server, body).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - let listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(listener_id)), - ) - .await??; - - let output_schema = serde_json::json!({ - "type": "object", - "properties": { - "answer": { "type": "string" } - }, - "required": ["answer"], - "additionalProperties": false - }); - - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - output_schema: Some(output_schema.clone()), - }) - .await?; - let _send_turn_resp: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id)), - ) - .await??, - )?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - let request = response_mock.single_request(); - let payload = request.body_json(); - let text = payload.get("text").expect("request missing text field"); - let format = text - .get("format") - .expect("request missing text.format field"); - assert_eq!( - format, - &serde_json::json!({ - "name": "codex_output_schema", - "type": "json_schema", - "strict": true, - "schema": output_schema, - }) - ); - - Ok(()) -} - -#[tokio::test] -async fn send_user_turn_output_schema_is_per_turn_v1() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let body1 = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let response_mock1 = responses::mount_sse_once(&server, body1).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::(new_conv_resp)?; - - let listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(listener_id)), - ) - .await??; - - let output_schema = serde_json::json!({ - "type": "object", - "properties": { - "answer": { "type": "string" } - }, - "required": ["answer"], - "additionalProperties": false - }); - - let send_turn_id = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - output_schema: Some(output_schema.clone()), - }) - .await?; - let _send_turn_resp: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id)), - ) - .await??, - )?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - let payload1 = response_mock1.single_request().body_json(); - assert_eq!( - payload1.pointer("/text/format"), - Some(&serde_json::json!({ - "name": "codex_output_schema", - "type": "json_schema", - "strict": true, - "schema": output_schema, - })) - ); - - let body2 = responses::sse(vec![ - responses::ev_response_created("resp-2"), - responses::ev_assistant_message("msg-2", "Done"), - responses::ev_completed("resp-2"), - ]); - let response_mock2 = responses::mount_sse_once(&server, body2).await; - - let send_turn_id_2 = mcp - .send_send_user_turn_request(SendUserTurnParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello again".to_string(), - text_elements: Vec::new(), - }], - cwd: codex_home.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - model: "mock-model".to_string(), - effort: Some(ReasoningEffort::Medium), - summary: ReasoningSummary::Auto, - output_schema: None, - }) - .await?; - let _send_turn_resp_2: SendUserTurnResponse = to_response::( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_turn_id_2)), - ) - .await??, - )?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - - let payload2 = response_mock2.single_request().body_json(); - assert_eq!(payload2.pointer("/text/format"), None); - - Ok(()) -} - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "read-only" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} diff --git a/codex-rs/app-server/tests/suite/send_message.rs b/codex-rs/app-server/tests/suite/send_message.rs deleted file mode 100644 index 0bf6e98cfb..0000000000 --- a/codex-rs/app-server/tests/suite/send_message.rs +++ /dev/null @@ -1,584 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_fake_rollout; -use app_test_support::rollout_path; -use app_test_support::to_response; -use codex_app_server_protocol::AddConversationListenerParams; -use codex_app_server_protocol::AddConversationSubscriptionResponse; -use codex_app_server_protocol::InputItem; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::NewConversationParams; -use codex_app_server_protocol::NewConversationResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ResumeConversationParams; -use codex_app_server_protocol::ResumeConversationResponse; -use codex_app_server_protocol::SendUserMessageParams; -use codex_app_server_protocol::SendUserMessageResponse; -use codex_execpolicy::Policy; -use codex_protocol::ThreadId; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::models::ContentItem; -use codex_protocol::models::DeveloperInstructions; -use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::RawResponseItemEvent; -use codex_protocol::protocol::RolloutItem; -use codex_protocol::protocol::RolloutLine; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::protocol::TurnContextItem; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test] -async fn test_send_message_success() -> Result<()> { - // Spin up a mock responses server that immediately ends the Codex turn. - // Two Codex turns hit the mock model (session start + send-user-message). Provide two SSE responses. - let server = responses::start_mock_server().await; - let body1 = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let body2 = responses::sse(vec![ - responses::ev_response_created("resp-2"), - responses::ev_assistant_message("msg-2", "Done"), - responses::ev_completed("resp-2"), - ]); - let _response_mock1 = responses::mount_sse_once(&server, body1).await; - let _response_mock2 = responses::mount_sse_once(&server, body2).await; - - // Create a temporary Codex home with config pointing at the mock server. - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - // Start MCP server process and initialize. - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - // Start a conversation using the new wire API. - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::<_>(new_conv_resp)?; - - // 2) addConversationListener - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::<_>(add_listener_resp)?; - - // Now exercise sendUserMessage twice. - send_message("Hello", conversation_id, &mut mcp).await?; - send_message("Hello again", conversation_id, &mut mcp).await?; - Ok(()) -} - -#[expect(clippy::expect_used)] -async fn send_message( - message: &str, - conversation_id: ThreadId, - mcp: &mut McpProcess, -) -> Result<()> { - // Now exercise sendUserMessage. - let send_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: message.to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_id)), - ) - .await??; - - let _ok: SendUserMessageResponse = to_response::(response)?; - - // Verify the task_finished notification is received. - // Note this also ensures that the final request to the server was made. - let task_finished_notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - let serde_json::Value::Object(map) = task_finished_notification - .params - .expect("notification should have params") - else { - panic!("task_finished_notification should have params"); - }; - assert_eq!( - map.get("conversationId") - .expect("should have conversationId"), - &serde_json::Value::String(conversation_id.to_string()) - ); - - let raw_attempt = tokio::time::timeout( - std::time::Duration::from_millis(200), - mcp.read_stream_until_notification_message("codex/event/raw_response_item"), - ) - .await; - assert!( - raw_attempt.is_err(), - "unexpected raw item notification when not opted in" - ); - Ok(()) -} - -#[tokio::test] -async fn test_send_message_raw_notifications_opt_in() -> Result<()> { - let server = responses::start_mock_server().await; - let body = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]); - let _response_mock = responses::mount_sse_once(&server, body).await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let new_conv_id = mcp - .send_new_conversation_request(NewConversationParams { - developer_instructions: Some("Use the test harness tools.".to_string()), - ..Default::default() - }) - .await?; - let new_conv_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), - ) - .await??; - let NewConversationResponse { - conversation_id, .. - } = to_response::<_>(new_conv_resp)?; - - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: true, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::<_>(add_listener_resp)?; - - let send_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id, - items: vec![InputItem::Text { - text: "Hello".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - - let permissions = read_raw_response_item(&mut mcp, conversation_id).await; - assert_permissions_message(&permissions); - - let developer = read_raw_response_item(&mut mcp, conversation_id).await; - assert_developer_message(&developer, "Use the test harness tools."); - - let instructions = read_raw_response_item(&mut mcp, conversation_id).await; - assert_instructions_message(&instructions); - - let environment = read_raw_response_item(&mut mcp, conversation_id).await; - assert_environment_message(&environment); - - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(send_id)), - ) - .await??; - let _ok: SendUserMessageResponse = to_response::(response)?; - - let user_message = read_raw_response_item(&mut mcp, conversation_id).await; - assert_user_message(&user_message, "Hello"); - - let assistant_message = read_raw_response_item(&mut mcp, conversation_id).await; - assert_assistant_message(&assistant_message, "Done"); - - let _ = tokio::time::timeout( - std::time::Duration::from_millis(250), - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await; - - Ok(()) -} - -#[tokio::test] -async fn test_send_message_session_not_found() -> Result<()> { - // Start MCP without creating a Codex session - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let unknown = ThreadId::new(); - let req_id = mcp - .send_send_user_message_request(SendUserMessageParams { - conversation_id: unknown, - items: vec![InputItem::Text { - text: "ping".to_string(), - text_elements: Vec::new(), - }], - }) - .await?; - - // Expect an error response for unknown conversation. - let err = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(req_id)), - ) - .await??; - assert_eq!(err.id, RequestId::Integer(req_id)); - Ok(()) -} - -#[tokio::test] -async fn resume_with_model_mismatch_appends_model_switch_once() -> Result<()> { - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence( - &server, - vec![ - responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "Done"), - responses::ev_completed("resp-1"), - ]), - responses::sse(vec![ - responses::ev_response_created("resp-2"), - responses::ev_assistant_message("msg-2", "Done again"), - responses::ev_completed("resp-2"), - ]), - ], - ) - .await; - - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path(), &server.uri())?; - - let filename_ts = "2025-01-02T12-00-00"; - let meta_rfc3339 = "2025-01-02T12:00:00Z"; - let preview = "Resume me"; - let conversation_id = create_fake_rollout( - codex_home.path(), - filename_ts, - meta_rfc3339, - preview, - Some("mock_provider"), - None, - )?; - let rollout_path = rollout_path(codex_home.path(), filename_ts, &conversation_id); - append_rollout_turn_context(&rollout_path, meta_rfc3339, "previous-model")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let resume_id = mcp - .send_resume_conversation_request(ResumeConversationParams { - path: Some(rollout_path.clone()), - conversation_id: None, - history: None, - overrides: Some(NewConversationParams { - model: Some("gpt-5.2-codex".to_string()), - ..Default::default() - }), - }) - .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("sessionConfigured"), - ) - .await??; - let resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), - ) - .await??; - let ResumeConversationResponse { - conversation_id, .. - } = to_response::(resume_resp)?; - - let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { - conversation_id, - experimental_raw_events: false, - }) - .await?; - let add_listener_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), - ) - .await??; - let AddConversationSubscriptionResponse { subscription_id: _ } = - to_response::<_>(add_listener_resp)?; - - send_message("hello after resume", conversation_id, &mut mcp).await?; - send_message("second turn", conversation_id, &mut mcp).await?; - - let requests = response_mock.requests(); - assert_eq!(requests.len(), 2, "expected two model requests"); - - let first_developer_texts = requests[0].message_input_texts("developer"); - let first_model_switch_count = first_developer_texts - .iter() - .filter(|text| text.contains("")) - .count(); - assert!( - first_model_switch_count >= 1, - "expected model switch message on first post-resume turn, got {first_developer_texts:?}" - ); - - let second_developer_texts = requests[1].message_input_texts("developer"); - let second_model_switch_count = second_developer_texts - .iter() - .filter(|text| text.contains("")) - .count(); - assert_eq!( - second_model_switch_count, 1, - "did not expect duplicate model switch message on second post-resume turn, got {second_developer_texts:?}" - ); - - Ok(()) -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -model = "mock-model" -approval_policy = "never" -sandbox_mode = "danger-full-access" - -model_provider = "mock_provider" - -[model_providers.mock_provider] -name = "Mock provider for test" -base_url = "{server_uri}/v1" -wire_api = "responses" -request_max_retries = 0 -stream_max_retries = 0 -"# - ), - ) -} - -#[expect(clippy::expect_used)] -async fn read_raw_response_item(mcp: &mut McpProcess, conversation_id: ThreadId) -> ResponseItem { - // TODO: Switch to rawResponseItem/completed once we migrate to app server v2 in codex web. - loop { - let raw_notification: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/raw_response_item"), - ) - .await - .expect("codex/event/raw_response_item notification timeout") - .expect("codex/event/raw_response_item notification resp"); - - let serde_json::Value::Object(params) = raw_notification - .params - .expect("codex/event/raw_response_item should have params") - else { - panic!("codex/event/raw_response_item should have params"); - }; - - let conversation_id_value = params - .get("conversationId") - .and_then(|value| value.as_str()) - .expect("raw response item should include conversationId"); - - assert_eq!( - conversation_id_value, - conversation_id.to_string(), - "raw response item conversation mismatch" - ); - - let msg_value = params - .get("msg") - .cloned() - .expect("raw response item should include msg payload"); - - // Ghost snapshots are produced concurrently and may arrive before the model reply. - let event: RawResponseItemEvent = - serde_json::from_value(msg_value).expect("deserialize raw response item"); - if !matches!(event.item, ResponseItem::GhostSnapshot { .. }) { - return event.item; - } - } -} - -fn assert_instructions_message(item: &ResponseItem) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "user"); - let texts = content_texts(content); - let is_instructions = texts - .iter() - .any(|text| text.starts_with("# AGENTS.md instructions for ")); - assert!( - is_instructions, - "expected instructions message, got {texts:?}" - ); - } - other => panic!("expected instructions message, got {other:?}"), - } -} - -fn assert_permissions_message(item: &ResponseItem) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "developer"); - let texts = content_texts(content); - let expected = DeveloperInstructions::from_policy( - &SandboxPolicy::DangerFullAccess, - AskForApproval::Never, - &Policy::empty(), - &PathBuf::from("/tmp"), - false, - ) - .into_text(); - assert_eq!( - texts, - vec![expected.as_str()], - "expected permissions developer message, got {texts:?}" - ); - } - other => panic!("expected permissions message, got {other:?}"), - } -} - -fn assert_developer_message(item: &ResponseItem, expected_text: &str) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "developer"); - let texts = content_texts(content); - assert_eq!( - texts, - vec![expected_text], - "expected developer instructions message, got {texts:?}" - ); - } - other => panic!("expected developer instructions message, got {other:?}"), - } -} - -fn assert_environment_message(item: &ResponseItem) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "user"); - let texts = content_texts(content); - assert!( - texts - .iter() - .any(|text| text.contains("")), - "expected environment context message, got {texts:?}" - ); - } - other => panic!("expected environment message, got {other:?}"), - } -} - -fn assert_user_message(item: &ResponseItem, expected_text: &str) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "user"); - let texts = content_texts(content); - assert_eq!(texts, vec![expected_text]); - } - other => panic!("expected user message, got {other:?}"), - } -} - -fn assert_assistant_message(item: &ResponseItem, expected_text: &str) { - match item { - ResponseItem::Message { role, content, .. } => { - assert_eq!(role, "assistant"); - let texts = content_texts(content); - assert_eq!(texts, vec![expected_text]); - } - other => panic!("expected assistant message, got {other:?}"), - } -} - -fn content_texts(content: &[ContentItem]) -> Vec<&str> { - content - .iter() - .filter_map(|item| match item { - ContentItem::InputText { text, .. } | ContentItem::OutputText { text } => { - Some(text.as_str()) - } - _ => None, - }) - .collect() -} - -fn append_rollout_turn_context(path: &Path, timestamp: &str, model: &str) -> std::io::Result<()> { - let line = RolloutLine { - timestamp: timestamp.to_string(), - item: RolloutItem::TurnContext(TurnContextItem { - turn_id: None, - cwd: PathBuf::from("/"), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - network: None, - model: model.to_string(), - personality: None, - collaboration_mode: None, - effort: None, - summary: ReasoningSummary::Auto, - user_instructions: None, - developer_instructions: None, - final_output_json_schema: None, - truncation_policy: None, - }), - }; - let serialized = serde_json::to_string(&line).map_err(std::io::Error::other)?; - std::fs::OpenOptions::new() - .append(true) - .open(path)? - .write_all(format!("{serialized}\n").as_bytes()) -} diff --git a/codex-rs/app-server/tests/suite/set_default_model.rs b/codex-rs/app-server/tests/suite/set_default_model.rs deleted file mode 100644 index b56c54dbd9..0000000000 --- a/codex-rs/app-server/tests/suite/set_default_model.rs +++ /dev/null @@ -1,64 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SetDefaultModelParams; -use codex_app_server_protocol::SetDefaultModelResponse; -use codex_core::config::ConfigToml; -use pretty_assertions::assert_eq; -use std::path::Path; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn set_default_model_persists_overrides() -> Result<()> { - let codex_home = TempDir::new()?; - create_config_toml(codex_home.path())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let params = SetDefaultModelParams { - model: Some("gpt-4.1".to_string()), - reasoning_effort: None, - }; - - let request_id = mcp.send_set_default_model_request(params).await?; - - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let _: SetDefaultModelResponse = to_response(resp)?; - - let config_path = codex_home.path().join("config.toml"); - let config_contents = tokio::fs::read_to_string(&config_path).await?; - let config_toml: ConfigToml = toml::from_str(&config_contents)?; - - assert_eq!( - ConfigToml { - model: Some("gpt-4.1".to_string()), - model_reasoning_effort: None, - ..Default::default() - }, - config_toml, - ); - Ok(()) -} - -// Helper to create a config.toml; mirrors create_conversation.rs -fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - r#" -model = "gpt-5.1-codex-max" -model_reasoning_effort = "medium" -"#, - ) -} diff --git a/codex-rs/app-server/tests/suite/user_agent.rs b/codex-rs/app-server/tests/suite/user_agent.rs deleted file mode 100644 index 9178a3ef58..0000000000 --- a/codex-rs/app-server/tests/suite/user_agent.rs +++ /dev/null @@ -1,43 +0,0 @@ -use anyhow::Result; -use app_test_support::DEFAULT_CLIENT_NAME; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::GetUserAgentResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn get_user_agent_returns_current_codex_user_agent() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_get_user_agent_request().await?; - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let os_info = os_info::get(); - let originator = DEFAULT_CLIENT_NAME; - let os_type = os_info.os_type(); - let os_version = os_info.version(); - let architecture = os_info.architecture().unwrap_or("unknown"); - let terminal_ua = codex_core::terminal::user_agent(); - let user_agent = format!( - "{originator}/0.0.0 ({os_type} {os_version}; {architecture}) {terminal_ua} ({DEFAULT_CLIENT_NAME}; 0.1.0)" - ); - - let received: GetUserAgentResponse = to_response(response)?; - let expected = GetUserAgentResponse { user_agent }; - - assert_eq!(received, expected); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/user_info.rs b/codex-rs/app-server/tests/suite/user_info.rs deleted file mode 100644 index 6a44f1a3ab..0000000000 --- a/codex-rs/app-server/tests/suite/user_info.rs +++ /dev/null @@ -1,46 +0,0 @@ -use anyhow::Result; -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::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::UserInfoResponse; -use codex_core::auth::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn user_info_returns_email_from_auth_json() -> Result<()> { - let codex_home = TempDir::new()?; - - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("access") - .refresh_token("refresh") - .email("user@example.com"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp.send_user_info_request().await?; - let response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let received: UserInfoResponse = to_response(response)?; - let expected = UserInfoResponse { - alleged_user_email: Some("user@example.com".to_string()), - }; - - assert_eq!(received, expected); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index 0c96800958..48ede78f40 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -131,6 +131,7 @@ async fn logout_account_removes_auth_and_notifies() -> Result<()> { payload.auth_mode.is_none(), "auth_method should be None after logout" ); + assert_eq!(payload.plan_type, None); assert!( !codex_home.path().join("auth.json").exists(), @@ -201,6 +202,7 @@ async fn set_auth_token_updates_account_and_notifies() -> Result<()> { bail!("unexpected notification: {parsed:?}"); }; assert_eq!(payload.auth_mode, Some(AuthMode::ChatgptAuthTokens)); + assert_eq!(payload.plan_type, Some(AccountPlanType::Pro)); let get_id = mcp .send_get_account_request(GetAccountParams { @@ -843,6 +845,7 @@ async fn login_account_api_key_succeeds_and_notifies() -> Result<()> { bail!("unexpected notification: {parsed:?}"); }; pretty_assertions::assert_eq!(payload.auth_mode, Some(AuthMode::ApiKey)); + pretty_assertions::assert_eq!(payload.plan_type, None); assert!(codex_home.path().join("auth.json").exists()); Ok(()) @@ -1227,3 +1230,45 @@ async fn get_account_with_chatgpt() -> Result<()> { assert_eq!(received, expected); Ok(()) } + +#[tokio::test] +async fn get_account_with_chatgpt_missing_plan_claim_returns_unknown() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + ..Default::default() + }, + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("access-chatgpt").email("user@example.com"), + AuthCredentialsStoreMode::File, + )?; + + let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let params = GetAccountParams { + refresh_token: false, + }; + let request_id = mcp.send_get_account_request(params).await?; + + let resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let received: GetAccountResponse = to_response(resp)?; + + let expected = GetAccountResponse { + account: Some(Account::Chatgpt { + email: "user@example.com".to_string(), + plan_type: AccountPlanType::Unknown, + }), + requires_openai_auth: true, + }; + assert_eq!(received, expected); + Ok(()) +} diff --git a/codex-rs/app-server/tests/suite/v2/analytics.rs b/codex-rs/app-server/tests/suite/v2/analytics.rs index 0d05d64465..e64287cb22 100644 --- a/codex-rs/app-server/tests/suite/v2/analytics.rs +++ b/codex-rs/app-server/tests/suite/v2/analytics.rs @@ -30,7 +30,7 @@ async fn app_server_default_analytics_disabled_without_flag() -> Result<()> { let provider = codex_core::otel_init::build_provider( &config, SERVICE_VERSION, - Some("codex_app_server"), + Some("codex-app-server"), false, ) .map_err(|err| anyhow::anyhow!(err.to_string()))?; @@ -55,7 +55,7 @@ async fn app_server_default_analytics_enabled_with_flag() -> Result<()> { let provider = codex_core::otel_init::build_provider( &config, SERVICE_VERSION, - Some("codex_app_server"), + Some("codex-app-server"), true, ) .map_err(|err| anyhow::anyhow!(err.to_string()))?; 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 a9bc14e932..72655b5afb 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -428,7 +428,7 @@ async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<( } #[tokio::test] -async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { +async fn list_apps_waits_for_accessible_data_before_emitting_directory_updates() -> Result<()> { let connectors = vec![ AppInfo { id: "alpha".to_string(), @@ -475,7 +475,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { codex_home.path(), ChatGptAuthFixture::new("chatgpt-token") .account_id("account-123") - .chatgpt_user_id("user-123") + .chatgpt_user_id("user-directory-first") .chatgpt_account_id("account-123"), AuthCredentialsStoreMode::File, )?; @@ -492,60 +492,14 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { }) .await?; - let expected_directory_first = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: false, - is_enabled: true, - }, - ]; - let expected_accessible_first = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - }]; - - let first_update = read_app_list_updated_notification(&mut mcp).await?; - // app/list emits an update after whichever async load finishes first. Even with - // a tools delay in this test, the accessible-tools path can return first if the - // process-global Codex Apps tools cache is warm from another test. + let maybe_update = timeout( + Duration::from_millis(150), + read_app_list_updated_notification(&mut mcp), + ) + .await; assert!( - first_update.data == expected_directory_first - || first_update.data == expected_accessible_first, - "unexpected first app/list update: {:#?}", - first_update.data + maybe_update.is_err(), + "unexpected directory-only app/list update before accessible apps loaded" ); let expected = vec![ @@ -579,8 +533,96 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { }, ]; - let second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(second_update.data, expected); + let update = read_app_list_updated_notification(&mut mcp).await?; + assert_eq!(update.data, expected); + + 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, expected); + assert!(next_cursor.is_none()); + + server_handle.abort(); + Ok(()) +} + +#[tokio::test] +async fn list_apps_does_not_emit_empty_interim_updates() -> Result<()> { + let connectors = vec![AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha 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, + }]; + let (server_url, server_handle) = start_apps_server_with_delays( + connectors.clone(), + Vec::new(), + Duration::from_millis(300), + 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-empty-interim") + .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: false, + }) + .await?; + + let maybe_update = timeout( + Duration::from_millis(150), + read_app_list_updated_notification(&mut mcp), + ) + .await; + assert!( + maybe_update.is_err(), + "unexpected empty interim app/list update" + ); + + let expected = vec![AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha connector".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), + is_accessible: false, + is_enabled: true, + }]; + + let update = read_app_list_updated_notification(&mut mcp).await?; + assert_eq!(update.data, expected); let response: JSONRPCResponse = timeout( DEFAULT_TIMEOUT, @@ -995,6 +1037,20 @@ async fn list_apps_force_refetch_patches_updates_from_cached_snapshots() -> Resu assert_eq!( first_update.data, vec![ + AppInfo { + id: "beta".to_string(), + name: "Beta App".to_string(), + description: Some("Beta v1".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), + is_accessible: true, + is_enabled: true, + }, AppInfo { id: "alpha".to_string(), name: "Alpha".to_string(), @@ -1009,23 +1065,19 @@ async fn list_apps_force_refetch_patches_updates_from_cached_snapshots() -> Resu is_accessible: false, is_enabled: true, }, - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: false, - is_enabled: true, - }, ] ); + let maybe_second_update = timeout( + Duration::from_millis(150), + read_app_list_updated_notification(&mut mcp), + ) + .await; + assert!( + maybe_second_update.is_err(), + "unexpected inaccessible-only app/list update during force refetch" + ); + let expected_final = vec![AppInfo { id: "alpha".to_string(), name: "Alpha".to_string(), diff --git a/codex-rs/app-server/tests/suite/v2/collaboration_mode_list.rs b/codex-rs/app-server/tests/suite/v2/collaboration_mode_list.rs index 4435542909..7c36827e6d 100644 --- a/codex-rs/app-server/tests/suite/v2/collaboration_mode_list.rs +++ b/codex-rs/app-server/tests/suite/v2/collaboration_mode_list.rs @@ -13,11 +13,10 @@ use app_test_support::McpProcess; use app_test_support::to_response; use codex_app_server_protocol::CollaborationModeListParams; use codex_app_server_protocol::CollaborationModeListResponse; +use codex_app_server_protocol::CollaborationModeMask; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_core::test_support::builtin_collaboration_mode_presets; -use codex_protocol::config_types::CollaborationModeMask; -use codex_protocol::config_types::ModeKind; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::time::timeout; @@ -33,7 +32,7 @@ async fn list_collaboration_modes_returns_presets() -> Result<()> { timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; let request_id = mcp - .send_list_collaboration_modes_request(CollaborationModeListParams {}) + .send_list_collaboration_modes_request(CollaborationModeListParams::default()) .await?; let response: JSONRPCResponse = timeout( @@ -45,28 +44,15 @@ async fn list_collaboration_modes_returns_presets() -> Result<()> { let CollaborationModeListResponse { data: items } = to_response::(response)?; - let expected = vec![plan_preset(), default_preset()]; + let expected: Vec = builtin_collaboration_mode_presets() + .into_iter() + .map(|preset| CollaborationModeMask { + name: preset.name, + mode: preset.mode, + model: preset.model, + reasoning_effort: preset.reasoning_effort, + }) + .collect(); assert_eq!(expected, items); Ok(()) } - -/// Builds the plan preset that the list response is expected to return. -/// -/// If the defaults change in the app server, this helper should be updated alongside the -/// contract, or the test will fail in ways that imply a regression in the API. -fn plan_preset() -> CollaborationModeMask { - let presets = builtin_collaboration_mode_presets(); - presets - .into_iter() - .find(|p| p.mode == Some(ModeKind::Plan)) - .unwrap() -} - -/// Builds the default preset that the list response is expected to return. -fn default_preset() -> CollaborationModeMask { - let presets = builtin_collaboration_mode_presets(); - presets - .into_iter() - .find(|p| p.mode == Some(ModeKind::Default)) - .unwrap() -} diff --git a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs index 0bbbc70b55..9799945383 100644 --- a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs +++ b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs @@ -174,6 +174,7 @@ pub(super) async fn send_request( id: RequestId::Integer(id), method: method.to_string(), params, + trace: None, }); send_jsonrpc(stream, message).await } 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 f4cd85a61d..52a597f66b 100644 --- a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs +++ b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs @@ -7,10 +7,15 @@ use app_test_support::to_response; use codex_app_server_protocol::DynamicToolCallOutputContentItem; use codex_app_server_protocol::DynamicToolCallParams; use codex_app_server_protocol::DynamicToolCallResponse; +use codex_app_server_protocol::DynamicToolCallStatus; use codex_app_server_protocol::DynamicToolSpec; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnStartParams; @@ -163,11 +168,12 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res ) .await??; let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + let thread_id = thread.id.clone(); // Start a turn so the tool call is emitted. let turn_req = mcp .send_turn_start_request(TurnStartParams { - thread_id: thread.id.clone(), + thread_id: thread_id.clone(), input: vec![V2UserInput::Text { text: "Run the tool".to_string(), text_elements: Vec::new(), @@ -181,6 +187,30 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res ) .await??; let TurnStartResponse { turn } = to_response::(turn_resp)?; + let turn_id = turn.id.clone(); + + let started = wait_for_dynamic_tool_started(&mut mcp, call_id).await?; + assert_eq!(started.thread_id, thread_id); + assert_eq!(started.turn_id, turn_id.clone()); + let ThreadItem::DynamicToolCall { + id, + tool, + arguments, + status, + content_items, + success, + duration_ms, + } = started.item + else { + panic!("expected dynamic tool call item"); + }; + assert_eq!(id, call_id); + assert_eq!(tool, tool_name); + assert_eq!(arguments, tool_args); + assert_eq!(status, DynamicToolCallStatus::InProgress); + assert_eq!(content_items, None); + assert_eq!(success, None); + assert_eq!(duration_ms, None); // Read the tool call request from the app server. let request = timeout( @@ -194,8 +224,8 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res }; let expected = DynamicToolCallParams { - thread_id: thread.id, - turn_id: turn.id, + thread_id: thread_id.clone(), + turn_id: turn_id.clone(), call_id: call_id.to_string(), tool: tool_name.to_string(), arguments: tool_args.clone(), @@ -212,6 +242,34 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res mcp.send_response(request_id, serde_json::to_value(response)?) .await?; + let completed = wait_for_dynamic_tool_completed(&mut mcp, call_id).await?; + assert_eq!(completed.thread_id, thread_id); + assert_eq!(completed.turn_id, turn_id); + let ThreadItem::DynamicToolCall { + id, + tool, + arguments, + status, + content_items, + success, + duration_ms, + } = completed.item + else { + panic!("expected dynamic tool call item"); + }; + assert_eq!(id, call_id); + assert_eq!(tool, tool_name); + assert_eq!(arguments, tool_args); + assert_eq!(status, DynamicToolCallStatus::Completed); + assert_eq!( + content_items, + Some(vec![DynamicToolCallOutputContentItem::InputText { + text: "dynamic-ok".to_string(), + }]) + ); + assert_eq!(success, Some(true)); + assert!(duration_ms.is_some()); + timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("turn/completed"), @@ -282,10 +340,11 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> 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.clone(), + thread_id: thread_id.clone(), input: vec![V2UserInput::Text { text: "Run the tool".to_string(), text_elements: Vec::new(), @@ -299,6 +358,11 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> Result<( ) .await??; let TurnStartResponse { turn } = to_response::(turn_resp)?; + let turn_id = turn.id.clone(); + + let started = wait_for_dynamic_tool_started(&mut mcp, call_id).await?; + assert_eq!(started.thread_id, thread_id.clone()); + assert_eq!(started.turn_id, turn_id.clone()); let request = timeout( DEFAULT_READ_TIMEOUT, @@ -311,8 +375,8 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> Result<( }; let expected = DynamicToolCallParams { - thread_id: thread.id, - turn_id: turn.id, + thread_id, + turn_id: turn_id.clone(), call_id: call_id.to_string(), tool: tool_name.to_string(), arguments: tool_args, @@ -346,6 +410,32 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> Result<( mcp.send_response(request_id, serde_json::to_value(response)?) .await?; + let completed = wait_for_dynamic_tool_completed(&mut mcp, call_id).await?; + assert_eq!(completed.thread_id, expected.thread_id.clone()); + assert_eq!(completed.turn_id, turn_id); + let ThreadItem::DynamicToolCall { + status, + content_items: completed_content_items, + success, + .. + } = completed.item + else { + panic!("expected dynamic tool call item"); + }; + assert_eq!(status, DynamicToolCallStatus::Completed); + assert_eq!( + completed_content_items, + Some(vec![ + DynamicToolCallOutputContentItem::InputText { + text: "dynamic-ok".to_string(), + }, + DynamicToolCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,AAA".to_string(), + }, + ]) + ); + assert_eq!(success, Some(true)); + timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("turn/completed"), @@ -432,6 +522,46 @@ fn function_call_output_raw_output(body: &Value, call_id: &str) -> Option .cloned() } +async fn wait_for_dynamic_tool_started( + mcp: &mut McpProcess, + call_id: &str, +) -> Result { + loop { + let notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("item/started"), + ) + .await??; + let Some(params) = notification.params else { + continue; + }; + let started: ItemStartedNotification = serde_json::from_value(params)?; + if matches!(&started.item, ThreadItem::DynamicToolCall { id, .. } if id == call_id) { + return Ok(started); + } + } +} + +async fn wait_for_dynamic_tool_completed( + mcp: &mut McpProcess, + call_id: &str, +) -> Result { + loop { + let notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("item/completed"), + ) + .await??; + let Some(params) = notification.params else { + continue; + }; + let completed: ItemCompletedNotification = serde_json::from_value(params)?; + if matches!(&completed.item, ThreadItem::DynamicToolCall { id, .. } if id == call_id) { + return Ok(completed); + } + } +} + fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { let config_toml = codex_home.join("config.toml"); std::fs::write( diff --git a/codex-rs/app-server/tests/suite/v2/initialize.rs b/codex-rs/app-server/tests/suite/v2/initialize.rs index 2edc83a7f4..de437c5bf5 100644 --- a/codex-rs/app-server/tests/suite/v2/initialize.rs +++ b/codex-rs/app-server/tests/suite/v2/initialize.rs @@ -1,16 +1,24 @@ use anyhow::Result; use app_test_support::McpProcess; +use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_mock_responses_server_sequence_unchecked; use app_test_support::to_response; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeResponse; use codex_app_server_protocol::JSONRPCMessage; +use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; 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 core_test_support::fs_wait; use pretty_assertions::assert_eq; +use serde_json::Value; use std::path::Path; +use std::time::Duration; use tempfile::TempDir; use tokio::time::timeout; @@ -178,11 +186,103 @@ async fn initialize_opt_out_notification_methods_filters_notifications() -> Resu Ok(()) } +#[tokio::test] +async fn turn_start_notify_payload_includes_initialize_client_name() -> Result<()> { + let responses = vec![create_final_assistant_message_sse_response("Done")?]; + let server = create_mock_responses_server_sequence_unchecked(responses).await; + let codex_home = TempDir::new()?; + let notify_script = codex_home.path().join("notify.py"); + std::fs::write( + ¬ify_script, + r#"from pathlib import Path +import sys + +payload_path = Path(__file__).with_name("notify.json") +tmp_path = payload_path.with_suffix(".json.tmp") +tmp_path.write_text(sys.argv[-1], encoding="utf-8") +tmp_path.replace(payload_path) +"#, + )?; + let notify_file = codex_home.path().join("notify.json"); + let notify_script = notify_script + .to_str() + .expect("notify script path should be valid UTF-8"); + create_config_toml_with_extra( + codex_home.path(), + &server.uri(), + "never", + &format!( + "notify = [\"python3\", {}]", + toml_basic_string(notify_script) + ), + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.initialize_with_client_info(ClientInfo { + name: "xcode".to_string(), + title: Some("Xcode".to_string()), + version: "1.0.0".to_string(), + }), + ) + .await??; + + let thread_req = mcp + .send_thread_start_request(ThreadStartParams::default()) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![V2UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let _: TurnStartResponse = to_response(turn_resp)?; + + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + fs_wait::wait_for_path_exists(¬ify_file, Duration::from_secs(5)).await?; + let payload_raw = tokio::fs::read_to_string(¬ify_file).await?; + let payload: Value = serde_json::from_str(&payload_raw)?; + assert_eq!(payload["client"], "xcode"); + + Ok(()) +} + // Helper to create a config.toml pointing at the mock model server. fn create_config_toml( codex_home: &Path, server_uri: &str, approval_policy: &str, +) -> std::io::Result<()> { + create_config_toml_with_extra(codex_home, server_uri, approval_policy, "") +} + +fn create_config_toml_with_extra( + codex_home: &Path, + server_uri: &str, + approval_policy: &str, + extra: &str, ) -> std::io::Result<()> { let config_toml = codex_home.join("config.toml"); std::fs::write( @@ -195,6 +295,8 @@ sandbox_mode = "read-only" model_provider = "mock_provider" +{extra} + [model_providers.mock_provider] name = "Mock provider for test" base_url = "{server_uri}/v1" @@ -205,3 +307,7 @@ stream_max_retries = 0 ), ) } + +fn toml_basic_string(value: &str) -> String { + format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) +} diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index 8afb1e3f40..cb3acb633d 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -19,7 +19,6 @@ mod realtime_conversation; mod request_user_input; mod review; mod safety_check_downgrade; -mod skill_approval; mod skills_list; mod thread_archive; mod thread_fork; @@ -31,6 +30,7 @@ mod thread_rollback; mod thread_start; mod thread_status; mod thread_unarchive; +mod thread_unsubscribe; mod turn_interrupt; mod turn_start; mod turn_start_zsh_fork; diff --git a/codex-rs/app-server/tests/suite/v2/model_list.rs b/codex-rs/app-server/tests/suite/v2/model_list.rs index 7597212490..eba8905a77 100644 --- a/codex-rs/app-server/tests/suite/v2/model_list.rs +++ b/codex-rs/app-server/tests/suite/v2/model_list.rs @@ -1,7 +1,6 @@ use std::time::Duration; use anyhow::Result; -use anyhow::anyhow; use app_test_support::McpProcess; use app_test_support::to_response; use app_test_support::write_models_cache; @@ -10,6 +9,7 @@ use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::Model; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; +use codex_app_server_protocol::ModelUpgradeInfo; use codex_app_server_protocol::ReasoningEffortOption; use codex_app_server_protocol::RequestId; use codex_protocol::openai_models::ModelPreset; @@ -25,6 +25,13 @@ fn model_from_preset(preset: &ModelPreset) -> Model { id: preset.id.clone(), model: preset.model.clone(), upgrade: preset.upgrade.as_ref().map(|upgrade| upgrade.id.clone()), + upgrade_info: preset.upgrade.as_ref().map(|upgrade| ModelUpgradeInfo { + model: upgrade.id.clone(), + upgrade_copy: upgrade.upgrade_copy.clone(), + model_link: upgrade.model_link.clone(), + migration_markdown: upgrade.migration_markdown.clone(), + }), + availability_nux: preset.availability_nux.clone().map(Into::into), display_name: preset.display_name.clone(), description: preset.description.clone(), hidden: !preset.show_in_picker, @@ -136,100 +143,45 @@ async fn list_models_pagination_works() -> Result<()> { timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - let first_request = mcp - .send_list_models_request(ModelListParams { - limit: Some(1), - cursor: None, - include_hidden: None, - }) - .await?; - - let first_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(first_request)), - ) - .await??; - - let ModelListResponse { - data: first_items, - next_cursor: first_cursor, - } = to_response::(first_response)?; - let expected_models = expected_visible_models(); + let mut cursor = None; + let mut items = Vec::new(); - assert_eq!(first_items.len(), 1); - assert_eq!(first_items[0].id, expected_models[0].id); - let next_cursor = first_cursor.ok_or_else(|| anyhow!("cursor for second page"))?; + for _ in 0..expected_models.len() { + let request_id = mcp + .send_list_models_request(ModelListParams { + limit: Some(1), + cursor: cursor.clone(), + include_hidden: None, + }) + .await?; - let second_request = mcp - .send_list_models_request(ModelListParams { - limit: Some(1), - cursor: Some(next_cursor.clone()), - include_hidden: None, - }) - .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; - let second_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(second_request)), - ) - .await??; + let ModelListResponse { + data: page_items, + next_cursor, + } = to_response::(response)?; - let ModelListResponse { - data: second_items, - next_cursor: second_cursor, - } = to_response::(second_response)?; + assert_eq!(page_items.len(), 1); + items.extend(page_items); - assert_eq!(second_items.len(), 1); - assert_eq!(second_items[0].id, expected_models[1].id); - let third_cursor = second_cursor.ok_or_else(|| anyhow!("cursor for third page"))?; + if let Some(next_cursor) = next_cursor { + cursor = Some(next_cursor); + } else { + assert_eq!(items, expected_models); + return Ok(()); + } + } - let third_request = mcp - .send_list_models_request(ModelListParams { - limit: Some(1), - cursor: Some(third_cursor.clone()), - include_hidden: None, - }) - .await?; - - let third_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(third_request)), - ) - .await??; - - let ModelListResponse { - data: third_items, - next_cursor: third_cursor, - } = to_response::(third_response)?; - - assert_eq!(third_items.len(), 1); - assert_eq!(third_items[0].id, expected_models[2].id); - let fourth_cursor = third_cursor.ok_or_else(|| anyhow!("cursor for fourth page"))?; - - let fourth_request = mcp - .send_list_models_request(ModelListParams { - limit: Some(1), - cursor: Some(fourth_cursor.clone()), - include_hidden: None, - }) - .await?; - - let fourth_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(fourth_request)), - ) - .await??; - - let ModelListResponse { - data: fourth_items, - next_cursor: fourth_cursor, - } = to_response::(fourth_response)?; - - assert_eq!(fourth_items.len(), 1); - assert_eq!(fourth_items[0].id, expected_models[3].id); - assert!(fourth_cursor.is_none()); - Ok(()) + panic!( + "model pagination did not terminate after {} pages", + expected_models.len() + ); } #[tokio::test] diff --git a/codex-rs/app-server/tests/suite/v2/rate_limits.rs b/codex-rs/app-server/tests/suite/v2/rate_limits.rs index 6f66d7bff7..51048202f6 100644 --- a/codex-rs/app-server/tests/suite/v2/rate_limits.rs +++ b/codex-rs/app-server/tests/suite/v2/rate_limits.rs @@ -6,7 +6,7 @@ use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginApiKeyParams; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RateLimitWindow; use codex_app_server_protocol::RequestId; @@ -221,17 +221,14 @@ async fn get_account_rate_limits_returns_snapshot() -> Result<()> { } async fn login_with_api_key(mcp: &mut McpProcess, api_key: &str) -> Result<()> { - let request_id = mcp - .send_login_api_key_request(LoginApiKeyParams { - api_key: api_key.to_string(), - }) - .await?; - - timeout( + let request_id = mcp.send_login_account_api_key_request(api_key).await?; + let response: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_response_message(RequestId::Integer(request_id)), ) .await??; + let login: LoginAccountResponse = to_response(response)?; + assert_eq!(login, LoginAccountResponse::ApiKey {}); Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs index f2664848ca..71150d7126 100644 --- a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs +++ b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs @@ -5,6 +5,7 @@ use app_test_support::create_mock_responses_server_sequence_unchecked; use app_test_support::to_response; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadRealtimeAppendAudioParams; use codex_app_server_protocol::ThreadRealtimeAppendAudioResponse; @@ -42,20 +43,17 @@ async fn realtime_conversation_streams_v2_notifications() -> Result<()> { let responses_server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; let realtime_server = start_websocket_server(vec![vec![ - vec![json!({ - "type": "session.created", - "session": { "id": "sess_backend" } - })], vec![json!({ "type": "session.updated", - "session": { "backend_prompt": "backend prompt" } + "session": { "id": "sess_backend", "instructions": "backend prompt" } })], + vec![], vec![ json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24_000, - "num_channels": 1, + "channels": 1, "samples_per_channel": 512 }), json!({ @@ -84,6 +82,7 @@ async fn realtime_conversation_streams_v2_notifications() -> Result<()> { let mut mcp = McpProcess::new(codex_home.path()).await?; mcp.initialize().await?; + login_with_api_key(&mut mcp, "sk-test-key").await?; let thread_start_request_id = mcp .send_thread_start_request(ThreadStartParams::default()) @@ -182,7 +181,7 @@ async fn realtime_conversation_streams_v2_notifications() -> Result<()> { assert_eq!(connection.len(), 3); assert_eq!( connection[0].body_json()["type"].as_str(), - Some("session.create") + Some("session.update") ); let mut request_types = [ connection[1].body_json()["type"] @@ -199,7 +198,7 @@ async fn realtime_conversation_streams_v2_notifications() -> Result<()> { request_types, [ "conversation.item.create".to_string(), - "response.input_audio.delta".to_string(), + "input_audio_buffer.append".to_string(), ] ); @@ -214,8 +213,8 @@ async fn realtime_conversation_stop_emits_closed_notification() -> Result<()> { let responses_server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; let realtime_server = start_websocket_server(vec![vec![ vec![json!({ - "type": "session.created", - "session": { "id": "sess_backend" } + "type": "session.updated", + "session": { "id": "sess_backend", "instructions": "backend prompt" } })], vec![], ]]) @@ -231,6 +230,7 @@ async fn realtime_conversation_stop_emits_closed_notification() -> Result<()> { let mut mcp = McpProcess::new(codex_home.path()).await?; mcp.initialize().await?; + login_with_api_key(&mut mcp, "sk-test-key").await?; let thread_start_request_id = mcp .send_thread_start_request(ThreadStartParams::default()) @@ -349,6 +349,19 @@ async fn read_notification(mcp: &mut McpProcess, method: &s Ok(serde_json::from_value(params)?) } +async fn login_with_api_key(mcp: &mut McpProcess, api_key: &str) -> Result<()> { + let request_id = mcp.send_login_account_api_key_request(api_key).await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let login: LoginAccountResponse = to_response(response)?; + assert_eq!(login, LoginAccountResponse::ApiKey {}); + + Ok(()) +} + fn create_config_toml( codex_home: &Path, responses_server_uri: &str, 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 4ee76bdca2..f77ddfb4f7 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 @@ -4,9 +4,11 @@ use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_mock_responses_server_sequence; use app_test_support::create_request_user_input_sse_response; use app_test_support::to_response; +use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::ServerRequestResolvedNotification; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnStartParams; @@ -86,6 +88,7 @@ async fn request_user_input_round_trip() -> Result<()> { assert_eq!(params.turn_id, turn.id); assert_eq!(params.item_id, "call1"); assert_eq!(params.questions.len(), 1); + let resolved_request_id = request_id.clone(); mcp.send_response( request_id, @@ -96,17 +99,31 @@ async fn request_user_input_round_trip() -> Result<()> { }), ) .await?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; + let mut saw_resolved = false; + loop { + let message = timeout(DEFAULT_READ_TIMEOUT, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notification) = message else { + continue; + }; + match notification.method.as_str() { + "serverRequest/resolved" => { + let resolved: ServerRequestResolvedNotification = serde_json::from_value( + notification + .params + .clone() + .expect("serverRequest/resolved params"), + )?; + assert_eq!(resolved.thread_id, thread.id); + assert_eq!(resolved.request_id, resolved_request_id); + saw_resolved = true; + } + "turn/completed" => { + assert!(saw_resolved, "serverRequest/resolved should arrive first"); + break; + } + _ => {} + } + } Ok(()) } @@ -123,9 +140,6 @@ sandbox_mode = "read-only" model_provider = "mock_provider" -[features] -collaboration_modes = true - [model_providers.mock_provider] name = "Mock provider for test" base_url = "{server_uri}/v1" diff --git a/codex-rs/app-server/tests/suite/v2/review.rs b/codex-rs/app-server/tests/suite/v2/review.rs index 262b13969e..6febbaf52a 100644 --- a/codex-rs/app-server/tests/suite/v2/review.rs +++ b/codex-rs/app-server/tests/suite/v2/review.rs @@ -8,6 +8,7 @@ use app_test_support::to_response; use codex_app_server_protocol::ItemCompletedNotification; use codex_app_server_protocol::ItemStartedNotification; use codex_app_server_protocol::JSONRPCError; +use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; @@ -19,9 +20,12 @@ use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::ThreadStartedNotification; +use codex_app_server_protocol::ThreadStatusChangedNotification; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; +use pretty_assertions::assert_eq; use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; @@ -301,6 +305,31 @@ async fn review_start_with_detached_delivery_returns_new_thread_id() -> Result<( "detached review should run on a different thread" ); + let deadline = tokio::time::Instant::now() + DEFAULT_READ_TIMEOUT; + let notification = loop { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + let message = timeout(remaining, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notification) = message else { + continue; + }; + if notification.method == "thread/status/changed" { + let status_changed: ThreadStatusChangedNotification = + serde_json::from_value(notification.params.expect("params must be present"))?; + if status_changed.thread_id == review_thread_id { + anyhow::bail!( + "detached review threads should be introduced without a preceding thread/status/changed" + ); + } + continue; + } + if notification.method == "thread/started" { + break notification; + } + }; + let started: ThreadStartedNotification = + serde_json::from_value(notification.params.expect("params must be present"))?; + assert_eq!(started.thread.id, review_thread_id); + Ok(()) } @@ -389,6 +418,11 @@ async fn start_default_thread(mcp: &mut McpProcess) -> Result { ) .await??; let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/started"), + ) + .await??; Ok(thread.id) } diff --git a/codex-rs/app-server/tests/suite/v2/skill_approval.rs b/codex-rs/app-server/tests/suite/v2/skill_approval.rs deleted file mode 100644 index a86e459768..0000000000 --- a/codex-rs/app-server/tests/suite/v2/skill_approval.rs +++ /dev/null @@ -1,138 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::create_mock_responses_server_sequence; -use app_test_support::to_response; -use app_test_support::write_mock_responses_config_toml; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerRequest; -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_core::features::Feature; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::BTreeMap; -use std::fs; -use std::path::Path; -use tokio::time::timeout; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); - -fn write_skill_with_script( - home: &Path, - name: &str, - script_body: &str, -) -> Result { - let skill_dir = home.join("skills").join(name); - let scripts_dir = skill_dir.join("scripts"); - fs::create_dir_all(&scripts_dir)?; - fs::write( - skill_dir.join("SKILL.md"), - format!("---\nname: {name}\ndescription: {name} skill\n---\n"), - )?; - let script_path = scripts_dir.join("run.py"); - fs::write(&script_path, script_body)?; - Ok(script_path) -} - -fn shell_command_response(tool_call_id: &str, command: &str) -> Result { - let arguments = serde_json::to_string(&json!({ - "command": command, - "timeout_ms": 500, - }))?; - Ok(responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_function_call(tool_call_id, "shell_command", &arguments), - responses::ev_completed("resp-1"), - ])) -} - -fn command_for_script(script_path: &Path) -> Result { - let runner = if cfg!(windows) { "python" } else { "python3" }; - let script_path = script_path.to_string_lossy().into_owned(); - Ok(shlex::try_join([runner, script_path.as_str()])?) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn skill_request_approval_round_trip_on_shell_command_skill_script_exec() -> Result<()> { - let codex_home = tempfile::TempDir::new()?; - let script_path = write_skill_with_script(codex_home.path(), "demo", "print('hello')")?; - let tool_call_id = "skill-call"; - let command = command_for_script(&script_path)?; - let server = create_mock_responses_server_sequence(vec![ - shell_command_response(tool_call_id, &command)?, - create_final_assistant_message_sse_response("done")?, - ]) - .await; - write_mock_responses_config_toml( - codex_home.path(), - &server.uri(), - &BTreeMap::from([(Feature::SkillApproval, true)]), - 8192, - Some(false), - "mock_provider", - "compact", - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let thread_start_id = mcp - .send_thread_start_request(ThreadStartParams { - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - let thread_start_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(thread_start_id)), - ) - .await??; - let ThreadStartResponse { thread, .. } = to_response(thread_start_resp)?; - - let turn_start_id = mcp - .send_turn_start_request(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![V2UserInput::Text { - text: "ask something".to_string(), - text_elements: Vec::new(), - }], - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - let turn_start_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(turn_start_id)), - ) - .await??; - let TurnStartResponse { .. } = to_response::(turn_start_resp)?; - - let server_req = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_request_message(), - ) - .await??; - let ServerRequest::SkillRequestApproval { request_id, params } = server_req else { - panic!("expected SkillRequestApproval request, got: {server_req:?}"); - }; - - assert_eq!(params.item_id, tool_call_id); - assert_eq!(params.skill_name, "demo"); - - mcp.send_response(request_id, serde_json::json!({ "decision": "approve" })) - .await?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; - - Ok(()) -} 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 d7aa60f2bb..20fd6fd884 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_archive.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_archive.rs @@ -8,8 +8,13 @@ use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadArchiveParams; use codex_app_server_protocol::ThreadArchiveResponse; use codex_app_server_protocol::ThreadArchivedNotification; +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::ThreadStatus; +use codex_app_server_protocol::ThreadUnarchiveParams; +use codex_app_server_protocol::ThreadUnarchiveResponse; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::UserInput; @@ -155,6 +160,140 @@ async fn thread_archive_requires_materialized_rollout() -> Result<()> { Ok(()) } +#[tokio::test] +async fn thread_archive_clears_stale_subscriptions_before_resume() -> 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 mut primary = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??; + + let start_id = primary + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let start_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(start_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; + + let turn_start_id = primary + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![UserInput::Text { + text: "materialize".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_start_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(turn_start_id)), + ) + .await??; + let _: TurnStartResponse = to_response::(turn_start_response)?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("turn/completed"), + ) + .await??; + primary.clear_message_buffer(); + + let mut secondary = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, secondary.initialize()).await??; + + let archive_id = primary + .send_thread_archive_request(ThreadArchiveParams { + thread_id: thread.id.clone(), + }) + .await?; + let archive_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(archive_id)), + ) + .await??; + let _: ThreadArchiveResponse = to_response::(archive_resp)?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("thread/archived"), + ) + .await??; + + let unarchive_id = primary + .send_thread_unarchive_request(ThreadUnarchiveParams { + thread_id: thread.id.clone(), + }) + .await?; + let unarchive_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(unarchive_id)), + ) + .await??; + let _: ThreadUnarchiveResponse = to_response::(unarchive_resp)?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("thread/unarchived"), + ) + .await??; + primary.clear_message_buffer(); + + let resume_id = secondary + .send_thread_resume_request(ThreadResumeParams { + thread_id: thread.id.clone(), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + secondary.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let resume: ThreadResumeResponse = to_response::(resume_resp)?; + assert_eq!(resume.thread.status, ThreadStatus::Idle); + primary.clear_message_buffer(); + secondary.clear_message_buffer(); + + let resumed_turn_id = secondary + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![UserInput::Text { + text: "secondary turn".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let resumed_turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + secondary.read_stream_until_response_message(RequestId::Integer(resumed_turn_id)), + ) + .await??; + let _: TurnStartResponse = to_response::(resumed_turn_resp)?; + + assert!( + timeout( + std::time::Duration::from_millis(250), + primary.read_stream_until_notification_message("turn/started"), + ) + .await + .is_err() + ); + + timeout( + DEFAULT_READ_TIMEOUT, + secondary.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + Ok(()) +} + fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { let config_toml = codex_home.join("config.toml"); std::fs::write(config_toml, config_contents(server_uri)) 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 a6f9942171..1f19ae8b97 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -4,7 +4,7 @@ use app_test_support::create_fake_rollout; use app_test_support::create_mock_responses_server_repeating_assistant; use app_test_support::to_response; use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCNotification; +use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SessionSource; @@ -15,6 +15,7 @@ use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::ThreadStartedNotification; use codex_app_server_protocol::ThreadStatus; +use codex_app_server_protocol::ThreadStatusChangedNotification; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput; use pretty_assertions::assert_eq; @@ -124,11 +125,27 @@ async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> { } // A corresponding thread/started notification should arrive. - let notif: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("thread/started"), - ) - .await??; + let deadline = tokio::time::Instant::now() + DEFAULT_READ_TIMEOUT; + let notif = loop { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + let message = timeout(remaining, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notif) = message else { + continue; + }; + if notif.method == "thread/status/changed" { + let status_changed: ThreadStatusChangedNotification = + serde_json::from_value(notif.params.expect("params must be present"))?; + if status_changed.thread_id == thread.id { + anyhow::bail!( + "thread/fork should introduce the thread without a preceding thread/status/changed" + ); + } + continue; + } + if notif.method == "thread/started" { + break notif; + } + }; let started_params = notif.params.clone().expect("params must be present"); let started_thread_json = started_params .get("thread") 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 5d2211d3c8..dcc411538e 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_read.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_read.rs @@ -10,6 +10,7 @@ use codex_app_server_protocol::SessionSource; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadListParams; 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::ThreadResumeParams; @@ -78,6 +79,7 @@ async fn thread_read_returns_summary_without_turns() -> Result<()> { assert_eq!(thread.id, conversation_id); assert_eq!(thread.preview, preview); assert_eq!(thread.model_provider, "mock_provider"); + assert!(!thread.ephemeral, "stored rollouts should not be ephemeral"); assert!(thread.path.as_ref().expect("thread path").is_absolute()); assert_eq!(thread.cwd, PathBuf::from("/")); assert_eq!(thread.cli_version, "0.0.0"); @@ -219,25 +221,6 @@ async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> { let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - // `thread/name/set` operates on loaded threads (via ThreadManager). A rollout existing on disk - // is not enough; we must `thread/resume` first to load it into the running server. - let pre_resume_id = mcp - .send_thread_resume_request(ThreadResumeParams { - thread_id: conversation_id.clone(), - ..Default::default() - }) - .await?; - let pre_resume_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(pre_resume_id)), - ) - .await??; - let ThreadResumeResponse { - thread: pre_resumed, - .. - } = to_response::(pre_resume_resp)?; - assert_eq!(pre_resumed.id, conversation_id); - // Set a user-facing thread title. let new_name = "My renamed thread"; let set_id = mcp @@ -252,6 +235,15 @@ async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> { ) .await??; let _: ThreadSetNameResponse = to_response::(set_resp)?; + let notification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/name/updated"), + ) + .await??; + let notification: ThreadNameUpdatedNotification = + serde_json::from_value(notification.params.expect("thread/name/updated params"))?; + assert_eq!(notification.thread_id, conversation_id); + assert_eq!(notification.thread_name.as_deref(), Some(new_name)); // Read should now surface `thread.name`, and the wire payload must include `name`. let read_id = mcp @@ -278,6 +270,11 @@ async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> { Some(new_name), "thread/read must serialize `thread.name` on the wire" ); + assert_eq!( + thread_json.get("ephemeral").and_then(Value::as_bool), + Some(false), + "thread/read must serialize `thread.ephemeral` on the wire" + ); // List should also surface the name. let list_id = mcp @@ -317,6 +314,11 @@ async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> { Some(new_name), "thread/list must serialize `thread.name` on the wire" ); + assert_eq!( + listed_json.get("ephemeral").and_then(Value::as_bool), + Some(false), + "thread/list must serialize `thread.ephemeral` on the wire" + ); // Resume should also surface the name. let resume_id = mcp @@ -345,6 +347,11 @@ async fn thread_name_set_is_reflected_in_read_list_and_resume() -> Result<()> { Some(new_name), "thread/resume must serialize `thread.name` on the wire" ); + assert_eq!( + resumed_json.get("ephemeral").and_then(Value::as_bool), + Some(false), + "thread/resume must serialize `thread.ephemeral` on the wire" + ); Ok(()) } 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 15bc4012eb..9628a78164 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -1,13 +1,26 @@ use anyhow::Result; use app_test_support::McpProcess; +use app_test_support::create_apply_patch_sse_response; use app_test_support::create_fake_rollout_with_text_elements; +use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_mock_responses_server_repeating_assistant; +use app_test_support::create_mock_responses_server_sequence; +use app_test_support::create_shell_command_sse_response; use app_test_support::rollout_path; use app_test_support::to_response; use chrono::Utc; +use codex_app_server_protocol::AskForApproval; +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::ItemStartedNotification; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::PatchApplyStatus; +use codex_app_server_protocol::PatchChangeKind; use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::SessionSource; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadResumeParams; @@ -639,6 +652,306 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R Ok(()) } +#[tokio::test] +async fn thread_resume_replays_pending_command_execution_request_approval() -> Result<()> { + let responses = vec![ + create_final_assistant_message_sse_response("seeded")?, + create_shell_command_sse_response( + vec![ + "python3".to_string(), + "-c".to_string(), + "print(42)".to_string(), + ], + None, + Some(5000), + "call-1", + )?, + create_final_assistant_message_sse_response("done")?, + ]; + let server = create_mock_responses_server_sequence(responses).await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let mut primary = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??; + + let start_id = primary + .send_thread_start_request(ThreadStartParams { + model: Some("gpt-5.1-codex-max".to_string()), + ..Default::default() + }) + .await?; + let start_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(start_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; + + let seed_turn_id = primary + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![UserInput::Text { + text: "seed history".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(seed_turn_id)), + ) + .await??; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("turn/completed"), + ) + .await??; + primary.clear_message_buffer(); + + let running_turn_id = primary + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![UserInput::Text { + text: "run command".to_string(), + text_elements: Vec::new(), + }], + approval_policy: Some(AskForApproval::UnlessTrusted), + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(running_turn_id)), + ) + .await??; + + let original_request = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::CommandExecutionRequestApproval { .. } = &original_request else { + panic!("expected CommandExecutionRequestApproval request, got {original_request:?}"); + }; + + let resume_id = primary + .send_thread_resume_request(ThreadResumeParams { + thread_id: thread.id.clone(), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let ThreadResumeResponse { + thread: resumed_thread, + .. + } = to_response::(resume_resp)?; + assert_eq!(resumed_thread.id, thread.id); + assert!( + resumed_thread + .turns + .iter() + .any(|turn| matches!(turn.status, TurnStatus::InProgress)) + ); + + let replayed_request = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_request_message(), + ) + .await??; + pretty_assertions::assert_eq!(replayed_request, original_request); + + let ServerRequest::CommandExecutionRequestApproval { request_id, .. } = replayed_request else { + panic!("expected CommandExecutionRequestApproval request"); + }; + primary + .send_response( + request_id, + serde_json::to_value(CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Accept, + })?, + ) + .await?; + + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + Ok(()) +} + +#[tokio::test] +async fn thread_resume_replays_pending_file_change_request_approval() -> Result<()> { + let tmp = TempDir::new()?; + let codex_home = tmp.path().join("codex_home"); + std::fs::create_dir(&codex_home)?; + let workspace = tmp.path().join("workspace"); + std::fs::create_dir(&workspace)?; + + let patch = r#"*** Begin Patch +*** Add File: README.md ++new line +*** End Patch +"#; + let responses = vec![ + create_final_assistant_message_sse_response("seeded")?, + create_apply_patch_sse_response(patch, "patch-call")?, + create_final_assistant_message_sse_response("done")?, + ]; + let server = create_mock_responses_server_sequence(responses).await; + create_config_toml(&codex_home, &server.uri())?; + + let mut primary = McpProcess::new(&codex_home).await?; + timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??; + + let start_id = primary + .send_thread_start_request(ThreadStartParams { + model: Some("gpt-5.1-codex-max".to_string()), + cwd: Some(workspace.to_string_lossy().into_owned()), + ..Default::default() + }) + .await?; + let start_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(start_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; + + let seed_turn_id = primary + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![UserInput::Text { + text: "seed history".to_string(), + text_elements: Vec::new(), + }], + cwd: Some(workspace.clone()), + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(seed_turn_id)), + ) + .await??; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("turn/completed"), + ) + .await??; + primary.clear_message_buffer(); + + let running_turn_id = primary + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![UserInput::Text { + text: "apply patch".to_string(), + text_elements: Vec::new(), + }], + cwd: Some(workspace.clone()), + approval_policy: Some(AskForApproval::UnlessTrusted), + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(running_turn_id)), + ) + .await??; + + let original_started = timeout(DEFAULT_READ_TIMEOUT, async { + loop { + let notification = primary + .read_stream_until_notification_message("item/started") + .await?; + let started: ItemStartedNotification = + serde_json::from_value(notification.params.clone().expect("item/started params"))?; + if let ThreadItem::FileChange { .. } = started.item { + return Ok::(started.item); + } + } + }) + .await??; + let expected_readme_path = workspace.join("README.md"); + let expected_file_change = ThreadItem::FileChange { + id: "patch-call".to_string(), + changes: vec![codex_app_server_protocol::FileUpdateChange { + path: expected_readme_path.to_string_lossy().into_owned(), + kind: PatchChangeKind::Add, + diff: "new line\n".to_string(), + }], + status: PatchApplyStatus::InProgress, + }; + assert_eq!(original_started, expected_file_change); + + let original_request = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::FileChangeRequestApproval { .. } = &original_request else { + panic!("expected FileChangeRequestApproval request, got {original_request:?}"); + }; + primary.clear_message_buffer(); + + let resume_id = primary + .send_thread_resume_request(ThreadResumeParams { + thread_id: thread.id.clone(), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let ThreadResumeResponse { + thread: resumed_thread, + .. + } = to_response::(resume_resp)?; + assert_eq!(resumed_thread.id, thread.id); + assert!( + resumed_thread + .turns + .iter() + .any(|turn| matches!(turn.status, TurnStatus::InProgress)) + ); + + let replayed_request = timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_request_message(), + ) + .await??; + assert_eq!(replayed_request, original_request); + + let ServerRequest::FileChangeRequestApproval { request_id, .. } = replayed_request else { + panic!("expected FileChangeRequestApproval request"); + }; + primary + .send_response( + request_id, + serde_json::to_value(FileChangeRequestApprovalResponse { + decision: FileChangeApprovalDecision::Accept, + })?, + ) + .await?; + + timeout( + DEFAULT_READ_TIMEOUT, + primary.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + Ok(()) +} + #[tokio::test] async fn thread_resume_with_overrides_defers_updated_at_until_turn_start() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index c0b84fe42f..57eddd195a 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -3,16 +3,18 @@ use app_test_support::McpProcess; use app_test_support::create_mock_responses_server_repeating_assistant; use app_test_support::to_response; use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCNotification; +use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::ThreadStartedNotification; use codex_app_server_protocol::ThreadStatus; +use codex_app_server_protocol::ThreadStatusChangedNotification; use codex_core::config::set_project_trust_level; use codex_protocol::config_types::TrustLevel; use codex_protocol::openai_models::ReasoningEffort; +use pretty_assertions::assert_eq; use serde_json::Value; use std::path::Path; use tempfile::TempDir; @@ -62,6 +64,10 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> { thread.created_at > 0, "created_at should be a positive UNIX timestamp" ); + assert!( + !thread.ephemeral, + "new persistent threads should not be ephemeral" + ); assert_eq!(thread.status, ThreadStatus::Idle); let thread_path = thread.path.clone().expect("thread path should be present"); assert!(thread_path.is_absolute(), "thread path should be absolute"); @@ -80,14 +86,35 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> { Some(&Value::Null), "new threads should serialize `name: null`" ); + assert_eq!( + thread_json.get("ephemeral").and_then(Value::as_bool), + Some(false), + "new persistent threads should serialize `ephemeral: false`" + ); assert_eq!(thread.name, None); // A corresponding thread/started notification should arrive. - let notif: JSONRPCNotification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("thread/started"), - ) - .await??; + let deadline = tokio::time::Instant::now() + DEFAULT_READ_TIMEOUT; + let notif = loop { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + let message = timeout(remaining, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notif) = message else { + continue; + }; + if notif.method == "thread/status/changed" { + let status_changed: ThreadStatusChangedNotification = + serde_json::from_value(notif.params.expect("params must be present"))?; + if status_changed.thread_id == thread.id { + anyhow::bail!( + "thread/start should introduce the thread without a preceding thread/status/changed" + ); + } + continue; + } + if notif.method == "thread/started" { + break notif; + } + }; let started_params = notif.params.clone().expect("params must be present"); let started_thread_json = started_params .get("thread") @@ -98,6 +125,13 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> { Some(&Value::Null), "thread/started should serialize `name: null` for new threads" ); + assert_eq!( + started_thread_json + .get("ephemeral") + .and_then(Value::as_bool), + Some(false), + "thread/started should serialize `ephemeral: false` for new persistent threads" + ); let started: ThreadStartedNotification = serde_json::from_value(notif.params.expect("params must be present"))?; assert_eq!(started.thread, thread); @@ -196,11 +230,25 @@ async fn thread_start_ephemeral_remains_pathless() -> Result<()> { mcp.read_stream_until_response_message(RequestId::Integer(req_id)), ) .await??; + let resp_result = resp.result.clone(); let ThreadStartResponse { thread, .. } = to_response::(resp)?; + assert!( + thread.ephemeral, + "ephemeral threads should be marked explicitly" + ); assert_eq!( thread.path, None, "ephemeral threads should not expose a path" ); + let thread_json = resp_result + .get("thread") + .and_then(Value::as_object) + .expect("thread/start result.thread must be an object"); + assert_eq!( + thread_json.get("ephemeral").and_then(Value::as_bool), + Some(true), + "ephemeral threads should serialize `ephemeral: true`" + ); Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs new file mode 100644 index 0000000000..f16ef8bb06 --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs @@ -0,0 +1,383 @@ +use anyhow::Context; +use anyhow::Result; +use app_test_support::McpProcess; +use app_test_support::create_mock_responses_server_repeating_assistant; +use app_test_support::create_mock_responses_server_sequence; +use app_test_support::create_shell_command_sse_response; +use app_test_support::to_response; +use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCNotification; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadLoadedListParams; +use codex_app_server_protocol::ThreadLoadedListResponse; +use codex_app_server_protocol::ThreadReadParams; +use codex_app_server_protocol::ThreadReadResponse; +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::ThreadStatus; +use codex_app_server_protocol::ThreadStatusChangedNotification; +use codex_app_server_protocol::ThreadUnsubscribeParams; +use codex_app_server_protocol::ThreadUnsubscribeResponse; +use codex_app_server_protocol::ThreadUnsubscribeStatus; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_app_server_protocol::UserInput as V2UserInput; +use core_test_support::responses; +use pretty_assertions::assert_eq; +use tempfile::TempDir; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +#[tokio::test] +async fn thread_unsubscribe_unloads_thread_and_emits_thread_closed_notification() -> 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 mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_id = start_thread(&mut mcp).await?; + + let unsubscribe_id = mcp + .send_thread_unsubscribe_request(ThreadUnsubscribeParams { + thread_id: thread_id.clone(), + }) + .await?; + let unsubscribe_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(unsubscribe_id)), + ) + .await??; + let unsubscribe = to_response::(unsubscribe_resp)?; + assert_eq!(unsubscribe.status, ThreadUnsubscribeStatus::Unsubscribed); + + let closed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/closed"), + ) + .await??; + let parsed: ServerNotification = closed_notif.try_into()?; + let ServerNotification::ThreadClosed(payload) = parsed else { + anyhow::bail!("expected thread/closed notification"); + }; + assert_eq!(payload.thread_id, thread_id); + + let status_changed = wait_for_thread_status_not_loaded(&mut mcp, &payload.thread_id).await?; + assert_eq!(status_changed.thread_id, payload.thread_id); + assert_eq!(status_changed.status, ThreadStatus::NotLoaded); + + let list_id = mcp + .send_thread_loaded_list_request(ThreadLoadedListParams::default()) + .await?; + let list_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(list_id)), + ) + .await??; + let ThreadLoadedListResponse { data, next_cursor } = + to_response::(list_resp)?; + assert_eq!(data, Vec::::new()); + assert_eq!(next_cursor, None); + + Ok(()) +} + +#[tokio::test] +async fn thread_unsubscribe_during_turn_interrupts_turn_and_emits_thread_closed() -> Result<()> { + #[cfg(target_os = "windows")] + let shell_command = vec![ + "powershell".to_string(), + "-Command".to_string(), + "Start-Sleep -Seconds 10".to_string(), + ]; + #[cfg(not(target_os = "windows"))] + let shell_command = vec!["sleep".to_string(), "10".to_string()]; + + let tmp = TempDir::new()?; + let codex_home = tmp.path().join("codex_home"); + std::fs::create_dir(&codex_home)?; + let working_directory = tmp.path().join("workdir"); + std::fs::create_dir(&working_directory)?; + + let server = create_mock_responses_server_sequence(vec![create_shell_command_sse_response( + shell_command.clone(), + Some(&working_directory), + Some(10_000), + "call_sleep", + )?]) + .await; + create_config_toml(&codex_home, &server.uri())?; + + let mut mcp = McpProcess::new(&codex_home).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_id = start_thread(&mut mcp).await?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread_id.clone(), + input: vec![V2UserInput::Text { + text: "run sleep".to_string(), + text_elements: Vec::new(), + }], + cwd: Some(working_directory), + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let _: TurnStartResponse = to_response::(turn_resp)?; + + timeout( + DEFAULT_READ_TIMEOUT, + wait_for_command_execution_item_started(&mut mcp), + ) + .await??; + + let unsubscribe_id = mcp + .send_thread_unsubscribe_request(ThreadUnsubscribeParams { + thread_id: thread_id.clone(), + }) + .await?; + let unsubscribe_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(unsubscribe_id)), + ) + .await??; + let unsubscribe = to_response::(unsubscribe_resp)?; + assert_eq!(unsubscribe.status, ThreadUnsubscribeStatus::Unsubscribed); + + let closed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/closed"), + ) + .await??; + let parsed: ServerNotification = closed_notif.try_into()?; + let ServerNotification::ThreadClosed(payload) = parsed else { + anyhow::bail!("expected thread/closed notification"); + }; + assert_eq!(payload.thread_id, thread_id); + + Ok(()) +} + +#[tokio::test] +async fn thread_unsubscribe_clears_cached_status_before_resume() -> Result<()> { + let server = responses::start_mock_server().await; + let _response_mock = responses::mount_sse_once( + &server, + responses::sse_failed("resp-1", "server_error", "simulated failure"), + ) + .await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_id = start_thread(&mut mcp).await?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread_id.clone(), + input: vec![V2UserInput::Text { + text: "fail this turn".to_string(), + text_elements: Vec::new(), + }], + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let _: TurnStartResponse = to_response::(turn_resp)?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("error"), + ) + .await??; + + let read_id = mcp + .send_thread_read_request(ThreadReadParams { + thread_id: thread_id.clone(), + include_turns: false, + }) + .await?; + let read_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(read_id)), + ) + .await??; + let ThreadReadResponse { thread } = to_response::(read_resp)?; + assert_eq!(thread.status, ThreadStatus::SystemError); + + let unsubscribe_id = mcp + .send_thread_unsubscribe_request(ThreadUnsubscribeParams { + thread_id: thread_id.clone(), + }) + .await?; + let unsubscribe_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(unsubscribe_id)), + ) + .await??; + let unsubscribe = to_response::(unsubscribe_resp)?; + assert_eq!(unsubscribe.status, ThreadUnsubscribeStatus::Unsubscribed); + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/closed"), + ) + .await??; + + let resume_id = mcp + .send_thread_resume_request(ThreadResumeParams { + thread_id, + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let resume: ThreadResumeResponse = to_response::(resume_resp)?; + assert_eq!(resume.thread.status, ThreadStatus::Idle); + + Ok(()) +} + +#[tokio::test] +async fn thread_unsubscribe_reports_not_loaded_after_thread_is_unloaded() -> 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 mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_id = start_thread(&mut mcp).await?; + + let first_unsubscribe_id = mcp + .send_thread_unsubscribe_request(ThreadUnsubscribeParams { + thread_id: thread_id.clone(), + }) + .await?; + let first_unsubscribe_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(first_unsubscribe_id)), + ) + .await??; + let first_unsubscribe = to_response::(first_unsubscribe_resp)?; + assert_eq!( + first_unsubscribe.status, + ThreadUnsubscribeStatus::Unsubscribed + ); + + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/closed"), + ) + .await??; + + let second_unsubscribe_id = mcp + .send_thread_unsubscribe_request(ThreadUnsubscribeParams { thread_id }) + .await?; + let second_unsubscribe_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(second_unsubscribe_id)), + ) + .await??; + let second_unsubscribe = to_response::(second_unsubscribe_resp)?; + assert_eq!( + second_unsubscribe.status, + ThreadUnsubscribeStatus::NotLoaded + ); + + Ok(()) +} + +async fn wait_for_command_execution_item_started(mcp: &mut McpProcess) -> Result<()> { + loop { + let started_notif = mcp + .read_stream_until_notification_message("item/started") + .await?; + let started_params = started_notif.params.context("item/started params")?; + let started: ItemStartedNotification = serde_json::from_value(started_params)?; + if let ThreadItem::CommandExecution { .. } = started.item { + return Ok(()); + } + } +} + +async fn wait_for_thread_status_not_loaded( + mcp: &mut McpProcess, + thread_id: &str, +) -> Result { + loop { + let status_changed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("thread/status/changed"), + ) + .await??; + let status_changed_params = status_changed_notif + .params + .context("thread/status/changed params must be present")?; + let status_changed: ThreadStatusChangedNotification = + serde_json::from_value(status_changed_params)?; + if status_changed.thread_id == thread_id && status_changed.status == ThreadStatus::NotLoaded + { + return Ok(status_changed); + } + } +} + +fn create_config_toml(codex_home: &std::path::Path, server_uri: &str) -> std::io::Result<()> { + let config_toml = codex_home.join("config.toml"); + std::fs::write( + config_toml, + format!( + r#" +model = "mock-model" +approval_policy = "never" +sandbox_mode = "danger-full-access" + +model_provider = "mock_provider" + +[model_providers.mock_provider] +name = "Mock provider for test" +base_url = "{server_uri}/v1" +wire_api = "responses" +request_max_retries = 0 +stream_max_retries = 0 +"# + ), + ) +} + +async fn start_thread(mcp: &mut McpProcess) -> Result { + let req_id = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(req_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(resp)?; + Ok(thread.id) +} 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 486e915f6f..8f944dca07 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs @@ -8,6 +8,8 @@ use app_test_support::to_response; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::ServerRequestResolvedNotification; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnCompletedNotification; @@ -48,7 +50,7 @@ async fn turn_interrupt_aborts_running_turn() -> Result<()> { "call_sleep", )?]) .await; - create_config_toml(&codex_home, &server.uri())?; + create_config_toml(&codex_home, &server.uri(), "never")?; let mut mcp = McpProcess::new(&codex_home).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; @@ -120,15 +122,134 @@ async fn turn_interrupt_aborts_running_turn() -> Result<()> { Ok(()) } +#[tokio::test] +async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<()> { + #[cfg(target_os = "windows")] + let shell_command = vec![ + "powershell".to_string(), + "-Command".to_string(), + "Start-Sleep -Seconds 10".to_string(), + ]; + #[cfg(not(target_os = "windows"))] + let shell_command = vec!["sleep".to_string(), "10".to_string()]; + + let tmp = TempDir::new()?; + let codex_home = tmp.path().join("codex_home"); + std::fs::create_dir(&codex_home)?; + let working_directory = tmp.path().join("workdir"); + std::fs::create_dir(&working_directory)?; + + let server = create_mock_responses_server_sequence(vec![create_shell_command_sse_response( + shell_command.clone(), + Some(&working_directory), + Some(10_000), + "call_sleep_approval", + )?]) + .await; + create_config_toml(&codex_home, &server.uri(), "untrusted")?; + + let mut mcp = McpProcess::new(&codex_home).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![V2UserInput::Text { + text: "run sleep".to_string(), + text_elements: Vec::new(), + }], + cwd: Some(working_directory), + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let TurnStartResponse { turn } = to_response::(turn_resp)?; + + let request = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::CommandExecutionRequestApproval { request_id, params } = request else { + panic!("expected CommandExecutionRequestApproval request"); + }; + assert_eq!(params.item_id, "call_sleep_approval"); + assert_eq!(params.thread_id, thread.id); + assert_eq!(params.turn_id, turn.id); + + let interrupt_id = mcp + .send_turn_interrupt_request(TurnInterruptParams { + thread_id: thread.id.clone(), + turn_id: turn.id.clone(), + }) + .await?; + let interrupt_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(interrupt_id)), + ) + .await??; + let _resp: TurnInterruptResponse = to_response::(interrupt_resp)?; + + let resolved_notification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("serverRequest/resolved"), + ) + .await??; + let resolved: ServerRequestResolvedNotification = serde_json::from_value( + resolved_notification + .params + .clone() + .expect("serverRequest/resolved params must be present"), + )?; + assert_eq!(resolved.thread_id, thread.id); + assert_eq!(resolved.request_id, request_id); + + let completed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let completed: TurnCompletedNotification = serde_json::from_value( + completed_notif + .params + .expect("turn/completed params must be present"), + )?; + assert_eq!(completed.thread_id, thread.id); + assert_eq!(completed.turn.status, TurnStatus::Interrupted); + + Ok(()) +} + // Helper to create a config.toml pointing at the mock model server. -fn create_config_toml(codex_home: &std::path::Path, server_uri: &str) -> std::io::Result<()> { +fn create_config_toml( + codex_home: &std::path::Path, + server_uri: &str, + approval_policy: &str, +) -> std::io::Result<()> { let config_toml = codex_home.join("config.toml"); std::fs::write( config_toml, format!( r#" model = "mock-model" -approval_policy = "never" +approval_policy = "{approval_policy}" sandbox_mode = "danger-full-access" model_provider = "mock_provider" 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 eaa017d6ae..0888d0f23e 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -9,6 +9,8 @@ use app_test_support::create_mock_responses_server_sequence_unchecked; use app_test_support::create_shell_command_sse_response; use app_test_support::format_with_current_shell_display; use app_test_support::to_response; +use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE; +use codex_app_server::INVALID_PARAMS_ERROR_CODE; use codex_app_server_protocol::ByteRange; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::CommandExecutionApprovalDecision; @@ -19,12 +21,15 @@ use codex_app_server_protocol::FileChangeOutputDeltaNotification; use codex_app_server_protocol::FileChangeRequestApprovalResponse; use codex_app_server_protocol::ItemCompletedNotification; use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCError; +use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::PatchApplyStatus; use codex_app_server_protocol::PatchChangeKind; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::ServerRequestResolvedNotification; use codex_app_server_protocol::TextElement; use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadStartParams; @@ -45,10 +50,13 @@ use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use core_test_support::responses; use core_test_support::skip_if_no_network; use pretty_assertions::assert_eq; +use serde_json::json; use std::collections::BTreeMap; +use std::collections::HashMap; use std::path::Path; use tempfile::TempDir; use tokio::time::timeout; @@ -221,6 +229,143 @@ async fn turn_start_emits_user_message_item_with_text_elements() -> Result<()> { Ok(()) } +#[tokio::test] +async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> { + let responses = vec![create_final_assistant_message_sse_response("Done")?]; + let server = create_mock_responses_server_sequence_unchecked(responses).await; + + let codex_home = TempDir::new()?; + create_config_toml( + codex_home.path(), + &server.uri(), + "never", + &BTreeMap::from([(Feature::Personality, true)]), + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![ + V2UserInput::Text { + text: "x".repeat(MAX_USER_INPUT_TEXT_CHARS), + text_elements: Vec::new(), + }, + V2UserInput::Mention { + name: "Demo App".to_string(), + path: "app://demo-app".to_string(), + }, + ], + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let TurnStartResponse { turn } = to_response::(turn_resp)?; + assert_eq!(turn.status, TurnStatus::InProgress); + + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + Ok(()) +} + +#[tokio::test] +async fn turn_start_rejects_combined_oversized_text_input() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml( + codex_home.path(), + "http://localhost/unused", + "never", + &BTreeMap::from([(Feature::Personality, true)]), + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let first = "x".repeat(MAX_USER_INPUT_TEXT_CHARS / 2); + let second = "y".repeat(MAX_USER_INPUT_TEXT_CHARS / 2 + 1); + let actual_chars = first.chars().count() + second.chars().count(); + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + input: vec![ + V2UserInput::Text { + text: first, + text_elements: Vec::new(), + }, + V2UserInput::Text { + text: second, + text_elements: Vec::new(), + }, + ], + ..Default::default() + }) + .await?; + let err: JSONRPCError = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(turn_req)), + ) + .await??; + + assert_eq!(err.error.code, INVALID_PARAMS_ERROR_CODE); + assert_eq!( + err.error.message, + format!("Input exceeds the maximum length of {MAX_USER_INPUT_TEXT_CHARS} characters.") + ); + let data = err.error.data.expect("expected structured error data"); + assert_eq!(data["input_error_code"], INPUT_TOO_LARGE_ERROR_CODE); + assert_eq!(data["max_chars"], MAX_USER_INPUT_TEXT_CHARS); + assert_eq!(data["actual_chars"], actual_chars); + + let turn_started = tokio::time::timeout( + std::time::Duration::from_millis(250), + mcp.read_stream_until_notification_message("turn/started"), + ) + .await; + assert!( + turn_started.is_err(), + "did not expect a turn/started notification for rejected input" + ); + + Ok(()) +} + #[tokio::test] async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<()> { // Provide a mock server and config so model wiring is valid. @@ -289,6 +434,21 @@ async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<( started.turn.status, codex_app_server_protocol::TurnStatus::InProgress ); + assert_eq!(started.turn.id, turn.id); + + let completed_notif: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + let completed: TurnCompletedNotification = serde_json::from_value( + completed_notif + .params + .expect("turn/completed params must be present"), + )?; + assert_eq!(completed.thread_id, thread.id); + assert_eq!(completed.turn.id, turn.id); + assert_eq!(completed.turn.status, TurnStatus::Completed); // Send a second turn that exercises the overrides path: change the model. let turn_req2 = mcp @@ -312,25 +472,30 @@ async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<( // Ensure the second turn has a different id than the first. assert_ne!(turn.id, turn2.id); - // Expect a second turn/started notification as well. - let _notif2: JSONRPCNotification = timeout( + let notif2: JSONRPCNotification = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("turn/started"), ) .await??; + let started2: TurnStartedNotification = + serde_json::from_value(notif2.params.expect("params must be present"))?; + assert_eq!(started2.thread_id, thread.id); + assert_eq!(started2.turn.id, turn2.id); + assert_eq!(started2.turn.status, TurnStatus::InProgress); - let completed_notif: JSONRPCNotification = timeout( + let completed_notif2: JSONRPCNotification = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("turn/completed"), ) .await??; - let completed: TurnCompletedNotification = serde_json::from_value( - completed_notif + let completed2: TurnCompletedNotification = serde_json::from_value( + completed_notif2 .params .expect("turn/completed params must be present"), )?; - assert_eq!(completed.thread_id, thread.id); - assert_eq!(completed.turn.status, TurnStatus::Completed); + assert_eq!(completed2.thread_id, thread.id); + assert_eq!(completed2.turn.id, turn2.id); + assert_eq!(completed2.turn.status, TurnStatus::Completed); Ok(()) } @@ -352,7 +517,7 @@ async fn turn_start_accepts_collaboration_mode_override_v2() -> Result<()> { codex_home.path(), &server.uri(), "never", - &BTreeMap::default(), + &BTreeMap::from([(Feature::DefaultModeRequestUserInput, true)]), )?; let mut mcp = McpProcess::new(codex_home.path()).await?; @@ -412,7 +577,92 @@ async fn turn_start_accepts_collaboration_mode_override_v2() -> Result<()> { let payload = request.body_json(); assert_eq!(payload["model"].as_str(), Some("mock-model-collab")); let payload_text = payload.to_string(); - assert!(payload_text.contains("The `request_user_input` tool is unavailable in Default mode.")); + assert!(payload_text.contains("The `request_user_input` tool is available in Default mode.")); + + Ok(()) +} + +#[tokio::test] +async fn turn_start_uses_thread_feature_overrides_for_collaboration_mode_instructions_v2() +-> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let body = responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_assistant_message("msg-1", "Done"), + responses::ev_completed("resp-1"), + ]); + let response_mock = responses::mount_sse_once(&server, body).await; + + let codex_home = TempDir::new()?; + create_config_toml( + codex_home.path(), + &server.uri(), + "never", + &BTreeMap::default(), + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("gpt-5.2-codex".to_string()), + config: Some(HashMap::from([( + "features.default_mode_request_user_input".to_string(), + json!(true), + )])), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let collaboration_mode = CollaborationMode { + mode: ModeKind::Default, + settings: Settings { + model: "mock-model-collab".to_string(), + reasoning_effort: Some(ReasoningEffort::High), + developer_instructions: None, + }, + }; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![V2UserInput::Text { + text: "Hello".to_string(), + text_elements: Vec::new(), + }], + model: Some("mock-model-override".to_string()), + effort: Some(ReasoningEffort::Low), + summary: Some(ReasoningSummary::Auto), + output_schema: None, + collaboration_mode: Some(collaboration_mode), + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let _turn: TurnStartResponse = to_response::(turn_resp)?; + + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let request = response_mock.single_request(); + let payload_text = request.body_json().to_string(); + assert!(payload_text.contains("The `request_user_input` tool is available in Default mode.")); Ok(()) } @@ -843,6 +1093,7 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { panic!("expected CommandExecutionRequestApproval request"); }; assert_eq!(params.item_id, "call1"); + let resolved_request_id = request_id.clone(); // Approve and wait for task completion mcp.send_response( @@ -852,16 +1103,31 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { })?, ) .await?; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("codex/event/task_complete"), - ) - .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; + let mut saw_resolved = false; + loop { + let message = timeout(DEFAULT_READ_TIMEOUT, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notification) = message else { + continue; + }; + match notification.method.as_str() { + "serverRequest/resolved" => { + let resolved: ServerRequestResolvedNotification = serde_json::from_value( + notification + .params + .clone() + .expect("serverRequest/resolved params"), + )?; + assert_eq!(resolved.thread_id, thread.id); + assert_eq!(resolved.request_id, resolved_request_id); + saw_resolved = true; + } + "turn/completed" => { + assert!(saw_resolved, "serverRequest/resolved should arrive first"); + break; + } + _ => {} + } + } // Second turn with approval_policy=never should not elicit approval let second_turn_id = mcp @@ -1119,6 +1385,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { model: Some("mock-model".to_string()), effort: Some(ReasoningEffort::Medium), summary: Some(ReasoningSummary::Auto), + service_tier: None, personality: None, output_schema: None, collaboration_mode: None, @@ -1150,6 +1417,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { model: Some("mock-model".to_string()), effort: Some(ReasoningEffort::Medium), summary: Some(ReasoningSummary::Auto), + service_tier: None, personality: None, output_schema: None, collaboration_mode: None, @@ -1299,6 +1567,7 @@ async fn turn_start_file_change_approval_v2() -> Result<()> { assert_eq!(params.item_id, "patch-call"); assert_eq!(params.thread_id, thread.id); assert_eq!(params.turn_id, turn.id); + let resolved_request_id = request_id.clone(); let expected_readme_path = workspace.join("README.md"); let expected_readme_path = expected_readme_path.to_string_lossy().into_owned(); pretty_assertions::assert_eq!( @@ -1317,18 +1586,49 @@ async fn turn_start_file_change_approval_v2() -> Result<()> { })?, ) .await?; - - let output_delta_notif = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("item/fileChange/outputDelta"), - ) - .await??; - let output_delta: FileChangeOutputDeltaNotification = serde_json::from_value( - output_delta_notif - .params - .clone() - .expect("item/fileChange/outputDelta params"), - )?; + let mut saw_resolved = false; + let mut output_delta: Option = None; + let mut completed_file_change: Option = None; + while !(output_delta.is_some() && completed_file_change.is_some()) { + let message = timeout(DEFAULT_READ_TIMEOUT, mcp.read_next_message()).await??; + let JSONRPCMessage::Notification(notification) = message else { + continue; + }; + match notification.method.as_str() { + "serverRequest/resolved" => { + let resolved: ServerRequestResolvedNotification = serde_json::from_value( + notification + .params + .clone() + .expect("serverRequest/resolved params"), + )?; + assert_eq!(resolved.thread_id, thread.id); + assert_eq!(resolved.request_id, resolved_request_id); + saw_resolved = true; + } + "item/fileChange/outputDelta" => { + assert!(saw_resolved, "serverRequest/resolved should arrive first"); + let notification: FileChangeOutputDeltaNotification = serde_json::from_value( + notification + .params + .clone() + .expect("item/fileChange/outputDelta params"), + )?; + output_delta = Some(notification); + } + "item/completed" => { + let completed: ItemCompletedNotification = serde_json::from_value( + notification.params.clone().expect("item/completed params"), + )?; + if let ThreadItem::FileChange { .. } = completed.item { + assert!(saw_resolved, "serverRequest/resolved should arrive first"); + completed_file_change = Some(completed.item); + } + } + _ => {} + } + } + let output_delta = output_delta.expect("file change output delta should be observed"); assert_eq!(output_delta.thread_id, thread.id); assert_eq!(output_delta.turn_id, turn.id); assert_eq!(output_delta.item_id, "patch-call"); @@ -1338,38 +1638,23 @@ async fn turn_start_file_change_approval_v2() -> Result<()> { output_delta.delta ); - let completed_file_change = timeout(DEFAULT_READ_TIMEOUT, async { - loop { - let completed_notif = mcp - .read_stream_until_notification_message("item/completed") - .await?; - let completed: ItemCompletedNotification = serde_json::from_value( - completed_notif - .params - .clone() - .expect("item/completed params"), - )?; - if let ThreadItem::FileChange { .. } = completed.item { - return Ok::(completed.item); - } - } - }) - .await??; + let completed_file_change = + completed_file_change.expect("file change completion should be observed"); let ThreadItem::FileChange { ref id, status, .. } = completed_file_change else { unreachable!("loop ensures we break on file change items"); }; assert_eq!(id, "patch-call"); assert_eq!(status, PatchApplyStatus::Completed); + let readme_contents = std::fs::read_to_string(expected_readme_path)?; + assert_eq!(readme_contents, "new line\n"); + timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("codex/event/task_complete"), ) .await??; - let readme_contents = std::fs::read_to_string(expected_readme_path)?; - assert_eq!(readme_contents, "new line\n"); - Ok(()) } 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 340a5e156c..bdbb283432 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 @@ -13,6 +13,7 @@ use app_test_support::create_mock_responses_server_sequence; use app_test_support::create_mock_responses_server_sequence_unchecked; use app_test_support::create_shell_command_sse_response; use app_test_support::to_response; +use codex_app_server_protocol::CommandAction; use codex_app_server_protocol::CommandExecutionApprovalDecision; use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; use codex_app_server_protocol::CommandExecutionStatus; @@ -542,7 +543,10 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() CommandExecutionApprovalDecision::Cancel, ]; let mut target_decision_index = 0; - while target_decision_index < target_decisions.len() { + let first_file_str = first_file.to_string_lossy().into_owned(); + let second_file_str = second_file.to_string_lossy().into_owned(); + let parent_shell_hint = format!("&& {}", &first_file_str); + while target_decision_index < target_decisions.len() || !saw_parent_approval { let server_req = timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_request_message(), @@ -558,16 +562,21 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() .command .as_deref() .expect("approval command should be present"); - let is_target_subcommand = (approval_command.starts_with("/bin/rm ") - || approval_command.starts_with("/usr/bin/rm ")) - && (approval_command.contains(&first_file.display().to_string()) - || approval_command.contains(&second_file.display().to_string())); + let has_first_file = approval_command.contains(&first_file_str); + let has_second_file = approval_command.contains(&second_file_str); + let mentions_rm_binary = + approval_command.contains("/bin/rm ") || approval_command.contains("/usr/bin/rm "); + let has_rm_action = params.command_actions.as_ref().is_some_and(|actions| { + actions.iter().any(|action| match action { + CommandAction::Read { name, .. } => name == "rm", + CommandAction::Unknown { command } => command.contains("rm"), + _ => false, + }) + }); + let is_target_subcommand = + (has_first_file != has_second_file) && (has_rm_action || mentions_rm_binary); + if is_target_subcommand { - assert!( - approval_command.contains(&first_file.display().to_string()) - || approval_command.contains(&second_file.display().to_string()), - "expected zsh subcommand approval for one of the rm commands, got: {approval_command}" - ); approved_subcommand_ids.push( params .approval_id @@ -577,7 +586,9 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() approved_subcommand_strings.push(approval_command.to_string()); } let is_parent_approval = approval_command.contains(&zsh_path.display().to_string()) - && approval_command.contains(&shell_command); + && (approval_command.contains(&shell_command) + || (has_first_file && has_second_file) + || approval_command.contains(&parent_shell_hint)); let decision = if is_target_subcommand { let decision = target_decisions[target_decision_index].clone(); target_decision_index += 1; 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 779e77577b..61a8a9794c 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_steer.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_steer.rs @@ -6,6 +6,8 @@ use app_test_support::create_mock_responses_server_sequence; use app_test_support::create_mock_responses_server_sequence_unchecked; use app_test_support::create_shell_command_sse_response; use app_test_support::to_response; +use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE; +use codex_app_server::INVALID_PARAMS_ERROR_CODE; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; @@ -17,6 +19,7 @@ use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnSteerParams; use codex_app_server_protocol::TurnSteerResponse; use codex_app_server_protocol::UserInput as V2UserInput; +use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use tempfile::TempDir; use tokio::time::timeout; @@ -67,6 +70,109 @@ async fn turn_steer_requires_active_turn() -> Result<()> { Ok(()) } +#[tokio::test] +async fn turn_steer_rejects_oversized_text_input() -> Result<()> { + #[cfg(target_os = "windows")] + let shell_command = vec![ + "powershell".to_string(), + "-Command".to_string(), + "Start-Sleep -Seconds 10".to_string(), + ]; + #[cfg(not(target_os = "windows"))] + let shell_command = vec!["sleep".to_string(), "10".to_string()]; + + let tmp = TempDir::new()?; + let codex_home = tmp.path().join("codex_home"); + std::fs::create_dir(&codex_home)?; + 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( + shell_command.clone(), + Some(&working_directory), + Some(10_000), + "call_sleep", + )?]) + .await; + create_config_toml(&codex_home, &server.uri())?; + + let mut mcp = McpProcess::new(&codex_home).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![V2UserInput::Text { + text: "run sleep".to_string(), + text_elements: Vec::new(), + }], + cwd: Some(working_directory.clone()), + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + let TurnStartResponse { turn } = to_response::(turn_resp)?; + + let _task_started: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("codex/event/task_started"), + ) + .await??; + + let oversized_input = "x".repeat(MAX_USER_INPUT_TEXT_CHARS + 1); + let steer_req = mcp + .send_turn_steer_request(TurnSteerParams { + thread_id: thread.id.clone(), + input: vec![V2UserInput::Text { + text: oversized_input.clone(), + text_elements: Vec::new(), + }], + expected_turn_id: turn.id.clone(), + }) + .await?; + let steer_err: JSONRPCError = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(steer_req)), + ) + .await??; + + assert_eq!(steer_err.error.code, INVALID_PARAMS_ERROR_CODE); + assert_eq!( + steer_err.error.message, + format!("Input exceeds the maximum length of {MAX_USER_INPUT_TEXT_CHARS} characters.") + ); + let data = steer_err + .error + .data + .expect("expected structured error data"); + assert_eq!(data["input_error_code"], INPUT_TOO_LARGE_ERROR_CODE); + assert_eq!(data["max_chars"], MAX_USER_INPUT_TEXT_CHARS); + assert_eq!(data["actual_chars"], oversized_input.chars().count()); + + mcp.interrupt_turn_and_wait_for_aborted(thread.id, turn.id, DEFAULT_READ_TIMEOUT) + .await?; + + Ok(()) +} + #[tokio::test] async fn turn_steer_returns_active_turn_id() -> Result<()> { #[cfg(target_os = "windows")] diff --git a/codex-rs/artifact-presentation/BUILD.bazel b/codex-rs/artifact-presentation/BUILD.bazel new file mode 100644 index 0000000000..d89e395b3f --- /dev/null +++ b/codex-rs/artifact-presentation/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "artifact-presentation", + crate_name = "codex_artifact_presentation", +) diff --git a/codex-rs/artifact-presentation/Cargo.toml b/codex-rs/artifact-presentation/Cargo.toml new file mode 100644 index 0000000000..898beb40f0 --- /dev/null +++ b/codex-rs/artifact-presentation/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "codex-artifact-presentation" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +name = "codex_artifact_presentation" +path = "src/lib.rs" + +[lints] +workspace = true + +[dependencies] +base64 = { workspace = true } +image = { workspace = true, features = ["jpeg", "png"] } +ppt-rs = { workspace = true } +reqwest = { workspace = true, features = ["blocking"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +uuid = { workspace = true, features = ["v4"] } +zip = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tiny_http = { workspace = true } diff --git a/codex-rs/artifact-presentation/src/lib.rs b/codex-rs/artifact-presentation/src/lib.rs new file mode 100644 index 0000000000..34bca50a91 --- /dev/null +++ b/codex-rs/artifact-presentation/src/lib.rs @@ -0,0 +1,6 @@ +mod presentation_artifact; + +#[cfg(test)] +mod tests; + +pub use presentation_artifact::*; diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/api.rs b/codex-rs/artifact-presentation/src/presentation_artifact/api.rs new file mode 100644 index 0000000000..5680bf97fe --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/api.rs @@ -0,0 +1,249 @@ +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use image::GenericImageView; +use image::ImageFormat; +use image::codecs::jpeg::JpegEncoder; +use image::imageops::FilterType; +use ppt_rs::Chart; +use ppt_rs::ChartSeries; +use ppt_rs::ChartType; +use ppt_rs::Hyperlink as PptHyperlink; +use ppt_rs::HyperlinkAction as PptHyperlinkAction; +use ppt_rs::Image; +use ppt_rs::Presentation; +use ppt_rs::Shape; +use ppt_rs::ShapeFill; +use ppt_rs::ShapeLine; +use ppt_rs::ShapeType; +use ppt_rs::SlideContent; +use ppt_rs::SlideLayout; +use ppt_rs::TableBuilder; +use ppt_rs::TableCell; +use ppt_rs::TableRow; +use ppt_rs::generator::ArrowSize; +use ppt_rs::generator::ArrowType; +use ppt_rs::generator::CellAlign; +use ppt_rs::generator::Connector; +use ppt_rs::generator::ConnectorLine; +use ppt_rs::generator::ConnectorType; +use ppt_rs::generator::LineDash; +use ppt_rs::generator::generate_image_content_type; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; +use std::collections::BTreeSet; +use std::collections::HashMap; +use std::collections::HashSet; +use std::io::Cursor; +use std::io::Read; +use std::io::Seek; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use thiserror::Error; +use uuid::Uuid; +use zip::ZipArchive; +use zip::ZipWriter; +use zip::write::SimpleFileOptions; + +const POINT_TO_EMU: u32 = 12_700; +const DEFAULT_SLIDE_WIDTH_POINTS: u32 = 720; +const DEFAULT_SLIDE_HEIGHT_POINTS: u32 = 540; +const DEFAULT_IMPORTED_TITLE_LEFT: u32 = 36; +const DEFAULT_IMPORTED_TITLE_TOP: u32 = 24; +const DEFAULT_IMPORTED_TITLE_WIDTH: u32 = 648; +const DEFAULT_IMPORTED_TITLE_HEIGHT: u32 = 48; +const DEFAULT_IMPORTED_CONTENT_LEFT: u32 = 48; +const DEFAULT_IMPORTED_CONTENT_TOP: u32 = 96; +const DEFAULT_IMPORTED_CONTENT_WIDTH: u32 = 624; +const DEFAULT_IMPORTED_CONTENT_HEIGHT: u32 = 324; + +#[derive(Debug, Error)] +pub enum PresentationArtifactError { + #[error("missing `artifact_id` for action `{action}`")] + MissingArtifactId { action: String }, + #[error("unknown artifact id `{artifact_id}` for action `{action}`")] + UnknownArtifactId { action: String, artifact_id: String }, + #[error("unknown action `{0}`")] + UnknownAction(String), + #[error("invalid args for action `{action}`: {message}")] + InvalidArgs { action: String, message: String }, + #[error("unsupported feature for action `{action}`: {message}")] + UnsupportedFeature { action: String, message: String }, + #[error("failed to import PPTX `{path}`: {message}")] + ImportFailed { path: PathBuf, message: String }, + #[error("failed to export PPTX `{path}`: {message}")] + ExportFailed { path: PathBuf, message: String }, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct PresentationArtifactRequest { + pub artifact_id: Option, + pub action: String, + #[serde(default)] + pub args: Value, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PresentationArtifactToolRequest { + pub artifact_id: Option, + pub actions: Vec, +} + +#[derive(Debug, Clone)] +pub struct PresentationArtifactExecutionRequest { + pub artifact_id: Option, + pub requests: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PresentationArtifactToolAction { + pub action: String, + #[serde(default)] + pub args: Value, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathAccessKind { + Read, + Write, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PathAccessRequirement { + pub action: String, + pub kind: PathAccessKind, + pub path: PathBuf, +} + +impl PresentationArtifactRequest { + pub fn is_mutating(&self) -> bool { + !is_read_only_action(&self.action) + } + + pub fn required_path_accesses( + &self, + cwd: &Path, + ) -> Result, PresentationArtifactError> { + let access = match self.action.as_str() { + "import_pptx" => { + let args: ImportPptxArgs = parse_args(&self.action, &self.args)?; + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Read, + path: resolve_path(cwd, &args.path), + }] + } + "export_pptx" => { + let args: ExportPptxArgs = parse_args(&self.action, &self.args)?; + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Write, + path: resolve_path(cwd, &args.path), + }] + } + "export_preview" => { + let args: ExportPreviewArgs = parse_args(&self.action, &self.args)?; + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Write, + path: resolve_path(cwd, &args.path), + }] + } + "add_image" => { + let args: AddImageArgs = parse_args(&self.action, &self.args)?; + match args.image_source()? { + ImageInputSource::Path(path) => vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Read, + path: resolve_path(cwd, &path), + }], + ImageInputSource::DataUrl(_) + | ImageInputSource::Blob(_) + | ImageInputSource::Uri(_) + | ImageInputSource::Placeholder => Vec::new(), + } + } + "replace_image" => { + let args: ReplaceImageArgs = parse_args(&self.action, &self.args)?; + match ( + &args.path, + &args.data_url, + &args.blob, + &args.uri, + &args.prompt, + ) { + (Some(path), None, None, None, None) => vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Read, + path: resolve_path(cwd, path), + }], + (None, Some(_), None, None, None) + | (None, None, Some(_), None, None) + | (None, None, None, Some(_), None) + | (None, None, None, None, Some(_)) => Vec::new(), + _ => { + return Err(PresentationArtifactError::InvalidArgs { + action: self.action.clone(), + message: + "provide exactly one of `path`, `data_url`, `blob`, or `uri`, or provide `prompt` for a placeholder image" + .to_string(), + }); + } + } + } + _ => Vec::new(), + }; + Ok(access) + } +} + +impl PresentationArtifactToolRequest { + pub fn is_mutating(&self) -> Result { + Ok(self.actions.iter().any(|request| !is_read_only_action(&request.action))) + } + + pub fn into_execution_request( + self, + ) -> Result { + if self.actions.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: "presentation_artifact".to_string(), + message: "`actions` must contain at least one item".to_string(), + }); + } + Ok(PresentationArtifactExecutionRequest { + artifact_id: self.artifact_id, + requests: self + .actions + .into_iter() + .map(|request| PresentationArtifactRequest { + artifact_id: None, + action: request.action, + args: request.args, + }) + .collect(), + }) + } + + pub fn required_path_accesses( + &self, + cwd: &Path, + ) -> Result, PresentationArtifactError> { + let mut accesses = Vec::new(); + for request in &self.actions { + accesses.extend( + PresentationArtifactRequest { + artifact_id: None, + action: request.action.clone(), + args: request.args.clone(), + } + .required_path_accesses(cwd)?, + ); + } + Ok(accesses) + } +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/args.rs b/codex-rs/artifact-presentation/src/presentation_artifact/args.rs new file mode 100644 index 0000000000..a139dcb055 --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/args.rs @@ -0,0 +1,729 @@ +#[derive(Debug, Deserialize)] +struct CreateArgs { + name: Option, + slide_size: Option, + theme: Option, +} + +#[derive(Debug, Deserialize)] +struct ImportPptxArgs { + path: PathBuf, +} + +#[derive(Debug, Deserialize)] +struct ExportPptxArgs { + path: PathBuf, +} + +#[derive(Debug, Deserialize)] +struct ExportPreviewArgs { + path: PathBuf, + slide_index: Option, + format: Option, + scale: Option, + quality: Option, +} + +#[derive(Debug, Default, Deserialize)] +struct AddSlideArgs { + layout: Option, + notes: Option, + background_fill: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateLayoutArgs { + name: String, + kind: Option, + parent_layout_id: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PreviewOutputFormat { + Png, + Jpeg, + Svg, +} + +impl PreviewOutputFormat { + fn extension(self) -> &'static str { + match self { + Self::Png => "png", + Self::Jpeg => "jpg", + Self::Svg => "svg", + } + } +} + +#[derive(Debug, Deserialize)] +struct AddLayoutPlaceholderArgs { + layout_id: String, + name: String, + placeholder_type: String, + index: Option, + text: Option, + geometry: Option, + position: Option, +} + +#[derive(Debug, Deserialize)] +struct LayoutIdArgs { + layout_id: String, +} + +#[derive(Debug, Deserialize)] +struct SetSlideLayoutArgs { + slide_index: u32, + layout_id: String, +} + +#[derive(Debug, Deserialize)] +struct UpdatePlaceholderTextArgs { + slide_index: u32, + name: String, + text: String, +} + +#[derive(Debug, Deserialize)] +struct NotesArgs { + slide_index: u32, + text: Option, +} + +#[derive(Debug, Deserialize)] +struct NotesVisibilityArgs { + slide_index: u32, + visible: bool, +} + +#[derive(Debug, Deserialize)] +struct ThemeArgs { + color_scheme: HashMap, + major_font: Option, + minor_font: Option, +} + +#[derive(Debug, Deserialize)] +struct StyleNameArgs { + name: String, +} + +#[derive(Debug, Deserialize)] +struct AddStyleArgs { + name: String, + #[serde(flatten)] + styling: TextStylingArgs, +} + +#[derive(Debug, Deserialize)] +struct InspectArgs { + kind: Option, + include: Option, + exclude: Option, + search: Option, + target_id: Option, + target: Option, + max_chars: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct InspectTargetArgs { + id: String, + before_lines: Option, + after_lines: Option, +} + +#[derive(Debug, Deserialize)] +struct ResolveArgs { + id: String, +} + +#[derive(Debug, Clone, Deserialize)] +struct PatchOperationInput { + artifact_id: Option, + action: String, + #[serde(default)] + args: Value, +} + +#[derive(Debug, Deserialize)] +struct RecordPatchArgs { + operations: Vec, +} + +#[derive(Debug, Deserialize)] +struct ApplyPatchArgs { + operations: Option>, + patch: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PresentationPatch { + version: u32, + artifact_id: String, + operations: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PatchOperation { + action: String, + #[serde(default)] + args: Value, +} + +#[derive(Debug, Default, Deserialize)] +struct InsertSlideArgs { + index: Option, + after_slide_index: Option, + layout: Option, + notes: Option, + background_fill: Option, +} + +#[derive(Debug, Deserialize)] +struct SlideIndexArgs { + slide_index: u32, +} + +#[derive(Debug, Deserialize)] +struct MoveSlideArgs { + from_index: u32, + to_index: u32, +} + +#[derive(Debug, Deserialize)] +struct SetActiveSlideArgs { + slide_index: u32, +} + +#[derive(Debug, Deserialize)] +struct SetSlideBackgroundArgs { + slide_index: u32, + fill: String, +} + +#[derive(Debug, Clone, Deserialize)] +struct PositionArgs { + left: u32, + top: u32, + width: u32, + height: u32, + rotation: Option, + flip_horizontal: Option, + flip_vertical: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +struct PartialPositionArgs { + left: Option, + top: Option, + width: Option, + height: Option, + rotation: Option, + flip_horizontal: Option, + flip_vertical: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +struct TextStylingArgs { + style: Option, + font_size: Option, + font_family: Option, + color: Option, + fill: Option, + alignment: Option, + bold: Option, + italic: Option, + underline: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +struct TextLayoutArgs { + insets: Option, + wrap: Option, + auto_fit: Option, + vertical_alignment: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct TextInsetsArgs { + left: u32, + right: u32, + top: u32, + bottom: u32, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum RichTextInput { + Plain(String), + Paragraphs(Vec), +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum RichParagraphInput { + Plain(String), + Runs(Vec), +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum RichRunInput { + Plain(String), + Styled(RichRunObjectInput), +} + +#[derive(Debug, Clone, Deserialize)] +struct RichRunObjectInput { + run: String, + #[serde(default)] + text_style: TextStylingArgs, + link: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct RichTextLinkInput { + uri: Option, + is_external: Option, +} + +#[derive(Debug, Deserialize)] +struct AddTextShapeArgs { + slide_index: u32, + text: String, + position: PositionArgs, + #[serde(flatten)] + styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Clone, Default, Deserialize)] +struct StrokeArgs { + color: String, + width: u32, + style: Option, +} + +#[derive(Debug, Deserialize)] +struct AddShapeArgs { + slide_index: u32, + geometry: String, + position: PositionArgs, + fill: Option, + stroke: Option, + text: Option, + rotation: Option, + flip_horizontal: Option, + flip_vertical: Option, + #[serde(default)] + text_style: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Clone, Default, Deserialize)] +struct ConnectorLineArgs { + color: Option, + width: Option, + style: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PointArgs { + left: u32, + top: u32, +} + +#[derive(Debug, Deserialize)] +struct AddConnectorArgs { + slide_index: u32, + connector_type: String, + start: PointArgs, + end: PointArgs, + line: Option, + start_arrow: Option, + end_arrow: Option, + arrow_size: Option, + label: Option, +} + +#[derive(Debug, Deserialize)] +struct AddImageArgs { + slide_index: u32, + path: Option, + data_url: Option, + blob: Option, + uri: Option, + position: PositionArgs, + fit: Option, + crop: Option, + rotation: Option, + flip_horizontal: Option, + flip_vertical: Option, + lock_aspect_ratio: Option, + alt: Option, + prompt: Option, +} + +impl AddImageArgs { + fn image_source(&self) -> Result { + match (&self.path, &self.data_url, &self.blob, &self.uri) { + (Some(path), None, None, None) => Ok(ImageInputSource::Path(path.clone())), + (None, Some(data_url), None, None) => Ok(ImageInputSource::DataUrl(data_url.clone())), + (None, None, Some(blob), None) => Ok(ImageInputSource::Blob(blob.clone())), + (None, None, None, Some(uri)) => Ok(ImageInputSource::Uri(uri.clone())), + (None, None, None, None) if self.prompt.is_some() => Ok(ImageInputSource::Placeholder), + _ => Err(PresentationArtifactError::InvalidArgs { + action: "add_image".to_string(), + message: + "provide exactly one of `path`, `data_url`, `blob`, or `uri`, or provide `prompt` for a placeholder image" + .to_string(), + }), + } + } +} + +enum ImageInputSource { + Path(PathBuf), + DataUrl(String), + Blob(String), + Uri(String), + Placeholder, +} + +#[derive(Debug, Clone, Deserialize)] +struct ImageCropArgs { + left: f64, + top: f64, + right: f64, + bottom: f64, +} + +#[derive(Debug, Deserialize)] +struct AddTableArgs { + slide_index: u32, + position: PositionArgs, + rows: Vec>, + column_widths: Option>, + row_heights: Option>, + style: Option, + style_options: Option, + borders: Option, + right_to_left: Option, +} + +#[derive(Debug, Deserialize)] +struct AddChartArgs { + slide_index: u32, + position: PositionArgs, + chart_type: String, + categories: Vec, + series: Vec, + title: Option, + style_index: Option, + has_legend: Option, + legend_position: Option, + #[serde(default)] + legend_text_style: TextStylingArgs, + x_axis_title: Option, + y_axis_title: Option, + data_labels: Option, + chart_fill: Option, + plot_area_fill: Option, +} + +#[derive(Debug, Deserialize)] +struct ChartSeriesArgs { + name: String, + values: Vec, + categories: Option>, + x_values: Option>, + fill: Option, + stroke: Option, + marker: Option, + data_label_overrides: Option>, +} + +#[derive(Debug, Clone, Deserialize)] +struct ChartMarkerArgs { + symbol: Option, + size: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct ChartDataLabelsArgs { + show_value: Option, + show_category_name: Option, + show_leader_lines: Option, + position: Option, + #[serde(default)] + text_style: TextStylingArgs, +} + +#[derive(Debug, Clone, Deserialize)] +struct ChartDataLabelOverrideArgs { + idx: u32, + text: Option, + position: Option, + #[serde(default)] + text_style: TextStylingArgs, + fill: Option, + stroke: Option, +} + +#[derive(Debug, Deserialize)] +struct UpdateTextArgs { + element_id: String, + text: String, + #[serde(default)] + styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Deserialize)] +struct SetRichTextArgs { + element_id: Option, + slide_index: Option, + row: Option, + column: Option, + notes: Option, + text: RichTextInput, + #[serde(default)] + styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Deserialize)] +struct FormatTextRangeArgs { + element_id: Option, + slide_index: Option, + row: Option, + column: Option, + notes: Option, + query: Option, + occurrence: Option, + start_cp: Option, + length: Option, + #[serde(default)] + styling: TextStylingArgs, + #[serde(default)] + text_layout: TextLayoutArgs, + link: Option, + spacing_before: Option, + spacing_after: Option, + line_spacing: Option, +} + +#[derive(Debug, Deserialize)] +struct ReplaceTextArgs { + element_id: String, + search: String, + replace: String, +} + +#[derive(Debug, Deserialize)] +struct InsertTextAfterArgs { + element_id: String, + after: String, + insert: String, +} + +#[derive(Debug, Deserialize)] +struct SetHyperlinkArgs { + element_id: String, + link_type: Option, + url: Option, + slide_index: Option, + address: Option, + subject: Option, + path: Option, + tooltip: Option, + highlight_click: Option, + clear: Option, +} + +#[derive(Debug, Deserialize)] +struct UpdateShapeStyleArgs { + element_id: String, + position: Option, + fill: Option, + stroke: Option, + rotation: Option, + flip_horizontal: Option, + flip_vertical: Option, + fit: Option, + crop: Option, + lock_aspect_ratio: Option, + z_order: Option, + #[serde(default)] + text_layout: TextLayoutArgs, +} + +#[derive(Debug, Deserialize)] +struct ElementIdArgs { + element_id: String, +} + +#[derive(Debug, Deserialize)] +struct ReplaceImageArgs { + element_id: String, + path: Option, + data_url: Option, + blob: Option, + uri: Option, + fit: Option, + crop: Option, + rotation: Option, + flip_horizontal: Option, + flip_vertical: Option, + lock_aspect_ratio: Option, + alt: Option, + prompt: Option, +} + +#[derive(Debug, Deserialize)] +struct UpdateTableCellArgs { + element_id: String, + row: u32, + column: u32, + value: Value, + #[serde(default)] + styling: TextStylingArgs, + background_fill: Option, + alignment: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct TableStyleOptionsArgs { + header_row: Option, + banded_rows: Option, + banded_columns: Option, + first_column: Option, + last_column: Option, + total_row: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct TableBorderArgs { + color: String, + width: u32, +} + +#[derive(Debug, Clone, Deserialize)] +struct TableBordersArgs { + outside: Option, + inside: Option, + top: Option, + bottom: Option, + left: Option, + right: Option, +} + +#[derive(Debug, Deserialize)] +struct UpdateTableStyleArgs { + element_id: String, + style: Option, + style_options: Option, + borders: Option, + right_to_left: Option, +} + +#[derive(Debug, Deserialize)] +struct StyleTableBlockArgs { + element_id: String, + row: u32, + column: u32, + row_count: u32, + column_count: u32, + #[serde(default)] + styling: TextStylingArgs, + background_fill: Option, + alignment: Option, + borders: Option, +} + +#[derive(Debug, Deserialize)] +struct MergeTableCellsArgs { + element_id: String, + start_row: u32, + end_row: u32, + start_column: u32, + end_column: u32, +} + +#[derive(Debug, Deserialize)] +struct UpdateChartArgs { + element_id: String, + title: Option, + categories: Option>, + style_index: Option, + has_legend: Option, + legend_position: Option, + #[serde(default)] + legend_text_style: TextStylingArgs, + x_axis_title: Option, + y_axis_title: Option, + data_labels: Option, + chart_fill: Option, + plot_area_fill: Option, +} + +#[derive(Debug, Deserialize)] +struct AddChartSeriesArgs { + element_id: String, + name: String, + values: Vec, + categories: Option>, + x_values: Option>, + fill: Option, + stroke: Option, + marker: Option, +} + +#[derive(Debug, Deserialize)] +struct SetCommentAuthorArgs { + display_name: String, + initials: String, + email: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct CommentPositionArgs { + x: u32, + y: u32, +} + +#[derive(Debug, Deserialize)] +struct AddCommentThreadArgs { + slide_index: Option, + element_id: Option, + query: Option, + occurrence: Option, + start_cp: Option, + length: Option, + text: String, + position: Option, +} + +#[derive(Debug, Deserialize)] +struct AddCommentReplyArgs { + thread_id: String, + text: String, +} + +#[derive(Debug, Deserialize)] +struct ToggleCommentReactionArgs { + thread_id: String, + message_id: Option, + emoji: String, +} + +#[derive(Debug, Deserialize)] +struct CommentThreadIdArgs { + thread_id: String, +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs b/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs new file mode 100644 index 0000000000..608e0734ee --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/inspect.rs @@ -0,0 +1,871 @@ +fn inspect_document(document: &PresentationDocument, args: &InspectArgs) -> String { + let include_kinds = args + .include + .as_deref() + .or(args.kind.as_deref()) + .unwrap_or( + "deck,slide,textbox,shape,connector,table,chart,image,notes,layoutList,textRange,comment", + ); + let included_kinds = include_kinds + .split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .collect::>(); + let excluded_kinds = args + .exclude + .as_deref() + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .collect::>(); + let include = |name: &str| included_kinds.contains(name) && !excluded_kinds.contains(name); + let mut records: Vec<(Value, Option)> = Vec::new(); + if include("deck") { + records.push(( + serde_json::json!({ + "kind": "deck", + "id": format!("pr/{}", document.artifact_id), + "name": document.name, + "slides": document.slides.len(), + "styleIds": document + .named_text_styles() + .iter() + .map(|style| format!("st/{}", style.name)) + .collect::>(), + "activeSlideIndex": document.active_slide_index, + "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| format!("sl/{}", slide.slide_id)), + "commentThreadIds": document + .comment_threads + .iter() + .map(|thread| format!("th/{}", thread.thread_id)) + .collect::>(), + }), + None, + )); + } + if include("styleList") { + for style in document.named_text_styles() { + records.push((named_text_style_to_json(&style, "st"), None)); + } + } + if include("layoutList") { + for layout in &document.layouts { + let placeholders = resolved_layout_placeholders(document, &layout.layout_id, "inspect") + .unwrap_or_default() + .into_iter() + .map(|placeholder| { + serde_json::json!({ + "name": placeholder.definition.name, + "type": placeholder.definition.placeholder_type, + "sourceLayoutId": placeholder.source_layout_id, + "textPreview": placeholder.definition.text, + }) + }) + .collect::>(); + records.push(( + serde_json::json!({ + "kind": "layout", + "id": format!("ly/{}", layout.layout_id), + "layoutId": layout.layout_id, + "name": layout.name, + "type": match layout.kind { LayoutKind::Layout => "layout", LayoutKind::Master => "master" }, + "parentLayoutId": layout.parent_layout_id, + "placeholders": placeholders, + }), + None, + )); + } + } + for (index, slide) in document.slides.iter().enumerate() { + let slide_id = format!("sl/{}", slide.slide_id); + if include("slide") { + records.push(( + serde_json::json!({ + "kind": "slide", + "id": slide_id, + "slide": index + 1, + "slideIndex": index, + "isActive": document.active_slide_index == Some(index), + "layoutId": slide.layout_id, + "elements": slide.elements.len(), + }), + Some(slide_id.clone()), + )); + } + if include("notes") && !slide.notes.text.is_empty() { + records.push(( + serde_json::json!({ + "kind": "notes", + "id": format!("nt/{}", slide.slide_id), + "slide": index + 1, + "visible": slide.notes.visible, + "text": slide.notes.text, + "textPreview": slide.notes.text.replace('\n', " | "), + "textChars": slide.notes.text.chars().count(), + "textLines": slide.notes.text.lines().count(), + "richText": rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text), + }), + Some(slide_id.clone()), + )); + } + if include("textRange") { + records.extend( + slide + .notes + .rich_text + .ranges + .iter() + .map(|range| { + let mut record = text_range_to_proto(&slide.notes.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!("nt/{}", slide.slide_id)); + record["hostKind"] = Value::String("notes".to_string()); + (record, Some(slide_id.clone())) + }), + ); + } + for element in &slide.elements { + let mut record = match element { + PresentationElement::Text(text) => { + if !include("textbox") { + continue; + } + serde_json::json!({ + "kind": "textbox", + "id": format!("sh/{}", text.element_id), + "slide": index + 1, + "text": text.text, + "textStyle": text_style_to_proto(&text.style), + "textPreview": text.text.replace('\n', " | "), + "textChars": text.text.chars().count(), + "textLines": text.text.lines().count(), + "richText": rich_text_to_proto(&text.text, &text.rich_text), + "bbox": [text.frame.left, text.frame.top, text.frame.width, text.frame.height], + "bboxUnit": "points", + }) + } + PresentationElement::Shape(shape) => { + if !(include("shape") || include("textbox") && shape.text.is_some()) { + continue; + } + let kind = if shape.text.is_some() && include("textbox") { + "textbox" + } else { + "shape" + }; + let mut record = serde_json::json!({ + "kind": kind, + "id": format!("sh/{}", shape.element_id), + "slide": index + 1, + "geometry": format!("{:?}", shape.geometry), + "text": shape.text, + "textStyle": text_style_to_proto(&shape.text_style), + "richText": shape + .text + .as_ref() + .zip(shape.rich_text.as_ref()) + .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) + .unwrap_or(Value::Null), + "rotation": shape.rotation_degrees, + "flipHorizontal": shape.flip_horizontal, + "flipVertical": shape.flip_vertical, + "bbox": [shape.frame.left, shape.frame.top, shape.frame.width, shape.frame.height], + "bboxUnit": "points", + }); + if let Some(text) = &shape.text { + record["textPreview"] = Value::String(text.replace('\n', " | ")); + record["textChars"] = Value::from(text.chars().count()); + record["textLines"] = Value::from(text.lines().count()); + } + record + } + PresentationElement::Connector(connector) => { + if !include("shape") && !include("connector") { + continue; + } + serde_json::json!({ + "kind": "connector", + "id": format!("cn/{}", connector.element_id), + "slide": index + 1, + "connectorType": format!("{:?}", connector.connector_type), + "start": [connector.start.left, connector.start.top], + "end": [connector.end.left, connector.end.top], + "lineStyle": format!("{:?}", connector.line_style), + "label": connector.label, + }) + } + PresentationElement::Table(table) => { + if !include("table") { + continue; + } + serde_json::json!({ + "kind": "table", + "id": format!("tb/{}", table.element_id), + "slide": index + 1, + "rows": table.rows.len(), + "cols": table.rows.iter().map(std::vec::Vec::len).max().unwrap_or(0), + "columnWidths": table.column_widths, + "rowHeights": table.row_heights, + "preview": table.rows.first().map(|row| row.iter().map(|cell| cell.text.clone()).collect::>().join(" | ")), + "style": table.style, + "styleOptions": table_style_options_to_proto(&table.style_options), + "borders": table.borders.as_ref().map(table_borders_to_proto), + "rightToLeft": table.right_to_left, + "cellTextStyles": table + .rows + .iter() + .map(|row| row.iter().map(|cell| text_style_to_proto(&cell.text_style)).collect::>()) + .collect::>(), + "rowsData": table + .rows + .iter() + .map(|row| row.iter().map(table_cell_to_proto).collect::>()) + .collect::>(), + "bbox": [table.frame.left, table.frame.top, table.frame.width, table.frame.height], + "bboxUnit": "points", + }) + } + PresentationElement::Chart(chart) => { + if !include("chart") { + continue; + } + serde_json::json!({ + "kind": "chart", + "id": format!("ch/{}", chart.element_id), + "slide": index + 1, + "chartType": format!("{:?}", chart.chart_type), + "title": chart.title, + "styleIndex": chart.style_index, + "hasLegend": chart.has_legend, + "legend": chart.legend.as_ref().map(chart_legend_to_proto), + "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), + "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), + "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), + "chartFill": chart.chart_fill, + "plotAreaFill": chart.plot_area_fill, + "series": chart + .series + .iter() + .map(|series| serde_json::json!({ + "name": series.name, + "values": series.values, + "categories": series.categories, + "xValues": series.x_values, + "fill": series.fill, + "stroke": series.stroke.as_ref().map(stroke_to_proto), + "marker": series.marker.as_ref().map(chart_marker_to_proto), + "dataLabelOverrides": series + .data_label_overrides + .iter() + .map(chart_data_label_override_to_proto) + .collect::>(), + })) + .collect::>(), + "bbox": [chart.frame.left, chart.frame.top, chart.frame.width, chart.frame.height], + "bboxUnit": "points", + }) + } + PresentationElement::Image(image) => { + if !include("image") { + continue; + } + serde_json::json!({ + "kind": "image", + "id": format!("im/{}", image.element_id), + "slide": index + 1, + "alt": image.alt_text, + "prompt": image.prompt, + "fit": format!("{:?}", image.fit_mode), + "rotation": image.rotation_degrees, + "flipHorizontal": image.flip_horizontal, + "flipVertical": image.flip_vertical, + "crop": image.crop.map(|(left, top, right, bottom)| serde_json::json!({ + "left": left, + "top": top, + "right": right, + "bottom": bottom, + })), + "isPlaceholder": image.is_placeholder, + "lockAspectRatio": image.lock_aspect_ratio, + "bbox": [image.frame.left, image.frame.top, image.frame.width, image.frame.height], + "bboxUnit": "points", + }) + } + }; + if let Some(placeholder) = match element { + PresentationElement::Text(text) => text.placeholder.as_ref(), + PresentationElement::Shape(shape) => shape.placeholder.as_ref(), + PresentationElement::Connector(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => None, + PresentationElement::Image(image) => image.placeholder.as_ref(), + } { + record["placeholder"] = Value::String(placeholder.placeholder_type.clone()); + record["placeholderName"] = Value::String(placeholder.name.clone()); + record["placeholderIndex"] = + placeholder.index.map(Value::from).unwrap_or(Value::Null); + } + if let PresentationElement::Shape(shape) = element + && let Some(stroke) = &shape.stroke + { + record["stroke"] = serde_json::json!({ + "color": stroke.color, + "width": stroke.width, + "style": stroke.style.as_api_str(), + }); + } + if let Some(hyperlink) = match element { + PresentationElement::Text(text) => text.hyperlink.as_ref(), + PresentationElement::Shape(shape) => shape.hyperlink.as_ref(), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => None, + } { + record["hyperlink"] = hyperlink.to_json(); + } + records.push((record, Some(slide_id.clone()))); + if include("textRange") { + match element { + PresentationElement::Text(text) => { + records.extend(text.rich_text.ranges.iter().map(|range| { + let mut record = text_range_to_proto(&text.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!("sh/{}", text.element_id)); + record["hostKind"] = Value::String("textbox".to_string()); + (record, Some(slide_id.clone())) + })); + } + PresentationElement::Shape(shape) => { + if let Some((text, rich_text)) = shape.text.as_ref().zip(shape.rich_text.as_ref()) { + records.extend(rich_text.ranges.iter().map(|range| { + let mut record = text_range_to_proto(text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!("sh/{}", shape.element_id)); + record["hostKind"] = Value::String("textbox".to_string()); + (record, Some(slide_id.clone())) + })); + } + } + PresentationElement::Table(table) => { + for (row_index, row) in table.rows.iter().enumerate() { + for (column_index, cell) in row.iter().enumerate() { + records.extend(cell.rich_text.ranges.iter().map(|range| { + let mut record = text_range_to_proto(&cell.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["slide"] = Value::from(index + 1); + record["slideIndex"] = Value::from(index); + record["hostAnchor"] = Value::String(format!( + "tb/{}#cell/{row_index}/{column_index}", + table.element_id + )); + record["hostKind"] = Value::String("tableCell".to_string()); + (record, Some(slide_id.clone())) + })); + } + } + } + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Chart(_) => {} + } + } + } + } + if include("comment") { + records.extend(document.comment_threads.iter().map(|thread| { + let mut record = comment_thread_to_proto(thread); + record["id"] = Value::String(format!("th/{}", thread.thread_id)); + (record, None) + })); + } + + if let Some(target_id) = args.target_id.as_deref() { + records.retain(|(record, slide_id)| { + legacy_target_matches(target_id, record, slide_id.as_deref()) + }); + if records.is_empty() { + records.push(( + serde_json::json!({ + "kind": "notice", + "noticeType": "targetNotFound", + "target": { "id": target_id }, + "message": format!("No inspect records matched target `{target_id}`."), + }), + None, + )); + } + } + + if let Some(search) = args.search.as_deref() { + let search_lowercase = search.to_ascii_lowercase(); + records.retain(|(record, _)| { + record + .to_string() + .to_ascii_lowercase() + .contains(&search_lowercase) + }); + if records.is_empty() { + records.push(( + serde_json::json!({ + "kind": "notice", + "noticeType": "noMatches", + "search": search, + "message": format!("No inspect records matched search `{search}`."), + }), + None, + )); + } + } + + if let Some(target) = args.target.as_ref() { + if let Some(target_index) = records.iter().position(|(record, _)| { + record.get("id").and_then(Value::as_str) == Some(target.id.as_str()) + }) { + let start = target_index.saturating_sub(target.before_lines.unwrap_or(0)); + let end = (target_index + target.after_lines.unwrap_or(0) + 1).min(records.len()); + records = records.into_iter().skip(start).take(end - start).collect(); + } else { + records = vec![( + serde_json::json!({ + "kind": "notice", + "noticeType": "targetNotFound", + "target": { + "id": target.id, + "beforeLines": target.before_lines, + "afterLines": target.after_lines, + }, + "message": format!("No inspect records matched target `{}`.", target.id), + }), + None, + )]; + } + } + + let mut lines = Vec::new(); + let mut omitted_lines = 0usize; + let mut omitted_chars = 0usize; + for line in records.into_iter().map(|(record, _)| record.to_string()) { + let separator_len = usize::from(!lines.is_empty()); + if let Some(max_chars) = args.max_chars + && lines.iter().map(String::len).sum::() + separator_len + line.len() > max_chars + { + omitted_lines += 1; + omitted_chars += line.len(); + continue; + } + lines.push(line); + } + if omitted_lines > 0 { + lines.push( + serde_json::json!({ + "kind": "notice", + "noticeType": "truncation", + "maxChars": args.max_chars, + "omittedLines": omitted_lines, + "omittedChars": omitted_chars, + "message": format!( + "Truncated inspect output by omitting {omitted_lines} lines. Increase maxChars or narrow the filter." + ), + }) + .to_string(), + ); + } + lines.join("\n") +} + +fn legacy_target_matches(target_id: &str, record: &Value, slide_id: Option<&str>) -> bool { + record.get("id").and_then(Value::as_str) == Some(target_id) || slide_id == Some(target_id) +} + +fn add_text_metadata(record: &mut Value, text: &str) { + record["textPreview"] = Value::String(text.replace('\n', " | ")); + record["textChars"] = Value::from(text.chars().count()); + record["textLines"] = Value::from(text.lines().count()); +} + +fn normalize_element_lookup_id(element_id: &str) -> &str { + element_id + .split_once('/') + .map(|(_, normalized)| normalized) + .unwrap_or(element_id) +} + +fn resolve_anchor( + document: &PresentationDocument, + id: &str, + action: &str, +) -> Result { + if id == format!("pr/{}", document.artifact_id) { + return Ok(serde_json::json!({ + "kind": "deck", + "id": id, + "artifactId": document.artifact_id, + "name": document.name, + "slideCount": document.slides.len(), + "styleIds": document + .named_text_styles() + .iter() + .map(|style| format!("st/{}", style.name)) + .collect::>(), + "activeSlideIndex": document.active_slide_index, + "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| format!("sl/{}", slide.slide_id)), + })); + } + if let Some(style_name) = id.strip_prefix("st/") { + let named_style = document + .named_text_styles() + .into_iter() + .find(|style| style.name == style_name) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown style id `{id}`"), + })?; + return Ok(named_text_style_to_json(&named_style, "st")); + } + + for (slide_index, slide) in document.slides.iter().enumerate() { + let slide_id = format!("sl/{}", slide.slide_id); + if id == slide_id { + return Ok(serde_json::json!({ + "kind": "slide", + "id": slide_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "isActive": document.active_slide_index == Some(slide_index), + "layoutId": slide.layout_id, + "notesId": (!slide.notes.text.is_empty()).then(|| format!("nt/{}", slide.slide_id)), + "elementIds": slide.elements.iter().map(|element| { + let prefix = match element { + PresentationElement::Text(_) | PresentationElement::Shape(_) => "sh", + PresentationElement::Connector(_) => "cn", + PresentationElement::Image(_) => "im", + PresentationElement::Table(_) => "tb", + PresentationElement::Chart(_) => "ch", + }; + format!("{prefix}/{}", element.element_id()) + }).collect::>(), + })); + } + let notes_id = format!("nt/{}", slide.slide_id); + if id == notes_id { + let mut record = serde_json::json!({ + "kind": "notes", + "id": notes_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "visible": slide.notes.visible, + "text": slide.notes.text, + }); + add_text_metadata(&mut record, &slide.notes.text); + record["richText"] = rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text); + return Ok(record); + } + if let Some(range_id) = id.strip_prefix("tr/") + && let Some(record) = slide + .notes + .rich_text + .ranges + .iter() + .find(|range| range.range_id == range_id) + .map(|range| { + let mut record = text_range_to_proto(&slide.notes.text, range); + record["kind"] = Value::String("textRange".to_string()); + record["id"] = Value::String(id.to_string()); + record["slide"] = Value::from(slide_index + 1); + record["slideIndex"] = Value::from(slide_index); + record["hostAnchor"] = Value::String(notes_id.clone()); + record["hostKind"] = Value::String("notes".to_string()); + record + }) + { + return Ok(record); + } + for element in &slide.elements { + let mut record = match element { + PresentationElement::Text(text) => { + let mut record = serde_json::json!({ + "kind": "textbox", + "id": format!("sh/{}", text.element_id), + "elementId": text.element_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "text": text.text, + "textStyle": text_style_to_proto(&text.style), + "richText": rich_text_to_proto(&text.text, &text.rich_text), + "bbox": [text.frame.left, text.frame.top, text.frame.width, text.frame.height], + "bboxUnit": "points", + }); + add_text_metadata(&mut record, &text.text); + record + } + PresentationElement::Shape(shape) => { + let mut record = serde_json::json!({ + "kind": if shape.text.is_some() { "textbox" } else { "shape" }, + "id": format!("sh/{}", shape.element_id), + "elementId": shape.element_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "geometry": format!("{:?}", shape.geometry), + "text": shape.text, + "textStyle": text_style_to_proto(&shape.text_style), + "richText": shape + .text + .as_ref() + .zip(shape.rich_text.as_ref()) + .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) + .unwrap_or(Value::Null), + "rotation": shape.rotation_degrees, + "flipHorizontal": shape.flip_horizontal, + "flipVertical": shape.flip_vertical, + "bbox": [shape.frame.left, shape.frame.top, shape.frame.width, shape.frame.height], + "bboxUnit": "points", + }); + if let Some(text) = &shape.text { + add_text_metadata(&mut record, text); + } + record + } + PresentationElement::Connector(connector) => serde_json::json!({ + "kind": "connector", + "id": format!("cn/{}", connector.element_id), + "elementId": connector.element_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "connectorType": format!("{:?}", connector.connector_type), + "start": [connector.start.left, connector.start.top], + "end": [connector.end.left, connector.end.top], + "lineStyle": format!("{:?}", connector.line_style), + "label": connector.label, + }), + PresentationElement::Image(image) => serde_json::json!({ + "kind": "image", + "id": format!("im/{}", image.element_id), + "elementId": image.element_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "alt": image.alt_text, + "prompt": image.prompt, + "fit": format!("{:?}", image.fit_mode), + "rotation": image.rotation_degrees, + "flipHorizontal": image.flip_horizontal, + "flipVertical": image.flip_vertical, + "crop": image.crop.map(|(left, top, right, bottom)| serde_json::json!({ + "left": left, + "top": top, + "right": right, + "bottom": bottom, + })), + "isPlaceholder": image.is_placeholder, + "lockAspectRatio": image.lock_aspect_ratio, + "bbox": [image.frame.left, image.frame.top, image.frame.width, image.frame.height], + "bboxUnit": "points", + }), + PresentationElement::Table(table) => serde_json::json!({ + "kind": "table", + "id": format!("tb/{}", table.element_id), + "elementId": table.element_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "rows": table.rows.len(), + "cols": table.rows.iter().map(std::vec::Vec::len).max().unwrap_or(0), + "columnWidths": table.column_widths, + "rowHeights": table.row_heights, + "style": table.style, + "styleOptions": table_style_options_to_proto(&table.style_options), + "borders": table.borders.as_ref().map(table_borders_to_proto), + "rightToLeft": table.right_to_left, + "cellTextStyles": table + .rows + .iter() + .map(|row| row.iter().map(|cell| text_style_to_proto(&cell.text_style)).collect::>()) + .collect::>(), + "rowsData": table + .rows + .iter() + .map(|row| row.iter().map(table_cell_to_proto).collect::>()) + .collect::>(), + "bbox": [table.frame.left, table.frame.top, table.frame.width, table.frame.height], + "bboxUnit": "points", + }), + PresentationElement::Chart(chart) => serde_json::json!({ + "kind": "chart", + "id": format!("ch/{}", chart.element_id), + "elementId": chart.element_id, + "slide": slide_index + 1, + "slideIndex": slide_index, + "chartType": format!("{:?}", chart.chart_type), + "title": chart.title, + "styleIndex": chart.style_index, + "hasLegend": chart.has_legend, + "legend": chart.legend.as_ref().map(chart_legend_to_proto), + "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), + "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), + "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), + "chartFill": chart.chart_fill, + "plotAreaFill": chart.plot_area_fill, + "series": chart + .series + .iter() + .map(|series| serde_json::json!({ + "name": series.name, + "values": series.values, + "categories": series.categories, + "xValues": series.x_values, + "fill": series.fill, + "stroke": series.stroke.as_ref().map(stroke_to_proto), + "marker": series.marker.as_ref().map(chart_marker_to_proto), + "dataLabelOverrides": series + .data_label_overrides + .iter() + .map(chart_data_label_override_to_proto) + .collect::>(), + })) + .collect::>(), + "bbox": [chart.frame.left, chart.frame.top, chart.frame.width, chart.frame.height], + "bboxUnit": "points", + }), + }; + if let Some(hyperlink) = match element { + PresentationElement::Text(text) => text.hyperlink.as_ref(), + PresentationElement::Shape(shape) => shape.hyperlink.as_ref(), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => None, + } { + record["hyperlink"] = hyperlink.to_json(); + } + if let PresentationElement::Shape(shape) = element + && let Some(stroke) = &shape.stroke + { + record["stroke"] = serde_json::json!({ + "color": stroke.color, + "width": stroke.width, + "style": stroke.style.as_api_str(), + }); + } + if let Some(placeholder) = match element { + PresentationElement::Text(text) => text.placeholder.as_ref(), + PresentationElement::Shape(shape) => shape.placeholder.as_ref(), + PresentationElement::Image(image) => image.placeholder.as_ref(), + PresentationElement::Connector(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => None, + } { + record["placeholder"] = Value::String(placeholder.placeholder_type.clone()); + record["placeholderName"] = Value::String(placeholder.name.clone()); + record["placeholderIndex"] = + placeholder.index.map(Value::from).unwrap_or(Value::Null); + } + if record.get("id").and_then(Value::as_str) == Some(id) { + return Ok(record); + } + if let Some(range_id) = id.strip_prefix("tr/") { + match element { + PresentationElement::Text(text) => { + if let Some(range) = + text.rich_text.ranges.iter().find(|range| range.range_id == range_id) + { + let mut range_record = text_range_to_proto(&text.text, range); + range_record["kind"] = Value::String("textRange".to_string()); + range_record["id"] = Value::String(id.to_string()); + range_record["slide"] = Value::from(slide_index + 1); + range_record["slideIndex"] = Value::from(slide_index); + range_record["hostAnchor"] = + Value::String(format!("sh/{}", text.element_id)); + range_record["hostKind"] = Value::String("textbox".to_string()); + return Ok(range_record); + } + } + PresentationElement::Shape(shape) => { + if let Some((text, rich_text)) = + shape.text.as_ref().zip(shape.rich_text.as_ref()) + && let Some(range) = + rich_text.ranges.iter().find(|range| range.range_id == range_id) + { + let mut range_record = text_range_to_proto(text, range); + range_record["kind"] = Value::String("textRange".to_string()); + range_record["id"] = Value::String(id.to_string()); + range_record["slide"] = Value::from(slide_index + 1); + range_record["slideIndex"] = Value::from(slide_index); + range_record["hostAnchor"] = + Value::String(format!("sh/{}", shape.element_id)); + range_record["hostKind"] = Value::String("textbox".to_string()); + return Ok(range_record); + } + } + PresentationElement::Table(table) => { + for (row_index, row) in table.rows.iter().enumerate() { + for (column_index, cell) in row.iter().enumerate() { + if let Some(range) = cell + .rich_text + .ranges + .iter() + .find(|range| range.range_id == range_id) + { + let mut range_record = text_range_to_proto(&cell.text, range); + range_record["kind"] = Value::String("textRange".to_string()); + range_record["id"] = Value::String(id.to_string()); + range_record["slide"] = Value::from(slide_index + 1); + range_record["slideIndex"] = Value::from(slide_index); + range_record["hostAnchor"] = Value::String(format!( + "tb/{}#cell/{row_index}/{column_index}", + table.element_id + )); + range_record["hostKind"] = + Value::String("tableCell".to_string()); + return Ok(range_record); + } + } + } + } + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Chart(_) => {} + } + } + } + } + + if let Some(thread_id) = id.strip_prefix("th/") + && let Some(thread) = document + .comment_threads + .iter() + .find(|thread| thread.thread_id == thread_id) + { + let mut record = comment_thread_to_proto(thread); + record["id"] = Value::String(id.to_string()); + return Ok(record); + } + + for layout in &document.layouts { + let layout_id = format!("ly/{}", layout.layout_id); + if id == layout_id { + return Ok(serde_json::json!({ + "kind": "layout", + "id": layout_id, + "layoutId": layout.layout_id, + "name": layout.name, + "type": match layout.kind { + LayoutKind::Layout => "layout", + LayoutKind::Master => "master", + }, + "parentLayoutId": layout.parent_layout_id, + "placeholders": layout_placeholder_list(document, &layout.layout_id, action)?, + })); + } + } + + Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown resolve id `{id}`"), + }) +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs new file mode 100644 index 0000000000..8539b62c76 --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/manager.rs @@ -0,0 +1,3203 @@ +#[derive(Debug, Default)] +pub struct PresentationArtifactManager { + documents: HashMap, + undo_stack: Vec, + redo_stack: Vec, +} + +#[derive(Debug, Clone)] +struct HistoryEntry { + artifact_id: String, + action: String, + before: Option, + after: Option, +} + +impl PresentationArtifactManager { + pub fn execute_requests( + &mut self, + request: PresentationArtifactExecutionRequest, + cwd: &Path, + ) -> Result { + let PresentationArtifactExecutionRequest { + artifact_id, + requests, + } = request; + let request_count = requests.len(); + let mut current_artifact_id = artifact_id; + let mut executed_actions = Vec::with_capacity(request_count); + let mut exported_paths = Vec::new(); + let mut last_response = None; + + for mut request in requests { + if request.artifact_id.is_none() { + request.artifact_id = current_artifact_id.clone(); + } + let response = self.execute(request, cwd)?; + current_artifact_id = Some(response.artifact_id.clone()); + exported_paths.extend(response.exported_paths.iter().cloned()); + executed_actions.push(response.action.clone()); + last_response = Some(response); + } + + let mut response = last_response.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: "presentation_artifact".to_string(), + message: "request sequence must contain at least one action".to_string(), + })?; + if request_count > 1 { + let final_summary = response.summary.clone(); + response.action = "batch".to_string(); + response.summary = + format!("Executed {request_count} actions sequentially. {final_summary}"); + response.executed_actions = Some(executed_actions); + response.exported_paths = exported_paths; + } + Ok(response) + } + + pub fn execute( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + match request.action.as_str() { + "undo" => return self.undo(request), + "redo" => return self.redo(request), + "record_patch" => return self.record_patch(request), + "apply_patch" => return self.apply_patch(request, cwd), + _ => {} + } + + let action = request.action.clone(); + let before = if tracks_history(&action) { + request + .artifact_id + .as_ref() + .and_then(|artifact_id| self.documents.get(artifact_id).cloned()) + } else { + None + }; + let response = self.execute_action(request, cwd)?; + if tracks_history(&action) { + let after = self.documents.get(&response.artifact_id).cloned(); + self.push_history_entry(HistoryEntry { + artifact_id: response.artifact_id.clone(), + action, + before, + after, + }); + } + Ok(response) + } + + fn execute_action( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + match request.action.as_str() { + "create" => self.create(request), + "import_pptx" => self.import_pptx(request, cwd), + "export_pptx" => self.export_pptx(request, cwd), + "export_preview" => self.export_preview(request, cwd), + "get_summary" => self.get_summary(request), + "list_slides" => self.list_slides(request), + "list_layouts" => self.list_layouts(request), + "list_layout_placeholders" => self.list_layout_placeholders(request), + "list_slide_placeholders" => self.list_slide_placeholders(request), + "inspect" => self.inspect(request), + "resolve" => self.resolve(request), + "to_proto" => self.proto_snapshot(request), + "add_slide" => self.add_slide(request), + "insert_slide" => self.insert_slide(request), + "duplicate_slide" => self.duplicate_slide(request), + "move_slide" => self.move_slide(request), + "delete_slide" => self.delete_slide(request), + "create_layout" => self.create_layout(request), + "add_layout_placeholder" => self.add_layout_placeholder(request), + "set_slide_layout" => self.set_slide_layout(request), + "update_placeholder_text" => self.update_placeholder_text(request), + "set_theme" => self.set_theme(request), + "add_style" => self.add_style(request), + "get_style" => self.get_style(request), + "describe_styles" => self.describe_styles(request), + "set_notes" => self.set_notes(request), + "set_notes_rich_text" => self.set_notes_rich_text(request), + "append_notes" => self.append_notes(request), + "clear_notes" => self.clear_notes(request), + "set_notes_visibility" => self.set_notes_visibility(request), + "set_active_slide" => self.set_active_slide(request), + "set_slide_background" => self.set_slide_background(request), + "add_text_shape" => self.add_text_shape(request), + "add_shape" => self.add_shape(request), + "add_connector" => self.add_connector(request), + "add_image" => self.add_image(request, cwd), + "replace_image" => self.replace_image(request, cwd), + "add_table" => self.add_table(request), + "update_table_style" => self.update_table_style(request), + "style_table_block" => self.style_table_block(request), + "update_table_cell" => self.update_table_cell(request), + "merge_table_cells" => self.merge_table_cells(request), + "add_chart" => self.add_chart(request), + "update_chart" => self.update_chart(request), + "add_chart_series" => self.add_chart_series(request), + "update_text" => self.update_text(request), + "set_rich_text" => self.set_rich_text(request), + "format_text_range" => self.format_text_range(request), + "replace_text" => self.replace_text(request), + "insert_text_after" => self.insert_text_after(request), + "set_hyperlink" => self.set_hyperlink(request), + "set_comment_author" => self.set_comment_author(request), + "add_comment_thread" => self.add_comment_thread(request), + "add_comment_reply" => self.add_comment_reply(request), + "toggle_comment_reaction" => self.toggle_comment_reaction(request), + "resolve_comment_thread" => self.resolve_comment_thread(request), + "reopen_comment_thread" => self.reopen_comment_thread(request), + "update_shape_style" => self.update_shape_style(request), + "bring_to_front" => self.bring_to_front(request), + "send_to_back" => self.send_to_back(request), + "delete_element" => self.delete_element(request), + "delete_artifact" => self.delete_artifact(request), + other => Err(PresentationArtifactError::UnknownAction(other.to_string())), + } + } + + fn push_history_entry(&mut self, entry: HistoryEntry) { + self.undo_stack.push(entry); + self.redo_stack.clear(); + } + + fn create( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: CreateArgs = parse_args(&request.action, &request.args)?; + let mut document = PresentationDocument::new(args.name); + if let Some(slide_size) = args.slide_size { + document.slide_size = parse_slide_size(&slide_size, &request.action)?; + } + if let Some(theme) = args.theme { + document.theme = normalize_theme(theme, &request.action)?; + } + let artifact_id = document.artifact_id.clone(); + let summary = format!( + "Created presentation artifact `{artifact_id}` with {} slides", + document.slides.len() + ); + let snapshot = snapshot_for_document(&document); + let mut response = + PresentationArtifactResponse::new(artifact_id, request.action, summary, snapshot); + response.theme = Some(document.theme_snapshot()); + self.documents + .insert(response.artifact_id.clone(), document); + Ok(response) + } + + fn import_pptx( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + let args: ImportPptxArgs = parse_args(&request.action, &request.args)?; + let path = resolve_path(cwd, &args.path); + let document = if let Some(document) = import_codex_metadata_document(&path) + .map_err(|message| PresentationArtifactError::ImportFailed { + path: path.clone(), + message, + })? + { + document + } else { + let imported = Presentation::from_path(&path).map_err(|error| { + PresentationArtifactError::ImportFailed { + path: path.clone(), + message: error.to_string(), + } + })?; + let mut document = PresentationDocument::from_ppt_rs(imported); + import_pptx_images(&path, &mut document, &request.action)?; + document + }; + let artifact_id = document.artifact_id.clone(); + let slide_count = document.slides.len(); + let snapshot = snapshot_for_document(&document); + self.documents.insert(artifact_id.clone(), document); + let summary = format!( + "Imported `{}` as artifact `{artifact_id}` with {slide_count} slides", + path.display() + ); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + summary, + snapshot, + )) + } + + fn export_pptx( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + let args: ExportPptxArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let path = resolve_path(cwd, &args.path); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: path.clone(), + message: error.to_string(), + } + })?; + } + + let bytes = build_pptx_bytes(document, &request.action).map_err(|message| { + PresentationArtifactError::ExportFailed { + path: path.clone(), + message, + } + })?; + std::fs::write(&path, bytes).map_err(|error| PresentationArtifactError::ExportFailed { + path: path.clone(), + message: error.to_string(), + })?; + + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Exported presentation to `{}`", path.display()), + snapshot_for_document(document), + ); + response.exported_paths.push(path); + Ok(response) + } + + fn export_preview( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + let args: ExportPreviewArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let output_path = resolve_path(cwd, &args.path); + let preview_format = + parse_preview_output_format(args.format.as_deref(), &output_path, &request.action)?; + let scale = normalize_preview_scale(args.scale, &request.action)?; + let quality = normalize_preview_quality(args.quality, &request.action)?; + if let Some(parent) = output_path.parent() { + std::fs::create_dir_all(parent).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: output_path.clone(), + message: error.to_string(), + } + })?; + } + let temp_dir = + std::env::temp_dir().join(format!("presentation_preview_{}", Uuid::new_v4().simple())); + std::fs::create_dir_all(&temp_dir).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: output_path.clone(), + message: error.to_string(), + } + })?; + let preview_document = if let Some(slide_index) = args.slide_index { + let slide = document + .slides + .get(slide_index as usize) + .cloned() + .ok_or_else(|| { + index_out_of_range(&request.action, slide_index as usize, document.slides.len()) + })?; + let slide_id = slide.slide_id.clone(); + PresentationDocument { + artifact_id: document.artifact_id.clone(), + name: document.name.clone(), + slide_size: document.slide_size, + theme: document.theme.clone(), + custom_text_styles: document.custom_text_styles.clone(), + layouts: Vec::new(), + slides: vec![slide], + active_slide_index: Some(0), + comment_self: document.comment_self.clone(), + comment_threads: document + .comment_threads + .iter() + .filter(|thread| match &thread.target { + CommentTarget::Slide { slide_id: target_slide_id } + | CommentTarget::Element { slide_id: target_slide_id, .. } + | CommentTarget::TextRange { slide_id: target_slide_id, .. } => { + target_slide_id == &slide_id + } + }) + .cloned() + .collect(), + next_slide_seq: 1, + next_element_seq: 1, + next_layout_seq: 1, + next_text_range_seq: document.next_text_range_seq, + next_comment_thread_seq: document.next_comment_thread_seq, + next_comment_message_seq: document.next_comment_message_seq, + } + } else { + document.clone() + }; + write_preview_images(&preview_document, &temp_dir, &request.action)?; + let mut exported_paths = collect_pngs(&temp_dir)?; + if args.slide_index.is_some() { + let rendered = + exported_paths + .pop() + .ok_or_else(|| PresentationArtifactError::ExportFailed { + path: output_path.clone(), + message: "preview renderer produced no images".to_string(), + })?; + write_preview_image( + &rendered, + &output_path, + preview_format, + scale, + quality, + &request.action, + )?; + exported_paths = vec![output_path]; + } else { + std::fs::create_dir_all(&output_path).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: output_path.clone(), + message: error.to_string(), + } + })?; + let mut relocated = Vec::new(); + for rendered in exported_paths { + let filename = rendered.file_name().ok_or_else(|| { + PresentationArtifactError::ExportFailed { + path: output_path.clone(), + message: "rendered preview had no filename".to_string(), + } + })?; + let stem = Path::new(filename) + .file_stem() + .and_then(|value| value.to_str()) + .unwrap_or("preview"); + let target = output_path.join(format!("{stem}.{}", preview_format.extension())); + write_preview_image( + &rendered, + &target, + preview_format, + scale, + quality, + &request.action, + )?; + relocated.push(target); + } + exported_paths = relocated; + } + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + "Exported slide preview".to_string(), + snapshot_for_document(document), + ); + response.exported_paths = exported_paths; + Ok(response) + } + + fn get_summary( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Presentation `{}` has {} slides, {} elements, {} layouts, and active slide {}", + document.name.as_deref().unwrap_or("Untitled"), + document.slides.len(), + document.total_element_count(), + document.layouts.len(), + document + .active_slide_index + .map(|index| index.to_string()) + .unwrap_or_else(|| "none".to_string()) + ), + snapshot_for_document(document), + ); + response.slide_list = Some(slide_list(document)); + response.layout_list = Some(layout_list(document)); + response.theme = Some(document.theme_snapshot()); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn list_slides( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} slides", document.slides.len()), + snapshot_for_document(document), + ); + response.slide_list = Some(slide_list(document)); + response.theme = Some(document.theme_snapshot()); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn list_layouts( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} layouts", document.layouts.len()), + snapshot_for_document(document), + ); + response.layout_list = Some(layout_list(document)); + response.theme = Some(document.theme_snapshot()); + Ok(response) + } + + fn list_layout_placeholders( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: LayoutIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let placeholders = layout_placeholder_list(document, &args.layout_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Listed {} placeholders for layout `{}`", + placeholders.len(), + args.layout_id + ), + snapshot_for_document(document), + ); + response.placeholder_list = Some(placeholders); + response.layout_list = Some(layout_list(document)); + Ok(response) + } + + fn list_slide_placeholders( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SlideIndexArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let slide_index = args.slide_index as usize; + let slide = document.slides.get(slide_index).ok_or_else(|| { + index_out_of_range(&request.action, slide_index, document.slides.len()) + })?; + let placeholders = slide_placeholder_list(slide, slide_index); + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Listed {} placeholders for slide {}", + placeholders.len(), + args.slide_index + ), + snapshot_for_document(document), + ); + response.placeholder_list = Some(placeholders); + response.slide_list = Some(slide_list(document)); + Ok(response) + } + + fn inspect( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: InspectArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let inspect_ndjson = inspect_document(document, &args); + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + "Generated inspection snapshot".to_string(), + snapshot_for_document(document), + ); + response.inspect_ndjson = Some(inspect_ndjson); + response.theme = Some(document.theme_snapshot()); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn resolve( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ResolveArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let resolved_record = resolve_anchor(document, &args.id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Resolved `{}`", args.id), + snapshot_for_document(document), + ); + response.resolved_record = Some(resolved_record); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn proto_snapshot( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + "Generated proto snapshot".to_string(), + snapshot_for_document(document), + ); + response.proto_json = Some(document_to_proto(document, "to_proto")?); + response.theme = Some(document.theme_snapshot()); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn record_patch( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: RecordPatchArgs = parse_args(&request.action, &request.args)?; + let patch = self.normalize_patch( + request.artifact_id.as_deref(), + args.operations, + &request.action, + )?; + let document = self.get_document(&patch.artifact_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + patch.artifact_id.clone(), + request.action, + format!("Recorded patch with {} operations", patch.operations.len()), + snapshot_for_document(document), + ); + response.patch = Some(serde_json::to_value(&patch).map_err(|error| { + PresentationArtifactError::InvalidArgs { + action: "record_patch".to_string(), + message: format!("failed to serialize patch: {error}"), + } + })?); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn apply_patch( + &mut self, + request: PresentationArtifactRequest, + _cwd: &Path, + ) -> Result { + let args: ApplyPatchArgs = parse_args(&request.action, &request.args)?; + let patch = if let Some(patch) = args.patch { + self.normalize_serialized_patch(request.artifact_id.as_deref(), patch, &request.action)? + } else { + let operations = + args.operations + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "provide either `patch` or `operations`".to_string(), + })?; + self.normalize_patch(request.artifact_id.as_deref(), operations, &request.action)? + }; + let before = self.documents.get(&patch.artifact_id).cloned(); + let Some(before_document) = before else { + return Err(PresentationArtifactError::UnknownArtifactId { + action: request.action, + artifact_id: patch.artifact_id, + }); + }; + for operation in &patch.operations { + let nested_request = PresentationArtifactRequest { + artifact_id: Some(patch.artifact_id.clone()), + action: operation.action.clone(), + args: operation.args.clone(), + }; + if let Err(error) = self.execute_action(nested_request, Path::new(".")) { + self.documents + .insert(patch.artifact_id.clone(), before_document); + return Err(error); + } + } + let document = self + .get_document(&patch.artifact_id, &request.action)? + .clone(); + self.push_history_entry(HistoryEntry { + artifact_id: patch.artifact_id.clone(), + action: request.action.clone(), + before: Some(before_document), + after: Some(document.clone()), + }); + let mut response = PresentationArtifactResponse::new( + patch.artifact_id.clone(), + request.action, + format!("Applied patch with {} operations", patch.operations.len()), + snapshot_for_document(&document), + ); + response.patch = Some(serde_json::to_value(&patch).map_err(|error| { + PresentationArtifactError::InvalidArgs { + action: "apply_patch".to_string(), + message: format!("failed to serialize patch: {error}"), + } + })?); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn undo( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let position = self + .undo_stack + .iter() + .rposition(|entry| { + request + .artifact_id + .as_deref() + .is_none_or(|artifact_id| artifact_id == entry.artifact_id) + }) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: "nothing to undo".to_string(), + })?; + let entry = self.undo_stack.remove(position); + match &entry.before { + Some(document) => { + self.documents + .insert(entry.artifact_id.clone(), document.clone()); + } + None => { + self.documents.remove(&entry.artifact_id); + } + } + self.redo_stack.push(entry.clone()); + Ok(response_for_document_state( + entry.artifact_id, + request.action, + format!("Undid `{}`", entry.action), + entry.before.as_ref(), + )) + } + + fn redo( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let position = self + .redo_stack + .iter() + .rposition(|entry| { + request + .artifact_id + .as_deref() + .is_none_or(|artifact_id| artifact_id == entry.artifact_id) + }) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: "nothing to redo".to_string(), + })?; + let entry = self.redo_stack.remove(position); + match &entry.after { + Some(document) => { + self.documents + .insert(entry.artifact_id.clone(), document.clone()); + } + None => { + self.documents.remove(&entry.artifact_id); + } + } + self.undo_stack.push(entry.clone()); + Ok(response_for_document_state( + entry.artifact_id, + request.action, + format!("Redid `{}`", entry.action), + entry.after.as_ref(), + )) + } + + fn create_layout( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: CreateLayoutArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let layout_id = document.next_layout_id(); + let kind = match args.kind.as_deref() { + Some("master") => LayoutKind::Master, + Some("layout") | None => LayoutKind::Layout, + Some(other) => { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!("unsupported layout kind `{other}`"), + }); + } + }; + let parent_layout_id = args + .parent_layout_id + .map(|parent_layout_ref| { + document + .get_layout(&parent_layout_ref, &request.action) + .map(|layout| layout.layout_id.clone()) + }) + .transpose()?; + document.layouts.push(LayoutDocument { + layout_id: layout_id.clone(), + name: args.name, + kind, + parent_layout_id, + placeholders: Vec::new(), + }); + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Created layout `{layout_id}`"), + snapshot_for_document(document), + ); + response.layout_list = Some(layout_list(document)); + Ok(response) + } + + fn add_layout_placeholder( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddLayoutPlaceholderArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let geometry = args + .geometry + .as_deref() + .map(|value| parse_shape_geometry(value, &request.action)) + .transpose()? + .unwrap_or(ShapeGeometry::Rectangle); + let frame = args.position.unwrap_or(PositionArgs { + left: 48, + top: 72, + width: 624, + height: 96, + rotation: None, + flip_horizontal: None, + flip_vertical: None, + }); + let layout_id = document + .get_layout(&args.layout_id, &request.action)? + .layout_id + .clone(); + let layout = document + .layouts + .iter_mut() + .find(|layout| layout.layout_id == layout_id) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: format!("unknown layout id `{}`", args.layout_id), + })?; + layout.placeholders.push(PlaceholderDefinition { + name: args.name, + placeholder_type: args.placeholder_type, + index: args.index, + text: args.text, + geometry, + frame: frame.into(), + }); + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added placeholder to layout `{}`", layout.layout_id), + snapshot_for_document(document), + ); + response.layout_list = Some(layout_list(document)); + Ok(response) + } + + fn set_slide_layout( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetSlideLayoutArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let layout = document + .get_layout(&args.layout_id, &request.action)? + .clone(); + let placeholders = + resolved_layout_placeholders(document, &layout.layout_id, &request.action)? + .into_iter() + .map(|resolved| resolved.definition) + .collect::>(); + let mut placeholder_elements = Vec::new(); + for placeholder in placeholders { + placeholder_elements.push(materialize_placeholder_element( + document.next_element_id(), + placeholder, + placeholder_elements.len(), + )); + } + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide.elements.retain(|element| match element { + PresentationElement::Text(text) => text.placeholder.is_none(), + PresentationElement::Shape(shape) => shape.placeholder.is_none(), + PresentationElement::Image(image) => image.placeholder.is_none(), + _ => true, + }); + slide.layout_id = Some(layout.layout_id.clone()); + slide.elements.extend(placeholder_elements); + resequence_z_order(slide); + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Applied layout `{}` to slide {}", + layout.layout_id, args.slide_index + ), + snapshot_for_document(document), + ); + response.slide_list = Some(slide_list(document)); + response.layout_list = Some(layout_list(document)); + Ok(response) + } + + fn update_placeholder_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdatePlaceholderTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + let target_name = args.name.to_ascii_lowercase(); + let element = slide + .elements + .iter_mut() + .find(|element| match element { + PresentationElement::Text(text) => text + .placeholder + .as_ref() + .map(|placeholder| placeholder.name.eq_ignore_ascii_case(&target_name)) + .unwrap_or(false), + PresentationElement::Shape(shape) => shape + .placeholder + .as_ref() + .map(|placeholder| placeholder.name.eq_ignore_ascii_case(&target_name)) + .unwrap_or(false), + _ => false, + }) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: format!( + "placeholder `{}` was not found on slide {}", + args.name, args.slide_index + ), + })?; + match element { + PresentationElement::Text(text) => text.text = args.text, + PresentationElement::Shape(shape) => shape.text = Some(args.text), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => {} + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Updated placeholder `{}` on slide {}", + args.name, args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn set_theme( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ThemeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + document.theme = normalize_theme(args, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + "Updated theme".to_string(), + snapshot_for_document(document), + ); + response.theme = Some(document.theme_snapshot()); + Ok(response) + } + + fn add_style( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let style_name = normalize_style_name(&args.name, &request.action)?; + let mut style = + normalize_text_style_with_document(document, &args.styling, &request.action)?; + style.style_name = Some(style_name.clone()); + let style_record = NamedTextStyle { + name: style_name.clone(), + style: style.clone(), + built_in: false, + }; + document + .custom_text_styles + .insert(style_name.clone(), style); + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added text style `{style_name}`"), + snapshot_for_document(document), + ); + response.resolved_record = Some(named_text_style_to_json(&style_record, "st")); + Ok(response) + } + + fn get_style( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: StyleNameArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let normalized_style_name = normalize_style_name(&args.name, &request.action)?; + let named_style = document + .named_text_styles() + .into_iter() + .find(|style| style.name == normalized_style_name) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: format!("unknown text style `{}`", args.name), + })?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Resolved text style `{}`", args.name), + snapshot_for_document(document), + ); + response.resolved_record = Some(named_text_style_to_json(&named_style, "st")); + Ok(response) + } + + fn describe_styles( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document(&artifact_id, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + "Described text styles".to_string(), + snapshot_for_document(document), + ); + response.resolved_record = Some(serde_json::json!({ + "kind": "styleList", + "styles": document + .named_text_styles() + .iter() + .map(|style| named_text_style_to_json(style, "st")) + .collect::>(), + })); + Ok(response) + } + + fn set_notes( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: NotesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide.notes.text = args.text.unwrap_or_default(); + slide.notes.rich_text = RichTextState::default(); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated notes for slide {}", args.slide_index), + snapshot_for_document(document), + )) + } + + fn set_notes_rich_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetRichTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`slide_index` is required for notes rich text".to_string(), + })?; + let (text, mut rich_text) = + normalize_rich_text_input(document, args.text, &request.action)?; + rich_text.layout = normalize_text_layout(&args.text_layout, &request.action)?; + let slide = document.get_slide_mut(slide_index, &request.action)?; + slide.notes.text = text; + slide.notes.rich_text = rich_text; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich notes for slide {slide_index}"), + snapshot_for_document(document), + )) + } + + fn append_notes( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: NotesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + let text = args.text.unwrap_or_default(); + if slide.notes.text.is_empty() { + slide.notes.text = text; + } else { + slide.notes.text = format!("{}\n{text}", slide.notes.text); + } + slide.notes.rich_text = RichTextState::default(); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Appended notes for slide {}", args.slide_index), + snapshot_for_document(document), + )) + } + + fn clear_notes( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: NotesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide.notes.text.clear(); + slide.notes.rich_text = RichTextState::default(); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Cleared notes for slide {}", args.slide_index), + snapshot_for_document(document), + )) + } + + fn set_notes_visibility( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: NotesVisibilityArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide.notes.visible = args.visible; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated notes visibility for slide {}", args.slide_index), + snapshot_for_document(document), + )) + } + + fn set_active_slide( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetActiveSlideArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + document.set_active_slide_index(args.slide_index as usize, &request.action)?; + let mut response = PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Set active slide to {}", args.slide_index), + snapshot_for_document(document), + ); + response.slide_list = Some(slide_list(document)); + response.active_slide_index = document.active_slide_index; + Ok(response) + } + + fn add_slide( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddSlideArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let mut slide = document.new_slide(args.notes, args.background_fill, &request.action)?; + if let Some(layout_id) = args.layout { + apply_layout_to_slide(document, &mut slide, &layout_id, &request.action)?; + } + let index = document.append_slide(slide); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added slide at index {index}"), + snapshot_for_document(document), + )) + } + + fn insert_slide( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: InsertSlideArgs = parse_args(&request.action, &request.args)?; + if args.index.is_some() && args.after_slide_index.is_some() { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: "provide at most one of `index` or `after_slide_index`".to_string(), + }); + } + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let index = if let Some(index) = args.index { + to_index(index)? + } else if let Some(after_slide_index) = args.after_slide_index { + after_slide_index as usize + 1 + } else { + document + .active_slide_index + .map(|active_slide_index| active_slide_index + 1) + .unwrap_or(document.slides.len()) + }; + if index > document.slides.len() { + return Err(index_out_of_range( + &request.action, + index, + document.slides.len(), + )); + } + let mut slide = document.new_slide(args.notes, args.background_fill, &request.action)?; + if let Some(layout_id) = args.layout { + apply_layout_to_slide(document, &mut slide, &layout_id, &request.action)?; + } + document.adjust_active_slide_for_insert(index); + document.slides.insert(index, slide); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Inserted slide at index {index}"), + snapshot_for_document(document), + )) + } + + fn duplicate_slide( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SlideIndexArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let source = document + .slides + .get(args.slide_index as usize) + .cloned() + .ok_or_else(|| { + index_out_of_range( + &request.action, + args.slide_index as usize, + document.slides.len(), + ) + })?; + let duplicated = document.clone_slide(source); + let insert_at = args.slide_index as usize + 1; + document.adjust_active_slide_for_insert(insert_at); + document.slides.insert(insert_at, duplicated); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Duplicated slide {} to index {insert_at}", args.slide_index), + snapshot_for_document(document), + )) + } + + fn move_slide( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: MoveSlideArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let from = args.from_index as usize; + let to = args.to_index as usize; + if from >= document.slides.len() { + return Err(index_out_of_range( + &request.action, + from, + document.slides.len(), + )); + } + if to >= document.slides.len() { + return Err(index_out_of_range( + &request.action, + to, + document.slides.len(), + )); + } + let slide = document.slides.remove(from); + document.slides.insert(to, slide); + document.adjust_active_slide_for_move(from, to); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Moved slide from index {from} to {to}"), + snapshot_for_document(document), + )) + } + + fn delete_slide( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SlideIndexArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let index = args.slide_index as usize; + if index >= document.slides.len() { + return Err(index_out_of_range( + &request.action, + index, + document.slides.len(), + )); + } + document.slides.remove(index); + document.adjust_active_slide_for_delete(index); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Deleted slide at index {index}"), + snapshot_for_document(document), + )) + } + + fn set_slide_background( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetSlideBackgroundArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let fill = normalize_color_with_document(document, &args.fill, &request.action, "fill")?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide.background_fill = Some(fill); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated background for slide {}", args.slide_index), + snapshot_for_document(document), + )) + } + + fn add_text_shape( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddTextShapeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; + let fill = args + .styling + .fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) + .transpose()?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; + let element_id = document.next_element_id(); + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide.elements.push(PresentationElement::Text(TextElement { + element_id: element_id.clone(), + text: args.text, + frame: args.position.into(), + fill, + style, + hyperlink: None, + rich_text: RichTextState { + ranges: Vec::new(), + layout: text_layout, + }, + placeholder: None, + z_order: slide.elements.len(), + })); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Added text element `{element_id}` to slide {}", + args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn add_shape( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddShapeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let text_style = + normalize_text_style_with_document(document, &args.text_style, &request.action)?; + let fill = args + .fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) + .transpose()?; + let stroke = parse_stroke(document, args.stroke, &request.action)?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; + let rich_text = args.text.as_ref().map(|_| RichTextState { + ranges: Vec::new(), + layout: text_layout, + }); + let element_id = document.next_element_id(); + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide + .elements + .push(PresentationElement::Shape(ShapeElement { + element_id: element_id.clone(), + geometry: parse_shape_geometry(&args.geometry, &request.action)?, + frame: args.position.clone().into(), + fill, + stroke, + text: args.text, + text_style, + hyperlink: None, + rich_text, + placeholder: None, + rotation_degrees: args.rotation.or(args.position.rotation), + flip_horizontal: args + .flip_horizontal + .or(args.position.flip_horizontal) + .unwrap_or(false), + flip_vertical: args + .flip_vertical + .or(args.position.flip_vertical) + .unwrap_or(false), + z_order: slide.elements.len(), + })); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Added shape element `{element_id}` to slide {}", + args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn add_connector( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddConnectorArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let element_id = document.next_element_id(); + let line = parse_connector_line(document, args.line, &request.action)?; + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide + .elements + .push(PresentationElement::Connector(ConnectorElement { + element_id: element_id.clone(), + connector_type: parse_connector_kind(&args.connector_type, &request.action)?, + start: args.start, + end: args.end, + line: StrokeStyle { + color: line.color, + width: line.width, + style: LineStyle::Solid, + }, + line_style: line.style, + start_arrow: args + .start_arrow + .as_deref() + .map(|value| parse_connector_arrow(value, &request.action)) + .transpose()? + .unwrap_or(ConnectorArrowKind::None), + end_arrow: args + .end_arrow + .as_deref() + .map(|value| parse_connector_arrow(value, &request.action)) + .transpose()? + .unwrap_or(ConnectorArrowKind::None), + arrow_size: args + .arrow_size + .as_deref() + .map(|value| parse_connector_arrow_size(value, &request.action)) + .transpose()? + .unwrap_or(ConnectorArrowScale::Medium), + label: args.label, + z_order: slide.elements.len(), + })); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Added connector element `{element_id}` to slide {}", + args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn add_image( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + let args: AddImageArgs = parse_args(&request.action, &request.args)?; + let image_source = args.image_source()?; + let is_placeholder = matches!(image_source, ImageInputSource::Placeholder); + let image_payload = match image_source { + ImageInputSource::Path(path) => Some(load_image_payload_from_path( + &resolve_path(cwd, &path), + &request.action, + )?), + ImageInputSource::DataUrl(data_url) => Some(load_image_payload_from_data_url( + &data_url, + &request.action, + )?), + ImageInputSource::Blob(blob) => { + Some(load_image_payload_from_blob(&blob, &request.action)?) + } + ImageInputSource::Uri(uri) => Some(load_image_payload_from_uri(&uri, &request.action)?), + ImageInputSource::Placeholder => None, + }; + let fit_mode = args.fit.unwrap_or(ImageFitMode::Stretch); + let lock_aspect_ratio = args + .lock_aspect_ratio + .unwrap_or(fit_mode != ImageFitMode::Stretch); + let crop = args + .crop + .map(|crop| normalize_image_crop(crop, &request.action)) + .transpose()?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let element_id = document.next_element_id(); + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide + .elements + .push(PresentationElement::Image(ImageElement { + element_id: element_id.clone(), + frame: args.position.clone().into(), + payload: image_payload, + fit_mode, + crop, + rotation_degrees: args.rotation.or(args.position.rotation), + flip_horizontal: args + .flip_horizontal + .or(args.position.flip_horizontal) + .unwrap_or(false), + flip_vertical: args + .flip_vertical + .or(args.position.flip_vertical) + .unwrap_or(false), + lock_aspect_ratio, + alt_text: args.alt, + prompt: args.prompt, + is_placeholder, + placeholder: None, + z_order: slide.elements.len(), + })); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Added image element `{element_id}` to slide {}", + args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn replace_image( + &mut self, + request: PresentationArtifactRequest, + cwd: &Path, + ) -> Result { + let args: ReplaceImageArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let image_source = match ( + &args.path, + &args.data_url, + &args.blob, + &args.uri, + &args.prompt, + ) { + (Some(path), None, None, None, None) => ImageInputSource::Path(path.clone()), + (None, Some(data_url), None, None, None) => ImageInputSource::DataUrl(data_url.clone()), + (None, None, Some(blob), None, None) => ImageInputSource::Blob(blob.clone()), + (None, None, None, Some(uri), None) => ImageInputSource::Uri(uri.clone()), + (None, None, None, None, Some(_)) => ImageInputSource::Placeholder, + _ => { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: + "provide exactly one of `path`, `data_url`, `blob`, or `uri`, or provide `prompt` for a placeholder image" + .to_string(), + }); + } + }; + let is_placeholder = matches!(image_source, ImageInputSource::Placeholder); + let image_payload = match image_source { + ImageInputSource::Path(path) => Some(load_image_payload_from_path( + &resolve_path(cwd, &path), + "replace_image", + )?), + ImageInputSource::DataUrl(data_url) => Some(load_image_payload_from_data_url( + &data_url, + "replace_image", + )?), + ImageInputSource::Blob(blob) => { + Some(load_image_payload_from_blob(&blob, "replace_image")?) + } + ImageInputSource::Uri(uri) => Some(load_image_payload_from_uri(&uri, "replace_image")?), + ImageInputSource::Placeholder => None, + }; + let fit_mode = args.fit.unwrap_or(ImageFitMode::Stretch); + let lock_aspect_ratio = args + .lock_aspect_ratio + .unwrap_or(fit_mode != ImageFitMode::Stretch); + let crop = args + .crop + .map(|crop| normalize_image_crop(crop, &request.action)) + .transpose()?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Image(image) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not an image", args.element_id), + }); + }; + image.payload = image_payload; + image.fit_mode = fit_mode; + image.crop = crop; + if let Some(rotation) = args.rotation { + image.rotation_degrees = Some(rotation); + } + if let Some(flip_horizontal) = args.flip_horizontal { + image.flip_horizontal = flip_horizontal; + } + if let Some(flip_vertical) = args.flip_vertical { + image.flip_vertical = flip_vertical; + } + image.lock_aspect_ratio = lock_aspect_ratio; + image.alt_text = args.alt; + image.prompt = args.prompt; + image.is_placeholder = is_placeholder; + Ok(PresentationArtifactResponse::new( + artifact_id, + "replace_image".to_string(), + format!("Replaced image `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn add_table( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddTableArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let rows = coerce_table_rows(args.rows, &request.action)?; + let borders = parse_table_borders(document, args.borders, &request.action)?; + let style_options = parse_table_style_options(args.style_options); + let mut frame: Rect = args.position.into(); + let (column_widths, row_heights) = normalize_table_dimensions( + &rows, + frame, + args.column_widths, + args.row_heights, + &request.action, + )?; + frame.width = column_widths.iter().sum(); + frame.height = row_heights.iter().sum(); + let element_id = document.next_element_id(); + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide + .elements + .push(PresentationElement::Table(TableElement { + element_id: element_id.clone(), + frame, + rows, + column_widths, + row_heights, + style: args.style, + style_options, + borders, + right_to_left: args.right_to_left.unwrap_or(false), + merges: Vec::new(), + z_order: slide.elements.len(), + })); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Added table element `{element_id}` to slide {}", + args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn update_table_cell( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateTableCellArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let text_style = + normalize_text_style_with_document(document, &args.styling, &request.action)?; + let background_fill = args + .background_fill + .as_deref() + .map(|fill| { + normalize_color_with_document(document, fill, &request.action, "background_fill") + }) + .transpose()?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a table", args.element_id), + }); + }; + let row = args.row as usize; + let column = args.column as usize; + if row >= table.rows.len() || column >= table.rows[row].len() { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!("cell ({row}, {column}) is out of bounds"), + }); + } + let cell = &mut table.rows[row][column]; + cell.text = cell_value_to_string(args.value); + cell.text_style = text_style; + cell.background_fill = background_fill; + cell.rich_text = RichTextState::default(); + cell.alignment = args + .alignment + .as_deref() + .map(|value| parse_alignment(value, &request.action)) + .transpose()?; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated table cell ({row}, {column})"), + snapshot_for_document(document), + )) + } + + fn update_table_style( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateTableStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let borders = parse_table_borders(document, args.borders, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a table", args.element_id), + }); + }; + table.style = args.style; + if let Some(borders) = borders { + if let Some(existing) = table.borders.as_mut() { + if borders.outside.is_some() { + existing.outside = borders.outside; + } + if borders.inside.is_some() { + existing.inside = borders.inside; + } + if borders.top.is_some() { + existing.top = borders.top; + } + if borders.bottom.is_some() { + existing.bottom = borders.bottom; + } + if borders.left.is_some() { + existing.left = borders.left; + } + if borders.right.is_some() { + existing.right = borders.right; + } + } else { + table.borders = Some(borders); + } + } + if let Some(style_options) = args.style_options { + if let Some(value) = style_options.header_row { + table.style_options.header_row = value; + } + if let Some(value) = style_options.banded_rows { + table.style_options.banded_rows = value; + } + if let Some(value) = style_options.banded_columns { + table.style_options.banded_columns = value; + } + if let Some(value) = style_options.first_column { + table.style_options.first_column = value; + } + if let Some(value) = style_options.last_column { + table.style_options.last_column = value; + } + if let Some(value) = style_options.total_row { + table.style_options.total_row = value; + } + } + if let Some(right_to_left) = args.right_to_left { + table.right_to_left = right_to_left; + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated table style for `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn style_table_block( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: StyleTableBlockArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let text_style = + normalize_text_style_with_document(document, &args.styling, &request.action)?; + let background_fill = args + .background_fill + .as_deref() + .map(|fill| { + normalize_color_with_document(document, fill, &request.action, "background_fill") + }) + .transpose()?; + let borders = parse_table_borders(document, args.borders, &request.action)?; + let alignment = args + .alignment + .as_deref() + .map(|value| parse_alignment(value, &request.action)) + .transpose()?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a table", args.element_id), + }); + }; + let end_row = (args.row + args.row_count) as usize; + let end_column = (args.column + args.column_count) as usize; + for row_index in args.row as usize..end_row { + if row_index >= table.rows.len() { + break; + } + for column_index in args.column as usize..end_column { + if column_index >= table.rows[row_index].len() { + break; + } + let cell = &mut table.rows[row_index][column_index]; + cell.text_style = text_style.clone(); + if let Some(fill) = background_fill.clone() { + cell.background_fill = Some(fill); + } + if let Some(alignment) = alignment { + cell.alignment = Some(alignment); + } + if let Some(borders) = borders.clone() { + cell.borders = Some(borders); + } + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Styled table block for `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn merge_table_cells( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: MergeTableCellsArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a table", args.element_id), + }); + }; + let region = TableMergeRegion { + start_row: args.start_row as usize, + end_row: args.end_row as usize, + start_column: args.start_column as usize, + end_column: args.end_column as usize, + }; + table.merges.push(region); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Merged table cells in `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn add_chart( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddChartArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let chart_type = parse_chart_type(&args.chart_type, &request.action)?; + let series = parse_chart_series(document, args.series, &request.action)?; + let legend_text_style = + normalize_text_style_with_document(document, &args.legend_text_style, &request.action)?; + let data_labels = parse_chart_data_labels(document, args.data_labels, &request.action)?; + let chart_fill = args + .chart_fill + .as_deref() + .map(|value| { + normalize_color_with_document(document, value, &request.action, "chart_fill") + }) + .transpose()?; + let plot_area_fill = args + .plot_area_fill + .as_deref() + .map(|value| { + normalize_color_with_document(document, value, &request.action, "plot_area_fill") + }) + .transpose()?; + let element_id = document.next_element_id(); + let slide = document.get_slide_mut(args.slide_index, &request.action)?; + slide + .elements + .push(PresentationElement::Chart(ChartElement { + element_id: element_id.clone(), + frame: args.position.into(), + chart_type, + categories: args.categories, + series, + title: args.title, + style_index: args.style_index, + has_legend: args.has_legend.unwrap_or(false), + legend: Some(ChartLegend { + position: args.legend_position, + text_style: legend_text_style, + }), + x_axis: Some(ChartAxisSpec { + title: args.x_axis_title, + }), + y_axis: Some(ChartAxisSpec { + title: args.y_axis_title, + }), + data_labels, + chart_fill, + plot_area_fill, + z_order: slide.elements.len(), + })); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!( + "Added chart element `{element_id}` to slide {}", + args.slide_index + ), + snapshot_for_document(document), + )) + } + + fn update_chart( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateChartArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let legend_text_style = + normalize_text_style_with_document(document, &args.legend_text_style, &request.action)?; + let data_labels = parse_chart_data_labels(document, args.data_labels, &request.action)?; + let chart_fill = args + .chart_fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "chart_fill")) + .transpose()?; + let plot_area_fill = args + .plot_area_fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "plot_area_fill")) + .transpose()?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Chart(chart) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a chart", args.element_id), + }); + }; + if let Some(title) = args.title { + chart.title = Some(title); + } + if let Some(categories) = args.categories { + chart.categories = categories; + } + if let Some(style_index) = args.style_index { + chart.style_index = Some(style_index); + } + if let Some(has_legend) = args.has_legend { + chart.has_legend = has_legend; + } + if args.legend_position.is_some() || !text_style_is_empty(&legend_text_style) { + chart.legend = Some(ChartLegend { + position: args.legend_position, + text_style: legend_text_style, + }); + } + if args.x_axis_title.is_some() { + chart.x_axis = Some(ChartAxisSpec { + title: args.x_axis_title, + }); + } + if args.y_axis_title.is_some() { + chart.y_axis = Some(ChartAxisSpec { + title: args.y_axis_title, + }); + } + if data_labels.is_some() { + chart.data_labels = data_labels; + } + if chart_fill.is_some() { + chart.chart_fill = chart_fill; + } + if plot_area_fill.is_some() { + chart.plot_area_fill = plot_area_fill; + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated chart `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn add_chart_series( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddChartSeriesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let series = parse_chart_series( + document, + vec![ChartSeriesArgs { + name: args.name, + values: args.values, + categories: args.categories, + x_values: args.x_values, + fill: args.fill, + stroke: args.stroke, + marker: args.marker, + data_label_overrides: None, + }], + &request.action, + )?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + let PresentationElement::Chart(chart) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{}` is not a chart", args.element_id), + }); + }; + chart.series.extend(series); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added chart series to `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn update_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; + let fill = args + .styling + .fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) + .transpose()?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + match element { + PresentationElement::Text(text) => { + text.text = args.text; + if let Some(fill) = fill.clone() { + text.fill = Some(fill); + } + text.style = style; + text.rich_text = RichTextState { + ranges: Vec::new(), + layout: text_layout, + }; + } + PresentationElement::Shape(shape) => { + if shape.text.is_none() { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` does not contain editable text", + args.element_id + ), + }); + } + shape.text = Some(args.text); + if let Some(fill) = fill { + shape.fill = Some(fill); + } + shape.text_style = style; + shape.rich_text = Some(RichTextState { + ranges: Vec::new(), + layout: text_layout, + }); + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` is `{}`; only text-bearing elements support `update_text`", + args.element_id, + other.kind() + ), + }); + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated text for element `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn set_rich_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetRichTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let (text, mut rich_text) = + normalize_rich_text_input(document, args.text, &request.action)?; + rich_text.layout = normalize_text_layout(&args.text_layout, &request.action)?; + let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; + if args.notes.unwrap_or(false) { + let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`slide_index` is required for notes rich text".to_string(), + })?; + let slide = document.get_slide_mut(slide_index, &request.action)?; + slide.notes.text = text; + slide.notes.rich_text = rich_text; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich text for notes on slide {slide_index}"), + snapshot_for_document(document), + )); + } + if let Some(element_id) = args.element_id { + if let (Some(row), Some(column)) = (args.row, args.column) { + let element = document.find_element_mut(&element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{element_id}` is not a table"), + }); + }; + let row = row as usize; + let column = column as usize; + if row >= table.rows.len() || column >= table.rows[row].len() { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!("cell ({row}, {column}) is out of bounds"), + }); + } + let cell = &mut table.rows[row][column]; + cell.text = text; + cell.text_style = style; + cell.rich_text = rich_text; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich text for table cell ({row}, {column})"), + snapshot_for_document(document), + )); + } + let element = document.find_element_mut(&element_id, &request.action)?; + match element { + PresentationElement::Text(text_element) => { + text_element.text = text; + text_element.style = style; + text_element.rich_text = rich_text; + } + PresentationElement::Shape(shape) => { + if shape.text.is_none() { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{element_id}` does not contain editable text" + ), + }); + } + shape.text = Some(text); + shape.text_style = style; + shape.rich_text = Some(rich_text); + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{element_id}` is `{}`; only text-bearing elements support `set_rich_text`", + other.kind() + ), + }); + } + } + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated rich text for element `{element_id}`"), + snapshot_for_document(document), + )); + } + Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: "provide `element_id` or `slide_index` with `notes: true`".to_string(), + }) + } + + fn format_text_range( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: FormatTextRangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let style = normalize_text_style_with_document(document, &args.styling, &request.action)?; + let hyperlink = args + .link + .as_ref() + .map(|link| parse_rich_text_link(link, &request.action)) + .transpose()?; + let layout = normalize_text_layout(&args.text_layout, &request.action)?; + let apply_annotation = + |range_id: String, + text: &str, + rich_text: &mut RichTextState| + -> Result<(), PresentationArtifactError> { + let (start_cp, length, _) = resolve_text_range_selector( + text, + args.query.as_deref(), + args.occurrence, + args.start_cp, + args.length, + &request.action, + )?; + rich_text.ranges.push(TextRangeAnnotation { + range_id, + start_cp, + length, + style: style.clone(), + hyperlink: hyperlink.clone(), + spacing_before: args.spacing_before.map(|value| value * 100), + spacing_after: args.spacing_after.map(|value| value * 100), + line_spacing: args.line_spacing, + }); + if layout.insets.is_some() + || layout.wrap.is_some() + || layout.auto_fit.is_some() + || layout.vertical_alignment.is_some() + { + rich_text.layout = layout.clone(); + } + Ok(()) + }; + if args.notes.unwrap_or(false) { + let slide_index = args.slide_index.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`slide_index` is required for notes text ranges".to_string(), + })?; + let range_id = document.next_text_range_id(); + let slide = document.get_slide_mut(slide_index, &request.action)?; + apply_annotation(range_id, &slide.notes.text, &mut slide.notes.rich_text)?; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Formatted notes text range on slide {slide_index}"), + snapshot_for_document(document), + )); + } + let element_id = args.element_id.clone().ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "`element_id` is required unless formatting notes".to_string(), + })?; + if let (Some(row), Some(column)) = (args.row, args.column) { + let range_id = document.next_text_range_id(); + let element = document.find_element_mut(&element_id, &request.action)?; + let PresentationElement::Table(table) = element else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!("element `{element_id}` is not a table"), + }); + }; + let row = row as usize; + let column = column as usize; + if row >= table.rows.len() || column >= table.rows[row].len() { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!("cell ({row}, {column}) is out of bounds"), + }); + } + let cell = &mut table.rows[row][column]; + apply_annotation(range_id, &cell.text, &mut cell.rich_text)?; + return Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Formatted table cell text range ({row}, {column})"), + snapshot_for_document(document), + )); + } + let range_id = document.next_text_range_id(); + let element = document.find_element_mut(&element_id, &request.action)?; + match element { + PresentationElement::Text(text) => { + apply_annotation(range_id, &text.text, &mut text.rich_text)?; + } + PresentationElement::Shape(shape) => { + let text_value = shape.text.as_ref().ok_or_else(|| { + PresentationArtifactError::UnsupportedFeature { + action: request.action.clone(), + message: format!("element `{element_id}` does not contain editable text"), + } + })?; + let rich_text = shape.rich_text.get_or_insert_with(RichTextState::default); + apply_annotation(range_id, text_value, rich_text)?; + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{element_id}` is `{}`; only text-bearing elements support `format_text_range`", + other.kind() + ), + }); + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Formatted text range on element `{element_id}`"), + snapshot_for_document(document), + )) + } + + fn replace_text( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ReplaceTextArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + match element { + PresentationElement::Text(text) => { + if !text.text.contains(&args.search) { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!( + "text `{}` was not found in element `{}`", + args.search, args.element_id + ), + }); + } + text.text = text.text.replace(&args.search, &args.replace); + } + PresentationElement::Shape(shape) => { + let Some(text) = &mut shape.text else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` does not contain editable text", + args.element_id + ), + }); + }; + if !text.contains(&args.search) { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!( + "text `{}` was not found in element `{}`", + args.search, args.element_id + ), + }); + } + *text = text.replace(&args.search, &args.replace); + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` is `{}`; only text-bearing elements support `replace_text`", + args.element_id, + other.kind() + ), + }); + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Replaced text in element `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn insert_text_after( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: InsertTextAfterArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let element = document.find_element_mut(&args.element_id, &request.action)?; + match element { + PresentationElement::Text(text) => { + let Some(index) = text.text.find(&args.after) else { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!( + "text `{}` was not found in element `{}`", + args.after, args.element_id + ), + }); + }; + let insert_at = index + args.after.len(); + text.text.insert_str(insert_at, &args.insert); + } + PresentationElement::Shape(shape) => { + let Some(text) = &mut shape.text else { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` does not contain editable text", + args.element_id + ), + }); + }; + let Some(index) = text.find(&args.after) else { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: format!( + "text `{}` was not found in element `{}`", + args.after, args.element_id + ), + }); + }; + let insert_at = index + args.after.len(); + text.insert_str(insert_at, &args.insert); + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` is `{}`; only text-bearing elements support `insert_text_after`", + args.element_id, + other.kind() + ), + }); + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Inserted text in element `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn set_hyperlink( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetHyperlinkArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let clear = args.clear.unwrap_or(false); + let hyperlink = if clear { + None + } else { + Some(parse_hyperlink_state(document, &args, &request.action)?) + }; + let element = document.find_element_mut(&args.element_id, &request.action)?; + match element { + PresentationElement::Text(text) => text.hyperlink = hyperlink, + PresentationElement::Shape(shape) => shape.hyperlink = hyperlink, + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: format!( + "element `{}` is `{}`; only text boxes and shapes support `set_hyperlink`", + args.element_id, + other.kind() + ), + }); + } + } + Ok(PresentationArtifactResponse::new( + artifact_id, + "set_hyperlink".to_string(), + if clear { + format!("Cleared hyperlink for element `{}`", args.element_id) + } else { + format!("Updated hyperlink for element `{}`", args.element_id) + }, + snapshot_for_document(document), + )) + } + + fn set_comment_author( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: SetCommentAuthorArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + document.comment_self = Some(CommentAuthorProfile { + display_name: args.display_name, + initials: args.initials, + email: args.email, + }); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + "Updated comment author".to_string(), + snapshot_for_document(document), + )) + } + + fn add_comment_thread( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddCommentThreadArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let author = document.comment_self.clone().ok_or_else(|| { + PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "set a comment author first with `set_comment_author`".to_string(), + } + })?; + let target = if let Some(slide_index) = args.slide_index { + let slide = document.get_slide_mut(slide_index, &request.action)?; + if let Some(element_id) = args.element_id { + if args.query.is_some() || args.start_cp.is_some() { + let (text, _rich_text) = lookup_text_target( + slide, + &element_id, + None, + None, + &request.action, + )?; + let (start_cp, length, context) = resolve_text_range_selector( + text, + args.query.as_deref(), + args.occurrence, + args.start_cp, + args.length, + &request.action, + )?; + CommentTarget::TextRange { + slide_id: slide.slide_id.clone(), + element_id: normalize_element_lookup_id(&element_id).to_string(), + start_cp, + length, + context, + } + } else { + CommentTarget::Element { + slide_id: slide.slide_id.clone(), + element_id: normalize_element_lookup_id(&element_id).to_string(), + } + } + } else { + CommentTarget::Slide { + slide_id: slide.slide_id.clone(), + } + } + } else { + return Err(PresentationArtifactError::InvalidArgs { + action: request.action, + message: "`slide_index` is required for comment threads".to_string(), + }); + }; + let thread_id = document.next_comment_thread_id(); + let message_id = document.next_comment_message_id(); + document.comment_threads.push(CommentThread { + thread_id: thread_id.clone(), + target, + position: args.position.map(|position| CommentPosition { + x: position.x, + y: position.y, + }), + status: CommentThreadStatus::Active, + messages: vec![CommentMessage { + message_id, + author, + text: args.text, + created_at: "2026-03-03T00:00:00Z".to_string(), + reactions: Vec::new(), + }], + }); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added comment thread `{thread_id}`"), + snapshot_for_document(document), + )) + } + + fn add_comment_reply( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: AddCommentReplyArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let author = document.comment_self.clone().ok_or_else(|| { + PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: "set a comment author first with `set_comment_author`".to_string(), + } + })?; + let message_id = document.next_comment_message_id(); + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + thread.messages.push(CommentMessage { + message_id, + author, + text: args.text, + created_at: "2026-03-03T00:00:00Z".to_string(), + reactions: Vec::new(), + }); + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Added reply to `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn toggle_comment_reaction( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ToggleCommentReactionArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + let target_message_id = args + .message_id + .clone() + .or_else(|| thread.messages.last().map(|message| message.message_id.clone())) + .unwrap_or_default(); + let message = thread + .messages + .iter_mut() + .find(|message| message.message_id == target_message_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment message `{target_message_id}`"), + })?; + if let Some(index) = message.reactions.iter().position(|emoji| emoji == &args.emoji) { + message.reactions.remove(index); + } else { + message.reactions.push(args.emoji.clone()); + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Toggled reaction on `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn resolve_comment_thread( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: CommentThreadIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + thread.status = CommentThreadStatus::Resolved; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Resolved `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn reopen_comment_thread( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: CommentThreadIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let thread = document + .comment_threads + .iter_mut() + .find(|thread| thread.thread_id == args.thread_id) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("unknown comment thread `{}`", args.thread_id), + })?; + thread.status = CommentThreadStatus::Active; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Reopened `{}`", args.thread_id), + snapshot_for_document(document), + )) + } + + fn update_shape_style( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: UpdateShapeStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let fill = args + .fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, &request.action, "fill")) + .transpose()?; + let stroke = args + .stroke + .clone() + .map(|value| parse_required_stroke(document, value, &request.action)) + .transpose()?; + let text_layout = normalize_text_layout(&args.text_layout, &request.action)?; + let has_text_layout = text_layout.insets.is_some() + || text_layout.wrap.is_some() + || text_layout.auto_fit.is_some() + || text_layout.vertical_alignment.is_some(); + let element = document.find_element_mut(&args.element_id, &request.action)?; + match element { + PresentationElement::Text(text) => { + if let Some(position) = args.position { + text.frame = apply_partial_position(text.frame, position); + } + if let Some(fill) = fill.clone() { + text.fill = Some(fill); + } + if has_text_layout { + text.rich_text.layout = text_layout; + } + if args.stroke.is_some() + || args.rotation.is_some() + || args.flip_horizontal.is_some() + || args.flip_vertical.is_some() + { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: + "text elements support only `position`, `z_order`, and `fill` updates" + .to_string(), + }); + } + } + PresentationElement::Shape(shape) => { + let position_rotation = args + .position + .as_ref() + .and_then(|position| position.rotation); + let position_flip_horizontal = args + .position + .as_ref() + .and_then(|position| position.flip_horizontal); + let position_flip_vertical = args + .position + .as_ref() + .and_then(|position| position.flip_vertical); + if let Some(position) = args.position { + shape.frame = apply_partial_position(shape.frame, position); + } + if let Some(fill) = fill { + shape.fill = Some(fill); + } + if let Some(stroke) = stroke { + shape.stroke = Some(stroke); + } + if let Some(rotation) = args.rotation.or(position_rotation) { + shape.rotation_degrees = Some(rotation); + } + if let Some(flip_horizontal) = args.flip_horizontal.or(position_flip_horizontal) { + shape.flip_horizontal = flip_horizontal; + } + if let Some(flip_vertical) = args.flip_vertical.or(position_flip_vertical) { + shape.flip_vertical = flip_vertical; + } + if shape.text.is_some() && has_text_layout { + shape.rich_text = Some(RichTextState { + ranges: shape.rich_text.take().unwrap_or_default().ranges, + layout: text_layout, + }); + } + } + PresentationElement::Connector(connector) => { + if args.fill.is_some() + || args.rotation.is_some() + || args.flip_horizontal.is_some() + || args.flip_vertical.is_some() + || args.fit.is_some() + || args.crop.is_some() + || args.lock_aspect_ratio.is_some() + { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: + "connector elements support only `position`, `stroke`, and `z_order` updates" + .to_string(), + }); + } + if let Some(position) = args.position { + let updated = apply_partial_position( + Rect { + left: connector.start.left, + top: connector.start.top, + width: connector.end.left.abs_diff(connector.start.left), + height: connector.end.top.abs_diff(connector.start.top), + }, + position, + ); + connector.start = PointArgs { + left: updated.left, + top: updated.top, + }; + connector.end = PointArgs { + left: updated.left.saturating_add(updated.width), + top: updated.top.saturating_add(updated.height), + }; + } + if let Some(stroke) = stroke { + connector.line = stroke; + } + } + PresentationElement::Image(image) => { + let position_rotation = args + .position + .as_ref() + .and_then(|position| position.rotation); + let position_flip_horizontal = args + .position + .as_ref() + .and_then(|position| position.flip_horizontal); + let position_flip_vertical = args + .position + .as_ref() + .and_then(|position| position.flip_vertical); + if args.fill.is_some() || args.stroke.is_some() { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: + "image elements support only `position`, `fit`, `crop`, `rotation`, `flip_horizontal`, `flip_vertical`, `lock_aspect_ratio`, and `z_order` updates" + .to_string(), + }); + } + if let Some(position) = args.position { + image.frame = apply_partial_position_to_image(image, position); + } + if let Some(fit) = args.fit { + image.fit_mode = fit; + if !matches!(fit, ImageFitMode::Stretch) && args.lock_aspect_ratio.is_none() { + image.lock_aspect_ratio = true; + } + } + if let Some(crop) = args.crop { + image.crop = Some(normalize_image_crop(crop, &request.action)?); + } + if let Some(rotation) = args.rotation.or(position_rotation) { + image.rotation_degrees = Some(rotation); + } + if let Some(flip_horizontal) = args.flip_horizontal.or(position_flip_horizontal) { + image.flip_horizontal = flip_horizontal; + } + if let Some(flip_vertical) = args.flip_vertical.or(position_flip_vertical) { + image.flip_vertical = flip_vertical; + } + if let Some(lock_aspect_ratio) = args.lock_aspect_ratio { + image.lock_aspect_ratio = lock_aspect_ratio; + } + } + PresentationElement::Table(table) => { + if args.fill.is_some() + || args.stroke.is_some() + || args.rotation.is_some() + || args.flip_horizontal.is_some() + || args.flip_vertical.is_some() + { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: "table elements support only `position` and `z_order` updates" + .to_string(), + }); + } + if let Some(position) = args.position { + table.frame = apply_partial_position(table.frame, position); + } + } + PresentationElement::Chart(chart) => { + if args.fill.is_some() + || args.stroke.is_some() + || args.rotation.is_some() + || args.flip_horizontal.is_some() + || args.flip_vertical.is_some() + { + return Err(PresentationArtifactError::UnsupportedFeature { + action: request.action, + message: "chart elements support only `position` and `z_order` updates" + .to_string(), + }); + } + if let Some(position) = args.position { + chart.frame = apply_partial_position(chart.frame, position); + } + } + } + if let Some(z_order) = args.z_order { + document.set_z_order(&args.element_id, z_order as usize, &request.action)?; + } + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Updated style for element `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn delete_element( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ElementIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + document.remove_element(&args.element_id, &request.action)?; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Deleted element `{}`", args.element_id), + snapshot_for_document(document), + )) + } + + fn bring_to_front( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ElementIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + let target_index = document.total_element_count(); + document.set_z_order(&args.element_id, target_index, &request.action)?; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Brought `{}` to front", args.element_id), + snapshot_for_document(document), + )) + } + + fn send_to_back( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let args: ElementIdArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let document = self.get_document_mut(&artifact_id, &request.action)?; + document.set_z_order(&args.element_id, 0, &request.action)?; + Ok(PresentationArtifactResponse::new( + artifact_id, + request.action, + format!("Sent `{}` to back", args.element_id), + snapshot_for_document(document), + )) + } + + fn delete_artifact( + &mut self, + request: PresentationArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let removed = self.documents.remove(&artifact_id).ok_or_else(|| { + PresentationArtifactError::UnknownArtifactId { + action: request.action.clone(), + artifact_id: artifact_id.clone(), + } + })?; + Ok(PresentationArtifactResponse { + artifact_id, + action: request.action, + summary: format!( + "Deleted in-memory artifact `{}` with {} slides", + removed.artifact_id, + removed.slides.len() + ), + executed_actions: None, + exported_paths: Vec::new(), + artifact_snapshot: None, + slide_list: None, + layout_list: None, + placeholder_list: None, + theme: None, + inspect_ndjson: None, + resolved_record: None, + proto_json: None, + patch: None, + active_slide_index: None, + }) + } + + fn get_document( + &self, + artifact_id: &str, + action: &str, + ) -> Result<&PresentationDocument, PresentationArtifactError> { + self.documents.get(artifact_id).ok_or_else(|| { + PresentationArtifactError::UnknownArtifactId { + action: action.to_string(), + artifact_id: artifact_id.to_string(), + } + }) + } + + fn get_document_mut( + &mut self, + artifact_id: &str, + action: &str, + ) -> Result<&mut PresentationDocument, PresentationArtifactError> { + self.documents.get_mut(artifact_id).ok_or_else(|| { + PresentationArtifactError::UnknownArtifactId { + action: action.to_string(), + artifact_id: artifact_id.to_string(), + } + }) + } + + fn normalize_patch( + &self, + request_artifact_id: Option<&str>, + operations: Vec, + action: &str, + ) -> Result { + if operations.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`operations` must contain at least one entry".to_string(), + }); + } + let mut patch_artifact_id = request_artifact_id.map(str::to_owned); + let mut normalized_operations = Vec::with_capacity(operations.len()); + for operation in operations { + let operation_artifact_id = operation + .artifact_id + .or_else(|| request_artifact_id.map(str::to_owned)) + .ok_or_else(|| PresentationArtifactError::MissingArtifactId { + action: action.to_string(), + })?; + if let Some(existing_artifact_id) = &patch_artifact_id { + if existing_artifact_id != &operation_artifact_id { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "patch operations must target a single artifact, found both `{existing_artifact_id}` and `{operation_artifact_id}`" + ), + }); + } + } else { + patch_artifact_id = Some(operation_artifact_id.clone()); + } + if !patch_operation_supported(&operation.action) { + return Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!( + "patch operations do not support nested action `{}`", + operation.action + ), + }); + } + normalized_operations.push(PatchOperation { + action: operation.action, + args: operation.args, + }); + } + let artifact_id = + patch_artifact_id.ok_or_else(|| PresentationArtifactError::MissingArtifactId { + action: action.to_string(), + })?; + self.get_document(&artifact_id, action)?; + Ok(PresentationPatch { + version: 1, + artifact_id, + operations: normalized_operations, + }) + } + + fn normalize_serialized_patch( + &self, + request_artifact_id: Option<&str>, + patch: PresentationPatch, + action: &str, + ) -> Result { + if patch.version != 1 { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported patch version `{}`", patch.version), + }); + } + if patch.operations.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`patch.operations` must contain at least one entry".to_string(), + }); + } + if let Some(request_artifact_id) = request_artifact_id + && request_artifact_id != patch.artifact_id + { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "request artifact `{request_artifact_id}` does not match patch artifact `{}`", + patch.artifact_id + ), + }); + } + for operation in &patch.operations { + if !patch_operation_supported(&operation.action) { + return Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!( + "patch operations do not support nested action `{}`", + operation.action + ), + }); + } + } + self.get_document(&patch.artifact_id, action)?; + Ok(patch) + } +} + +fn lookup_text_target<'a>( + slide: &'a PresentationSlide, + element_id: &str, + _row: Option, + _column: Option, + action: &str, +) -> Result<(&'a str, Option<&'a RichTextState>), PresentationArtifactError> { + let normalized_element_id = normalize_element_lookup_id(element_id); + let element = slide + .elements + .iter() + .find(|element| element.element_id() == normalized_element_id) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown element `{element_id}` on slide `{}`", slide.slide_id), + })?; + match element { + PresentationElement::Text(text) => Ok((&text.text, Some(&text.rich_text))), + PresentationElement::Shape(shape) => shape + .text + .as_deref() + .map(|text| (text, shape.rich_text.as_ref())) + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("element `{element_id}` does not contain editable text"), + }), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!( + "element `{element_id}` does not support text-range comments" + ), + }), + } +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/mod.rs b/codex-rs/artifact-presentation/src/presentation_artifact/mod.rs new file mode 100644 index 0000000000..8497062a91 --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/mod.rs @@ -0,0 +1,10 @@ +include!("api.rs"); +include!("manager.rs"); +include!("response.rs"); +include!("model.rs"); +include!("args.rs"); +include!("parsing.rs"); +include!("proto.rs"); +include!("inspect.rs"); +include!("pptx.rs"); +include!("snapshot.rs"); diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/model.rs b/codex-rs/artifact-presentation/src/presentation_artifact/model.rs new file mode 100644 index 0000000000..b5cd5d00a3 --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/model.rs @@ -0,0 +1,1934 @@ +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ThemeState { + color_scheme: HashMap, + major_font: Option, + minor_font: Option, +} + +impl ThemeState { + fn resolve_color(&self, color: &str) -> Option { + let key = color.trim().to_ascii_lowercase(); + let alias = match key.as_str() { + "background1" => "bg1", + "background2" => "bg2", + "text1" => "tx1", + "text2" => "tx2", + "dark1" => "dk1", + "dark2" => "dk2", + "light1" => "lt1", + "light2" => "lt2", + other => other, + }; + self.color_scheme + .get(alias) + .or_else(|| self.color_scheme.get(&key)) + .cloned() + .map(|value| value.trim_start_matches('#').to_uppercase()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum LayoutKind { + Layout, + Master, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct LayoutDocument { + layout_id: String, + name: String, + kind: LayoutKind, + parent_layout_id: Option, + placeholders: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PlaceholderDefinition { + name: String, + placeholder_type: String, + index: Option, + text: Option, + geometry: ShapeGeometry, + frame: Rect, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ResolvedPlaceholder { + source_layout_id: String, + definition: PlaceholderDefinition, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct NotesState { + text: String, + visible: bool, + #[serde(default)] + rich_text: RichTextState, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TextStyle { + style_name: Option, + font_size: Option, + font_family: Option, + color: Option, + alignment: Option, + bold: bool, + italic: bool, + underline: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct NamedTextStyle { + name: String, + style: TextStyle, + built_in: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct HyperlinkState { + target: HyperlinkTarget, + tooltip: Option, + highlight_click: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +enum HyperlinkTarget { + Url(String), + Slide(u32), + FirstSlide, + LastSlide, + NextSlide, + PreviousSlide, + EndShow, + Email { + address: String, + subject: Option, + }, + File(String), +} + +impl HyperlinkTarget { + fn relationship_target(&self) -> String { + match self { + Self::Url(url) => url.clone(), + Self::Slide(slide_index) => format!("slide{}.xml", slide_index + 1), + Self::FirstSlide => "ppaction://hlinkshowjump?jump=firstslide".to_string(), + Self::LastSlide => "ppaction://hlinkshowjump?jump=lastslide".to_string(), + Self::NextSlide => "ppaction://hlinkshowjump?jump=nextslide".to_string(), + Self::PreviousSlide => "ppaction://hlinkshowjump?jump=previousslide".to_string(), + Self::EndShow => "ppaction://hlinkshowjump?jump=endshow".to_string(), + Self::Email { address, subject } => { + let mut mailto = format!("mailto:{address}"); + if let Some(subject) = subject { + mailto.push_str(&format!("?subject={subject}")); + } + mailto + } + Self::File(path) => format!("file:///{}", path.replace('\\', "/")), + } + } + + fn is_external(&self) -> bool { + matches!(self, Self::Url(_) | Self::Email { .. } | Self::File(_)) + } +} + +impl HyperlinkState { + fn to_ppt_rs(&self, relationship_id: &str) -> PptHyperlink { + let hyperlink = match &self.target { + HyperlinkTarget::Url(url) => PptHyperlink::new(PptHyperlinkAction::url(url)), + HyperlinkTarget::Slide(slide_index) => { + PptHyperlink::new(PptHyperlinkAction::slide(slide_index + 1)) + } + HyperlinkTarget::FirstSlide => PptHyperlink::new(PptHyperlinkAction::FirstSlide), + HyperlinkTarget::LastSlide => PptHyperlink::new(PptHyperlinkAction::LastSlide), + HyperlinkTarget::NextSlide => PptHyperlink::new(PptHyperlinkAction::NextSlide), + HyperlinkTarget::PreviousSlide => PptHyperlink::new(PptHyperlinkAction::PreviousSlide), + HyperlinkTarget::EndShow => PptHyperlink::new(PptHyperlinkAction::EndShow), + HyperlinkTarget::Email { address, subject } => PptHyperlink::new(match subject { + Some(subject) => PptHyperlinkAction::email_with_subject(address, subject), + None => PptHyperlinkAction::email(address), + }), + HyperlinkTarget::File(path) => PptHyperlink::new(PptHyperlinkAction::file(path)), + }; + let hyperlink = if let Some(tooltip) = &self.tooltip { + hyperlink.with_tooltip(tooltip) + } else { + hyperlink + }; + hyperlink + .with_highlight_click(self.highlight_click) + .with_r_id(relationship_id) + } + + fn to_json(&self) -> Value { + let mut record = match &self.target { + HyperlinkTarget::Url(url) => serde_json::json!({ + "type": "url", + "url": url, + }), + HyperlinkTarget::Slide(slide_index) => serde_json::json!({ + "type": "slide", + "slideIndex": slide_index, + }), + HyperlinkTarget::FirstSlide => serde_json::json!({ + "type": "firstSlide", + }), + HyperlinkTarget::LastSlide => serde_json::json!({ + "type": "lastSlide", + }), + HyperlinkTarget::NextSlide => serde_json::json!({ + "type": "nextSlide", + }), + HyperlinkTarget::PreviousSlide => serde_json::json!({ + "type": "previousSlide", + }), + HyperlinkTarget::EndShow => serde_json::json!({ + "type": "endShow", + }), + HyperlinkTarget::Email { address, subject } => serde_json::json!({ + "type": "email", + "address": address, + "subject": subject, + }), + HyperlinkTarget::File(path) => serde_json::json!({ + "type": "file", + "path": path, + }), + }; + record["tooltip"] = self + .tooltip + .as_ref() + .map(|tooltip| Value::String(tooltip.clone())) + .unwrap_or(Value::Null); + record["highlightClick"] = Value::Bool(self.highlight_click); + record + } + + fn relationship_xml(&self, relationship_id: &str) -> String { + let target_mode = if self.target.is_external() { + r#" TargetMode="External""# + } else { + "" + }; + format!( + r#""#, + ppt_rs::escape_xml(&self.target.relationship_target()), + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +enum TextAlignment { + Left, + Center, + Right, + Justify, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct RichTextState { + #[serde(default)] + ranges: Vec, + #[serde(default)] + layout: TextLayoutState, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TextRangeAnnotation { + range_id: String, + start_cp: usize, + length: usize, + style: TextStyle, + hyperlink: Option, + spacing_before: Option, + spacing_after: Option, + line_spacing: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TextLayoutState { + insets: Option, + wrap: Option, + auto_fit: Option, + vertical_alignment: Option, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +struct TextInsets { + left: u32, + right: u32, + top: u32, + bottom: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum TextWrapMode { + Square, + None, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum TextAutoFitMode { + None, + ShrinkText, + ResizeShapeToFitText, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum TextVerticalAlignment { + Top, + Middle, + Bottom, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentAuthorProfile { + display_name: String, + initials: String, + email: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentPosition { + x: u32, + y: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum CommentThreadStatus { + Active, + Resolved, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentMessage { + message_id: String, + author: CommentAuthorProfile, + text: String, + created_at: String, + #[serde(default)] + reactions: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +enum CommentTarget { + Slide { + slide_id: String, + }, + Element { + slide_id: String, + element_id: String, + }, + TextRange { + slide_id: String, + element_id: String, + start_cp: usize, + length: usize, + context: Option, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CommentThread { + thread_id: String, + target: CommentTarget, + position: Option, + status: CommentThreadStatus, + messages: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TableBorder { + color: String, + width: u32, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TableBorders { + outside: Option, + inside: Option, + top: Option, + bottom: Option, + left: Option, + right: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct TableStyleOptions { + header_row: bool, + banded_rows: bool, + banded_columns: bool, + first_column: bool, + last_column: bool, + total_row: bool, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartMarkerStyle { + symbol: Option, + size: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartDataLabels { + show_value: bool, + show_category_name: bool, + show_leader_lines: bool, + position: Option, + text_style: TextStyle, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartLegend { + position: Option, + text_style: TextStyle, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartAxisSpec { + title: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct ChartDataLabelOverride { + idx: usize, + text: Option, + position: Option, + text_style: TextStyle, + fill: Option, + stroke: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct PlaceholderRef { + name: String, + placeholder_type: String, + index: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TableMergeRegion { + start_row: usize, + end_row: usize, + start_column: usize, + end_column: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TableCellSpec { + text: String, + text_style: TextStyle, + background_fill: Option, + alignment: Option, + #[serde(default)] + rich_text: RichTextState, + borders: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PresentationDocument { + artifact_id: String, + name: Option, + slide_size: Rect, + theme: ThemeState, + custom_text_styles: HashMap, + layouts: Vec, + slides: Vec, + active_slide_index: Option, + #[serde(default)] + comment_self: Option, + #[serde(default)] + comment_threads: Vec, + next_slide_seq: u32, + next_element_seq: u32, + next_layout_seq: u32, + next_text_range_seq: u32, + next_comment_thread_seq: u32, + next_comment_message_seq: u32, +} + +impl PresentationDocument { + fn new(name: Option) -> Self { + Self { + artifact_id: format!("presentation_{}", Uuid::new_v4().simple()), + name, + slide_size: Rect { + left: 0, + top: 0, + width: DEFAULT_SLIDE_WIDTH_POINTS, + height: DEFAULT_SLIDE_HEIGHT_POINTS, + }, + theme: ThemeState::default(), + custom_text_styles: HashMap::new(), + layouts: Vec::new(), + slides: Vec::new(), + active_slide_index: None, + comment_self: None, + comment_threads: Vec::new(), + next_slide_seq: 1, + next_element_seq: 1, + next_layout_seq: 1, + next_text_range_seq: 1, + next_comment_thread_seq: 1, + next_comment_message_seq: 1, + } + } + + fn from_ppt_rs(presentation: Presentation) -> Self { + let mut document = Self::new( + (!presentation.get_title().is_empty()).then(|| presentation.get_title().to_string()), + ); + for imported_slide in presentation.slides() { + let mut slide = PresentationSlide { + slide_id: format!("slide_{}", document.next_slide_seq), + notes: NotesState { + text: imported_slide.notes.clone().unwrap_or_default(), + visible: true, + rich_text: RichTextState::default(), + }, + background_fill: None, + layout_id: None, + elements: Vec::new(), + }; + document.next_slide_seq += 1; + + if !imported_slide.title.is_empty() { + slide.elements.push(PresentationElement::Text(TextElement { + element_id: document.next_element_id(), + text: imported_slide.title.clone(), + frame: Rect { + left: DEFAULT_IMPORTED_TITLE_LEFT, + top: DEFAULT_IMPORTED_TITLE_TOP, + width: DEFAULT_IMPORTED_TITLE_WIDTH, + height: DEFAULT_IMPORTED_TITLE_HEIGHT, + }, + fill: None, + style: TextStyle::default(), + hyperlink: None, + rich_text: RichTextState::default(), + placeholder: None, + z_order: slide.elements.len(), + })); + } + + if !imported_slide.content.is_empty() { + slide.elements.push(PresentationElement::Text(TextElement { + element_id: document.next_element_id(), + text: imported_slide.content.join("\n"), + frame: Rect { + left: DEFAULT_IMPORTED_CONTENT_LEFT, + top: DEFAULT_IMPORTED_CONTENT_TOP, + width: DEFAULT_IMPORTED_CONTENT_WIDTH, + height: DEFAULT_IMPORTED_CONTENT_HEIGHT, + }, + fill: None, + style: TextStyle::default(), + hyperlink: None, + rich_text: RichTextState::default(), + placeholder: None, + z_order: slide.elements.len(), + })); + } + + for imported_shape in &imported_slide.shapes { + slide + .elements + .push(PresentationElement::Shape(ShapeElement { + element_id: document.next_element_id(), + geometry: ShapeGeometry::from_shape_type(imported_shape.shape_type), + frame: Rect::from_emu( + imported_shape.x, + imported_shape.y, + imported_shape.width, + imported_shape.height, + ), + fill: imported_shape.fill.as_ref().map(|fill| fill.color.clone()), + stroke: imported_shape.line.as_ref().map(|line| StrokeStyle { + color: line.color.clone(), + width: emu_to_points(line.width), + style: LineStyle::Solid, + }), + text: imported_shape.text.clone(), + text_style: TextStyle::default(), + hyperlink: None, + rich_text: imported_shape + .text + .as_ref() + .map(|_| RichTextState::default()), + placeholder: None, + rotation_degrees: imported_shape.rotation, + flip_horizontal: false, + flip_vertical: false, + z_order: slide.elements.len(), + })); + } + + if let Some(imported_table) = &imported_slide.table { + slide + .elements + .push(PresentationElement::Table(TableElement { + element_id: document.next_element_id(), + frame: Rect::from_emu( + imported_table.x, + imported_table.y, + imported_table.width(), + imported_table.height(), + ), + rows: imported_table + .rows + .iter() + .map(|row| { + row.cells + .iter() + .map(|text| TableCellSpec { + text: text.text.clone(), + text_style: TextStyle::default(), + background_fill: None, + alignment: None, + rich_text: RichTextState::default(), + borders: None, + }) + .collect() + }) + .collect(), + column_widths: imported_table + .column_widths + .iter() + .copied() + .map(emu_to_points) + .collect(), + row_heights: imported_table + .rows + .iter() + .map(|row| row.height.map_or(400_000, |height| height)) + .map(emu_to_points) + .collect(), + style: None, + style_options: TableStyleOptions::default(), + borders: None, + right_to_left: false, + merges: Vec::new(), + z_order: slide.elements.len(), + })); + } + + document.slides.push(slide); + } + document.active_slide_index = (!document.slides.is_empty()).then_some(0); + document + } + + fn new_slide( + &mut self, + notes: Option, + background_fill: Option, + action: &str, + ) -> Result { + let normalized_fill = background_fill + .map(|value| { + normalize_color_with_palette(Some(&self.theme), &value, action, "background_fill") + }) + .transpose()?; + let slide = PresentationSlide { + slide_id: format!("slide_{}", self.next_slide_seq), + notes: NotesState { + text: notes.unwrap_or_default(), + visible: true, + rich_text: RichTextState::default(), + }, + background_fill: normalized_fill, + layout_id: None, + elements: Vec::new(), + }; + self.next_slide_seq += 1; + Ok(slide) + } + + fn append_slide(&mut self, slide: PresentationSlide) -> usize { + let index = self.slides.len(); + self.slides.push(slide); + if self.active_slide_index.is_none() { + self.active_slide_index = Some(index); + } + index + } + + fn clone_slide(&mut self, slide: PresentationSlide) -> PresentationSlide { + let mut clone = slide; + clone.slide_id = format!("slide_{}", self.next_slide_seq); + self.next_slide_seq += 1; + for element in &mut clone.elements { + element.set_element_id(self.next_element_id()); + } + clone + } + + fn next_element_id(&mut self) -> String { + let element_id = format!("element_{}", self.next_element_seq); + self.next_element_seq += 1; + element_id + } + + fn next_text_range_id(&mut self) -> String { + let range_id = format!("range_{}", self.next_text_range_seq); + self.next_text_range_seq += 1; + range_id + } + + fn next_comment_thread_id(&mut self) -> String { + let thread_id = format!("thread_{}", self.next_comment_thread_seq); + self.next_comment_thread_seq += 1; + thread_id + } + + fn next_comment_message_id(&mut self) -> String { + let message_id = format!("message_{}", self.next_comment_message_seq); + self.next_comment_message_seq += 1; + message_id + } + + fn total_element_count(&self) -> usize { + self.slides.iter().map(|slide| slide.elements.len()).sum() + } + + fn set_active_slide_index( + &mut self, + slide_index: usize, + action: &str, + ) -> Result<(), PresentationArtifactError> { + if slide_index >= self.slides.len() { + return Err(index_out_of_range(action, slide_index, self.slides.len())); + } + self.active_slide_index = Some(slide_index); + Ok(()) + } + + fn adjust_active_slide_for_insert(&mut self, inserted_index: usize) { + match self.active_slide_index { + None => self.active_slide_index = Some(inserted_index), + Some(active_index) if inserted_index <= active_index => { + self.active_slide_index = Some(active_index + 1); + } + Some(_) => {} + } + } + + fn adjust_active_slide_for_move(&mut self, from_index: usize, to_index: usize) { + if let Some(active_index) = self.active_slide_index { + self.active_slide_index = Some(if active_index == from_index { + to_index + } else if from_index < active_index && active_index <= to_index { + active_index - 1 + } else if to_index <= active_index && active_index < from_index { + active_index + 1 + } else { + active_index + }); + } + } + + fn adjust_active_slide_for_delete(&mut self, deleted_index: usize) { + self.active_slide_index = match self.active_slide_index { + None => None, + Some(_) if self.slides.is_empty() => None, + Some(active_index) if active_index == deleted_index => { + Some(deleted_index.min(self.slides.len() - 1)) + } + Some(active_index) if deleted_index < active_index => Some(active_index - 1), + Some(active_index) => Some(active_index), + }; + } + + fn next_layout_id(&mut self) -> String { + let layout_id = format!("layout_{}", self.next_layout_seq); + self.next_layout_seq += 1; + layout_id + } + + fn get_layout( + &self, + layout_ref: &str, + action: &str, + ) -> Result<&LayoutDocument, PresentationArtifactError> { + if let Some(layout) = self + .layouts + .iter() + .find(|layout| layout.layout_id == layout_ref) + { + return Ok(layout); + } + + let exact_name_matches = self + .layouts + .iter() + .filter(|layout| layout.name == layout_ref) + .collect::>(); + if exact_name_matches.len() > 1 { + return Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("layout name `{layout_ref}` is ambiguous"), + }); + } + if let Some(layout) = exact_name_matches.into_iter().next() { + return Ok(layout); + } + + let case_insensitive_name_matches = self + .layouts + .iter() + .filter(|layout| layout.name.eq_ignore_ascii_case(layout_ref)) + .collect::>(); + if case_insensitive_name_matches.len() > 1 { + return Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("layout name `{layout_ref}` is ambiguous"), + }); + } + case_insensitive_name_matches + .into_iter() + .next() + .ok_or_else(|| PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown layout id or name `{layout_ref}`"), + }) + } + + fn theme_snapshot(&self) -> ThemeSnapshot { + ThemeSnapshot { + color_scheme: self.theme.color_scheme.clone(), + hex_color_map: self.theme.color_scheme.clone(), + major_font: self.theme.major_font.clone(), + minor_font: self.theme.minor_font.clone(), + } + } + + fn named_text_styles(&self) -> Vec { + let mut styles = built_in_text_styles(&self.theme) + .into_iter() + .map(|(name, style)| NamedTextStyle { + name, + style, + built_in: true, + }) + .collect::>(); + styles.extend( + self.custom_text_styles + .iter() + .map(|(name, style)| NamedTextStyle { + name: name.clone(), + style: style.clone(), + built_in: false, + }), + ); + styles.sort_by_cached_key(|style| style.name.to_ascii_lowercase()); + styles + } + + fn resolve_named_text_style( + &self, + style_name: &str, + action: &str, + ) -> Result { + let normalized_style_name = style_name.trim().to_ascii_lowercase(); + if let Some(style) = self.custom_text_styles.get(&normalized_style_name) { + return Ok(style.clone()); + } + built_in_text_style(&self.theme, &normalized_style_name).ok_or_else(|| { + PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown text style `{style_name}`"), + } + }) + } + + fn find_element_mut( + &mut self, + element_id: &str, + action: &str, + ) -> Result<&mut PresentationElement, PresentationArtifactError> { + let element_id = normalize_element_lookup_id(element_id); + for slide in &mut self.slides { + if let Some(element) = slide + .elements + .iter_mut() + .find(|element| element.element_id() == element_id) + { + return Ok(element); + } + } + Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown element id `{element_id}`"), + }) + } + + fn get_slide_mut( + &mut self, + slide_index: u32, + action: &str, + ) -> Result<&mut PresentationSlide, PresentationArtifactError> { + let index = slide_index as usize; + if index >= self.slides.len() { + return Err(index_out_of_range(action, index, self.slides.len())); + } + Ok(&mut self.slides[index]) + } + + fn remove_element( + &mut self, + element_id: &str, + action: &str, + ) -> Result<(), PresentationArtifactError> { + let element_id = normalize_element_lookup_id(element_id); + for slide in &mut self.slides { + if let Some(index) = slide + .elements + .iter() + .position(|element| element.element_id() == element_id) + { + slide.elements.remove(index); + resequence_z_order(slide); + return Ok(()); + } + } + Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown element id `{element_id}`"), + }) + } + + fn set_z_order( + &mut self, + element_id: &str, + target_index: usize, + action: &str, + ) -> Result<(), PresentationArtifactError> { + let element_id = normalize_element_lookup_id(element_id); + for slide in &mut self.slides { + if let Some(current_index) = slide + .elements + .iter() + .position(|element| element.element_id() == element_id) + { + let destination = target_index.min(slide.elements.len().saturating_sub(1)); + let element = slide.elements.remove(current_index); + slide.elements.insert(destination, element); + resequence_z_order(slide); + return Ok(()); + } + } + Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("unknown element id `{element_id}`"), + }) + } + + fn to_ppt_rs(&self) -> Presentation { + let mut presentation = self + .name + .as_deref() + .map(Presentation::with_title) + .unwrap_or_default(); + for slide in &self.slides { + presentation = presentation.add_slide(slide.to_ppt_rs(self.slide_size)); + } + presentation + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PresentationSlide { + slide_id: String, + notes: NotesState, + background_fill: Option, + layout_id: Option, + elements: Vec, +} + +struct ImportedPicture { + relationship_id: String, + frame: Rect, + crop: Option, + alt_text: Option, + rotation_degrees: Option, + flip_horizontal: bool, + flip_vertical: bool, + lock_aspect_ratio: bool, +} + +fn import_pptx_images( + path: &Path, + document: &mut PresentationDocument, + action: &str, +) -> Result<(), PresentationArtifactError> { + let file = + std::fs::File::open(path).map_err(|error| PresentationArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + let mut archive = + ZipArchive::new(file).map_err(|error| PresentationArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + for slide_index in 0..document.slides.len() { + let slide_number = slide_index + 1; + let slide_xml_path = format!("ppt/slides/slide{slide_number}.xml"); + let Some(slide_xml) = + zip_entry_string_if_exists(&mut archive, &slide_xml_path).map_err(|message| { + PresentationArtifactError::ImportFailed { + path: path.to_path_buf(), + message, + } + })? + else { + continue; + }; + let pictures = parse_imported_pictures(&slide_xml); + if pictures.is_empty() { + continue; + } + let relationships = zip_entry_string_if_exists( + &mut archive, + &format!("ppt/slides/_rels/slide{slide_number}.xml.rels"), + ) + .map_err(|message| PresentationArtifactError::ImportFailed { + path: path.to_path_buf(), + message, + })? + .map(|xml| parse_slide_image_relationship_targets(&xml)) + .unwrap_or_default(); + let mut imported_images = Vec::new(); + for picture in pictures { + let Some(target) = relationships.get(&picture.relationship_id) else { + continue; + }; + let media_path = resolve_zip_relative_path(&slide_xml_path, target); + let Some(bytes) = + zip_entry_bytes_if_exists(&mut archive, &media_path).map_err(|message| { + PresentationArtifactError::ImportFailed { + path: path.to_path_buf(), + message, + } + })? + else { + continue; + }; + let Some(filename) = Path::new(&media_path) + .file_name() + .and_then(|name| name.to_str()) + .map(str::to_owned) + else { + continue; + }; + let Ok(payload) = build_image_payload(bytes, filename, action) else { + continue; + }; + imported_images.push(ImageElement { + element_id: document.next_element_id(), + frame: picture.frame, + payload: Some(payload), + fit_mode: ImageFitMode::Stretch, + crop: picture.crop, + rotation_degrees: picture.rotation_degrees, + flip_horizontal: picture.flip_horizontal, + flip_vertical: picture.flip_vertical, + lock_aspect_ratio: picture.lock_aspect_ratio, + alt_text: picture.alt_text, + prompt: None, + is_placeholder: false, + placeholder: None, + z_order: 0, + }); + } + let slide = &mut document.slides[slide_index]; + for mut image in imported_images { + image.z_order = slide.elements.len(); + slide.elements.push(PresentationElement::Image(image)); + } + } + Ok(()) +} + +fn zip_entry_string_if_exists( + archive: &mut ZipArchive, + path: &str, +) -> Result, String> { + let Some(bytes) = zip_entry_bytes_if_exists(archive, path)? else { + return Ok(None); + }; + String::from_utf8(bytes) + .map(Some) + .map_err(|error| format!("zip entry `{path}` is not valid UTF-8: {error}")) +} + +fn zip_entry_bytes_if_exists( + archive: &mut ZipArchive, + path: &str, +) -> Result>, String> { + match archive.by_name(path) { + Ok(mut entry) => { + let mut bytes = Vec::new(); + entry + .read_to_end(&mut bytes) + .map_err(|error| format!("failed to read zip entry `{path}`: {error}"))?; + Ok(Some(bytes)) + } + Err(zip::result::ZipError::FileNotFound) => Ok(None), + Err(error) => Err(format!("failed to open zip entry `{path}`: {error}")), + } +} + +fn parse_imported_pictures(slide_xml: &str) -> Vec { + let mut pictures = Vec::new(); + let mut remaining = slide_xml; + while let Some(start) = remaining.find("") { + let block_start = start; + let Some(block_end_offset) = remaining[block_start..].find("") else { + break; + }; + let block_end = block_start + block_end_offset + "".len(); + let block = &remaining[block_start..block_end]; + remaining = &remaining[block_end..]; + + let Some(relationship_id) = xml_tag_attribute(block, "().unwrap_or(0.0) / 100_000.0, + xml_tag_attribute(block, "().ok()) + .unwrap_or(0.0) + / 100_000.0, + xml_tag_attribute(block, "().ok()) + .unwrap_or(0.0) + / 100_000.0, + xml_tag_attribute(block, "().ok()) + .unwrap_or(0.0) + / 100_000.0, + ) + }), + alt_text: xml_tag_attribute(block, "().ok()) + .map(|rotation| (rotation as f64 / 60_000.0).round() as i32), + flip_horizontal: xml_tag_attribute(block, " HashMap { + let mut relationships = HashMap::new(); + let mut remaining = rels_xml; + while let Some(start) = remaining.find("") else { + break; + }; + let tag_end = tag_start + tag_end_offset + 2; + let tag = &remaining[tag_start..tag_end]; + remaining = &remaining[tag_end..]; + if xml_attribute(tag, "Type").as_deref() + != Some("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") + { + continue; + } + let (Some(id), Some(target)) = (xml_attribute(tag, "Id"), xml_attribute(tag, "Target")) + else { + continue; + }; + relationships.insert(id, target); + } + relationships +} + +fn resolve_zip_relative_path(base_path: &str, target: &str) -> String { + let mut components = Path::new(base_path) + .parent() + .into_iter() + .flat_map(Path::components) + .filter_map(|component| match component { + std::path::Component::Normal(value) => Some(value.to_string_lossy().to_string()), + std::path::Component::CurDir => None, + std::path::Component::ParentDir => None, + std::path::Component::RootDir | std::path::Component::Prefix(_) => None, + }) + .collect::>(); + for component in Path::new(target).components() { + match component { + std::path::Component::Normal(value) => { + components.push(value.to_string_lossy().to_string()) + } + std::path::Component::ParentDir => { + components.pop(); + } + std::path::Component::CurDir => {} + std::path::Component::RootDir | std::path::Component::Prefix(_) => { + components.clear(); + } + } + } + components.join("/") +} + +fn xml_tag_attribute(xml: &str, tag_start: &str, attribute: &str) -> Option { + let start = xml.find(tag_start)?; + let tag = &xml[start..start + xml[start..].find('>')?]; + xml_attribute(tag, attribute) +} + +fn xml_attribute(tag: &str, attribute: &str) -> Option { + let pattern = format!(r#"{attribute}=""#); + let start = tag.find(&pattern)? + pattern.len(); + let end = start + tag[start..].find('"')?; + Some( + tag[start..end] + .replace(""", "\"") + .replace("'", "'") + .replace("<", "<") + .replace(">", ">") + .replace("&", "&"), + ) +} + +impl PresentationSlide { + fn to_ppt_rs(&self, slide_size: Rect) -> SlideContent { + let mut content = SlideContent::new("").layout(SlideLayout::Blank); + if self.notes.visible && !self.notes.text.is_empty() { + content = content.notes(&self.notes.text); + } + + if let Some(background_fill) = &self.background_fill { + content = content.add_shape( + Shape::new( + ShapeType::Rectangle, + 0, + 0, + points_to_emu(slide_size.width), + points_to_emu(slide_size.height), + ) + .with_fill(ShapeFill::new(background_fill)), + ); + } + + let mut ordered = self.elements.clone(); + ordered.sort_by_key(PresentationElement::z_order); + let mut hyperlink_seq = 1_u32; + for element in ordered { + match element { + PresentationElement::Text(text) => { + let mut shape = Shape::new( + ShapeType::Rectangle, + points_to_emu(text.frame.left), + points_to_emu(text.frame.top), + points_to_emu(text.frame.width), + points_to_emu(text.frame.height), + ) + .with_text(&text.text); + if let Some(fill) = text.fill { + shape = shape.with_fill(ShapeFill::new(&fill)); + } + if let Some(hyperlink) = &text.hyperlink { + let relationship_id = format!("rIdHyperlink{hyperlink_seq}"); + hyperlink_seq += 1; + shape = shape.with_hyperlink(hyperlink.to_ppt_rs(&relationship_id)); + } + content = content.add_shape(shape); + } + PresentationElement::Shape(shape) => { + let mut ppt_shape = Shape::new( + shape.geometry.to_ppt_rs(), + points_to_emu(shape.frame.left), + points_to_emu(shape.frame.top), + points_to_emu(shape.frame.width), + points_to_emu(shape.frame.height), + ); + if let Some(text) = shape.text { + ppt_shape = ppt_shape.with_text(&text); + } + if let Some(fill) = shape.fill { + ppt_shape = ppt_shape.with_fill(ShapeFill::new(&fill)); + } + if let Some(stroke) = shape.stroke { + ppt_shape = ppt_shape + .with_line(ShapeLine::new(&stroke.color, points_to_emu(stroke.width))); + } + if let Some(rotation) = shape.rotation_degrees { + ppt_shape = ppt_shape.with_rotation(rotation); + } + if let Some(hyperlink) = &shape.hyperlink { + let relationship_id = format!("rIdHyperlink{hyperlink_seq}"); + hyperlink_seq += 1; + ppt_shape = ppt_shape.with_hyperlink(hyperlink.to_ppt_rs(&relationship_id)); + } + content = content.add_shape(ppt_shape); + } + PresentationElement::Connector(connector) => { + let mut ppt_connector = Connector::new( + connector.connector_type.to_ppt_rs(), + points_to_emu(connector.start.left), + points_to_emu(connector.start.top), + points_to_emu(connector.end.left), + points_to_emu(connector.end.top), + ) + .with_line( + ConnectorLine::new( + &connector.line.color, + points_to_emu(connector.line.width), + ) + .with_dash(connector.line_style.to_ppt_rs()), + ) + .with_arrow_size(connector.arrow_size.to_ppt_rs()) + .with_start_arrow(connector.start_arrow.to_ppt_rs()) + .with_end_arrow(connector.end_arrow.to_ppt_rs()); + if let Some(label) = connector.label { + ppt_connector = ppt_connector.with_label(&label); + } + content = content.add_connector(ppt_connector); + } + PresentationElement::Image(image) => { + if let Some(ref payload) = image.payload { + let mut ppt_image = Image::from_bytes( + payload.bytes.clone(), + points_to_emu(image.frame.width), + points_to_emu(image.frame.height), + &payload.format, + ) + .position( + points_to_emu(image.frame.left), + points_to_emu(image.frame.top), + ); + if image.fit_mode != ImageFitMode::Stretch { + let (x, y, width, height, crop) = fit_image(&image); + ppt_image = Image::from_bytes( + payload.bytes.clone(), + points_to_emu(width), + points_to_emu(height), + &payload.format, + ) + .position(points_to_emu(x), points_to_emu(y)); + if let Some((left, top, right, bottom)) = crop { + ppt_image = ppt_image.with_crop(left, top, right, bottom); + } + } + if let Some((left, top, right, bottom)) = image.crop { + ppt_image = ppt_image.with_crop(left, top, right, bottom); + } + content = content.add_image(ppt_image); + } else { + let mut placeholder = Shape::new( + ShapeType::Rectangle, + points_to_emu(image.frame.left), + points_to_emu(image.frame.top), + points_to_emu(image.frame.width), + points_to_emu(image.frame.height), + ) + .with_text(image.prompt.as_deref().unwrap_or("Image placeholder")); + if let Some(rotation) = image.rotation_degrees { + placeholder = placeholder.with_rotation(rotation); + } + content = content.add_shape(placeholder); + } + } + PresentationElement::Table(table) => { + let mut builder = TableBuilder::new( + table + .column_widths + .iter() + .copied() + .map(points_to_emu) + .collect(), + ) + .position( + points_to_emu(table.frame.left), + points_to_emu(table.frame.top), + ); + for (row_index, row) in table.rows.into_iter().enumerate() { + let cells = row + .into_iter() + .enumerate() + .map(|(column_index, cell)| { + build_table_cell(cell, &table.merges, row_index, column_index) + }) + .collect::>(); + let mut table_row = TableRow::new(cells); + if let Some(height) = table.row_heights.get(row_index) { + table_row = table_row.with_height(points_to_emu(*height)); + } + builder = builder.add_row(table_row); + } + content = content.table(builder.build()); + } + PresentationElement::Chart(chart) => { + let mut ppt_chart = Chart::new( + chart.title.as_deref().unwrap_or("Chart"), + chart.chart_type.to_ppt_rs(), + chart.categories, + points_to_emu(chart.frame.left), + points_to_emu(chart.frame.top), + points_to_emu(chart.frame.width), + points_to_emu(chart.frame.height), + ); + for series in chart.series { + ppt_chart = + ppt_chart.add_series(ChartSeries::new(&series.name, series.values)); + } + content = content.add_chart(ppt_chart); + } + } + } + content + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +enum PresentationElement { + Text(TextElement), + Shape(ShapeElement), + Connector(ConnectorElement), + Image(ImageElement), + Table(TableElement), + Chart(ChartElement), +} + +impl PresentationElement { + fn element_id(&self) -> &str { + match self { + Self::Text(element) => &element.element_id, + Self::Shape(element) => &element.element_id, + Self::Connector(element) => &element.element_id, + Self::Image(element) => &element.element_id, + Self::Table(element) => &element.element_id, + Self::Chart(element) => &element.element_id, + } + } + + fn set_element_id(&mut self, new_id: String) { + match self { + Self::Text(element) => element.element_id = new_id, + Self::Shape(element) => element.element_id = new_id, + Self::Connector(element) => element.element_id = new_id, + Self::Image(element) => element.element_id = new_id, + Self::Table(element) => element.element_id = new_id, + Self::Chart(element) => element.element_id = new_id, + } + } + + fn kind(&self) -> &'static str { + match self { + Self::Text(_) => "text", + Self::Shape(_) => "shape", + Self::Connector(_) => "connector", + Self::Image(_) => "image", + Self::Table(_) => "table", + Self::Chart(_) => "chart", + } + } + + fn z_order(&self) -> usize { + match self { + Self::Text(element) => element.z_order, + Self::Shape(element) => element.z_order, + Self::Connector(element) => element.z_order, + Self::Image(element) => element.z_order, + Self::Table(element) => element.z_order, + Self::Chart(element) => element.z_order, + } + } + + fn set_z_order(&mut self, z_order: usize) { + match self { + Self::Text(element) => element.z_order = z_order, + Self::Shape(element) => element.z_order = z_order, + Self::Connector(element) => element.z_order = z_order, + Self::Image(element) => element.z_order = z_order, + Self::Table(element) => element.z_order = z_order, + Self::Chart(element) => element.z_order = z_order, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TextElement { + element_id: String, + text: String, + frame: Rect, + fill: Option, + style: TextStyle, + hyperlink: Option, + #[serde(default)] + rich_text: RichTextState, + placeholder: Option, + z_order: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ShapeElement { + element_id: String, + geometry: ShapeGeometry, + frame: Rect, + fill: Option, + stroke: Option, + text: Option, + text_style: TextStyle, + hyperlink: Option, + rich_text: Option, + placeholder: Option, + rotation_degrees: Option, + flip_horizontal: bool, + flip_vertical: bool, + z_order: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ConnectorElement { + element_id: String, + connector_type: ConnectorKind, + start: PointArgs, + end: PointArgs, + line: StrokeStyle, + line_style: LineStyle, + start_arrow: ConnectorArrowKind, + end_arrow: ConnectorArrowKind, + arrow_size: ConnectorArrowScale, + label: Option, + z_order: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct ImageElement { + pub(crate) element_id: String, + pub(crate) frame: Rect, + pub(crate) payload: Option, + pub(crate) fit_mode: ImageFitMode, + pub(crate) crop: Option, + pub(crate) rotation_degrees: Option, + pub(crate) flip_horizontal: bool, + pub(crate) flip_vertical: bool, + pub(crate) lock_aspect_ratio: bool, + pub(crate) alt_text: Option, + pub(crate) prompt: Option, + pub(crate) is_placeholder: bool, + pub(crate) placeholder: Option, + pub(crate) z_order: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct TableElement { + element_id: String, + frame: Rect, + rows: Vec>, + column_widths: Vec, + row_heights: Vec, + style: Option, + style_options: TableStyleOptions, + borders: Option, + right_to_left: bool, + merges: Vec, + z_order: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ChartElement { + element_id: String, + frame: Rect, + chart_type: ChartTypeSpec, + categories: Vec, + series: Vec, + title: Option, + style_index: Option, + has_legend: bool, + legend: Option, + x_axis: Option, + y_axis: Option, + data_labels: Option, + chart_fill: Option, + plot_area_fill: Option, + z_order: usize, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct ImagePayload { + pub(crate) bytes: Vec, + pub(crate) format: String, + pub(crate) width_px: u32, + pub(crate) height_px: u32, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ChartSeriesSpec { + name: String, + values: Vec, + categories: Option>, + x_values: Option>, + fill: Option, + stroke: Option, + marker: Option, + #[serde(default)] + data_label_overrides: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum ShapeGeometry { + Rectangle, + RoundedRectangle, + Ellipse, + Triangle, + RightTriangle, + Diamond, + Pentagon, + Hexagon, + Octagon, + Star4, + Star5, + Star6, + Star8, + RightArrow, + LeftArrow, + UpArrow, + DownArrow, + LeftRightArrow, + UpDownArrow, + Chevron, + Heart, + Cloud, + Wave, + FlowChartProcess, + FlowChartDecision, + FlowChartConnector, + Parallelogram, + Trapezoid, +} + +impl ShapeGeometry { + fn from_shape_type(shape_type: ShapeType) -> Self { + match shape_type { + ShapeType::RoundedRectangle => Self::RoundedRectangle, + ShapeType::Ellipse | ShapeType::Circle => Self::Ellipse, + ShapeType::Triangle => Self::Triangle, + ShapeType::RightTriangle => Self::RightTriangle, + ShapeType::Diamond => Self::Diamond, + ShapeType::Pentagon => Self::Pentagon, + ShapeType::Hexagon => Self::Hexagon, + ShapeType::Octagon => Self::Octagon, + ShapeType::Star4 => Self::Star4, + ShapeType::Star5 => Self::Star5, + ShapeType::Star6 => Self::Star6, + ShapeType::Star8 => Self::Star8, + ShapeType::RightArrow => Self::RightArrow, + ShapeType::LeftArrow => Self::LeftArrow, + ShapeType::UpArrow => Self::UpArrow, + ShapeType::DownArrow => Self::DownArrow, + ShapeType::LeftRightArrow => Self::LeftRightArrow, + ShapeType::UpDownArrow => Self::UpDownArrow, + ShapeType::ChevronArrow => Self::Chevron, + ShapeType::Heart => Self::Heart, + ShapeType::Cloud => Self::Cloud, + ShapeType::Wave => Self::Wave, + ShapeType::FlowChartProcess => Self::FlowChartProcess, + ShapeType::FlowChartDecision => Self::FlowChartDecision, + ShapeType::FlowChartConnector => Self::FlowChartConnector, + ShapeType::Parallelogram => Self::Parallelogram, + ShapeType::Trapezoid => Self::Trapezoid, + _ => Self::Rectangle, + } + } + + fn to_ppt_rs(self) -> ShapeType { + match self { + Self::Rectangle => ShapeType::Rectangle, + Self::RoundedRectangle => ShapeType::RoundedRectangle, + Self::Ellipse => ShapeType::Ellipse, + Self::Triangle => ShapeType::Triangle, + Self::RightTriangle => ShapeType::RightTriangle, + Self::Diamond => ShapeType::Diamond, + Self::Pentagon => ShapeType::Pentagon, + Self::Hexagon => ShapeType::Hexagon, + Self::Octagon => ShapeType::Octagon, + Self::Star4 => ShapeType::Star4, + Self::Star5 => ShapeType::Star5, + Self::Star6 => ShapeType::Star6, + Self::Star8 => ShapeType::Star8, + Self::RightArrow => ShapeType::RightArrow, + Self::LeftArrow => ShapeType::LeftArrow, + Self::UpArrow => ShapeType::UpArrow, + Self::DownArrow => ShapeType::DownArrow, + Self::LeftRightArrow => ShapeType::LeftRightArrow, + Self::UpDownArrow => ShapeType::UpDownArrow, + Self::Chevron => ShapeType::ChevronArrow, + Self::Heart => ShapeType::Heart, + Self::Cloud => ShapeType::Cloud, + Self::Wave => ShapeType::Wave, + Self::FlowChartProcess => ShapeType::FlowChartProcess, + Self::FlowChartDecision => ShapeType::FlowChartDecision, + Self::FlowChartConnector => ShapeType::FlowChartConnector, + Self::Parallelogram => ShapeType::Parallelogram, + Self::Trapezoid => ShapeType::Trapezoid, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum ChartTypeSpec { + Bar, + BarHorizontal, + BarStacked, + BarStacked100, + Line, + LineMarkers, + LineStacked, + Pie, + Doughnut, + Area, + AreaStacked, + AreaStacked100, + Scatter, + ScatterLines, + ScatterSmooth, + Bubble, + Radar, + RadarFilled, + StockHlc, + StockOhlc, + Combo, +} + +impl ChartTypeSpec { + fn to_ppt_rs(self) -> ChartType { + match self { + Self::Bar => ChartType::Bar, + Self::BarHorizontal => ChartType::BarHorizontal, + Self::BarStacked => ChartType::BarStacked, + Self::BarStacked100 => ChartType::BarStacked100, + Self::Line => ChartType::Line, + Self::LineMarkers => ChartType::LineMarkers, + Self::LineStacked => ChartType::LineStacked, + Self::Pie => ChartType::Pie, + Self::Doughnut => ChartType::Doughnut, + Self::Area => ChartType::Area, + Self::AreaStacked => ChartType::AreaStacked, + Self::AreaStacked100 => ChartType::AreaStacked100, + Self::Scatter => ChartType::Scatter, + Self::ScatterLines => ChartType::ScatterLines, + Self::ScatterSmooth => ChartType::ScatterSmooth, + Self::Bubble => ChartType::Bubble, + Self::Radar => ChartType::Radar, + Self::RadarFilled => ChartType::RadarFilled, + Self::StockHlc => ChartType::StockHLC, + Self::StockOhlc => ChartType::StockOHLC, + Self::Combo => ChartType::Combo, + } + } +} + +impl ConnectorKind { + fn to_ppt_rs(self) -> ConnectorType { + match self { + Self::Straight => ConnectorType::Straight, + Self::Elbow => ConnectorType::Elbow, + Self::Curved => ConnectorType::Curved, + } + } +} + +impl ConnectorArrowKind { + fn to_ppt_rs(self) -> ArrowType { + match self { + Self::None => ArrowType::None, + Self::Triangle => ArrowType::Triangle, + Self::Stealth => ArrowType::Stealth, + Self::Diamond => ArrowType::Diamond, + Self::Oval => ArrowType::Oval, + Self::Open => ArrowType::Open, + } + } +} + +impl ConnectorArrowScale { + fn to_ppt_rs(self) -> ArrowSize { + match self { + Self::Small => ArrowSize::Small, + Self::Medium => ArrowSize::Medium, + Self::Large => ArrowSize::Large, + } + } +} + +impl LineStyle { + fn to_ppt_rs(self) -> LineDash { + match self { + Self::Solid => LineDash::Solid, + Self::Dashed => LineDash::Dash, + Self::Dotted => LineDash::Dot, + Self::DashDot => LineDash::DashDot, + Self::DashDotDot => LineDash::DashDotDot, + Self::LongDash => LineDash::LongDash, + Self::LongDashDot => LineDash::LongDashDot, + } + } + + fn to_ppt_xml(self) -> &'static str { + match self { + Self::Solid => "solid", + Self::Dashed => "dash", + Self::Dotted => "dot", + Self::DashDot => "dashDot", + Self::DashDotDot => "dashDotDot", + Self::LongDash => "lgDash", + Self::LongDashDot => "lgDashDot", + } + } + + fn as_api_str(self) -> &'static str { + match self { + Self::Solid => "solid", + Self::Dashed => "dashed", + Self::Dotted => "dotted", + Self::DashDot => "dash-dot", + Self::DashDotDot => "dash-dot-dot", + Self::LongDash => "long-dash", + Self::LongDashDot => "long-dash-dot", + } + } +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ImageFitMode { + Stretch, + Contain, + Cover, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct StrokeStyle { + color: String, + width: u32, + style: LineStyle, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum ConnectorKind { + Straight, + Elbow, + Curved, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum ConnectorArrowKind { + None, + Triangle, + Stealth, + Diamond, + Oval, + Open, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum ConnectorArrowScale { + Small, + Medium, + Large, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +enum LineStyle { + Solid, + Dashed, + Dotted, + DashDot, + DashDotDot, + LongDash, + LongDashDot, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub(crate) struct Rect { + pub(crate) left: u32, + pub(crate) top: u32, + pub(crate) width: u32, + pub(crate) height: u32, +} + +impl Rect { + fn from_emu(left: u32, top: u32, width: u32, height: u32) -> Self { + Self { + left: emu_to_points(left), + top: emu_to_points(top), + width: emu_to_points(width), + height: emu_to_points(height), + } + } +} + +impl From for Rect { + fn from(value: PositionArgs) -> Self { + Self { + left: value.left, + top: value.top, + width: value.width, + height: value.height, + } + } +} + +fn apply_partial_position(rect: Rect, position: PartialPositionArgs) -> Rect { + Rect { + left: position.left.unwrap_or(rect.left), + top: position.top.unwrap_or(rect.top), + width: position.width.unwrap_or(rect.width), + height: position.height.unwrap_or(rect.height), + } +} + +fn apply_partial_position_to_image(image: &ImageElement, position: PartialPositionArgs) -> Rect { + let mut frame = apply_partial_position(image.frame, position.clone()); + if image.lock_aspect_ratio { + let base_ratio = image + .payload + .as_ref() + .map(|payload| payload.width_px as f64 / payload.height_px as f64) + .unwrap_or_else(|| image.frame.width as f64 / image.frame.height as f64); + if let Some(width) = position.width + && position.height.is_none() + { + frame.height = (width as f64 / base_ratio).round() as u32; + } else if let Some(height) = position.height + && position.width.is_none() + { + frame.width = (height as f64 * base_ratio).round() as u32; + } + } + frame +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs b/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs new file mode 100644 index 0000000000..efca31a99b --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/parsing.rs @@ -0,0 +1,1273 @@ +fn parse_args(action: &str, value: &Value) -> Result +where + T: for<'de> Deserialize<'de>, +{ + serde_json::from_value(value.clone()).map_err(|error| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: error.to_string(), + }) +} + +fn required_artifact_id( + request: &PresentationArtifactRequest, +) -> Result { + request + .artifact_id + .clone() + .ok_or_else(|| PresentationArtifactError::MissingArtifactId { + action: request.action.clone(), + }) +} + +fn is_read_only_action(action: &str) -> bool { + matches!( + action, + "get_summary" + | "list_slides" + | "list_layouts" + | "list_layout_placeholders" + | "list_slide_placeholders" + | "inspect" + | "resolve" + | "to_proto" + | "get_style" + | "describe_styles" + | "record_patch" + ) +} + +fn tracks_history(action: &str) -> bool { + !is_read_only_action(action) + && !matches!( + action, + "export_pptx" | "export_preview" | "undo" | "redo" | "apply_patch" + ) +} + +fn patch_operation_supported(action: &str) -> bool { + tracks_history(action) && !matches!(action, "create" | "import_pptx" | "delete_artifact") +} + +fn resolve_path(cwd: &Path, path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_path_buf() + } else { + cwd.join(path) + } +} + +fn normalize_color( + color: &str, + action: &str, + field: &str, +) -> Result { + normalize_color_with_palette(None, color, action, field) +} + +fn normalize_color_with_document( + document: &PresentationDocument, + color: &str, + action: &str, + field: &str, +) -> Result { + normalize_color_with_palette(Some(&document.theme), color, action, field) +} + +fn normalize_color_with_palette( + theme: Option<&ThemeState>, + color: &str, + action: &str, + field: &str, +) -> Result { + let trimmed = color.trim(); + let normalized = theme + .and_then(|palette| palette.resolve_color(trimmed)) + .unwrap_or_else(|| trimmed.trim_start_matches('#').to_uppercase()); + if normalized.len() != 6 + || !normalized + .chars() + .all(|character| character.is_ascii_hexdigit()) + { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("field `{field}` must be a 6-digit RGB hex color"), + }); + } + Ok(normalized) +} + +fn parse_shape_geometry( + geometry: &str, + action: &str, +) -> Result { + match geometry { + "rectangle" | "rect" => Ok(ShapeGeometry::Rectangle), + "rounded_rectangle" | "roundedRect" => Ok(ShapeGeometry::RoundedRectangle), + "ellipse" | "circle" => Ok(ShapeGeometry::Ellipse), + "triangle" => Ok(ShapeGeometry::Triangle), + "right_triangle" => Ok(ShapeGeometry::RightTriangle), + "diamond" => Ok(ShapeGeometry::Diamond), + "pentagon" => Ok(ShapeGeometry::Pentagon), + "hexagon" => Ok(ShapeGeometry::Hexagon), + "octagon" => Ok(ShapeGeometry::Octagon), + "star4" => Ok(ShapeGeometry::Star4), + "star" | "star5" => Ok(ShapeGeometry::Star5), + "star6" => Ok(ShapeGeometry::Star6), + "star8" => Ok(ShapeGeometry::Star8), + "right_arrow" => Ok(ShapeGeometry::RightArrow), + "left_arrow" => Ok(ShapeGeometry::LeftArrow), + "up_arrow" => Ok(ShapeGeometry::UpArrow), + "down_arrow" => Ok(ShapeGeometry::DownArrow), + "left_right_arrow" | "leftRightArrow" => Ok(ShapeGeometry::LeftRightArrow), + "up_down_arrow" | "upDownArrow" => Ok(ShapeGeometry::UpDownArrow), + "chevron" => Ok(ShapeGeometry::Chevron), + "heart" => Ok(ShapeGeometry::Heart), + "cloud" => Ok(ShapeGeometry::Cloud), + "wave" => Ok(ShapeGeometry::Wave), + "flowChartProcess" | "flow_chart_process" => Ok(ShapeGeometry::FlowChartProcess), + "flowChartDecision" | "flow_chart_decision" => Ok(ShapeGeometry::FlowChartDecision), + "flowChartConnector" | "flow_chart_connector" => Ok(ShapeGeometry::FlowChartConnector), + "parallelogram" => Ok(ShapeGeometry::Parallelogram), + "trapezoid" => Ok(ShapeGeometry::Trapezoid), + _ => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("geometry `{geometry}` is not supported"), + }), + } +} + +fn parse_chart_type( + chart_type: &str, + action: &str, +) -> Result { + match chart_type { + "bar" => Ok(ChartTypeSpec::Bar), + "bar_horizontal" => Ok(ChartTypeSpec::BarHorizontal), + "bar_stacked" => Ok(ChartTypeSpec::BarStacked), + "bar_stacked_100" => Ok(ChartTypeSpec::BarStacked100), + "line" => Ok(ChartTypeSpec::Line), + "line_markers" => Ok(ChartTypeSpec::LineMarkers), + "line_stacked" => Ok(ChartTypeSpec::LineStacked), + "pie" => Ok(ChartTypeSpec::Pie), + "doughnut" => Ok(ChartTypeSpec::Doughnut), + "area" => Ok(ChartTypeSpec::Area), + "area_stacked" => Ok(ChartTypeSpec::AreaStacked), + "area_stacked_100" => Ok(ChartTypeSpec::AreaStacked100), + "scatter" => Ok(ChartTypeSpec::Scatter), + "scatter_lines" => Ok(ChartTypeSpec::ScatterLines), + "scatter_smooth" => Ok(ChartTypeSpec::ScatterSmooth), + "bubble" => Ok(ChartTypeSpec::Bubble), + "radar" => Ok(ChartTypeSpec::Radar), + "radar_filled" => Ok(ChartTypeSpec::RadarFilled), + "stock_hlc" => Ok(ChartTypeSpec::StockHlc), + "stock_ohlc" => Ok(ChartTypeSpec::StockOhlc), + "combo" => Ok(ChartTypeSpec::Combo), + _ => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("chart_type `{chart_type}` is not supported"), + }), + } +} + +fn parse_chart_marker(marker: Option) -> ChartMarkerStyle { + marker + .map(|marker| ChartMarkerStyle { + symbol: marker.symbol, + size: marker.size, + }) + .unwrap_or_default() +} + +fn parse_chart_data_labels( + document: &PresentationDocument, + data_labels: Option, + action: &str, +) -> Result, PresentationArtifactError> { + data_labels + .map(|data_labels| { + Ok(ChartDataLabels { + show_value: data_labels.show_value.unwrap_or(false), + show_category_name: data_labels.show_category_name.unwrap_or(false), + show_leader_lines: data_labels.show_leader_lines.unwrap_or(false), + position: data_labels.position, + text_style: normalize_text_style_with_document( + document, + &data_labels.text_style, + action, + )?, + }) + }) + .transpose() +} + +fn parse_chart_series( + document: &PresentationDocument, + series: Vec, + action: &str, +) -> Result, PresentationArtifactError> { + series + .into_iter() + .map(|entry| { + if entry.values.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("series `{}` must contain at least one value", entry.name), + }); + } + let fill = entry + .fill + .as_deref() + .map(|value| normalize_color_with_document(document, value, action, "series.fill")) + .transpose()?; + let stroke = entry + .stroke + .map(|stroke| { + Ok(StrokeStyle { + color: normalize_color_with_document( + document, + &stroke.color, + action, + "series.stroke.color", + )?, + width: stroke.width, + style: stroke + .style + .as_deref() + .map(|value| parse_line_style(value, action)) + .transpose()? + .unwrap_or(LineStyle::Solid), + }) + }) + .transpose()?; + let data_label_overrides = entry + .data_label_overrides + .unwrap_or_default() + .into_iter() + .map(|override_args| { + Ok(ChartDataLabelOverride { + idx: override_args.idx as usize, + text: override_args.text, + position: override_args.position, + text_style: normalize_text_style_with_document( + document, + &override_args.text_style, + action, + )?, + fill: override_args + .fill + .as_deref() + .map(|value| { + normalize_color_with_document(document, value, action, "fill") + }) + .transpose()?, + stroke: override_args + .stroke + .map(|stroke| { + Ok(StrokeStyle { + color: normalize_color_with_document( + document, + &stroke.color, + action, + "stroke.color", + )?, + width: stroke.width, + style: stroke + .style + .as_deref() + .map(|value| parse_line_style(value, action)) + .transpose()? + .unwrap_or(LineStyle::Solid), + }) + }) + .transpose()?, + }) + }) + .collect::, _>>()?; + Ok(ChartSeriesSpec { + name: entry.name, + values: entry.values, + categories: entry.categories, + x_values: entry.x_values, + fill, + stroke, + marker: Some(parse_chart_marker(entry.marker)), + data_label_overrides, + }) + }) + .collect() +} + +fn parse_stroke( + document: &PresentationDocument, + stroke: Option, + action: &str, +) -> Result, PresentationArtifactError> { + stroke + .map(|value| parse_required_stroke(document, value, action)) + .transpose() +} + +fn parse_required_stroke( + document: &PresentationDocument, + stroke: StrokeArgs, + action: &str, +) -> Result { + Ok(StrokeStyle { + color: normalize_color_with_document(document, &stroke.color, action, "stroke.color")?, + width: stroke.width, + style: stroke + .style + .as_deref() + .map(|style| parse_line_style(style, action)) + .transpose()? + .unwrap_or(LineStyle::Solid), + }) +} + +fn parse_connector_kind( + connector_type: &str, + action: &str, +) -> Result { + match connector_type { + "straight" => Ok(ConnectorKind::Straight), + "elbow" => Ok(ConnectorKind::Elbow), + "curved" => Ok(ConnectorKind::Curved), + _ => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("connector_type `{connector_type}` is not supported"), + }), + } +} + +fn parse_connector_arrow( + value: &str, + action: &str, +) -> Result { + match value { + "none" => Ok(ConnectorArrowKind::None), + "triangle" => Ok(ConnectorArrowKind::Triangle), + "stealth" => Ok(ConnectorArrowKind::Stealth), + "diamond" => Ok(ConnectorArrowKind::Diamond), + "oval" => Ok(ConnectorArrowKind::Oval), + "open" => Ok(ConnectorArrowKind::Open), + _ => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("connector arrow `{value}` is not supported"), + }), + } +} + +fn parse_connector_arrow_size( + value: &str, + action: &str, +) -> Result { + match value { + "small" => Ok(ConnectorArrowScale::Small), + "medium" => Ok(ConnectorArrowScale::Medium), + "large" => Ok(ConnectorArrowScale::Large), + _ => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("connector arrow_size `{value}` is not supported"), + }), + } +} + +fn parse_line_style(value: &str, action: &str) -> Result { + match value { + "solid" => Ok(LineStyle::Solid), + "dashed" => Ok(LineStyle::Dashed), + "dotted" => Ok(LineStyle::Dotted), + "dash-dot" | "dash_dot" => Ok(LineStyle::DashDot), + "dash-dot-dot" | "dash_dot_dot" => Ok(LineStyle::DashDotDot), + "long-dash" | "long_dash" => Ok(LineStyle::LongDash), + "long-dash-dot" | "long_dash_dot" => Ok(LineStyle::LongDashDot), + _ => Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("line style `{value}` is not supported"), + }), + } +} + +fn parse_connector_line( + document: &PresentationDocument, + line: Option, + action: &str, +) -> Result { + let line = line.unwrap_or_default(); + Ok(ParsedConnectorLine { + color: line + .color + .as_deref() + .map(|value| normalize_color_with_document(document, value, action, "line.color")) + .transpose()? + .unwrap_or_else(|| "000000".to_string()), + width: line.width.unwrap_or(1), + style: line + .style + .as_deref() + .map(|value| parse_line_style(value, action)) + .transpose()? + .unwrap_or(LineStyle::Solid), + }) +} + +struct ParsedConnectorLine { + color: String, + width: u32, + style: LineStyle, +} + +fn normalize_text_style_with_document( + document: &PresentationDocument, + styling: &TextStylingArgs, + action: &str, +) -> Result { + normalize_text_style_with_palette(Some(&document.theme), styling, action, |style_name| { + document.resolve_named_text_style(style_name, action) + }) +} + +fn normalize_text_layout( + layout: &TextLayoutArgs, + action: &str, +) -> Result { + let wrap = layout + .wrap + .as_deref() + .map(|value| match value { + "square" => Ok(TextWrapMode::Square), + "none" => Ok(TextWrapMode::None), + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported wrap `{value}`"), + }), + }) + .transpose()?; + let auto_fit = layout + .auto_fit + .as_deref() + .map(|value| match value { + "none" => Ok(TextAutoFitMode::None), + "shrinkText" | "shrink_text" => Ok(TextAutoFitMode::ShrinkText), + "resizeShapeToFitText" | "resize_shape_to_fit_text" => { + Ok(TextAutoFitMode::ResizeShapeToFitText) + } + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported auto_fit `{value}`"), + }), + }) + .transpose()?; + let vertical_alignment = layout + .vertical_alignment + .as_deref() + .map(|value| match value { + "top" => Ok(TextVerticalAlignment::Top), + "middle" | "center" => Ok(TextVerticalAlignment::Middle), + "bottom" => Ok(TextVerticalAlignment::Bottom), + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported vertical_alignment `{value}`"), + }), + }) + .transpose()?; + Ok(TextLayoutState { + insets: layout.insets.as_ref().map(|insets| TextInsets { + left: insets.left, + right: insets.right, + top: insets.top, + bottom: insets.bottom, + }), + wrap, + auto_fit, + vertical_alignment, + }) +} + +fn normalize_rich_text_input( + document: &PresentationDocument, + input: RichTextInput, + action: &str, +) -> Result<(String, RichTextState), PresentationArtifactError> { + let mut text = String::new(); + let mut ranges = Vec::new(); + let paragraphs = match input { + RichTextInput::Plain(value) => vec![RichParagraphInput::Plain(value)], + RichTextInput::Paragraphs(paragraphs) => paragraphs, + }; + for (paragraph_index, paragraph) in paragraphs.into_iter().enumerate() { + if paragraph_index > 0 { + text.push('\n'); + } + let paragraph_start = text.chars().count(); + match paragraph { + RichParagraphInput::Plain(value) => text.push_str(&value), + RichParagraphInput::Runs(runs) => { + for run in runs { + match run { + RichRunInput::Plain(value) => text.push_str(&value), + RichRunInput::Styled(value) => { + let start_cp = text.chars().count(); + text.push_str(&value.run); + let length = value.run.chars().count(); + let style = normalize_text_style_with_document( + document, + &value.text_style, + action, + )?; + let hyperlink = value + .link + .as_ref() + .map(|link| parse_rich_text_link(link, action)) + .transpose()?; + if length > 0 + && (!text_style_is_empty(&style) || hyperlink.is_some()) + { + ranges.push(TextRangeAnnotation { + range_id: format!("inline_{paragraph_index}_{start_cp}"), + start_cp, + length, + style, + hyperlink, + spacing_before: None, + spacing_after: None, + line_spacing: None, + }); + } + } + } + } + } + } + let paragraph_len = text.chars().count() - paragraph_start; + if paragraph_len == 0 { + continue; + } + } + Ok(( + text, + RichTextState { + ranges, + layout: TextLayoutState::default(), + }, + )) +} + +fn parse_rich_text_link( + link: &RichTextLinkInput, + action: &str, +) -> Result { + let uri = link + .uri + .as_ref() + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`link.uri` is required".to_string(), + })?; + let target = if link.is_external.unwrap_or(true) { + HyperlinkTarget::Url(uri.clone()) + } else { + HyperlinkTarget::File(uri.clone()) + }; + Ok(HyperlinkState { + target, + tooltip: None, + highlight_click: true, + }) +} + +fn text_style_is_empty(style: &TextStyle) -> bool { + style.style_name.is_none() + && style.font_size.is_none() + && style.font_family.is_none() + && style.color.is_none() + && style.alignment.is_none() + && !style.bold + && !style.italic + && !style.underline +} + +fn resolve_text_range_selector( + text: &str, + query: Option<&str>, + occurrence: Option, + start_cp: Option, + length: Option, + action: &str, +) -> Result<(usize, usize, Option), PresentationArtifactError> { + if let Some(query) = query { + let occurrence = occurrence.unwrap_or(0); + let haystack = text.chars().collect::>(); + let needle = query.chars().collect::>(); + if needle.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`query` must not be empty".to_string(), + }); + } + let mut matches = Vec::new(); + for start in 0..=haystack.len().saturating_sub(needle.len()) { + if haystack[start..start + needle.len()] == needle[..] { + matches.push(start); + } + } + let Some(found) = matches.get(occurrence).copied() else { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("query `{query}` occurrence {occurrence} was not found"), + }); + }; + return Ok((found, needle.len(), Some(query.to_string()))); + } + let start_cp = start_cp.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "provide either `query` or `start_cp`".to_string(), + })?; + let length = length.ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`length` is required with `start_cp`".to_string(), + })?; + if start_cp + length > text.chars().count() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "text range is out of bounds".to_string(), + }); + } + Ok((start_cp, length, None)) +} + +fn normalize_text_style_with_palette( + theme: Option<&ThemeState>, + styling: &TextStylingArgs, + action: &str, + resolve_style_name: impl Fn(&str) -> Result, +) -> Result { + let mut style = styling + .style + .as_deref() + .map(resolve_style_name) + .transpose()? + .unwrap_or_default(); + style.font_size = styling.font_size.or(style.font_size); + style.font_family = styling.font_family.clone().or(style.font_family); + style.color = styling + .color + .as_deref() + .map(|value| normalize_color_with_palette(theme, value, action, "color")) + .transpose()? + .or(style.color); + style.alignment = styling + .alignment + .as_deref() + .map(|value| parse_alignment(value, action)) + .transpose()? + .or(style.alignment); + style.bold = styling.bold.unwrap_or(style.bold); + style.italic = styling.italic.unwrap_or(style.italic); + style.underline = styling.underline.unwrap_or(style.underline); + if let Some(style_name) = &styling.style { + style.style_name = Some(normalize_style_name(style_name, action)?); + } + Ok(style) +} + +fn parse_hyperlink_state( + document: &PresentationDocument, + args: &SetHyperlinkArgs, + action: &str, +) -> Result { + let link_type = + args.link_type + .as_deref() + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`link_type` is required unless `clear` is true".to_string(), + })?; + let target = match link_type { + "url" => HyperlinkTarget::Url(required_hyperlink_field(&args.url, action, "url")?.clone()), + "slide" => { + let slide_index = + args.slide_index + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`slide_index` is required for slide hyperlinks".to_string(), + })?; + if slide_index as usize >= document.slides.len() { + return Err(index_out_of_range( + action, + slide_index as usize, + document.slides.len(), + )); + } + HyperlinkTarget::Slide(slide_index) + } + "first_slide" => HyperlinkTarget::FirstSlide, + "last_slide" => HyperlinkTarget::LastSlide, + "next_slide" => HyperlinkTarget::NextSlide, + "previous_slide" => HyperlinkTarget::PreviousSlide, + "end_show" => HyperlinkTarget::EndShow, + "email" => HyperlinkTarget::Email { + address: required_hyperlink_field(&args.address, action, "address")?.clone(), + subject: args.subject.clone(), + }, + "file" => { + HyperlinkTarget::File(required_hyperlink_field(&args.path, action, "path")?.clone()) + } + other => { + return Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("hyperlink type `{other}` is not supported"), + }); + } + }; + Ok(HyperlinkState { + target, + tooltip: args.tooltip.clone(), + highlight_click: args.highlight_click.unwrap_or(true), + }) +} + +fn required_hyperlink_field<'a>( + value: &'a Option, + action: &str, + field: &str, +) -> Result<&'a String, PresentationArtifactError> { + value + .as_ref() + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("`{field}` is required for this hyperlink type"), + }) +} + +fn coerce_table_rows( + rows: Vec>, + action: &str, +) -> Result>, PresentationArtifactError> { + if rows.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`rows` must contain at least one row".to_string(), + }); + } + Ok(rows + .into_iter() + .map(|row| { + row.into_iter() + .map(|value| TableCellSpec { + text: cell_value_to_string(value), + text_style: TextStyle::default(), + background_fill: None, + alignment: None, + rich_text: RichTextState::default(), + borders: None, + }) + .collect() + }) + .collect()) +} + +fn parse_table_border( + document: &PresentationDocument, + border: &TableBorderArgs, + action: &str, + field: &str, +) -> Result { + Ok(TableBorder { + color: normalize_color_with_document(document, &border.color, action, field)?, + width: border.width, + }) +} + +fn parse_table_borders( + document: &PresentationDocument, + borders: Option, + action: &str, +) -> Result, PresentationArtifactError> { + borders + .map(|borders| { + Ok(TableBorders { + outside: borders + .outside + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.outside")) + .transpose()?, + inside: borders + .inside + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.inside")) + .transpose()?, + top: borders + .top + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.top")) + .transpose()?, + bottom: borders + .bottom + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.bottom")) + .transpose()?, + left: borders + .left + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.left")) + .transpose()?, + right: borders + .right + .as_ref() + .map(|border| parse_table_border(document, border, action, "borders.right")) + .transpose()?, + }) + }) + .transpose() +} + +fn parse_table_style_options(style_options: Option) -> TableStyleOptions { + style_options + .map(|style_options| TableStyleOptions { + header_row: style_options.header_row.unwrap_or(false), + banded_rows: style_options.banded_rows.unwrap_or(false), + banded_columns: style_options.banded_columns.unwrap_or(false), + first_column: style_options.first_column.unwrap_or(false), + last_column: style_options.last_column.unwrap_or(false), + total_row: style_options.total_row.unwrap_or(false), + }) + .unwrap_or_default() +} + +fn normalize_table_dimensions( + rows: &[Vec], + frame: Rect, + column_widths: Option>, + row_heights: Option>, + action: &str, +) -> Result<(Vec, Vec), PresentationArtifactError> { + let column_count = rows.iter().map(std::vec::Vec::len).max().unwrap_or(1); + let normalized_column_widths = match column_widths { + Some(widths) => { + if widths.len() != column_count { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "`column_widths` must contain {column_count} entries for this table" + ), + }); + } + widths + } + None => split_points(frame.width, column_count), + }; + let normalized_row_heights = match row_heights { + Some(heights) => { + if heights.len() != rows.len() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "`row_heights` must contain {} entries for this table", + rows.len() + ), + }); + } + heights + } + None => split_points(frame.height, rows.len()), + }; + Ok((normalized_column_widths, normalized_row_heights)) +} + +fn split_points(total: u32, count: usize) -> Vec { + if count == 0 { + return Vec::new(); + } + let base = total / count as u32; + let remainder = total % count as u32; + (0..count) + .map(|index| base + u32::from(index < remainder as usize)) + .collect() +} + +fn parse_alignment(value: &str, action: &str) -> Result { + match value { + "left" => Ok(TextAlignment::Left), + "center" | "middle" => Ok(TextAlignment::Center), + "right" => Ok(TextAlignment::Right), + "justify" => Ok(TextAlignment::Justify), + _ => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("unsupported alignment `{value}`"), + }), + } +} + +fn normalize_theme(args: ThemeArgs, action: &str) -> Result { + let color_scheme = args + .color_scheme + .into_iter() + .map(|(key, value)| { + normalize_color(&value, action, &key) + .map(|normalized| (key.to_ascii_lowercase(), normalized)) + }) + .collect::, _>>()?; + Ok(ThemeState { + color_scheme, + major_font: args.major_font, + minor_font: args.minor_font, + }) +} + +fn normalize_style_name( + style_name: &str, + action: &str, +) -> Result { + let normalized_style_name = style_name.trim().to_ascii_lowercase(); + if normalized_style_name.is_empty() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`name` must not be empty".to_string(), + }); + } + Ok(normalized_style_name) +} + +fn built_in_text_styles(theme: &ThemeState) -> HashMap { + ["title", "heading1", "body", "list", "numberedlist"] + .into_iter() + .filter_map(|name| built_in_text_style(theme, name).map(|style| (name.to_string(), style))) + .collect() +} + +fn built_in_text_style(theme: &ThemeState, style_name: &str) -> Option { + let default_color = theme.resolve_color("tx1"); + let default_font = theme + .major_font + .clone() + .or_else(|| theme.minor_font.clone()); + let body_font = theme + .minor_font + .clone() + .or_else(|| theme.major_font.clone()); + let style = match style_name { + "title" => TextStyle { + style_name: Some("title".to_string()), + font_size: Some(28), + font_family: default_font, + color: default_color, + alignment: Some(TextAlignment::Left), + bold: true, + italic: false, + underline: false, + }, + "heading1" => TextStyle { + style_name: Some("heading1".to_string()), + font_size: Some(22), + font_family: default_font, + color: default_color, + alignment: Some(TextAlignment::Left), + bold: true, + italic: false, + underline: false, + }, + "body" => TextStyle { + style_name: Some("body".to_string()), + font_size: Some(14), + font_family: body_font, + color: default_color, + alignment: Some(TextAlignment::Left), + bold: false, + italic: false, + underline: false, + }, + "list" => TextStyle { + style_name: Some("list".to_string()), + font_size: Some(14), + font_family: body_font, + color: default_color, + alignment: Some(TextAlignment::Left), + bold: false, + italic: false, + underline: false, + }, + "numberedlist" => TextStyle { + style_name: Some("numberedlist".to_string()), + font_size: Some(14), + font_family: body_font, + color: default_color, + alignment: Some(TextAlignment::Left), + bold: false, + italic: false, + underline: false, + }, + _ => return None, + }; + Some(style) +} + +fn named_text_style_to_json(style: &NamedTextStyle, id_prefix: &str) -> Value { + serde_json::json!({ + "kind": "textStyle", + "id": format!("{id_prefix}/{}", style.name), + "name": style.name, + "builtIn": style.built_in, + "style": text_style_to_proto(&style.style), + }) +} + +fn parse_slide_size(value: &Value, action: &str) -> Result { + #[derive(Deserialize)] + struct SlideSizeArgs { + width: u32, + height: u32, + } + + let slide_size: SlideSizeArgs = serde_json::from_value(value.clone()).map_err(|error| { + PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("invalid slide_size: {error}"), + } + })?; + Ok(Rect { + left: 0, + top: 0, + width: slide_size.width, + height: slide_size.height, + }) +} + +fn apply_layout_to_slide( + document: &mut PresentationDocument, + slide: &mut PresentationSlide, + layout_ref: &str, + action: &str, +) -> Result<(), PresentationArtifactError> { + let layout = document.get_layout(layout_ref, action)?.clone(); + let placeholders = resolved_layout_placeholders(document, &layout.layout_id, action)?; + slide.layout_id = Some(layout.layout_id); + for resolved in placeholders { + slide.elements.push(materialize_placeholder_element( + document.next_element_id(), + resolved.definition, + slide.elements.len(), + )); + } + Ok(()) +} + +fn materialize_placeholder_element( + element_id: String, + placeholder: PlaceholderDefinition, + z_order: usize, +) -> PresentationElement { + let placeholder_ref = Some(PlaceholderRef { + name: placeholder.name.clone(), + placeholder_type: placeholder.placeholder_type.clone(), + index: placeholder.index, + }); + if placeholder_is_image(&placeholder.placeholder_type) { + return PresentationElement::Image(ImageElement { + element_id, + frame: placeholder.frame, + payload: None, + fit_mode: ImageFitMode::Stretch, + crop: None, + rotation_degrees: None, + flip_horizontal: false, + flip_vertical: false, + lock_aspect_ratio: true, + alt_text: Some(placeholder.name.clone()), + prompt: placeholder + .text + .clone() + .or_else(|| Some(format!("Image placeholder: {}", placeholder.name))), + is_placeholder: true, + placeholder: placeholder_ref, + z_order, + }); + } + if placeholder.geometry == ShapeGeometry::Rectangle { + PresentationElement::Text(TextElement { + element_id, + text: placeholder.text.unwrap_or_default(), + frame: placeholder.frame, + fill: None, + style: TextStyle::default(), + hyperlink: None, + rich_text: RichTextState::default(), + placeholder: placeholder_ref, + z_order, + }) + } else { + PresentationElement::Shape(ShapeElement { + element_id, + geometry: placeholder.geometry, + frame: placeholder.frame, + fill: None, + stroke: None, + text: placeholder.text, + text_style: TextStyle::default(), + hyperlink: None, + rich_text: None, + placeholder: placeholder_ref, + rotation_degrees: None, + flip_horizontal: false, + flip_vertical: false, + z_order, + }) + } +} + +fn resolved_layout_placeholders( + document: &PresentationDocument, + layout_id: &str, + action: &str, +) -> Result, PresentationArtifactError> { + let mut lineage = Vec::new(); + collect_layout_lineage( + document, + layout_id, + action, + &mut HashSet::new(), + &mut lineage, + )?; + let mut resolved: Vec = Vec::new(); + for layout in lineage { + for placeholder in &layout.placeholders { + if let Some(index) = resolved.iter().position(|entry| { + placeholder_key(&entry.definition) == placeholder_key(placeholder) + }) { + resolved[index] = ResolvedPlaceholder { + source_layout_id: layout.layout_id.clone(), + definition: placeholder.clone(), + }; + } else { + resolved.push(ResolvedPlaceholder { + source_layout_id: layout.layout_id.clone(), + definition: placeholder.clone(), + }); + } + } + } + Ok(resolved) +} + +fn collect_layout_lineage<'a>( + document: &'a PresentationDocument, + layout_id: &str, + action: &str, + seen: &mut HashSet, + lineage: &mut Vec<&'a LayoutDocument>, +) -> Result<(), PresentationArtifactError> { + if !seen.insert(layout_id.to_string()) { + return Err(PresentationArtifactError::UnsupportedFeature { + action: action.to_string(), + message: format!("layout inheritance cycle detected at `{layout_id}`"), + }); + } + let layout = document.get_layout(layout_id, action)?; + if let Some(parent_layout_id) = &layout.parent_layout_id { + collect_layout_lineage(document, parent_layout_id, action, seen, lineage)?; + } + lineage.push(layout); + Ok(()) +} + +fn placeholder_key(placeholder: &PlaceholderDefinition) -> (String, String, Option) { + ( + placeholder.name.to_ascii_lowercase(), + placeholder.placeholder_type.to_ascii_lowercase(), + placeholder.index, + ) +} + +fn layout_placeholder_list( + document: &PresentationDocument, + layout_id: &str, + action: &str, +) -> Result, PresentationArtifactError> { + resolved_layout_placeholders(document, layout_id, action).map(|placeholders| { + placeholders + .into_iter() + .map(|placeholder| PlaceholderListEntry { + scope: "layout".to_string(), + source_layout_id: Some(placeholder.source_layout_id), + slide_index: None, + element_id: None, + name: placeholder.definition.name, + placeholder_type: placeholder.definition.placeholder_type, + index: placeholder.definition.index, + geometry: Some(format!("{:?}", placeholder.definition.geometry)), + text_preview: placeholder.definition.text, + }) + .collect() + }) +} + +fn placeholder_is_image(placeholder_type: &str) -> bool { + matches!( + placeholder_type.to_ascii_lowercase().as_str(), + "image" | "picture" | "pic" | "photo" + ) +} + +fn slide_placeholder_list( + slide: &PresentationSlide, + slide_index: usize, +) -> Vec { + slide + .elements + .iter() + .filter_map(|element| match element { + PresentationElement::Text(text) => { + text.placeholder + .as_ref() + .map(|placeholder| PlaceholderListEntry { + scope: "slide".to_string(), + source_layout_id: slide.layout_id.clone(), + slide_index: Some(slide_index), + element_id: Some(text.element_id.clone()), + name: placeholder.name.clone(), + placeholder_type: placeholder.placeholder_type.clone(), + index: placeholder.index, + geometry: Some("Rectangle".to_string()), + text_preview: Some(text.text.clone()), + }) + } + PresentationElement::Shape(shape) => { + shape + .placeholder + .as_ref() + .map(|placeholder| PlaceholderListEntry { + scope: "slide".to_string(), + source_layout_id: slide.layout_id.clone(), + slide_index: Some(slide_index), + element_id: Some(shape.element_id.clone()), + name: placeholder.name.clone(), + placeholder_type: placeholder.placeholder_type.clone(), + index: placeholder.index, + geometry: Some(format!("{:?}", shape.geometry)), + text_preview: shape.text.clone(), + }) + } + PresentationElement::Image(image) => { + image + .placeholder + .as_ref() + .map(|placeholder| PlaceholderListEntry { + scope: "slide".to_string(), + source_layout_id: slide.layout_id.clone(), + slide_index: Some(slide_index), + element_id: Some(image.element_id.clone()), + name: placeholder.name.clone(), + placeholder_type: placeholder.placeholder_type.clone(), + index: placeholder.index, + geometry: Some("Image".to_string()), + text_preview: image.prompt.clone(), + }) + } + PresentationElement::Connector(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => None, + }) + .collect() +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs b/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs new file mode 100644 index 0000000000..a06abc7017 --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/pptx.rs @@ -0,0 +1,951 @@ +const CODEX_METADATA_ENTRY: &str = "ppt/codex-document.json"; + +fn import_codex_metadata_document(path: &Path) -> Result, String> { + let file = std::fs::File::open(path).map_err(|error| error.to_string())?; + let mut archive = ZipArchive::new(file).map_err(|error| error.to_string())?; + let mut entry = match archive.by_name(CODEX_METADATA_ENTRY) { + Ok(entry) => entry, + Err(zip::result::ZipError::FileNotFound) => return Ok(None), + Err(error) => return Err(error.to_string()), + }; + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|error| error.to_string()) +} + +fn build_pptx_bytes(document: &PresentationDocument, action: &str) -> Result, String> { + let bytes = document + .to_ppt_rs() + .build() + .map_err(|error| format!("{action}: {error}"))?; + patch_pptx_package(bytes, document).map_err(|error| format!("{action}: {error}")) +} + +struct SlideImageAsset { + xml: String, + relationship_xml: String, + media_path: String, + media_bytes: Vec, + extension: String, +} + +fn normalized_image_extension(format: &str) -> String { + match format.to_ascii_lowercase().as_str() { + "jpeg" => "jpg".to_string(), + other => other.to_string(), + } +} + +fn image_relationship_xml(relationship_id: &str, target: &str) -> String { + format!( + r#""#, + ppt_rs::escape_xml(target) + ) +} + +fn image_picture_xml( + image: &ImageElement, + shape_id: usize, + relationship_id: &str, + frame: Rect, + crop: Option, +) -> String { + let blip_fill = if let Some((crop_left, crop_top, crop_right, crop_bottom)) = crop { + format!( + r#" + + + + + +"#, + (crop_left * 100_000.0).round() as u32, + (crop_top * 100_000.0).round() as u32, + (crop_right * 100_000.0).round() as u32, + (crop_bottom * 100_000.0).round() as u32, + ) + } else { + format!( + r#" + + + + +"# + ) + }; + let descr = image + .alt_text + .as_deref() + .map(|alt| format!(r#" descr="{}""#, ppt_rs::escape_xml(alt))) + .unwrap_or_default(); + let no_change_aspect = if image.lock_aspect_ratio { 1 } else { 0 }; + let rotation = image + .rotation_degrees + .map(|rotation| format!(r#" rot="{}""#, i64::from(rotation) * 60_000)) + .unwrap_or_default(); + let flip_horizontal = if image.flip_horizontal { + r#" flipH="1""# + } else { + "" + }; + let flip_vertical = if image.flip_vertical { + r#" flipV="1""# + } else { + "" + }; + format!( + r#" + + + + + + + +{blip_fill} + + + + + + + + + +"#, + points_to_emu(frame.left), + points_to_emu(frame.top), + points_to_emu(frame.width), + points_to_emu(frame.height), + ) +} + +fn slide_image_assets( + slide: &PresentationSlide, + next_media_index: &mut usize, +) -> Vec { + let mut ordered = slide.elements.iter().collect::>(); + ordered.sort_by_key(|element| element.z_order()); + let shape_count = ordered + .iter() + .filter(|element| { + matches!( + element, + PresentationElement::Text(_) + | PresentationElement::Shape(_) + | PresentationElement::Image(ImageElement { payload: None, .. }) + ) + }) + .count() + + usize::from(slide.background_fill.is_some()); + let mut image_index = 0_usize; + let mut assets = Vec::new(); + for element in ordered { + let PresentationElement::Image(image) = element else { + continue; + }; + let Some(payload) = &image.payload else { + continue; + }; + let (left, top, width, height, fitted_crop) = if image.fit_mode != ImageFitMode::Stretch { + fit_image(image) + } else { + ( + image.frame.left, + image.frame.top, + image.frame.width, + image.frame.height, + None, + ) + }; + image_index += 1; + let relationship_id = format!("rIdImage{image_index}"); + let extension = normalized_image_extension(&payload.format); + let media_name = format!("image{next_media_index}.{extension}"); + *next_media_index += 1; + assets.push(SlideImageAsset { + xml: image_picture_xml( + image, + 20 + shape_count + image_index - 1, + &relationship_id, + Rect { + left, + top, + width, + height, + }, + image.crop.or(fitted_crop), + ), + relationship_xml: image_relationship_xml( + &relationship_id, + &format!("../media/{media_name}"), + ), + media_path: format!("ppt/media/{media_name}"), + media_bytes: payload.bytes.clone(), + extension, + }); + } + assets +} + +fn patch_pptx_package( + source_bytes: Vec, + document: &PresentationDocument, +) -> Result, String> { + let mut archive = + ZipArchive::new(Cursor::new(source_bytes)).map_err(|error| error.to_string())?; + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + let mut next_media_index = 1_usize; + let mut pending_slide_relationships = HashMap::new(); + let mut pending_slide_images = HashMap::new(); + let mut pending_media = Vec::new(); + let mut image_extensions = BTreeSet::new(); + for (slide_index, slide) in document.slides.iter().enumerate() { + let slide_number = slide_index + 1; + let images = slide_image_assets(slide, &mut next_media_index); + let mut relationships = slide_hyperlink_relationships(slide); + relationships.extend(images.iter().map(|image| image.relationship_xml.clone())); + if !relationships.is_empty() { + pending_slide_relationships.insert(slide_number, relationships); + } + if !images.is_empty() { + image_extensions.extend(images.iter().map(|image| image.extension.clone())); + pending_media.extend( + images + .iter() + .map(|image| (image.media_path.clone(), image.media_bytes.clone())), + ); + pending_slide_images.insert(slide_number, images); + } + } + + for index in 0..archive.len() { + let mut file = archive.by_index(index).map_err(|error| error.to_string())?; + if file.is_dir() { + continue; + } + let name = file.name().to_string(); + if name == CODEX_METADATA_ENTRY { + continue; + } + let options = file.options(); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + writer + .start_file(&name, options) + .map_err(|error| error.to_string())?; + if name == "[Content_Types].xml" { + writer + .write_all(update_content_types_xml(bytes, &image_extensions)?.as_bytes()) + .map_err(|error| error.to_string())?; + continue; + } + if name == "ppt/presentation.xml" { + writer + .write_all( + update_presentation_xml_dimensions(bytes, document.slide_size)?.as_bytes(), + ) + .map_err(|error| error.to_string())?; + continue; + } + if let Some(slide_number) = parse_slide_xml_path(&name) { + writer + .write_all( + update_slide_xml( + bytes, + &document.slides[slide_number - 1], + pending_slide_images + .get(&slide_number) + .map(std::vec::Vec::as_slice) + .unwrap_or(&[]), + )? + .as_bytes(), + ) + .map_err(|error| error.to_string())?; + continue; + } + if let Some(slide_number) = parse_slide_relationships_path(&name) + && let Some(relationships) = pending_slide_relationships.remove(&slide_number) + { + writer + .write_all(update_slide_relationships_xml(bytes, &relationships)?.as_bytes()) + .map_err(|error| error.to_string())?; + continue; + } + writer + .write_all(&bytes) + .map_err(|error| error.to_string())?; + } + + for (slide_number, relationships) in pending_slide_relationships { + writer + .start_file( + format!("ppt/slides/_rels/slide{slide_number}.xml.rels"), + SimpleFileOptions::default(), + ) + .map_err(|error| error.to_string())?; + writer + .write_all(slide_relationships_xml(&relationships).as_bytes()) + .map_err(|error| error.to_string())?; + } + + for (path, bytes) in pending_media { + writer + .start_file(path, SimpleFileOptions::default()) + .map_err(|error| error.to_string())?; + writer + .write_all(&bytes) + .map_err(|error| error.to_string())?; + } + + writer + .start_file(CODEX_METADATA_ENTRY, SimpleFileOptions::default()) + .map_err(|error| error.to_string())?; + writer + .write_all( + &serde_json::to_vec(document).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + + writer + .finish() + .map_err(|error| error.to_string()) + .map(Cursor::into_inner) +} + +fn update_presentation_xml_dimensions( + existing_bytes: Vec, + slide_size: Rect, +) -> Result { + let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; + let updated = replace_self_closing_xml_tag( + &existing, + "p:sldSz", + &format!( + r#""#, + points_to_emu(slide_size.width), + points_to_emu(slide_size.height) + ), + )?; + replace_self_closing_xml_tag( + &updated, + "p:notesSz", + &format!( + r#""#, + points_to_emu(slide_size.height), + points_to_emu(slide_size.width) + ), + ) +} + +fn replace_self_closing_xml_tag(xml: &str, tag: &str, replacement: &str) -> Result { + let start = xml + .find(&format!("<{tag} ")) + .ok_or_else(|| format!("presentation xml is missing `<{tag} .../>`"))?; + let end = xml[start..] + .find("/>") + .map(|offset| start + offset + 2) + .ok_or_else(|| format!("presentation xml tag `{tag}` is not self-closing"))?; + Ok(format!("{}{replacement}{}", &xml[..start], &xml[end..])) +} + +fn slide_hyperlink_relationships(slide: &PresentationSlide) -> Vec { + let mut ordered = slide.elements.iter().collect::>(); + ordered.sort_by_key(|element| element.z_order()); + let mut hyperlink_index = 1_u32; + let mut relationships = Vec::new(); + for element in ordered { + let Some(hyperlink) = (match element { + PresentationElement::Text(text) => text.hyperlink.as_ref(), + PresentationElement::Shape(shape) => shape.hyperlink.as_ref(), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => None, + }) else { + continue; + }; + let relationship_id = format!("rIdHyperlink{hyperlink_index}"); + hyperlink_index += 1; + relationships.push(hyperlink.relationship_xml(&relationship_id)); + } + relationships +} + +fn parse_slide_relationships_path(path: &str) -> Option { + path.strip_prefix("ppt/slides/_rels/slide")? + .strip_suffix(".xml.rels")? + .parse::() + .ok() +} + +fn parse_slide_xml_path(path: &str) -> Option { + path.strip_prefix("ppt/slides/slide")? + .strip_suffix(".xml")? + .parse::() + .ok() +} + +fn update_slide_relationships_xml( + existing_bytes: Vec, + relationships: &[String], +) -> Result { + let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; + let injected = relationships.join("\n"); + existing + .contains("") + .then(|| existing.replace("", &format!("{injected}\n"))) + .ok_or_else(|| { + "slide relationships xml is missing a closing ``".to_string() + }) +} + +fn slide_relationships_xml(relationships: &[String]) -> String { + let body = relationships.join("\n"); + format!( + r#" + +{body} +"# + ) +} + +fn update_content_types_xml( + existing_bytes: Vec, + image_extensions: &BTreeSet, +) -> Result { + let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; + if image_extensions.is_empty() { + return Ok(existing); + } + let existing_lower = existing.to_ascii_lowercase(); + let additions = image_extensions + .iter() + .filter(|extension| { + !existing_lower.contains(&format!( + r#"extension="{}""#, + extension.to_ascii_lowercase() + )) + }) + .map(|extension| generate_image_content_type(extension)) + .collect::>(); + if additions.is_empty() { + return Ok(existing); + } + existing + .contains("") + .then(|| existing.replace("", &format!("{}\n", additions.join("\n")))) + .ok_or_else(|| "content types xml is missing a closing ``".to_string()) +} + +fn update_slide_xml( + existing_bytes: Vec, + slide: &PresentationSlide, + slide_images: &[SlideImageAsset], +) -> Result { + let existing = String::from_utf8(existing_bytes).map_err(|error| error.to_string())?; + let existing = replace_image_placeholders(existing, slide_images)?; + let existing = apply_shape_block_patches(existing, slide)?; + let table_xml = slide_table_xml(slide); + if table_xml.is_empty() { + return Ok(existing); + } + existing + .contains("") + .then(|| existing.replace("", &format!("{table_xml}\n"))) + .ok_or_else(|| "slide xml is missing a closing ``".to_string()) +} + +fn replace_image_placeholders( + existing: String, + slide_images: &[SlideImageAsset], +) -> Result { + if slide_images.is_empty() { + return Ok(existing); + } + let mut updated = String::with_capacity(existing.len()); + let mut remaining = existing.as_str(); + for image in slide_images { + let marker = remaining + .find("name=\"Image Placeholder: ") + .ok_or_else(|| { + "slide xml is missing an image placeholder block for exported images".to_string() + })?; + let start = remaining[..marker].rfind("").ok_or_else(|| { + "slide xml is missing an opening `` for image placeholder".to_string() + })?; + let end = remaining[marker..] + .find("") + .map(|offset| marker + offset + "".len()) + .ok_or_else(|| { + "slide xml is missing a closing `` for image placeholder".to_string() + })?; + updated.push_str(&remaining[..start]); + updated.push_str(&image.xml); + remaining = &remaining[end..]; + } + updated.push_str(remaining); + Ok(updated) +} + +#[derive(Clone, Copy)] +struct ShapeXmlPatch { + line_style: Option, + flip_horizontal: bool, + flip_vertical: bool, +} + +fn apply_shape_block_patches( + existing: String, + slide: &PresentationSlide, +) -> Result { + let mut patches = Vec::new(); + if slide.background_fill.is_some() { + patches.push(None); + } + let mut ordered = slide.elements.iter().collect::>(); + ordered.sort_by_key(|element| element.z_order()); + for element in ordered { + match element { + PresentationElement::Text(_) => patches.push(None), + PresentationElement::Shape(shape) => patches.push(Some(ShapeXmlPatch { + line_style: shape + .stroke + .as_ref() + .map(|stroke| stroke.style) + .filter(|style| *style != LineStyle::Solid), + flip_horizontal: shape.flip_horizontal, + flip_vertical: shape.flip_vertical, + })), + PresentationElement::Image(ImageElement { payload: None, .. }) => patches.push(None), + PresentationElement::Connector(_) + | PresentationElement::Image(_) + | PresentationElement::Table(_) + | PresentationElement::Chart(_) => {} + } + } + if patches.iter().all(|patch| { + patch.is_none_or(|patch| { + patch.line_style.is_none() && !patch.flip_horizontal && !patch.flip_vertical + }) + }) { + return Ok(existing); + } + + let mut updated = String::with_capacity(existing.len()); + let mut remaining = existing.as_str(); + for patch in patches { + let Some(start) = remaining.find("") else { + return Err("slide xml is missing an expected `` block".to_string()); + }; + let end = remaining[start..] + .find("") + .map(|offset| start + offset + "".len()) + .ok_or_else(|| "slide xml is missing a closing `` block".to_string())?; + updated.push_str(&remaining[..start]); + let block = &remaining[start..end]; + if let Some(patch) = patch { + updated.push_str(&patch_shape_block(block, patch)?); + } else { + updated.push_str(block); + } + remaining = &remaining[end..]; + } + updated.push_str(remaining); + Ok(updated) +} + +fn patch_shape_block(block: &str, patch: ShapeXmlPatch) -> Result { + let block = if let Some(line_style) = patch.line_style { + patch_shape_block_dash(block, line_style)? + } else { + block.to_string() + }; + if patch.flip_horizontal || patch.flip_vertical { + patch_shape_block_flip(&block, patch.flip_horizontal, patch.flip_vertical) + } else { + Ok(block) + } +} + +fn patch_shape_block_dash(block: &str, line_style: LineStyle) -> Result { + let Some(line_start) = block.find("` entry for stroke styling".to_string()); + }; + if let Some(dash_start) = block[line_start..].find("") + .map(|offset| dash_start + offset + 2) + .ok_or_else(|| "shape line dash entry is missing a closing `/>`".to_string())?; + let mut patched = String::with_capacity(block.len() + 32); + patched.push_str(&block[..dash_start]); + patched.push_str(&format!( + r#""#, + line_style.to_ppt_xml() + )); + patched.push_str(&block[dash_end..]); + return Ok(patched); + } + + if let Some(line_end) = block[line_start..].find("") { + let line_end = line_start + line_end; + let mut patched = String::with_capacity(block.len() + 32); + patched.push_str(&block[..line_end]); + patched.push_str(&format!( + r#""#, + line_style.to_ppt_xml() + )); + patched.push_str(&block[line_end..]); + return Ok(patched); + } + + let line_end = block[line_start..] + .find("/>") + .map(|offset| line_start + offset + 2) + .ok_or_else(|| "shape line entry is missing a closing marker".to_string())?; + let line_tag = &block[line_start..line_end - 2]; + let mut patched = String::with_capacity(block.len() + 48); + patched.push_str(&block[..line_start]); + patched.push_str(line_tag); + patched.push('>'); + patched.push_str(&format!( + r#""#, + line_style.to_ppt_xml() + )); + patched.push_str(""); + patched.push_str(&block[line_end..]); + Ok(patched) +} + +fn patch_shape_block_flip( + block: &str, + flip_horizontal: bool, + flip_vertical: bool, +) -> Result { + let Some(xfrm_start) = block.find("` entry for flip styling".to_string()); + }; + let tag_end = block[xfrm_start..] + .find('>') + .map(|offset| xfrm_start + offset) + .ok_or_else(|| "shape transform entry is missing a closing `>`".to_string())?; + let tag = &block[xfrm_start..=tag_end]; + let mut patched_tag = tag.to_string(); + patched_tag = upsert_xml_attribute( + &patched_tag, + "flipH", + if flip_horizontal { "1" } else { "0" }, + ); + patched_tag = + upsert_xml_attribute(&patched_tag, "flipV", if flip_vertical { "1" } else { "0" }); + Ok(format!( + "{}{}{}", + &block[..xfrm_start], + patched_tag, + &block[tag_end + 1..] + )) +} + +fn upsert_xml_attribute(tag: &str, attribute: &str, value: &str) -> String { + let needle = format!(r#"{attribute}=""#); + if let Some(start) = tag.find(&needle) { + let value_start = start + needle.len(); + if let Some(end_offset) = tag[value_start..].find('"') { + let end = value_start + end_offset; + return format!("{}{}{}", &tag[..value_start], value, &tag[end..]); + } + } + let insert_at = tag.len() - 1; + format!(r#"{} {attribute}="{value}""#, &tag[..insert_at]) + &tag[insert_at..] +} + +fn slide_table_xml(slide: &PresentationSlide) -> String { + let mut ordered = slide.elements.iter().collect::>(); + ordered.sort_by_key(|element| element.z_order()); + let mut table_index = 0_usize; + ordered + .into_iter() + .filter_map(|element| { + let PresentationElement::Table(table) = element else { + return None; + }; + table_index += 1; + let rows = table + .rows + .clone() + .into_iter() + .enumerate() + .map(|(row_index, row)| { + let cells = row + .into_iter() + .enumerate() + .map(|(column_index, cell)| { + build_table_cell(cell, &table.merges, row_index, column_index) + }) + .collect::>(); + let mut table_row = TableRow::new(cells); + if let Some(height) = table.row_heights.get(row_index) { + table_row = table_row.with_height(points_to_emu(*height)); + } + Some(table_row) + }) + .collect::>>()?; + Some(ppt_rs::generator::table::generate_table_xml( + &ppt_rs::generator::table::Table::new( + rows, + table + .column_widths + .iter() + .copied() + .map(points_to_emu) + .collect(), + points_to_emu(table.frame.left), + points_to_emu(table.frame.top), + ), + 300 + table_index, + )) + }) + .collect::>() + .join("\n") +} + +fn write_preview_images( + document: &PresentationDocument, + output_dir: &Path, + action: &str, +) -> Result<(), PresentationArtifactError> { + let pptx_path = output_dir.join("preview.pptx"); + let bytes = build_pptx_bytes(document, action).map_err(|message| { + PresentationArtifactError::ExportFailed { + path: pptx_path.clone(), + message, + } + })?; + std::fs::write(&pptx_path, bytes).map_err(|error| PresentationArtifactError::ExportFailed { + path: pptx_path.clone(), + message: error.to_string(), + })?; + render_pptx_to_pngs(&pptx_path, output_dir, action) +} + +fn render_pptx_to_pngs( + pptx_path: &Path, + output_dir: &Path, + action: &str, +) -> Result<(), PresentationArtifactError> { + let soffice_cmd = if cfg!(target_os = "macos") + && Path::new("/Applications/LibreOffice.app/Contents/MacOS/soffice").exists() + { + "/Applications/LibreOffice.app/Contents/MacOS/soffice" + } else { + "soffice" + }; + let conversion = Command::new(soffice_cmd) + .arg("--headless") + .arg("--convert-to") + .arg("pdf") + .arg(pptx_path) + .arg("--outdir") + .arg(output_dir) + .output() + .map_err(|error| PresentationArtifactError::ExportFailed { + path: pptx_path.to_path_buf(), + message: format!("{action}: failed to execute LibreOffice: {error}"), + })?; + if !conversion.status.success() { + return Err(PresentationArtifactError::ExportFailed { + path: pptx_path.to_path_buf(), + message: format!( + "{action}: LibreOffice conversion failed: {}", + String::from_utf8_lossy(&conversion.stderr) + ), + }); + } + + let pdf_path = output_dir.join( + pptx_path + .file_stem() + .and_then(|stem| stem.to_str()) + .map(|stem| format!("{stem}.pdf")) + .ok_or_else(|| PresentationArtifactError::ExportFailed { + path: pptx_path.to_path_buf(), + message: format!("{action}: preview pptx filename is invalid"), + })?, + ); + let prefix = output_dir.join("slide"); + let conversion = Command::new("pdftoppm") + .arg("-png") + .arg(&pdf_path) + .arg(&prefix) + .output() + .map_err(|error| PresentationArtifactError::ExportFailed { + path: pdf_path.clone(), + message: format!("{action}: failed to execute pdftoppm: {error}"), + })?; + std::fs::remove_file(&pdf_path).ok(); + if !conversion.status.success() { + return Err(PresentationArtifactError::ExportFailed { + path: output_dir.to_path_buf(), + message: format!( + "{action}: pdftoppm conversion failed: {}", + String::from_utf8_lossy(&conversion.stderr) + ), + }); + } + Ok(()) +} + +pub(crate) fn write_preview_image( + source_path: &Path, + target_path: &Path, + format: PreviewOutputFormat, + scale: f32, + quality: u8, + action: &str, +) -> Result<(), PresentationArtifactError> { + if matches!(format, PreviewOutputFormat::Png) && scale == 1.0 { + std::fs::rename(source_path, target_path).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: target_path.to_path_buf(), + message: error.to_string(), + } + })?; + return Ok(()); + } + let mut preview = + image::open(source_path).map_err(|error| PresentationArtifactError::ExportFailed { + path: source_path.to_path_buf(), + message: format!("{action}: {error}"), + })?; + if scale != 1.0 { + let width = (preview.width() as f32 * scale).round().max(1.0) as u32; + let height = (preview.height() as f32 * scale).round().max(1.0) as u32; + preview = preview.resize_exact(width, height, FilterType::Lanczos3); + } + let file = std::fs::File::create(target_path).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: target_path.to_path_buf(), + message: error.to_string(), + } + })?; + let mut writer = std::io::BufWriter::new(file); + match format { + PreviewOutputFormat::Png => { + preview + .write_to(&mut writer, ImageFormat::Png) + .map_err(|error| PresentationArtifactError::ExportFailed { + path: target_path.to_path_buf(), + message: format!("{action}: {error}"), + })? + } + PreviewOutputFormat::Jpeg => { + let rgb = preview.to_rgb8(); + let mut encoder = JpegEncoder::new_with_quality(&mut writer, quality); + encoder.encode_image(&rgb).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: target_path.to_path_buf(), + message: format!("{action}: {error}"), + } + })?; + } + PreviewOutputFormat::Svg => { + let mut png_bytes = Cursor::new(Vec::new()); + preview + .write_to(&mut png_bytes, ImageFormat::Png) + .map_err(|error| PresentationArtifactError::ExportFailed { + path: target_path.to_path_buf(), + message: format!("{action}: {error}"), + })?; + let embedded_png = BASE64_STANDARD.encode(png_bytes.into_inner()); + let svg = format!( + r#""#, + preview.width(), + preview.height(), + preview.width(), + preview.height(), + preview.width(), + preview.height(), + ); + writer.write_all(svg.as_bytes()).map_err(|error| { + PresentationArtifactError::ExportFailed { + path: target_path.to_path_buf(), + message: format!("{action}: {error}"), + } + })?; + } + } + std::fs::remove_file(source_path).ok(); + Ok(()) +} + +fn collect_pngs(output_dir: &Path) -> Result, PresentationArtifactError> { + let mut files = std::fs::read_dir(output_dir) + .map_err(|error| PresentationArtifactError::ExportFailed { + path: output_dir.to_path_buf(), + message: error.to_string(), + })? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("png")) + .collect::>(); + files.sort(); + Ok(files) +} + +fn parse_preview_output_format( + format: Option<&str>, + path: &Path, + action: &str, +) -> Result { + let value = format + .map(str::to_owned) + .or_else(|| { + path.extension() + .and_then(|extension| extension.to_str()) + .map(str::to_owned) + }) + .unwrap_or_else(|| "png".to_string()); + match value.to_ascii_lowercase().as_str() { + "png" => Ok(PreviewOutputFormat::Png), + "jpg" | "jpeg" => Ok(PreviewOutputFormat::Jpeg), + "svg" => Ok(PreviewOutputFormat::Svg), + other => Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("preview format `{other}` is not supported"), + }), + } +} + +fn normalize_preview_scale( + scale: Option, + action: &str, +) -> Result { + let scale = scale.unwrap_or(1.0); + if !scale.is_finite() || scale <= 0.0 { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`scale` must be a positive number".to_string(), + }); + } + Ok(scale) +} + +fn normalize_preview_quality( + quality: Option, + action: &str, +) -> Result { + let quality = quality.unwrap_or(90); + if quality == 0 || quality > 100 { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "`quality` must be between 1 and 100".to_string(), + }); + } + Ok(quality) +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs b/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs new file mode 100644 index 0000000000..05741303ac --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/proto.rs @@ -0,0 +1,614 @@ +fn document_to_proto( + document: &PresentationDocument, + action: &str, +) -> Result { + let layouts = document + .layouts + .iter() + .map(|layout| layout_to_proto(document, layout, action)) + .collect::, _>>()?; + let slides = document + .slides + .iter() + .enumerate() + .map(|(slide_index, slide)| slide_to_proto(slide, slide_index)) + .collect::>(); + Ok(serde_json::json!({ + "kind": "presentation", + "artifactId": document.artifact_id, + "anchor": format!("pr/{}", document.artifact_id), + "name": document.name, + "slideSize": rect_to_proto(document.slide_size), + "activeSlideIndex": document.active_slide_index, + "activeSlideId": document.active_slide_index.and_then(|index| document.slides.get(index)).map(|slide| slide.slide_id.clone()), + "theme": serde_json::json!({ + "colorScheme": document.theme.color_scheme, + "hexColorMap": document.theme.color_scheme, + "majorFont": document.theme.major_font, + "minorFont": document.theme.minor_font, + }), + "styles": document + .named_text_styles() + .iter() + .map(|style| named_text_style_to_json(style, "st")) + .collect::>(), + "masters": document.layouts.iter().filter(|layout| layout.kind == LayoutKind::Master).map(|layout| layout.layout_id.clone()).collect::>(), + "layouts": layouts, + "slides": slides, + "commentAuthor": document.comment_self.as_ref().map(comment_author_to_proto), + "commentThreads": document + .comment_threads + .iter() + .map(comment_thread_to_proto) + .collect::>(), + })) +} + +fn layout_to_proto( + document: &PresentationDocument, + layout: &LayoutDocument, + action: &str, +) -> Result { + let placeholders = layout + .placeholders + .iter() + .map(placeholder_definition_to_proto) + .collect::>(); + let resolved_placeholders = resolved_layout_placeholders(document, &layout.layout_id, action)? + .into_iter() + .map(|placeholder| { + let mut value = placeholder_definition_to_proto(&placeholder.definition); + value["sourceLayoutId"] = Value::String(placeholder.source_layout_id); + value + }) + .collect::>(); + Ok(serde_json::json!({ + "layoutId": layout.layout_id, + "anchor": format!("ly/{}", layout.layout_id), + "name": layout.name, + "kind": match layout.kind { + LayoutKind::Layout => "layout", + LayoutKind::Master => "master", + }, + "parentLayoutId": layout.parent_layout_id, + "placeholders": placeholders, + "resolvedPlaceholders": resolved_placeholders, + })) +} + +fn placeholder_definition_to_proto(placeholder: &PlaceholderDefinition) -> Value { + serde_json::json!({ + "name": placeholder.name, + "placeholderType": placeholder.placeholder_type, + "index": placeholder.index, + "text": placeholder.text, + "geometry": format!("{:?}", placeholder.geometry), + "frame": rect_to_proto(placeholder.frame), + }) +} + +fn slide_to_proto(slide: &PresentationSlide, slide_index: usize) -> Value { + serde_json::json!({ + "slideId": slide.slide_id, + "anchor": format!("sl/{}", slide.slide_id), + "index": slide_index, + "layoutId": slide.layout_id, + "backgroundFill": slide.background_fill, + "notes": serde_json::json!({ + "anchor": format!("nt/{}", slide.slide_id), + "text": slide.notes.text, + "visible": slide.notes.visible, + "textPreview": slide.notes.text.replace('\n', " | "), + "textChars": slide.notes.text.chars().count(), + "textLines": slide.notes.text.lines().count(), + "richText": rich_text_to_proto(&slide.notes.text, &slide.notes.rich_text), + }), + "elements": slide.elements.iter().map(element_to_proto).collect::>(), + }) +} + +fn element_to_proto(element: &PresentationElement) -> Value { + match element { + PresentationElement::Text(text) => { + let mut record = serde_json::json!({ + "kind": "text", + "elementId": text.element_id, + "anchor": format!("sh/{}", text.element_id), + "frame": rect_to_proto(text.frame), + "text": text.text, + "textPreview": text.text.replace('\n', " | "), + "textChars": text.text.chars().count(), + "textLines": text.text.lines().count(), + "fill": text.fill, + "style": text_style_to_proto(&text.style), + "richText": rich_text_to_proto(&text.text, &text.rich_text), + "zOrder": text.z_order, + }); + if let Some(placeholder) = &text.placeholder { + record["placeholder"] = placeholder_ref_to_proto(placeholder); + } + if let Some(hyperlink) = &text.hyperlink { + record["hyperlink"] = hyperlink.to_json(); + } + record + } + PresentationElement::Shape(shape) => { + let mut record = serde_json::json!({ + "kind": "shape", + "elementId": shape.element_id, + "anchor": format!("sh/{}", shape.element_id), + "geometry": format!("{:?}", shape.geometry), + "frame": rect_to_proto(shape.frame), + "fill": shape.fill, + "stroke": shape.stroke.as_ref().map(stroke_to_proto), + "text": shape.text, + "textStyle": text_style_to_proto(&shape.text_style), + "richText": shape + .text + .as_ref() + .zip(shape.rich_text.as_ref()) + .map(|(text, rich_text)| rich_text_to_proto(text, rich_text)) + .unwrap_or(Value::Null), + "rotation": shape.rotation_degrees, + "flipHorizontal": shape.flip_horizontal, + "flipVertical": shape.flip_vertical, + "zOrder": shape.z_order, + }); + if let Some(text) = &shape.text { + record["textPreview"] = Value::String(text.replace('\n', " | ")); + record["textChars"] = Value::from(text.chars().count()); + record["textLines"] = Value::from(text.lines().count()); + } + if let Some(placeholder) = &shape.placeholder { + record["placeholder"] = placeholder_ref_to_proto(placeholder); + } + if let Some(hyperlink) = &shape.hyperlink { + record["hyperlink"] = hyperlink.to_json(); + } + record + } + PresentationElement::Connector(connector) => serde_json::json!({ + "kind": "connector", + "elementId": connector.element_id, + "anchor": format!("cn/{}", connector.element_id), + "connectorType": format!("{:?}", connector.connector_type), + "start": serde_json::json!({ + "left": connector.start.left, + "top": connector.start.top, + "unit": "points", + }), + "end": serde_json::json!({ + "left": connector.end.left, + "top": connector.end.top, + "unit": "points", + }), + "line": stroke_to_proto(&connector.line), + "lineStyle": connector.line_style.as_api_str(), + "startArrow": format!("{:?}", connector.start_arrow), + "endArrow": format!("{:?}", connector.end_arrow), + "arrowSize": format!("{:?}", connector.arrow_size), + "label": connector.label, + "zOrder": connector.z_order, + }), + PresentationElement::Image(image) => { + let mut record = serde_json::json!({ + "kind": "image", + "elementId": image.element_id, + "anchor": format!("im/{}", image.element_id), + "frame": rect_to_proto(image.frame), + "fit": format!("{:?}", image.fit_mode), + "crop": image.crop.map(|(left, top, right, bottom)| serde_json::json!({ + "left": left, + "top": top, + "right": right, + "bottom": bottom, + })), + "rotation": image.rotation_degrees, + "flipHorizontal": image.flip_horizontal, + "flipVertical": image.flip_vertical, + "lockAspectRatio": image.lock_aspect_ratio, + "alt": image.alt_text, + "prompt": image.prompt, + "isPlaceholder": image.is_placeholder, + "payload": image.payload.as_ref().map(image_payload_to_proto), + "zOrder": image.z_order, + }); + if let Some(placeholder) = &image.placeholder { + record["placeholder"] = placeholder_ref_to_proto(placeholder); + } + record + } + PresentationElement::Table(table) => serde_json::json!({ + "kind": "table", + "elementId": table.element_id, + "anchor": format!("tb/{}", table.element_id), + "frame": rect_to_proto(table.frame), + "rows": table.rows.iter().map(|row| { + row.iter().map(table_cell_to_proto).collect::>() + }).collect::>(), + "columnWidths": table.column_widths, + "rowHeights": table.row_heights, + "style": table.style, + "styleOptions": table_style_options_to_proto(&table.style_options), + "borders": table.borders.as_ref().map(table_borders_to_proto), + "rightToLeft": table.right_to_left, + "merges": table.merges.iter().map(|merge| serde_json::json!({ + "startRow": merge.start_row, + "endRow": merge.end_row, + "startColumn": merge.start_column, + "endColumn": merge.end_column, + })).collect::>(), + "zOrder": table.z_order, + }), + PresentationElement::Chart(chart) => serde_json::json!({ + "kind": "chart", + "elementId": chart.element_id, + "anchor": format!("ch/{}", chart.element_id), + "frame": rect_to_proto(chart.frame), + "chartType": format!("{:?}", chart.chart_type), + "title": chart.title, + "categories": chart.categories, + "styleIndex": chart.style_index, + "hasLegend": chart.has_legend, + "legend": chart.legend.as_ref().map(chart_legend_to_proto), + "xAxis": chart.x_axis.as_ref().map(chart_axis_to_proto), + "yAxis": chart.y_axis.as_ref().map(chart_axis_to_proto), + "dataLabels": chart.data_labels.as_ref().map(chart_data_labels_to_proto), + "chartFill": chart.chart_fill, + "plotAreaFill": chart.plot_area_fill, + "series": chart.series.iter().map(|series| serde_json::json!({ + "name": series.name, + "values": series.values, + "categories": series.categories, + "xValues": series.x_values, + "fill": series.fill, + "stroke": series.stroke.as_ref().map(stroke_to_proto), + "marker": series.marker.as_ref().map(chart_marker_to_proto), + "dataLabelOverrides": series + .data_label_overrides + .iter() + .map(chart_data_label_override_to_proto) + .collect::>(), + })).collect::>(), + "zOrder": chart.z_order, + }), + } +} + +fn rect_to_proto(rect: Rect) -> Value { + serde_json::json!({ + "left": rect.left, + "top": rect.top, + "width": rect.width, + "height": rect.height, + "unit": "points", + }) +} + +fn stroke_to_proto(stroke: &StrokeStyle) -> Value { + serde_json::json!({ + "color": stroke.color, + "width": stroke.width, + "style": stroke.style.as_api_str(), + "unit": "points", + }) +} + +fn text_style_to_proto(style: &TextStyle) -> Value { + serde_json::json!({ + "styleName": style.style_name, + "fontSize": style.font_size, + "fontFamily": style.font_family, + "color": style.color, + "alignment": style.alignment, + "bold": style.bold, + "italic": style.italic, + "underline": style.underline, + }) +} + +fn rich_text_to_proto(text: &str, rich_text: &RichTextState) -> Value { + serde_json::json!({ + "layout": text_layout_to_proto(&rich_text.layout), + "ranges": rich_text + .ranges + .iter() + .map(|range| text_range_to_proto(text, range)) + .collect::>(), + }) +} + +fn text_range_to_proto(text: &str, range: &TextRangeAnnotation) -> Value { + serde_json::json!({ + "rangeId": range.range_id, + "anchor": format!("tr/{}", range.range_id), + "startCp": range.start_cp, + "length": range.length, + "text": text_slice_by_codepoint_range(text, range.start_cp, range.length), + "style": text_style_to_proto(&range.style), + "hyperlink": range.hyperlink.as_ref().map(HyperlinkState::to_json), + "spacingBefore": range.spacing_before, + "spacingAfter": range.spacing_after, + "lineSpacing": range.line_spacing, + }) +} + +fn text_layout_to_proto(layout: &TextLayoutState) -> Value { + serde_json::json!({ + "insets": layout.insets.map(|insets| serde_json::json!({ + "left": insets.left, + "right": insets.right, + "top": insets.top, + "bottom": insets.bottom, + "unit": "points", + })), + "wrap": layout.wrap.map(text_wrap_mode_to_proto), + "autoFit": layout.auto_fit.map(text_auto_fit_mode_to_proto), + "verticalAlignment": layout + .vertical_alignment + .map(text_vertical_alignment_to_proto), + }) +} + +fn text_wrap_mode_to_proto(mode: TextWrapMode) -> &'static str { + match mode { + TextWrapMode::Square => "square", + TextWrapMode::None => "none", + } +} + +fn text_auto_fit_mode_to_proto(mode: TextAutoFitMode) -> &'static str { + match mode { + TextAutoFitMode::None => "none", + TextAutoFitMode::ShrinkText => "shrinkText", + TextAutoFitMode::ResizeShapeToFitText => "resizeShapeToFitText", + } +} + +fn text_vertical_alignment_to_proto(alignment: TextVerticalAlignment) -> &'static str { + match alignment { + TextVerticalAlignment::Top => "top", + TextVerticalAlignment::Middle => "middle", + TextVerticalAlignment::Bottom => "bottom", + } +} + +fn placeholder_ref_to_proto(placeholder: &PlaceholderRef) -> Value { + serde_json::json!({ + "name": placeholder.name, + "placeholderType": placeholder.placeholder_type, + "index": placeholder.index, + }) +} + +fn image_payload_to_proto(payload: &ImagePayload) -> Value { + serde_json::json!({ + "format": payload.format, + "widthPx": payload.width_px, + "heightPx": payload.height_px, + "bytesBase64": BASE64_STANDARD.encode(&payload.bytes), + }) +} + +fn table_cell_to_proto(cell: &TableCellSpec) -> Value { + serde_json::json!({ + "text": cell.text, + "textStyle": text_style_to_proto(&cell.text_style), + "richText": rich_text_to_proto(&cell.text, &cell.rich_text), + "backgroundFill": cell.background_fill, + "alignment": cell.alignment, + "borders": cell.borders.as_ref().map(table_borders_to_proto), + }) +} + +fn table_style_options_to_proto(style_options: &TableStyleOptions) -> Value { + serde_json::json!({ + "headerRow": style_options.header_row, + "bandedRows": style_options.banded_rows, + "bandedColumns": style_options.banded_columns, + "firstColumn": style_options.first_column, + "lastColumn": style_options.last_column, + "totalRow": style_options.total_row, + }) +} + +fn table_borders_to_proto(borders: &TableBorders) -> Value { + serde_json::json!({ + "outside": borders.outside.as_ref().map(table_border_to_proto), + "inside": borders.inside.as_ref().map(table_border_to_proto), + "top": borders.top.as_ref().map(table_border_to_proto), + "bottom": borders.bottom.as_ref().map(table_border_to_proto), + "left": borders.left.as_ref().map(table_border_to_proto), + "right": borders.right.as_ref().map(table_border_to_proto), + }) +} + +fn table_border_to_proto(border: &TableBorder) -> Value { + serde_json::json!({ + "color": border.color, + "width": border.width, + "unit": "points", + }) +} + +fn chart_marker_to_proto(marker: &ChartMarkerStyle) -> Value { + serde_json::json!({ + "symbol": marker.symbol, + "size": marker.size, + }) +} + +fn chart_data_labels_to_proto(data_labels: &ChartDataLabels) -> Value { + serde_json::json!({ + "showValue": data_labels.show_value, + "showCategoryName": data_labels.show_category_name, + "showLeaderLines": data_labels.show_leader_lines, + "position": data_labels.position, + "textStyle": text_style_to_proto(&data_labels.text_style), + }) +} + +fn chart_legend_to_proto(legend: &ChartLegend) -> Value { + serde_json::json!({ + "position": legend.position, + "textStyle": text_style_to_proto(&legend.text_style), + }) +} + +fn chart_axis_to_proto(axis: &ChartAxisSpec) -> Value { + serde_json::json!({ + "title": axis.title, + }) +} + +fn chart_data_label_override_to_proto(override_spec: &ChartDataLabelOverride) -> Value { + serde_json::json!({ + "idx": override_spec.idx, + "text": override_spec.text, + "position": override_spec.position, + "textStyle": text_style_to_proto(&override_spec.text_style), + "fill": override_spec.fill, + "stroke": override_spec.stroke.as_ref().map(stroke_to_proto), + }) +} + +fn comment_author_to_proto(author: &CommentAuthorProfile) -> Value { + serde_json::json!({ + "displayName": author.display_name, + "initials": author.initials, + "email": author.email, + }) +} + +fn comment_thread_to_proto(thread: &CommentThread) -> Value { + serde_json::json!({ + "kind": "comment", + "threadId": thread.thread_id, + "anchor": format!("th/{}", thread.thread_id), + "target": comment_target_to_proto(&thread.target), + "position": thread.position.as_ref().map(comment_position_to_proto), + "status": comment_status_to_proto(thread.status), + "messages": thread.messages.iter().map(comment_message_to_proto).collect::>(), + }) +} + +fn comment_target_to_proto(target: &CommentTarget) -> Value { + match target { + CommentTarget::Slide { slide_id } => serde_json::json!({ + "type": "slide", + "slideId": slide_id, + "slideAnchor": format!("sl/{slide_id}"), + }), + CommentTarget::Element { + slide_id, + element_id, + } => serde_json::json!({ + "type": "element", + "slideId": slide_id, + "slideAnchor": format!("sl/{slide_id}"), + "elementId": element_id, + "elementAnchor": format!("sh/{element_id}"), + }), + CommentTarget::TextRange { + slide_id, + element_id, + start_cp, + length, + context, + } => serde_json::json!({ + "type": "textRange", + "slideId": slide_id, + "slideAnchor": format!("sl/{slide_id}"), + "elementId": element_id, + "elementAnchor": format!("sh/{element_id}"), + "startCp": start_cp, + "length": length, + "context": context, + }), + } +} + +fn comment_position_to_proto(position: &CommentPosition) -> Value { + serde_json::json!({ + "x": position.x, + "y": position.y, + "unit": "points", + }) +} + +fn comment_message_to_proto(message: &CommentMessage) -> Value { + serde_json::json!({ + "messageId": message.message_id, + "author": comment_author_to_proto(&message.author), + "text": message.text, + "createdAt": message.created_at, + "reactions": message.reactions, + }) +} + +fn comment_status_to_proto(status: CommentThreadStatus) -> &'static str { + match status { + CommentThreadStatus::Active => "active", + CommentThreadStatus::Resolved => "resolved", + } +} + +fn text_slice_by_codepoint_range(text: &str, start_cp: usize, length: usize) -> String { + text.chars().skip(start_cp).take(length).collect() +} + +fn build_table_cell( + cell: TableCellSpec, + merges: &[TableMergeRegion], + row_index: usize, + column_index: usize, +) -> TableCell { + let mut table_cell = TableCell::new(&cell.text); + if cell.text_style.bold { + table_cell = table_cell.bold(); + } + if cell.text_style.italic { + table_cell = table_cell.italic(); + } + if cell.text_style.underline { + table_cell = table_cell.underline(); + } + if let Some(color) = cell.text_style.color { + table_cell = table_cell.text_color(&color); + } + if let Some(fill) = cell.background_fill { + table_cell = table_cell.background_color(&fill); + } + if let Some(size) = cell.text_style.font_size { + table_cell = table_cell.font_size(size); + } + if let Some(font_family) = cell.text_style.font_family { + table_cell = table_cell.font_family(&font_family); + } + if let Some(alignment) = cell.alignment.or(cell.text_style.alignment) { + table_cell = match alignment { + TextAlignment::Left => table_cell.align_left(), + TextAlignment::Center => table_cell.align_center(), + TextAlignment::Right => table_cell.align_right(), + TextAlignment::Justify => table_cell.align(CellAlign::Justify), + }; + } + for merge in merges { + if row_index == merge.start_row && column_index == merge.start_column { + table_cell = table_cell + .grid_span((merge.end_column - merge.start_column + 1) as u32) + .row_span((merge.end_row - merge.start_row + 1) as u32); + } else if row_index >= merge.start_row + && row_index <= merge.end_row + && column_index >= merge.start_column + && column_index <= merge.end_column + { + if row_index == merge.start_row { + table_cell = table_cell.h_merge(); + } else { + table_cell = table_cell.v_merge(); + } + } + } + table_cell +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/response.rs b/codex-rs/artifact-presentation/src/presentation_artifact/response.rs new file mode 100644 index 0000000000..241cce570d --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/response.rs @@ -0,0 +1,138 @@ +#[derive(Debug, Clone, Serialize)] +pub struct PresentationArtifactResponse { + pub artifact_id: String, + pub action: String, + pub summary: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub executed_actions: Option>, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub exported_paths: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub artifact_snapshot: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub slide_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub placeholder_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub theme: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub inspect_ndjson: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub resolved_record: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub proto_json: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub patch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub active_slide_index: Option, +} + +impl PresentationArtifactResponse { + fn new( + artifact_id: String, + action: String, + summary: String, + artifact_snapshot: ArtifactSnapshot, + ) -> Self { + Self { + artifact_id, + action, + summary, + executed_actions: None, + exported_paths: Vec::new(), + artifact_snapshot: Some(artifact_snapshot), + slide_list: None, + layout_list: None, + placeholder_list: None, + theme: None, + inspect_ndjson: None, + resolved_record: None, + proto_json: None, + patch: None, + active_slide_index: None, + } + } +} + +fn response_for_document_state( + artifact_id: String, + action: String, + summary: String, + document: Option<&PresentationDocument>, +) -> PresentationArtifactResponse { + PresentationArtifactResponse { + artifact_id, + action, + summary, + executed_actions: None, + exported_paths: Vec::new(), + artifact_snapshot: document.map(snapshot_for_document), + slide_list: None, + layout_list: None, + placeholder_list: None, + theme: document.map(PresentationDocument::theme_snapshot), + inspect_ndjson: None, + resolved_record: None, + proto_json: None, + patch: None, + active_slide_index: document.and_then(|current| current.active_slide_index), + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct ArtifactSnapshot { + pub slide_count: usize, + pub slides: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SlideSnapshot { + pub slide_id: String, + pub index: usize, + pub element_ids: Vec, + pub element_types: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SlideListEntry { + pub slide_id: String, + pub index: usize, + pub is_active: bool, + pub notes: Option, + pub notes_visible: bool, + pub background_fill: Option, + pub layout_id: Option, + pub element_count: usize, +} + +#[derive(Debug, Clone, Serialize)] +pub struct LayoutListEntry { + pub layout_id: String, + pub name: String, + pub kind: String, + pub parent_layout_id: Option, + pub placeholder_count: usize, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PlaceholderListEntry { + pub scope: String, + pub source_layout_id: Option, + pub slide_index: Option, + pub element_id: Option, + pub name: String, + pub placeholder_type: String, + pub index: Option, + pub geometry: Option, + pub text_preview: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ThemeSnapshot { + pub color_scheme: HashMap, + pub hex_color_map: HashMap, + pub major_font: Option, + pub minor_font: Option, +} diff --git a/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs b/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs new file mode 100644 index 0000000000..8606649c38 --- /dev/null +++ b/codex-rs/artifact-presentation/src/presentation_artifact/snapshot.rs @@ -0,0 +1,339 @@ +fn cell_value_to_string(value: Value) -> String { + match value { + Value::Null => String::new(), + Value::String(text) => text, + Value::Bool(boolean) => boolean.to_string(), + Value::Number(number) => number.to_string(), + other => other.to_string(), + } +} + +fn snapshot_for_document(document: &PresentationDocument) -> ArtifactSnapshot { + ArtifactSnapshot { + slide_count: document.slides.len(), + slides: document + .slides + .iter() + .enumerate() + .map(|(index, slide)| SlideSnapshot { + slide_id: slide.slide_id.clone(), + index, + element_ids: slide + .elements + .iter() + .map(|element| element.element_id().to_string()) + .collect(), + element_types: slide + .elements + .iter() + .map(|element| element.kind().to_string()) + .collect(), + }) + .collect(), + } +} + +fn slide_list(document: &PresentationDocument) -> Vec { + document + .slides + .iter() + .enumerate() + .map(|(index, slide)| SlideListEntry { + slide_id: slide.slide_id.clone(), + index, + is_active: document.active_slide_index == Some(index), + notes: (slide.notes.visible && !slide.notes.text.is_empty()) + .then(|| slide.notes.text.clone()), + notes_visible: slide.notes.visible, + background_fill: slide.background_fill.clone(), + layout_id: slide.layout_id.clone(), + element_count: slide.elements.len(), + }) + .collect() +} + +fn layout_list(document: &PresentationDocument) -> Vec { + document + .layouts + .iter() + .map(|layout| LayoutListEntry { + layout_id: layout.layout_id.clone(), + name: layout.name.clone(), + kind: match layout.kind { + LayoutKind::Layout => "layout".to_string(), + LayoutKind::Master => "master".to_string(), + }, + parent_layout_id: layout.parent_layout_id.clone(), + placeholder_count: layout.placeholders.len(), + }) + .collect() +} + +fn points_to_emu(points: u32) -> u32 { + points.saturating_mul(POINT_TO_EMU) +} + +fn emu_to_points(emu: u32) -> u32 { + emu / POINT_TO_EMU +} + +type ImageCrop = (f64, f64, f64, f64); +type FittedImage = (u32, u32, u32, u32, Option); + +pub(crate) fn fit_image(image: &ImageElement) -> FittedImage { + let Some(payload) = image.payload.as_ref() else { + return ( + image.frame.left, + image.frame.top, + image.frame.width, + image.frame.height, + None, + ); + }; + let frame = image.frame; + let source_width = payload.width_px as f64; + let source_height = payload.height_px as f64; + let target_width = frame.width as f64; + let target_height = frame.height as f64; + let source_ratio = source_width / source_height; + let target_ratio = target_width / target_height; + + match image.fit_mode { + ImageFitMode::Stretch => (frame.left, frame.top, frame.width, frame.height, None), + ImageFitMode::Contain => { + let scale = if source_ratio > target_ratio { + target_width / source_width + } else { + target_height / source_height + }; + let width = (source_width * scale).round() as u32; + let height = (source_height * scale).round() as u32; + let left = frame.left + frame.width.saturating_sub(width) / 2; + let top = frame.top + frame.height.saturating_sub(height) / 2; + (left, top, width, height, None) + } + ImageFitMode::Cover => { + let scale = if source_ratio > target_ratio { + target_height / source_height + } else { + target_width / source_width + }; + let width = source_width * scale; + let height = source_height * scale; + let crop_x = ((width - target_width).max(0.0) / width) / 2.0; + let crop_y = ((height - target_height).max(0.0) / height) / 2.0; + ( + frame.left, + frame.top, + frame.width, + frame.height, + Some((crop_x, crop_y, crop_x, crop_y)), + ) + } + } +} + +fn normalize_image_crop( + crop: ImageCropArgs, + action: &str, +) -> Result { + for (name, value) in [ + ("left", crop.left), + ("top", crop.top), + ("right", crop.right), + ("bottom", crop.bottom), + ] { + if !(0.0..=1.0).contains(&value) { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("image crop `{name}` must be between 0.0 and 1.0"), + }); + } + } + Ok((crop.left, crop.top, crop.right, crop.bottom)) +} + +fn load_image_payload_from_path( + path: &Path, + action: &str, +) -> Result { + let bytes = std::fs::read(path).map_err(|error| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to read image `{}`: {error}", path.display()), + })?; + build_image_payload( + bytes, + path.file_name() + .and_then(|name| name.to_str()) + .unwrap_or("image") + .to_string(), + action, + ) +} + +fn load_image_payload_from_data_url( + data_url: &str, + action: &str, +) -> Result { + let (header, payload) = + data_url + .split_once(',') + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "data_url must include a MIME header and base64 payload".to_string(), + })?; + let mime = header + .strip_prefix("data:") + .and_then(|prefix| prefix.strip_suffix(";base64")) + .ok_or_else(|| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: "data_url must be base64-encoded".to_string(), + })?; + let bytes = BASE64_STANDARD.decode(payload).map_err(|error| { + PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to decode image data_url: {error}"), + } + })?; + build_image_payload( + bytes, + format!("image.{}", image_extension_from_mime(mime)), + action, + ) +} + +fn load_image_payload_from_blob( + blob: &str, + action: &str, +) -> Result { + let bytes = BASE64_STANDARD.decode(blob.trim()).map_err(|error| { + PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to decode image blob: {error}"), + } + })?; + let extension = image::guess_format(&bytes) + .ok() + .map(image_extension_from_format) + .unwrap_or("png"); + build_image_payload(bytes, format!("image.{extension}"), action) +} + +fn load_image_payload_from_uri( + uri: &str, + action: &str, +) -> Result { + let response = + reqwest::blocking::get(uri).map_err(|error| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to fetch image `{uri}`: {error}"), + })?; + let status = response.status(); + if !status.is_success() { + return Err(PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to fetch image `{uri}`: HTTP {status}"), + }); + } + let content_type = response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(|value| value.split(';').next().unwrap_or(value).trim().to_string()); + let bytes = response + .bytes() + .map_err(|error| PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to read image `{uri}`: {error}"), + })?; + build_image_payload( + bytes.to_vec(), + infer_remote_image_filename(uri, content_type.as_deref()), + action, + ) +} + +fn infer_remote_image_filename(uri: &str, content_type: Option<&str>) -> String { + let path_name = reqwest::Url::parse(uri) + .ok() + .and_then(|url| { + url.path_segments() + .and_then(Iterator::last) + .map(str::to_owned) + }) + .filter(|segment| !segment.is_empty()); + match (path_name, content_type) { + (Some(path_name), _) if Path::new(&path_name).extension().is_some() => path_name, + (Some(path_name), Some(content_type)) => { + format!("{path_name}.{}", image_extension_from_mime(content_type)) + } + (Some(path_name), None) => path_name, + (None, Some(content_type)) => format!("image.{}", image_extension_from_mime(content_type)), + (None, None) => "image.png".to_string(), + } +} + +fn build_image_payload( + bytes: Vec, + filename: String, + action: &str, +) -> Result { + let image = image::load_from_memory(&bytes).map_err(|error| { + PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("failed to decode image bytes: {error}"), + } + })?; + let (width_px, height_px) = image.dimensions(); + let format = Path::new(&filename) + .extension() + .and_then(|extension| extension.to_str()) + .unwrap_or("png") + .to_uppercase(); + Ok(ImagePayload { + bytes, + format, + width_px, + height_px, + }) +} + +fn image_extension_from_mime(mime: &str) -> &'static str { + match mime { + "image/jpeg" => "jpg", + "image/gif" => "gif", + "image/webp" => "webp", + _ => "png", + } +} + +fn image_extension_from_format(format: image::ImageFormat) -> &'static str { + match format { + image::ImageFormat::Jpeg => "jpg", + image::ImageFormat::Gif => "gif", + image::ImageFormat::WebP => "webp", + image::ImageFormat::Bmp => "bmp", + image::ImageFormat::Tiff => "tiff", + _ => "png", + } +} + +fn index_out_of_range(action: &str, index: usize, len: usize) -> PresentationArtifactError { + PresentationArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("slide index {index} is out of range for {len} slides"), + } +} + +fn to_index(value: u32) -> Result { + usize::try_from(value).map_err(|_| PresentationArtifactError::InvalidArgs { + action: "insert_slide".to_string(), + message: "index does not fit in usize".to_string(), + }) +} + +fn resequence_z_order(slide: &mut PresentationSlide) { + for (index, element) in slide.elements.iter_mut().enumerate() { + element.set_z_order(index); + } +} diff --git a/codex-rs/artifact-presentation/src/tests.rs b/codex-rs/artifact-presentation/src/tests.rs new file mode 100644 index 0000000000..2ced6ad642 --- /dev/null +++ b/codex-rs/artifact-presentation/src/tests.rs @@ -0,0 +1,3512 @@ +use super::presentation_artifact::*; +use base64::Engine; +use pretty_assertions::assert_eq; +use std::io::Read; + +fn zip_entry_text( + path: &std::path::Path, + entry_name: &str, +) -> Result> { + let file = std::fs::File::open(path)?; + let mut archive = zip::ZipArchive::new(file)?; + let mut entry = archive.by_name(entry_name)?; + let mut text = String::new(); + entry.read_to_string(&mut text)?; + Ok(text) +} + +fn zip_entry_names(path: &std::path::Path) -> Result, Box> { + let file = std::fs::File::open(path)?; + let archive = zip::ZipArchive::new(file)?; + Ok(archive.file_names().map(str::to_owned).collect()) +} + +fn parse_ndjson_lines(ndjson: &str) -> Result, serde_json::Error> { + ndjson + .lines() + .filter(|line| !line.is_empty()) + .map(serde_json::from_str) + .collect() +} + +#[test] +fn manager_can_create_add_text_and_export() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let create_response = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Demo" }), + }, + temp_dir.path(), + )?; + let artifact_id = create_response.artifact_id; + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + + let add_text = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "hello", + "position": { "left": 40, "top": 40, "width": 200, "height": 80 } + }), + }, + temp_dir.path(), + )?; + assert_eq!( + add_text + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(1) + ); + + let export_path = temp_dir.path().join("deck.pptx"); + let export = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + assert_eq!(export.exported_paths.len(), 1); + assert!(export.exported_paths[0].exists()); + Ok(()) +} + +#[test] +fn manager_can_import_exported_presentation() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Roundtrip" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id.clone(); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "add_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "geometry": "rectangle", + "position": { "left": 24, "top": 24, "width": 180, "height": 120 }, + "text": "shape" + }), + }, + temp_dir.path(), + )?; + let export_path = temp_dir.path().join("roundtrip.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + + let imported = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "import_pptx".to_string(), + args: serde_json::json!({ "path": "roundtrip.pptx" }), + }, + temp_dir.path(), + )?; + assert_eq!( + imported + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(1) + ); + Ok(()) +} + +#[test] +fn custom_slide_size_is_written_to_exported_pptx() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ + "name": "Custom Size", + "slide_size": { "width": 960, "height": 540 } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let export_path = temp_dir.path().join("custom-size.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + + let presentation_xml = zip_entry_text( + &temp_dir.path().join("custom-size.pptx"), + "ppt/presentation.xml", + )?; + assert!(presentation_xml.contains(r#"cx="12192000" cy="6858000""#)); + assert!(presentation_xml.contains(r#"p:notesSz cx="6858000" cy="12192000""#)); + Ok(()) +} + +#[test] +fn exported_images_are_real_pictures_with_media_parts() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let source_path = temp_dir.path().join("source.png"); + image::RgbaImage::from_pixel(24, 16, image::Rgba([0x20, 0x90, 0xD0, 0xFF])) + .save(&source_path)?; + + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Image Export" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "add_image".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "path": "source.png", + "position": { "left": 36, "top": 48, "width": 144, "height": 96 }, + "rotation": 15, + "flip_horizontal": true, + "alt": "Company logo" + }), + }, + temp_dir.path(), + )?; + + let export_path = temp_dir.path().join("images.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + + let pptx_path = temp_dir.path().join("images.pptx"); + let slide_xml = zip_entry_text(&pptx_path, "ppt/slides/slide1.xml")?; + let rels_xml = zip_entry_text(&pptx_path, "ppt/slides/_rels/slide1.xml.rels")?; + let content_types_xml = zip_entry_text(&pptx_path, "[Content_Types].xml")?; + let entry_names = zip_entry_names(&pptx_path)?; + + assert!(slide_xml.contains("")); + assert!(slide_xml.contains(r#"descr="Company logo""#)); + assert!(slide_xml.contains(r#"r:embed="rIdImage1""#)); + assert!(slide_xml.contains(r#""#)); + assert!(!slide_xml.contains("Image Placeholder:")); + assert!(rels_xml.contains("relationships/image")); + assert!(rels_xml.contains(r#"Target="../media/image1.png""#)); + assert!(content_types_xml.contains(r#"Extension="png" ContentType="image/png""#)); + assert!(entry_names.contains(&"ppt/media/image1.png".to_string())); + Ok(()) +} + +#[test] +fn tool_request_accepts_sequential_actions() -> Result<(), Box> { + let request: PresentationArtifactToolRequest = serde_json::from_value(serde_json::json!({ + "actions": [ + { + "action": "create", + "args": { "name": "Batch Deck" } + }, + { + "action": "export_pptx", + "args": { "path": "deck.pptx" } + } + ] + }))?; + + let execution = request.into_execution_request()?; + assert_eq!(execution.artifact_id, None); + assert_eq!(execution.requests.len(), 2); + assert_eq!(execution.requests[0].action, "create"); + assert_eq!(execution.requests[1].action, "export_pptx"); + Ok(()) +} + +#[test] +fn manager_can_execute_sequential_actions() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let response = manager.execute_requests( + PresentationArtifactExecutionRequest { + artifact_id: None, + requests: vec![ + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Batch Deck" }), + }, + PresentationArtifactRequest { + artifact_id: None, + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + PresentationArtifactRequest { + artifact_id: None, + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "hello", + "position": { "left": 40, "top": 40, "width": 200, "height": 80 } + }), + }, + ], + }, + temp_dir.path(), + )?; + + assert_eq!(response.action, "batch"); + assert_eq!( + response.executed_actions, + Some(vec![ + "create".to_string(), + "add_slide".to_string(), + "add_text_shape".to_string(), + ]) + ); + assert_eq!( + response + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(1) + ); + assert!( + response + .summary + .contains("Executed 3 actions sequentially.") + ); + Ok(()) +} + +#[test] +fn imported_pptx_surfaces_image_elements() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let source_path = temp_dir.path().join("import-source.png"); + image::RgbaImage::from_pixel(20, 20, image::Rgba([0xD0, 0x60, 0x20, 0xFF])) + .save(&source_path)?; + + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Image Import" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "add_image".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "path": "import-source.png", + "position": { "left": 40, "top": 52, "width": 120, "height": 120 }, + "crop": { "left": 0.1, "top": 0.0, "right": 0.05, "bottom": 0.0 }, + "rotation": -10, + "flip_horizontal": true, + "flip_vertical": true, + "lock_aspect_ratio": true, + "alt": "Imported logo" + }), + }, + temp_dir.path(), + )?; + let export_path = temp_dir.path().join("image-import-roundtrip.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + + let imported = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "import_pptx".to_string(), + args: serde_json::json!({ "path": "image-import-roundtrip.pptx" }), + }, + temp_dir.path(), + )?; + assert_eq!( + imported + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.element_types.clone()), + Some(vec!["image".to_string()]) + ); + let image_anchor = imported + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .map(|id| format!("im/{id}")) + .expect("image anchor"); + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported.artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": image_anchor }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("alt")) + .and_then(serde_json::Value::as_str), + Some("Imported logo") + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("rotation")) + .and_then(serde_json::Value::as_i64), + Some(-10) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("flipHorizontal")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("flipVertical")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("lockAspectRatio")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("crop")) + .and_then(|crop| crop.get("left")) + .and_then(serde_json::Value::as_f64), + Some(0.1) + ); + Ok(()) +} + +#[test] +fn image_fit_contain_preserves_aspect_ratio() { + let image = ImageElement { + element_id: "element_1".to_string(), + frame: Rect { + left: 10, + top: 10, + width: 200, + height: 200, + }, + payload: Some(ImagePayload { + bytes: Vec::new(), + format: "PNG".to_string(), + width_px: 400, + height_px: 200, + }), + fit_mode: ImageFitMode::Contain, + crop: None, + rotation_degrees: None, + flip_horizontal: false, + flip_vertical: false, + lock_aspect_ratio: true, + alt_text: None, + prompt: None, + is_placeholder: false, + placeholder: None, + z_order: 0, + }; + + let (left, top, width, height, crop) = fit_image(&image); + assert_eq!((left, top, width, height), (10, 60, 200, 100)); + assert_eq!(crop, None); +} + +#[test] +fn preview_image_writer_supports_jpeg_scale_and_svg() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let source_path = temp_dir.path().join("preview.png"); + image::RgbaImage::from_pixel(80, 40, image::Rgba([0x22, 0x66, 0xAA, 0xFF])) + .save(&source_path)?; + let target_path = temp_dir.path().join("preview.jpg"); + write_preview_image( + &source_path, + &target_path, + PreviewOutputFormat::Jpeg, + 0.5, + 82, + "test", + )?; + let rendered = image::open(&target_path)?; + assert_eq!((rendered.width(), rendered.height()), (40, 20)); + assert_eq!( + image::ImageFormat::from_path(&target_path)?, + image::ImageFormat::Jpeg + ); + assert!(!source_path.exists()); + + let svg_source_path = temp_dir.path().join("preview-svg.png"); + image::RgbaImage::from_pixel(32, 16, image::Rgba([0x55, 0xAA, 0x44, 0xFF])) + .save(&svg_source_path)?; + let svg_target_path = temp_dir.path().join("preview.svg"); + write_preview_image( + &svg_source_path, + &svg_target_path, + PreviewOutputFormat::Svg, + 0.5, + 90, + "test", + )?; + let svg = std::fs::read_to_string(&svg_target_path)?; + assert!(svg.contains(r#" Result<(), Box> { + let mut image_bytes = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 16, + 8, + image::Rgba([0x11, 0x88, 0xCC, 0xFF]), + )) + .write_to(&mut image_bytes, image::ImageFormat::Png)?; + let png = image_bytes.into_inner(); + + let server = tiny_http::Server::http("127.0.0.1:0").expect("server"); + let port = server.server_addr().to_ip().expect("ip addr").port(); + let server_thread = std::thread::spawn(move || { + for request in server.incoming_requests().take(2) { + let response = tiny_http::Response::from_data(png.clone()).with_header( + tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"image/png"[..]) + .expect("header"), + ); + request.respond(response).expect("respond"); + } + }); + + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Remote Images" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let remote_uri = format!("http://127.0.0.1:{port}/image.png"); + let added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_image".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "uri": remote_uri, + "position": { "left": 32, "top": 48, "width": 120, "height": 60 } + }), + }, + temp_dir.path(), + )?; + let element_id = added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("image id"); + assert_eq!( + added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.element_types.clone()), + Some(vec!["image".to_string()]) + ); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "replace_image".to_string(), + args: serde_json::json!({ + "element_id": format!("im/{element_id}"), + "uri": format!("http://127.0.0.1:{port}/updated.png"), + "fit": "contain" + }), + }, + temp_dir.path(), + )?; + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "inspect".to_string(), + args: serde_json::json!({ "kind": "image" }), + }, + temp_dir.path(), + )?; + assert!( + inspect + .inspect_ndjson + .expect("image inspect") + .contains("\"fit\":\"Contain\"") + ); + server_thread.join().expect("server thread"); + Ok(()) +} + +#[test] +fn image_blobs_can_add_images() -> Result<(), Box> { + let mut image_bytes = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 10, + 6, + image::Rgba([0xAA, 0x55, 0x22, 0xFF]), + )) + .write_to(&mut image_bytes, image::ImageFormat::Png)?; + let blob = base64::engine::general_purpose::STANDARD.encode(image_bytes.into_inner()); + + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Blob Images" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_image".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "blob": blob, + "position": { "left": 32, "top": 48, "width": 100, "height": 60 } + }), + }, + temp_dir.path(), + )?; + let image_id = added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("image id"); + let proto = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "to_proto".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!( + proto + .proto_json + .as_ref() + .and_then(|proto| proto.get("slides")) + .and_then(serde_json::Value::as_array) + .and_then(|slides| slides.first()) + .and_then(|slide| slide.get("elements")) + .and_then(serde_json::Value::as_array) + .and_then(|elements| elements.iter().find(|element| { + element.get("elementId").and_then(serde_json::Value::as_str) + == Some(image_id.as_str()) + })) + .and_then(|record| record.get("payload")) + .and_then(|payload| payload.get("format")) + .and_then(serde_json::Value::as_str), + Some("PNG") + ); + Ok(()) +} + +#[test] +fn active_slide_can_be_set_and_tracks_reorders() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Active Slide" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + for _ in 0..3 { + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + } + let set_active = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_active_slide".to_string(), + args: serde_json::json!({ "slide_index": 2 }), + }, + temp_dir.path(), + )?; + assert_eq!(set_active.active_slide_index, Some(2)); + assert_eq!( + set_active.slide_list.as_ref().map(|slides| slides + .iter() + .map(|slide| slide.is_active) + .collect::>()), + Some(vec![false, false, true]) + ); + + let moved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "move_slide".to_string(), + args: serde_json::json!({ "from_index": 2, "to_index": 0 }), + }, + temp_dir.path(), + )?; + let summary = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_summary".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!(summary.active_slide_index, Some(0)); + assert_eq!( + summary.slide_list.as_ref().map(|slides| slides + .iter() + .map(|slide| slide.is_active) + .collect::>()), + Some(vec![true, false, false]) + ); + + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({ "kind": "deck,slide" }), + }, + temp_dir.path(), + )?; + let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); + assert!(inspect_ndjson.contains("\"activeSlideIndex\":0")); + assert!(inspect_ndjson.contains("\"isActive\":true")); + + let active_slide_id = moved + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.slide_id.clone()) + .expect("active slide id"); + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sl/{active_slide_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("isActive")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + + let deleted = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "delete_slide".to_string(), + args: serde_json::json!({ "slide_index": 0 }), + }, + temp_dir.path(), + )?; + assert_eq!( + deleted + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(2) + ); + let after_delete = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(deleted.artifact_id), + action: "list_slides".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!(after_delete.active_slide_index, Some(0)); + assert_eq!( + after_delete.slide_list.as_ref().map(|slides| slides + .iter() + .map(|slide| slide.is_active) + .collect::>()), + Some(vec![true, false]) + ); + Ok(()) +} + +#[test] +fn text_replace_and_insert_helpers_update_text_elements() -> Result<(), Box> +{ + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Text Helpers" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Revenue up 24%", + "position": { "left": 24, "top": 24, "width": 240, "height": 80 } + }), + }, + temp_dir.path(), + )?; + let element_id = added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("text id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "replace_text".to_string(), + args: serde_json::json!({ + "element_id": format!("sh/{element_id}"), + "search": "24%", + "replace": "31%" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "insert_text_after".to_string(), + args: serde_json::json!({ + "element_id": format!("sh/{element_id}"), + "after": "Revenue", + "insert": " QoQ" + }), + }, + temp_dir.path(), + )?; + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{element_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("text")) + .and_then(serde_json::Value::as_str), + Some("Revenue QoQ up 31%") + ); + Ok(()) +} + +#[test] +fn hyperlinks_are_inspectable_and_exported() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Hyperlinks" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + for _ in 0..2 { + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + } + + let text = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Open roadmap", + "position": { "left": 24, "top": 24, "width": 220, "height": 60 } + }), + }, + temp_dir.path(), + )?; + let text_id = text + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("text id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_hyperlink".to_string(), + args: serde_json::json!({ + "element_id": format!("sh/{text_id}"), + "link_type": "url", + "url": "https://example.com/roadmap", + "tooltip": "Roadmap", + "highlight_click": false + }), + }, + temp_dir.path(), + )?; + + let shape = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "geometry": "rounded_rectangle", + "position": { "left": 24, "top": 120, "width": 220, "height": 72 }, + "text": "Jump to appendix" + }), + }, + temp_dir.path(), + )?; + let shape_id = shape + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("shape id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_hyperlink".to_string(), + args: serde_json::json!({ + "element_id": format!("sh/{shape_id}"), + "link_type": "slide", + "slide_index": 1, + "tooltip": "Appendix" + }), + }, + temp_dir.path(), + )?; + + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({ "kind": "textbox,shape" }), + }, + temp_dir.path(), + )?; + let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); + assert!(inspect_ndjson.contains("\"type\":\"url\"")); + assert!(inspect_ndjson.contains("\"url\":\"https://example.com/roadmap\"")); + assert!(inspect_ndjson.contains("\"type\":\"slide\"")); + assert!(inspect_ndjson.contains("\"slideIndex\":1")); + + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{text_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("hyperlink")) + .and_then(|hyperlink| hyperlink.get("url")) + .and_then(serde_json::Value::as_str), + Some("https://example.com/roadmap") + ); + + let export_path = temp_dir.path().join("hyperlinks.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + let slide_xml = zip_entry_text( + &temp_dir.path().join("hyperlinks.pptx"), + "ppt/slides/slide1.xml", + )?; + let rels_xml = zip_entry_text( + &temp_dir.path().join("hyperlinks.pptx"), + "ppt/slides/_rels/slide1.xml.rels", + )?; + assert!(slide_xml.contains("hlinkClick")); + assert!(rels_xml.contains("https://example.com/roadmap")); + assert!(rels_xml.contains("slide2.xml")); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_hyperlink".to_string(), + args: serde_json::json!({ + "element_id": format!("sh/{text_id}"), + "clear": true + }), + }, + temp_dir.path(), + )?; + let cleared = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{text_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + cleared + .resolved_record + .as_ref() + .and_then(|record| record.get("hyperlink")), + None + ); + Ok(()) +} + +#[test] +fn manager_supports_layout_theme_notes_and_inspect() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ + "name": "Deck", + "theme": { + "color_scheme": { + "accent1": "#123456", + "bg1": "#FFFFFF", + "tx1": "#111111" + }, + "major_font": "Aptos" + } + }), + }, + temp_dir.path(), + )?; + assert_eq!( + created + .theme + .as_ref() + .map(|theme| theme.hex_color_map.clone()), + Some( + [ + ("accent1".to_string(), "123456".to_string()), + ("bg1".to_string(), "FFFFFF".to_string()), + ("tx1".to_string(), "111111".to_string()), + ] + .into_iter() + .collect() + ) + ); + let artifact_id = created.artifact_id.clone(); + + let master_layouts = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_layout".to_string(), + args: serde_json::json!({ "name": "Brand Master", "kind": "master" }), + }, + temp_dir.path(), + )?; + assert_eq!(master_layouts.layout_list.as_ref().map(Vec::len), Some(1)); + let master_id = master_layouts.layout_list.unwrap()[0].layout_id.clone(); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_layout_placeholder".to_string(), + args: serde_json::json!({ + "layout_id": master_id, + "name": "title", + "placeholder_type": "title", + "text": "Placeholder title", + "position": { "left": 48, "top": 48, "width": 500, "height": 60 } + }), + }, + temp_dir.path(), + )?; + + let child_layouts = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_layout".to_string(), + args: serde_json::json!({ + "name": "Title Slide", + "kind": "layout", + "parent_layout_id": master_id + }), + }, + temp_dir.path(), + )?; + assert_eq!(child_layouts.layout_list.as_ref().map(Vec::len), Some(2)); + let layout_id = child_layouts + .layout_list + .as_ref() + .and_then(|layouts| layouts.iter().find(|layout| layout.kind == "layout")) + .map(|layout| layout.layout_id.clone()) + .expect("child layout id"); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_layout_placeholder".to_string(), + args: serde_json::json!({ + "layout_id": "Title Slide", + "name": "subtitle", + "placeholder_type": "subtitle", + "text": "Placeholder subtitle", + "position": { "left": 48, "top": 128, "width": 500, "height": 48 } + }), + }, + temp_dir.path(), + )?; + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_layout_placeholder".to_string(), + args: serde_json::json!({ + "layout_id": "title slide", + "name": "hero-image", + "placeholder_type": "picture", + "text": "Add cover image", + "position": { "left": 420, "top": 40, "width": 180, "height": 120 } + }), + }, + temp_dir.path(), + )?; + + let added_slide = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({ "layout": layout_id }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_notes".to_string(), + args: serde_json::json!({ "slide_index": 0, "text": "Speaker notes" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "append_notes".to_string(), + args: serde_json::json!({ "slide_index": 0, "text": "More context" }), + }, + temp_dir.path(), + )?; + let layout_placeholders = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "list_layout_placeholders".to_string(), + args: serde_json::json!({ "layout_id": layout_id }), + }, + temp_dir.path(), + )?; + assert_eq!( + layout_placeholders.placeholder_list.as_ref().map(Vec::len), + Some(3) + ); + + let slide_placeholders = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "list_slide_placeholders".to_string(), + args: serde_json::json!({ "slide_index": 0 }), + }, + temp_dir.path(), + )?; + assert_eq!( + slide_placeholders.placeholder_list.as_ref().map(Vec::len), + Some(3) + ); + assert_eq!( + slide_placeholders + .placeholder_list + .as_ref() + .and_then(|placeholders| placeholders + .iter() + .find(|placeholder| placeholder.placeholder_type == "picture") + .map(|placeholder| ( + placeholder.geometry.clone(), + placeholder.text_preview.clone() + ))), + Some(( + Some("Image".to_string()), + Some("Add cover image".to_string()) + )) + ); + let image_placeholder_id = added_slide + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("image placeholder id"); + + let resolved_layout = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("ly/{layout_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_layout + .resolved_record + .as_ref() + .and_then(|record| record.get("kind")) + .and_then(serde_json::Value::as_str), + Some("layout") + ); + + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({ "kind": "deck,slide,textbox,image,notes,layoutList" }), + }, + temp_dir.path(), + )?; + let inspect_ndjson = inspect.inspect_ndjson.expect("inspect output"); + assert!(inspect_ndjson.contains("\"kind\":\"layout\"")); + assert!(inspect_ndjson.contains("\"kind\":\"notes\"")); + assert!(inspect_ndjson.contains("\"placeholder\":\"title\"")); + assert!(inspect_ndjson.contains("\"placeholder\":\"picture\"")); + assert!(inspect_ndjson.contains("\"kind\":\"image\"")); + + let resolved_image_placeholder = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("im/{image_placeholder_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_image_placeholder + .resolved_record + .as_ref() + .and_then(|record| record.get("isPlaceholder")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + resolved_image_placeholder + .resolved_record + .as_ref() + .and_then(|record| record.get("placeholder")) + .and_then(serde_json::Value::as_str), + Some("picture") + ); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_slide_layout".to_string(), + args: serde_json::json!({ "slide_index": 1, "layout_id": "title slide" }), + }, + temp_dir.path(), + )?; + let inherited_placeholders = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "list_slide_placeholders".to_string(), + args: serde_json::json!({ "slide_index": 1 }), + }, + temp_dir.path(), + )?; + assert_eq!( + inherited_placeholders + .placeholder_list + .as_ref() + .map(Vec::len), + Some(3) + ); + assert_eq!( + inherited_placeholders + .placeholder_list + .as_ref() + .and_then(|placeholders| placeholders + .iter() + .find(|placeholder| placeholder.placeholder_type == "title") + .map(|placeholder| placeholder.name.clone())), + Some("title".to_string()) + ); + assert_eq!( + inherited_placeholders + .placeholder_list + .as_ref() + .and_then(|placeholders| placeholders + .iter() + .find(|placeholder| placeholder.placeholder_type == "picture") + .map(|placeholder| placeholder.geometry.clone())), + Some(Some("Image".to_string())) + ); + + let truncated = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id), + action: "inspect".to_string(), + args: serde_json::json!({ + "kind": "deck,slide,textbox,image,notes,layoutList", + "max_chars": 250 + }), + }, + temp_dir.path(), + )?; + assert!( + truncated + .inspect_ndjson + .expect("truncated inspect") + .contains("\"noticeType\":\"truncation\"") + ); + Ok(()) +} + +#[test] +fn named_text_styles_apply_to_text_and_tables() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ + "name": "Styles", + "theme": { + "color_scheme": { + "tx1": "#222222" + }, + "major_font": "Aptos Display", + "minor_font": "Aptos" + } + }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + let described = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "describe_styles".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!( + described + .resolved_record + .as_ref() + .and_then(|record| record.get("styles")) + .and_then(serde_json::Value::as_array) + .map(Vec::len), + Some(5) + ); + let title_style = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_style".to_string(), + args: serde_json::json!({ "name": "title" }), + }, + temp_dir.path(), + )?; + assert_eq!( + title_style.resolved_record, + Some(serde_json::json!({ + "kind": "textStyle", + "id": "st/title", + "name": "title", + "builtIn": true, + "style": { + "styleName": "title", + "fontSize": 28, + "fontFamily": "Aptos Display", + "color": "222222", + "alignment": "left", + "bold": true, + "italic": false, + "underline": false + } + })) + ); + let custom_style = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_style".to_string(), + args: serde_json::json!({ + "name": "callout", + "font_size": 18, + "color": "#336699", + "italic": true, + "underline": true + }), + }, + temp_dir.path(), + )?; + assert_eq!( + custom_style.resolved_record, + Some(serde_json::json!({ + "kind": "textStyle", + "id": "st/callout", + "name": "callout", + "builtIn": false, + "style": { + "styleName": "callout", + "fontSize": 18, + "fontFamily": serde_json::Value::Null, + "color": "336699", + "alignment": serde_json::Value::Null, + "bold": false, + "italic": true, + "underline": true + } + })) + ); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let text_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Styled title", + "position": { "left": 40, "top": 40, "width": 220, "height": 50 }, + "style": "title", + "underline": true + }), + }, + temp_dir.path(), + )?; + let text_id = text_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("text id"); + let table_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_table".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 40, "top": 120, "width": 180, "height": 80 }, + "rows": [["A"]], + }), + }, + temp_dir.path(), + )?; + let table_id = table_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("table id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_table_cell".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "row": 0, + "column": 0, + "value": "Styled cell", + "styling": { + "style": "callout" + } + }), + }, + temp_dir.path(), + )?; + + let resolved_text = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{text_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_text + .resolved_record + .as_ref() + .and_then(|record| record.get("textStyle")) + .cloned(), + Some(serde_json::json!({ + "styleName": "title", + "fontSize": 28, + "fontFamily": "Aptos Display", + "color": "222222", + "alignment": "left", + "bold": true, + "italic": false, + "underline": true + })) + ); + let resolved_table = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("tb/{table_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_table + .resolved_record + .as_ref() + .and_then(|record| record.get("cellTextStyles")) + .cloned(), + Some(serde_json::json!([ + [ + { + "styleName": "callout", + "fontSize": 18, + "fontFamily": serde_json::Value::Null, + "color": "336699", + "alignment": serde_json::Value::Null, + "bold": false, + "italic": true, + "underline": true + } + ] + ])) + ); + Ok(()) +} + +#[test] +fn layout_names_resolve_in_slide_actions_and_insert_defaults_after_active_slide() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Layouts by Name" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + let layout_created = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_layout".to_string(), + args: serde_json::json!({ "name": "Title Slide" }), + }, + temp_dir.path(), + )?; + let layout_id = layout_created + .layout_list + .as_ref() + .and_then(|layouts| layouts.first()) + .map(|layout| layout.layout_id.clone()) + .expect("layout id"); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_layout_placeholder".to_string(), + args: serde_json::json!({ + "layout_id": layout_id, + "name": "title", + "placeholder_type": "title", + "text": "Placeholder title" + }), + }, + temp_dir.path(), + )?; + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({ "layout": "Title Slide" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_active_slide".to_string(), + args: serde_json::json!({ "slide_index": 0 }), + }, + temp_dir.path(), + )?; + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "insert_slide".to_string(), + args: serde_json::json!({ "layout": "title slide" }), + }, + temp_dir.path(), + )?; + let inserted = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "list_slides".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!( + inserted.slide_list.as_ref().map(|slides| slides + .iter() + .map(|slide| slide.layout_id.clone()) + .collect::>()), + Some(vec![ + Some("layout_1".to_string()), + Some("layout_1".to_string()), + None + ]) + ); + assert_eq!( + inserted.slide_list.as_ref().map(|slides| slides + .iter() + .map(|slide| slide.is_active) + .collect::>()), + Some(vec![true, false, false]) + ); + + let placeholders = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "list_layout_placeholders".to_string(), + args: serde_json::json!({ "layout_id": "TITLE SLIDE" }), + }, + temp_dir.path(), + )?; + assert_eq!( + placeholders.placeholder_list.as_ref().map(|entries| entries + .iter() + .map(|entry| entry.name.clone()) + .collect::>()), + Some(vec!["title".to_string()]) + ); + + let child_layout = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(placeholders.artifact_id), + action: "create_layout".to_string(), + args: serde_json::json!({ + "name": "Child Layout", + "parent_layout_id": "title slide" + }), + }, + temp_dir.path(), + )?; + assert_eq!( + child_layout.layout_list.as_ref().map(|layouts| layouts + .iter() + .find(|layout| layout.name == "Child Layout") + .and_then(|layout| layout.parent_layout_id.clone())), + Some(Some("layout_1".to_string())) + ); + Ok(()) +} + +#[test] +fn inspect_supports_filters_target_windows_and_shape_text_metadata() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Inspect Filters" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + + let first_text = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "First KPI", + "position": { "left": 10, "top": 10, "width": 120, "height": 40 } + }), + }, + temp_dir.path(), + )?; + let second_text = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Second KPI", + "position": { "left": 10, "top": 60, "width": 120, "height": 40 } + }), + }, + temp_dir.path(), + )?; + let third_text = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Third KPI", + "position": { "left": 10, "top": 110, "width": 120, "height": 40 } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_notes".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Speaker note" + }), + }, + temp_dir.path(), + )?; + let shape = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "geometry": "rectangle", + "position": { "left": 180, "top": 10, "width": 180, "height": 90 }, + "text": "Detailed\nShape KPI" + }), + }, + temp_dir.path(), + )?; + + let middle_text_id = second_text + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.get(1)) + .cloned() + .expect("middle text id"); + let first_text_id = first_text + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("first text id"); + let third_text_id = third_text + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.get(2)) + .cloned() + .expect("third text id"); + let shape_id = shape + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.get(3)) + .cloned() + .expect("shape id"); + let slide_id = shape + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.slide_id.clone()) + .expect("slide id"); + + let filtered = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({ + "include": "shape,notes", + "exclude": "notes", + "search": "Detailed" + }), + }, + temp_dir.path(), + )?; + let filtered_records = parse_ndjson_lines( + filtered + .inspect_ndjson + .as_deref() + .expect("filtered inspect"), + )?; + assert_eq!(filtered_records.len(), 1); + assert_eq!( + filtered_records[0], + serde_json::json!({ + "kind": "shape", + "id": format!("sh/{shape_id}"), + "slide": 1, + "geometry": "Rectangle", + "text": "Detailed\nShape KPI", + "textStyle": { + "styleName": serde_json::Value::Null, + "fontSize": serde_json::Value::Null, + "fontFamily": serde_json::Value::Null, + "color": serde_json::Value::Null, + "alignment": serde_json::Value::Null, + "bold": false, + "italic": false, + "underline": false + }, + "richText": { + "layout": { + "insets": serde_json::Value::Null, + "wrap": serde_json::Value::Null, + "autoFit": serde_json::Value::Null, + "verticalAlignment": serde_json::Value::Null + }, + "ranges": [] + }, + "rotation": serde_json::Value::Null, + "flipHorizontal": false, + "flipVertical": false, + "bbox": [180, 10, 180, 90], + "bboxUnit": "points", + "textPreview": "Detailed | Shape KPI", + "textChars": 18, + "textLines": 2 + }) + ); + + let targeted = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({ + "include": "textbox", + "target": { + "id": format!("sh/{middle_text_id}"), + "before_lines": 1, + "after_lines": 1 + } + }), + }, + temp_dir.path(), + )?; + let targeted_records = parse_ndjson_lines( + targeted + .inspect_ndjson + .as_deref() + .expect("targeted inspect"), + )?; + assert_eq!( + targeted_records + .iter() + .filter_map(|record| record.get("id").and_then(serde_json::Value::as_str)) + .map(str::to_owned) + .collect::>(), + vec![ + format!("sh/{first_text_id}"), + format!("sh/{middle_text_id}"), + format!("sh/{third_text_id}") + ] + ); + + let missing_target = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "inspect".to_string(), + args: serde_json::json!({ + "include": "textbox", + "target": { + "id": "sh/missing", + "before_lines": 1, + "after_lines": 1 + } + }), + }, + temp_dir.path(), + )?; + let missing_target_records = parse_ndjson_lines( + missing_target + .inspect_ndjson + .as_deref() + .expect("missing target inspect"), + )?; + assert_eq!( + missing_target_records, + vec![serde_json::json!({ + "kind": "notice", + "noticeType": "targetNotFound", + "target": { + "id": "sh/missing", + "beforeLines": 1, + "afterLines": 1 + }, + "message": "No inspect records matched target `sh/missing`." + })] + ); + + let resolved_shape = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(missing_target.artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{shape_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_shape + .resolved_record + .as_ref() + .and_then(|record| record.get("textPreview")) + .and_then(serde_json::Value::as_str), + Some("Detailed | Shape KPI") + ); + assert_eq!( + resolved_shape + .resolved_record + .as_ref() + .and_then(|record| record.get("textChars")) + .and_then(serde_json::Value::as_u64), + Some(18) + ); + assert_eq!( + resolved_shape + .resolved_record + .as_ref() + .and_then(|record| record.get("textLines")) + .and_then(serde_json::Value::as_u64), + Some(2) + ); + + let resolved_notes = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(missing_target.artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("nt/{slide_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_notes + .resolved_record + .as_ref() + .and_then(|record| record.get("textPreview")) + .and_then(serde_json::Value::as_str), + Some("Speaker note") + ); + assert_eq!( + resolved_notes + .resolved_record + .as_ref() + .and_then(|record| record.get("textChars")) + .and_then(serde_json::Value::as_u64), + Some(12) + ); + assert_eq!( + resolved_notes + .resolved_record + .as_ref() + .and_then(|record| record.get("textLines")) + .and_then(serde_json::Value::as_u64), + Some(1) + ); + Ok(()) +} + +#[test] +fn notes_visibility_controls_exported_notes() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Notes" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({ "notes": "Hidden notes" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_notes_visibility".to_string(), + args: serde_json::json!({ "slide_index": 0, "visible": false }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": "notes-hidden.pptx" }), + }, + temp_dir.path(), + )?; + + let imported = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "import_pptx".to_string(), + args: serde_json::json!({ "path": "notes-hidden.pptx" }), + }, + temp_dir.path(), + )?; + let summary = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported.artifact_id), + action: "list_slides".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!( + summary + .slide_list + .as_ref() + .and_then(|slides| slides.first()) + .and_then(|slide| slide.notes.clone()), + None + ); + Ok(()) +} + +#[test] +fn image_placeholders_and_anchor_updates_work() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Images" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let placeholder = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_image".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 24, "top": 24, "width": 200, "height": 120 }, + "fit": "contain", + "prompt": "Generate a hero illustration", + "alt": "Hero placeholder" + }), + }, + temp_dir.path(), + )?; + let image_anchor = placeholder + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .map(|id| format!("im/{id}")) + .expect("image anchor"); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_shape_style".to_string(), + args: serde_json::json!({ + "element_id": image_anchor, + "fit": "cover", + "crop": { "left": 0.1, "top": 0.0, "right": 0.1, "bottom": 0.0 }, + "rotation": 12, + "flip_horizontal": true, + "lock_aspect_ratio": true + }), + }, + temp_dir.path(), + )?; + + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": image_anchor }), + }, + temp_dir.path(), + )?; + let record = resolved.resolved_record.expect("resolved image"); + assert_eq!( + record.get("kind").and_then(serde_json::Value::as_str), + Some("image") + ); + assert_eq!( + record + .get("isPlaceholder") + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + record + .get("lockAspectRatio") + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + record.get("rotation").and_then(serde_json::Value::as_i64), + Some(12) + ); + assert_eq!( + record + .get("flipHorizontal") + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + record + .get("flipVertical") + .and_then(serde_json::Value::as_bool), + Some(false) + ); + Ok(()) +} + +#[test] +fn image_partial_resize_respects_lock_aspect_ratio() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Image Resize" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_image".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 10, "top": 10, "width": 200, "height": 100 }, + "prompt": "Placeholder image", + "lock_aspect_ratio": true + }), + }, + temp_dir.path(), + )?; + let image_anchor = added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .map(|id| format!("im/{id}")) + .expect("image anchor"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_shape_style".to_string(), + args: serde_json::json!({ + "element_id": image_anchor, + "position": { "width": 120 } + }), + }, + temp_dir.path(), + )?; + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": image_anchor }), + }, + temp_dir.path(), + )?; + let bbox = resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("bbox")) + .and_then(serde_json::Value::as_array) + .expect("bbox"); + assert_eq!(bbox[2].as_u64(), Some(120)); + assert_eq!(bbox[3].as_u64(), Some(60)); + Ok(()) +} + +#[test] +fn connectors_support_arrows_and_inspect() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Connectors" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_connector".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "connector_type": "elbow", + "start": { "left": 20, "top": 20 }, + "end": { "left": 180, "top": 160 }, + "line": { "color": "#ff0000", "width": 2, "style": "dash-dot" }, + "start_arrow": "none", + "end_arrow": "triangle", + "arrow_size": "large", + "label": "flow" + }), + }, + temp_dir.path(), + )?; + let connector_id = added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .map(|id| format!("cn/{id}")) + .expect("connector id"); + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": connector_id }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("kind")) + .and_then(serde_json::Value::as_str), + Some("connector") + ); + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "inspect".to_string(), + args: serde_json::json!({ "kind": "connector" }), + }, + temp_dir.path(), + )?; + assert!( + inspect + .inspect_ndjson + .expect("connector inspect") + .contains("\"kind\":\"connector\"") + ); + Ok(()) +} + +#[test] +fn shapes_support_stroke_dash_styles() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Shape Strokes" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let added_shape = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "geometry": "rectangle", + "position": { + "left": 24, + "top": 24, + "width": 180, + "height": 120, + "rotation": 15, + "flip_horizontal": true, + "flip_vertical": true + }, + "stroke": { "color": "#ff0000", "width": 2, "style": "dash-dot" } + }), + }, + temp_dir.path(), + )?; + let shape_id = added_shape + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("shape id"); + + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{shape_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("stroke")) + .and_then(|stroke| stroke.get("style")) + .and_then(serde_json::Value::as_str), + Some("dash-dot") + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("rotation")) + .and_then(serde_json::Value::as_i64), + Some(15) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("flipHorizontal")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("flipVertical")) + .and_then(serde_json::Value::as_bool), + Some(true) + ); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_shape_style".to_string(), + args: serde_json::json!({ + "element_id": format!("sh/{shape_id}"), + "position": { + "rotation": 30, + "flip_horizontal": false, + "flip_vertical": true + } + }), + }, + temp_dir.path(), + )?; + let updated = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("sh/{shape_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + updated + .resolved_record + .as_ref() + .and_then(|record| record.get("rotation")) + .and_then(serde_json::Value::as_i64), + Some(30) + ); + assert_eq!( + updated + .resolved_record + .as_ref() + .and_then(|record| record.get("flipHorizontal")) + .and_then(serde_json::Value::as_bool), + Some(false) + ); + + let export_path = temp_dir.path().join("shape-strokes.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + + let slide_xml = zip_entry_text( + &temp_dir.path().join("shape-strokes.pptx"), + "ppt/slides/slide1.xml", + )?; + assert!(slide_xml.contains(r#""#)); + assert!(slide_xml.contains(r#""#)); + Ok(()) +} + +#[test] +fn z_order_helpers_resequence_elements() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Z Order" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let first = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "A", + "position": { "left": 10, "top": 10, "width": 100, "height": 40 } + }), + }, + temp_dir.path(), + )?; + let second = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "B", + "position": { "left": 20, "top": 20, "width": 100, "height": 40 } + }), + }, + temp_dir.path(), + )?; + let first_id = first + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("first id"); + let second_id = second + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("second id"); + let sent_back = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "send_to_back".to_string(), + args: serde_json::json!({ "element_id": format!("sh/{second_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + sent_back + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.element_ids.clone()), + Some(vec![second_id.clone(), first_id.clone()]) + ); + let brought_front = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "bring_to_front".to_string(), + args: serde_json::json!({ "element_id": format!("sh/{second_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + brought_front + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.element_ids.clone()), + Some(vec![first_id, second_id]) + ); + Ok(()) +} + +#[test] +fn manager_supports_table_cell_updates_and_merges() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Tables" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let table = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_table".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 24, "top": 24, "width": 240, "height": 120 }, + "rows": [["A", "B"], ["C", "D"]], + "column_widths": [90, 150], + "row_heights": [40, 80], + "style": "TableStyleMedium9" + }), + }, + temp_dir.path(), + )?; + let table_id = table + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("table id"); + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_table_cell".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "row": 0, + "column": 1, + "value": "Updated", + "background_fill": "#eeeeee", + "alignment": "right", + "styling": { "bold": true } + }), + }, + temp_dir.path(), + )?; + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({ "kind": "table" }), + }, + temp_dir.path(), + )?; + assert!( + inspect + .inspect_ndjson + .expect("inspect") + .contains("\"kind\":\"table\"") + ); + let resolved = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": format!("tb/{table_id}") }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("columnWidths")) + .and_then(serde_json::Value::as_array) + .map(|widths| widths + .iter() + .filter_map(serde_json::Value::as_u64) + .collect::>()), + Some(vec![90, 150]) + ); + assert_eq!( + resolved + .resolved_record + .as_ref() + .and_then(|record| record.get("rowHeights")) + .and_then(serde_json::Value::as_array) + .map(|heights| heights + .iter() + .filter_map(serde_json::Value::as_u64) + .collect::>()), + Some(vec![40, 80]) + ); + + let merged = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "merge_table_cells".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "start_row": 0, + "end_row": 0, + "start_column": 0, + "end_column": 1 + }), + }, + temp_dir.path(), + )?; + assert_eq!( + merged + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(1) + ); + let export_path = temp_dir.path().join("tables.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(merged.artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + let slide_xml = zip_entry_text( + &temp_dir.path().join("tables.pptx"), + "ppt/slides/slide1.xml", + )?; + assert!( + slide_xml.contains(r#""#), + "{slide_xml}" + ); + assert!(slide_xml.contains(r#""#)); + assert!(slide_xml.contains(r#""#)); + assert!(slide_xml.contains(r#""#)); + Ok(()) +} + +#[test] +fn rich_text_comments_tables_and_charts_roundtrip_through_metadata() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Parity Roundtrip" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + + let text_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_text_shape".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "text": "Placeholder", + "position": { "left": 32, "top": 28, "width": 280, "height": 72 } + }), + }, + temp_dir.path(), + )?; + let text_id = text_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.first()) + .cloned() + .expect("text id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_rich_text".to_string(), + args: serde_json::json!({ + "element_id": text_id, + "text": [[ + { + "run": "Quarterly ", + "text_style": { "bold": true, "color": "#114488" } + }, + "update pipeline" + ]], + "text_layout": { + "wrap": "square", + "auto_fit": "shrinkText", + "vertical_alignment": "middle", + "insets": { "left": 6, "right": 6, "top": 4, "bottom": 4 } + } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "format_text_range".to_string(), + args: serde_json::json!({ + "element_id": text_id, + "query": "update", + "styling": { "italic": true }, + "link": { "uri": "https://example.com/update", "is_external": true } + }), + }, + temp_dir.path(), + )?; + + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_comment_author".to_string(), + args: serde_json::json!({ + "display_name": "Jamie Fox", + "initials": "JF", + "email": "jamie@example.com" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_comment_thread".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "element_id": text_id, + "query": "Quarterly", + "text": "Tighten this headline", + "position": { "x": 240, "y": 44 } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_comment_reply".to_string(), + args: serde_json::json!({ + "thread_id": "thread_1", + "text": "Applied to the slide draft." + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "toggle_comment_reaction".to_string(), + args: serde_json::json!({ + "thread_id": "thread_1", + "emoji": "eyes" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "resolve_comment_thread".to_string(), + args: serde_json::json!({ "thread_id": "thread_1" }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "reopen_comment_thread".to_string(), + args: serde_json::json!({ "thread_id": "thread_1" }), + }, + temp_dir.path(), + )?; + + let table_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_table".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 32, "top": 124, "width": 320, "height": 120 }, + "rows": [["Metric", "Value"], ["Status", "Beta"]], + "style": "TableStyleMedium2", + "style_options": { + "header_row": true, + "banded_rows": true, + "first_column": true + }, + "borders": { + "outside": { "color": "#222222", "width": 2 } + }, + "right_to_left": true + }), + }, + temp_dir.path(), + )?; + let table_id = table_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("table id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_table_style".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "style_options": { "last_column": true, "total_row": true }, + "borders": { + "inside": { "color": "#999999", "width": 1 } + } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "style_table_block".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "row": 1, + "column": 0, + "row_count": 1, + "column_count": 2, + "background_fill": "#FFF2CC", + "alignment": "center", + "styling": { "bold": true } + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "format_text_range".to_string(), + args: serde_json::json!({ + "element_id": table_id, + "row": 1, + "column": 1, + "query": "Beta", + "styling": { "italic": true, "color": "#AA0000" } + }), + }, + temp_dir.path(), + )?; + + let chart_added = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_chart".to_string(), + args: serde_json::json!({ + "slide_index": 0, + "position": { "left": 372, "top": 120, "width": 280, "height": 210 }, + "chart_type": "bar", + "categories": ["Q1", "Q2"], + "series": [{ + "name": "Revenue", + "values": [10.0, 12.0], + "fill": "#4472C4", + "stroke": { "color": "#1F4E79", "width": 2 }, + "marker": { "symbol": "circle", "size": 7 }, + "data_label_overrides": [{ + "idx": 1, + "text": "12M", + "position": "outsideEnd", + "fill": "#FFFFFF" + }] + }], + "title": "Revenue", + "style_index": 7, + "has_legend": true, + "legend_position": "right", + "legend_text_style": { "italic": true }, + "x_axis_title": "Quarter", + "y_axis_title": "USD", + "data_labels": { + "show_value": true, + "position": "outsideEnd", + "text_style": { "bold": true } + }, + "chart_fill": "#F8F8F8", + "plot_area_fill": "#FFFFFF" + }), + }, + temp_dir.path(), + )?; + let chart_id = chart_added + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .and_then(|slide| slide.element_ids.last()) + .cloned() + .expect("chart id"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "update_chart".to_string(), + args: serde_json::json!({ + "element_id": chart_id, + "title": "Revenue outlook", + "style_index": 12, + "legend_position": "bottom", + "y_axis_title": "USD (millions)" + }), + }, + temp_dir.path(), + )?; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_chart_series".to_string(), + args: serde_json::json!({ + "element_id": chart_id, + "name": "Target", + "values": [11.0, 13.0], + "fill": "#70AD47", + "marker": { "symbol": "diamond", "size": 6 } + }), + }, + temp_dir.path(), + )?; + + let export_path = temp_dir.path().join("parity-roundtrip.pptx"); + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "export_pptx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + let metadata = zip_entry_text( + &temp_dir.path().join("parity-roundtrip.pptx"), + "ppt/codex-document.json", + )?; + assert!(metadata.contains("\"thread_id\":\"thread_1\"")); + assert!(metadata.contains("\"style_index\":12")); + assert!(metadata.contains("\"right_to_left\":true")); + + let imported = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "import_pptx".to_string(), + args: serde_json::json!({ "path": "parity-roundtrip.pptx" }), + }, + temp_dir.path(), + )?; + let imported_artifact_id = imported.artifact_id; + + let proto = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id.clone()), + action: "to_proto".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let proto = proto.proto_json.expect("proto"); + let comments = proto["commentThreads"].as_array().expect("comments"); + assert_eq!(comments.len(), 1); + assert_eq!(comments[0]["status"], "active"); + assert_eq!(comments[0]["messages"].as_array().map(Vec::len), Some(2)); + assert_eq!( + comments[0]["messages"][1]["reactions"], + serde_json::json!(["eyes"]) + ); + + let elements = proto["slides"][0]["elements"].as_array().expect("elements"); + let text_record = elements + .iter() + .find(|element| element["elementId"] == text_id) + .expect("text record"); + assert_eq!(text_record["richText"]["layout"]["wrap"], "square"); + assert_eq!(text_record["richText"]["layout"]["autoFit"], "shrinkText"); + assert_eq!( + text_record["richText"]["layout"]["verticalAlignment"], + "middle" + ); + assert_eq!( + text_record["richText"]["ranges"].as_array().map(Vec::len), + Some(2) + ); + assert!( + text_record["richText"]["ranges"] + .as_array() + .expect("text ranges") + .iter() + .any(|range| range["text"] == "update") + ); + + let table_record = elements + .iter() + .find(|element| element["elementId"] == table_id) + .expect("table record"); + assert_eq!(table_record["styleOptions"]["headerRow"], true); + assert_eq!(table_record["styleOptions"]["lastColumn"], true); + assert_eq!(table_record["rightToLeft"], true); + assert_eq!(table_record["borders"]["outside"]["color"], "222222"); + assert_eq!( + table_record["rows"][1][1]["richText"]["ranges"] + .as_array() + .map(Vec::len), + Some(1) + ); + + let chart_record = elements + .iter() + .find(|element| element["elementId"] == chart_id) + .expect("chart record"); + assert_eq!(chart_record["styleIndex"], 12); + assert_eq!(chart_record["legend"]["position"], "bottom"); + assert_eq!(chart_record["series"].as_array().map(Vec::len), Some(2)); + assert_eq!(chart_record["series"][1]["name"], "Target"); + + let inspect = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id.clone()), + action: "inspect".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let inspect_ndjson = inspect.inspect_ndjson.expect("inspect"); + assert!(inspect_ndjson.contains("\"kind\":\"comment\"")); + assert!(inspect_ndjson.contains("\"kind\":\"textRange\"")); + assert!(inspect_ndjson.contains("\"chartType\":\"Bar\"")); + + let resolved_thread = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id.clone()), + action: "resolve".to_string(), + args: serde_json::json!({ "id": "th/thread_1" }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_thread + .resolved_record + .as_ref() + .and_then(|record| record.get("target")) + .and_then(|target| target.get("type")), + Some(&serde_json::json!("textRange")) + ); + + let resolved_range = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(imported_artifact_id), + action: "resolve".to_string(), + args: serde_json::json!({ "id": "tr/range_1" }), + }, + temp_dir.path(), + )?; + assert_eq!( + resolved_range + .resolved_record + .as_ref() + .and_then(|record| record.get("text")), + Some(&serde_json::json!("update")) + ); + Ok(()) +} + +#[test] +fn history_can_undo_and_redo_created_artifact() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "History" }), + }, + temp_dir.path(), + )?; + + let undone = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "undo".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!(undone.artifact_id, created.artifact_id); + assert!(undone.artifact_snapshot.is_none()); + assert!( + manager + .execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "get_summary".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + ) + .is_err() + ); + + let redone = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(created.artifact_id.clone()), + action: "redo".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!(redone.artifact_id, created.artifact_id); + assert_eq!( + redone + .artifact_snapshot + .as_ref() + .map(|snapshot| snapshot.slide_count), + Some(0) + ); + Ok(()) +} + +#[test] +fn proto_and_patch_actions_work_and_patch_history_is_atomic() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = PresentationArtifactManager::default(); + let created = manager.execute( + PresentationArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Proto Patch" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "add_slide".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + + let patch_ops = serde_json::json!([ + { + "action": "add_text_shape", + "args": { + "slide_index": 0, + "text": "Patch text", + "position": { "left": 40, "top": 60, "width": 180, "height": 50 } + } + }, + { + "action": "set_slide_background", + "args": { + "slide_index": 0, + "fill": "#ffeecc" + } + } + ]); + let recorded = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "record_patch".to_string(), + args: serde_json::json!({ "operations": patch_ops }), + }, + temp_dir.path(), + )?; + let expected_patch = serde_json::json!({ + "version": 1, + "artifactId": artifact_id, + "operations": [ + { + "action": "add_text_shape", + "args": { + "slide_index": 0, + "text": "Patch text", + "position": { "left": 40, "top": 60, "width": 180, "height": 50 } + } + }, + { + "action": "set_slide_background", + "args": { + "slide_index": 0, + "fill": "#ffeecc" + } + } + ] + }); + assert_eq!(recorded.patch.as_ref(), Some(&expected_patch)); + + let applied = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "apply_patch".to_string(), + args: serde_json::json!({ "patch": expected_patch }), + }, + temp_dir.path(), + )?; + let slide_snapshot = applied + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .cloned() + .expect("slide snapshot"); + let slide_id = slide_snapshot.slide_id.clone(); + let element_id = slide_snapshot + .element_ids + .first() + .cloned() + .expect("element id"); + + let proto = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "to_proto".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + let proto = proto.proto_json.expect("proto"); + assert_eq!(proto["kind"], "presentation"); + assert_eq!(proto["artifactId"], artifact_id); + assert_eq!(proto["activeSlideId"], slide_id); + assert_eq!(proto["commentAuthor"], serde_json::Value::Null); + assert_eq!(proto["commentThreads"], serde_json::json!([])); + assert_eq!(proto["masters"], serde_json::json!([])); + assert_eq!(proto["layouts"], serde_json::json!([])); + assert_eq!(proto["theme"]["hexColorMap"], serde_json::json!({})); + assert_eq!(proto["styles"].as_array().map(Vec::len), Some(5)); + assert_eq!(proto["slides"].as_array().map(Vec::len), Some(1)); + assert_eq!(proto["slides"][0]["slideId"], slide_id); + assert_eq!(proto["slides"][0]["backgroundFill"], "FFEECC"); + assert_eq!( + proto["slides"][0]["notes"]["richText"]["ranges"], + serde_json::json!([]) + ); + assert_eq!( + proto["slides"][0]["elements"].as_array().map(Vec::len), + Some(1) + ); + assert_eq!(proto["slides"][0]["elements"][0]["elementId"], element_id); + assert_eq!(proto["slides"][0]["elements"][0]["text"], "Patch text"); + assert_eq!( + proto["slides"][0]["elements"][0]["richText"]["ranges"], + serde_json::json!([]) + ); + + let undone = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "undo".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!( + undone + .artifact_snapshot + .as_ref() + .and_then(|snapshot| snapshot.slides.first()) + .map(|slide| slide.element_ids.clone()), + Some(Vec::new()) + ); + let undone_proto = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "to_proto".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!( + undone_proto + .proto_json + .as_ref() + .and_then(|proto| proto.get("slides")) + .and_then(serde_json::Value::as_array) + .and_then(|slides| slides.first()) + .and_then(|slide| slide.get("backgroundFill")), + Some(&serde_json::Value::Null) + ); + assert_eq!( + undone_proto + .proto_json + .as_ref() + .and_then(|proto| proto.get("slides")) + .and_then(serde_json::Value::as_array) + .and_then(|slides| slides.first()) + .and_then(|slide| slide.get("elements")) + .and_then(serde_json::Value::as_array) + .map(Vec::len), + Some(0) + ); + + let redone = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "redo".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!(redone.patch, None); + let redone_proto = manager.execute( + PresentationArtifactRequest { + artifact_id: Some(artifact_id), + action: "to_proto".to_string(), + args: serde_json::json!({}), + }, + temp_dir.path(), + )?; + assert_eq!(redone_proto.proto_json, Some(proto)); + Ok(()) +} diff --git a/codex-rs/artifact-spreadsheet/BUILD.bazel b/codex-rs/artifact-spreadsheet/BUILD.bazel new file mode 100644 index 0000000000..07d1337283 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "artifact-spreadsheet", + crate_name = "codex_artifact_spreadsheet", +) diff --git a/codex-rs/artifact-spreadsheet/Cargo.toml b/codex-rs/artifact-spreadsheet/Cargo.toml new file mode 100644 index 0000000000..66e030ea43 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "codex-artifact-spreadsheet" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +name = "codex_artifact_spreadsheet" +path = "src/lib.rs" + +[lints] +workspace = true + +[dependencies] +base64 = { workspace = true } +regex = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +uuid = { workspace = true, features = ["v4"] } +zip = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/artifact-spreadsheet/src/address.rs b/codex-rs/artifact-spreadsheet/src/address.rs new file mode 100644 index 0000000000..28e4da5e3a --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/address.rs @@ -0,0 +1,245 @@ +use serde::Deserialize; +use serde::Serialize; + +use crate::SpreadsheetArtifactError; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct CellAddress { + pub column: u32, + pub row: u32, +} + +impl CellAddress { + pub fn parse(address: &str) -> Result { + let trimmed = address.trim(); + if trimmed.is_empty() { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: address.to_string(), + message: "address is empty".to_string(), + }); + } + + let mut split = 0usize; + for (index, ch) in trimmed.char_indices() { + if ch.is_ascii_alphabetic() { + split = index + ch.len_utf8(); + } else { + break; + } + } + + let (letters, digits) = trimmed.split_at(split); + if letters.is_empty() || digits.is_empty() { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: address.to_string(), + message: "expected A1-style address".to_string(), + }); + } + + if !letters.chars().all(|ch| ch.is_ascii_alphabetic()) + || !digits.chars().all(|ch| ch.is_ascii_digit()) + { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: address.to_string(), + message: "expected letters followed by digits".to_string(), + }); + } + + let column = column_letters_to_index(letters)?; + let row = digits + .parse::() + .map_err(|_| SpreadsheetArtifactError::InvalidAddress { + address: address.to_string(), + message: "row must be a positive integer".to_string(), + })?; + + if row == 0 { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: address.to_string(), + message: "row must be positive".to_string(), + }); + } + + Ok(Self { column, row }) + } + + pub fn to_a1(self) -> String { + format!("{}{}", column_index_to_letters(self.column), self.row) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CellRange { + pub start: CellAddress, + pub end: CellAddress, +} + +impl CellRange { + pub fn parse(address: &str) -> Result { + let trimmed = address.trim(); + if trimmed.is_empty() { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: address.to_string(), + message: "range is empty".to_string(), + }); + } + + let (start, end) = if let Some((left, right)) = trimmed.split_once(':') { + (CellAddress::parse(left)?, CellAddress::parse(right)?) + } else { + let cell = CellAddress::parse(trimmed)?; + (cell, cell) + }; + + let normalized = Self { + start: CellAddress { + column: start.column.min(end.column), + row: start.row.min(end.row), + }, + end: CellAddress { + column: start.column.max(end.column), + row: start.row.max(end.row), + }, + }; + Ok(normalized) + } + + pub fn from_start_end(start: CellAddress, end: CellAddress) -> Self { + Self { + start: CellAddress { + column: start.column.min(end.column), + row: start.row.min(end.row), + }, + end: CellAddress { + column: start.column.max(end.column), + row: start.row.max(end.row), + }, + } + } + + pub fn to_a1(&self) -> String { + if self.is_single_cell() { + self.start.to_a1() + } else { + format!("{}:{}", self.start.to_a1(), self.end.to_a1()) + } + } + + pub fn is_single_cell(&self) -> bool { + self.start == self.end + } + + pub fn is_single_row(&self) -> bool { + self.start.row == self.end.row + } + + pub fn is_single_column(&self) -> bool { + self.start.column == self.end.column + } + + pub fn width(&self) -> usize { + (self.end.column - self.start.column + 1) as usize + } + + pub fn height(&self) -> usize { + (self.end.row - self.start.row + 1) as usize + } + + pub fn contains(&self, address: CellAddress) -> bool { + self.start.column <= address.column + && address.column <= self.end.column + && self.start.row <= address.row + && address.row <= self.end.row + } + + pub fn contains_range(&self, other: &CellRange) -> bool { + self.contains(other.start) && self.contains(other.end) + } + + pub fn intersects(&self, other: &CellRange) -> bool { + !(self.end.column < other.start.column + || other.end.column < self.start.column + || self.end.row < other.start.row + || other.end.row < self.start.row) + } + + pub fn addresses(&self) -> impl Iterator { + let range = self.clone(); + (range.start.row..=range.end.row).flat_map(move |row| { + let range = range.clone(); + (range.start.column..=range.end.column).map(move |column| CellAddress { column, row }) + }) + } +} + +pub fn column_letters_to_index(column: &str) -> Result { + let trimmed = column.trim(); + if trimmed.is_empty() { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: column.to_string(), + message: "column is empty".to_string(), + }); + } + + let mut result = 0u32; + for ch in trimmed.chars() { + if !ch.is_ascii_alphabetic() { + return Err(SpreadsheetArtifactError::InvalidAddress { + address: column.to_string(), + message: "column must contain only letters".to_string(), + }); + } + result = result + .checked_mul(26) + .and_then(|value| value.checked_add((ch.to_ascii_uppercase() as u8 - b'A' + 1) as u32)) + .ok_or_else(|| SpreadsheetArtifactError::InvalidAddress { + address: column.to_string(), + message: "column is too large".to_string(), + })?; + } + Ok(result) +} + +pub fn column_index_to_letters(mut index: u32) -> String { + if index == 0 { + return String::new(); + } + + let mut letters = Vec::new(); + while index > 0 { + let remainder = (index - 1) % 26; + letters.push((b'A' + remainder as u8) as char); + index = (index - 1) / 26; + } + letters.iter().rev().collect() +} + +pub fn parse_column_reference(reference: &str) -> Result<(u32, u32), SpreadsheetArtifactError> { + let trimmed = reference.trim(); + if let Some((left, right)) = trimmed.split_once(':') { + let start = column_letters_to_index(left)?; + let end = column_letters_to_index(right)?; + Ok((start.min(end), start.max(end))) + } else { + let column = column_letters_to_index(trimmed)?; + Ok((column, column)) + } +} + +pub fn is_valid_cell_reference(address: &str) -> bool { + CellAddress::parse(address).is_ok() +} + +pub fn is_valid_range_reference(address: &str) -> bool { + CellRange::parse(address).is_ok() +} + +pub fn is_valid_row_reference(address: &str) -> bool { + CellRange::parse(address) + .map(|range| range.is_single_row()) + .unwrap_or(false) +} + +pub fn is_valid_column_reference(address: &str) -> bool { + parse_column_reference(address).is_ok() +} diff --git a/codex-rs/artifact-spreadsheet/src/chart.rs b/codex-rs/artifact-spreadsheet/src/chart.rs new file mode 100644 index 0000000000..83b02b6be1 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/chart.rs @@ -0,0 +1,357 @@ +use serde::Deserialize; +use serde::Serialize; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SpreadsheetChartType { + Area, + Bar, + Doughnut, + Line, + Pie, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SpreadsheetChartLegendPosition { + Bottom, + Top, + Left, + Right, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetChartLegend { + pub visible: bool, + pub position: SpreadsheetChartLegendPosition, + pub overlay: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetChartAxis { + pub linked_number_format: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetChartSeries { + pub id: u32, + pub name: Option, + pub category_sheet_name: Option, + pub category_range: String, + pub value_sheet_name: Option, + pub value_range: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetChart { + pub id: u32, + pub chart_type: SpreadsheetChartType, + pub source_sheet_name: Option, + pub source_range: Option, + pub title: Option, + pub style_index: u32, + pub display_blanks_as: String, + pub legend: SpreadsheetChartLegend, + pub category_axis: SpreadsheetChartAxis, + pub value_axis: SpreadsheetChartAxis, + #[serde(default)] + pub series: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct SpreadsheetChartLookup { + pub id: Option, + pub index: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetChartCreateOptions { + pub id: Option, + pub title: Option, + pub legend_visible: Option, + pub legend_position: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetChartProperties { + pub title: Option, + pub legend_visible: Option, + pub legend_position: Option, +} + +impl SpreadsheetSheet { + pub fn list_charts( + &self, + range: Option<&CellRange>, + ) -> Result, SpreadsheetArtifactError> { + Ok(self + .charts + .iter() + .filter(|chart| { + range.is_none_or(|target| { + chart + .source_range + .as_deref() + .map(CellRange::parse) + .transpose() + .ok() + .flatten() + .is_some_and(|chart_range| chart_range.intersects(target)) + }) + }) + .cloned() + .collect()) + } + + pub fn get_chart( + &self, + action: &str, + lookup: SpreadsheetChartLookup, + ) -> Result<&SpreadsheetChart, SpreadsheetArtifactError> { + if let Some(id) = lookup.id { + return self + .charts + .iter() + .find(|chart| chart.id == id) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("chart id `{id}` was not found"), + }); + } + if let Some(index) = lookup.index { + return self.charts.get(index).ok_or_else(|| { + SpreadsheetArtifactError::IndexOutOfRange { + action: action.to_string(), + index, + len: self.charts.len(), + } + }); + } + Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "chart id or index is required".to_string(), + }) + } + + pub fn create_chart( + &mut self, + action: &str, + chart_type: SpreadsheetChartType, + source_sheet_name: Option, + source_range: &CellRange, + options: SpreadsheetChartCreateOptions, + ) -> Result { + if source_range.width() < 2 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "chart source range must include at least two columns".to_string(), + }); + } + let id = if let Some(id) = options.id { + if self.charts.iter().any(|chart| chart.id == id) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("chart id `{id}` already exists"), + }); + } + id + } else { + self.charts.iter().map(|chart| chart.id).max().unwrap_or(0) + 1 + }; + let series = (source_range.start.column + 1..=source_range.end.column) + .enumerate() + .map(|(index, value_column)| SpreadsheetChartSeries { + id: index as u32 + 1, + name: None, + category_sheet_name: source_sheet_name.clone(), + category_range: CellRange::from_start_end( + source_range.start, + CellAddress { + column: source_range.start.column, + row: source_range.end.row, + }, + ) + .to_a1(), + value_sheet_name: source_sheet_name.clone(), + value_range: CellRange::from_start_end( + CellAddress { + column: value_column, + row: source_range.start.row, + }, + CellAddress { + column: value_column, + row: source_range.end.row, + }, + ) + .to_a1(), + }) + .collect::>(); + self.charts.push(SpreadsheetChart { + id, + chart_type, + source_sheet_name, + source_range: Some(source_range.to_a1()), + title: options.title, + style_index: 102, + display_blanks_as: "gap".to_string(), + legend: SpreadsheetChartLegend { + visible: options.legend_visible.unwrap_or(true), + position: options + .legend_position + .unwrap_or(SpreadsheetChartLegendPosition::Bottom), + overlay: false, + }, + category_axis: SpreadsheetChartAxis { + linked_number_format: true, + }, + value_axis: SpreadsheetChartAxis { + linked_number_format: true, + }, + series, + }); + Ok(id) + } + + pub fn add_chart_series( + &mut self, + action: &str, + lookup: SpreadsheetChartLookup, + mut series: SpreadsheetChartSeries, + ) -> Result { + validate_chart_series(action, &series)?; + let chart = self.get_chart_mut(action, lookup)?; + let next_id = chart.series.iter().map(|entry| entry.id).max().unwrap_or(0) + 1; + series.id = next_id; + chart.series.push(series); + Ok(next_id) + } + + pub fn delete_chart( + &mut self, + action: &str, + lookup: SpreadsheetChartLookup, + ) -> Result<(), SpreadsheetArtifactError> { + let index = if let Some(id) = lookup.id { + self.charts + .iter() + .position(|chart| chart.id == id) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("chart id `{id}` was not found"), + })? + } else if let Some(index) = lookup.index { + if index >= self.charts.len() { + return Err(SpreadsheetArtifactError::IndexOutOfRange { + action: action.to_string(), + index, + len: self.charts.len(), + }); + } + index + } else { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "chart id or index is required".to_string(), + }); + }; + self.charts.remove(index); + Ok(()) + } + + pub fn set_chart_properties( + &mut self, + action: &str, + lookup: SpreadsheetChartLookup, + properties: SpreadsheetChartProperties, + ) -> Result<(), SpreadsheetArtifactError> { + let chart = self.get_chart_mut(action, lookup)?; + if let Some(title) = properties.title { + chart.title = Some(title); + } + if let Some(visible) = properties.legend_visible { + chart.legend.visible = visible; + } + if let Some(position) = properties.legend_position { + chart.legend.position = position; + } + Ok(()) + } + + pub fn validate_charts(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { + for chart in &self.charts { + if let Some(source_range) = &chart.source_range { + let range = CellRange::parse(source_range)?; + if range.width() < 2 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "chart `{}` source range `{source_range}` is too narrow", + chart.id + ), + }); + } + } + for series in &chart.series { + validate_chart_series(action, series)?; + } + } + Ok(()) + } + + fn get_chart_mut( + &mut self, + action: &str, + lookup: SpreadsheetChartLookup, + ) -> Result<&mut SpreadsheetChart, SpreadsheetArtifactError> { + if let Some(id) = lookup.id { + return self + .charts + .iter_mut() + .find(|chart| chart.id == id) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("chart id `{id}` was not found"), + }); + } + if let Some(index) = lookup.index { + let len = self.charts.len(); + return self.charts.get_mut(index).ok_or_else(|| { + SpreadsheetArtifactError::IndexOutOfRange { + action: action.to_string(), + index, + len, + } + }); + } + Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "chart id or index is required".to_string(), + }) + } +} + +fn validate_chart_series( + action: &str, + series: &SpreadsheetChartSeries, +) -> Result<(), SpreadsheetArtifactError> { + let category_range = CellRange::parse(&series.category_range)?; + let value_range = CellRange::parse(&series.value_range)?; + if !category_range.is_single_column() || !value_range.is_single_column() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "chart category and value ranges must be single-column ranges".to_string(), + }); + } + if category_range.height() != value_range.height() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "chart category and value series lengths must match".to_string(), + }); + } + Ok(()) +} diff --git a/codex-rs/artifact-spreadsheet/src/conditional.rs b/codex-rs/artifact-spreadsheet/src/conditional.rs new file mode 100644 index 0000000000..96c0c8ebd8 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/conditional.rs @@ -0,0 +1,308 @@ +use serde::Deserialize; +use serde::Serialize; + +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SpreadsheetConditionalFormatType { + Expression, + CellIs, + ColorScale, + DataBar, + IconSet, + Top10, + UniqueValues, + DuplicateValues, + ContainsText, + NotContainsText, + BeginsWith, + EndsWith, + ContainsBlanks, + NotContainsBlanks, + ContainsErrors, + NotContainsErrors, + TimePeriod, + AboveAverage, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetColorScale { + pub min_type: Option, + pub mid_type: Option, + pub max_type: Option, + pub min_value: Option, + pub mid_value: Option, + pub max_value: Option, + pub min_color: String, + pub mid_color: Option, + pub max_color: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetDataBar { + pub color: String, + pub min_length: Option, + pub max_length: Option, + pub show_value: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetIconSet { + pub style: String, + pub show_value: Option, + pub reverse_order: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetConditionalFormat { + pub id: u32, + pub range: String, + pub rule_type: SpreadsheetConditionalFormatType, + pub operator: Option, + #[serde(default)] + pub formulas: Vec, + pub text: Option, + pub dxf_id: Option, + pub stop_if_true: bool, + pub priority: u32, + pub rank: Option, + pub percent: Option, + pub time_period: Option, + pub above_average: Option, + pub equal_average: Option, + pub color_scale: Option, + pub data_bar: Option, + pub icon_set: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetConditionalFormatCollection { + pub sheet_name: String, + pub range: String, +} + +impl SpreadsheetConditionalFormatCollection { + pub fn new(sheet_name: String, range: &CellRange) -> Self { + Self { + sheet_name, + range: range.to_a1(), + } + } + + pub fn range(&self) -> Result { + CellRange::parse(&self.range) + } + + pub fn list( + &self, + artifact: &SpreadsheetArtifact, + ) -> Result, SpreadsheetArtifactError> { + let sheet = artifact.sheet_lookup( + "conditional_format_collection", + Some(&self.sheet_name), + None, + )?; + Ok(sheet.list_conditional_formats(Some(&self.range()?))) + } + + pub fn add( + &self, + artifact: &mut SpreadsheetArtifact, + mut format: SpreadsheetConditionalFormat, + ) -> Result { + format.range = self.range.clone(); + artifact.add_conditional_format("conditional_format_collection", &self.sheet_name, format) + } + + pub fn delete( + &self, + artifact: &mut SpreadsheetArtifact, + id: u32, + ) -> Result<(), SpreadsheetArtifactError> { + artifact.delete_conditional_format("conditional_format_collection", &self.sheet_name, id) + } +} + +impl SpreadsheetArtifact { + pub fn validate_conditional_formats( + &self, + action: &str, + sheet_name: &str, + ) -> Result<(), SpreadsheetArtifactError> { + let sheet = self.sheet_lookup(action, Some(sheet_name), None)?; + for format in &sheet.conditional_formats { + validate_conditional_format(self, format, action)?; + } + Ok(()) + } + + pub fn add_conditional_format( + &mut self, + action: &str, + sheet_name: &str, + mut format: SpreadsheetConditionalFormat, + ) -> Result { + validate_conditional_format(self, &format, action)?; + let sheet = self.sheet_lookup_mut(action, Some(sheet_name), None)?; + let next_id = sheet + .conditional_formats + .iter() + .map(|entry| entry.id) + .max() + .unwrap_or(0) + + 1; + format.id = next_id; + format.priority = if format.priority == 0 { + next_id + } else { + format.priority + }; + sheet.conditional_formats.push(format); + Ok(next_id) + } + + pub fn delete_conditional_format( + &mut self, + action: &str, + sheet_name: &str, + id: u32, + ) -> Result<(), SpreadsheetArtifactError> { + let sheet = self.sheet_lookup_mut(action, Some(sheet_name), None)?; + let previous_len = sheet.conditional_formats.len(); + sheet.conditional_formats.retain(|entry| entry.id != id); + if sheet.conditional_formats.len() == previous_len { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("conditional format `{id}` was not found"), + }); + } + Ok(()) + } +} + +impl SpreadsheetSheet { + pub fn conditional_format_collection( + &self, + range: &CellRange, + ) -> SpreadsheetConditionalFormatCollection { + SpreadsheetConditionalFormatCollection::new(self.name.clone(), range) + } + + pub fn list_conditional_formats( + &self, + range: Option<&CellRange>, + ) -> Vec { + self.conditional_formats + .iter() + .filter(|entry| { + range.is_none_or(|target| { + CellRange::parse(&entry.range) + .map(|entry_range| entry_range.intersects(target)) + .unwrap_or(false) + }) + }) + .cloned() + .collect() + } +} + +fn validate_conditional_format( + artifact: &SpreadsheetArtifact, + format: &SpreadsheetConditionalFormat, + action: &str, +) -> Result<(), SpreadsheetArtifactError> { + CellRange::parse(&format.range)?; + if let Some(dxf_id) = format.dxf_id + && artifact.get_differential_format(dxf_id).is_none() + { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("differential format `{dxf_id}` was not found"), + }); + } + + let has_style = format.dxf_id.is_some(); + let has_intrinsic_visual = + format.color_scale.is_some() || format.data_bar.is_some() || format.icon_set.is_some(); + + match format.rule_type { + SpreadsheetConditionalFormatType::Expression | SpreadsheetConditionalFormatType::CellIs => { + if format.formulas.is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "conditional format formulas are required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::ContainsText + | SpreadsheetConditionalFormatType::NotContainsText + | SpreadsheetConditionalFormatType::BeginsWith + | SpreadsheetConditionalFormatType::EndsWith => { + if format.text.as_deref().unwrap_or_default().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "conditional format text is required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::ColorScale => { + if format.color_scale.is_none() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "color scale settings are required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::DataBar => { + if format.data_bar.is_none() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "data bar settings are required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::IconSet => { + if format.icon_set.is_none() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "icon set settings are required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::Top10 => { + if format.rank.is_none() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "top10 rank is required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::TimePeriod => { + if format.time_period.as_deref().unwrap_or_default().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "time period is required".to_string(), + }); + } + } + SpreadsheetConditionalFormatType::AboveAverage => {} + SpreadsheetConditionalFormatType::UniqueValues + | SpreadsheetConditionalFormatType::DuplicateValues + | SpreadsheetConditionalFormatType::ContainsBlanks + | SpreadsheetConditionalFormatType::NotContainsBlanks + | SpreadsheetConditionalFormatType::ContainsErrors + | SpreadsheetConditionalFormatType::NotContainsErrors => {} + } + + if !has_style && !has_intrinsic_visual { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "conditional formatting requires at least one style component".to_string(), + }); + } + Ok(()) +} diff --git a/codex-rs/artifact-spreadsheet/src/error.rs b/codex-rs/artifact-spreadsheet/src/error.rs new file mode 100644 index 0000000000..d6d0b31bc5 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/error.rs @@ -0,0 +1,39 @@ +use std::path::PathBuf; + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum SpreadsheetArtifactError { + #[error("missing `artifact_id` for action `{action}`")] + MissingArtifactId { action: String }, + #[error("unknown artifact id `{artifact_id}` for action `{action}`")] + UnknownArtifactId { action: String, artifact_id: String }, + #[error("unknown action `{0}`")] + UnknownAction(String), + #[error("invalid args for action `{action}`: {message}")] + InvalidArgs { action: String, message: String }, + #[error("invalid address `{address}`: {message}")] + InvalidAddress { address: String, message: String }, + #[error("sheet lookup failed for action `{action}`: {message}")] + SheetLookup { action: String, message: String }, + #[error("index `{index}` is out of range for action `{action}`; len={len}")] + IndexOutOfRange { + action: String, + index: usize, + len: usize, + }, + #[error("merge conflict for action `{action}` on range `{range}` with `{conflict}`")] + MergeConflict { + action: String, + range: String, + conflict: String, + }, + #[error("formula error at `{location}`: {message}")] + Formula { location: String, message: String }, + #[error("serialization failed: {message}")] + Serialization { message: String }, + #[error("failed to import XLSX `{path}`: {message}")] + ImportFailed { path: PathBuf, message: String }, + #[error("failed to export XLSX `{path}`: {message}")] + ExportFailed { path: PathBuf, message: String }, +} diff --git a/codex-rs/artifact-spreadsheet/src/formula.rs b/codex-rs/artifact-spreadsheet/src/formula.rs new file mode 100644 index 0000000000..9ee8d0824f --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/formula.rs @@ -0,0 +1,535 @@ +use std::collections::BTreeSet; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCellValue; + +#[derive(Debug, Clone)] +enum Token { + Number(f64), + Cell(String), + Ident(String), + Plus, + Minus, + Star, + Slash, + LParen, + RParen, + Colon, + Comma, +} + +#[derive(Debug, Clone)] +enum Expr { + Number(f64), + Cell(CellAddress), + Range(CellRange), + UnaryMinus(Box), + Binary { + op: BinaryOp, + left: Box, + right: Box, + }, + Function { + name: String, + args: Vec, + }, +} + +#[derive(Debug, Clone, Copy)] +enum BinaryOp { + Add, + Subtract, + Multiply, + Divide, +} + +#[derive(Debug, Clone)] +enum EvalValue { + Scalar(Option), + Range(Vec>), +} + +pub(crate) fn recalculate_workbook(artifact: &mut SpreadsheetArtifact) { + let updates = artifact + .sheets + .iter() + .enumerate() + .flat_map(|(sheet_index, sheet)| { + sheet.cells.iter().filter_map(move |(address, cell)| { + cell.formula + .as_ref() + .map(|formula| (sheet_index, *address, formula.clone())) + }) + }) + .map(|(sheet_index, address, formula)| { + let mut stack = BTreeSet::new(); + let value = evaluate_formula(artifact, sheet_index, &formula, &mut stack) + .unwrap_or_else(|error| { + Some(SpreadsheetCellValue::Error(map_error_to_code(&error))) + }); + (sheet_index, address, value) + }) + .collect::>(); + + for (sheet_index, address, value) in updates { + if let Some(sheet) = artifact.sheets.get_mut(sheet_index) + && let Some(cell) = sheet.cells.get_mut(&address) + { + cell.value = value; + } + } +} + +fn evaluate_formula( + artifact: &SpreadsheetArtifact, + sheet_index: usize, + formula: &str, + stack: &mut BTreeSet<(usize, CellAddress)>, +) -> Result, SpreadsheetArtifactError> { + let source = formula.trim().trim_start_matches('='); + let tokens = tokenize(source)?; + let mut parser = Parser::new(tokens); + let expr = parser.parse_expression()?; + if parser.has_remaining() { + return Err(SpreadsheetArtifactError::Formula { + location: formula.to_string(), + message: "unexpected trailing tokens".to_string(), + }); + } + match evaluate_expr(artifact, sheet_index, &expr, stack)? { + EvalValue::Scalar(value) => Ok(value), + EvalValue::Range(_) => Err(SpreadsheetArtifactError::Formula { + location: formula.to_string(), + message: "range expressions are only allowed inside functions".to_string(), + }), + } +} + +fn evaluate_expr( + artifact: &SpreadsheetArtifact, + sheet_index: usize, + expr: &Expr, + stack: &mut BTreeSet<(usize, CellAddress)>, +) -> Result { + match expr { + Expr::Number(value) => Ok(EvalValue::Scalar(Some(number_to_value(*value)))), + Expr::Cell(address) => evaluate_cell_reference(artifact, sheet_index, *address, stack), + Expr::Range(range) => { + let sheet = artifact.sheets.get(sheet_index).ok_or_else(|| { + SpreadsheetArtifactError::Formula { + location: range.to_a1(), + message: "sheet index was not found".to_string(), + } + })?; + let values = range + .addresses() + .map(|address| sheet.get_cell(address).and_then(|cell| cell.value.clone())) + .collect::>(); + Ok(EvalValue::Range(values)) + } + Expr::UnaryMinus(inner) => { + let value = evaluate_scalar(artifact, sheet_index, inner, stack)?; + Ok(EvalValue::Scalar(match value { + None => Some(SpreadsheetCellValue::Integer(0)), + Some(SpreadsheetCellValue::Integer(value)) => { + Some(SpreadsheetCellValue::Integer(-value)) + } + Some(SpreadsheetCellValue::Float(value)) => { + Some(SpreadsheetCellValue::Float(-value)) + } + Some(SpreadsheetCellValue::Error(value)) => { + Some(SpreadsheetCellValue::Error(value)) + } + Some(_) => Some(SpreadsheetCellValue::Error("#VALUE!".to_string())), + })) + } + Expr::Binary { op, left, right } => { + let left = evaluate_scalar(artifact, sheet_index, left, stack)?; + let right = evaluate_scalar(artifact, sheet_index, right, stack)?; + Ok(EvalValue::Scalar(Some(apply_binary_op(*op, left, right)?))) + } + Expr::Function { name, args } => { + let mut numeric = Vec::new(); + for arg in args { + match evaluate_expr(artifact, sheet_index, arg, stack)? { + EvalValue::Scalar(value) => { + if let Some(number) = scalar_to_number(value.clone())? { + numeric.push(number); + } + } + EvalValue::Range(values) => { + for value in values { + if let Some(number) = scalar_to_number(value.clone())? { + numeric.push(number); + } + } + } + } + } + let upper = name.to_ascii_uppercase(); + let result = match upper.as_str() { + "SUM" => numeric.iter().sum::(), + "AVERAGE" => { + if numeric.is_empty() { + return Ok(EvalValue::Scalar(None)); + } + numeric.iter().sum::() / numeric.len() as f64 + } + "MIN" => numeric.iter().copied().reduce(f64::min).unwrap_or(0.0), + "MAX" => numeric.iter().copied().reduce(f64::max).unwrap_or(0.0), + _ => { + return Ok(EvalValue::Scalar(Some(SpreadsheetCellValue::Error( + "#NAME?".to_string(), + )))); + } + }; + Ok(EvalValue::Scalar(Some(number_to_value(result)))) + } + } +} + +fn evaluate_scalar( + artifact: &SpreadsheetArtifact, + sheet_index: usize, + expr: &Expr, + stack: &mut BTreeSet<(usize, CellAddress)>, +) -> Result, SpreadsheetArtifactError> { + match evaluate_expr(artifact, sheet_index, expr, stack)? { + EvalValue::Scalar(value) => Ok(value), + EvalValue::Range(_) => Err(SpreadsheetArtifactError::Formula { + location: format!("{expr:?}"), + message: "expected a scalar expression".to_string(), + }), + } +} + +fn evaluate_cell_reference( + artifact: &SpreadsheetArtifact, + sheet_index: usize, + address: CellAddress, + stack: &mut BTreeSet<(usize, CellAddress)>, +) -> Result { + let Some(sheet) = artifact.sheets.get(sheet_index) else { + return Err(SpreadsheetArtifactError::Formula { + location: address.to_a1(), + message: "sheet index was not found".to_string(), + }); + }; + let key = (sheet_index, address); + if !stack.insert(key) { + return Ok(EvalValue::Scalar(Some(SpreadsheetCellValue::Error( + "#CYCLE!".to_string(), + )))); + } + + let value = if let Some(cell) = sheet.get_cell(address) { + if let Some(formula) = &cell.formula { + evaluate_formula(artifact, sheet_index, formula, stack)? + } else { + cell.value.clone() + } + } else { + None + }; + stack.remove(&key); + Ok(EvalValue::Scalar(value)) +} + +fn apply_binary_op( + op: BinaryOp, + left: Option, + right: Option, +) -> Result { + if let Some(SpreadsheetCellValue::Error(value)) = &left { + return Ok(SpreadsheetCellValue::Error(value.clone())); + } + if let Some(SpreadsheetCellValue::Error(value)) = &right { + return Ok(SpreadsheetCellValue::Error(value.clone())); + } + + let left = scalar_to_number(left)?; + let right = scalar_to_number(right)?; + let left = left.unwrap_or(0.0); + let right = right.unwrap_or(0.0); + let result = match op { + BinaryOp::Add => left + right, + BinaryOp::Subtract => left - right, + BinaryOp::Multiply => left * right, + BinaryOp::Divide => { + if right == 0.0 { + return Ok(SpreadsheetCellValue::Error("#DIV/0!".to_string())); + } + left / right + } + }; + Ok(number_to_value(result)) +} + +fn scalar_to_number( + value: Option, +) -> Result, SpreadsheetArtifactError> { + match value { + None => Ok(None), + Some(SpreadsheetCellValue::Integer(value)) => Ok(Some(value as f64)), + Some(SpreadsheetCellValue::Float(value)) => Ok(Some(value)), + Some(SpreadsheetCellValue::Bool(value)) => Ok(Some(if value { 1.0 } else { 0.0 })), + Some(SpreadsheetCellValue::Error(value)) => Err(SpreadsheetArtifactError::Formula { + location: value, + message: "encountered error value".to_string(), + }), + Some(other) => Err(SpreadsheetArtifactError::Formula { + location: format!("{other:?}"), + message: "value is not numeric".to_string(), + }), + } +} + +fn number_to_value(number: f64) -> SpreadsheetCellValue { + if number.fract() == 0.0 { + SpreadsheetCellValue::Integer(number as i64) + } else { + SpreadsheetCellValue::Float(number) + } +} + +fn map_error_to_code(error: &SpreadsheetArtifactError) -> String { + match error { + SpreadsheetArtifactError::Formula { message, .. } => { + if message.contains("cycle") { + "#CYCLE!".to_string() + } else if message.contains("not numeric") || message.contains("scalar") { + "#VALUE!".to_string() + } else { + "#ERROR!".to_string() + } + } + SpreadsheetArtifactError::InvalidAddress { .. } => "#REF!".to_string(), + _ => "#ERROR!".to_string(), + } +} + +fn tokenize(source: &str) -> Result, SpreadsheetArtifactError> { + let chars = source.chars().collect::>(); + let mut index = 0usize; + let mut tokens = Vec::new(); + while index < chars.len() { + let ch = chars[index]; + if ch.is_ascii_whitespace() { + index += 1; + continue; + } + match ch { + '+' => { + tokens.push(Token::Plus); + index += 1; + } + '-' => { + tokens.push(Token::Minus); + index += 1; + } + '*' => { + tokens.push(Token::Star); + index += 1; + } + '/' => { + tokens.push(Token::Slash); + index += 1; + } + '(' => { + tokens.push(Token::LParen); + index += 1; + } + ')' => { + tokens.push(Token::RParen); + index += 1; + } + ':' => { + tokens.push(Token::Colon); + index += 1; + } + ',' => { + tokens.push(Token::Comma); + index += 1; + } + '0'..='9' | '.' => { + let start = index; + index += 1; + while index < chars.len() && (chars[index].is_ascii_digit() || chars[index] == '.') + { + index += 1; + } + let number = source[start..index].parse::().map_err(|_| { + SpreadsheetArtifactError::Formula { + location: source.to_string(), + message: "invalid numeric literal".to_string(), + } + })?; + tokens.push(Token::Number(number)); + } + 'A'..='Z' | 'a'..='z' | '_' => { + let start = index; + index += 1; + while index < chars.len() + && (chars[index].is_ascii_alphanumeric() || chars[index] == '_') + { + index += 1; + } + let text = source[start..index].to_string(); + if text.chars().any(|part| part.is_ascii_digit()) + && text.chars().any(|part| part.is_ascii_alphabetic()) + { + tokens.push(Token::Cell(text)); + } else { + tokens.push(Token::Ident(text)); + } + } + other => { + return Err(SpreadsheetArtifactError::Formula { + location: source.to_string(), + message: format!("unsupported token `{other}`"), + }); + } + } + } + Ok(tokens) +} + +struct Parser { + tokens: Vec, + index: usize, +} + +impl Parser { + fn new(tokens: Vec) -> Self { + Self { tokens, index: 0 } + } + + fn has_remaining(&self) -> bool { + self.index < self.tokens.len() + } + + fn parse_expression(&mut self) -> Result { + let mut expr = self.parse_term()?; + while let Some(token) = self.peek() { + let op = match token { + Token::Plus => BinaryOp::Add, + Token::Minus => BinaryOp::Subtract, + _ => break, + }; + self.index += 1; + let right = self.parse_term()?; + expr = Expr::Binary { + op, + left: Box::new(expr), + right: Box::new(right), + }; + } + Ok(expr) + } + + fn parse_term(&mut self) -> Result { + let mut expr = self.parse_factor()?; + while let Some(token) = self.peek() { + let op = match token { + Token::Star => BinaryOp::Multiply, + Token::Slash => BinaryOp::Divide, + _ => break, + }; + self.index += 1; + let right = self.parse_factor()?; + expr = Expr::Binary { + op, + left: Box::new(expr), + right: Box::new(right), + }; + } + Ok(expr) + } + + fn parse_factor(&mut self) -> Result { + match self.peek() { + Some(Token::Minus) => { + self.index += 1; + Ok(Expr::UnaryMinus(Box::new(self.parse_factor()?))) + } + _ => self.parse_primary(), + } + } + + fn parse_primary(&mut self) -> Result { + match self.next().cloned() { + Some(Token::Number(value)) => Ok(Expr::Number(value)), + Some(Token::Cell(address)) => { + let start = CellAddress::parse(&address)?; + if matches!(self.peek(), Some(Token::Colon)) { + self.index += 1; + let Some(Token::Cell(end)) = self.next().cloned() else { + return Err(SpreadsheetArtifactError::Formula { + location: address, + message: "expected cell after `:`".to_string(), + }); + }; + Ok(Expr::Range(CellRange::from_start_end( + start, + CellAddress::parse(&end)?, + ))) + } else { + Ok(Expr::Cell(start)) + } + } + Some(Token::Ident(name)) => { + if !matches!(self.next(), Some(Token::LParen)) { + return Err(SpreadsheetArtifactError::Formula { + location: name, + message: "expected `(` after function name".to_string(), + }); + } + let mut args = Vec::new(); + if !matches!(self.peek(), Some(Token::RParen)) { + loop { + args.push(self.parse_expression()?); + if matches!(self.peek(), Some(Token::Comma)) { + self.index += 1; + continue; + } + break; + } + } + if !matches!(self.next(), Some(Token::RParen)) { + return Err(SpreadsheetArtifactError::Formula { + location: name, + message: "expected `)`".to_string(), + }); + } + Ok(Expr::Function { name, args }) + } + Some(Token::LParen) => { + let expr = self.parse_expression()?; + if !matches!(self.next(), Some(Token::RParen)) { + return Err(SpreadsheetArtifactError::Formula { + location: format!("{expr:?}"), + message: "expected `)`".to_string(), + }); + } + Ok(expr) + } + other => Err(SpreadsheetArtifactError::Formula { + location: format!("{other:?}"), + message: "unexpected token".to_string(), + }), + } + } + + fn peek(&self) -> Option<&Token> { + self.tokens.get(self.index) + } + + fn next(&mut self) -> Option<&Token> { + let token = self.tokens.get(self.index); + self.index += usize::from(token.is_some()); + token + } +} diff --git a/codex-rs/artifact-spreadsheet/src/lib.rs b/codex-rs/artifact-spreadsheet/src/lib.rs new file mode 100644 index 0000000000..bd9f6ed8fb --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/lib.rs @@ -0,0 +1,26 @@ +mod address; +mod chart; +mod conditional; +mod error; +mod formula; +mod manager; +mod model; +mod pivot; +mod render; +mod style; +mod table; +mod xlsx; + +#[cfg(test)] +mod tests; + +pub use address::*; +pub use chart::*; +pub use conditional::*; +pub use error::*; +pub use manager::*; +pub use model::*; +pub use pivot::*; +pub use render::*; +pub use style::*; +pub use table::*; diff --git a/codex-rs/artifact-spreadsheet/src/manager.rs b/codex-rs/artifact-spreadsheet/src/manager.rs new file mode 100644 index 0000000000..392b685c48 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/manager.rs @@ -0,0 +1,3346 @@ +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCellRangeRef; +use crate::SpreadsheetCellRef; +use crate::SpreadsheetCellValue; +use crate::SpreadsheetCitation; +use crate::SpreadsheetRangeView; +use crate::SpreadsheetSheetSummary; +use crate::SpreadsheetSummary; + +#[derive(Debug, Clone, Deserialize)] +pub struct SpreadsheetArtifactRequest { + pub artifact_id: Option, + pub action: String, + #[serde(default)] + pub args: Value, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathAccessKind { + Read, + Write, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PathAccessRequirement { + pub action: String, + pub kind: PathAccessKind, + pub path: PathBuf, +} + +impl SpreadsheetArtifactRequest { + pub fn required_path_accesses( + &self, + cwd: &Path, + ) -> Result, SpreadsheetArtifactError> { + let access = match self.action.as_str() { + "import_xlsx" | "load" | "read" => { + let args: PathArgs = parse_args(&self.action, &self.args)?; + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Read, + path: resolve_path(cwd, &args.path), + }] + } + "export_xlsx" => { + let args: PathArgs = parse_args(&self.action, &self.args)?; + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Write, + path: resolve_path(cwd, &args.path), + }] + } + "save" => { + let args: SaveArgs = parse_args(&self.action, &self.args)?; + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Write, + path: resolve_path(cwd, &args.path), + }] + } + "render_workbook" | "render_sheet" | "render_range" => { + let args: RenderArgs = parse_args(&self.action, &self.args)?; + args.output_path + .map(|path| { + vec![PathAccessRequirement { + action: self.action.clone(), + kind: PathAccessKind::Write, + path: resolve_path(cwd, &path), + }] + }) + .unwrap_or_default() + } + _ => Vec::new(), + }; + Ok(access) + } +} + +#[derive(Debug, Default)] +pub struct SpreadsheetArtifactManager { + documents: HashMap, +} + +impl SpreadsheetArtifactManager { + pub fn execute( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + match request.action.as_str() { + "create" => self.create(request), + "import_xlsx" | "load" | "read" => self.import_xlsx(request, cwd), + "export_xlsx" => self.export_xlsx(request, cwd), + "save" => self.save(request, cwd), + "render_workbook" => self.render_workbook(request, cwd), + "render_sheet" => self.render_sheet(request, cwd), + "render_range" => self.render_range(request, cwd), + "get_summary" => self.get_summary(request), + "list_sheets" => self.list_sheets(request), + "get_sheet" => self.get_sheet(request), + "inspect" => self.inspect(request), + "list_charts" => self.list_charts(request), + "get_chart" => self.get_chart(request), + "create_chart" => self.create_chart(request), + "add_chart_series" => self.add_chart_series(request), + "set_chart_properties" => self.set_chart_properties(request), + "delete_chart" => self.delete_chart(request), + "list_tables" => self.list_tables(request), + "get_table" => self.get_table(request), + "create_table" => self.create_table(request), + "set_table_style" => self.set_table_style(request), + "clear_table_filters" => self.clear_table_filters(request), + "reapply_table_filters" => self.reapply_table_filters(request), + "rename_table_column" => self.rename_table_column(request), + "set_table_column_totals" => self.set_table_column_totals(request), + "delete_table" => self.delete_table(request), + "list_conditional_formats" => self.list_conditional_formats(request), + "add_conditional_format" => self.add_conditional_format(request), + "delete_conditional_format" => self.delete_conditional_format(request), + "list_pivot_tables" => self.list_pivot_tables(request), + "get_pivot_table" => self.get_pivot_table(request), + "create_sheet" => self.create_sheet(request), + "rename_sheet" => self.rename_sheet(request), + "delete_sheet" => self.delete_sheet(request), + "set_sheet_properties" => self.set_sheet_properties(request), + "set_column_widths" => self.set_column_widths(request), + "set_column_widths_bulk" => self.set_column_widths_bulk(request), + "set_row_height" => self.set_row_height(request), + "set_row_heights" => self.set_row_heights(request), + "set_row_heights_bulk" => self.set_row_heights_bulk(request), + "get_row_height" => self.get_row_height(request), + "cleanup_and_validate_sheet" => self.cleanup_and_validate_sheet(request), + "create_text_style" => self.create_text_style(request), + "get_text_style" => self.get_text_style(request), + "create_fill" => self.create_fill(request), + "get_fill" => self.get_fill(request), + "create_border" => self.create_border(request), + "get_border" => self.get_border(request), + "create_number_format" => self.create_number_format(request), + "get_number_format" => self.get_number_format(request), + "create_cell_format" => self.create_cell_format(request), + "get_cell_format" => self.get_cell_format(request), + "create_differential_format" => self.create_differential_format(request), + "get_differential_format" => self.get_differential_format(request), + "get_cell_format_summary" => self.get_cell_format_summary(request), + "get_range_format_summary" => self.get_range_format_summary(request), + "get_reference" => self.get_reference(request), + "get_cell" => self.get_cell(request), + "get_cell_by_indices" => self.get_cell_by_indices(request), + "get_cell_field" => self.get_cell_field(request), + "get_cell_field_by_indices" => self.get_cell_field_by_indices(request), + "get_range" => self.get_range(request), + "set_cell_value" => self.set_cell_value(request), + "set_range_value" => self.set_range_value(request), + "set_range_values" => self.set_range_values(request), + "set_cell_formula" => self.set_cell_formula(request), + "set_range_formula" => self.set_range_formula(request), + "set_range_formulas" => self.set_range_formulas(request), + "set_cell_style" => self.set_cell_style(request), + "set_range_style" => self.set_range_style(request), + "clear_range" => self.clear_range(request), + "merge_range" => self.merge_range(request), + "unmerge_range" => self.unmerge_range(request), + "cite_cell" => self.cite_cell(request), + "cite_range" => self.cite_range(request), + "calculate" | "recalculate" => self.calculate(request), + "serialize_dict" => self.serialize_dict(request), + "serialize_json" => self.serialize_json(request), + "serialize_bytes" => self.serialize_bytes(request), + "deserialize_dict" => self.deserialize_dict(request), + "deserialize_json" => self.deserialize_json(request), + "deserialize_bytes" => self.deserialize_bytes(request), + "delete_artifact" => self.delete_artifact(request), + other => Err(SpreadsheetArtifactError::UnknownAction(other.to_string())), + } + } + + fn create( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateArgs = parse_args(&request.action, &request.args)?; + let mut artifact = SpreadsheetArtifact::new(args.name); + if let Some(auto_recalculate) = args.auto_recalculate { + artifact.auto_recalculate = auto_recalculate; + } + let artifact_id = artifact.artifact_id.clone(); + let summary = format!("Created spreadsheet artifact `{artifact_id}`"); + let snapshot = snapshot_for_artifact(&artifact); + self.documents.insert(artifact_id.clone(), artifact); + Ok(SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + summary, + snapshot, + )) + } + + fn import_xlsx( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let args: PathArgs = parse_args(&request.action, &request.args)?; + let path = resolve_path(cwd, &args.path); + let artifact = SpreadsheetArtifact::from_source_file(&path, None)?; + let artifact_id = artifact.artifact_id.clone(); + let snapshot = snapshot_for_artifact(&artifact); + let summary = format!( + "Imported `{}` as spreadsheet artifact `{artifact_id}` with {} sheets", + path.display(), + artifact.sheets.len() + ); + self.documents.insert(artifact_id.clone(), artifact); + Ok(SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + summary, + snapshot, + )) + } + + fn export_xlsx( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let args: PathArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let path = resolve_path(cwd, &args.path); + let exported = artifact.export(&path)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Exported spreadsheet to `{}`", exported.display()), + snapshot_for_artifact(artifact), + ); + response.exported_paths.push(exported); + response.workbook_summary = Some(artifact.summary()); + response.sheet_list = Some( + artifact + .sheets + .iter() + .map(super::model::SpreadsheetSheet::summary) + .collect(), + ); + Ok(response) + } + + fn save( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let args: SaveArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let path = resolve_path(cwd, &args.path); + let exported = artifact.save(&path, args.file_type.as_deref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Saved spreadsheet to `{}`", exported.display()), + snapshot_for_artifact(artifact), + ); + response.exported_paths.push(exported); + response.workbook_summary = Some(artifact.summary()); + Ok(response) + } + + fn get_summary( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Spreadsheet has {} sheets and {} bytes of serialized state", + artifact.sheets.len(), + artifact.summary().size_bytes + ), + snapshot_for_artifact(artifact), + ); + response.workbook_summary = Some(artifact.summary()); + response.sheet_list = Some( + artifact + .sheets + .iter() + .map(super::model::SpreadsheetSheet::summary) + .collect(), + ); + Ok(response) + } + + fn render_workbook( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let args: RenderArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let rendered = artifact.render_workbook_previews(cwd, &render_options_from_args(args)?)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Rendered workbook to {} preview files", rendered.len()), + snapshot_for_artifact(artifact), + ); + response.exported_paths = rendered.into_iter().map(|output| output.path).collect(); + Ok(response) + } + + fn render_sheet( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let args: RenderArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let rendered = + artifact.render_sheet_preview(cwd, sheet, &render_options_from_args(args)?)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Rendered sheet `{}`", sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.exported_paths.push(rendered.path); + response.rendered_html = Some(rendered.html); + response.rendered_text = Some(sheet.to_rendered_text(None)); + Ok(response) + } + + fn render_range( + &mut self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let args: RenderArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range_text = + args.range + .clone() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: "range is required".to_string(), + })?; + let range = CellRange::parse(&range_text)?; + let rendered = + artifact.render_range_preview(cwd, sheet, &range, &render_options_from_args(args)?)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Rendered range `{range_text}` from `{}`", sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + response.exported_paths.push(rendered.path); + response.rendered_html = Some(rendered.html); + response.rendered_text = Some(sheet.to_rendered_text(Some(&range))); + Ok(response) + } + + fn list_sheets( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} sheets", artifact.sheets.len()), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some( + artifact + .sheets + .iter() + .map(super::model::SpreadsheetSheet::summary) + .collect(), + ); + Ok(response) + } + + fn get_sheet( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = if let Some(range) = args.range.as_deref() { + Some(CellRange::parse(range)?) + } else { + sheet.minimum_range() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved sheet `{}`", sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet.summary()]); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.rendered_text = Some(sheet.to_rendered_text(range.as_ref())); + response.range = range.as_ref().map(|entry| sheet.get_range_view(entry)); + response.top_left_style_index = range + .as_ref() + .map(|entry| sheet.top_left_style_index(entry)); + response.range_format = range.as_ref().map(|entry| sheet.range_format(entry)); + response.cell_format_summary = response + .top_left_style_index + .and_then(|style_index| artifact.cell_format_summary(style_index)); + response.serialized_dict = Some(sheet.to_dict()?); + Ok(response) + } + + fn inspect( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let inspected = if args.sheet_name.is_none() && args.sheet_index.is_none() { + artifact.to_dict()? + } else { + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + serde_json::to_value(sheet).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Generated inspection snapshot".to_string(), + snapshot_for_artifact(artifact), + ); + response.serialized_dict = Some(inspected); + Ok(response) + } + + fn create_sheet( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateSheetArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let name = args.name.clone(); + artifact.create_sheet(args.name)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created sheet `{name}`"), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some( + artifact + .sheets + .iter() + .map(super::model::SpreadsheetSheet::summary) + .collect(), + ); + Ok(response) + } + + fn list_charts( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let charts = sheet.list_charts(range.as_ref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} charts on `{}`", charts.len(), sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.chart_list = Some(charts); + Ok(response) + } + + fn get_chart( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: ChartLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let chart = sheet + .get_chart(&request.action, chart_lookup_from_args(&args))? + .clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved chart `{}` from `{}`", chart.id, sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn create_chart( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateChartArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + if let Some(source_sheet_name) = args.source_sheet_name.as_deref() { + artifact.sheet_lookup(&request.action, Some(source_sheet_name), None)?; + } + let source_range = CellRange::parse(&args.source_range)?; + let chart = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let chart_id = sheet.create_chart( + &request.action, + args.chart_type, + args.source_sheet_name.or_else(|| Some(sheet.name.clone())), + &source_range, + args.options.unwrap_or_default(), + )?; + sheet + .get_chart( + &request.action, + crate::SpreadsheetChartLookup { + id: Some(chart_id), + index: None, + }, + )? + .clone() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created chart `{}`", chart.id), + snapshot_for_artifact(artifact), + ); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn add_chart_series( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: AddChartSeriesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let chart = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let series_id = sheet.add_chart_series( + &request.action, + crate::SpreadsheetChartLookup { + id: args.chart_id, + index: args.chart_index.map(|value| value as usize), + }, + args.series, + )?; + let chart = sheet.get_chart( + &request.action, + crate::SpreadsheetChartLookup { + id: args.chart_id.or(Some(series_id).and(None)), + index: args.chart_index.map(|value| value as usize), + }, + ); + match chart { + Ok(chart) => chart.clone(), + Err(_) => sheet + .get_chart( + &request.action, + crate::SpreadsheetChartLookup { + id: None, + index: args.chart_index.map(|value| value as usize), + }, + )? + .clone(), + } + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Added chart series to chart `{}`", chart.id), + snapshot_for_artifact(artifact), + ); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn set_chart_properties( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetChartPropertiesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let chart = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + let lookup = chart_lookup_from_args(&args.lookup); + sheet.set_chart_properties(&request.action, lookup.clone(), args.properties)?; + sheet.get_chart(&request.action, lookup)?.clone() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated chart `{}`", chart.id), + snapshot_for_artifact(artifact), + ); + response.chart_list = Some(vec![chart]); + Ok(response) + } + + fn delete_chart( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: ChartLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let name = sheet.name.clone(); + sheet.delete_chart(&request.action, chart_lookup_from_args(&args))?; + name + }; + let action = request.action.clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Deleted chart from `{sheet_name}`"), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![ + artifact + .sheet_lookup(&action, Some(&sheet_name), None)? + .summary(), + ]); + Ok(response) + } + + fn list_tables( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let tables = sheet.list_tables(range.as_ref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} tables on `{}`", tables.len(), sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.table_list = Some(tables); + Ok(response) + } + + fn get_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let table = sheet.get_table_view(&request.action, table_lookup_from_args(&args))?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved table `{}` from `{}`", table.name, sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn create_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateTableArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let table_id = sheet.create_table(&request.action, &range, args.options)?; + sheet.get_table_view( + &request.action, + crate::SpreadsheetTableLookup { + name: None, + display_name: None, + id: Some(table_id), + }, + )? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created table `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn set_table_style( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetTableStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + let lookup = table_lookup_from_args(&args.lookup); + sheet.set_table_style(&request.action, lookup.clone(), args.options)?; + sheet.get_table_view(&request.action, lookup)? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated table style for `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn clear_table_filters( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let lookup = table_lookup_from_args(&args); + sheet.clear_table_filters(&request.action, lookup.clone())?; + sheet.get_table_view(&request.action, lookup)? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Cleared table filters for `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn reapply_table_filters( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let table = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let lookup = table_lookup_from_args(&args); + sheet.reapply_table_filters(&request.action, lookup.clone())?; + sheet.get_table_view(&request.action, lookup)? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Reapplied table filters for `{}`", table.name), + snapshot_for_artifact(artifact), + ); + response.table_list = Some(vec![table]); + Ok(response) + } + + fn rename_table_column( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: RenameTableColumnArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let column = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + sheet.rename_table_column( + &request.action, + table_lookup_from_args(&args.lookup), + args.column_id, + args.column_name.as_deref(), + args.new_name, + )? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Renamed table column to `{}`", column.name), + snapshot_for_artifact(artifact), + ); + response.serialized_dict = Some(to_serialized_value(column)?); + Ok(response) + } + + fn set_table_column_totals( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetTableColumnTotalsArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let column = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.lookup.sheet_name.as_deref(), + args.lookup.sheet_index.map(|value| value as usize), + )?; + sheet.set_table_column_totals( + &request.action, + table_lookup_from_args(&args.lookup), + args.column_id, + args.column_name.as_deref(), + args.totals_row_label, + args.totals_row_function, + )? + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated totals metadata for column `{}`", column.name), + snapshot_for_artifact(artifact), + ); + response.serialized_dict = Some(to_serialized_value(column)?); + Ok(response) + } + + fn delete_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: TableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let name = sheet.name.clone(); + sheet.delete_table(&request.action, table_lookup_from_args(&args))?; + name + }; + let action = request.action.clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Deleted table from `{sheet_name}`"), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![ + artifact + .sheet_lookup(&action, Some(&sheet_name), None)? + .summary(), + ]); + Ok(response) + } + + fn list_conditional_formats( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let formats = sheet.list_conditional_formats(range.as_ref()); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Listed {} conditional formats on `{}`", + formats.len(), + sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.conditional_format_list = Some(formats); + Ok(response) + } + + fn add_conditional_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: AddConditionalFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = artifact + .sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )? + .name + .clone(); + let format_id = + artifact.add_conditional_format(&request.action, &sheet_name, args.format)?; + let format = artifact + .sheet_lookup(&request.action, Some(&sheet_name), None)? + .conditional_formats + .iter() + .find(|entry| entry.id == format_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::Serialization { + message: format!("created conditional format `{format_id}` was not available"), + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created conditional format `{format_id}`"), + snapshot_for_artifact(artifact), + ); + response.conditional_format_list = Some(vec![format]); + Ok(response) + } + + fn delete_conditional_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: DeleteConditionalFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_name = artifact + .sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )? + .name + .clone(); + artifact.delete_conditional_format(&request.action, &sheet_name, args.id)?; + let action = request.action.clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Deleted conditional format `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![ + artifact + .sheet_lookup(&action, Some(&sheet_name), None)? + .summary(), + ]); + Ok(response) + } + + fn list_pivot_tables( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = args.range.as_deref().map(CellRange::parse).transpose()?; + let pivots = sheet.list_pivot_tables(range.as_ref())?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Listed {} pivot tables on `{}`", pivots.len(), sheet.name), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.range_ref = range + .as_ref() + .map(|entry| SpreadsheetCellRangeRef::new(sheet.name.clone(), entry)); + response.pivot_table_list = Some(pivots); + Ok(response) + } + + fn get_pivot_table( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: PivotTableLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let pivot = sheet + .get_pivot_table(&request.action, pivot_lookup_from_args(&args))? + .clone(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Retrieved pivot table `{}` from `{}`", + pivot.name, sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.pivot_table_list = Some(vec![pivot]); + Ok(response) + } + + fn rename_sheet( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: RenameSheetArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let new_name = args.new_name.clone(); + artifact.rename_sheet( + args.new_name, + args.old_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Renamed sheet to `{new_name}`"), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some( + artifact + .sheets + .iter() + .map(super::model::SpreadsheetSheet::summary) + .collect(), + ); + Ok(response) + } + + fn delete_sheet( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: DeleteSheetArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + artifact.delete_sheet( + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Deleted sheet".to_string(), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some( + artifact + .sheets + .iter() + .map(super::model::SpreadsheetSheet::summary) + .collect(), + ); + Ok(response) + } + + fn set_sheet_properties( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetSheetPropertiesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_summary = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + if let Some(default_row_height) = args.default_row_height { + sheet.default_row_height = Some(default_row_height); + } + if let Some(default_column_width) = args.default_column_width { + sheet.default_column_width = Some(default_column_width); + } + if let Some(show_grid_lines) = args.show_grid_lines { + sheet.show_grid_lines = show_grid_lines; + } + sheet.summary() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Updated sheet `{}` properties", sheet_summary.name), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + Ok(response) + } + + fn set_column_widths( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetColumnWidthsArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_summary = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_column_widths(&args.reference, args.width)?; + sheet.summary() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Updated column widths `{}` on `{}`", + args.reference, sheet_summary.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + Ok(response) + } + + fn set_column_widths_bulk( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetColumnWidthsBulkArgs = parse_args(&request.action, &request.args)?; + let width_count = args.widths.len(); + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_summary = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_column_widths_bulk(&args.widths)?; + sheet.summary() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Updated {width_count} column width references on `{}`", + sheet_summary.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + Ok(response) + } + + fn set_row_height( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetRowHeightArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let (sheet_summary, row_height) = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_row_height(args.row_index, args.height)?; + (sheet.summary(), sheet.get_row_height(args.row_index)) + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Updated row height for row {} on `{}`", + args.row_index, sheet_summary.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + response.row_height = row_height; + Ok(response) + } + + fn set_row_heights( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetRowHeightsArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let start = args.start_row_index.min(args.end_row_index); + let end = args.start_row_index.max(args.end_row_index); + let sheet_summary = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_row_heights(args.start_row_index, args.end_row_index, args.height)?; + sheet.summary() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Updated row heights {start}:{end} on `{}`", + sheet_summary.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + Ok(response) + } + + fn set_row_heights_bulk( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetRowHeightsBulkArgs = parse_args(&request.action, &request.args)?; + let height_count = args.heights.len(); + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_summary = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_row_heights_bulk(&args.heights)?; + sheet.summary() + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Updated {height_count} row height entries on `{}`", + sheet_summary.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + Ok(response) + } + + fn get_row_height( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetRowHeightArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Retrieved row height for row {} from `{}`", + args.row_index, sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.sheet_ref = Some(sheet_reference(sheet)); + response.sheet_list = Some(vec![sheet.summary()]); + response.row_height = sheet.get_row_height(args.row_index); + Ok(response) + } + + fn cleanup_and_validate_sheet( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SheetLookupArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let sheet_summary = { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.cleanup_and_validate_sheet()?; + sheet.summary() + }; + artifact.validate_conditional_formats(&request.action, &sheet_summary.name)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Cleaned and validated `{}`", sheet_summary.name), + snapshot_for_artifact(artifact), + ); + response.sheet_list = Some(vec![sheet_summary]); + Ok(response) + } + + fn create_text_style( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateTextStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let style_id = artifact.create_text_style( + args.style, + args.source_style_id, + args.merge_with_existing_components.unwrap_or(false), + )?; + let style = artifact.get_text_style(style_id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::Serialization { + message: format!("created text style `{style_id}` was not available"), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created text style `{style_id}`"), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(style_id); + response.serialized_dict = Some(to_serialized_value(style)?); + Ok(response) + } + + fn get_text_style( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let style = artifact.get_text_style(args.id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("text style `{}` was not found", args.id), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved text style `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(args.id); + response.serialized_dict = Some(to_serialized_value(style)?); + Ok(response) + } + + fn create_fill( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateFillArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let style_id = artifact.create_fill( + args.fill, + args.source_fill_id, + args.merge_with_existing_components.unwrap_or(false), + )?; + let fill = artifact.get_fill(style_id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::Serialization { + message: format!("created fill `{style_id}` was not available"), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created fill `{style_id}`"), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(style_id); + response.serialized_dict = Some(to_serialized_value(fill)?); + Ok(response) + } + + fn get_fill( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let fill = artifact.get_fill(args.id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("fill `{}` was not found", args.id), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved fill `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(args.id); + response.serialized_dict = Some(to_serialized_value(fill)?); + Ok(response) + } + + fn create_border( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateBorderArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let style_id = artifact.create_border( + args.border, + args.source_border_id, + args.merge_with_existing_components.unwrap_or(false), + )?; + let border = artifact.get_border(style_id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::Serialization { + message: format!("created border `{style_id}` was not available"), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created border `{style_id}`"), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(style_id); + response.serialized_dict = Some(to_serialized_value(border)?); + Ok(response) + } + + fn get_border( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let border = artifact.get_border(args.id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("border `{}` was not found", args.id), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved border `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(args.id); + response.serialized_dict = Some(to_serialized_value(border)?); + Ok(response) + } + + fn create_number_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateNumberFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let style_id = artifact.create_number_format( + args.number_format, + args.source_number_format_id, + args.merge_with_existing_components.unwrap_or(false), + )?; + let number_format = artifact + .get_number_format(style_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::Serialization { + message: format!("created number format `{style_id}` was not available"), + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created number format `{style_id}`"), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(style_id); + response.serialized_dict = Some(to_serialized_value(number_format)?); + Ok(response) + } + + fn get_number_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let number_format = artifact + .get_number_format(args.id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("number format `{}` was not found", args.id), + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved number format `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(args.id); + response.serialized_dict = Some(to_serialized_value(number_format)?); + Ok(response) + } + + fn create_cell_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateCellFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let style_id = artifact.create_cell_format( + args.format, + args.source_format_id, + args.merge_with_existing_components.unwrap_or(false), + )?; + let format = artifact.get_cell_format(style_id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::Serialization { + message: format!("created cell format `{style_id}` was not available"), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created cell format `{style_id}`"), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(style_id); + response.serialized_dict = Some(to_serialized_value(format)?); + response.cell_format_summary = artifact.cell_format_summary(style_id); + Ok(response) + } + + fn get_cell_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let format = artifact.get_cell_format(args.id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("cell format `{}` was not found", args.id), + } + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved cell format `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(args.id); + response.serialized_dict = Some(to_serialized_value(format)?); + response.cell_format_summary = artifact.cell_format_summary(args.id); + Ok(response) + } + + fn create_differential_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CreateDifferentialFormatArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let style_id = artifact.create_differential_format(args.format); + let format = artifact + .get_differential_format(style_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::Serialization { + message: format!("created differential format `{style_id}` was not available"), + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Created differential format `{style_id}`"), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(style_id); + response.serialized_dict = Some(to_serialized_value(format)?); + Ok(response) + } + + fn get_differential_format( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: GetStyleArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let format = artifact + .get_differential_format(args.id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: request.action.clone(), + message: format!("differential format `{}` was not found", args.id), + })?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved differential format `{}`", args.id), + snapshot_for_artifact(artifact), + ); + response.style_id = Some(args.id); + response.serialized_dict = Some(to_serialized_value(format)?); + Ok(response) + } + + fn get_cell_format_summary( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CellAddressArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let cell = sheet.get_cell_view(CellAddress::parse(&args.address)?); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved cell format summary for `{}`", args.address), + snapshot_for_artifact(artifact), + ); + response.cell_ref = Some(sheet.cell_ref(&args.address)?); + response.cell = Some(cell.clone()); + response.cell_format_summary = artifact.cell_format_summary(cell.style_index); + Ok(response) + } + + fn get_range_format_summary( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: RangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = CellRange::parse(&args.range)?; + let top_left_style_index = sheet.top_left_style_index(&range); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved range format summary for `{}`", args.range), + snapshot_for_artifact(artifact), + ); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + response.range_format = Some(sheet.range_format(&range)); + response.range = Some(sheet.get_range_view(&range)); + response.top_left_style_index = Some(top_left_style_index); + response.cell_format_summary = artifact.cell_format_summary(top_left_style_index); + Ok(response) + } + + fn get_reference( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: ReferenceArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Resolved reference `{}` on `{}`", + args.reference, sheet.name + ), + snapshot_for_artifact(artifact), + ); + match sheet.reference(&args.reference)? { + crate::SpreadsheetSheetReference::Cell { cell_ref } => { + let address = cell_ref.cell_address()?; + let cell = sheet.get_cell_view(address); + response.cell_format_summary = artifact.cell_format_summary(cell.style_index); + response.cell = Some(cell); + response.raw_cell = sheet.get_raw_cell(address); + response.cell_ref = Some(cell_ref); + } + crate::SpreadsheetSheetReference::Range { range_ref } => { + let range = range_ref.range()?; + let top_left_style_index = sheet.top_left_style_index(&range); + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(range_ref); + response.range_format = Some(sheet.range_format(&range)); + response.top_left_style_index = Some(top_left_style_index); + response.cell_format_summary = artifact.cell_format_summary(top_left_style_index); + response.rendered_text = Some(sheet.to_rendered_text(Some(&range))); + } + } + Ok(response) + } + + fn get_cell( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CellAddressArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let cell = sheet.get_cell_view(CellAddress::parse(&args.address)?); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved cell `{}` from `{}`", args.address, sheet.name), + snapshot_for_artifact(artifact), + ); + response.cell_format_summary = artifact.cell_format_summary(cell.style_index); + response.cell = Some(cell); + response.raw_cell = sheet.get_raw_cell(CellAddress::parse(&args.address)?); + response.cell_ref = Some(sheet.cell_ref(&args.address)?); + Ok(response) + } + + fn get_cell_by_indices( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CellIndicesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let address = CellAddress { + column: args.column_index, + row: args.row_index, + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Retrieved cell by indices ({}, {}) from `{}`", + args.column_index, args.row_index, sheet.name + ), + snapshot_for_artifact(artifact), + ); + let cell = sheet.get_cell_view_by_indices(args.column_index, args.row_index); + response.cell_format_summary = artifact.cell_format_summary(cell.style_index); + response.cell = Some(cell); + response.raw_cell = sheet.get_raw_cell(address); + response.cell_ref = Some(sheet.cell_ref(address.to_a1())?); + Ok(response) + } + + fn get_cell_field( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CellFieldArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let value = sheet.get_cell_field(CellAddress::parse(&args.address)?, &args.field)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Retrieved field `{}` from `{}` on `{}`", + args.field, args.address, sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.cell_field = value; + response.cell_ref = Some(sheet.cell_ref(&args.address)?); + Ok(response) + } + + fn get_cell_field_by_indices( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: CellFieldByIndicesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let value = + sheet.get_cell_field_by_indices(args.column_index, args.row_index, &args.field)?; + let address = CellAddress { + column: args.column_index, + row: args.row_index, + }; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!( + "Retrieved field `{}` from indices ({}, {}) on `{}`", + args.field, args.column_index, args.row_index, sheet.name + ), + snapshot_for_artifact(artifact), + ); + response.cell_field = value; + response.cell_ref = Some(sheet.cell_ref(address.to_a1())?); + Ok(response) + } + + fn get_range( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: RangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let sheet = artifact.sheet_lookup( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let range = CellRange::parse(&args.range)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + format!("Retrieved range `{}` from `{}`", args.range, sheet.name), + snapshot_for_artifact(artifact), + ); + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + response.range_format = Some(sheet.range_format(&range)); + response.top_left_style_index = Some(sheet.top_left_style_index(&range)); + response.cell_format_summary = + artifact.cell_format_summary(sheet.top_left_style_index(&range)); + response.rendered_text = Some(sheet.to_rendered_text(Some(&range))); + Ok(response) + } + + fn set_cell_value( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: SetCellValueArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let address = CellAddress::parse(&args.address)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let value = normalize_optional_cell_value(args.value)?; + sheet.set_value(address, value)?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated cell `{}`", args.address), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.cell = Some(sheet.get_cell_view(address)); + response.cell_ref = Some(sheet.cell_ref(&args.address)?); + Ok(response) + } + + fn set_range_value( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: SetRangeValueArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_range_to_value(&range, normalize_optional_cell_value(args.value)?)?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated range `{}` to a single value", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn set_range_values( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: SetRangeValuesArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + let values = normalize_value_matrix(args.values, &request.action)?; + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_values_matrix(&range, &values)?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated range `{}`", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn set_cell_formula( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: SetCellFormulaArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let address = CellAddress::parse(&args.address)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_formula(address, Some(normalize_formula(args.formula)))?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated formula in `{}`", args.address), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.cell = Some(sheet.get_cell_view(address)); + response.cell_ref = Some(sheet.cell_ref(&args.address)?); + Ok(response) + } + + fn set_range_formula( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: SetRangeFormulaArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_range_to_formula(&range, Some(normalize_formula(args.formula)))?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated range `{}` to a single formula", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn set_range_formulas( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: SetRangeFormulasArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + let formulas = args + .formulas + .into_iter() + .map(|row| { + row.into_iter() + .map(|value| value.map(normalize_formula)) + .collect() + }) + .collect::>>>(); + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.set_formulas_matrix(&range, &formulas)?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated formulas in `{}`", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn set_cell_style( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetCellStyleArgs = parse_args(&request.action, &request.args)?; + let range = CellRange::parse(&args.address)?; + self.set_style_impl( + request, + args.sheet_name, + args.sheet_index, + range, + args.style_index, + ) + } + + fn set_range_style( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: SetRangeStyleArgs = parse_args(&request.action, &request.args)?; + let range = CellRange::parse(&args.range)?; + self.set_style_impl( + request, + args.sheet_name, + args.sheet_index, + range, + args.style_index, + ) + } + + fn set_style_impl( + &mut self, + request: SpreadsheetArtifactRequest, + sheet_name: Option, + sheet_index: Option, + range: CellRange, + style_index: u32, + ) -> Result { + let action = request.action.clone(); + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + sheet_name.as_deref(), + sheet_index.map(|value| value as usize), + )?; + sheet.set_style_index(&range, style_index)?; + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Updated style index {} on `{}`", style_index, range.to_a1()), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + sheet_name.as_deref(), + sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn clear_range( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: ClearRangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let recalculate = args.recalculate.unwrap_or(artifact.auto_recalculate); + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.clear_range(&range, args.fields.as_deref())?; + } + if recalculate { + artifact.recalculate(); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Cleared range `{}`", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn merge_range( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: MergeRangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.merge_cells(&range, args.raise_on_conflict.unwrap_or(false))?; + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Merged `{}`", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + response.range_ref = Some(SpreadsheetCellRangeRef::new(sheet.name.clone(), &range)); + Ok(response) + } + + fn cite_cell( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: CiteCellArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let address = CellAddress::parse(&args.address)?; + let citation = SpreadsheetCitation { + tether_id: args.tether_id, + start_line: args.start_line, + end_line: args.end_line, + content_reference_type: args.content_reference_type, + source_type: args.source_type, + }; + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + let cell_ref = sheet.cell_ref(&args.address)?; + cell_ref.cite(sheet, citation)?; + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Attached citation to cell `{}`", args.address), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.cell = Some(sheet.get_cell_view(address)); + response.cell_ref = Some(sheet.cell_ref(&args.address)?); + Ok(response) + } + + fn unmerge_range( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: RangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.unmerge_cells(&range); + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Unmerged `{}`", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + Ok(response) + } + + fn cite_range( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let action = request.action.clone(); + let args: CiteRangeArgs = parse_args(&request.action, &request.args)?; + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + let range = CellRange::parse(&args.range)?; + let citation = SpreadsheetCitation { + tether_id: args.tether_id, + start_line: args.start_line, + end_line: args.end_line, + content_reference_type: args.content_reference_type, + source_type: args.source_type, + }; + { + let sheet = artifact.sheet_lookup_mut( + &request.action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + sheet.cite_range(&range, citation)?; + } + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + action.clone(), + format!("Attached citation to `{}`", args.range), + snapshot_for_artifact(artifact), + ); + let sheet = artifact.sheet_lookup( + &action, + args.sheet_name.as_deref(), + args.sheet_index.map(|value| value as usize), + )?; + response.range = Some(sheet.get_range_view(&range)); + Ok(response) + } + + fn calculate( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact_mut(&artifact_id, &request.action)?; + artifact.recalculate(); + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Recalculated workbook".to_string(), + snapshot_for_artifact(artifact), + ); + response.workbook_summary = Some(artifact.summary()); + Ok(response) + } + + fn serialize_dict( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Serialized workbook to dict".to_string(), + snapshot_for_artifact(artifact), + ); + response.serialized_dict = Some(artifact.to_dict()?); + Ok(response) + } + + fn serialize_json( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Serialized workbook to JSON".to_string(), + snapshot_for_artifact(artifact), + ); + response.serialized_json = Some(artifact.to_json()?); + Ok(response) + } + + fn serialize_bytes( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.get_artifact(&artifact_id, &request.action)?; + let mut response = SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Serialized workbook to bytes".to_string(), + snapshot_for_artifact(artifact), + ); + response.serialized_bytes_base64 = Some(artifact.to_bytes_base64()); + Ok(response) + } + + fn deserialize_dict( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: DeserializeDictArgs = parse_args(&request.action, &request.args)?; + let artifact = SpreadsheetArtifact::from_dict(args.data, args.artifact_id)?; + let artifact_id = artifact.artifact_id.clone(); + let snapshot = snapshot_for_artifact(&artifact); + self.documents.insert(artifact_id.clone(), artifact); + Ok(SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Deserialized workbook from dict".to_string(), + snapshot, + )) + } + + fn deserialize_json( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: DeserializeJsonArgs = parse_args(&request.action, &request.args)?; + let artifact = SpreadsheetArtifact::from_json(args.json, args.artifact_id)?; + let artifact_id = artifact.artifact_id.clone(); + let snapshot = snapshot_for_artifact(&artifact); + self.documents.insert(artifact_id.clone(), artifact); + Ok(SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Deserialized workbook from JSON".to_string(), + snapshot, + )) + } + + fn deserialize_bytes( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let args: DeserializeBytesArgs = parse_args(&request.action, &request.args)?; + let bytes = BASE64_STANDARD.decode(args.bytes_base64).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + let artifact = SpreadsheetArtifact::from_bytes(&bytes, args.artifact_id)?; + let artifact_id = artifact.artifact_id.clone(); + let snapshot = snapshot_for_artifact(&artifact); + self.documents.insert(artifact_id.clone(), artifact); + Ok(SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Deserialized workbook from bytes".to_string(), + snapshot, + )) + } + + fn delete_artifact( + &mut self, + request: SpreadsheetArtifactRequest, + ) -> Result { + let artifact_id = required_artifact_id(&request)?; + let artifact = self.documents.remove(&artifact_id).ok_or_else(|| { + SpreadsheetArtifactError::UnknownArtifactId { + action: request.action.clone(), + artifact_id: artifact_id.clone(), + } + })?; + let snapshot = snapshot_for_artifact(&artifact); + Ok(SpreadsheetArtifactResponse::new( + artifact_id, + request.action, + "Deleted spreadsheet artifact".to_string(), + snapshot, + )) + } + + fn get_artifact( + &self, + artifact_id: &str, + action: &str, + ) -> Result<&SpreadsheetArtifact, SpreadsheetArtifactError> { + self.documents + .get(artifact_id) + .ok_or_else(|| SpreadsheetArtifactError::UnknownArtifactId { + action: action.to_string(), + artifact_id: artifact_id.to_string(), + }) + } + + fn get_artifact_mut( + &mut self, + artifact_id: &str, + action: &str, + ) -> Result<&mut SpreadsheetArtifact, SpreadsheetArtifactError> { + self.documents.get_mut(artifact_id).ok_or_else(|| { + SpreadsheetArtifactError::UnknownArtifactId { + action: action.to_string(), + artifact_id: artifact_id.to_string(), + } + }) + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct SpreadsheetArtifactResponse { + pub artifact_id: String, + pub action: String, + pub summary: String, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub exported_paths: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub artifact_snapshot: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub workbook_summary: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sheet_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub chart_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub table_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub conditional_format_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub pivot_table_list: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub sheet_ref: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cell_ref: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub range_ref: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub range_format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cell: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub raw_cell: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub style_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cell_field: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub range: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub top_left_style_index: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cell_format_summary: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rendered_text: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rendered_html: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub row_height: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub serialized_dict: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub serialized_json: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub serialized_bytes_base64: Option, +} + +impl SpreadsheetArtifactResponse { + fn new( + artifact_id: String, + action: String, + summary: String, + artifact_snapshot: SpreadsheetArtifactSnapshot, + ) -> Self { + Self { + artifact_id, + action, + summary, + exported_paths: Vec::new(), + artifact_snapshot: Some(artifact_snapshot), + workbook_summary: None, + sheet_list: None, + chart_list: None, + table_list: None, + conditional_format_list: None, + pivot_table_list: None, + sheet_ref: None, + cell_ref: None, + range_ref: None, + range_format: None, + cell: None, + raw_cell: None, + style_id: None, + cell_field: None, + range: None, + top_left_style_index: None, + cell_format_summary: None, + rendered_text: None, + rendered_html: None, + row_height: None, + serialized_dict: None, + serialized_json: None, + serialized_bytes_base64: None, + } + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct SpreadsheetSheetRef { + pub sheet_name: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SpreadsheetArtifactSnapshot { + pub sheet_count: usize, + pub sheet_names: Vec, + pub sheets: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SpreadsheetSheetSnapshot { + pub sheet_id: String, + pub name: String, + pub filled_rows: usize, + pub filled_columns: usize, + pub minimum_range_filled: String, + pub merged_range_count: usize, + pub chart_count: usize, + pub table_count: usize, + pub conditional_format_count: usize, + pub pivot_table_count: usize, +} + +#[derive(Debug, Deserialize)] +struct CreateArgs { + name: Option, + auto_recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct PathArgs { + path: PathBuf, +} + +#[derive(Debug, Deserialize)] +struct SaveArgs { + path: PathBuf, + file_type: Option, +} + +#[derive(Debug, Deserialize)] +struct RenderArgs { + output_path: Option, + sheet_name: Option, + sheet_index: Option, + range: Option, + center_address: Option, + width: Option, + height: Option, + include_headers: Option, + scale: Option, + performance_mode: Option, +} + +#[derive(Debug, Deserialize)] +struct SheetLookupArgs { + sheet_name: Option, + sheet_index: Option, + range: Option, +} + +#[derive(Debug, Deserialize)] +struct ChartLookupArgs { + sheet_name: Option, + sheet_index: Option, + chart_id: Option, + chart_index: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateChartArgs { + sheet_name: Option, + sheet_index: Option, + chart_type: crate::SpreadsheetChartType, + source_sheet_name: Option, + source_range: String, + options: Option, +} + +#[derive(Debug, Deserialize)] +struct AddChartSeriesArgs { + sheet_name: Option, + sheet_index: Option, + chart_id: Option, + chart_index: Option, + series: crate::SpreadsheetChartSeries, +} + +#[derive(Debug, Deserialize)] +struct SetChartPropertiesArgs { + #[serde(flatten)] + lookup: ChartLookupArgs, + properties: crate::SpreadsheetChartProperties, +} + +#[derive(Debug, Deserialize)] +struct TableLookupArgs { + sheet_name: Option, + sheet_index: Option, + name: Option, + display_name: Option, + id: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateTableArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + options: crate::SpreadsheetCreateTableOptions, +} + +#[derive(Debug, Deserialize)] +struct SetTableStyleArgs { + #[serde(flatten)] + lookup: TableLookupArgs, + options: crate::SpreadsheetTableStyleOptions, +} + +#[derive(Debug, Deserialize)] +struct RenameTableColumnArgs { + #[serde(flatten)] + lookup: TableLookupArgs, + column_id: Option, + column_name: Option, + new_name: String, +} + +#[derive(Debug, Deserialize)] +struct SetTableColumnTotalsArgs { + #[serde(flatten)] + lookup: TableLookupArgs, + column_id: Option, + column_name: Option, + totals_row_label: Option, + totals_row_function: Option, +} + +#[derive(Debug, Deserialize)] +struct AddConditionalFormatArgs { + sheet_name: Option, + sheet_index: Option, + format: crate::SpreadsheetConditionalFormat, +} + +#[derive(Debug, Deserialize)] +struct DeleteConditionalFormatArgs { + sheet_name: Option, + sheet_index: Option, + id: u32, +} + +#[derive(Debug, Deserialize)] +struct PivotTableLookupArgs { + sheet_name: Option, + sheet_index: Option, + name: Option, + index: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateSheetArgs { + name: String, +} + +#[derive(Debug, Deserialize)] +struct RenameSheetArgs { + old_name: Option, + sheet_index: Option, + new_name: String, +} + +#[derive(Debug, Deserialize)] +struct DeleteSheetArgs { + sheet_name: Option, + sheet_index: Option, +} + +#[derive(Debug, Deserialize)] +struct SetSheetPropertiesArgs { + sheet_name: Option, + sheet_index: Option, + default_row_height: Option, + default_column_width: Option, + show_grid_lines: Option, +} + +#[derive(Debug, Deserialize)] +struct SetColumnWidthsArgs { + sheet_name: Option, + sheet_index: Option, + reference: String, + width: f64, +} + +#[derive(Debug, Deserialize)] +struct SetColumnWidthsBulkArgs { + sheet_name: Option, + sheet_index: Option, + widths: BTreeMap, +} + +#[derive(Debug, Deserialize)] +struct SetRowHeightArgs { + sheet_name: Option, + sheet_index: Option, + row_index: u32, + height: Option, +} + +#[derive(Debug, Deserialize)] +struct SetRowHeightsArgs { + sheet_name: Option, + sheet_index: Option, + start_row_index: u32, + end_row_index: u32, + height: Option, +} + +#[derive(Debug, Deserialize)] +struct SetRowHeightsBulkArgs { + sheet_name: Option, + sheet_index: Option, + heights: BTreeMap>, +} + +#[derive(Debug, Deserialize)] +struct GetRowHeightArgs { + sheet_name: Option, + sheet_index: Option, + row_index: u32, +} + +#[derive(Debug, Deserialize)] +struct CreateTextStyleArgs { + style: crate::SpreadsheetTextStyle, + source_style_id: Option, + merge_with_existing_components: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateFillArgs { + fill: crate::SpreadsheetFill, + source_fill_id: Option, + merge_with_existing_components: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateBorderArgs { + border: crate::SpreadsheetBorder, + source_border_id: Option, + merge_with_existing_components: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateNumberFormatArgs { + number_format: crate::SpreadsheetNumberFormat, + source_number_format_id: Option, + merge_with_existing_components: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateCellFormatArgs { + format: crate::SpreadsheetCellFormat, + source_format_id: Option, + merge_with_existing_components: Option, +} + +#[derive(Debug, Deserialize)] +struct CreateDifferentialFormatArgs { + format: crate::SpreadsheetDifferentialFormat, +} + +#[derive(Debug, Deserialize)] +struct GetStyleArgs { + id: u32, +} + +#[derive(Debug, Deserialize)] +struct CellAddressArgs { + sheet_name: Option, + sheet_index: Option, + address: String, +} + +#[derive(Debug, Deserialize)] +struct ReferenceArgs { + sheet_name: Option, + sheet_index: Option, + reference: String, +} + +#[derive(Debug, Deserialize)] +struct CellIndicesArgs { + sheet_name: Option, + sheet_index: Option, + column_index: u32, + row_index: u32, +} + +#[derive(Debug, Deserialize)] +struct CellFieldArgs { + sheet_name: Option, + sheet_index: Option, + address: String, + field: String, +} + +#[derive(Debug, Deserialize)] +struct CellFieldByIndicesArgs { + sheet_name: Option, + sheet_index: Option, + column_index: u32, + row_index: u32, + field: String, +} + +#[derive(Debug, Deserialize)] +struct RangeArgs { + sheet_name: Option, + sheet_index: Option, + range: String, +} + +#[derive(Debug, Deserialize)] +struct SetCellValueArgs { + sheet_name: Option, + sheet_index: Option, + address: String, + value: Value, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct SetRangeValuesArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + values: Vec>, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct SetRangeValueArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + value: Value, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct SetCellFormulaArgs { + sheet_name: Option, + sheet_index: Option, + address: String, + formula: String, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct SetRangeFormulasArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + formulas: Vec>>, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct SetRangeFormulaArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + formula: String, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct SetCellStyleArgs { + sheet_name: Option, + sheet_index: Option, + address: String, + style_index: u32, +} + +#[derive(Debug, Deserialize)] +struct SetRangeStyleArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + style_index: u32, +} + +#[derive(Debug, Deserialize)] +struct ClearRangeArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + fields: Option>, + recalculate: Option, +} + +#[derive(Debug, Deserialize)] +struct MergeRangeArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + raise_on_conflict: Option, +} + +#[derive(Debug, Deserialize)] +struct CiteRangeArgs { + sheet_name: Option, + sheet_index: Option, + range: String, + tether_id: String, + start_line: Option, + end_line: Option, + content_reference_type: Option, + source_type: Option, +} + +#[derive(Debug, Deserialize)] +struct CiteCellArgs { + sheet_name: Option, + sheet_index: Option, + address: String, + tether_id: String, + start_line: Option, + end_line: Option, + content_reference_type: Option, + source_type: Option, +} + +#[derive(Debug, Deserialize)] +struct DeserializeDictArgs { + data: Value, + artifact_id: Option, +} + +#[derive(Debug, Deserialize)] +struct DeserializeJsonArgs { + json: String, + artifact_id: Option, +} + +#[derive(Debug, Deserialize)] +struct DeserializeBytesArgs { + bytes_base64: String, + artifact_id: Option, +} + +fn snapshot_for_artifact(artifact: &SpreadsheetArtifact) -> SpreadsheetArtifactSnapshot { + SpreadsheetArtifactSnapshot { + sheet_count: artifact.sheets.len(), + sheet_names: artifact.list_sheet_names(), + sheets: artifact + .sheets + .iter() + .map(|sheet| SpreadsheetSheetSnapshot { + sheet_id: sheet.sheet_id.clone(), + name: sheet.name.clone(), + filled_rows: sheet.filled_rows(), + filled_columns: sheet.filled_columns(), + minimum_range_filled: sheet.minimum_range_filled(), + merged_range_count: sheet.merged_ranges.len(), + chart_count: sheet.charts.len(), + table_count: sheet.tables.len(), + conditional_format_count: sheet.conditional_formats.len(), + pivot_table_count: sheet.pivot_tables.len(), + }) + .collect(), + } +} + +fn chart_lookup_from_args(args: &ChartLookupArgs) -> crate::SpreadsheetChartLookup { + crate::SpreadsheetChartLookup { + id: args.chart_id, + index: args.chart_index.map(|value| value as usize), + } +} + +fn table_lookup_from_args(args: &TableLookupArgs) -> crate::SpreadsheetTableLookup<'_> { + crate::SpreadsheetTableLookup { + name: args.name.as_deref(), + display_name: args.display_name.as_deref(), + id: args.id, + } +} + +fn pivot_lookup_from_args(args: &PivotTableLookupArgs) -> crate::SpreadsheetPivotTableLookup<'_> { + crate::SpreadsheetPivotTableLookup { + name: args.name.as_deref(), + index: args.index.map(|value| value as usize), + } +} + +fn sheet_reference(sheet: &crate::SpreadsheetSheet) -> SpreadsheetSheetRef { + SpreadsheetSheetRef { + sheet_name: sheet.name.clone(), + } +} + +fn normalize_optional_cell_value( + value: Value, +) -> Result, SpreadsheetArtifactError> { + if value.is_null() { + Ok(None) + } else { + Ok(Some(SpreadsheetCellValue::try_from(value)?)) + } +} + +fn normalize_value_matrix( + values: Vec>, + action: &str, +) -> Result>>, SpreadsheetArtifactError> { + if values.is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "values matrix cannot be empty".to_string(), + }); + } + let width = values.first().map(Vec::len).unwrap_or(0); + if width == 0 || values.iter().any(|row| row.len() != width) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "values matrix must be rectangular".to_string(), + }); + } + values + .into_iter() + .map(|row| { + row.into_iter() + .map(normalize_optional_cell_value) + .collect::, _>>() + }) + .collect::, _>>() +} + +fn normalize_formula(formula: String) -> String { + let trimmed = formula.trim(); + if trimmed.starts_with('=') { + trimmed.to_string() + } else { + format!("={trimmed}") + } +} + +fn render_options_from_args( + args: RenderArgs, +) -> Result { + let scale = args.scale.unwrap_or(1.0); + if scale <= 0.0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "render".to_string(), + message: "render scale must be positive".to_string(), + }); + } + Ok(crate::SpreadsheetRenderOptions { + output_path: args.output_path, + center_address: args.center_address, + width: args.width, + height: args.height, + include_headers: args.include_headers.unwrap_or(true), + scale, + performance_mode: args.performance_mode.unwrap_or(false), + }) +} + +fn required_artifact_id( + request: &SpreadsheetArtifactRequest, +) -> Result { + request + .artifact_id + .clone() + .ok_or_else(|| SpreadsheetArtifactError::MissingArtifactId { + action: request.action.clone(), + }) +} + +fn parse_args Deserialize<'de>>( + action: &str, + value: &Value, +) -> Result { + serde_json::from_value(value.clone()).map_err(|error| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: error.to_string(), + }) +} + +fn resolve_path(cwd: &Path, path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_path_buf() + } else { + cwd.join(path) + } +} + +fn to_serialized_value(value: T) -> Result { + serde_json::to_value(value).map_err(|error| SpreadsheetArtifactError::Serialization { + message: error.to_string(), + }) +} diff --git a/codex-rs/artifact-spreadsheet/src/model.rs b/codex-rs/artifact-spreadsheet/src/model.rs new file mode 100644 index 0000000000..747eedbcea --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/model.rs @@ -0,0 +1,1787 @@ +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::path::Path; +use std::path::PathBuf; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; +use uuid::Uuid; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifactError; +use crate::formula::recalculate_workbook; +use crate::parse_column_reference; +use crate::xlsx::import_xlsx; +use crate::xlsx::write_xlsx; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SpreadsheetFileType { + Xlsx, + Json, + Binary, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum SpreadsheetCellValue { + Bool(bool), + Integer(i64), + Float(f64), + String(String), + DateTime(String), + Error(String), +} + +impl SpreadsheetCellValue { + pub fn to_json_value(&self) -> Value { + match self { + Self::Bool(value) => Value::Bool(*value), + Self::Integer(value) => Value::Number((*value).into()), + Self::Float(value) => serde_json::Number::from_f64(*value) + .map(Value::Number) + .unwrap_or_else(|| Value::String(value.to_string())), + Self::String(value) | Self::DateTime(value) | Self::Error(value) => { + Value::String(value.clone()) + } + } + } + + pub fn as_f64(&self) -> Option { + match self { + Self::Integer(value) => Some(*value as f64), + Self::Float(value) => Some(*value), + _ => None, + } + } +} + +impl TryFrom for SpreadsheetCellValue { + type Error = SpreadsheetArtifactError; + + fn try_from(value: Value) -> Result { + match value { + Value::Object(_) => serde_json::from_value(value).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + }), + Value::Bool(value) => Ok(Self::Bool(value)), + Value::Number(value) => { + if let Some(integer) = value.as_i64() { + Ok(Self::Integer(integer)) + } else if let Some(float) = value.as_f64() { + Ok(Self::Float(float)) + } else { + Err(SpreadsheetArtifactError::Serialization { + message: "unsupported JSON number".to_string(), + }) + } + } + Value::String(value) => Ok(Self::String(value)), + Value::Null => Err(SpreadsheetArtifactError::Serialization { + message: "null is represented as an empty cell, not a cell value".to_string(), + }), + other => Err(SpreadsheetArtifactError::Serialization { + message: format!("unsupported JSON cell value `{other}`"), + }), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetCitation { + pub tether_id: String, + pub start_line: Option, + pub end_line: Option, + pub content_reference_type: Option, + pub source_type: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetCell { + pub value: Option, + pub formula: Option, + pub style_index: u32, + #[serde(default)] + pub citations: Vec, +} + +impl SpreadsheetCell { + pub fn to_dict(&self) -> Result { + serde_json::to_value(self).map_err(|error| SpreadsheetArtifactError::Serialization { + message: error.to_string(), + }) + } + + pub fn data(&self) -> Option { + if let Some(formula) = &self.formula { + return Some(Value::String(formula.clone())); + } + self.value.as_ref().map(SpreadsheetCellValue::to_json_value) + } + + pub fn is_empty(&self) -> bool { + self.value.is_none() + && self.formula.is_none() + && self.style_index == 0 + && self.citations.is_empty() + } + + pub fn is_calculation_error(&self) -> bool { + matches!( + self.value, + Some(SpreadsheetCellValue::Error(ref value)) + if matches!( + value.as_str(), + "#DIV/0!" + | "#N/A" + | "#NAME?" + | "#NUM!" + | "#REF!" + | "#VALUE!" + | "#CYCLE!" + | "#ERROR!" + | "#LIC!" + ) + ) + } + + pub fn calculation_error_message(&self) -> Option<&'static str> { + match self.value.as_ref() { + Some(SpreadsheetCellValue::Error(value)) => match value.as_str() { + "#DIV/0!" => Some("Division by zero"), + "#N/A" => Some("Value is not available"), + "#NAME?" => Some("Unknown function or name"), + "#NUM!" => Some("Invalid numeric result"), + "#REF!" => Some("Invalid cell reference"), + "#VALUE!" => Some("Invalid value type"), + "#CYCLE!" => Some("Formula cycle detected"), + "#ERROR!" => Some("Formula parse error"), + "#LIC!" => Some("Calculation engine license error"), + _ => None, + }, + _ => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetCellRef { + pub sheet_name: String, + pub address: String, +} + +impl SpreadsheetCellRef { + pub fn new(sheet_name: String, address: CellAddress) -> Self { + Self { + sheet_name, + address: address.to_a1(), + } + } + + pub fn cell_address(&self) -> Result { + CellAddress::parse(&self.address) + } + + pub fn get( + &self, + sheet: &SpreadsheetSheet, + ) -> Result { + self.ensure_sheet(sheet)?; + Ok(sheet.get_cell_view(self.cell_address()?)) + } + + pub fn data( + &self, + sheet: &SpreadsheetSheet, + ) -> Result, SpreadsheetArtifactError> { + Ok(self.get(sheet)?.data) + } + + pub fn raw_cell( + &self, + sheet: &SpreadsheetSheet, + ) -> Result, SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + Ok(sheet.get_cell(self.cell_address()?).cloned()) + } + + pub fn to_dict(&self, sheet: &SpreadsheetSheet) -> Result { + Ok(match self.raw_cell(sheet)? { + Some(cell) => cell.to_dict()?, + None => Value::Object(Default::default()), + }) + } + + pub fn set_value( + &self, + sheet: &mut SpreadsheetSheet, + value: Option, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_value(self.cell_address()?, value) + } + + pub fn set_formula( + &self, + sheet: &mut SpreadsheetSheet, + formula: Option, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_formula(self.cell_address()?, formula) + } + + pub fn cite( + &self, + sheet: &mut SpreadsheetSheet, + citation: SpreadsheetCitation, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.cite_range( + &CellRange::from_start_end(self.cell_address()?, self.cell_address()?), + citation, + ) + } + + pub fn set_style_index( + &self, + sheet: &mut SpreadsheetSheet, + style_index: u32, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_style_index( + &CellRange::from_start_end(self.cell_address()?, self.cell_address()?), + style_index, + ) + } + + pub fn is_calculation_error( + &self, + sheet: &SpreadsheetSheet, + ) -> Result { + Ok(self.get(sheet)?.is_calculation_error) + } + + pub fn get_calculation_error_message( + &self, + sheet: &SpreadsheetSheet, + ) -> Result, SpreadsheetArtifactError> { + Ok(self.get(sheet)?.calculation_error_message) + } + + fn ensure_sheet(&self, sheet: &SpreadsheetSheet) -> Result<(), SpreadsheetArtifactError> { + if self.sheet_name != sheet.name { + return Err(SpreadsheetArtifactError::SheetLookup { + action: "cell_ref".to_string(), + message: format!( + "cell ref points to `{}` but sheet is `{}`", + self.sheet_name, sheet.name + ), + }); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetCellRangeRef { + pub sheet_name: String, + pub address: String, +} + +impl SpreadsheetCellRangeRef { + pub fn new(sheet_name: String, range: &CellRange) -> Self { + Self { + sheet_name, + address: range.to_a1(), + } + } + + pub fn range(&self) -> Result { + CellRange::parse(&self.address) + } + + pub fn get( + &self, + sheet: &SpreadsheetSheet, + ) -> Result { + self.ensure_sheet(sheet)?; + Ok(sheet.get_range_view(&self.range()?)) + } + + pub fn get_values( + &self, + sheet: &SpreadsheetSheet, + ) -> Result>>, SpreadsheetArtifactError> { + Ok(self.get(sheet)?.values) + } + + pub fn get_formulas( + &self, + sheet: &SpreadsheetSheet, + ) -> Result>>, SpreadsheetArtifactError> { + Ok(self.get(sheet)?.formulas) + } + + pub fn get_style_indices( + &self, + sheet: &SpreadsheetSheet, + ) -> Result>, SpreadsheetArtifactError> { + Ok(self.get(sheet)?.style_indices) + } + + pub fn get_data( + &self, + sheet: &SpreadsheetSheet, + ) -> Result>>, SpreadsheetArtifactError> { + Ok(self.get(sheet)?.data) + } + + pub fn top_left_style_index( + &self, + sheet: &SpreadsheetSheet, + ) -> Result { + self.ensure_sheet(sheet)?; + Ok(sheet.top_left_style_index(&self.range()?)) + } + + pub fn set_value( + &self, + sheet: &mut SpreadsheetSheet, + value: Option, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_range_to_value(&self.range()?, value) + } + + pub fn set_values( + &self, + sheet: &mut SpreadsheetSheet, + values: &[Vec>], + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_values_matrix(&self.range()?, values) + } + + pub fn set_formula( + &self, + sheet: &mut SpreadsheetSheet, + formula: Option, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_range_to_formula(&self.range()?, formula) + } + + pub fn set_formulas( + &self, + sheet: &mut SpreadsheetSheet, + formulas: &[Vec>], + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_formulas_matrix(&self.range()?, formulas) + } + + pub fn set_style_index( + &self, + sheet: &mut SpreadsheetSheet, + style_index: u32, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.set_style_index(&self.range()?, style_index) + } + + pub fn merge( + &self, + sheet: &mut SpreadsheetSheet, + raise_on_conflict: bool, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.merge_cells(&self.range()?, raise_on_conflict) + } + + pub fn unmerge(&self, sheet: &mut SpreadsheetSheet) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.unmerge_cells(&self.range()?); + Ok(()) + } + + pub fn cite( + &self, + sheet: &mut SpreadsheetSheet, + citation: SpreadsheetCitation, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_sheet(sheet)?; + sheet.cite_range(&self.range()?, citation) + } + + fn ensure_sheet(&self, sheet: &SpreadsheetSheet) -> Result<(), SpreadsheetArtifactError> { + if self.sheet_name != sheet.name { + return Err(SpreadsheetArtifactError::SheetLookup { + action: "range_ref".to_string(), + message: format!( + "range ref points to `{}` but sheet is `{}`", + self.sheet_name, sheet.name + ), + }); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum SpreadsheetSheetReference { + Cell { cell_ref: SpreadsheetCellRef }, + Range { range_ref: SpreadsheetCellRangeRef }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetSheetSummary { + pub name: String, + pub filled_rows: usize, + pub filled_columns: usize, + pub minimum_range_filled: String, + pub min_row_idx: Option, + pub max_row_idx: Option, + pub min_column_idx: Option, + pub max_column_idx: Option, + pub min_column_letter: Option, + pub max_column_letter: Option, + pub first_row_address_range: Option, + pub default_row_height: Option, + pub default_column_width: Option, + pub show_grid_lines: bool, + pub merged_range_count: usize, + pub chart_count: usize, + pub table_count: usize, + pub conditional_format_count: usize, + pub pivot_table_count: usize, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetSummary { + pub artifact_id: String, + pub sheets: Vec, + pub size_bytes: usize, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetCellView { + pub sheet_name: String, + pub address: String, + pub effective_address: String, + pub exists: bool, + pub value: Option, + pub formula: Option, + pub style_index: u32, + pub data: Option, + pub is_calculation_error: bool, + pub calculation_error_message: Option, + pub citations: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetRangeView { + pub sheet_name: String, + pub address: String, + pub values: Vec>>, + pub formulas: Vec>>, + pub style_indices: Vec>, + pub data: Vec>>, + pub is_single_cell: bool, + pub is_single_row: bool, + pub is_single_column: bool, + pub contains_merged_cells: bool, + pub is_exactly_one_merged_cell: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetSheet { + pub sheet_id: String, + pub name: String, + #[serde(default, with = "cell_map_serde")] + pub cells: BTreeMap, + #[serde(default)] + pub merged_ranges: Vec, + #[serde(default)] + pub charts: Vec, + #[serde(default)] + pub tables: Vec, + #[serde(default)] + pub conditional_formats: Vec, + #[serde(default)] + pub pivot_tables: Vec, + pub default_row_height: Option, + pub default_column_width: Option, + pub show_grid_lines: bool, + #[serde(default)] + pub column_widths: BTreeMap, + #[serde(default)] + pub row_heights: BTreeMap, +} + +mod cell_map_serde { + use std::collections::BTreeMap; + + use serde::Deserialize; + use serde::Deserializer; + use serde::Serialize; + use serde::Serializer; + + use crate::CellAddress; + use crate::SpreadsheetCell; + #[derive(Serialize, Deserialize)] + struct CellEntry { + address: String, + cell: SpreadsheetCell, + } + + pub fn serialize( + cells: &BTreeMap, + serializer: S, + ) -> Result + where + S: Serializer, + { + let entries = cells + .iter() + .map(|(address, cell)| CellEntry { + address: address.to_a1(), + cell: cell.clone(), + }) + .collect::>(); + entries.serialize(serializer) + } + + pub fn deserialize<'de, D>( + deserializer: D, + ) -> Result, D::Error> + where + D: Deserializer<'de>, + { + let entries = Vec::::deserialize(deserializer)?; + let mut cells = BTreeMap::new(); + for entry in entries { + let address = CellAddress::parse(&entry.address).map_err(serde::de::Error::custom)?; + cells.insert(address, entry.cell); + } + Ok(cells) + } +} + +impl SpreadsheetSheet { + pub fn new(name: String) -> Self { + Self { + sheet_id: format!("sheet_{}", Uuid::new_v4().simple()), + name, + cells: BTreeMap::new(), + merged_ranges: Vec::new(), + charts: Vec::new(), + tables: Vec::new(), + conditional_formats: Vec::new(), + pivot_tables: Vec::new(), + default_row_height: None, + default_column_width: None, + show_grid_lines: true, + column_widths: BTreeMap::new(), + row_heights: BTreeMap::new(), + } + } + + pub fn filled_rows(&self) -> usize { + self.cells + .keys() + .map(|address| address.row) + .collect::>() + .len() + } + + pub fn filled_columns(&self) -> usize { + self.cells + .keys() + .map(|address| address.column) + .collect::>() + .len() + } + + pub fn is_empty(&self) -> bool { + self.cells.is_empty() + } + + pub fn minimum_range(&self) -> Option { + let mut iter = self.cells.keys(); + let first = *iter.next()?; + let mut min_row = first.row; + let mut max_row = first.row; + let mut min_column = first.column; + let mut max_column = first.column; + + for address in iter { + min_row = min_row.min(address.row); + max_row = max_row.max(address.row); + min_column = min_column.min(address.column); + max_column = max_column.max(address.column); + } + + Some(CellRange::from_start_end( + CellAddress { + column: min_column, + row: min_row, + }, + CellAddress { + column: max_column, + row: max_row, + }, + )) + } + + pub fn minimum_range_ref(&self) -> Option { + self.minimum_range() + .map(|range| SpreadsheetCellRangeRef::new(self.name.clone(), &range)) + } + + pub fn minimum_range_filled(&self) -> String { + self.minimum_range() + .map(|range| range.to_a1()) + .unwrap_or_default() + } + + pub fn min_column_letter(&self) -> Option { + self.minimum_range() + .map(|range| crate::column_index_to_letters(range.start.column)) + } + + pub fn max_column_letter(&self) -> Option { + self.minimum_range() + .map(|range| crate::column_index_to_letters(range.end.column)) + } + + pub fn first_row_address_range(&self) -> Option { + self.minimum_range().map(|range| { + CellRange::from_start_end( + CellAddress { + column: range.start.column, + row: range.start.row, + }, + CellAddress { + column: range.end.column, + row: range.start.row, + }, + ) + .to_a1() + }) + } + + pub fn summary(&self) -> SpreadsheetSheetSummary { + let minimum = self.minimum_range(); + SpreadsheetSheetSummary { + name: self.name.clone(), + filled_rows: self.filled_rows(), + filled_columns: self.filled_columns(), + minimum_range_filled: self.minimum_range_filled(), + min_row_idx: minimum.as_ref().map(|range| range.start.row), + max_row_idx: minimum.as_ref().map(|range| range.end.row), + min_column_idx: minimum.as_ref().map(|range| range.start.column), + max_column_idx: minimum.as_ref().map(|range| range.end.column), + min_column_letter: self.min_column_letter(), + max_column_letter: self.max_column_letter(), + first_row_address_range: self.first_row_address_range(), + default_row_height: self.default_row_height, + default_column_width: self.default_column_width, + show_grid_lines: self.show_grid_lines, + merged_range_count: self.merged_ranges.len(), + chart_count: self.charts.len(), + table_count: self.tables.len(), + conditional_format_count: self.conditional_formats.len(), + pivot_table_count: self.pivot_tables.len(), + } + } + + pub fn to_dict(&self) -> Result { + serde_json::to_value(self).map_err(|error| SpreadsheetArtifactError::Serialization { + message: error.to_string(), + }) + } + + pub fn cell_ref( + &self, + address: impl AsRef, + ) -> Result { + Ok(SpreadsheetCellRef::new( + self.name.clone(), + CellAddress::parse(address.as_ref())?, + )) + } + + pub fn range_ref( + &self, + address: impl AsRef, + ) -> Result { + let range = CellRange::parse(address.as_ref())?; + Ok(SpreadsheetCellRangeRef::new(self.name.clone(), &range)) + } + + pub fn reference( + &self, + address: impl AsRef, + ) -> Result { + let address = address.as_ref(); + if let Ok(cell_ref) = self.cell_ref(address) { + return Ok(SpreadsheetSheetReference::Cell { cell_ref }); + } + Ok(SpreadsheetSheetReference::Range { + range_ref: self.range_ref(address)?, + }) + } + + pub fn set_column_widths( + &mut self, + reference: &str, + width: f64, + ) -> Result<(), SpreadsheetArtifactError> { + if width <= 0.0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "set_column_widths".to_string(), + message: "column width must be positive".to_string(), + }); + } + let (start, end) = parse_column_reference(reference)?; + for column in start..=end { + self.column_widths.insert(column, width); + } + Ok(()) + } + + pub fn set_column_widths_bulk( + &mut self, + widths: &BTreeMap, + ) -> Result<(), SpreadsheetArtifactError> { + for (reference, width) in widths { + self.set_column_widths(reference, *width)?; + } + Ok(()) + } + + pub fn get_column_width( + &self, + reference: &str, + ) -> Result, SpreadsheetArtifactError> { + let (start, end) = parse_column_reference(reference)?; + if start != end { + return Ok((start..=end) + .find_map(|column| self.column_widths.get(&column).copied()) + .or(self.default_column_width)); + } + Ok(self + .column_widths + .get(&start) + .copied() + .or(self.default_column_width)) + } + + pub fn set_row_height( + &mut self, + row_index: u32, + height: Option, + ) -> Result<(), SpreadsheetArtifactError> { + if row_index == 0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "set_row_height".to_string(), + message: "row index must be positive".to_string(), + }); + } + if let Some(height) = height { + if height <= 0.0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "set_row_height".to_string(), + message: "row height must be positive".to_string(), + }); + } + self.row_heights.insert(row_index, height); + } else { + self.row_heights.remove(&row_index); + } + Ok(()) + } + + pub fn set_row_heights( + &mut self, + start_row_index: u32, + end_row_index: u32, + height: Option, + ) -> Result<(), SpreadsheetArtifactError> { + if start_row_index == 0 || end_row_index == 0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "set_row_heights".to_string(), + message: "row indices must be positive".to_string(), + }); + } + let start = start_row_index.min(end_row_index); + let end = start_row_index.max(end_row_index); + for row_index in start..=end { + self.set_row_height(row_index, height)?; + } + Ok(()) + } + + pub fn set_row_heights_bulk( + &mut self, + heights: &BTreeMap>, + ) -> Result<(), SpreadsheetArtifactError> { + for (row_index, height) in heights { + self.set_row_height(*row_index, *height)?; + } + Ok(()) + } + + pub fn get_row_height(&self, row_index: u32) -> Option { + self.row_heights + .get(&row_index) + .copied() + .or(self.default_row_height) + } + + pub fn cell_exists(&self, address: CellAddress) -> bool { + self.cells.contains_key(&address) + } + + pub fn merged_range_for(&self, address: CellAddress) -> Option<&CellRange> { + self.merged_ranges + .iter() + .find(|range| range.contains(address)) + } + + pub fn effective_address(&self, address: CellAddress) -> CellAddress { + self.merged_range_for(address) + .map(|range| range.start) + .unwrap_or(address) + } + + pub fn get_cell(&self, address: CellAddress) -> Option<&SpreadsheetCell> { + let effective = self.effective_address(address); + self.cells.get(&effective) + } + + pub fn get_cell_by_indices(&self, column: u32, row: u32) -> Option<&SpreadsheetCell> { + self.get_cell(CellAddress { column, row }) + } + + pub fn get_cell_mut(&mut self, address: CellAddress) -> Option<&mut SpreadsheetCell> { + let effective = self.effective_address(address); + self.cells.get_mut(&effective) + } + + pub fn get_or_create_cell_mut(&mut self, address: CellAddress) -> &mut SpreadsheetCell { + let effective = self.effective_address(address); + self.cells.entry(effective).or_insert(SpreadsheetCell { + value: None, + formula: None, + style_index: 0, + citations: Vec::new(), + }) + } + + pub fn clear_range( + &mut self, + range: &CellRange, + fields: Option<&[String]>, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, false, "clear_range")?; + for address in range.addresses() { + if let Some(cell) = self.get_cell_mut(address) { + match fields { + Some(fields) => { + for field in fields { + match field.as_str() { + "value" => cell.value = None, + "formula" => cell.formula = None, + "style_index" => cell.style_index = 0, + "citations" => cell.citations.clear(), + other => { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "clear_range".to_string(), + message: format!("unsupported cell field `{other}`"), + }); + } + } + } + } + None => { + cell.value = None; + cell.formula = None; + cell.style_index = 0; + cell.citations.clear(); + } + } + } + } + self.cells.retain(|_, cell| !cell.is_empty()); + Ok(()) + } + + pub fn set_value( + &mut self, + address: CellAddress, + value: Option, + ) -> Result<(), SpreadsheetArtifactError> { + let range = CellRange::from_start_end(address, address); + self.ensure_range_write_allowed(&range, false, "set_value")?; + let cell = self.get_or_create_cell_mut(address); + cell.formula = None; + cell.value = value; + if cell.is_empty() { + self.cells.remove(&address); + } + Ok(()) + } + + pub fn set_range_to_value( + &mut self, + range: &CellRange, + value: Option, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, false, "set_range_to_value")?; + for address in range.addresses() { + let cell = self.get_or_create_cell_mut(address); + cell.formula = None; + cell.value = value.clone(); + } + self.cells.retain(|_, cell| !cell.is_empty()); + Ok(()) + } + + pub fn set_formula( + &mut self, + address: CellAddress, + formula: Option, + ) -> Result<(), SpreadsheetArtifactError> { + let range = CellRange::from_start_end(address, address); + self.ensure_range_write_allowed(&range, false, "set_formula")?; + let cell = self.get_or_create_cell_mut(address); + cell.formula = formula; + if cell.formula.is_none() { + cell.value = None; + } + if cell.is_empty() { + self.cells.remove(&address); + } + Ok(()) + } + + pub fn set_range_to_formula( + &mut self, + range: &CellRange, + formula: Option, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, false, "set_range_to_formula")?; + for address in range.addresses() { + let cell = self.get_or_create_cell_mut(address); + cell.formula = formula.clone(); + } + self.cells.retain(|_, cell| !cell.is_empty()); + Ok(()) + } + + pub fn set_cell_values_to( + &mut self, + address: &str, + value: Option, + ) -> Result<(), SpreadsheetArtifactError> { + let range = CellRange::parse(address)?; + self.set_range_to_value(&range, value) + } + + pub fn set_cell_formulas_to( + &mut self, + address: &str, + formula: Option, + ) -> Result<(), SpreadsheetArtifactError> { + let range = CellRange::parse(address)?; + self.set_range_to_formula(&range, formula) + } + + pub fn set_style_index( + &mut self, + range: &CellRange, + style_index: u32, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, false, "set_style_index")?; + for address in range.addresses() { + let cell = self.get_or_create_cell_mut(address); + cell.style_index = style_index; + } + self.cells.retain(|_, cell| !cell.is_empty()); + Ok(()) + } + + pub fn cite_range( + &mut self, + range: &CellRange, + citation: SpreadsheetCitation, + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, true, "cite_range")?; + for address in range.addresses() { + let cell = self.get_or_create_cell_mut(address); + cell.citations.push(citation.clone()); + } + Ok(()) + } + + pub fn set_values_matrix( + &mut self, + range: &CellRange, + values: &[Vec>], + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, false, "set_values_matrix")?; + if values.len() != range.height() || values.iter().any(|row| row.len() != range.width()) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "set_range_values".to_string(), + message: format!( + "matrix dimensions {}x{} do not match range {}x{}", + values.len(), + values.first().map(Vec::len).unwrap_or(0), + range.height(), + range.width() + ), + }); + } + + for (row_offset, row) in values.iter().enumerate() { + for (column_offset, value) in row.iter().enumerate() { + let address = CellAddress { + column: range.start.column + column_offset as u32, + row: range.start.row + row_offset as u32, + }; + let cell = self.get_or_create_cell_mut(address); + cell.formula = None; + cell.value = value.clone(); + } + } + self.cells.retain(|_, cell| !cell.is_empty()); + Ok(()) + } + + pub fn set_formulas_matrix( + &mut self, + range: &CellRange, + formulas: &[Vec>], + ) -> Result<(), SpreadsheetArtifactError> { + self.ensure_range_write_allowed(range, false, "set_formulas_matrix")?; + if formulas.len() != range.height() || formulas.iter().any(|row| row.len() != range.width()) + { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "set_range_formulas".to_string(), + message: format!( + "matrix dimensions {}x{} do not match range {}x{}", + formulas.len(), + formulas.first().map(Vec::len).unwrap_or(0), + range.height(), + range.width() + ), + }); + } + + for (row_offset, row) in formulas.iter().enumerate() { + for (column_offset, formula) in row.iter().enumerate() { + let address = CellAddress { + column: range.start.column + column_offset as u32, + row: range.start.row + row_offset as u32, + }; + let cell = self.get_or_create_cell_mut(address); + cell.formula = formula.clone(); + } + } + self.cells.retain(|_, cell| !cell.is_empty()); + Ok(()) + } + + pub fn merge_cells( + &mut self, + range: &CellRange, + raise_on_conflict: bool, + ) -> Result<(), SpreadsheetArtifactError> { + for existing in &self.merged_ranges { + if existing.intersects(range) && existing != range { + if raise_on_conflict { + return Err(SpreadsheetArtifactError::MergeConflict { + action: "merge_range".to_string(), + range: range.to_a1(), + conflict: existing.to_a1(), + }); + } + return Ok(()); + } + } + self.merged_ranges.push(range.clone()); + self.merged_ranges + .sort_by_key(|entry| (entry.start.row, entry.start.column)); + Ok(()) + } + + pub fn unmerge_cells(&mut self, range: &CellRange) { + self.merged_ranges.retain(|entry| entry != range); + } + + pub fn contains_merged_cells(&self, range: &CellRange) -> bool { + self.merged_ranges + .iter() + .any(|entry| entry.intersects(range)) + } + + pub fn is_exactly_one_merged_cell(&self, range: &CellRange) -> bool { + self.merged_ranges.iter().any(|entry| entry == range) + } + + pub fn get_cell_view(&self, address: CellAddress) -> SpreadsheetCellView { + let effective = self.effective_address(address); + let cell = self.get_cell(address); + SpreadsheetCellView { + sheet_name: self.name.clone(), + address: address.to_a1(), + effective_address: effective.to_a1(), + exists: cell.is_some(), + value: cell.and_then(|entry| entry.value.clone()), + formula: cell.and_then(|entry| entry.formula.clone()), + style_index: cell.map(|entry| entry.style_index).unwrap_or(0), + data: cell.and_then(SpreadsheetCell::data), + is_calculation_error: cell + .map(SpreadsheetCell::is_calculation_error) + .unwrap_or(false), + calculation_error_message: cell + .and_then(SpreadsheetCell::calculation_error_message) + .map(str::to_string), + citations: cell + .map(|entry| entry.citations.clone()) + .unwrap_or_default(), + } + } + + pub fn get_cell_view_by_indices(&self, column: u32, row: u32) -> SpreadsheetCellView { + self.get_cell_view(CellAddress { column, row }) + } + + pub fn get_cell_field( + &self, + address: CellAddress, + field: &str, + ) -> Result, SpreadsheetArtifactError> { + let cell = self.get_cell(address); + Ok(match field { + "value" => cell.and_then(|entry| { + entry + .value + .as_ref() + .map(SpreadsheetCellValue::to_json_value) + }), + "formula" => cell.and_then(|entry| entry.formula.clone().map(Value::String)), + "style_index" => cell.map(|entry| Value::Number(entry.style_index.into())), + "data" => cell.and_then(SpreadsheetCell::data), + "citations" => cell + .map(|entry| serde_json::to_value(&entry.citations)) + .transpose() + .map_err(|error| SpreadsheetArtifactError::Serialization { + message: error.to_string(), + })?, + other => { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "get_cell_field".to_string(), + message: format!("unsupported field `{other}`"), + }); + } + }) + } + + pub fn get_cell_field_by_indices( + &self, + column: u32, + row: u32, + field: &str, + ) -> Result, SpreadsheetArtifactError> { + self.get_cell_field(CellAddress { column, row }, field) + } + + pub fn get_raw_cell(&self, address: CellAddress) -> Option { + self.get_cell(address).cloned() + } + + pub fn top_left_style_index(&self, range: &CellRange) -> u32 { + self.get_cell(range.start) + .map(|cell| cell.style_index) + .unwrap_or(0) + } + + pub fn get_range_view(&self, range: &CellRange) -> SpreadsheetRangeView { + let mut values = Vec::new(); + let mut formulas = Vec::new(); + let mut style_indices = Vec::new(); + let mut data = Vec::new(); + + for row in range.start.row..=range.end.row { + let mut value_row = Vec::new(); + let mut formula_row = Vec::new(); + let mut style_row = Vec::new(); + let mut data_row = Vec::new(); + for column in range.start.column..=range.end.column { + let cell = self.get_cell(CellAddress { column, row }); + value_row.push(cell.and_then(|entry| entry.value.clone())); + formula_row.push(cell.and_then(|entry| entry.formula.clone())); + style_row.push(cell.map(|entry| entry.style_index).unwrap_or(0)); + data_row.push(cell.and_then(SpreadsheetCell::data)); + } + values.push(value_row); + formulas.push(formula_row); + style_indices.push(style_row); + data.push(data_row); + } + + SpreadsheetRangeView { + sheet_name: self.name.clone(), + address: range.to_a1(), + values, + formulas, + style_indices, + data, + is_single_cell: range.is_single_cell(), + is_single_row: range.is_single_row(), + is_single_column: range.is_single_column(), + contains_merged_cells: self.contains_merged_cells(range), + is_exactly_one_merged_cell: self.is_exactly_one_merged_cell(range), + } + } + + pub fn to_rendered_text(&self, range: Option<&CellRange>) -> String { + let target = range + .cloned() + .or_else(|| self.minimum_range()) + .unwrap_or_else(|| { + CellRange::from_start_end( + CellAddress { column: 1, row: 1 }, + CellAddress { column: 1, row: 1 }, + ) + }); + let mut lines = Vec::new(); + for row in target.start.row..=target.end.row { + let mut entries = Vec::new(); + for column in target.start.column..=target.end.column { + let view = self.get_cell_view(CellAddress { column, row }); + let text = match view.data { + Some(Value::String(value)) => value, + Some(Value::Bool(value)) => value.to_string(), + Some(Value::Number(value)) => value.to_string(), + Some(Value::Null) | None => String::new(), + Some(other) => other.to_string(), + }; + entries.push(text); + } + lines.push(entries.join("\t")); + } + lines.join("\n") + } + + pub fn cleanup_and_validate_sheet(&mut self) -> Result<(), SpreadsheetArtifactError> { + self.cells.retain(|_, cell| !cell.is_empty()); + + for (column, width) in &self.column_widths { + if *column == 0 || *width <= 0.0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "cleanup_and_validate_sheet".to_string(), + message: format!("invalid column width entry for column {column}"), + }); + } + } + for (row, height) in &self.row_heights { + if *row == 0 || *height <= 0.0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "cleanup_and_validate_sheet".to_string(), + message: format!("invalid row height entry for row {row}"), + }); + } + } + + self.merged_ranges.sort_by_key(|range| { + ( + range.start.row, + range.start.column, + range.end.row, + range.end.column, + ) + }); + self.merged_ranges.dedup(); + for index in 0..self.merged_ranges.len() { + for other in index + 1..self.merged_ranges.len() { + if self.merged_ranges[index].intersects(&self.merged_ranges[other]) { + return Err(SpreadsheetArtifactError::MergeConflict { + action: "cleanup_and_validate_sheet".to_string(), + range: self.merged_ranges[index].to_a1(), + conflict: self.merged_ranges[other].to_a1(), + }); + } + } + } + self.validate_tables("cleanup_and_validate_sheet")?; + self.validate_charts("cleanup_and_validate_sheet")?; + self.validate_pivot_tables("cleanup_and_validate_sheet")?; + Ok(()) + } + + fn ensure_range_write_allowed( + &self, + range: &CellRange, + allow_exact_merged_cell: bool, + action: &str, + ) -> Result<(), SpreadsheetArtifactError> { + for merged in &self.merged_ranges { + if !merged.intersects(range) { + continue; + } + if allow_exact_merged_cell && merged == range { + continue; + } + if merged.contains_range(range) || range.contains_range(merged) { + if allow_exact_merged_cell || merged != range { + return Err(SpreadsheetArtifactError::MergeConflict { + action: action.to_string(), + range: range.to_a1(), + conflict: merged.to_a1(), + }); + } + } else { + return Err(SpreadsheetArtifactError::MergeConflict { + action: action.to_string(), + range: range.to_a1(), + conflict: merged.to_a1(), + }); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetArtifact { + pub artifact_id: String, + pub name: Option, + #[serde(default)] + pub sheets: Vec, + pub auto_recalculate: bool, + #[serde(default)] + pub text_styles: BTreeMap, + #[serde(default)] + pub fills: BTreeMap, + #[serde(default)] + pub borders: BTreeMap, + #[serde(default)] + pub number_formats: BTreeMap, + #[serde(default)] + pub cell_formats: BTreeMap, + #[serde(default)] + pub differential_formats: BTreeMap, +} + +impl SpreadsheetArtifact { + pub fn new(name: Option) -> Self { + Self { + artifact_id: format!("spreadsheet_{}", Uuid::new_v4().simple()), + name, + sheets: Vec::new(), + auto_recalculate: false, + text_styles: BTreeMap::new(), + fills: BTreeMap::new(), + borders: BTreeMap::new(), + number_formats: BTreeMap::new(), + cell_formats: BTreeMap::new(), + differential_formats: BTreeMap::new(), + } + } + + pub fn allowed_file_extensions() -> &'static [&'static str] { + &["xlsx", "json", "bin"] + } + + pub fn allowed_file_mime_types() -> &'static [&'static str] { + &[ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/json", + "application/octet-stream", + ] + } + + pub fn allowed_file_types() -> &'static [SpreadsheetFileType] { + &[ + SpreadsheetFileType::Xlsx, + SpreadsheetFileType::Json, + SpreadsheetFileType::Binary, + ] + } + + pub fn get_output_file_name( + &self, + suffix: Option<&str>, + file_type: SpreadsheetFileType, + ) -> String { + let extension = match file_type { + SpreadsheetFileType::Xlsx => "xlsx", + SpreadsheetFileType::Json => "json", + SpreadsheetFileType::Binary => "bin", + }; + match suffix { + Some(suffix) => format!("{}_{}.{}", self.artifact_id, suffix, extension), + None => format!("{}.{}", self.artifact_id, extension), + } + } + + pub fn create_sheet( + &mut self, + name: String, + ) -> Result<&mut SpreadsheetSheet, SpreadsheetArtifactError> { + if name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "create_sheet".to_string(), + message: "sheet name cannot be empty".to_string(), + }); + } + if self.sheets.iter().any(|sheet| sheet.name == name) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "create_sheet".to_string(), + message: format!("sheet `{name}` already exists"), + }); + } + self.sheets.push(SpreadsheetSheet::new(name)); + self.sheets + .last_mut() + .ok_or_else(|| SpreadsheetArtifactError::Serialization { + message: "created sheet was not available".to_string(), + }) + } + + pub fn get_sheet(&self, name: Option<&str>, index: Option) -> Option<&SpreadsheetSheet> { + if let Some(name) = name { + self.sheets.iter().find(|sheet| sheet.name == name) + } else if let Some(index) = index { + self.sheets.get(index) + } else { + None + } + } + + pub fn get_sheet_mut( + &mut self, + name: Option<&str>, + index: Option, + ) -> Option<&mut SpreadsheetSheet> { + if let Some(name) = name { + self.sheets.iter_mut().find(|sheet| sheet.name == name) + } else if let Some(index) = index { + self.sheets.get_mut(index) + } else { + None + } + } + + pub fn sheet_lookup( + &self, + action: &str, + name: Option<&str>, + index: Option, + ) -> Result<&SpreadsheetSheet, SpreadsheetArtifactError> { + self.get_sheet(name, index) + .ok_or_else(|| SpreadsheetArtifactError::SheetLookup { + action: action.to_string(), + message: match (name, index) { + (Some(name), _) => format!("sheet `{name}` was not found"), + (None, Some(index)) => format!("sheet index {index} was not found"), + (None, None) => "sheet name or index is required".to_string(), + }, + }) + } + + pub fn sheet_lookup_mut( + &mut self, + action: &str, + name: Option<&str>, + index: Option, + ) -> Result<&mut SpreadsheetSheet, SpreadsheetArtifactError> { + self.get_sheet_mut(name, index) + .ok_or_else(|| SpreadsheetArtifactError::SheetLookup { + action: action.to_string(), + message: match (name, index) { + (Some(name), _) => format!("sheet `{name}` was not found"), + (None, Some(index)) => format!("sheet index {index} was not found"), + (None, None) => "sheet name or index is required".to_string(), + }, + }) + } + + pub fn rename_sheet( + &mut self, + new_name: String, + old_name: Option<&str>, + index: Option, + ) -> Result<(), SpreadsheetArtifactError> { + if self.sheets.iter().any(|sheet| sheet.name == new_name) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "rename_sheet".to_string(), + message: format!("sheet `{new_name}` already exists"), + }); + } + let sheet = self.sheet_lookup_mut("rename_sheet", old_name, index)?; + sheet.name = new_name; + Ok(()) + } + + pub fn delete_sheet( + &mut self, + name: Option<&str>, + index: Option, + ) -> Result<(), SpreadsheetArtifactError> { + let remove_index = if let Some(name) = name { + self.sheets + .iter() + .position(|sheet| sheet.name == name) + .ok_or_else(|| SpreadsheetArtifactError::SheetLookup { + action: "delete_sheet".to_string(), + message: format!("sheet `{name}` was not found"), + })? + } else if let Some(index) = index { + if index >= self.sheets.len() { + return Err(SpreadsheetArtifactError::IndexOutOfRange { + action: "delete_sheet".to_string(), + index, + len: self.sheets.len(), + }); + } + index + } else { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: "delete_sheet".to_string(), + message: "sheet name or index is required".to_string(), + }); + }; + self.sheets.remove(remove_index); + Ok(()) + } + + pub fn list_sheet_names(&self) -> Vec { + self.sheets.iter().map(|sheet| sheet.name.clone()).collect() + } + + pub fn summary(&self) -> SpreadsheetSummary { + SpreadsheetSummary { + artifact_id: self.artifact_id.clone(), + sheets: self.sheets.iter().map(SpreadsheetSheet::summary).collect(), + size_bytes: self.to_bytes().len(), + } + } + + pub fn calculate(&mut self) { + recalculate_workbook(self); + } + + pub fn recalculate(&mut self) { + self.calculate(); + } + + pub fn to_dict(&self) -> Result { + serde_json::to_value(self).map_err(|error| SpreadsheetArtifactError::Serialization { + message: error.to_string(), + }) + } + + pub fn to_json(&self) -> Result { + serde_json::to_string_pretty(self).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + }) + } + + pub fn to_bytes(&self) -> Vec { + self.to_json() + .unwrap_or_else(|_| "{}".to_string()) + .into_bytes() + } + + pub fn to_bytes_base64(&self) -> String { + BASE64_STANDARD.encode(self.to_bytes()) + } + + pub fn from_dict( + data: Value, + artifact_id: Option, + ) -> Result { + let mut artifact: Self = serde_json::from_value(data).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + if let Some(artifact_id) = artifact_id { + artifact.artifact_id = artifact_id; + } else if artifact.artifact_id.is_empty() { + artifact.artifact_id = format!("spreadsheet_{}", Uuid::new_v4().simple()); + } + Ok(artifact) + } + + pub fn from_json( + json: impl AsRef<[u8]>, + artifact_id: Option, + ) -> Result { + let text = std::str::from_utf8(json.as_ref()).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + Self::from_dict( + serde_json::from_str(text).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?, + artifact_id, + ) + } + + pub fn from_bytes( + bytes: &[u8], + artifact_id: Option, + ) -> Result { + Self::from_json(bytes, artifact_id) + } + + pub fn from_source_file( + path: &Path, + artifact_id: Option, + ) -> Result { + match path + .extension() + .and_then(|value| value.to_str()) + .unwrap_or_default() + .to_ascii_lowercase() + .as_str() + { + "xlsx" => import_xlsx(path, artifact_id), + "json" => { + let bytes = std::fs::read(path).map_err(|error| { + SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + Self::from_json(bytes, artifact_id) + } + "bin" => { + let bytes = std::fs::read(path).map_err(|error| { + SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + Self::from_bytes(&bytes, artifact_id) + } + other => Err(SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: format!("unsupported import file type `{other}`"), + }), + } + } + + pub fn read( + path: &Path, + artifact_id: Option, + ) -> Result { + Self::from_source_file(path, artifact_id) + } + + pub fn load( + path: &Path, + artifact_id: Option, + ) -> Result { + Self::from_source_file(path, artifact_id) + } + + pub fn save( + &mut self, + path: &Path, + file_type: Option<&str>, + ) -> Result { + self.to_source_file(path, file_type) + } + + pub fn export(&mut self, path: &Path) -> Result { + self.to_source_file(path, Some("xlsx")) + } + + pub fn to_source_file( + &mut self, + path: &Path, + file_type: Option<&str>, + ) -> Result { + let selected = file_type + .map(str::to_string) + .or_else(|| { + path.extension() + .and_then(|value| value.to_str()) + .map(str::to_string) + }) + .unwrap_or_else(|| "xlsx".to_string()) + .to_ascii_lowercase(); + + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + } + + match selected.as_str() { + "xlsx" => { + for sheet in &self.sheets { + if !sheet.charts.is_empty() + || !sheet.tables.is_empty() + || !sheet.conditional_formats.is_empty() + || !sheet.pivot_tables.is_empty() + { + return Err(SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: format!( + "xlsx export does not yet support charts, tables, conditional formats, or pivot tables on sheet `{}`; use json or bin export instead", + sheet.name + ), + }); + } + } + write_xlsx(self, path) + } + "json" => { + let json = self.to_json()?; + std::fs::write(path, json).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + Ok(path.to_path_buf()) + } + "bin" => { + std::fs::write(path, self.to_bytes()).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + Ok(path.to_path_buf()) + } + other => Err(SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: format!("unsupported export file type `{other}`"), + }), + } + } +} diff --git a/codex-rs/artifact-spreadsheet/src/pivot.rs b/codex-rs/artifact-spreadsheet/src/pivot.rs new file mode 100644 index 0000000000..c0c42985c9 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/pivot.rs @@ -0,0 +1,177 @@ +use std::collections::BTreeMap; + +use serde::Deserialize; +use serde::Serialize; + +use crate::CellRange; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCellRangeRef; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotFieldItem { + pub item_type: Option, + pub index: Option, + pub hidden: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotField { + pub index: u32, + pub name: Option, + pub axis: Option, + #[serde(default)] + pub items: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotFieldReference { + pub field_index: u32, + pub field_name: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotPageField { + pub field_index: u32, + pub field_name: Option, + pub selected_item: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotDataField { + pub field_index: u32, + pub field_name: Option, + pub name: Option, + pub subtotal: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotFilter { + pub field_index: Option, + pub field_name: Option, + pub filter_type: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotTable { + pub name: String, + pub cache_id: u32, + pub address: Option, + #[serde(default)] + pub row_fields: Vec, + #[serde(default)] + pub column_fields: Vec, + #[serde(default)] + pub page_fields: Vec, + #[serde(default)] + pub data_fields: Vec, + #[serde(default)] + pub filters: Vec, + #[serde(default)] + pub pivot_fields: Vec, + pub style_name: Option, + pub part_path: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct SpreadsheetPivotTableLookup<'a> { + pub name: Option<&'a str>, + pub index: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetPivotCacheDefinition { + pub definition_path: String, + #[serde(default)] + pub field_names: Vec>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SpreadsheetPivotPreservation { + #[serde(default)] + pub caches: BTreeMap, + #[serde(default)] + pub parts: BTreeMap, +} + +impl SpreadsheetPivotTable { + pub fn range(&self) -> Result, SpreadsheetArtifactError> { + self.address.as_deref().map(CellRange::parse).transpose() + } + + pub fn range_ref( + &self, + sheet_name: &str, + ) -> Result, SpreadsheetArtifactError> { + Ok(self + .range()? + .map(|range| SpreadsheetCellRangeRef::new(sheet_name.to_string(), &range))) + } +} + +impl SpreadsheetSheet { + pub fn list_pivot_tables( + &self, + range: Option<&CellRange>, + ) -> Result, SpreadsheetArtifactError> { + Ok(self + .pivot_tables + .iter() + .filter(|pivot_table| { + range.is_none_or(|target| { + pivot_table + .range() + .ok() + .flatten() + .is_some_and(|pivot_range| pivot_range.intersects(target)) + }) + }) + .cloned() + .collect()) + } + + pub fn get_pivot_table( + &self, + action: &str, + lookup: SpreadsheetPivotTableLookup, + ) -> Result<&SpreadsheetPivotTable, SpreadsheetArtifactError> { + if let Some(name) = lookup.name { + return self + .pivot_tables + .iter() + .find(|pivot_table| pivot_table.name == name) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("pivot table `{name}` was not found"), + }); + } + if let Some(index) = lookup.index { + return self.pivot_tables.get(index).ok_or_else(|| { + SpreadsheetArtifactError::IndexOutOfRange { + action: action.to_string(), + index, + len: self.pivot_tables.len(), + } + }); + } + Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "pivot table name or index is required".to_string(), + }) + } + + pub fn validate_pivot_tables(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { + for pivot_table in &self.pivot_tables { + if pivot_table.name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "pivot table name cannot be empty".to_string(), + }); + } + if let Some(address) = &pivot_table.address { + CellRange::parse(address)?; + } + } + Ok(()) + } +} diff --git a/codex-rs/artifact-spreadsheet/src/render.rs b/codex-rs/artifact-spreadsheet/src/render.rs new file mode 100644 index 0000000000..05e41b6083 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/render.rs @@ -0,0 +1,373 @@ +use std::fs; +use std::path::Path; +use std::path::PathBuf; + +use serde::Deserialize; +use serde::Serialize; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetRenderOptions { + pub output_path: Option, + pub center_address: Option, + pub width: Option, + pub height: Option, + pub include_headers: bool, + pub scale: f64, + pub performance_mode: bool, +} + +impl Default for SpreadsheetRenderOptions { + fn default() -> Self { + Self { + output_path: None, + center_address: None, + width: None, + height: None, + include_headers: true, + scale: 1.0, + performance_mode: false, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SpreadsheetRenderedOutput { + pub path: PathBuf, + pub html: String, +} + +impl SpreadsheetSheet { + pub fn render_html( + &self, + range: Option<&CellRange>, + options: &SpreadsheetRenderOptions, + ) -> Result { + let center = options + .center_address + .as_deref() + .map(CellAddress::parse) + .transpose()?; + let viewport = render_viewport(self, range, center, options)?; + let title = range + .map(CellRange::to_a1) + .unwrap_or_else(|| self.name.clone()); + Ok(format!( + concat!( + "", + "{}", + "", + "", + "
", + "

{}

{}

", + "
", + "{}
", + "
" + ), + html_escape(&title), + preview_css(), + html_escape(&self.name), + options.performance_mode, + html_escape(&title), + html_escape(&viewport.to_a1()), + viewport_style(options), + render_table(self, &viewport, options), + )) + } +} + +impl SpreadsheetArtifact { + pub fn render_workbook_previews( + &self, + cwd: &Path, + options: &SpreadsheetRenderOptions, + ) -> Result, SpreadsheetArtifactError> { + let sheets = if self.sheets.is_empty() { + vec![SpreadsheetSheet::new("Sheet1".to_string())] + } else { + self.sheets.clone() + }; + let output_paths = workbook_output_paths(self, cwd, options, &sheets); + sheets + .iter() + .zip(output_paths) + .map(|(sheet, path)| { + let html = sheet.render_html(None, options)?; + write_rendered_output(&path, &html)?; + Ok(SpreadsheetRenderedOutput { path, html }) + }) + .collect() + } + + pub fn render_sheet_preview( + &self, + cwd: &Path, + sheet: &SpreadsheetSheet, + options: &SpreadsheetRenderOptions, + ) -> Result { + let path = single_output_path( + cwd, + self, + options.output_path.as_deref(), + &format!("render_{}", sanitize_file_component(&sheet.name)), + ); + let html = sheet.render_html(None, options)?; + write_rendered_output(&path, &html)?; + Ok(SpreadsheetRenderedOutput { path, html }) + } + + pub fn render_range_preview( + &self, + cwd: &Path, + sheet: &SpreadsheetSheet, + range: &CellRange, + options: &SpreadsheetRenderOptions, + ) -> Result { + let path = single_output_path( + cwd, + self, + options.output_path.as_deref(), + &format!( + "render_{}_{}", + sanitize_file_component(&sheet.name), + sanitize_file_component(&range.to_a1()) + ), + ); + let html = sheet.render_html(Some(range), options)?; + write_rendered_output(&path, &html)?; + Ok(SpreadsheetRenderedOutput { path, html }) + } +} + +fn render_viewport( + sheet: &SpreadsheetSheet, + range: Option<&CellRange>, + center: Option, + options: &SpreadsheetRenderOptions, +) -> Result { + let base = range + .cloned() + .or_else(|| sheet.minimum_range()) + .unwrap_or_else(|| { + CellRange::from_start_end( + CellAddress { column: 1, row: 1 }, + CellAddress { column: 1, row: 1 }, + ) + }); + let Some(center) = center else { + return Ok(base); + }; + let visible_columns = options + .width + .map(|width| estimated_visible_count(width, 96.0, options.scale)) + .unwrap_or(base.width() as u32); + let visible_rows = options + .height + .map(|height| estimated_visible_count(height, 28.0, options.scale)) + .unwrap_or(base.height() as u32); + + let half_columns = visible_columns / 2; + let half_rows = visible_rows / 2; + let start_column = center + .column + .saturating_sub(half_columns) + .max(base.start.column); + let start_row = center.row.saturating_sub(half_rows).max(base.start.row); + let end_column = (start_column + visible_columns.saturating_sub(1)).min(base.end.column); + let end_row = (start_row + visible_rows.saturating_sub(1)).min(base.end.row); + Ok(CellRange::from_start_end( + CellAddress { + column: start_column, + row: start_row, + }, + CellAddress { + column: end_column.max(start_column), + row: end_row.max(start_row), + }, + )) +} + +fn estimated_visible_count(dimension: u32, cell_size: f64, scale: f64) -> u32 { + ((dimension as f64 / (cell_size * scale.max(0.1))).floor() as u32).max(1) +} + +fn render_table( + sheet: &SpreadsheetSheet, + range: &CellRange, + options: &SpreadsheetRenderOptions, +) -> String { + let mut rows = Vec::new(); + if options.include_headers { + let mut header = vec!["".to_string()]; + for column in range.start.column..=range.end.column { + header.push(format!( + "{}", + crate::column_index_to_letters(column) + )); + } + header.push("".to_string()); + rows.push(header.join("")); + } + for row in range.start.row..=range.end.row { + let mut cells = Vec::new(); + if options.include_headers { + cells.push(format!("{row}")); + } + for column in range.start.column..=range.end.column { + let address = CellAddress { column, row }; + let view = sheet.get_cell_view(address); + let value = view + .data + .as_ref() + .map(render_data_value) + .unwrap_or_default(); + cells.push(format!( + "{}", + address.to_a1(), + view.style_index, + html_escape(&value) + )); + } + rows.push(format!("{}", cells.join(""))); + } + rows.join("") +} + +fn render_data_value(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(value) => value.clone(), + serde_json::Value::Bool(value) => value.to_string(), + serde_json::Value::Number(value) => value.to_string(), + serde_json::Value::Null => String::new(), + other => other.to_string(), + } +} + +fn viewport_style(options: &SpreadsheetRenderOptions) -> String { + let mut style = vec![ + format!("--scale: {}", options.scale.max(0.1)), + format!( + "--headers: {}", + if options.include_headers { "1" } else { "0" } + ), + ]; + if let Some(width) = options.width { + style.push(format!("width: {width}px")); + } + if let Some(height) = options.height { + style.push(format!("height: {height}px")); + } + style.push("overflow: auto".to_string()); + style.join("; ") +} + +fn preview_css() -> &'static str { + concat!( + "body{margin:0;padding:24px;background:#f5f3ee;color:#1e1e1e;font-family:Georgia,serif;}", + ".spreadsheet-preview{display:flex;flex-direction:column;gap:16px;}", + "header h1{margin:0;font-size:24px;}header p{margin:0;color:#6b6257;font-size:13px;}", + ".viewport{border:1px solid #d6d0c7;background:#fff;box-shadow:0 12px 30px rgba(0,0,0,.08);}", + "table{border-collapse:collapse;transform:scale(var(--scale));transform-origin:top left;}", + "th,td{border:1px solid #ddd3c6;padding:6px 10px;min-width:72px;max-width:240px;font-size:13px;text-align:left;vertical-align:top;}", + "th{background:#f0ebe3;font-weight:600;position:sticky;top:0;z-index:1;}", + ".corner{background:#e7e0d6;left:0;z-index:2;}", + "td{white-space:pre-wrap;}" + ) +} + +fn write_rendered_output(path: &Path, html: &str) -> Result<(), SpreadsheetArtifactError> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + } + fs::write(path, html).map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + }) +} + +fn workbook_output_paths( + artifact: &SpreadsheetArtifact, + cwd: &Path, + options: &SpreadsheetRenderOptions, + sheets: &[SpreadsheetSheet], +) -> Vec { + if let Some(output_path) = options.output_path.as_deref() { + if output_path.extension().is_some_and(|ext| ext == "html") { + let stem = output_path + .file_stem() + .and_then(|value| value.to_str()) + .unwrap_or("render"); + let parent = output_path.parent().unwrap_or(cwd); + return sheets + .iter() + .map(|sheet| { + parent.join(format!( + "{}_{}.html", + stem, + sanitize_file_component(&sheet.name) + )) + }) + .collect(); + } + return sheets + .iter() + .map(|sheet| output_path.join(format!("{}.html", sanitize_file_component(&sheet.name)))) + .collect(); + } + sheets + .iter() + .map(|sheet| { + cwd.join(format!( + "{}_render_{}.html", + artifact.artifact_id, + sanitize_file_component(&sheet.name) + )) + }) + .collect() +} + +fn single_output_path( + cwd: &Path, + artifact: &SpreadsheetArtifact, + output_path: Option<&Path>, + suffix: &str, +) -> PathBuf { + if let Some(output_path) = output_path { + return if output_path.extension().is_some_and(|ext| ext == "html") { + output_path.to_path_buf() + } else { + output_path.join(format!("{suffix}.html")) + }; + } + cwd.join(format!("{}_{}.html", artifact.artifact_id, suffix)) +} + +fn sanitize_file_component(value: &str) -> String { + value + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() { + character + } else { + '_' + } + }) + .collect() +} + +fn html_escape(value: &str) -> String { + value + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} diff --git a/codex-rs/artifact-spreadsheet/src/style.rs b/codex-rs/artifact-spreadsheet/src/style.rs new file mode 100644 index 0000000000..0c9a3782a5 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/style.rs @@ -0,0 +1,580 @@ +use std::collections::BTreeMap; + +use serde::Deserialize; +use serde::Serialize; + +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCellRangeRef; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SpreadsheetFontFace { + pub font_family: Option, + pub font_scheme: Option, + pub typeface: Option, +} + +impl SpreadsheetFontFace { + fn merge(&self, patch: &Self) -> Self { + Self { + font_family: patch + .font_family + .clone() + .or_else(|| self.font_family.clone()), + font_scheme: patch + .font_scheme + .clone() + .or_else(|| self.font_scheme.clone()), + typeface: patch.typeface.clone().or_else(|| self.typeface.clone()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SpreadsheetTextStyle { + pub bold: Option, + pub italic: Option, + pub underline: Option, + pub font_size: Option, + pub font_color: Option, + pub text_alignment: Option, + pub anchor: Option, + pub vertical_text_orientation: Option, + pub text_rotation: Option, + pub paragraph_spacing: Option, + pub bottom_inset: Option, + pub left_inset: Option, + pub right_inset: Option, + pub top_inset: Option, + pub font_family: Option, + pub font_scheme: Option, + pub typeface: Option, + pub font_face: Option, +} + +impl SpreadsheetTextStyle { + fn merge(&self, patch: &Self) -> Self { + Self { + bold: patch.bold.or(self.bold), + italic: patch.italic.or(self.italic), + underline: patch.underline.or(self.underline), + font_size: patch.font_size.or(self.font_size), + font_color: patch.font_color.clone().or_else(|| self.font_color.clone()), + text_alignment: patch + .text_alignment + .clone() + .or_else(|| self.text_alignment.clone()), + anchor: patch.anchor.clone().or_else(|| self.anchor.clone()), + vertical_text_orientation: patch + .vertical_text_orientation + .clone() + .or_else(|| self.vertical_text_orientation.clone()), + text_rotation: patch.text_rotation.or(self.text_rotation), + paragraph_spacing: patch.paragraph_spacing.or(self.paragraph_spacing), + bottom_inset: patch.bottom_inset.or(self.bottom_inset), + left_inset: patch.left_inset.or(self.left_inset), + right_inset: patch.right_inset.or(self.right_inset), + top_inset: patch.top_inset.or(self.top_inset), + font_family: patch + .font_family + .clone() + .or_else(|| self.font_family.clone()), + font_scheme: patch + .font_scheme + .clone() + .or_else(|| self.font_scheme.clone()), + typeface: patch.typeface.clone().or_else(|| self.typeface.clone()), + font_face: match (&self.font_face, &patch.font_face) { + (Some(base), Some(update)) => Some(base.merge(update)), + (None, Some(update)) => Some(update.clone()), + (Some(base), None) => Some(base.clone()), + (None, None) => None, + }, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetGradientStop { + pub position: f64, + pub color: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetFillRectangle { + pub left: f64, + pub right: f64, + pub top: f64, + pub bottom: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SpreadsheetFill { + pub solid_fill_color: Option, + pub pattern_type: Option, + pub pattern_foreground_color: Option, + pub pattern_background_color: Option, + #[serde(default)] + pub color_transforms: Vec, + pub gradient_fill_type: Option, + #[serde(default)] + pub gradient_stops: Vec, + pub gradient_kind: Option, + pub angle: Option, + pub scaled: Option, + pub path_type: Option, + pub fill_rectangle: Option, + pub image_reference: Option, +} + +impl SpreadsheetFill { + fn merge(&self, patch: &Self) -> Self { + Self { + solid_fill_color: patch + .solid_fill_color + .clone() + .or_else(|| self.solid_fill_color.clone()), + pattern_type: patch + .pattern_type + .clone() + .or_else(|| self.pattern_type.clone()), + pattern_foreground_color: patch + .pattern_foreground_color + .clone() + .or_else(|| self.pattern_foreground_color.clone()), + pattern_background_color: patch + .pattern_background_color + .clone() + .or_else(|| self.pattern_background_color.clone()), + color_transforms: if patch.color_transforms.is_empty() { + self.color_transforms.clone() + } else { + patch.color_transforms.clone() + }, + gradient_fill_type: patch + .gradient_fill_type + .clone() + .or_else(|| self.gradient_fill_type.clone()), + gradient_stops: if patch.gradient_stops.is_empty() { + self.gradient_stops.clone() + } else { + patch.gradient_stops.clone() + }, + gradient_kind: patch + .gradient_kind + .clone() + .or_else(|| self.gradient_kind.clone()), + angle: patch.angle.or(self.angle), + scaled: patch.scaled.or(self.scaled), + path_type: patch.path_type.clone().or_else(|| self.path_type.clone()), + fill_rectangle: patch + .fill_rectangle + .clone() + .or_else(|| self.fill_rectangle.clone()), + image_reference: patch + .image_reference + .clone() + .or_else(|| self.image_reference.clone()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SpreadsheetBorderLine { + pub style: Option, + pub color: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SpreadsheetBorder { + pub top: Option, + pub right: Option, + pub bottom: Option, + pub left: Option, +} + +impl SpreadsheetBorder { + fn merge(&self, patch: &Self) -> Self { + Self { + top: patch.top.clone().or_else(|| self.top.clone()), + right: patch.right.clone().or_else(|| self.right.clone()), + bottom: patch.bottom.clone().or_else(|| self.bottom.clone()), + left: patch.left.clone().or_else(|| self.left.clone()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SpreadsheetAlignment { + pub horizontal: Option, + pub vertical: Option, +} + +impl SpreadsheetAlignment { + fn merge(&self, patch: &Self) -> Self { + Self { + horizontal: patch.horizontal.clone().or_else(|| self.horizontal.clone()), + vertical: patch.vertical.clone().or_else(|| self.vertical.clone()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SpreadsheetNumberFormat { + pub format_id: Option, + pub format_code: Option, +} + +impl SpreadsheetNumberFormat { + fn merge(&self, patch: &Self) -> Self { + Self { + format_id: patch.format_id.or(self.format_id), + format_code: patch + .format_code + .clone() + .or_else(|| self.format_code.clone()), + } + } + + fn normalized(mut self) -> Self { + if self.format_code.is_none() { + self.format_code = self.format_id.and_then(builtin_number_format_code); + } + self + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SpreadsheetCellFormat { + pub text_style_id: Option, + pub fill_id: Option, + pub border_id: Option, + pub alignment: Option, + pub number_format_id: Option, + pub wrap_text: Option, + pub base_cell_style_format_id: Option, +} + +impl SpreadsheetCellFormat { + pub fn wrap(mut self) -> Self { + self.wrap_text = Some(true); + self + } + + pub fn unwrap(mut self) -> Self { + self.wrap_text = Some(false); + self + } + + fn merge(&self, patch: &Self) -> Self { + Self { + text_style_id: patch.text_style_id.or(self.text_style_id), + fill_id: patch.fill_id.or(self.fill_id), + border_id: patch.border_id.or(self.border_id), + alignment: match (&self.alignment, &patch.alignment) { + (Some(base), Some(update)) => Some(base.merge(update)), + (None, Some(update)) => Some(update.clone()), + (Some(base), None) => Some(base.clone()), + (None, None) => None, + }, + number_format_id: patch.number_format_id.or(self.number_format_id), + wrap_text: patch.wrap_text.or(self.wrap_text), + base_cell_style_format_id: patch + .base_cell_style_format_id + .or(self.base_cell_style_format_id), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SpreadsheetDifferentialFormat { + pub text_style_id: Option, + pub fill_id: Option, + pub border_id: Option, + pub alignment: Option, + pub number_format_id: Option, + pub wrap_text: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetCellFormatSummary { + pub style_index: u32, + pub text_style: Option, + pub fill: Option, + pub border: Option, + pub alignment: Option, + pub number_format: Option, + pub wrap_text: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetRangeFormat { + pub sheet_name: String, + pub range: String, +} + +impl SpreadsheetRangeFormat { + pub fn new(sheet_name: String, range: &CellRange) -> Self { + Self { + sheet_name, + range: range.to_a1(), + } + } + + pub fn range_ref(&self) -> Result { + let range = CellRange::parse(&self.range)?; + Ok(SpreadsheetCellRangeRef::new( + self.sheet_name.clone(), + &range, + )) + } + + pub fn top_left_style_index( + &self, + sheet: &SpreadsheetSheet, + ) -> Result { + self.range_ref()?.top_left_style_index(sheet) + } + + pub fn top_left_cell_format( + &self, + artifact: &SpreadsheetArtifact, + sheet: &SpreadsheetSheet, + ) -> Result, SpreadsheetArtifactError> { + let range = self.range_ref()?.range()?; + Ok(artifact.cell_format_summary(sheet.top_left_style_index(&range))) + } +} + +impl SpreadsheetArtifact { + pub fn create_text_style( + &mut self, + style: SpreadsheetTextStyle, + source_style_id: Option, + merge_with_existing_components: bool, + ) -> Result { + let created = if let Some(source_style_id) = source_style_id { + let source = self + .text_styles + .get(&source_style_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: "create_text_style".to_string(), + message: format!("text style `{source_style_id}` was not found"), + })?; + if merge_with_existing_components { + source.merge(&style) + } else { + style + } + } else { + style + }; + Ok(insert_with_next_id(&mut self.text_styles, created)) + } + + pub fn get_text_style(&self, style_id: u32) -> Option<&SpreadsheetTextStyle> { + self.text_styles.get(&style_id) + } + + pub fn create_fill( + &mut self, + fill: SpreadsheetFill, + source_fill_id: Option, + merge_with_existing_components: bool, + ) -> Result { + let created = if let Some(source_fill_id) = source_fill_id { + let source = self.fills.get(&source_fill_id).cloned().ok_or_else(|| { + SpreadsheetArtifactError::InvalidArgs { + action: "create_fill".to_string(), + message: format!("fill `{source_fill_id}` was not found"), + } + })?; + if merge_with_existing_components { + source.merge(&fill) + } else { + fill + } + } else { + fill + }; + Ok(insert_with_next_id(&mut self.fills, created)) + } + + pub fn get_fill(&self, fill_id: u32) -> Option<&SpreadsheetFill> { + self.fills.get(&fill_id) + } + + pub fn create_border( + &mut self, + border: SpreadsheetBorder, + source_border_id: Option, + merge_with_existing_components: bool, + ) -> Result { + let created = if let Some(source_border_id) = source_border_id { + let source = self + .borders + .get(&source_border_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: "create_border".to_string(), + message: format!("border `{source_border_id}` was not found"), + })?; + if merge_with_existing_components { + source.merge(&border) + } else { + border + } + } else { + border + }; + Ok(insert_with_next_id(&mut self.borders, created)) + } + + pub fn get_border(&self, border_id: u32) -> Option<&SpreadsheetBorder> { + self.borders.get(&border_id) + } + + pub fn create_number_format( + &mut self, + format: SpreadsheetNumberFormat, + source_number_format_id: Option, + merge_with_existing_components: bool, + ) -> Result { + let created = if let Some(source_number_format_id) = source_number_format_id { + let source = self + .number_formats + .get(&source_number_format_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: "create_number_format".to_string(), + message: format!("number format `{source_number_format_id}` was not found"), + })?; + if merge_with_existing_components { + source.merge(&format) + } else { + format + } + } else { + format + }; + Ok(insert_with_next_id( + &mut self.number_formats, + created.normalized(), + )) + } + + pub fn get_number_format(&self, number_format_id: u32) -> Option<&SpreadsheetNumberFormat> { + self.number_formats.get(&number_format_id) + } + + pub fn create_cell_format( + &mut self, + format: SpreadsheetCellFormat, + source_format_id: Option, + merge_with_existing_components: bool, + ) -> Result { + let created = if let Some(source_format_id) = source_format_id { + let source = self + .cell_formats + .get(&source_format_id) + .cloned() + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: "create_cell_format".to_string(), + message: format!("cell format `{source_format_id}` was not found"), + })?; + if merge_with_existing_components { + source.merge(&format) + } else { + format + } + } else { + format + }; + Ok(insert_with_next_id(&mut self.cell_formats, created)) + } + + pub fn get_cell_format(&self, format_id: u32) -> Option<&SpreadsheetCellFormat> { + self.cell_formats.get(&format_id) + } + + pub fn create_differential_format(&mut self, format: SpreadsheetDifferentialFormat) -> u32 { + insert_with_next_id(&mut self.differential_formats, format) + } + + pub fn get_differential_format( + &self, + format_id: u32, + ) -> Option<&SpreadsheetDifferentialFormat> { + self.differential_formats.get(&format_id) + } + + pub fn resolve_cell_format(&self, style_index: u32) -> Option { + let format = self.cell_formats.get(&style_index)?.clone(); + resolve_cell_format_recursive(&self.cell_formats, &format, 0) + } + + pub fn cell_format_summary(&self, style_index: u32) -> Option { + let resolved = self.resolve_cell_format(style_index)?; + Some(SpreadsheetCellFormatSummary { + style_index, + text_style: resolved + .text_style_id + .and_then(|id| self.text_styles.get(&id).cloned()), + fill: resolved.fill_id.and_then(|id| self.fills.get(&id).cloned()), + border: resolved + .border_id + .and_then(|id| self.borders.get(&id).cloned()), + alignment: resolved.alignment, + number_format: resolved + .number_format_id + .and_then(|id| self.number_formats.get(&id).cloned()), + wrap_text: resolved.wrap_text, + }) + } +} + +impl SpreadsheetSheet { + pub fn range_format(&self, range: &CellRange) -> SpreadsheetRangeFormat { + SpreadsheetRangeFormat::new(self.name.clone(), range) + } +} + +fn insert_with_next_id(map: &mut BTreeMap, value: T) -> u32 { + let next_id = map.last_key_value().map(|(key, _)| key + 1).unwrap_or(1); + map.insert(next_id, value); + next_id +} + +fn resolve_cell_format_recursive( + cell_formats: &BTreeMap, + format: &SpreadsheetCellFormat, + depth: usize, +) -> Option { + if depth > 32 { + return None; + } + let base = format + .base_cell_style_format_id + .and_then(|id| cell_formats.get(&id)) + .and_then(|base| resolve_cell_format_recursive(cell_formats, base, depth + 1)); + Some(match base { + Some(base) => base.merge(format), + None => format.clone(), + }) +} + +fn builtin_number_format_code(format_id: u32) -> Option { + match format_id { + 0 => Some("General".to_string()), + 1 => Some("0".to_string()), + 2 => Some("0.00".to_string()), + 3 => Some("#,##0".to_string()), + 4 => Some("#,##0.00".to_string()), + 9 => Some("0%".to_string()), + 10 => Some("0.00%".to_string()), + _ => None, + } +} diff --git a/codex-rs/artifact-spreadsheet/src/table.rs b/codex-rs/artifact-spreadsheet/src/table.rs new file mode 100644 index 0000000000..be04c188e2 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/table.rs @@ -0,0 +1,630 @@ +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +use serde::Deserialize; +use serde::Serialize; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCellValue; +use crate::SpreadsheetSheet; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetTableColumn { + pub id: u32, + pub name: String, + pub totals_row_label: Option, + pub totals_row_function: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetTable { + pub id: u32, + pub name: String, + pub display_name: String, + pub range: String, + pub header_row_count: u32, + pub totals_row_count: u32, + pub style_name: Option, + pub show_first_column: bool, + pub show_last_column: bool, + pub show_row_stripes: bool, + pub show_column_stripes: bool, + #[serde(default)] + pub columns: Vec, + #[serde(default)] + pub filters: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SpreadsheetTableView { + pub id: u32, + pub name: String, + pub display_name: String, + pub address: String, + pub full_range: String, + pub header_row_count: u32, + pub totals_row_count: u32, + pub totals_row_visible: bool, + pub header_row_range: Option, + pub data_body_range: Option, + pub totals_row_range: Option, + pub style_name: Option, + pub show_first_column: bool, + pub show_last_column: bool, + pub show_row_stripes: bool, + pub show_column_stripes: bool, + pub columns: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct SpreadsheetTableLookup<'a> { + pub name: Option<&'a str>, + pub display_name: Option<&'a str>, + pub id: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetCreateTableOptions { + pub name: Option, + pub display_name: Option, + pub header_row_count: u32, + pub totals_row_count: u32, + pub style_name: Option, + pub show_first_column: bool, + pub show_last_column: bool, + pub show_row_stripes: bool, + pub show_column_stripes: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpreadsheetTableStyleOptions { + pub style_name: Option, + pub show_first_column: Option, + pub show_last_column: Option, + pub show_row_stripes: Option, + pub show_column_stripes: Option, +} + +impl SpreadsheetTable { + pub fn range(&self) -> Result { + CellRange::parse(&self.range) + } + + pub fn address(&self) -> String { + self.range.clone() + } + + pub fn full_range(&self) -> String { + self.range.clone() + } + + pub fn totals_row_visible(&self) -> bool { + self.totals_row_count > 0 + } + + pub fn header_row_range(&self) -> Result, SpreadsheetArtifactError> { + if self.header_row_count == 0 { + return Ok(None); + } + let range = self.range()?; + Ok(Some(CellRange::from_start_end( + range.start, + CellAddress { + column: range.end.column, + row: range.start.row + self.header_row_count - 1, + }, + ))) + } + + pub fn data_body_range(&self) -> Result, SpreadsheetArtifactError> { + let range = self.range()?; + let start_row = range.start.row + self.header_row_count; + let end_row = range.end.row.saturating_sub(self.totals_row_count); + if start_row > end_row { + return Ok(None); + } + Ok(Some(CellRange::from_start_end( + CellAddress { + column: range.start.column, + row: start_row, + }, + CellAddress { + column: range.end.column, + row: end_row, + }, + ))) + } + + pub fn totals_row_range(&self) -> Result, SpreadsheetArtifactError> { + if self.totals_row_count == 0 { + return Ok(None); + } + let range = self.range()?; + Ok(Some(CellRange::from_start_end( + CellAddress { + column: range.start.column, + row: range.end.row - self.totals_row_count + 1, + }, + range.end, + ))) + } + + pub fn view(&self) -> Result { + Ok(SpreadsheetTableView { + id: self.id, + name: self.name.clone(), + display_name: self.display_name.clone(), + address: self.address(), + full_range: self.full_range(), + header_row_count: self.header_row_count, + totals_row_count: self.totals_row_count, + totals_row_visible: self.totals_row_visible(), + header_row_range: self.header_row_range()?.map(|range| range.to_a1()), + data_body_range: self.data_body_range()?.map(|range| range.to_a1()), + totals_row_range: self.totals_row_range()?.map(|range| range.to_a1()), + style_name: self.style_name.clone(), + show_first_column: self.show_first_column, + show_last_column: self.show_last_column, + show_row_stripes: self.show_row_stripes, + show_column_stripes: self.show_column_stripes, + columns: self.columns.clone(), + }) + } +} + +impl SpreadsheetSheet { + pub fn create_table( + &mut self, + action: &str, + range: &CellRange, + options: SpreadsheetCreateTableOptions, + ) -> Result { + validate_table_geometry( + action, + range, + options.header_row_count, + options.totals_row_count, + )?; + for table in &self.tables { + let table_range = table.range()?; + if table_range.intersects(range) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "table range `{}` intersects existing table `{}`", + range.to_a1(), + table.name + ), + }); + } + } + + let next_id = self.tables.iter().map(|table| table.id).max().unwrap_or(0) + 1; + let name = options.name.unwrap_or_else(|| format!("Table{next_id}")); + if name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table name cannot be empty".to_string(), + }); + } + let display_name = options.display_name.unwrap_or_else(|| name.clone()); + if display_name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table display_name cannot be empty".to_string(), + }); + } + ensure_unique_table_name(&self.tables, action, &name, &display_name, None)?; + + let columns = build_table_columns(self, range, options.header_row_count); + self.tables.push(SpreadsheetTable { + id: next_id, + name, + display_name, + range: range.to_a1(), + header_row_count: options.header_row_count, + totals_row_count: options.totals_row_count, + style_name: options.style_name, + show_first_column: options.show_first_column, + show_last_column: options.show_last_column, + show_row_stripes: options.show_row_stripes, + show_column_stripes: options.show_column_stripes, + columns, + filters: BTreeMap::new(), + }); + Ok(next_id) + } + + pub fn list_tables( + &self, + range: Option<&CellRange>, + ) -> Result, SpreadsheetArtifactError> { + self.tables + .iter() + .filter(|table| { + range.is_none_or(|target| { + table + .range() + .map(|table_range| table_range.intersects(target)) + .unwrap_or(false) + }) + }) + .map(SpreadsheetTable::view) + .collect() + } + + pub fn get_table( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<&SpreadsheetTable, SpreadsheetArtifactError> { + self.table_lookup_internal(action, lookup) + } + + pub fn get_table_view( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result { + self.get_table(action, lookup)?.view() + } + + pub fn delete_table( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<(), SpreadsheetArtifactError> { + let index = self.table_index(action, lookup)?; + self.tables.remove(index); + Ok(()) + } + + pub fn set_table_style( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + options: SpreadsheetTableStyleOptions, + ) -> Result<(), SpreadsheetArtifactError> { + let table = self.table_lookup_mut(action, lookup)?; + table.style_name = options.style_name; + if let Some(value) = options.show_first_column { + table.show_first_column = value; + } + if let Some(value) = options.show_last_column { + table.show_last_column = value; + } + if let Some(value) = options.show_row_stripes { + table.show_row_stripes = value; + } + if let Some(value) = options.show_column_stripes { + table.show_column_stripes = value; + } + Ok(()) + } + + pub fn clear_table_filters( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<(), SpreadsheetArtifactError> { + self.table_lookup_mut(action, lookup)?.filters.clear(); + Ok(()) + } + + pub fn reapply_table_filters( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<(), SpreadsheetArtifactError> { + let _ = self.table_lookup_mut(action, lookup)?; + Ok(()) + } + + pub fn rename_table_column( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + column_id: Option, + column_name: Option<&str>, + new_name: String, + ) -> Result { + if new_name.trim().is_empty() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table column name cannot be empty".to_string(), + }); + } + let table = self.table_lookup_mut(action, lookup)?; + if table + .columns + .iter() + .any(|column| column.name == new_name && Some(column.id) != column_id) + { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table column `{new_name}` already exists"), + }); + } + let column = table_column_lookup_mut(&mut table.columns, action, column_id, column_name)?; + column.name = new_name; + Ok(column.clone()) + } + + pub fn set_table_column_totals( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + column_id: Option, + column_name: Option<&str>, + totals_row_label: Option, + totals_row_function: Option, + ) -> Result { + let table = self.table_lookup_mut(action, lookup)?; + let column = table_column_lookup_mut(&mut table.columns, action, column_id, column_name)?; + column.totals_row_label = totals_row_label; + column.totals_row_function = totals_row_function; + Ok(column.clone()) + } + + pub fn validate_tables(&self, action: &str) -> Result<(), SpreadsheetArtifactError> { + let mut seen_names = BTreeSet::new(); + let mut seen_display_names = BTreeSet::new(); + for table in &self.tables { + let range = table.range()?; + validate_table_geometry( + action, + &range, + table.header_row_count, + table.totals_row_count, + )?; + if !seen_names.insert(table.name.clone()) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("duplicate table name `{}`", table.name), + }); + } + if !seen_display_names.insert(table.display_name.clone()) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("duplicate table display_name `{}`", table.display_name), + }); + } + let column_names = table + .columns + .iter() + .map(|column| column.name.clone()) + .collect::>(); + if column_names.len() != table.columns.len() { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table `{}` has duplicate column names", table.name), + }); + } + } + + for index in 0..self.tables.len() { + for other in index + 1..self.tables.len() { + if self.tables[index] + .range()? + .intersects(&self.tables[other].range()?) + { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!( + "table `{}` intersects table `{}`", + self.tables[index].name, self.tables[other].name + ), + }); + } + } + } + Ok(()) + } + + fn table_index( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result { + self.tables + .iter() + .position(|table| table_matches_lookup(table, lookup.clone())) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: describe_missing_table(lookup), + }) + } + + fn table_lookup_internal( + &self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<&SpreadsheetTable, SpreadsheetArtifactError> { + self.tables + .iter() + .find(|table| table_matches_lookup(table, lookup.clone())) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: describe_missing_table(lookup), + }) + } + + fn table_lookup_mut( + &mut self, + action: &str, + lookup: SpreadsheetTableLookup<'_>, + ) -> Result<&mut SpreadsheetTable, SpreadsheetArtifactError> { + let index = self.table_index(action, lookup)?; + Ok(&mut self.tables[index]) + } +} + +fn table_matches_lookup(table: &SpreadsheetTable, lookup: SpreadsheetTableLookup<'_>) -> bool { + if let Some(name) = lookup.name { + table.name == name + } else if let Some(display_name) = lookup.display_name { + table.display_name == display_name + } else if let Some(id) = lookup.id { + table.id == id + } else { + false + } +} + +fn describe_missing_table(lookup: SpreadsheetTableLookup<'_>) -> String { + if let Some(name) = lookup.name { + format!("table name `{name}` was not found") + } else if let Some(display_name) = lookup.display_name { + format!("table display_name `{display_name}` was not found") + } else if let Some(id) = lookup.id { + format!("table id `{id}` was not found") + } else { + "table name, display_name, or id is required".to_string() + } +} + +fn ensure_unique_table_name( + tables: &[SpreadsheetTable], + action: &str, + name: &str, + display_name: &str, + exclude_id: Option, +) -> Result<(), SpreadsheetArtifactError> { + if tables.iter().any(|table| { + Some(table.id) != exclude_id && (table.name == name || table.display_name == name) + }) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table name `{name}` already exists"), + }); + } + if tables.iter().any(|table| { + Some(table.id) != exclude_id + && (table.display_name == display_name || table.name == display_name) + }) { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: format!("table display_name `{display_name}` already exists"), + }); + } + Ok(()) +} + +fn validate_table_geometry( + action: &str, + range: &CellRange, + header_row_count: u32, + totals_row_count: u32, +) -> Result<(), SpreadsheetArtifactError> { + if range.width() == 0 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table range must include at least one column".to_string(), + }); + } + if header_row_count + totals_row_count > range.height() as u32 { + return Err(SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: "table range is smaller than header and totals rows".to_string(), + }); + } + Ok(()) +} + +fn build_table_columns( + sheet: &SpreadsheetSheet, + range: &CellRange, + header_row_count: u32, +) -> Vec { + let header_row = range.start.row + header_row_count.saturating_sub(1); + let default_names = (0..range.width()) + .map(|index| format!("Column{}", index + 1)) + .collect::>(); + let names = unique_table_column_names( + (range.start.column..=range.end.column) + .enumerate() + .map(|(index, column)| { + if header_row_count == 0 { + return default_names[index].clone(); + } + sheet + .get_cell(CellAddress { + column, + row: header_row, + }) + .and_then(|cell| cell.value.as_ref()) + .map(cell_value_to_table_header) + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| default_names[index].clone()) + }) + .collect::>(), + ); + names + .into_iter() + .enumerate() + .map(|(index, name)| SpreadsheetTableColumn { + id: index as u32 + 1, + name, + totals_row_label: None, + totals_row_function: None, + }) + .collect() +} + +fn unique_table_column_names(names: Vec) -> Vec { + let mut seen = BTreeMap::::new(); + names + .into_iter() + .map(|name| { + let entry = seen.entry(name.clone()).or_insert(0); + *entry += 1; + if *entry == 1 { + name + } else { + format!("{name}_{}", *entry) + } + }) + .collect() +} + +fn cell_value_to_table_header(value: &SpreadsheetCellValue) -> String { + match value { + SpreadsheetCellValue::Bool(value) => value.to_string(), + SpreadsheetCellValue::Integer(value) => value.to_string(), + SpreadsheetCellValue::Float(value) => value.to_string(), + SpreadsheetCellValue::String(value) + | SpreadsheetCellValue::DateTime(value) + | SpreadsheetCellValue::Error(value) => value.clone(), + } +} + +fn table_column_lookup_mut<'a>( + columns: &'a mut [SpreadsheetTableColumn], + action: &str, + column_id: Option, + column_name: Option<&str>, +) -> Result<&'a mut SpreadsheetTableColumn, SpreadsheetArtifactError> { + columns + .iter_mut() + .find(|column| { + if let Some(column_id) = column_id { + column.id == column_id + } else if let Some(column_name) = column_name { + column.name == column_name + } else { + false + } + }) + .ok_or_else(|| SpreadsheetArtifactError::InvalidArgs { + action: action.to_string(), + message: if let Some(column_id) = column_id { + format!("table column id `{column_id}` was not found") + } else if let Some(column_name) = column_name { + format!("table column `{column_name}` was not found") + } else { + "table column id or name is required".to_string() + }, + }) +} diff --git a/codex-rs/artifact-spreadsheet/src/tests.rs b/codex-rs/artifact-spreadsheet/src/tests.rs new file mode 100644 index 0000000000..608ac7b392 --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/tests.rs @@ -0,0 +1,1228 @@ +use std::collections::BTreeMap; + +use pretty_assertions::assert_eq; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactManager; +use crate::SpreadsheetArtifactRequest; +use crate::SpreadsheetCell; +use crate::SpreadsheetCellFormat; +use crate::SpreadsheetCellFormatSummary; +use crate::SpreadsheetCellValue; +use crate::SpreadsheetFileType; +use crate::SpreadsheetFill; +use crate::SpreadsheetFontFace; +use crate::SpreadsheetNumberFormat; +use crate::SpreadsheetRenderOptions; +use crate::SpreadsheetSheet; +use crate::SpreadsheetSheetReference; +use crate::SpreadsheetTextStyle; + +#[test] +fn manager_can_create_edit_recalculate_and_export() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = SpreadsheetArtifactManager::default(); + + let created = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Budget" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_sheet".to_string(), + args: serde_json::json!({ "name": "Sheet1" }), + }, + temp_dir.path(), + )?; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_range_values".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A1:B2", + "values": [[1, 2], [3, 4]] + }), + }, + temp_dir.path(), + )?; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_cell_formula".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "address": "C1", + "formula": "=SUM(A1:B2)", + "recalculate": true + }), + }, + temp_dir.path(), + )?; + + let cell = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_cell".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "address": "C1" + }), + }, + temp_dir.path(), + )?; + assert_eq!( + cell.cell.and_then(|entry| entry.value), + Some(SpreadsheetCellValue::Integer(10)) + ); + + let export_path = temp_dir.path().join("budget.xlsx"); + let export = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "export_xlsx".to_string(), + args: serde_json::json!({ "path": export_path }), + }, + temp_dir.path(), + )?; + assert_eq!(export.exported_paths.len(), 1); + assert!(export.exported_paths[0].exists()); + Ok(()) +} + +#[test] +fn spreadsheet_serialization_roundtrip_preserves_cells() -> Result<(), Box> { + let mut artifact = SpreadsheetArtifact::new(Some("Roundtrip".to_string())); + let sheet = artifact.create_sheet("Sheet1".to_string())?; + sheet.set_value( + crate::CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::String("hello".to_string())), + )?; + sheet.set_formula(crate::CellAddress::parse("B1")?, Some("=A1".to_string()))?; + artifact.recalculate(); + + let json = artifact.to_json()?; + let restored = SpreadsheetArtifact::from_json(json, None)?; + let restored_sheet = restored.get_sheet(Some("Sheet1"), None).expect("sheet"); + let cell = restored_sheet.get_cell_view(crate::CellAddress::parse("A1")?); + assert_eq!( + cell.value, + Some(SpreadsheetCellValue::String("hello".to_string())) + ); + Ok(()) +} + +#[test] +fn xlsx_roundtrip_preserves_merged_ranges_and_style_indices() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let path = temp_dir.path().join("styled.xlsx"); + + let mut artifact = SpreadsheetArtifact::new(Some("Styled".to_string())); + let sheet = artifact.create_sheet("Sheet1".to_string())?; + sheet.set_value( + crate::CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::Integer(42)), + )?; + sheet.set_style_index(&crate::CellRange::parse("A1:B1")?, 3)?; + sheet.merge_cells(&crate::CellRange::parse("A1:B1")?, true)?; + artifact.export(&path)?; + + let restored = SpreadsheetArtifact::from_source_file(&path, None)?; + let restored_sheet = restored.get_sheet(Some("Sheet1"), None).expect("sheet"); + assert_eq!(restored_sheet.merged_ranges.len(), 1); + assert_eq!( + restored_sheet + .get_cell_view(crate::CellAddress::parse("A1")?) + .style_index, + 3 + ); + Ok(()) +} + +#[test] +fn path_accesses_cover_import_and_export() -> Result<(), Box> { + let cwd = tempfile::tempdir()?; + let request = crate::SpreadsheetArtifactRequest { + artifact_id: Some("spreadsheet_1".to_string()), + action: "export_xlsx".to_string(), + args: serde_json::json!({ "path": "out/report.xlsx" }), + }; + let accesses = request.required_path_accesses(cwd.path())?; + assert_eq!(accesses.len(), 1); + assert!(accesses[0].path.ends_with("out/report.xlsx")); + Ok(()) +} + +#[test] +fn render_options_write_deterministic_html_previews() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut artifact = SpreadsheetArtifact::new(Some("Preview".to_string())); + artifact.create_sheet("Sheet 1".to_string())?; + { + let sheet = artifact + .get_sheet_mut(Some("Sheet 1"), None) + .expect("sheet"); + sheet.set_value( + CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::String("Name".to_string())), + )?; + sheet.set_value( + CellAddress::parse("B1")?, + Some(SpreadsheetCellValue::String("Value".to_string())), + )?; + sheet.set_value( + CellAddress::parse("A2")?, + Some(SpreadsheetCellValue::String("Alpha".to_string())), + )?; + sheet.set_value( + CellAddress::parse("B2")?, + Some(SpreadsheetCellValue::Integer(42)), + )?; + } + + let rendered = artifact.render_range_preview( + temp_dir.path(), + artifact.get_sheet(Some("Sheet 1"), None).expect("sheet"), + &CellRange::parse("A1:B2")?, + &SpreadsheetRenderOptions { + output_path: Some(temp_dir.path().join("range-preview.html")), + width: Some(320), + height: Some(200), + include_headers: true, + scale: 1.25, + performance_mode: true, + ..Default::default() + }, + )?; + assert!(rendered.path.exists()); + assert_eq!(std::fs::read_to_string(&rendered.path)?, rendered.html); + assert!(rendered.html.contains("")); + assert!(rendered.html.contains("data-performance-mode=\"true\"")); + assert!(rendered.html.contains( + "style=\"--scale: 1.25; --headers: 1; width: 320px; height: 200px; overflow: auto\"" + )); + assert!(rendered.html.contains("A")); + assert!(rendered.html.contains("data-address=\"B2\"")); + assert!(rendered.html.contains(">42")); + + let workbook = artifact.render_workbook_previews( + temp_dir.path(), + &SpreadsheetRenderOptions { + output_path: Some(temp_dir.path().join("workbook")), + include_headers: false, + ..Default::default() + }, + )?; + assert_eq!(workbook.len(), 1); + assert!(workbook[0].path.ends_with("Sheet_1.html")); + assert!(!workbook[0].html.contains("A")); + Ok(()) +} + +#[test] +fn sheet_refs_support_handle_and_field_apis() -> Result<(), Box> { + let mut artifact = SpreadsheetArtifact::new(Some("Handles".to_string())); + let (range_ref, cell_ref) = { + let sheet = artifact.create_sheet("Sheet1".to_string())?; + let range_ref = sheet.range_ref("A1:B2")?; + range_ref.set_value(sheet, Some(SpreadsheetCellValue::Integer(7)))?; + let cell_ref = sheet.cell_ref("B2")?; + cell_ref.set_formula(sheet, Some("=SUM(A1:B2)".to_string()))?; + (range_ref, cell_ref) + }; + artifact.recalculate(); + let sheet = artifact.get_sheet(Some("Sheet1"), None).expect("sheet"); + + let values = range_ref.get_values(sheet)?; + assert_eq!(values[0][0], Some(SpreadsheetCellValue::Integer(7))); + assert_eq!( + cell_ref.get(sheet)?.value, + Some(SpreadsheetCellValue::Integer(28)) + ); + assert_eq!( + sheet.get_cell_field_by_indices(2, 2, "formula")?, + Some(serde_json::Value::String("=SUM(A1:B2)".to_string())) + ); + assert_eq!( + sheet.minimum_range_ref().map(|entry| entry.address), + Some("A1:B2".to_string()) + ); + assert!(matches!( + sheet.to_dict()?, + serde_json::Value::Object(_) | serde_json::Value::Array(_) + )); + Ok(()) +} + +#[test] +fn manager_supports_single_value_formula_and_cite_cell_actions() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = SpreadsheetArtifactManager::default(); + let created = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Actions" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_sheet".to_string(), + args: serde_json::json!({ "name": "Sheet1" }), + }, + temp_dir.path(), + )?; + + let uniform = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_range_value".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A1:B2", + "value": 5 + }), + }, + temp_dir.path(), + )?; + assert_eq!( + uniform + .range_ref + .as_ref() + .map(|entry| entry.address.clone()), + Some("A1:B2".to_string()) + ); + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_range_formula".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "C1:C2", + "formula": "=SUM(A1:B2)", + "recalculate": true + }), + }, + temp_dir.path(), + )?; + + let cited = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "cite_cell".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "address": "C1", + "tether_id": "source-1", + "start_line": 3, + "end_line": 8 + }), + }, + temp_dir.path(), + )?; + assert_eq!( + cited.cell.as_ref().map(|entry| entry.citations.len()), + Some(1) + ); + + let by_indices = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_cell_by_indices".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "column_index": 3, + "row_index": 1 + }), + }, + temp_dir.path(), + )?; + assert_eq!( + by_indices + .cell + .as_ref() + .and_then(|entry| entry.value.clone()), + Some(SpreadsheetCellValue::Integer(20)) + ); + + let field = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "get_cell_field".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "address": "C1", + "field": "formula" + }), + }, + temp_dir.path(), + )?; + assert_eq!( + field.cell_field, + Some(serde_json::Value::String("=SUM(A1:B2)".to_string())) + ); + Ok(()) +} + +#[test] +fn artifact_file_type_helpers_and_source_files_work() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut artifact = SpreadsheetArtifact::new(Some("Files".to_string())); + artifact.artifact_id = "spreadsheet_fixed".to_string(); + artifact.create_sheet("Sheet1".to_string())?.set_value( + CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::String("hello".to_string())), + )?; + + assert_eq!( + SpreadsheetArtifact::allowed_file_extensions(), + &["xlsx", "json", "bin"] + ); + assert_eq!( + SpreadsheetArtifact::allowed_file_mime_types(), + &[ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/json", + "application/octet-stream", + ] + ); + assert_eq!( + SpreadsheetArtifact::allowed_file_types().to_vec(), + vec![ + SpreadsheetFileType::Xlsx, + SpreadsheetFileType::Json, + SpreadsheetFileType::Binary, + ] + ); + assert_eq!( + artifact.get_output_file_name(Some("preview"), SpreadsheetFileType::Json), + "spreadsheet_fixed_preview.json".to_string() + ); + + let json_path = temp_dir + .path() + .join(artifact.get_output_file_name(None, SpreadsheetFileType::Json)); + artifact.save(&json_path, Some("json"))?; + let restored_json = SpreadsheetArtifact::load(&json_path, None)?; + assert_eq!(restored_json.to_dict()?, artifact.to_dict()?); + + let bytes_path = temp_dir + .path() + .join(artifact.get_output_file_name(Some("bytes"), SpreadsheetFileType::Binary)); + artifact.save(&bytes_path, Some("bin"))?; + let restored_bytes = SpreadsheetArtifact::read(&bytes_path, None)?; + assert_eq!(restored_bytes.to_dict()?, artifact.to_dict()?); + Ok(()) +} + +#[test] +fn sheet_cleanup_and_row_sizing_helpers_work() -> Result<(), Box> { + let mut sheet = SpreadsheetSheet::new("Sheet1".to_string()); + sheet.default_row_height = Some(15.0); + sheet.set_column_widths_bulk(&BTreeMap::from([ + ("A".to_string(), 12.0), + ("C:D".to_string(), 20.0), + ]))?; + sheet.set_row_height(2, Some(18.0))?; + sheet.set_row_heights(3, 4, Some(22.0))?; + sheet.set_row_heights_bulk(&BTreeMap::from([(4, None), (5, Some(30.0))]))?; + + assert_eq!(sheet.get_column_width("A")?, Some(12.0)); + assert_eq!(sheet.get_column_width("B")?, None); + assert_eq!(sheet.get_column_width("D")?, Some(20.0)); + assert_eq!(sheet.get_row_height(2), Some(18.0)); + assert_eq!(sheet.get_row_height(3), Some(22.0)); + assert_eq!(sheet.get_row_height(4), Some(15.0)); + assert_eq!(sheet.get_row_height(5), Some(30.0)); + + sheet.cells.insert( + CellAddress::parse("A1")?, + SpreadsheetCell { + value: None, + formula: None, + style_index: 0, + citations: Vec::new(), + }, + ); + let merged = CellRange::parse("B2:C3")?; + sheet.merged_ranges = vec![merged.clone(), merged.clone()]; + sheet.cleanup_and_validate_sheet()?; + + assert_eq!(sheet.cells, BTreeMap::new()); + assert_eq!(sheet.merged_ranges, vec![merged]); + Ok(()) +} + +#[test] +fn xlsx_roundtrip_preserves_row_and_column_sizes() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let path = temp_dir.path().join("sizing.xlsx"); + + let mut artifact = SpreadsheetArtifact::new(Some("Sizing".to_string())); + let (expected_column_widths, expected_row_heights, expected_show_grid_lines) = { + let sheet = artifact.create_sheet("Sheet1".to_string())?; + sheet.show_grid_lines = false; + sheet.set_value( + CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::Integer(42)), + )?; + sheet.set_column_widths_bulk(&BTreeMap::from([ + ("A:B".to_string(), 12.5), + ("D".to_string(), 18.0), + ]))?; + sheet.set_row_heights_bulk(&BTreeMap::from([(2, Some(24.0)), (6, Some(19.5))]))?; + ( + sheet.column_widths.clone(), + sheet.row_heights.clone(), + sheet.show_grid_lines, + ) + }; + artifact.export(&path)?; + + let restored = SpreadsheetArtifact::from_source_file(&path, None)?; + let restored_sheet = restored.get_sheet(Some("Sheet1"), None).expect("sheet"); + assert_eq!(restored_sheet.column_widths, expected_column_widths); + assert_eq!(restored_sheet.row_heights, expected_row_heights); + assert_eq!(restored_sheet.show_grid_lines, expected_show_grid_lines); + Ok(()) +} + +#[test] +fn manager_supports_bulk_sizes_and_row_heights() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = SpreadsheetArtifactManager::default(); + let created = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Sizing" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_sheet".to_string(), + args: serde_json::json!({ "name": "Sheet1" }), + }, + temp_dir.path(), + )?; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_column_widths_bulk".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "widths": { + "A:B": 12.0, + "D": 20.0 + } + }), + }, + temp_dir.path(), + )?; + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_row_height".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "row_index": 2, + "height": 18.0 + }), + }, + temp_dir.path(), + )?; + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_row_heights".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "start_row_index": 3, + "end_row_index": 4, + "height": 21.0 + }), + }, + temp_dir.path(), + )?; + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_row_heights_bulk".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "heights": { + "4": null, + "5": 25.0 + } + }), + }, + temp_dir.path(), + )?; + + let row_height = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_row_height".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "row_index": 5 + }), + }, + temp_dir.path(), + )?; + assert_eq!(row_height.row_height, Some(25.0)); + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "cleanup_and_validate_sheet".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1" + }), + }, + temp_dir.path(), + )?; + + let sheet = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "get_sheet".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1" + }), + }, + temp_dir.path(), + )?; + let restored: SpreadsheetSheet = + serde_json::from_value(sheet.serialized_dict.expect("sheet dict"))?; + assert_eq!( + restored.column_widths, + BTreeMap::from([(1, 12.0), (2, 12.0), (4, 20.0)]) + ); + assert_eq!( + restored.row_heights, + BTreeMap::from([(2, 18.0), (3, 21.0), (5, 25.0)]) + ); + Ok(()) +} + +#[test] +fn manager_style_registry_and_format_summaries_work() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = SpreadsheetArtifactManager::default(); + let created = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Styles" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_sheet".to_string(), + args: serde_json::json!({ "name": "Sheet1" }), + }, + temp_dir.path(), + )?; + + let text_style = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_text_style".to_string(), + args: serde_json::json!({ + "style": { + "bold": true, + "italic": true, + "underline": true, + "font_size": 14.0, + "font_color": "#112233", + "text_alignment": "center", + "anchor": "middle", + "vertical_text_orientation": "stacked", + "text_rotation": 90, + "paragraph_spacing": true, + "bottom_inset": 1.0, + "left_inset": 2.0, + "right_inset": 3.0, + "top_inset": 4.0, + "font_family": "IBM Plex Sans", + "font_scheme": "minor", + "typeface": "IBM Plex Sans", + "font_face": { + "font_family": "IBM Plex Sans", + "font_scheme": "minor", + "typeface": "IBM Plex Sans" + } + } + }), + }, + temp_dir.path(), + )?; + let text_style_id = text_style.style_id.expect("text style id"); + + let fill = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_fill".to_string(), + args: serde_json::json!({ + "fill": { + "solid_fill_color": "#ffeeaa", + "pattern_type": "solid", + "pattern_foreground_color": "#ffeeaa", + "pattern_background_color": "#221100", + "color_transforms": ["tint:0.2"], + "gradient_fill_type": "linear", + "gradient_stops": [ + { "position": 0.0, "color": "#ffeeaa" }, + { "position": 1.0, "color": "#aa5500" } + ], + "gradient_kind": "linear", + "angle": 45.0, + "scaled": true, + "path_type": "rect", + "fill_rectangle": { + "left": 0.0, + "right": 1.0, + "top": 0.0, + "bottom": 1.0 + }, + "image_reference": "image://fill" + } + }), + }, + temp_dir.path(), + )?; + let fill_id = fill.style_id.expect("fill id"); + + let border = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_border".to_string(), + args: serde_json::json!({ + "border": { + "top": { "style": "solid", "color": "#111111" }, + "right": { "style": "dashed", "color": "#222222" }, + "bottom": { "style": "double", "color": "#333333" }, + "left": { "style": "solid", "color": "#444444" } + } + }), + }, + temp_dir.path(), + )?; + let border_id = border.style_id.expect("border id"); + + let number_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_number_format".to_string(), + args: serde_json::json!({ + "number_format": { + "format_id": 4 + } + }), + }, + temp_dir.path(), + )?; + let number_format_id = number_format.style_id.expect("number format id"); + + let base_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_cell_format".to_string(), + args: serde_json::json!({ + "format": { + "text_style_id": text_style_id, + "number_format_id": number_format_id, + "alignment": { + "horizontal": "center", + "vertical": "middle" + } + } + }), + }, + temp_dir.path(), + )?; + let base_format_id = base_format.style_id.expect("base format id"); + + let derived_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_cell_format".to_string(), + args: serde_json::json!({ + "format": { + "fill_id": fill_id, + "border_id": border_id, + "wrap_text": true, + "base_cell_style_format_id": base_format_id + } + }), + }, + temp_dir.path(), + )?; + let derived_format_id = derived_format.style_id.expect("derived format id"); + + let merged_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_cell_format".to_string(), + args: serde_json::json!({ + "source_format_id": derived_format_id, + "merge_with_existing_components": true, + "format": { + "alignment": { + "vertical": "bottom" + } + } + }), + }, + temp_dir.path(), + )?; + let merged_format_id = merged_format.style_id.expect("merged format id"); + + let differential_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_differential_format".to_string(), + args: serde_json::json!({ + "format": { + "fill_id": fill_id, + "wrap_text": true + } + }), + }, + temp_dir.path(), + )?; + let differential_format_id = differential_format.style_id.expect("dxf id"); + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_cell_style".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "address": "A1", + "style_index": merged_format_id + }), + }, + temp_dir.path(), + )?; + + let summary = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_cell_format_summary".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "address": "A1" + }), + }, + temp_dir.path(), + )?; + assert_eq!( + summary.cell_format_summary, + Some(SpreadsheetCellFormatSummary { + style_index: merged_format_id, + text_style: Some(SpreadsheetTextStyle { + bold: Some(true), + italic: Some(true), + underline: Some(true), + font_size: Some(14.0), + font_color: Some("#112233".to_string()), + text_alignment: Some("center".to_string()), + anchor: Some("middle".to_string()), + vertical_text_orientation: Some("stacked".to_string()), + text_rotation: Some(90), + paragraph_spacing: Some(true), + bottom_inset: Some(1.0), + left_inset: Some(2.0), + right_inset: Some(3.0), + top_inset: Some(4.0), + font_family: Some("IBM Plex Sans".to_string()), + font_scheme: Some("minor".to_string()), + typeface: Some("IBM Plex Sans".to_string()), + font_face: Some(SpreadsheetFontFace { + font_family: Some("IBM Plex Sans".to_string()), + font_scheme: Some("minor".to_string()), + typeface: Some("IBM Plex Sans".to_string()), + }), + }), + fill: Some(SpreadsheetFill { + solid_fill_color: Some("#ffeeaa".to_string()), + pattern_type: Some("solid".to_string()), + pattern_foreground_color: Some("#ffeeaa".to_string()), + pattern_background_color: Some("#221100".to_string()), + color_transforms: vec!["tint:0.2".to_string()], + gradient_fill_type: Some("linear".to_string()), + gradient_stops: vec![ + crate::SpreadsheetGradientStop { + position: 0.0, + color: "#ffeeaa".to_string(), + }, + crate::SpreadsheetGradientStop { + position: 1.0, + color: "#aa5500".to_string(), + }, + ], + gradient_kind: Some("linear".to_string()), + angle: Some(45.0), + scaled: Some(true), + path_type: Some("rect".to_string()), + fill_rectangle: Some(crate::SpreadsheetFillRectangle { + left: 0.0, + right: 1.0, + top: 0.0, + bottom: 1.0, + }), + image_reference: Some("image://fill".to_string()), + }), + border: Some(crate::SpreadsheetBorder { + top: Some(crate::SpreadsheetBorderLine { + style: Some("solid".to_string()), + color: Some("#111111".to_string()), + }), + right: Some(crate::SpreadsheetBorderLine { + style: Some("dashed".to_string()), + color: Some("#222222".to_string()), + }), + bottom: Some(crate::SpreadsheetBorderLine { + style: Some("double".to_string()), + color: Some("#333333".to_string()), + }), + left: Some(crate::SpreadsheetBorderLine { + style: Some("solid".to_string()), + color: Some("#444444".to_string()), + }), + }), + alignment: Some(crate::SpreadsheetAlignment { + horizontal: Some("center".to_string()), + vertical: Some("bottom".to_string()), + }), + number_format: Some(SpreadsheetNumberFormat { + format_id: Some(4), + format_code: Some("#,##0.00".to_string()), + }), + wrap_text: Some(true), + }) + ); + + let retrieved_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_cell_format".to_string(), + args: serde_json::json!({ "id": merged_format_id }), + }, + temp_dir.path(), + )?; + let retrieved_format: SpreadsheetCellFormat = + serde_json::from_value(retrieved_format.serialized_dict.expect("cell format"))?; + assert_eq!( + retrieved_format, + SpreadsheetCellFormat { + text_style_id: None, + fill_id: Some(fill_id), + border_id: Some(border_id), + alignment: Some(crate::SpreadsheetAlignment { + horizontal: None, + vertical: Some("bottom".to_string()), + }), + number_format_id: None, + wrap_text: Some(true), + base_cell_style_format_id: Some(base_format_id), + } + ); + + let retrieved_number_format = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_number_format".to_string(), + args: serde_json::json!({ "id": number_format_id }), + }, + temp_dir.path(), + )?; + assert_eq!( + serde_json::from_value::( + retrieved_number_format + .serialized_dict + .expect("number format") + )?, + SpreadsheetNumberFormat { + format_id: Some(4), + format_code: Some("#,##0.00".to_string()), + } + ); + + let retrieved_text_style = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_text_style".to_string(), + args: serde_json::json!({ "id": text_style_id }), + }, + temp_dir.path(), + )?; + assert_eq!( + serde_json::from_value::( + retrieved_text_style.serialized_dict.expect("text style") + )? + .bold, + Some(true) + ); + + let range_summary = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_range_format_summary".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A1:B2" + }), + }, + temp_dir.path(), + )?; + assert_eq!(range_summary.top_left_style_index, Some(merged_format_id)); + assert_eq!( + range_summary + .range_format + .as_ref() + .map(|format| format.range.clone()), + Some("A1:B2".to_string()) + ); + + let retrieved_dxf = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "get_differential_format".to_string(), + args: serde_json::json!({ "id": differential_format_id }), + }, + temp_dir.path(), + )?; + assert_eq!( + serde_json::from_value::( + retrieved_dxf.serialized_dict.expect("differential format") + )? + .wrap_text, + Some(true) + ); + Ok(()) +} + +#[test] +fn sheet_references_resolve_cells_and_ranges() -> Result<(), Box> { + let sheet = SpreadsheetSheet::new("Sheet1".to_string()); + assert_eq!( + sheet.reference("A1")?, + SpreadsheetSheetReference::Cell { + cell_ref: sheet.cell_ref("A1")?, + } + ); + assert_eq!( + sheet.reference("A1:B2")?, + SpreadsheetSheetReference::Range { + range_ref: sheet.range_ref("A1:B2")?, + } + ); + Ok(()) +} + +#[test] +fn manager_get_reference_and_xlsx_import_preserve_workbook_name() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let path = temp_dir.path().join("named.xlsx"); + + let mut artifact = SpreadsheetArtifact::new(Some("Named Workbook".to_string())); + artifact.create_sheet("Sheet1".to_string())?.set_value( + CellAddress::parse("A1")?, + Some(SpreadsheetCellValue::Integer(9)), + )?; + artifact.export(&path)?; + + let restored = SpreadsheetArtifact::from_source_file(&path, None)?; + assert_eq!(restored.name, Some("Named Workbook".to_string())); + + let mut manager = SpreadsheetArtifactManager::default(); + let imported = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "read".to_string(), + args: serde_json::json!({ "path": path }), + }, + temp_dir.path(), + )?; + let artifact_id = imported.artifact_id; + + let cell_reference = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "get_reference".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "reference": "A1" + }), + }, + temp_dir.path(), + )?; + assert_eq!( + cell_reference + .raw_cell + .as_ref() + .and_then(|cell| cell.value.clone()), + Some(SpreadsheetCellValue::Integer(9)) + ); + + let range_reference = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "get_reference".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "reference": "A1:B2" + }), + }, + temp_dir.path(), + )?; + assert_eq!( + range_reference + .range_ref + .as_ref() + .map(|range_ref| range_ref.address.clone()), + Some("A1:B2".to_string()) + ); + Ok(()) +} + +#[test] +fn manager_render_actions_support_workbook_sheet_and_range() +-> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let mut manager = SpreadsheetArtifactManager::default(); + let created = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: None, + action: "create".to_string(), + args: serde_json::json!({ "name": "Render" }), + }, + temp_dir.path(), + )?; + let artifact_id = created.artifact_id; + + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "create_sheet".to_string(), + args: serde_json::json!({ "name": "Sheet1" }), + }, + temp_dir.path(), + )?; + manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "set_range_values".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A1:C4", + "values": [ + ["h1", "h2", "h3"], + ["a", 1, 2], + ["b", 3, 4], + ["c", 5, 6] + ] + }), + }, + temp_dir.path(), + )?; + + let workbook = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "render_workbook".to_string(), + args: serde_json::json!({ + "output_path": temp_dir.path().join("workbook-previews"), + "include_headers": false + }), + }, + temp_dir.path(), + )?; + assert_eq!(workbook.exported_paths.len(), 1); + assert!(workbook.exported_paths[0].exists()); + + let sheet = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id.clone()), + action: "render_sheet".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "output_path": temp_dir.path().join("sheet-preview.html"), + "center_address": "B3", + "width": 220, + "height": 90, + "scale": 1.5, + "performance_mode": true + }), + }, + temp_dir.path(), + )?; + assert_eq!(sheet.exported_paths.len(), 1); + assert!(sheet.exported_paths[0].exists()); + assert!( + sheet + .rendered_html + .as_ref() + .is_some_and(|html| html.contains("data-performance-mode=\"true\"")) + ); + + let range = manager.execute( + SpreadsheetArtifactRequest { + artifact_id: Some(artifact_id), + action: "render_range".to_string(), + args: serde_json::json!({ + "sheet_name": "Sheet1", + "range": "A2:C4", + "output_path": temp_dir.path().join("range-preview.html"), + "include_headers": true + }), + }, + temp_dir.path(), + )?; + assert_eq!(range.exported_paths.len(), 1); + assert_eq!( + range + .range_ref + .as_ref() + .map(|range_ref| range_ref.address.clone()), + Some("A2:C4".to_string()) + ); + assert!( + range + .rendered_html + .as_ref() + .is_some_and(|html| html.contains("A")) + ); + Ok(()) +} diff --git a/codex-rs/artifact-spreadsheet/src/xlsx.rs b/codex-rs/artifact-spreadsheet/src/xlsx.rs new file mode 100644 index 0000000000..5175f3b51e --- /dev/null +++ b/codex-rs/artifact-spreadsheet/src/xlsx.rs @@ -0,0 +1,860 @@ +use std::collections::BTreeMap; +use std::fs::File; +use std::io::Read; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; + +use regex::Regex; +use zip::ZipArchive; +use zip::ZipWriter; +use zip::write::SimpleFileOptions; + +use crate::CellAddress; +use crate::CellRange; +use crate::SpreadsheetArtifact; +use crate::SpreadsheetArtifactError; +use crate::SpreadsheetCell; +use crate::SpreadsheetCellValue; +use crate::SpreadsheetSheet; + +pub(crate) fn write_xlsx( + artifact: &mut SpreadsheetArtifact, + path: &Path, +) -> Result { + if artifact.auto_recalculate { + artifact.recalculate(); + } + for sheet in &mut artifact.sheets { + sheet.cleanup_and_validate_sheet()?; + } + + let file = File::create(path).map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + let mut zip = ZipWriter::new(file); + let options = SimpleFileOptions::default(); + + let sheet_count = artifact.sheets.len().max(1); + zip.start_file("[Content_Types].xml", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(content_types_xml(sheet_count).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.add_directory("_rels/", options).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + zip.start_file("_rels/.rels", options).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + zip.write_all(root_relationships_xml().as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.add_directory("docProps/", options).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + zip.start_file("docProps/app.xml", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(app_xml(artifact).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.start_file("docProps/core.xml", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(core_xml(artifact).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.add_directory("xl/", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.start_file("xl/workbook.xml", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(workbook_xml(artifact).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.add_directory("xl/_rels/", options).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + zip.start_file("xl/_rels/workbook.xml.rels", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(workbook_relationships_xml(artifact).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.start_file("xl/styles.xml", options).map_err(|error| { + SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + } + })?; + zip.write_all(styles_xml(artifact).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + zip.add_directory("xl/worksheets/", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + if artifact.sheets.is_empty() { + let empty = SpreadsheetSheet::new("Sheet1".to_string()); + zip.start_file("xl/worksheets/sheet1.xml", options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(sheet_xml(&empty).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + } else { + for (index, sheet) in artifact.sheets.iter().enumerate() { + zip.start_file(format!("xl/worksheets/sheet{}.xml", index + 1), options) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + zip.write_all(sheet_xml(sheet).as_bytes()) + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + } + } + + zip.finish() + .map_err(|error| SpreadsheetArtifactError::ExportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + Ok(path.to_path_buf()) +} + +pub(crate) fn import_xlsx( + path: &Path, + artifact_id: Option, +) -> Result { + let file = File::open(path).map_err(|error| SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + let mut archive = + ZipArchive::new(file).map_err(|error| SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + + let workbook_xml = read_zip_entry(&mut archive, "xl/workbook.xml", path)?; + let workbook_rels = read_zip_entry(&mut archive, "xl/_rels/workbook.xml.rels", path)?; + let workbook_name = if archive.by_name("docProps/core.xml").is_ok() { + let title = + extract_workbook_title(&read_zip_entry(&mut archive, "docProps/core.xml", path)?); + (!title.trim().is_empty()).then_some(title) + } else { + None + }; + let shared_strings = if archive.by_name("xl/sharedStrings.xml").is_ok() { + Some(parse_shared_strings(&read_zip_entry( + &mut archive, + "xl/sharedStrings.xml", + path, + )?)?) + } else { + None + }; + + let relationships = parse_relationships(&workbook_rels)?; + let sheets = parse_sheet_definitions(&workbook_xml)? + .into_iter() + .map(|(name, relation)| { + let target = relationships.get(&relation).ok_or_else(|| { + SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: format!("missing relationship `{relation}` for sheet `{name}`"), + } + })?; + let normalized = if target.starts_with('/') { + target.trim_start_matches('/').to_string() + } else if target.starts_with("xl/") { + target.clone() + } else { + format!("xl/{target}") + }; + Ok((name, normalized)) + }) + .collect::, SpreadsheetArtifactError>>()?; + + let mut artifact = SpreadsheetArtifact::new(workbook_name.or_else(|| { + path.file_stem() + .and_then(|value| value.to_str()) + .map(str::to_string) + })); + if let Some(artifact_id) = artifact_id { + artifact.artifact_id = artifact_id; + } + artifact.sheets.clear(); + + for (name, target) in sheets { + let xml = read_zip_entry(&mut archive, &target, path)?; + let sheet = parse_sheet(&name, &xml, shared_strings.as_deref())?; + artifact.sheets.push(sheet); + } + + Ok(artifact) +} + +fn read_zip_entry( + archive: &mut ZipArchive, + entry: &str, + path: &Path, +) -> Result { + let mut file = + archive + .by_name(entry) + .map_err(|error| SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + let mut text = String::new(); + file.read_to_string(&mut text) + .map_err(|error| SpreadsheetArtifactError::ImportFailed { + path: path.to_path_buf(), + message: error.to_string(), + })?; + Ok(text) +} + +fn parse_sheet_definitions( + workbook_xml: &str, +) -> Result, SpreadsheetArtifactError> { + let regex = Regex::new(r#"]*)/?>"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + let mut sheets = Vec::new(); + for captures in regex.captures_iter(workbook_xml) { + let Some(attributes) = captures.get(1).map(|value| value.as_str()) else { + continue; + }; + let Some(name) = extract_attribute(attributes, "name") else { + continue; + }; + let relation = extract_attribute(attributes, "r:id") + .or_else(|| extract_attribute(attributes, "id")) + .unwrap_or_default(); + sheets.push((xml_unescape(&name), relation)); + } + Ok(sheets) +} + +fn parse_relationships(xml: &str) -> Result, SpreadsheetArtifactError> { + let regex = Regex::new(r#"]*)/?>"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + Ok(regex + .captures_iter(xml) + .filter_map(|captures| { + let attributes = captures.get(1)?.as_str(); + let id = extract_attribute(attributes, "Id")?; + let target = extract_attribute(attributes, "Target")?; + Some((id, target)) + }) + .collect()) +} + +fn parse_shared_strings(xml: &str) -> Result, SpreadsheetArtifactError> { + let regex = Regex::new(r#"(?s)]*>(.*?)"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + regex + .captures_iter(xml) + .filter_map(|captures| captures.get(1).map(|value| value.as_str())) + .map(all_text_nodes) + .collect() +} + +fn parse_sheet( + name: &str, + xml: &str, + shared_strings: Option<&[String]>, +) -> Result { + let mut sheet = SpreadsheetSheet::new(name.to_string()); + + if let Some(sheet_view) = first_tag_attributes(xml, "sheetView") + && let Some(show_grid_lines) = extract_attribute(&sheet_view, "showGridLines") + { + sheet.show_grid_lines = show_grid_lines != "0"; + } + if let Some(format_pr) = first_tag_attributes(xml, "sheetFormatPr") { + sheet.default_row_height = extract_attribute(&format_pr, "defaultRowHeight") + .and_then(|value| value.parse::().ok()); + sheet.default_column_width = extract_attribute(&format_pr, "defaultColWidth") + .and_then(|value| value.parse::().ok()); + } + + let col_regex = Regex::new(r#"]*)/?>"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + for captures in col_regex.captures_iter(xml) { + let Some(attributes) = captures.get(1).map(|value| value.as_str()) else { + continue; + }; + let Some(min) = + extract_attribute(attributes, "min").and_then(|value| value.parse::().ok()) + else { + continue; + }; + let Some(max) = + extract_attribute(attributes, "max").and_then(|value| value.parse::().ok()) + else { + continue; + }; + let Some(width) = + extract_attribute(attributes, "width").and_then(|value| value.parse::().ok()) + else { + continue; + }; + for column in min..=max { + sheet.column_widths.insert(column, width); + } + } + + let row_regex = Regex::new(r#"(?s)]*)>(.*?)"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + let cell_regex = Regex::new(r#"(?s)]*)>(.*?)"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + for row_captures in row_regex.captures_iter(xml) { + let row_attributes = row_captures + .get(1) + .map(|value| value.as_str()) + .unwrap_or_default(); + if let Some(row_index) = + extract_attribute(row_attributes, "r").and_then(|value| value.parse::().ok()) + && let Some(height) = + extract_attribute(row_attributes, "ht").and_then(|value| value.parse::().ok()) + && row_index > 0 + && height > 0.0 + { + sheet.row_heights.insert(row_index, height); + } + let Some(row_body) = row_captures.get(2).map(|value| value.as_str()) else { + continue; + }; + for cell_captures in cell_regex.captures_iter(row_body) { + let Some(attributes) = cell_captures.get(1).map(|value| value.as_str()) else { + continue; + }; + let Some(body) = cell_captures.get(2).map(|value| value.as_str()) else { + continue; + }; + let Some(address) = extract_attribute(attributes, "r") else { + continue; + }; + let address = CellAddress::parse(&address)?; + let style_index = extract_attribute(attributes, "s") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let cell_type = extract_attribute(attributes, "t").unwrap_or_default(); + let formula = first_tag_text(body, "f").map(|value| format!("={value}")); + let value = parse_cell_value(body, &cell_type, shared_strings)?; + + let cell = SpreadsheetCell { + value, + formula, + style_index, + citations: Vec::new(), + }; + if !cell.is_empty() { + sheet.cells.insert(address, cell); + } + } + } + + let merge_regex = Regex::new(r#"]*)/?>"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + for captures in merge_regex.captures_iter(xml) { + let Some(attributes) = captures.get(1).map(|value| value.as_str()) else { + continue; + }; + if let Some(reference) = extract_attribute(attributes, "ref") { + sheet.merged_ranges.push(CellRange::parse(&reference)?); + } + } + + Ok(sheet) +} + +fn parse_cell_value( + body: &str, + cell_type: &str, + shared_strings: Option<&[String]>, +) -> Result, SpreadsheetArtifactError> { + let inline_text = first_tag_text(body, "t").map(|value| xml_unescape(&value)); + let raw_value = first_tag_text(body, "v").map(|value| xml_unescape(&value)); + + let parsed = match cell_type { + "inlineStr" => inline_text.map(SpreadsheetCellValue::String), + "s" => raw_value + .and_then(|value| value.parse::().ok()) + .and_then(|index| shared_strings.and_then(|entries| entries.get(index).cloned())) + .map(SpreadsheetCellValue::String), + "b" => raw_value.map(|value| SpreadsheetCellValue::Bool(value == "1")), + "str" => raw_value.map(SpreadsheetCellValue::String), + "e" => raw_value.map(SpreadsheetCellValue::Error), + _ => match raw_value { + Some(value) => { + if let Ok(integer) = value.parse::() { + Some(SpreadsheetCellValue::Integer(integer)) + } else if let Ok(float) = value.parse::() { + Some(SpreadsheetCellValue::Float(float)) + } else { + Some(SpreadsheetCellValue::String(value)) + } + } + None => None, + }, + }; + Ok(parsed) +} + +fn content_types_xml(sheet_count: usize) -> String { + let mut overrides = String::new(); + for index in 1..=sheet_count { + overrides.push_str(&format!( + r#""# + )); + } + format!( + "{}{}{}{}{}{}{}{}{}{}", + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + overrides, + r#""# + ) +} + +fn root_relationships_xml() -> &'static str { + concat!( + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""# + ) +} + +fn app_xml(artifact: &SpreadsheetArtifact) -> String { + let title = artifact + .name + .clone() + .unwrap_or_else(|| "Spreadsheet".to_string()); + format!( + concat!( + r#""#, + r#""#, + r#"Codex"#, + r#"0"#, + r#"false"#, + r#"Worksheets{}"#, + r#"{}"#, + r#"OpenAI"#, + r#"{}"#, + r#""# + ), + artifact.sheets.len(), + artifact.sheets.len(), + artifact + .sheets + .iter() + .map(|sheet| format!(r#"{}"#, xml_escape(&sheet.name))) + .collect::>() + .join(""), + xml_escape(&title), + ) +} + +fn core_xml(artifact: &SpreadsheetArtifact) -> String { + let title = artifact + .name + .clone() + .unwrap_or_else(|| artifact.artifact_id.clone()); + format!( + concat!( + r#""#, + r#""#, + r#"{}"#, + r#"Codex"#, + r#"Codex"#, + r#""# + ), + xml_escape(&title), + ) +} + +fn workbook_xml(artifact: &SpreadsheetArtifact) -> String { + let sheets = if artifact.sheets.is_empty() { + r#""#.to_string() + } else { + artifact + .sheets + .iter() + .enumerate() + .map(|(index, sheet)| { + format!( + r#""#, + xml_escape(&sheet.name), + index + 1, + index + 1 + ) + }) + .collect::>() + .join("") + }; + format!( + "{}{}{}{}{}", + r#""#, + r#""#, + r#""#, + sheets, + r#""# + ) +} + +fn workbook_relationships_xml(artifact: &SpreadsheetArtifact) -> String { + let sheet_relationships = if artifact.sheets.is_empty() { + r#""#.to_string() + } else { + artifact + .sheets + .iter() + .enumerate() + .map(|(index, _)| { + format!( + r#""#, + index + 1, + index + 1 + ) + }) + .collect::>() + .join("") + }; + let style_relation_id = artifact.sheets.len().max(1) + 1; + format!( + "{}{}{}{}", + r#""#, + r#""#, + sheet_relationships, + style_relation_id, + r#""# + ) +} + +fn styles_xml(artifact: &SpreadsheetArtifact) -> String { + let max_style_index = artifact + .sheets + .iter() + .flat_map(|sheet| sheet.cells.values().map(|cell| cell.style_index)) + .max() + .unwrap_or(0); + let cell_xfs = (0..=max_style_index) + .map(|_| r#""#) + .collect::>() + .join(""); + format!( + concat!( + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#"{}"#, + r#""#, + r#""# + ), + max_style_index + 1, + cell_xfs, + ) +} + +fn sheet_xml(sheet: &SpreadsheetSheet) -> String { + let mut rows = BTreeMap::>::new(); + for row_index in sheet.row_heights.keys() { + rows.entry(*row_index).or_default(); + } + for (address, cell) in &sheet.cells { + rows.entry(address.row).or_default().push((*address, cell)); + } + + let sheet_data = rows + .into_iter() + .map(|(row_index, mut entries)| { + entries.sort_by_key(|(address, _)| address.column); + let cells = entries + .into_iter() + .map(|(address, cell)| cell_xml(address, cell)) + .collect::>() + .join(""); + let height = sheet + .row_heights + .get(&row_index) + .map(|value| format!(r#" ht="{value}" customHeight="1""#)) + .unwrap_or_default(); + format!(r#"{cells}"#) + }) + .collect::>() + .join(""); + + let cols = if sheet.column_widths.is_empty() { + String::new() + } else { + let mut groups = Vec::new(); + let mut iter = sheet.column_widths.iter().peekable(); + while let Some((&start, &width)) = iter.next() { + let mut end = start; + while let Some((next_column, next_width)) = + iter.peek().map(|(column, width)| (**column, **width)) + { + if next_column == end + 1 && (next_width - width).abs() < f64::EPSILON { + end = next_column; + iter.next(); + } else { + break; + } + } + groups.push(format!( + r#""# + )); + } + format!("{}", groups.join("")) + }; + + let merge_cells = if sheet.merged_ranges.is_empty() { + String::new() + } else { + format!( + r#"{}"#, + sheet.merged_ranges.len(), + sheet + .merged_ranges + .iter() + .map(|range| format!(r#""#, range.to_a1())) + .collect::>() + .join("") + ) + }; + + let default_row_height = sheet.default_row_height.unwrap_or(15.0); + let default_column_width = sheet.default_column_width.unwrap_or(8.43); + let grid_lines = if sheet.show_grid_lines { "1" } else { "0" }; + + format!( + "{}{}{}{}{}{}", + r#""#, + r#""#, + grid_lines, + default_row_height, + default_column_width, + cols, + sheet_data, + merge_cells, + r#""# + ) +} + +fn cell_xml(address: CellAddress, cell: &SpreadsheetCell) -> String { + let style = if cell.style_index == 0 { + String::new() + } else { + format!(r#" s="{}""#, cell.style_index) + }; + + if let Some(formula) = &cell.formula { + let formula = xml_escape(formula.trim_start_matches('=')); + let value_xml = match &cell.value { + Some(SpreadsheetCellValue::Bool(value)) => { + format!( + r#" t="b">{formula}{}"#, + usize::from(*value) + ) + } + Some(SpreadsheetCellValue::Integer(value)) => { + format!(r#">{formula}{value}"#) + } + Some(SpreadsheetCellValue::Float(value)) => { + format!(r#">{formula}{value}"#) + } + Some(SpreadsheetCellValue::String(value)) + | Some(SpreadsheetCellValue::DateTime(value)) => format!( + r#" t="str">{formula}{}"#, + xml_escape(value) + ), + Some(SpreadsheetCellValue::Error(value)) => { + format!(r#" t="e">{formula}{}"#, xml_escape(value)) + } + None => format!(r#">{formula}"#), + }; + return format!(r#" format!( + r#"{}"#, + address.to_a1(), + usize::from(*value) + ), + Some(SpreadsheetCellValue::Integer(value)) => { + format!(r#"{value}"#, address.to_a1()) + } + Some(SpreadsheetCellValue::Float(value)) => { + format!(r#"{value}"#, address.to_a1()) + } + Some(SpreadsheetCellValue::String(value)) | Some(SpreadsheetCellValue::DateTime(value)) => { + format!( + r#"{}"#, + address.to_a1(), + xml_escape(value) + ) + } + Some(SpreadsheetCellValue::Error(value)) => format!( + r#"{}"#, + address.to_a1(), + xml_escape(value) + ), + None => format!(r#""#, address.to_a1()), + } +} + +fn first_tag_attributes(xml: &str, tag: &str) -> Option { + let regex = Regex::new(&format!(r#"<{tag}\b([^>]*)/?>"#)).ok()?; + let captures = regex.captures(xml)?; + captures.get(1).map(|value| value.as_str().to_string()) +} + +fn first_tag_text(xml: &str, tag: &str) -> Option { + let regex = Regex::new(&format!(r#"(?s)<{tag}\b[^>]*>(.*?)"#)).ok()?; + let captures = regex.captures(xml)?; + captures.get(1).map(|value| value.as_str().to_string()) +} + +fn extract_workbook_title(xml: &str) -> String { + let Ok(regex) = + Regex::new(r#"(?s)<(?:[A-Za-z0-9_]+:)?title\b[^>]*>(.*?)"#) + else { + return String::new(); + }; + regex + .captures(xml) + .and_then(|captures| captures.get(1).map(|value| xml_unescape(value.as_str()))) + .unwrap_or_default() +} + +fn all_text_nodes(xml: &str) -> Result { + let regex = Regex::new(r#"(?s)]*>(.*?)"#).map_err(|error| { + SpreadsheetArtifactError::Serialization { + message: error.to_string(), + } + })?; + Ok(regex + .captures_iter(xml) + .filter_map(|captures| captures.get(1).map(|value| xml_unescape(value.as_str()))) + .collect::>() + .join("")) +} + +fn extract_attribute(attributes: &str, name: &str) -> Option { + let pattern = format!(r#"{name}="([^"]*)""#); + let regex = Regex::new(&pattern).ok()?; + let captures = regex.captures(attributes)?; + captures.get(1).map(|value| xml_unescape(value.as_str())) +} + +fn xml_escape(value: &str) -> String { + value + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} + +fn xml_unescape(value: &str) -> String { + value + .replace("'", "'") + .replace(""", "\"") + .replace(">", ">") + .replace("<", "<") + .replace("&", "&") +} diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index a3470ff1b9..620a93872e 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -298,12 +298,7 @@ fn merge_directory_app(existing: &mut DirectoryApp, incoming: DirectoryApp) { .as_deref() .map(|value| !value.trim().is_empty()) .unwrap_or(false); - let existing_description_present = existing - .description - .as_deref() - .map(|value| !value.trim().is_empty()) - .unwrap_or(false); - if !existing_description_present && incoming_description_present { + if incoming_description_present { existing.description = description; } diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index 1d955bbaaf..b197cc3d59 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -35,6 +35,7 @@ codex-mcp-server = { workspace = true } codex-protocol = { workspace = true } codex-responses-api-proxy = { workspace = true } codex-rmcp-client = { workspace = true } +codex-state = { workspace = true } codex-stdio-to-uds = { workspace = true } codex-tui = { workspace = true } libc = { workspace = true } @@ -62,3 +63,4 @@ assert_matches = { workspace = true } codex-utils-cargo-bin = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } +sqlx = { workspace = true } diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 42622f25d3..f2fd5a3bdc 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -22,7 +22,7 @@ const LOGIN_SUCCESS_MESSAGE: &str = "Successfully logged in"; fn print_login_server_start(actual_port: u16, auth_url: &str) { eprintln!( - "Starting local login server on http://localhost:{actual_port}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{auth_url}" + "Starting local login server on http://localhost:{actual_port}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{auth_url}\n\nOn a remote or headless machine? Use `codex login --device-auth` instead." ); } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 42ded11c06..f818b743e9 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -22,6 +22,8 @@ use codex_exec::Command as ExecCommand; use codex_exec::ReviewArgs; use codex_execpolicy::ExecPolicyCheckCommand; use codex_responses_api_proxy::Args as ResponsesApiProxyArgs; +use codex_state::StateRuntime; +use codex_state::state_db_path; use codex_tui::AppExitInfo; use codex_tui::Cli as TuiCli; use codex_tui::ExitReason; @@ -163,6 +165,10 @@ struct DebugCommand { enum DebugSubcommand { /// Tooling: helps debug the app server. AppServer(DebugAppServerCommand), + + /// Internal: reset local memory state for a fresh start. + #[clap(hide = true)] + ClearMemories, } #[derive(Debug, Parser)] @@ -751,6 +757,9 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { DebugSubcommand::AppServer(cmd) => { run_debug_app_server_command(cmd)?; } + DebugSubcommand::ClearMemories => { + run_debug_clear_memories_command(&root_config_overrides, &interactive).await?; + } }, Some(Subcommand::Execpolicy(ExecpolicyCommand { sub })) => match sub { ExecpolicySubcommand::Check(cmd) => run_execpolicycheck(cmd)?, @@ -808,6 +817,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { stage_width = stage_width.max(stage.len()); rows.push((name, stage, enabled)); } + rows.sort_unstable_by_key(|(name, _, _)| *name); for (name, stage, enabled) in rows { println!("{name: anyhow::Result<()> { + let cli_kv_overrides = root_config_overrides + .parse_overrides() + .map_err(anyhow::Error::msg)?; + let overrides = ConfigOverrides { + config_profile: interactive.config_profile.clone(), + ..Default::default() + }; + let config = + Config::load_with_cli_overrides_and_harness_overrides(cli_kv_overrides, overrides).await?; + + let state_path = state_db_path(config.sqlite_home.as_path()); + let mut cleared_state_db = false; + if tokio::fs::try_exists(&state_path).await? { + let state_db = StateRuntime::init( + config.sqlite_home.clone(), + config.model_provider_id.clone(), + None, + ) + .await?; + state_db.reset_memory_data_for_fresh_start().await?; + cleared_state_db = true; + } + + let memory_root = config.codex_home.join("memories"); + let removed_memory_root = match tokio::fs::remove_dir_all(&memory_root).await { + Ok(()) => true, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => false, + Err(err) => return Err(err.into()), + }; + + let mut message = if cleared_state_db { + format!("Cleared memory state from {}.", state_path.display()) + } else { + format!("No state db found at {}.", state_path.display()) + }; + + if removed_memory_root { + message.push_str(&format!(" Removed {}.", memory_root.display())); + } else { + message.push_str(&format!( + " No memory directory found at {}.", + memory_root.display() + )); + } + + println!("{message}"); + + Ok(()) +} + /// Prepend root-level overrides so they have lower precedence than /// CLI-specific ones specified after the subcommand (if any). fn prepend_config_flags( diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 396e077411..00a04693f9 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::sync::Arc; use anyhow::Context; use anyhow::Result; @@ -11,9 +12,11 @@ use codex_core::config::find_codex_home; use codex_core::config::load_global_mcp_servers; use codex_core::config::types::McpServerConfig; use codex_core::config::types::McpServerTransportConfig; +use codex_core::mcp::McpManager; use codex_core::mcp::auth::McpOAuthLoginSupport; use codex_core::mcp::auth::compute_auth_statuses; use codex_core::mcp::auth::oauth_login_support; +use codex_core::plugins::PluginsManager; use codex_protocol::protocol::McpAuthStatus; use codex_rmcp_client::delete_oauth_tokens; use codex_rmcp_client::perform_oauth_login; @@ -250,6 +253,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }; servers.insert(name.clone(), new_entry); @@ -272,6 +276,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re oauth_config.http_headers, oauth_config.env_http_headers, &Vec::new(), + None, config.mcp_oauth_callback_port, config.mcp_oauth_callback_url.as_deref(), ) @@ -327,10 +332,12 @@ async fn run_login(config_overrides: &CliConfigOverrides, login_args: LoginArgs) let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let mcp_servers = mcp_manager.effective_servers(&config, None); let LoginArgs { name, scopes } = login_args; - let Some(server) = config.mcp_servers.get().get(&name) else { + let Some(server) = mcp_servers.get(&name) else { bail!("No MCP server named '{name}' found."); }; @@ -356,6 +363,7 @@ async fn run_login(config_overrides: &CliConfigOverrides, login_args: LoginArgs) http_headers, env_http_headers, &scopes, + server.oauth_resource.as_deref(), config.mcp_oauth_callback_port, config.mcp_oauth_callback_url.as_deref(), ) @@ -371,12 +379,12 @@ async fn run_logout(config_overrides: &CliConfigOverrides, logout_args: LogoutAr let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let mcp_servers = mcp_manager.effective_servers(&config, None); let LogoutArgs { name } = logout_args; - let server = config - .mcp_servers - .get() + let server = mcp_servers .get(&name) .ok_or_else(|| anyhow!("No MCP server named '{name}' found in configuration."))?; @@ -401,14 +409,13 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let mcp_servers = mcp_manager.effective_servers(&config, None); - let mut entries: Vec<_> = config.mcp_servers.iter().collect(); + let mut entries: Vec<_> = mcp_servers.iter().collect(); entries.sort_by(|(a, _), (b, _)| a.cmp(b)); - let auth_statuses = compute_auth_statuses( - config.mcp_servers.iter(), - config.mcp_oauth_credentials_store_mode, - ) - .await; + let auth_statuses = + compute_auth_statuses(mcp_servers.iter(), config.mcp_oauth_credentials_store_mode).await; if list_args.json { let json_entries: Vec<_> = entries @@ -651,8 +658,10 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let mcp_servers = mcp_manager.effective_servers(&config, None); - let Some(server) = config.mcp_servers.get().get(&get_args.name) else { + let Some(server) = mcp_servers.get(&get_args.name) else { bail!("No MCP server named '{name}' found.", name = get_args.name); }; diff --git a/codex-rs/cli/tests/debug_clear_memories.rs b/codex-rs/cli/tests/debug_clear_memories.rs new file mode 100644 index 0000000000..d8db1ebbc4 --- /dev/null +++ b/codex-rs/cli/tests/debug_clear_memories.rs @@ -0,0 +1,141 @@ +use std::path::Path; + +use anyhow::Result; +use codex_state::StateRuntime; +use codex_state::state_db_path; +use predicates::str::contains; +use sqlx::SqlitePool; +use tempfile::TempDir; + +fn codex_command(codex_home: &Path) -> Result { + let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); + cmd.env("CODEX_HOME", codex_home); + Ok(cmd) +} + +#[tokio::test] +async fn debug_clear_memories_resets_state_and_removes_memory_dir() -> Result<()> { + let codex_home = TempDir::new()?; + let runtime = StateRuntime::init( + codex_home.path().to_path_buf(), + "test-provider".to_string(), + None, + ) + .await?; + drop(runtime); + + let thread_id = "00000000-0000-0000-0000-000000000123"; + let db_path = state_db_path(codex_home.path()); + let pool = SqlitePool::connect(&format!("sqlite://{}", db_path.display())).await?; + + sqlx::query( + r#" +INSERT INTO threads ( + id, + rollout_path, + created_at, + updated_at, + source, + agent_nickname, + agent_role, + model_provider, + cwd, + cli_version, + title, + sandbox_policy, + approval_mode, + tokens_used, + first_user_message, + archived, + archived_at, + git_sha, + git_branch, + git_origin_url, + memory_mode +) VALUES (?, ?, 1, 1, 'cli', NULL, NULL, 'test-provider', ?, '', '', 'read-only', 'on-request', 0, '', 0, NULL, NULL, NULL, NULL, 'enabled') + "#, + ) + .bind(thread_id) + .bind(codex_home.path().join("session.jsonl").display().to_string()) + .bind(codex_home.path().display().to_string()) + .execute(&pool) + .await?; + + sqlx::query( + r#" +INSERT INTO stage1_outputs ( + thread_id, + source_updated_at, + raw_memory, + rollout_summary, + generated_at, + rollout_slug, + usage_count, + last_usage, + selected_for_phase2, + selected_for_phase2_source_updated_at +) VALUES (?, 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL) + "#, + ) + .bind(thread_id) + .execute(&pool) + .await?; + + sqlx::query( + r#" +INSERT INTO jobs ( + kind, + job_key, + status, + worker_id, + ownership_token, + started_at, + finished_at, + lease_until, + retry_at, + retry_remaining, + last_error, + input_watermark, + last_success_watermark +) VALUES + ('memory_stage1', ?, 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1), + ('memory_consolidate_global', 'global', 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1) + "#, + ) + .bind(thread_id) + .execute(&pool) + .await?; + + let memory_root = codex_home.path().join("memories"); + std::fs::create_dir_all(&memory_root)?; + std::fs::write(memory_root.join("memory_summary.md"), "stale memory")?; + drop(pool); + + let mut cmd = codex_command(codex_home.path())?; + cmd.args(["debug", "clear-memories"]) + .assert() + .success() + .stdout(contains("Cleared memory state")); + + let pool = SqlitePool::connect(&format!("sqlite://{}", db_path.display())).await?; + let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs") + .fetch_one(&pool) + .await?; + assert_eq!(stage1_outputs_count, 0); + + let memory_jobs_count: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM jobs WHERE kind = 'memory_stage1' OR kind = 'memory_consolidate_global'", + ) + .fetch_one(&pool) + .await?; + assert_eq!(memory_jobs_count, 0); + + let memory_mode: String = sqlx::query_scalar("SELECT memory_mode FROM threads WHERE id = ?") + .bind(thread_id) + .fetch_one(&pool) + .await?; + assert_eq!(memory_mode, "disabled"); + assert!(!memory_root.exists()); + + Ok(()) +} diff --git a/codex-rs/cli/tests/features.rs b/codex-rs/cli/tests/features.rs index 6b2ed72f8a..17a7eff679 100644 --- a/codex-rs/cli/tests/features.rs +++ b/codex-rs/cli/tests/features.rs @@ -2,6 +2,7 @@ use std::path::Path; use anyhow::Result; use predicates::str::contains; +use pretty_assertions::assert_eq; use tempfile::TempDir; fn codex_command(codex_home: &Path) -> Result { @@ -58,3 +59,33 @@ async fn features_enable_under_development_feature_prints_warning() -> Result<() Ok(()) } + +#[tokio::test] +async fn features_list_is_sorted_alphabetically_by_feature_name() -> Result<()> { + let codex_home = TempDir::new()?; + + let mut cmd = codex_command(codex_home.path())?; + let output = cmd + .args(["features", "list"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let stdout = String::from_utf8(output)?; + + let actual_names = stdout + .lines() + .map(|line| { + line.split_once(" ") + .map(|(name, _)| name.trim_end().to_string()) + .expect("feature list output should contain aligned columns") + }) + .collect::>(); + let mut expected_names = actual_names.clone(); + expected_names.sort(); + + assert_eq!(actual_names, expected_names); + + Ok(()) +} diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index 6f6bf3b6de..2b51a9e9eb 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -4,9 +4,9 @@ //! from the local filesystem. It only applies to Business (aka Enterprise CBP) or Enterprise ChatGPT //! customers. //! -//! Today, fetching is best-effort: on error or timeout, Codex continues without cloud requirements. -//! We expect to tighten this so that Enterprise ChatGPT customers must successfully fetch these -//! requirements before Codex will run. +//! Fetching fails closed for eligible ChatGPT Business and Enterprise accounts. When cloud +//! requirements cannot be loaded for those accounts, Codex fails configuration loading rather than +//! continuing without them. use async_trait::async_trait; use base64::Engine; @@ -17,6 +17,7 @@ use chrono::Utc; use codex_backend_client::Client as BackendClient; use codex_core::AuthManager; use codex_core::auth::CodexAuth; +use codex_core::config_loader::CloudRequirementsLoadError; use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::ConfigRequirementsToml; use codex_core::util::backoff; @@ -28,17 +29,21 @@ use serde::Serialize; use sha2::Sha256; use std::path::PathBuf; use std::sync::Arc; +use std::sync::Mutex; +use std::sync::OnceLock; use std::time::Duration; use std::time::Instant; use thiserror::Error; use tokio::fs; +use tokio::task::JoinHandle; use tokio::time::sleep; use tokio::time::timeout; const CLOUD_REQUIREMENTS_TIMEOUT: Duration = Duration::from_secs(15); const CLOUD_REQUIREMENTS_MAX_ATTEMPTS: usize = 5; const CLOUD_REQUIREMENTS_CACHE_FILENAME: &str = "cloud-requirements-cache.json"; -const CLOUD_REQUIREMENTS_CACHE_TTL: Duration = Duration::from_secs(60 * 60); +const CLOUD_REQUIREMENTS_CACHE_REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60); +const CLOUD_REQUIREMENTS_CACHE_TTL: Duration = Duration::from_secs(30 * 60); const CLOUD_REQUIREMENTS_CACHE_WRITE_HMAC_KEY: &[u8] = b"codex-cloud-requirements-cache-v3-064f8542-75b4-494c-a294-97d3ce597271"; const CLOUD_REQUIREMENTS_CACHE_READ_HMAC_KEYS: &[&[u8]] = @@ -46,6 +51,11 @@ const CLOUD_REQUIREMENTS_CACHE_READ_HMAC_KEYS: &[&[u8]] = type HmacSha256 = Hmac; +fn refresher_task_slot() -> &'static Mutex>> { + static REFRESHER_TASK: OnceLock>>> = OnceLock::new(); + REFRESHER_TASK.get_or_init(|| Mutex::new(None)) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum FetchCloudRequirementsStatus { BackendClientInit, @@ -188,6 +198,7 @@ impl RequirementsFetcher for BackendRequirementsFetcher { } } +#[derive(Clone)] struct CloudRequirementsService { auth_manager: Arc, fetcher: Arc, @@ -210,16 +221,34 @@ impl CloudRequirementsService { } } - async fn fetch_with_timeout(&self) -> Option { + async fn fetch_with_timeout( + &self, + ) -> Result, CloudRequirementsLoadError> { let _timer = codex_otel::start_global_timer("codex.cloud_requirements.fetch.duration_ms", &[]); let started_at = Instant::now(); let result = timeout(self.timeout, self.fetch()) .await .inspect_err(|_| { - tracing::warn!("Timed out waiting for cloud requirements; continuing without them"); + let message = format!( + "Timed out waiting for cloud requirements after {}s", + self.timeout.as_secs() + ); + tracing::error!("{message}"); + if let Some(metrics) = codex_otel::metrics::global() { + let _ = metrics.counter( + "codex.cloud_requirements.load_failure", + 1, + &[("trigger", "startup")], + ); + } }) - .ok()?; + .map_err(|_| { + CloudRequirementsLoadError::new(format!( + "timed out waiting for cloud requirements after {}s", + self.timeout.as_secs() + )) + })??; match result.as_ref() { Some(requirements) => { @@ -237,18 +266,20 @@ impl CloudRequirementsService { } } - result + Ok(result) } - async fn fetch(&self) -> Option { - let auth = self.auth_manager.auth().await?; + async fn fetch(&self) -> Result, CloudRequirementsLoadError> { + let Some(auth) = self.auth_manager.auth().await else { + return Ok(None); + }; if !auth.is_chatgpt_auth() || !matches!( auth.account_plan_type(), Some(PlanType::Business | PlanType::Enterprise) ) { - return None; + return Ok(None); } let token_data = auth.get_token_data().ok(); let chatgpt_user_id = token_data @@ -263,7 +294,7 @@ impl CloudRequirementsService { path = %self.cache_path.display(), "Using cached cloud requirements" ); - return signed_payload.requirements(); + return Ok(signed_payload.requirements()); } Err(cache_load_status) => { self.log_cache_load_status(&cache_load_status); @@ -271,7 +302,15 @@ impl CloudRequirementsService { } self.fetch_with_retries(&auth, chatgpt_user_id, account_id) - .await? + .await + .ok_or_else(|| { + let message = "failed to load your workspace-managed config"; + tracing::error!( + path = %self.cache_path.display(), + "{message}" + ); + CloudRequirementsLoadError::new(message) + }) } async fn fetch_with_retries( @@ -301,7 +340,7 @@ impl CloudRequirementsService { Some(contents) => match parse_cloud_requirements(contents) { Ok(requirements) => requirements, Err(err) => { - tracing::warn!(error = %err, "Failed to parse cloud requirements"); + tracing::error!(error = %err, "Failed to parse cloud requirements"); return None; } }, @@ -325,6 +364,61 @@ impl CloudRequirementsService { None } + async fn refresh_cache_in_background(&self) { + loop { + sleep(CLOUD_REQUIREMENTS_CACHE_REFRESH_INTERVAL).await; + match timeout(self.timeout, self.refresh_cache()).await { + Ok(true) => {} + Ok(false) => break, + Err(_) => { + tracing::error!( + "Timed out refreshing cloud requirements cache from remote; keeping existing cache" + ); + } + } + } + } + + async fn refresh_cache(&self) -> bool { + let Some(auth) = self.auth_manager.auth().await else { + return false; + }; + if !auth.is_chatgpt_auth() + || !matches!( + auth.account_plan_type(), + Some(PlanType::Business | PlanType::Enterprise) + ) + { + return false; + } + + let token_data = auth.get_token_data().ok(); + let chatgpt_user_id = token_data + .as_ref() + .and_then(|token_data| token_data.id_token.chatgpt_user_id.as_deref()); + let account_id = auth.get_account_id(); + let account_id = account_id.as_deref(); + + if self + .fetch_with_retries(&auth, chatgpt_user_id, account_id) + .await + .is_none() + { + tracing::error!( + path = %self.cache_path.display(), + "Failed to refresh cloud requirements cache from remote" + ); + if let Some(metrics) = codex_otel::metrics::global() { + let _ = metrics.counter( + "codex.cloud_requirements.load_failure", + 1, + &[("trigger", "refresh")], + ); + } + } + true + } + async fn load_cache( &self, chatgpt_user_id: Option<&str>, @@ -452,12 +546,22 @@ pub fn cloud_requirements_loader( codex_home, CLOUD_REQUIREMENTS_TIMEOUT, ); + let refresh_service = service.clone(); let task = tokio::spawn(async move { service.fetch_with_timeout().await }); + let refresh_task = + tokio::spawn(async move { refresh_service.refresh_cache_in_background().await }); + let mut refresher_guard = refresher_task_slot().lock().unwrap_or_else(|err| { + tracing::warn!("cloud requirements refresher task slot was poisoned"); + err.into_inner() + }); + if let Some(existing_task) = refresher_guard.replace(refresh_task) { + existing_task.abort(); + } CloudRequirementsLoader::new(async move { - task.await - .inspect_err(|err| tracing::warn!(error = %err, "Cloud requirements task failed")) - .ok() - .flatten() + task.await.map_err(|err| { + tracing::error!(error = %err, "Cloud requirements task failed"); + CloudRequirementsLoadError::new(format!("cloud requirements load failed: {err}")) + })? }) } @@ -624,7 +728,7 @@ mod tests { CLOUD_REQUIREMENTS_TIMEOUT, ); let result = service.fetch().await; - assert!(result.is_none()); + assert_eq!(result, Ok(None)); } #[tokio::test] @@ -637,7 +741,7 @@ mod tests { CLOUD_REQUIREMENTS_TIMEOUT, ); let result = service.fetch().await; - assert!(result.is_none()); + assert_eq!(result, Ok(None)); } #[tokio::test] @@ -653,7 +757,7 @@ mod tests { ); assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -661,7 +765,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); } @@ -721,7 +825,11 @@ mod tests { tokio::time::advance(CLOUD_REQUIREMENTS_TIMEOUT + Duration::from_millis(1)).await; let result = handle.await.expect("cloud requirements task"); - assert!(result.is_none()); + let err = result.expect_err("cloud requirements timeout should fail closed"); + assert!( + err.to_string() + .contains("timed out waiting for cloud requirements") + ); } #[tokio::test(start_paused = true)] @@ -744,7 +852,7 @@ mod tests { assert_eq!( handle.await.expect("cloud requirements task"), - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -752,7 +860,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); } @@ -771,7 +879,7 @@ mod tests { CLOUD_REQUIREMENTS_TIMEOUT, ); - assert!(service.fetch().await.is_none()); + assert!(service.fetch().await.is_err()); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); } @@ -800,7 +908,7 @@ mod tests { assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -808,7 +916,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 0); } @@ -827,7 +935,7 @@ mod tests { assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -835,7 +943,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); let path = codex_home.path().join(CLOUD_REQUIREMENTS_CACHE_FILENAME); @@ -874,7 +982,7 @@ mod tests { assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -882,7 +990,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); } @@ -920,7 +1028,7 @@ mod tests { assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -928,7 +1036,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); } @@ -970,7 +1078,7 @@ mod tests { assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -978,7 +1086,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); } @@ -1021,7 +1129,7 @@ mod tests { assert_eq!( service.fetch().await, - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -1029,7 +1137,7 @@ mod tests { rules: None, enforce_residency: None, network: None, - }) + })) ); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); } @@ -1052,7 +1160,11 @@ mod tests { let cache_file: CloudRequirementsCacheFile = serde_json::from_str(&std::fs::read_to_string(path).expect("read cache")) .expect("parse cache"); - assert!(cache_file.signed_payload.expires_at > Utc::now()); + assert!( + cache_file.signed_payload.expires_at + <= cache_file.signed_payload.cached_at + ChronoDuration::minutes(30) + ); + assert!(cache_file.signed_payload.expires_at > cache_file.signed_payload.cached_at); assert!(cache_file.signed_payload.cached_at <= Utc::now()); assert_eq!( cache_file.signed_payload.chatgpt_user_id, @@ -1099,7 +1211,7 @@ mod tests { CLOUD_REQUIREMENTS_TIMEOUT, ); - assert!(service.fetch().await.is_none()); + assert_eq!(service.fetch().await, Ok(None)); assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); } @@ -1124,10 +1236,70 @@ mod tests { tokio::time::advance(Duration::from_secs(5)).await; tokio::task::yield_now().await; - assert!(handle.await.expect("cloud requirements task").is_none()); + let err = handle + .await + .expect("cloud requirements task") + .expect_err("cloud requirements retry exhaustion should fail closed"); + assert_eq!( + err.to_string(), + "failed to load your workspace-managed config" + ); assert_eq!( fetcher.request_count.load(Ordering::SeqCst), CLOUD_REQUIREMENTS_MAX_ATTEMPTS ); } + + #[tokio::test] + async fn refresh_from_remote_updates_cached_cloud_requirements() { + let codex_home = tempdir().expect("tempdir"); + let fetcher = Arc::new(SequenceFetcher::new(vec![ + Ok(Some("allowed_approval_policies = [\"never\"]".to_string())), + Ok(Some( + "allowed_approval_policies = [\"on-request\"]".to_string(), + )), + ])); + let service = CloudRequirementsService::new( + auth_manager_with_plan("business"), + fetcher, + codex_home.path().to_path_buf(), + CLOUD_REQUIREMENTS_TIMEOUT, + ); + + assert_eq!( + service.fetch().await, + Ok(Some(ConfigRequirementsToml { + allowed_approval_policies: Some(vec![AskForApproval::Never]), + allowed_sandbox_modes: None, + allowed_web_search_modes: None, + mcp_servers: None, + rules: None, + enforce_residency: None, + network: None, + })) + ); + + assert!(service.refresh_cache().await); + + let path = codex_home.path().join(CLOUD_REQUIREMENTS_CACHE_FILENAME); + let cache_file: CloudRequirementsCacheFile = + serde_json::from_str(&std::fs::read_to_string(path).expect("read cache")) + .expect("parse cache"); + assert_eq!( + cache_file + .signed_payload + .contents + .as_deref() + .and_then(|contents| parse_cloud_requirements(contents).ok().flatten()), + Some(ConfigRequirementsToml { + allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), + allowed_sandbox_modes: None, + allowed_web_search_modes: None, + mcp_servers: None, + rules: None, + enforce_residency: None, + network: None, + }) + ); + } } diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index 7176a1586d..31b4dcdb44 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -67,8 +67,6 @@ pub enum ResponseEvent { Completed { response_id: String, token_usage: Option, - /// Whether the client can append more items to a long-running websocket response. - can_append: bool, }, OutputTextDelta(String), ReasoningSummaryDelta { @@ -155,6 +153,8 @@ pub struct ResponsesApiRequest { pub stream: bool, pub include: Vec, #[serde(skip_serializing_if = "Option::is_none")] + pub service_tier: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub prompt_cache_key: Option, #[serde(skip_serializing_if = "Option::is_none")] pub text: Option, @@ -174,6 +174,7 @@ impl From<&ResponsesApiRequest> for ResponseCreateWsRequest { store: request.store, stream: request.stream, include: request.include.clone(), + service_tier: request.service_tier.clone(), prompt_cache_key: request.prompt_cache_key.clone(), text: request.text.clone(), generate: None, @@ -197,6 +198,8 @@ pub struct ResponseCreateWsRequest { pub stream: bool, pub include: Vec, #[serde(skip_serializing_if = "Option::is_none")] + pub service_tier: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub prompt_cache_key: Option, #[serde(skip_serializing_if = "Option::is_none")] pub text: Option, @@ -206,20 +209,12 @@ pub struct ResponseCreateWsRequest { pub client_metadata: Option>, } -#[derive(Debug, Serialize)] -pub struct ResponseAppendWsRequest { - pub input: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub client_metadata: Option>, -} #[derive(Debug, Serialize)] #[serde(tag = "type")] #[allow(clippy::large_enum_variant)] pub enum ResponsesWsRequest { #[serde(rename = "response.create")] ResponseCreate(ResponseCreateWsRequest), - #[serde(rename = "response.append")] - ResponseAppend(ResponseAppendWsRequest), } pub fn create_text_param_for_request( diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs index 48cc1d7002..cb6583ded7 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs @@ -4,7 +4,10 @@ use crate::endpoint::realtime_websocket::protocol::RealtimeAudioFrame; use crate::endpoint::realtime_websocket::protocol::RealtimeEvent; use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage; use crate::endpoint::realtime_websocket::protocol::RealtimeSessionConfig; -use crate::endpoint::realtime_websocket::protocol::SessionCreateSession; +use crate::endpoint::realtime_websocket::protocol::SessionAudio; +use crate::endpoint::realtime_websocket::protocol::SessionAudioFormat; +use crate::endpoint::realtime_websocket::protocol::SessionAudioInput; +use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput; use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession; use crate::endpoint::realtime_websocket::protocol::parse_realtime_event; use crate::error::ApiError; @@ -13,6 +16,8 @@ use codex_utils_rustls_provider::ensure_rustls_crypto_provider; use futures::SinkExt; use futures::StreamExt; use http::HeaderMap; +use http::HeaderValue; +use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -25,6 +30,8 @@ use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::tungstenite::Error as WsError; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tracing::debug; +use tracing::error; use tracing::info; use tracing::trace; use tungstenite::protocol::WebSocketConfig; @@ -62,15 +69,23 @@ impl WsStream { }; match command { WsCommand::Send { message, tx_result } => { + debug!("realtime websocket sending message"); let result = inner.send(message).await; let should_break = result.is_err(); + if let Err(err) = &result { + error!("realtime websocket send failed: {err}"); + } let _ = tx_result.send(result); if should_break { break; } } WsCommand::Close { tx_result } => { + info!("realtime websocket sending close"); let result = inner.close(None).await; + if let Err(err) = &result { + error!("realtime websocket close failed: {err}"); + } let _ = tx_result.send(result); break; } @@ -82,7 +97,9 @@ impl WsStream { }; match message { Ok(Message::Ping(payload)) => { + trace!(payload_len = payload.len(), "realtime websocket received ping"); if let Err(err) = inner.send(Message::Pong(payload)).await { + error!("realtime websocket failed to send pong: {err}"); let _ = tx_message.send(Err(err)); break; } @@ -93,6 +110,24 @@ impl WsStream { | Message::Close(_) | Message::Frame(_))) => { let is_close = matches!(message, Message::Close(_)); + match &message { + Message::Text(_) => trace!("realtime websocket received text frame"), + Message::Binary(binary) => { + error!( + payload_len = binary.len(), + "realtime websocket received unexpected binary frame" + ); + } + Message::Close(frame) => info!( + "realtime websocket received close frame: code={:?} reason={:?}", + frame.as_ref().map(|frame| frame.code), + frame.as_ref().map(|frame| frame.reason.as_str()) + ), + Message::Frame(_) => { + trace!("realtime websocket received raw frame"); + } + Message::Ping(_) | Message::Pong(_) => {} + } if tx_message.send(Ok(message)).is_err() { break; } @@ -101,6 +136,7 @@ impl WsStream { } } Err(err) => { + error!("realtime websocket receive failed: {err}"); let _ = tx_message.send(Err(err)); break; } @@ -108,6 +144,7 @@ impl WsStream { } } } + info!("realtime websocket pump exiting"); }); ( @@ -173,23 +210,13 @@ impl RealtimeWebsocketConnection { self.writer.send_conversation_item_create(text).await } - pub async fn send_session_update( + pub async fn send_conversation_handoff_append( &self, - backend_prompt: String, - conversation_id: Option, + handoff_id: String, + output_text: String, ) -> Result<(), ApiError> { self.writer - .send_session_update(backend_prompt, conversation_id) - .await - } - - pub async fn send_session_create( - &self, - backend_prompt: String, - conversation_id: Option, - ) -> Result<(), ApiError> { - self.writer - .send_session_create(backend_prompt, conversation_id) + .send_conversation_handoff_append(handoff_id, output_text) .await } @@ -230,13 +257,8 @@ impl RealtimeWebsocketConnection { impl RealtimeWebsocketWriter { pub async fn send_audio_frame(&self, frame: RealtimeAudioFrame) -> Result<(), ApiError> { - self.send_json(RealtimeOutboundMessage::InputAudioDelta { - delta: frame.data, - sample_rate: frame.sample_rate, - num_channels: frame.num_channels, - samples_per_channel: frame.samples_per_channel, - }) - .await + self.send_json(RealtimeOutboundMessage::InputAudioBufferAppend { audio: frame.data }) + .await } pub async fn send_conversation_item_create(&self, text: String) -> Result<(), ApiError> { @@ -253,29 +275,34 @@ impl RealtimeWebsocketWriter { .await } - pub async fn send_session_update( + pub async fn send_conversation_handoff_append( &self, - backend_prompt: String, - conversation_id: Option, + handoff_id: String, + output_text: String, ) -> Result<(), ApiError> { - self.send_json(RealtimeOutboundMessage::SessionUpdate { - session: Some(SessionUpdateSession { - backend_prompt, - conversation_id, - }), + self.send_json(RealtimeOutboundMessage::ConversationHandoffAppend { + handoff_id, + output_text, }) .await } - pub async fn send_session_create( - &self, - backend_prompt: String, - conversation_id: Option, - ) -> Result<(), ApiError> { - self.send_json(RealtimeOutboundMessage::SessionCreate { - session: SessionCreateSession { - backend_prompt, - conversation_id, + pub async fn send_session_update(&self, instructions: String) -> Result<(), ApiError> { + self.send_json(RealtimeOutboundMessage::SessionUpdate { + session: SessionUpdateSession { + kind: "quicksilver".to_string(), + instructions, + audio: SessionAudio { + input: SessionAudioInput { + format: SessionAudioFormat { + kind: "audio/pcm".to_string(), + rate: 24_000, + }, + }, + output: SessionAudioOutput { + voice: "mundo".to_string(), + }, + }, }, }) .await @@ -298,7 +325,7 @@ impl RealtimeWebsocketWriter { async fn send_json(&self, message: RealtimeOutboundMessage) -> Result<(), ApiError> { let payload = serde_json::to_string(&message) .map_err(|err| ApiError::Stream(format!("failed to encode realtime request: {err}")))?; - trace!("realtime websocket request: {payload}"); + debug!(?message, "realtime websocket request"); if self.is_closed.load(Ordering::SeqCst) { return Err(ApiError::Stream( @@ -325,12 +352,14 @@ impl RealtimeWebsocketEvents { Some(Ok(msg)) => msg, Some(Err(err)) => { self.is_closed.store(true, Ordering::SeqCst); + error!("realtime websocket read failed: {err}"); return Err(ApiError::Stream(format!( "failed to read websocket message: {err}" ))); } None => { self.is_closed.store(true, Ordering::SeqCst); + info!("realtime websocket event stream ended"); return Ok(None); } }; @@ -338,11 +367,18 @@ impl RealtimeWebsocketEvents { match msg { Message::Text(text) => { if let Some(event) = parse_realtime_event(&text) { + debug!(?event, "realtime websocket parsed event"); return Ok(Some(event)); } + debug!("realtime websocket ignored unsupported text frame"); } - Message::Close(_) => { + Message::Close(frame) => { self.is_closed.store(true, Ordering::SeqCst); + info!( + "realtime websocket closed: code={:?} reason={:?}", + frame.as_ref().map(|frame| frame.code), + frame.as_ref().map(|frame| frame.reason.as_str()) + ); return Ok(None); } Message::Binary(_) => { @@ -372,28 +408,45 @@ impl RealtimeWebsocketClient { default_headers: HeaderMap, ) -> Result { ensure_rustls_crypto_provider(); - // Keep provider base_url semantics aligned with HTTP clients; derive the ws endpoint here. - let ws_url = websocket_url_from_api_url(self.provider.base_url.as_str())?; + let ws_url = websocket_url_from_api_url( + self.provider.base_url.as_str(), + self.provider.query_params.as_ref(), + config.model.as_deref(), + )?; let mut request = ws_url .as_str() .into_client_request() .map_err(|err| ApiError::Stream(format!("failed to build websocket request: {err}")))?; - let headers = merge_request_headers(&self.provider.headers, extra_headers, default_headers); + let headers = merge_request_headers( + &self.provider.headers, + with_session_id_header(extra_headers, config.session_id.as_deref())?, + default_headers, + ); request.headers_mut().extend(headers); info!("connecting realtime websocket: {ws_url}"); - let (stream, _) = + let (stream, response) = tokio_tungstenite::connect_async_with_config(request, Some(websocket_config()), false) .await .map_err(|err| { ApiError::Stream(format!("failed to connect realtime websocket: {err}")) })?; + info!( + ws_url = %ws_url, + status = %response.status(), + "realtime websocket connected" + ); let (stream, rx_message) = WsStream::new(stream); let connection = RealtimeWebsocketConnection::new(stream, rx_message); + debug!( + session_id = config.session_id.as_deref().unwrap_or(""), + "realtime websocket sending session.update" + ); connection - .send_session_create(config.prompt, config.session_id) + .writer + .send_session_update(config.instructions) .await?; Ok(connection) } @@ -414,38 +467,99 @@ fn merge_request_headers( headers } +fn with_session_id_header( + mut headers: HeaderMap, + session_id: Option<&str>, +) -> Result { + let Some(session_id) = session_id else { + return Ok(headers); + }; + headers.insert( + "x-session-id", + HeaderValue::from_str(session_id).map_err(|err| { + ApiError::Stream(format!("invalid realtime session id header: {err}")) + })?, + ); + Ok(headers) +} + fn websocket_config() -> WebSocketConfig { WebSocketConfig::default() } -fn websocket_url_from_api_url(api_url: &str) -> Result { +fn websocket_url_from_api_url( + api_url: &str, + query_params: Option<&HashMap>, + model: Option<&str>, +) -> Result { let mut url = Url::parse(api_url) .map_err(|err| ApiError::Stream(format!("failed to parse realtime api_url: {err}")))?; + normalize_realtime_path(&mut url); + match url.scheme() { - "ws" | "wss" => { - if url.path().is_empty() || url.path() == "/" { - url.set_path("/ws"); - } - Ok(url) - } + "ws" | "wss" => {} "http" | "https" => { - if url.path().is_empty() || url.path() == "/" { - url.set_path("/ws"); - } let scheme = if url.scheme() == "http" { "ws" } else { "wss" }; let _ = url.set_scheme(scheme); - Ok(url) } - scheme => Err(ApiError::Stream(format!( - "unsupported realtime api_url scheme: {scheme}" - ))), + scheme => { + return Err(ApiError::Stream(format!( + "unsupported realtime api_url scheme: {scheme}" + ))); + } + } + + { + let mut query = url.query_pairs_mut(); + query.append_pair("intent", "quicksilver"); + if let Some(model) = model { + query.append_pair("model", model); + } + if let Some(query_params) = query_params { + for (key, value) in query_params { + if key == "intent" || (key == "model" && model.is_some()) { + continue; + } + query.append_pair(key, value); + } + } + } + + Ok(url) +} + +fn normalize_realtime_path(url: &mut Url) { + let path = url.path().to_string(); + if path.is_empty() || path == "/" { + url.set_path("/v1/realtime"); + return; + } + + if path.ends_with("/realtime") { + return; + } + + if path.ends_with("/realtime/") { + url.set_path(path.trim_end_matches('/')); + return; + } + + if path.ends_with("/v1") { + url.set_path(&format!("{path}/realtime")); + return; + } + + if path.ends_with("/v1/") { + url.set_path(&format!("{path}realtime")); } } #[cfg(test)] mod tests { use super::*; + use crate::endpoint::realtime_websocket::protocol::RealtimeHandoffMessage; + use crate::endpoint::realtime_websocket::protocol::RealtimeHandoffRequested; use http::HeaderValue; use pretty_assertions::assert_eq; use serde_json::Value; @@ -457,17 +571,18 @@ mod tests { use tokio_tungstenite::tungstenite::Message; #[test] - fn parse_session_created_event() { + fn parse_session_updated_event() { let payload = json!({ - "type": "session.created", - "session": {"id": "sess_123"} + "type": "session.updated", + "session": {"id": "sess_123", "instructions": "backend prompt"} }) .to_string(); assert_eq!( parse_realtime_event(payload.as_str()), - Some(RealtimeEvent::SessionCreated { - session_id: "sess_123".to_string() + Some(RealtimeEvent::SessionUpdated { + session_id: "sess_123".to_string(), + instructions: Some("backend prompt".to_string()), }) ); } @@ -475,10 +590,10 @@ mod tests { #[test] fn parse_audio_delta_event() { let payload = json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AAA=", "sample_rate": 48000, - "num_channels": 1, + "channels": 1, "samples_per_channel": 960 }) .to_string(); @@ -497,17 +612,59 @@ mod tests { fn parse_conversation_item_added_event() { let payload = json!({ "type": "conversation.item.added", - "item": {"type": "spawn_transcript", "seq": 7} + "item": {"type": "message", "seq": 7} }) .to_string(); assert_eq!( parse_realtime_event(payload.as_str()), Some(RealtimeEvent::ConversationItemAdded( - json!({"type": "spawn_transcript", "seq": 7}) + json!({"type": "message", "seq": 7}) )) ); } + #[test] + fn parse_conversation_item_done_event() { + let payload = json!({ + "type": "conversation.item.done", + "item": {"id": "item_123", "type": "message"} + }) + .to_string(); + assert_eq!( + parse_realtime_event(payload.as_str()), + Some(RealtimeEvent::ConversationItemDone { + item_id: "item_123".to_string(), + }) + ); + } + + #[test] + fn parse_handoff_requested_event() { + let payload = json!({ + "type": "conversation.handoff.requested", + "handoff_id": "handoff_123", + "item_id": "item_123", + "input_transcript": "delegate this", + "messages": [ + {"role": "user", "text": "delegate this"} + ] + }) + .to_string(); + + assert_eq!( + parse_realtime_event(payload.as_str()), + Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested { + handoff_id: "handoff_123".to_string(), + item_id: "item_123".to_string(), + input_transcript: "delegate this".to_string(), + messages: vec![RealtimeHandoffMessage { + role: "user".to_string(), + text: "delegate this".to_string(), + }], + })) + ); + } + #[test] fn merge_request_headers_matches_http_precedence() { let mut provider_headers = HeaderMap::new(); @@ -543,14 +700,61 @@ mod tests { #[test] fn websocket_url_from_http_base_defaults_to_ws_path() { - let url = websocket_url_from_api_url("http://127.0.0.1:8011").expect("build ws url"); - assert_eq!(url.as_str(), "ws://127.0.0.1:8011/ws"); + let url = + websocket_url_from_api_url("http://127.0.0.1:8011", None, None).expect("build ws url"); + assert_eq!( + url.as_str(), + "ws://127.0.0.1:8011/v1/realtime?intent=quicksilver" + ); } #[test] fn websocket_url_from_ws_base_defaults_to_ws_path() { - let url = websocket_url_from_api_url("wss://example.com").expect("build ws url"); - assert_eq!(url.as_str(), "wss://example.com/ws"); + let url = + websocket_url_from_api_url("wss://example.com", None, Some("realtime-test-model")) + .expect("build ws url"); + assert_eq!( + url.as_str(), + "wss://example.com/v1/realtime?intent=quicksilver&model=realtime-test-model" + ); + } + + #[test] + fn websocket_url_from_v1_base_appends_realtime_path() { + let url = websocket_url_from_api_url("https://api.openai.com/v1", None, Some("snapshot")) + .expect("build ws url"); + assert_eq!( + url.as_str(), + "wss://api.openai.com/v1/realtime?intent=quicksilver&model=snapshot" + ); + } + + #[test] + fn websocket_url_from_nested_v1_base_appends_realtime_path() { + let url = + websocket_url_from_api_url("https://example.com/openai/v1", None, Some("snapshot")) + .expect("build ws url"); + assert_eq!( + url.as_str(), + "wss://example.com/openai/v1/realtime?intent=quicksilver&model=snapshot" + ); + } + + #[test] + fn websocket_url_preserves_existing_realtime_path_and_extra_query_params() { + let url = websocket_url_from_api_url( + "https://example.com/v1/realtime?foo=bar", + Some(&HashMap::from([ + ("trace".to_string(), "1".to_string()), + ("intent".to_string(), "ignored".to_string()), + ])), + Some("snapshot"), + ) + .expect("build ws url"); + assert_eq!( + url.as_str(), + "wss://example.com/v1/realtime?foo=bar&intent=quicksilver&model=snapshot&trace=1" + ); } #[tokio::test] @@ -570,26 +774,38 @@ mod tests { .into_text() .expect("text"); let first_json: Value = serde_json::from_str(&first).expect("json"); - assert_eq!(first_json["type"], "session.create"); + assert_eq!(first_json["type"], "session.update"); assert_eq!( - first_json["session"]["backend_prompt"], + first_json["session"]["type"], + Value::String("quicksilver".to_string()) + ); + assert_eq!( + first_json["session"]["instructions"], Value::String("backend prompt".to_string()) ); assert_eq!( - first_json["session"]["conversation_id"], - Value::String("conv_1".to_string()) + first_json["session"]["audio"]["input"]["format"]["type"], + Value::String("audio/pcm".to_string()) + ); + assert_eq!( + first_json["session"]["audio"]["input"]["format"]["rate"], + Value::from(24_000) + ); + assert_eq!( + first_json["session"]["audio"]["output"]["voice"], + Value::String("mundo".to_string()) ); ws.send(Message::Text( json!({ - "type": "session.created", - "session": {"id": "sess_mock"} + "type": "session.updated", + "session": {"id": "sess_mock", "instructions": "backend prompt"} }) .to_string() .into(), )) .await - .expect("send session.created"); + .expect("send session.updated"); let second = ws .next() @@ -599,7 +815,7 @@ mod tests { .into_text() .expect("text"); let second_json: Value = serde_json::from_str(&second).expect("json"); - assert_eq!(second_json["type"], "response.input_audio.delta"); + assert_eq!(second_json["type"], "input_audio_buffer.append"); let third = ws .next() @@ -612,12 +828,24 @@ mod tests { assert_eq!(third_json["type"], "conversation.item.create"); assert_eq!(third_json["item"]["content"][0]["text"], "hello agent"); + let fourth = ws + .next() + .await + .expect("fourth msg") + .expect("fourth msg ok") + .into_text() + .expect("text"); + let fourth_json: Value = serde_json::from_str(&fourth).expect("json"); + assert_eq!(fourth_json["type"], "conversation.handoff.append"); + assert_eq!(fourth_json["handoff_id"], "handoff_1"); + assert_eq!(fourth_json["output_text"], "hello from codex"); + ws.send(Message::Text( json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 48000, - "num_channels": 1 + "channels": 1 }) .to_string() .into(), @@ -627,8 +855,11 @@ mod tests { ws.send(Message::Text( json!({ - "type": "conversation.item.added", - "item": {"type": "spawn_transcript", "seq": 2} + "type": "conversation.handoff.requested", + "handoff_id": "handoff_1", + "item_id": "item_2", + "input_transcript": "delegate now", + "messages": [{"role": "user", "text": "delegate now"}] }) .to_string() .into(), @@ -655,7 +886,8 @@ mod tests { let connection = client .connect( RealtimeSessionConfig { - prompt: "backend prompt".to_string(), + instructions: "backend prompt".to_string(), + model: Some("realtime-test-model".to_string()), session_id: Some("conv_1".to_string()), }, HeaderMap::new(), @@ -671,8 +903,9 @@ mod tests { .expect("event"); assert_eq!( created, - RealtimeEvent::SessionCreated { - session_id: "sess_mock".to_string() + RealtimeEvent::SessionUpdated { + session_id: "sess_mock".to_string(), + instructions: Some("backend prompt".to_string()), } ); @@ -689,6 +922,13 @@ mod tests { .send_conversation_item_create("hello agent".to_string()) .await .expect("send item"); + connection + .send_conversation_handoff_append( + "handoff_1".to_string(), + "hello from codex".to_string(), + ) + .await + .expect("send handoff"); let audio_event = connection .next_event() @@ -712,10 +952,15 @@ mod tests { .expect("event"); assert_eq!( added_event, - RealtimeEvent::ConversationItemAdded(json!({ - "type": "spawn_transcript", - "seq": 2 - })) + RealtimeEvent::HandoffRequested(RealtimeHandoffRequested { + handoff_id: "handoff_1".to_string(), + item_id: "item_2".to_string(), + input_transcript: "delegate now".to_string(), + messages: vec![RealtimeHandoffMessage { + role: "user".to_string(), + text: "delegate now".to_string(), + }], + }) ); connection.close().await.expect("close"); @@ -739,7 +984,7 @@ mod tests { .into_text() .expect("text"); let first_json: Value = serde_json::from_str(&first).expect("json"); - assert_eq!(first_json["type"], "session.create"); + assert_eq!(first_json["type"], "session.update"); let second = ws .next() @@ -749,18 +994,18 @@ mod tests { .into_text() .expect("text"); let second_json: Value = serde_json::from_str(&second).expect("json"); - assert_eq!(second_json["type"], "response.input_audio.delta"); + assert_eq!(second_json["type"], "input_audio_buffer.append"); ws.send(Message::Text( json!({ - "type": "session.created", - "session": {"id": "sess_after_send"} + "type": "session.updated", + "session": {"id": "sess_after_send", "instructions": "backend prompt"} }) .to_string() .into(), )) .await - .expect("send session.created"); + .expect("send session.updated"); }); let provider = Provider { @@ -781,7 +1026,8 @@ mod tests { let connection = client .connect( RealtimeSessionConfig { - prompt: "backend prompt".to_string(), + instructions: "backend prompt".to_string(), + model: Some("realtime-test-model".to_string()), session_id: Some("conv_1".to_string()), }, HeaderMap::new(), @@ -812,8 +1058,9 @@ mod tests { let next_event = next_result.expect("next event").expect("event"); assert_eq!( next_event, - RealtimeEvent::SessionCreated { - session_id: "sess_after_send".to_string() + RealtimeEvent::SessionUpdated { + session_id: "sess_after_send".to_string(), + instructions: Some("backend prompt".to_string()), } ); diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs index f2f0616fc6..82957c5ec4 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs @@ -1,49 +1,63 @@ pub use codex_protocol::protocol::RealtimeAudioFrame; pub use codex_protocol::protocol::RealtimeEvent; +pub use codex_protocol::protocol::RealtimeHandoffMessage; +pub use codex_protocol::protocol::RealtimeHandoffRequested; use serde::Serialize; use serde_json::Value; use tracing::debug; #[derive(Debug, Clone, PartialEq, Eq)] pub struct RealtimeSessionConfig { - pub prompt: String, + pub instructions: String, + pub model: Option, pub session_id: Option, } #[derive(Debug, Clone, Serialize)] #[serde(tag = "type")] pub(super) enum RealtimeOutboundMessage { - #[serde(rename = "response.input_audio.delta")] - InputAudioDelta { - delta: String, - sample_rate: u32, - num_channels: u16, - #[serde(skip_serializing_if = "Option::is_none")] - samples_per_channel: Option, + #[serde(rename = "input_audio_buffer.append")] + InputAudioBufferAppend { audio: String }, + #[serde(rename = "conversation.handoff.append")] + ConversationHandoffAppend { + handoff_id: String, + output_text: String, }, - #[serde(rename = "session.create")] - SessionCreate { session: SessionCreateSession }, #[serde(rename = "session.update")] - SessionUpdate { - #[serde(skip_serializing_if = "Option::is_none")] - session: Option, - }, + SessionUpdate { session: SessionUpdateSession }, #[serde(rename = "conversation.item.create")] ConversationItemCreate { item: ConversationItem }, } #[derive(Debug, Clone, Serialize)] pub(super) struct SessionUpdateSession { - pub(super) backend_prompt: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub(super) conversation_id: Option, + #[serde(rename = "type")] + pub(super) kind: String, + pub(super) instructions: String, + pub(super) audio: SessionAudio, } #[derive(Debug, Clone, Serialize)] -pub(super) struct SessionCreateSession { - pub(super) backend_prompt: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub(super) conversation_id: Option, +pub(super) struct SessionAudio { + pub(super) input: SessionAudioInput, + pub(super) output: SessionAudioOutput, +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct SessionAudioInput { + pub(super) format: SessionAudioFormat, +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct SessionAudioFormat { + #[serde(rename = "type")] + pub(super) kind: String, + pub(super) rate: u32, +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct SessionAudioOutput { + pub(super) voice: String, } #[derive(Debug, Clone, Serialize)] @@ -78,30 +92,25 @@ pub(super) fn parse_realtime_event(payload: &str) -> Option { } }; match message_type { - "session.created" => { - let session = parsed.get("session").and_then(Value::as_object); - let session_id = session - .and_then(|session| session.get("id")) - .and_then(Value::as_str) - .map(str::to_string) - .or_else(|| { - parsed - .get("session_id") - .and_then(Value::as_str) - .map(str::to_string) - }); - session_id.map(|id| RealtimeEvent::SessionCreated { session_id: id }) - } "session.updated" => { - let backend_prompt = parsed + let session_id = parsed .get("session") .and_then(Value::as_object) - .and_then(|session| session.get("backend_prompt")) + .and_then(|session| session.get("id")) .and_then(Value::as_str) .map(str::to_string); - Some(RealtimeEvent::SessionUpdated { backend_prompt }) + let instructions = parsed + .get("session") + .and_then(Value::as_object) + .and_then(|session| session.get("instructions")) + .and_then(Value::as_str) + .map(str::to_string); + session_id.map(|session_id| RealtimeEvent::SessionUpdated { + session_id, + instructions, + }) } - "response.output_audio.delta" => { + "conversation.output_audio.delta" => { let data = parsed .get("delta") .and_then(Value::as_str) @@ -112,7 +121,8 @@ pub(super) fn parse_realtime_event(payload: &str) -> Option { .and_then(Value::as_u64) .and_then(|v| u32::try_from(v).ok())?; let num_channels = parsed - .get("num_channels") + .get("channels") + .or_else(|| parsed.get("num_channels")) .and_then(Value::as_u64) .and_then(|v| u16::try_from(v).ok())?; Some(RealtimeEvent::AudioOut(RealtimeAudioFrame { @@ -129,10 +139,55 @@ pub(super) fn parse_realtime_event(payload: &str) -> Option { .get("item") .cloned() .map(RealtimeEvent::ConversationItemAdded), + "conversation.item.done" => parsed + .get("item") + .and_then(Value::as_object) + .and_then(|item| item.get("id")) + .and_then(Value::as_str) + .map(str::to_string) + .map(|item_id| RealtimeEvent::ConversationItemDone { item_id }), + "conversation.handoff.requested" => { + let handoff_id = parsed + .get("handoff_id") + .and_then(Value::as_str) + .map(str::to_string)?; + let item_id = parsed + .get("item_id") + .and_then(Value::as_str) + .map(str::to_string)?; + let input_transcript = parsed + .get("input_transcript") + .and_then(Value::as_str) + .map(str::to_string)?; + let messages = parsed + .get("messages") + .and_then(Value::as_array)? + .iter() + .filter_map(|message| { + let role = message.get("role").and_then(Value::as_str)?.to_string(); + let text = message.get("text").and_then(Value::as_str)?.to_string(); + Some(RealtimeHandoffMessage { role, text }) + }) + .collect(); + Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested { + handoff_id, + item_id, + input_transcript, + messages, + })) + } "error" => parsed .get("message") .and_then(Value::as_str) .map(str::to_string) + .or_else(|| { + parsed + .get("error") + .and_then(Value::as_object) + .and_then(|error| error.get("message")) + .and_then(Value::as_str) + .map(str::to_string) + }) .or_else(|| parsed.get("error").map(std::string::ToString::to_string)) .map(RealtimeEvent::Error), _ => { diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index bdd32fbd5a..925f7d52d0 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -164,6 +164,8 @@ const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state"; const X_MODELS_ETAG_HEADER: &str = "x-models-etag"; const X_REASONING_INCLUDED_HEADER: &str = "x-reasoning-included"; const OPENAI_MODEL_HEADER: &str = "openai-model"; +const WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE: &str = "websocket_connection_limit_reached"; +const WEBSOCKET_CONNECTION_LIMIT_REACHED_MESSAGE: &str = "Responses websocket connection limit reached (60 minutes). Create a new websocket connection to continue."; pub struct ResponsesWebsocketConnection { stream: Arc>>, @@ -417,6 +419,12 @@ fn map_ws_error(err: WsError, url: &Url) -> ApiError { } } +#[derive(Debug, Deserialize)] +struct WrappedWebsocketError { + code: Option, + message: Option, +} + #[derive(Debug, Deserialize)] struct WrappedWebsocketErrorEvent { #[serde(rename = "type")] @@ -424,7 +432,7 @@ struct WrappedWebsocketErrorEvent { #[serde(alias = "status_code")] status: Option, #[serde(default)] - error: Option, + error: Option, #[serde(default)] headers: Option>, } @@ -437,7 +445,10 @@ fn parse_wrapped_websocket_error_event(payload: &str) -> Option Option { +fn map_wrapped_websocket_error_event( + event: WrappedWebsocketErrorEvent, + original_payload: String, +) -> Option { let WrappedWebsocketErrorEvent { status, error, @@ -445,28 +456,29 @@ fn map_wrapped_websocket_error_event(event: WrappedWebsocketErrorEvent) -> Optio .. } = event; + if let Some(error) = error.as_ref() + && let Some(code) = error.code.as_deref() + && code == WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE + { + return Some(ApiError::Retryable { + message: error + .message + .clone() + .unwrap_or_else(|| WEBSOCKET_CONNECTION_LIMIT_REACHED_MESSAGE.to_string()), + delay: None, + }); + } + let status = StatusCode::from_u16(status?).ok()?; if status.is_success() { return None; } - let body = error.map(|error| { - serde_json::to_string_pretty(&serde_json::json!({ - "error": error - })) - .unwrap_or_else(|_| { - serde_json::json!({ - "error": error - }) - .to_string() - }) - }); - Some(ApiError::Transport(TransportError::Http { status, url: None, headers: headers.map(json_headers_to_http_headers), - body, + body: Some(original_payload), })) } @@ -551,7 +563,8 @@ async fn run_websocket_response_stream( Message::Text(text) => { trace!("websocket event: {text}"); if let Some(wrapped_error) = parse_wrapped_websocket_error_event(&text) - && let Some(error) = map_wrapped_websocket_error_event(wrapped_error) + && let Some(error) = + map_wrapped_websocket_error_event(wrapped_error, text.to_string()) { return Err(error); } @@ -639,7 +652,7 @@ mod tests { let wrapped_error = parse_wrapped_websocket_error_event(&payload) .expect("expected websocket error payload to be parsed"); - let api_error = map_wrapped_websocket_error_event(wrapped_error) + let api_error = map_wrapped_websocket_error_event(wrapped_error, payload) .expect("expected websocket error payload to map to ApiError"); let ApiError::Transport(TransportError::Http { @@ -699,7 +712,7 @@ mod tests { let wrapped_error = parse_wrapped_websocket_error_event(&payload) .expect("expected websocket error payload to be parsed"); - let api_error = map_wrapped_websocket_error_event(wrapped_error) + let api_error = map_wrapped_websocket_error_event(wrapped_error, payload) .expect("expected websocket error payload to map to ApiError"); let ApiError::Transport(TransportError::Http { status, body, .. }) = api_error else { panic!("expected ApiError::Transport(Http)"); @@ -710,6 +723,30 @@ mod tests { assert!(body.contains("Model does not support image inputs")); } + #[test] + fn parse_wrapped_websocket_error_event_with_connection_limit_maps_retryable() { + let payload = json!({ + "type": "error", + "status": 400, + "error": { + "type": "invalid_request_error", + "code": "websocket_connection_limit_reached", + "message": "Responses websocket connection limit reached (60 minutes). Create a new websocket connection to continue." + } + }) + .to_string(); + + let wrapped_error = parse_wrapped_websocket_error_event(&payload) + .expect("expected websocket error payload to be parsed"); + let api_error = map_wrapped_websocket_error_event(wrapped_error, payload) + .expect("expected websocket error payload to map to ApiError"); + let ApiError::Retryable { message, delay } = api_error else { + panic!("expected ApiError::Retryable"); + }; + assert_eq!(message, WEBSOCKET_CONNECTION_LIMIT_REACHED_MESSAGE); + assert_eq!(delay, None); + } + #[test] fn parse_wrapped_websocket_error_event_without_status_is_not_mapped() { let payload = json!({ @@ -727,7 +764,7 @@ mod tests { let wrapped_error = parse_wrapped_websocket_error_event(&payload) .expect("expected websocket error payload to be parsed"); - let api_error = map_wrapped_websocket_error_event(wrapped_error); + let api_error = map_wrapped_websocket_error_event(wrapped_error, payload); assert!(api_error.is_none()); } diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index b9152ec576..138929602b 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -19,7 +19,6 @@ pub use crate::common::MemorySummarizeInput; pub use crate::common::MemorySummarizeOutput; pub use crate::common::RawMemory; pub use crate::common::RawMemoryMetadata; -pub use crate::common::ResponseAppendWsRequest; pub use crate::common::ResponseCreateWsRequest; pub use crate::common::ResponseEvent; pub use crate::common::ResponseStream; diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 3c039380c9..d01e1d918a 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -118,14 +118,6 @@ struct ResponseCompleted { usage: Option, } -#[derive(Debug, Deserialize)] -struct ResponseDone { - #[serde(default)] - id: Option, - #[serde(default)] - usage: Option, -} - #[derive(Debug, Deserialize)] struct ResponseCompletedUsage { input_tokens: i64, @@ -324,7 +316,6 @@ pub fn process_responses_event( return Ok(Some(ResponseEvent::Completed { response_id: resp.id, token_usage: resp.usage.map(Into::into), - can_append: false, })); } Err(err) => { @@ -335,31 +326,6 @@ pub fn process_responses_event( } } } - "response.done" => { - if let Some(resp_val) = event.response { - match serde_json::from_value::(resp_val) { - Ok(resp) => { - return Ok(Some(ResponseEvent::Completed { - response_id: resp.id.unwrap_or_default(), - token_usage: resp.usage.map(Into::into), - can_append: true, - })); - } - Err(err) => { - let error = format!("failed to parse ResponseCompleted: {err}"); - debug!("{error}"); - return Err(ResponsesEventError::Api(ApiError::Stream(error))); - } - } - } - - debug!("response.done missing response payload"); - return Ok(Some(ResponseEvent::Completed { - response_id: String::new(), - token_usage: None, - can_append: true, - })); - } "response.output_item.added" => { if let Some(item_val) = event.item { if let Ok(item) = serde_json::from_value::(item_val) { @@ -639,11 +605,9 @@ mod tests { Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, }) => { assert_eq!(response_id, "resp1"); assert!(token_usage.is_none()); - assert!(!can_append); } other => panic!("unexpected third event: {other:?}"), } @@ -677,69 +641,6 @@ mod tests { } } - #[tokio::test] - async fn response_done_emits_incremental_completed() { - let done = json!({ - "type": "response.done", - "response": { - "usage": { - "input_tokens": 1, - "input_tokens_details": null, - "output_tokens": 2, - "output_tokens_details": null, - "total_tokens": 3 - } - } - }) - .to_string(); - - let sse1 = format!("event: response.done\ndata: {done}\n\n"); - - let events = collect_events(&[sse1.as_bytes()]).await; - - assert_eq!(events.len(), 1); - - match &events[0] { - Ok(ResponseEvent::Completed { - response_id, - token_usage, - can_append, - }) => { - assert_eq!(response_id, ""); - assert!(token_usage.is_some()); - assert!(*can_append); - } - other => panic!("unexpected event: {other:?}"), - } - } - - #[tokio::test] - async fn response_done_without_payload_emits_completed() { - let done = json!({ - "type": "response.done" - }) - .to_string(); - - let sse1 = format!("event: response.done\ndata: {done}\n\n"); - - let events = collect_events(&[sse1.as_bytes()]).await; - - assert_eq!(events.len(), 1); - - match &events[0] { - Ok(ResponseEvent::Completed { - response_id, - token_usage, - can_append, - }) => { - assert_eq!(response_id, ""); - assert!(token_usage.is_none()); - assert!(*can_append); - } - other => panic!("unexpected event: {other:?}"), - } - } - #[tokio::test] async fn emits_completed_without_stream_end() { let completed = json!({ @@ -770,11 +671,9 @@ mod tests { Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, }) => { assert_eq!(response_id, "resp1"); assert!(token_usage.is_none()); - assert!(!can_append); } other => panic!("unexpected event: {other:?}"), } @@ -996,8 +895,7 @@ mod tests { &events[1], ResponseEvent::Completed { response_id, - token_usage: None, - can_append: false + token_usage: None } if response_id == "resp-1" ); } @@ -1033,8 +931,7 @@ mod tests { &events[2], ResponseEvent::Completed { response_id, - token_usage: None, - can_append: false + token_usage: None } if response_id == "resp-1" ); } diff --git a/codex-rs/codex-api/tests/clients.rs b/codex-rs/codex-api/tests/clients.rs index 955ccf3fa7..63a033dea3 100644 --- a/codex-rs/codex-api/tests/clients.rs +++ b/codex-rs/codex-api/tests/clients.rs @@ -265,6 +265,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> { store: false, stream: true, include: Vec::new(), + service_tier: None, prompt_cache_key: None, text: None, }; @@ -306,6 +307,7 @@ async fn azure_default_store_attaches_ids_and_headers() -> Result<()> { store: true, stream: true, include: Vec::new(), + service_tier: None, prompt_cache_key: None, text: None, }; diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index 9f7e380665..2b61f0de60 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -3,6 +3,7 @@ use codex_api::ModelsClient; use codex_api::provider::Provider; use codex_api::provider::RetryConfig; use codex_client::ReqwestTransport; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelVisibility; @@ -78,8 +79,10 @@ async fn models_client_hits_models_endpoint() { base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, diff --git a/codex-rs/codex-api/tests/realtime_websocket_e2e.rs b/codex-rs/codex-api/tests/realtime_websocket_e2e.rs index ae8b082b93..aa11b79584 100644 --- a/codex-rs/codex-api/tests/realtime_websocket_e2e.rs +++ b/codex-rs/codex-api/tests/realtime_websocket_e2e.rs @@ -78,26 +78,34 @@ async fn realtime_ws_e2e_session_create_and_event_flow() { .into_text() .expect("text"); let first_json: Value = serde_json::from_str(&first).expect("json"); - assert_eq!(first_json["type"], "session.create"); + assert_eq!(first_json["type"], "session.update"); assert_eq!( - first_json["session"]["backend_prompt"], + first_json["session"]["type"], + Value::String("quicksilver".to_string()) + ); + assert_eq!( + first_json["session"]["instructions"], Value::String("backend prompt".to_string()) ); assert_eq!( - first_json["session"]["conversation_id"], - Value::String("conv_123".to_string()) + first_json["session"]["audio"]["input"]["format"]["type"], + Value::String("audio/pcm".to_string()) + ); + assert_eq!( + first_json["session"]["audio"]["input"]["format"]["rate"], + Value::from(24_000) ); ws.send(Message::Text( json!({ - "type": "session.created", - "session": {"id": "sess_mock"} + "type": "session.updated", + "session": {"id": "sess_mock", "instructions": "backend prompt"} }) .to_string() .into(), )) .await - .expect("send session.created"); + .expect("send session.updated"); let second = ws .next() @@ -107,14 +115,14 @@ async fn realtime_ws_e2e_session_create_and_event_flow() { .into_text() .expect("text"); let second_json: Value = serde_json::from_str(&second).expect("json"); - assert_eq!(second_json["type"], "response.input_audio.delta"); + assert_eq!(second_json["type"], "input_audio_buffer.append"); ws.send(Message::Text( json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 48000, - "num_channels": 1 + "channels": 1 }) .to_string() .into(), @@ -128,7 +136,8 @@ async fn realtime_ws_e2e_session_create_and_event_flow() { let connection = client .connect( RealtimeSessionConfig { - prompt: "backend prompt".to_string(), + instructions: "backend prompt".to_string(), + model: Some("realtime-test-model".to_string()), session_id: Some("conv_123".to_string()), }, HeaderMap::new(), @@ -144,8 +153,9 @@ async fn realtime_ws_e2e_session_create_and_event_flow() { .expect("event"); assert_eq!( created, - RealtimeEvent::SessionCreated { - session_id: "sess_mock".to_string() + RealtimeEvent::SessionUpdated { + session_id: "sess_mock".to_string(), + instructions: Some("backend prompt".to_string()), } ); @@ -189,7 +199,7 @@ async fn realtime_ws_e2e_send_while_next_event_waits() { .into_text() .expect("text"); let first_json: Value = serde_json::from_str(&first).expect("json"); - assert_eq!(first_json["type"], "session.create"); + assert_eq!(first_json["type"], "session.update"); let second = ws .next() @@ -199,18 +209,18 @@ async fn realtime_ws_e2e_send_while_next_event_waits() { .into_text() .expect("text"); let second_json: Value = serde_json::from_str(&second).expect("json"); - assert_eq!(second_json["type"], "response.input_audio.delta"); + assert_eq!(second_json["type"], "input_audio_buffer.append"); ws.send(Message::Text( json!({ - "type": "session.created", - "session": {"id": "sess_after_send"} + "type": "session.updated", + "session": {"id": "sess_after_send", "instructions": "backend prompt"} }) .to_string() .into(), )) .await - .expect("send session.created"); + .expect("send session.updated"); }) .await; @@ -218,7 +228,8 @@ async fn realtime_ws_e2e_send_while_next_event_waits() { let connection = client .connect( RealtimeSessionConfig { - prompt: "backend prompt".to_string(), + instructions: "backend prompt".to_string(), + model: Some("realtime-test-model".to_string()), session_id: Some("conv_123".to_string()), }, HeaderMap::new(), @@ -249,8 +260,9 @@ async fn realtime_ws_e2e_send_while_next_event_waits() { let next_event = next_result.expect("next event").expect("event"); assert_eq!( next_event, - RealtimeEvent::SessionCreated { - session_id: "sess_after_send".to_string() + RealtimeEvent::SessionUpdated { + session_id: "sess_after_send".to_string(), + instructions: Some("backend prompt".to_string()), } ); @@ -269,7 +281,7 @@ async fn realtime_ws_e2e_disconnected_emitted_once() { .into_text() .expect("text"); let first_json: Value = serde_json::from_str(&first).expect("json"); - assert_eq!(first_json["type"], "session.create"); + assert_eq!(first_json["type"], "session.update"); ws.send(Message::Close(None)).await.expect("send close"); }) @@ -279,7 +291,8 @@ async fn realtime_ws_e2e_disconnected_emitted_once() { let connection = client .connect( RealtimeSessionConfig { - prompt: "backend prompt".to_string(), + instructions: "backend prompt".to_string(), + model: Some("realtime-test-model".to_string()), session_id: Some("conv_123".to_string()), }, HeaderMap::new(), @@ -308,7 +321,7 @@ async fn realtime_ws_e2e_ignores_unknown_text_events() { .into_text() .expect("text"); let first_json: Value = serde_json::from_str(&first).expect("json"); - assert_eq!(first_json["type"], "session.create"); + assert_eq!(first_json["type"], "session.update"); ws.send(Message::Text( json!({ @@ -323,14 +336,14 @@ async fn realtime_ws_e2e_ignores_unknown_text_events() { ws.send(Message::Text( json!({ - "type": "session.created", - "session": {"id": "sess_after_unknown"} + "type": "session.updated", + "session": {"id": "sess_after_unknown", "instructions": "backend prompt"} }) .to_string() .into(), )) .await - .expect("send session.created"); + .expect("send session.updated"); }) .await; @@ -338,7 +351,8 @@ async fn realtime_ws_e2e_ignores_unknown_text_events() { let connection = client .connect( RealtimeSessionConfig { - prompt: "backend prompt".to_string(), + instructions: "backend prompt".to_string(), + model: Some("realtime-test-model".to_string()), session_id: Some("conv_123".to_string()), }, HeaderMap::new(), @@ -354,8 +368,9 @@ async fn realtime_ws_e2e_ignores_unknown_text_events() { .expect("event"); assert_eq!( event, - RealtimeEvent::SessionCreated { - session_id: "sess_after_unknown".to_string() + RealtimeEvent::SessionUpdated { + session_id: "sess_after_unknown".to_string(), + instructions: Some("backend prompt".to_string()), } ); diff --git a/codex-rs/codex-api/tests/sse_end_to_end.rs b/codex-rs/codex-api/tests/sse_end_to_end.rs index ca840d1b9f..f625fdcd9d 100644 --- a/codex-rs/codex-api/tests/sse_end_to_end.rs +++ b/codex-rs/codex-api/tests/sse_end_to_end.rs @@ -159,11 +159,9 @@ async fn responses_stream_parses_items_and_completed_end_to_end() -> Result<()> ResponseEvent::Completed { response_id, token_usage, - can_append, } => { assert_eq!(response_id, "resp1"); assert!(token_usage.is_none()); - assert!(!can_append); } other => panic!("unexpected third event: {other:?}"), } diff --git a/codex-rs/config/src/cloud_requirements.rs b/codex-rs/config/src/cloud_requirements.rs index cfff1824fa..1cf58563b9 100644 --- a/codex-rs/config/src/cloud_requirements.rs +++ b/codex-rs/config/src/cloud_requirements.rs @@ -4,24 +4,42 @@ use futures::future::FutureExt; use futures::future::Shared; use std::fmt; use std::future::Future; +use thiserror::Error; + +#[derive(Clone, Debug, Eq, Error, PartialEq)] +#[error("{message}")] +pub struct CloudRequirementsLoadError { + message: String, +} + +impl CloudRequirementsLoadError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} #[derive(Clone)] pub struct CloudRequirementsLoader { - // TODO(gt): This should return a Result once we can fail-closed. - fut: Shared>>, + fut: Shared< + BoxFuture<'static, Result, CloudRequirementsLoadError>>, + >, } impl CloudRequirementsLoader { pub fn new(fut: F) -> Self where - F: Future> + Send + 'static, + F: Future, CloudRequirementsLoadError>> + + Send + + 'static, { Self { fut: fut.boxed().shared(), } } - pub async fn get(&self) -> Option { + pub async fn get(&self) -> Result, CloudRequirementsLoadError> { self.fut.clone().await } } @@ -34,7 +52,7 @@ impl fmt::Debug for CloudRequirementsLoader { impl Default for CloudRequirementsLoader { fn default() -> Self { - Self::new(async { None }) + Self::new(async { Ok(None) }) } } @@ -52,7 +70,7 @@ mod tests { let counter_clone = Arc::clone(&counter); let loader = CloudRequirementsLoader::new(async move { counter_clone.fetch_add(1, Ordering::SeqCst); - Some(ConfigRequirementsToml::default()) + Ok(Some(ConfigRequirementsToml::default())) }); let (first, second) = tokio::join!(loader.get(), loader.get()); diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index c20e9e116b..85fa634c27 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -1163,6 +1163,7 @@ mod tests { matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["rm"]), decision: Decision::Forbidden, + resolved_program: None, justification: None, }], } diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index 41b9a3ae06..b85e99133d 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -10,6 +10,7 @@ mod state; pub const CONFIG_TOML_FILE: &str = "config.toml"; +pub use cloud_requirements::CloudRequirementsLoadError; pub use cloud_requirements::CloudRequirementsLoader; pub use config_requirements::ConfigRequirements; pub use config_requirements::ConfigRequirementsToml; diff --git a/codex-rs/core/BUILD.bazel b/codex-rs/core/BUILD.bazel index 5269148bc2..cbfd6cacf1 100644 --- a/codex-rs/core/BUILD.bazel +++ b/codex-rs/core/BUILD.bazel @@ -1,5 +1,14 @@ load("//:defs.bzl", "codex_rust_crate") +filegroup( + name = "model_availability_nux_fixtures", + srcs = [ + "models.json", + "tests/cli_responses_fixture.sse", + ], + visibility = ["//visibility:public"], +) + codex_rust_crate( name = "core", crate_name = "codex_core", @@ -14,6 +23,12 @@ codex_rust_crate( ) + [ "//codex-rs:node-version.txt", ], + rustc_env = { + # Askama resolves template paths relative to CARGO_MANIFEST_DIR. In + # Bazel, the Cargo-provided absolute source path points outside the + # sandbox, so keep the manifest root anchored inside the execroot. + "CARGO_MANIFEST_DIR": "codex-rs/core", + }, integration_compile_data_extra = [ "//codex-rs/apply-patch:apply_patch_tool_instructions.md", "models.json", diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index c79e905883..c3a37bb989 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -21,6 +21,7 @@ anyhow = { workspace = true } arc-swap = "1.8.2" async-channel = { workspace = true } async-trait = { workspace = true } +askama = { workspace = true } base64 = { workspace = true } bm25 = { workspace = true } chardetng = { workspace = true } @@ -41,6 +42,8 @@ codex-hooks = { workspace = true } codex-keyring-store = { workspace = true } codex-network-proxy = { workspace = true } codex-otel = { workspace = true } +codex-artifact-presentation = { workspace = true } +codex-artifact-spreadsheet = { workspace = true } codex-protocol = { workspace = true } codex-rmcp-client = { workspace = true } codex-state = { workspace = true } @@ -60,6 +63,7 @@ env-flags = { workspace = true } eventsource-stream = { workspace = true } futures = { workspace = true } http = { workspace = true } +iana-time-zone = { workspace = true } indexmap = { workspace = true } keyring = { workspace = true, features = ["crypto-rust"] } libc = { workspace = true } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index c5e85ad682..3cd7000913 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -313,6 +313,9 @@ "apps_mcp_gateway": { "type": "boolean" }, + "artifact": { + "type": "boolean" + }, "child_agents_md": { "type": "boolean" }, @@ -328,6 +331,9 @@ "connectors": { "type": "boolean" }, + "default_mode_request_user_input": { + "type": "boolean" + }, "elevated_windows_sandbox": { "type": "boolean" }, @@ -346,6 +352,9 @@ "experimental_windows_sandbox": { "type": "boolean" }, + "fast_mode": { + "type": "boolean" + }, "include_apply_patch_tool": { "type": "boolean" }, @@ -367,6 +376,9 @@ "personality": { "type": "boolean" }, + "plugins": { + "type": "boolean" + }, "powershell_utf8": { "type": "boolean" }, @@ -406,9 +418,6 @@ "shell_zsh_fork": { "type": "boolean" }, - "skill_approval": { - "type": "boolean" - }, "skill_env_var_dependency_prompt": { "type": "boolean" }, @@ -502,6 +511,9 @@ "sandbox_mode": { "$ref": "#/definitions/SandboxMode" }, + "service_tier": { + "$ref": "#/definitions/ServiceTier" + }, "tools_view_image": { "type": "boolean" }, @@ -613,7 +625,19 @@ "additionalProperties": false, "description": "Memories settings loaded from config.toml.", "properties": { - "max_raw_memories_for_global": { + "consolidation_model": { + "description": "Model used for memory consolidation.", + "type": "string" + }, + "extract_model": { + "description": "Model used for thread summarisation.", + "type": "string" + }, + "generate_memories": { + "description": "When `false`, newly created threads are stored with `memory_mode = \"disabled\"` in the state DB.", + "type": "boolean" + }, + "max_raw_memories_for_consolidation": { "description": "Maximum number of recent raw memories retained for global consolidation.", "format": "uint", "minimum": 0.0, @@ -630,22 +654,35 @@ "minimum": 0.0, "type": "integer" }, + "max_unused_days": { + "description": "Maximum number of days since a memory was last used before it becomes ineligible for phase 2 selection.", + "format": "int64", + "type": "integer" + }, "min_rollout_idle_hours": { "description": "Minimum idle time between last thread activity and memory creation (hours). > 12h recommended.", "format": "int64", "type": "integer" }, - "phase_1_model": { - "description": "Model used for thread summarisation.", - "type": "string" + "no_memories_if_mcp_or_web_search": { + "description": "When `true`, web searches and MCP tool calls mark the thread `memory_mode` as `\"polluted\"`.", + "type": "boolean" }, - "phase_2_model": { - "description": "Model used for memory consolidation.", - "type": "string" + "use_memories": { + "description": "When `false`, skip injecting memory usage instructions into developer prompts.", + "type": "boolean" } }, "type": "object" }, + "ModelAvailabilityNuxConfig": { + "additionalProperties": { + "format": "uint32", + "minimum": 0.0, + "type": "integer" + }, + "type": "object" + }, "ModelProviderInfo": { "additionalProperties": false, "description": "Serializable representation of a provider definition.", @@ -1064,6 +1101,22 @@ ], "type": "string" }, + "PluginConfig": { + "additionalProperties": false, + "properties": { + "enabled": { + "default": true, + "type": "boolean" + }, + "path": { + "$ref": "#/definitions/AbsolutePathBuf" + } + }, + "required": [ + "path" + ], + "type": "object" + }, "ProjectConfig": { "additionalProperties": false, "properties": { @@ -1141,6 +1194,10 @@ }, "type": "object" }, + "oauth_resource": { + "default": null, + "type": "string" + }, "required": { "default": null, "type": "boolean" @@ -1174,6 +1231,18 @@ }, "type": "object" }, + "RealtimeAudioToml": { + "additionalProperties": false, + "properties": { + "microphone": { + "type": "string" + }, + "speaker": { + "type": "string" + } + }, + "type": "object" + }, "ReasoningEffort": { "description": "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", "enum": [ @@ -1261,6 +1330,12 @@ }, "type": "object" }, + "ServiceTier": { + "enum": [ + "fast" + ], + "type": "string" + }, "ShellEnvironmentPolicyInherit": { "oneOf": [ { @@ -1391,6 +1466,15 @@ "description": "Enable animations (welcome screen, shimmer effects, spinners). Defaults to `true`.", "type": "boolean" }, + "model_availability_nux": { + "allOf": [ + { + "$ref": "#/definitions/ModelAvailabilityNuxConfig" + } + ], + "default": {}, + "description": "Startup tooltip availability NUX state persisted by the TUI." + }, "notification_method": { "allOf": [ { @@ -1535,6 +1619,15 @@ "default": null, "description": "Settings for app-specific controls." }, + "audio": { + "allOf": [ + { + "$ref": "#/definitions/RealtimeAudioToml" + } + ], + "default": null, + "description": "Machine-local realtime audio device preferences used by realtime voice." + }, "background_terminal_max_timeout": { "description": "Maximum poll window for background terminal output (`write_stdin`), in milliseconds. Default: `300000` (5 minutes).", "format": "uint64", @@ -1579,11 +1672,15 @@ "$ref": "#/definitions/AbsolutePathBuf" }, "experimental_realtime_ws_backend_prompt": { - "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport backend prompt (the `Op::RealtimeConversation` `/ws` session.create backend_prompt) without changing normal prompts.", + "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport instructions (the `Op::RealtimeConversation` `/ws` session.update instructions) without changing normal prompts.", "type": "string" }, "experimental_realtime_ws_base_url": { - "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport base URL (the `Op::RealtimeConversation` `/ws` connection) without changing normal provider HTTP requests.", + "description": "Experimental / do not use. Overrides only the realtime conversation websocket transport base URL (the `Op::RealtimeConversation` `/v1/realtime` connection) without changing normal provider HTTP requests.", + "type": "string" + }, + "experimental_realtime_ws_model": { + "description": "Experimental / do not use. Selects the realtime websocket model/snapshot used for the `Op::RealtimeConversation` connection.", "type": "string" }, "experimental_use_freeform_apply_patch": { @@ -1606,6 +1703,9 @@ "apps_mcp_gateway": { "type": "boolean" }, + "artifact": { + "type": "boolean" + }, "child_agents_md": { "type": "boolean" }, @@ -1621,6 +1721,9 @@ "connectors": { "type": "boolean" }, + "default_mode_request_user_input": { + "type": "boolean" + }, "elevated_windows_sandbox": { "type": "boolean" }, @@ -1639,6 +1742,9 @@ "experimental_windows_sandbox": { "type": "boolean" }, + "fast_mode": { + "type": "boolean" + }, "include_apply_patch_tool": { "type": "boolean" }, @@ -1660,6 +1766,9 @@ "personality": { "type": "boolean" }, + "plugins": { + "type": "boolean" + }, "powershell_utf8": { "type": "boolean" }, @@ -1699,9 +1808,6 @@ "shell_zsh_fork": { "type": "boolean" }, - "skill_approval": { - "type": "boolean" - }, "skill_env_var_dependency_prompt": { "type": "boolean" }, @@ -1960,6 +2066,14 @@ "plan_mode_reasoning_effort": { "$ref": "#/definitions/ReasoningEffort" }, + "plugins": { + "additionalProperties": { + "$ref": "#/definitions/PluginConfig" + }, + "default": {}, + "description": "User-level plugin config entries keyed by plugin name.", + "type": "object" + }, "profile": { "description": "Profile to use from the `profiles` map.", "type": "string" @@ -2019,6 +2133,14 @@ ], "description": "Sandbox configuration to apply if `sandbox` is `WorkspaceWrite`." }, + "service_tier": { + "allOf": [ + { + "$ref": "#/definitions/ServiceTier" + } + ], + "description": "Optional explicit service tier preference for new turns." + }, "shell_environment_policy": { "allOf": [ { diff --git a/codex-rs/core/models.json b/codex-rs/core/models.json index 3f7d08b431..2fd55b9869 100644 --- a/codex-rs/core/models.json +++ b/codex-rs/core/models.json @@ -40,7 +40,7 @@ } ], "shell_type": "shell_command", - "visibility": "hide", + "visibility": "list", "minimal_client_version": "0.98.0", "supported_in_api": true, "upgrade": null, diff --git a/codex-rs/core/src/agent/agent_names.txt b/codex-rs/core/src/agent/agent_names.txt index e5a712ff5c..7574e69a80 100644 --- a/codex-rs/core/src/agent/agent_names.txt +++ b/codex-rs/core/src/agent/agent_names.txt @@ -1,87 +1,100 @@ -Ash -Elm -Yew -Fir -Oak -Pine -Spruce -Cedar -Birch -Maple -Beech -Alder -Willow -Poplar -Aspen -Larch -Juniper -Cypress -Hemlock -Sequoia -Baobab -Acacia -Banyan -Teak -Olive -Cherry -Apple -Pear -Plum -Peach -Mango -Guava -Fig -Date -Palm -Holly -Ivy -Fern -Moss -Reed -Cane -Rush -Sage -Mint -Thyme -Basil -Dill -Fennel -Parsley -Laurel -Myrtle -Lotus -Tulip -Rose -Daisy -Lily -Iris -Poppy -Aster -Peony -Camellia -Azalea -Begonia -Petunia -Verbena -Marigold -Daffodil -Orchid -Violet -Clover -Bamboo -Eucalypt -Oleander -Yucca -Agave -Aloe -Cactus -Sedum -Boxwood -Hawthorn -Redwood -Ironwood -Sandal -Kapok -Mahonia -Spirea -Wisteria \ No newline at end of file +Euclid +Archimedes +Ptolemy +Hypatia +Avicenna +Averroes +Aquinas +Copernicus +Kepler +Galileo +Bacon +Descartes +Pascal +Fermat +Huygens +Leibniz +Newton +Halley +Euler +Lagrange +Laplace +Volta +Gauss +Ampere +Faraday +Darwin +Lovelace +Boole +Pasteur +Maxwell +Mendel +Curie +Planck +Tesla +Poincare +Noether +Hilbert +Einstein +Raman +Bohr +Turing +Hubble +Feynman +Franklin +McClintock +Meitner +Herschel +Linnaeus +Wegener +Chandrasekhar +Sagan +Goodall +Carson +Carver +Socrates +Plato +Aristotle +Epicurus +Cicero +Confucius +Mencius +Zeno +Locke +Hume +Kant +Hegel +Kierkegaard +Mill +Nietzsche +Peirce +James +Dewey +Russell +Popper +Sartre +Beauvoir +Arendt +Rawls +Singer +Anscombe +Parfit +Kuhn +Boyle +Hooke +Harvey +Dalton +Ohm +Helmholtz +Gibbs +Lorentz +Schrodinger +Heisenberg +Pauli +Dirac +Bernoulli +Godel +Nash +Banach +Ramanujan +Erdos \ No newline at end of file diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index e94ac79669..85f28b4f6b 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -4,11 +4,18 @@ use crate::agent::status::is_final; use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::find_thread_path_by_id_str; +use crate::rollout::RolloutRecorder; +use crate::session_prefix::format_subagent_context_line; use crate::session_prefix::format_subagent_notification_message; +use crate::shell_snapshot::ShellSnapshot; use crate::state_db; use crate::thread_manager::ThreadManagerState; use codex_protocol::ThreadId; +use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; @@ -18,6 +25,12 @@ use std::sync::Weak; use tokio::sync::watch; const AGENT_NAMES: &str = include_str!("agent_names.txt"); +const FORKED_SPAWN_AGENT_OUTPUT_MESSAGE: &str = "You are the newly spawned agent. The prior conversation history was forked from your parent agent. Treat the next user message as your new task, and use the forked history only as background context."; + +#[derive(Clone, Debug, Default)] +pub(crate) struct SpawnAgentOptions { + pub(crate) fork_parent_spawn_call_id: Option, +} fn agent_nickname_list() -> Vec<&'static str> { AGENT_NAMES @@ -57,9 +70,23 @@ impl AgentControl { config: crate::config::Config, items: Vec, session_source: Option, + ) -> CodexResult { + self.spawn_agent_with_options(config, items, session_source, SpawnAgentOptions::default()) + .await + } + + pub(crate) async fn spawn_agent_with_options( + &self, + config: crate::config::Config, + items: Vec, + session_source: Option, + options: SpawnAgentOptions, ) -> CodexResult { let state = self.upgrade()?; let mut reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; + let inherited_shell_snapshot = self + .inherited_shell_snapshot_for_source(&state, session_source.as_ref()) + .await; let session_source = match session_source { Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, @@ -82,9 +109,77 @@ impl AgentControl { // The same `AgentControl` is sent to spawn the thread. let new_thread = match session_source { Some(session_source) => { - state - .spawn_new_thread_with_source(config, self.clone(), session_source, false, None) - .await? + if let Some(call_id) = options.fork_parent_spawn_call_id.as_ref() { + let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + .. + }) = session_source.clone() + else { + return Err(CodexErr::Fatal( + "spawn_agent fork requires a thread-spawn session source".to_string(), + )); + }; + let parent_thread = state.get_thread(parent_thread_id).await.ok(); + if let Some(parent_thread) = parent_thread.as_ref() { + // `record_conversation_items` only queues rollout writes asynchronously. + // Flush/materialize the live parent before snapshotting JSONL for a fork. + parent_thread + .codex + .session + .ensure_rollout_materialized() + .await; + parent_thread.codex.session.flush_rollout().await; + } + let rollout_path = parent_thread + .as_ref() + .and_then(|parent_thread| parent_thread.rollout_path()) + .or(find_thread_path_by_id_str( + config.codex_home.as_path(), + &parent_thread_id.to_string(), + ) + .await?) + .ok_or_else(|| { + CodexErr::Fatal(format!( + "parent thread rollout unavailable for fork: {parent_thread_id}" + )) + })?; + let mut forked_rollout_items = + RolloutRecorder::get_rollout_history(&rollout_path) + .await? + .get_rollout_items(); + let mut output = FunctionCallOutputPayload::from_text( + FORKED_SPAWN_AGENT_OUTPUT_MESSAGE.to_string(), + ); + output.success = Some(true); + forked_rollout_items.push(RolloutItem::ResponseItem( + ResponseItem::FunctionCallOutput { + call_id: call_id.clone(), + output, + }, + )); + let initial_history = InitialHistory::Forked(forked_rollout_items); + state + .fork_thread_with_source( + config, + initial_history, + self.clone(), + session_source, + false, + inherited_shell_snapshot, + ) + .await? + } else { + state + .spawn_new_thread_with_source( + config, + self.clone(), + session_source, + false, + None, + inherited_shell_snapshot, + ) + .await? + } } None => state.spawn_new_thread(config, self.clone()).await?, }; @@ -146,6 +241,9 @@ impl AgentControl { other => other, }; let notification_source = session_source.clone(); + let inherited_shell_snapshot = self + .inherited_shell_snapshot_for_source(&state, Some(&session_source)) + .await; let rollout_path = find_thread_path_by_id_str(config.codex_home.as_path(), &thread_id.to_string()) .await? @@ -157,6 +255,7 @@ impl AgentControl { rollout_path, self.clone(), session_source, + inherited_shell_snapshot, ) .await?; reservation.commit(resumed_thread.thread_id); @@ -255,6 +354,40 @@ impl AgentControl { thread.total_token_usage().await } + pub(crate) async fn format_environment_context_subagents( + &self, + parent_thread_id: ThreadId, + ) -> String { + let Ok(state) = self.upgrade() else { + return String::new(); + }; + + let mut agents = Vec::new(); + for thread_id in state.list_thread_ids().await { + let Ok(thread) = state.get_thread(thread_id).await else { + continue; + }; + let snapshot = thread.config_snapshot().await; + let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: agent_parent_thread_id, + agent_nickname, + .. + }) = snapshot.session_source + else { + continue; + }; + if agent_parent_thread_id != parent_thread_id { + continue; + } + agents.push(format_subagent_context_line( + &thread_id.to_string(), + agent_nickname.as_deref(), + )); + } + agents.sort(); + agents.join("\n") + } + /// Starts a detached watcher for sub-agents spawned from another thread. /// /// This is only enabled for `SubAgentSource::ThreadSpawn`, where a parent thread exists and @@ -272,18 +405,20 @@ impl AgentControl { }; let control = self.clone(); tokio::spawn(async move { - let mut status_rx = match control.subscribe_status(child_thread_id).await { - Ok(rx) => rx, - Err(_) => return, - }; - let mut status = status_rx.borrow().clone(); - while !is_final(&status) { - if status_rx.changed().await.is_err() { - status = control.get_status(child_thread_id).await; - break; + let status = match control.subscribe_status(child_thread_id).await { + Ok(mut status_rx) => { + let mut status = status_rx.borrow().clone(); + while !is_final(&status) { + if status_rx.changed().await.is_err() { + status = control.get_status(child_thread_id).await; + break; + } + status = status_rx.borrow().clone(); + } + status } - status = status_rx.borrow().clone(); - } + Err(_) => control.get_status(child_thread_id).await, + }; if !is_final(&status) { return; } @@ -308,6 +443,22 @@ impl AgentControl { .upgrade() .ok_or_else(|| CodexErr::UnsupportedOperation("thread manager dropped".to_string())) } + + async fn inherited_shell_snapshot_for_source( + &self, + state: &Arc, + session_source: Option<&SessionSource>, + ) -> Option> { + let Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, .. + })) = session_source + else { + return None; + }; + + let parent_thread = state.get_thread(*parent_thread_id).await.ok()?; + parent_thread.codex.session.user_shell().shell_snapshot() + } } #[cfg(test)] mod tests { @@ -319,8 +470,8 @@ mod tests { use crate::config::Config; use crate::config::ConfigBuilder; use crate::config_loader::LoaderOverrides; + use crate::contextual_user_message::SUBAGENT_NOTIFICATION_OPEN_TAG; use crate::features::Feature; - use crate::session_prefix::SUBAGENT_NOTIFICATION_OPEN_TAG; use assert_matches::assert_matches; use codex_protocol::config_types::ModeKind; use codex_protocol::models::ContentItem; @@ -421,6 +572,21 @@ mod tests { }) } + /// Returns true when any message item contains `needle` in a text span. + fn history_contains_text(history_items: &[ResponseItem], needle: &str) -> bool { + history_items.iter().any(|item| { + let ResponseItem::Message { content, .. } = item else { + return false; + }; + content.iter().any(|content_item| match content_item { + ContentItem::InputText { text } | ContentItem::OutputText { text } => { + text.contains(needle) + } + ContentItem::InputImage { .. } => false, + }) + }) + } + async fn wait_for_subagent_notification(parent_thread: &Arc) -> bool { let wait = async { loop { @@ -673,6 +839,242 @@ mod tests { assert_eq!(captured, Some(expected)); } + #[tokio::test] + async fn spawn_agent_can_fork_parent_thread_history() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + parent_thread + .inject_user_message_without_turn("parent seed context".to_string()) + .await; + let turn_context = parent_thread.codex.session.new_default_turn().await; + let parent_spawn_call_id = "spawn-call-history".to_string(); + let parent_spawn_call = ResponseItem::FunctionCall { + id: None, + name: "spawn_agent".to_string(), + arguments: "{}".to_string(), + call_id: parent_spawn_call_id.clone(), + }; + parent_thread + .codex + .session + .record_conversation_items(turn_context.as_ref(), &[parent_spawn_call]) + .await; + parent_thread + .codex + .session + .ensure_rollout_materialized() + .await; + parent_thread.codex.session.flush_rollout().await; + + let child_thread_id = harness + .control + .spawn_agent_with_options( + harness.config.clone(), + text_input("child task"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + })), + SpawnAgentOptions { + fork_parent_spawn_call_id: Some(parent_spawn_call_id), + }, + ) + .await + .expect("forked spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + assert_ne!(child_thread_id, parent_thread_id); + let history = child_thread.codex.session.clone_history().await; + assert!(history_contains_text( + history.raw_items(), + "parent seed context" + )); + + let expected = ( + child_thread_id, + Op::UserInput { + items: vec![UserInput::Text { + text: "child task".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }, + ); + let captured = harness + .manager + .captured_ops() + .into_iter() + .find(|entry| *entry == expected); + assert_eq!(captured, Some(expected)); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); + } + + #[tokio::test] + async fn spawn_agent_fork_injects_output_for_parent_spawn_call() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + let turn_context = parent_thread.codex.session.new_default_turn().await; + let parent_spawn_call_id = "spawn-call-1".to_string(); + let parent_spawn_call = ResponseItem::FunctionCall { + id: None, + name: "spawn_agent".to_string(), + arguments: "{}".to_string(), + call_id: parent_spawn_call_id.clone(), + }; + parent_thread + .codex + .session + .record_conversation_items(turn_context.as_ref(), &[parent_spawn_call]) + .await; + parent_thread + .codex + .session + .ensure_rollout_materialized() + .await; + parent_thread.codex.session.flush_rollout().await; + + let child_thread_id = harness + .control + .spawn_agent_with_options( + harness.config.clone(), + text_input("child task"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + })), + SpawnAgentOptions { + fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()), + }, + ) + .await + .expect("forked spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let history = child_thread.codex.session.clone_history().await; + let injected_output = history.raw_items().iter().find_map(|item| match item { + ResponseItem::FunctionCallOutput { call_id, output } + if call_id == &parent_spawn_call_id => + { + Some(output) + } + _ => None, + }); + let injected_output = + injected_output.expect("forked child should contain synthetic tool output"); + assert_eq!( + injected_output.text_content(), + Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE) + ); + assert_eq!(injected_output.success, Some(true)); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); + } + + #[tokio::test] + async fn spawn_agent_fork_flushes_parent_rollout_before_loading_history() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + let turn_context = parent_thread.codex.session.new_default_turn().await; + let parent_spawn_call_id = "spawn-call-unflushed".to_string(); + let parent_spawn_call = ResponseItem::FunctionCall { + id: None, + name: "spawn_agent".to_string(), + arguments: "{}".to_string(), + call_id: parent_spawn_call_id.clone(), + }; + parent_thread + .codex + .session + .record_conversation_items(turn_context.as_ref(), &[parent_spawn_call]) + .await; + + let child_thread_id = harness + .control + .spawn_agent_with_options( + harness.config.clone(), + text_input("child task"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + })), + SpawnAgentOptions { + fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()), + }, + ) + .await + .expect("forked spawn should flush parent rollout before loading history"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let history = child_thread.codex.session.clone_history().await; + + let mut parent_call_index = None; + let mut injected_output_index = None; + for (idx, item) in history.raw_items().iter().enumerate() { + match item { + ResponseItem::FunctionCall { call_id, .. } if call_id == &parent_spawn_call_id => { + parent_call_index = Some(idx); + } + ResponseItem::FunctionCallOutput { call_id, .. } + if call_id == &parent_spawn_call_id => + { + injected_output_index = Some(idx); + } + _ => {} + } + } + + let parent_call_index = + parent_call_index.expect("forked child should include the parent spawn_agent call"); + let injected_output_index = injected_output_index + .expect("forked child should include synthetic output for the parent spawn_agent call"); + assert!(parent_call_index < injected_output_index); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); + } + #[tokio::test] async fn spawn_agent_respects_max_threads_limit() { let max_threads = 1usize; @@ -896,6 +1298,44 @@ mod tests { assert_eq!(wait_for_subagent_notification(&parent_thread).await, true); } + #[tokio::test] + async fn completion_watcher_notifies_parent_when_child_is_missing() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + let child_thread_id = ThreadId::new(); + + harness.control.maybe_start_completion_watcher( + child_thread_id, + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: Some("explorer".to_string()), + })), + ); + + assert_eq!(wait_for_subagent_notification(&parent_thread).await, true); + + let history_items = parent_thread + .codex + .session + .clone_history() + .await + .raw_items() + .to_vec(); + assert_eq!( + history_contains_text( + &history_items, + &format!("\"agent_id\":\"{child_thread_id}\"") + ), + true + ); + assert_eq!( + history_contains_text(&history_items, "\"status\":\"not_found\""), + true + ); + } + #[tokio::test] async fn spawn_thread_subagent_gets_random_nickname_in_session_source() { let harness = AgentControlHarness::new().await; diff --git a/codex-rs/core/src/agent/role.rs b/codex-rs/core/src/agent/role.rs index ba9bb51a0d..3ca496d6e1 100644 --- a/codex-rs/core/src/agent/role.rs +++ b/codex-rs/core/src/agent/role.rs @@ -1,3 +1,11 @@ +//! Applies agent-role configuration layers on top of an existing session config. +//! +//! Roles are selected at spawn time and are loaded with the same config machinery as +//! `config.toml`. This module resolves built-in and user-defined role files, inserts the role as a +//! high-precedence layer, and preserves the caller's current profile/provider unless the role +//! explicitly takes ownership of model selection. It does not decide when to spawn a sub-agent or +//! which role to use; the multi-agent tool handler owns that orchestration. + use crate::config::AgentRoleConfig; use crate::config::Config; use crate::config::ConfigOverrides; @@ -13,10 +21,18 @@ use std::path::Path; use std::sync::LazyLock; use toml::Value as TomlValue; +/// The role name used when a caller omits `agent_type`. pub const DEFAULT_ROLE_NAME: &str = "default"; const AGENT_TYPE_UNAVAILABLE_ERROR: &str = "agent type is currently not available"; -/// Applies a role config layer to a mutable config and preserves unspecified keys. +/// Applies a named role layer to `config` while preserving caller-owned model selection. +/// +/// The role layer is inserted at session-flag precedence so it can override persisted config, but +/// the caller's current `profile` and `model_provider` remain sticky runtime choices unless the +/// role explicitly sets `profile`, explicitly sets `model_provider`, or rewrites the active +/// profile's `model_provider` in place. Rebuilding the config without those overrides would make a +/// spawned agent silently fall back to the default provider, which is the bug this preservation +/// logic avoids. pub(crate) async fn apply_role_to_config( config: &mut Config, role_name: Option<&str>, @@ -60,6 +76,25 @@ pub(crate) async fn apply_role_to_config( .map_err(|_| AGENT_TYPE_UNAVAILABLE_ERROR.to_string())?; let role_layer_toml = resolve_relative_paths_in_config_toml(role_config_toml, role_config_base) .map_err(|_| AGENT_TYPE_UNAVAILABLE_ERROR.to_string())?; + let role_selects_provider = role_layer_toml.get("model_provider").is_some(); + let role_selects_profile = role_layer_toml.get("profile").is_some(); + let role_updates_active_profile_provider = config + .active_profile + .as_ref() + .and_then(|active_profile| { + role_layer_toml + .get("profiles") + .and_then(TomlValue::as_table) + .and_then(|profiles| profiles.get(active_profile)) + .and_then(TomlValue::as_table) + .map(|profile| profile.contains_key("model_provider")) + }) + .unwrap_or(false); + // A role that does not explicitly take ownership of model selection should inherit the + // caller's current profile/provider choices across the config reload. + let preserve_current_profile = !role_selects_provider && !role_selects_profile; + let preserve_current_provider = + preserve_current_profile && !role_updates_active_profile_provider; let mut layers: Vec = config .config_layer_stack @@ -86,6 +121,10 @@ pub(crate) async fn apply_role_to_config( merged_config, ConfigOverrides { cwd: Some(config.cwd.clone()), + model_provider: preserve_current_provider.then(|| config.model_provider_id.clone()), + config_profile: preserve_current_profile + .then(|| config.active_profile.clone()) + .flatten(), codex_linux_sandbox_exe: config.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: config.main_execve_wrapper_exe.clone(), js_repl_node_path: config.js_repl_node_path.clone(), @@ -187,19 +226,24 @@ Rules: config_file: None, } ), - ( - "awaiter".to_string(), - AgentRoleConfig { - description: Some(r#"Use an `awaiter` agent EVERY TIME you must run a command that might take some time. -This includes, but not only: -* testing -* monitoring of a long running process -* explicit ask to wait for something - -When YOU wait for the `awaiter` agent to be done, use the largest possible timeout."#.to_string()), - config_file: Some("awaiter.toml".to_string().parse().unwrap_or_default()), - } - ) + // Awaiter is temp removed +// ( +// "awaiter".to_string(), +// AgentRoleConfig { +// description: Some(r#"Use an `awaiter` agent EVERY TIME you must run a command that will take some very long time. +// This includes, but not only: +// * testing +// * monitoring of a long running process +// * explicit ask to wait for something +// +// Rules: +// - When an awaiter is running, you can work on something else. If you need to wait for its completion, use the largest possible timeout. +// - Be patient with the `awaiter`. +// - Do not use an awaiter for every compilation/test if it won't take time. Only use if for long running commands. +// - Close the awaiter when you're done with it."#.to_string()), +// config_file: Some("awaiter.toml".to_string().parse().unwrap_or_default()), +// } +// ) ]) }); &CONFIG @@ -220,11 +264,16 @@ When YOU wait for the `awaiter` agent to be done, use the largest possible timeo #[cfg(test)] mod tests { use super::*; + use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigBuilder; use crate::config_loader::ConfigLayerStackOrdering; + use crate::plugins::PluginsManager; + use crate::skills::SkillsManager; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; + use std::fs; use std::path::PathBuf; + use std::sync::Arc; use tempfile::TempDir; async fn test_config_with_cli_overrides( @@ -373,6 +422,227 @@ mod tests { ); } + #[tokio::test] + async fn apply_role_preserves_active_profile_and_model_provider() { + let home = TempDir::new().expect("create temp dir"); + tokio::fs::write( + home.path().join(CONFIG_TOML_FILE), + r#" +[model_providers.test-provider] +name = "Test Provider" +base_url = "https://example.com/v1" +env_key = "TEST_PROVIDER_API_KEY" +wire_api = "responses" + +[profiles.test-profile] +model_provider = "test-provider" +"#, + ) + .await + .expect("write config.toml"); + let mut config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .harness_overrides(ConfigOverrides { + config_profile: Some("test-profile".to_string()), + ..Default::default() + }) + .fallback_cwd(Some(home.path().to_path_buf())) + .build() + .await + .expect("load config"); + let role_path = write_role_config(&home, "empty-role.toml", "").await; + config.agent_roles.insert( + "custom".to_string(), + AgentRoleConfig { + description: None, + config_file: Some(role_path), + }, + ); + + apply_role_to_config(&mut config, Some("custom")) + .await + .expect("custom role should apply"); + + assert_eq!(config.active_profile.as_deref(), Some("test-profile")); + assert_eq!(config.model_provider_id, "test-provider"); + assert_eq!(config.model_provider.name, "Test Provider"); + } + + #[tokio::test] + async fn apply_role_uses_role_profile_instead_of_current_profile() { + let home = TempDir::new().expect("create temp dir"); + tokio::fs::write( + home.path().join(CONFIG_TOML_FILE), + r#" +[model_providers.base-provider] +name = "Base Provider" +base_url = "https://base.example.com/v1" +env_key = "BASE_PROVIDER_API_KEY" +wire_api = "responses" + +[model_providers.role-provider] +name = "Role Provider" +base_url = "https://role.example.com/v1" +env_key = "ROLE_PROVIDER_API_KEY" +wire_api = "responses" + +[profiles.base-profile] +model_provider = "base-provider" + +[profiles.role-profile] +model_provider = "role-provider" +"#, + ) + .await + .expect("write config.toml"); + let mut config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .harness_overrides(ConfigOverrides { + config_profile: Some("base-profile".to_string()), + ..Default::default() + }) + .fallback_cwd(Some(home.path().to_path_buf())) + .build() + .await + .expect("load config"); + let role_path = + write_role_config(&home, "profile-role.toml", "profile = \"role-profile\"").await; + config.agent_roles.insert( + "custom".to_string(), + AgentRoleConfig { + description: None, + config_file: Some(role_path), + }, + ); + + apply_role_to_config(&mut config, Some("custom")) + .await + .expect("custom role should apply"); + + assert_eq!(config.active_profile.as_deref(), Some("role-profile")); + assert_eq!(config.model_provider_id, "role-provider"); + assert_eq!(config.model_provider.name, "Role Provider"); + } + + #[tokio::test] + async fn apply_role_uses_role_model_provider_instead_of_current_profile_provider() { + let home = TempDir::new().expect("create temp dir"); + tokio::fs::write( + home.path().join(CONFIG_TOML_FILE), + r#" +[model_providers.base-provider] +name = "Base Provider" +base_url = "https://base.example.com/v1" +env_key = "BASE_PROVIDER_API_KEY" +wire_api = "responses" + +[model_providers.role-provider] +name = "Role Provider" +base_url = "https://role.example.com/v1" +env_key = "ROLE_PROVIDER_API_KEY" +wire_api = "responses" + +[profiles.base-profile] +model_provider = "base-provider" +"#, + ) + .await + .expect("write config.toml"); + let mut config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .harness_overrides(ConfigOverrides { + config_profile: Some("base-profile".to_string()), + ..Default::default() + }) + .fallback_cwd(Some(home.path().to_path_buf())) + .build() + .await + .expect("load config"); + let role_path = write_role_config( + &home, + "provider-role.toml", + "model_provider = \"role-provider\"", + ) + .await; + config.agent_roles.insert( + "custom".to_string(), + AgentRoleConfig { + description: None, + config_file: Some(role_path), + }, + ); + + apply_role_to_config(&mut config, Some("custom")) + .await + .expect("custom role should apply"); + + assert_eq!(config.active_profile, None); + assert_eq!(config.model_provider_id, "role-provider"); + assert_eq!(config.model_provider.name, "Role Provider"); + } + + #[tokio::test] + async fn apply_role_uses_active_profile_model_provider_update() { + let home = TempDir::new().expect("create temp dir"); + tokio::fs::write( + home.path().join(CONFIG_TOML_FILE), + r#" +[model_providers.base-provider] +name = "Base Provider" +base_url = "https://base.example.com/v1" +env_key = "BASE_PROVIDER_API_KEY" +wire_api = "responses" + +[model_providers.role-provider] +name = "Role Provider" +base_url = "https://role.example.com/v1" +env_key = "ROLE_PROVIDER_API_KEY" +wire_api = "responses" + +[profiles.base-profile] +model_provider = "base-provider" +model_reasoning_effort = "low" +"#, + ) + .await + .expect("write config.toml"); + let mut config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .harness_overrides(ConfigOverrides { + config_profile: Some("base-profile".to_string()), + ..Default::default() + }) + .fallback_cwd(Some(home.path().to_path_buf())) + .build() + .await + .expect("load config"); + let role_path = write_role_config( + &home, + "profile-edit-role.toml", + r#"[profiles.base-profile] +model_provider = "role-provider" +model_reasoning_effort = "high" +"#, + ) + .await; + config.agent_roles.insert( + "custom".to_string(), + AgentRoleConfig { + description: None, + config_file: Some(role_path), + }, + ); + + apply_role_to_config(&mut config, Some("custom")) + .await + .expect("custom role should apply"); + + assert_eq!(config.active_profile.as_deref(), Some("base-profile")); + assert_eq!(config.model_provider_id, "role-provider"); + assert_eq!(config.model_provider.name, "Role Provider"); + assert_eq!(config.model_reasoning_effort, Some(ReasoningEffort::High)); + } + #[tokio::test] #[cfg(not(windows))] async fn apply_role_does_not_materialize_default_sandbox_workspace_write_fields() { @@ -465,6 +735,54 @@ writable_roots = ["./sandbox-root"] assert_eq!(session_flags_layer_count(&config), before_layers + 1); } + #[cfg_attr(windows, ignore)] + #[tokio::test] + async fn apply_role_skills_config_disables_skill_for_spawned_agent() { + let (home, mut config) = test_config_with_cli_overrides(Vec::new()).await; + let skill_dir = home.path().join("skills").join("demo"); + fs::create_dir_all(&skill_dir).expect("create skill dir"); + let skill_path = skill_dir.join("SKILL.md"); + fs::write( + &skill_path, + "---\nname: demo-skill\ndescription: demo description\n---\n\n# Body\n", + ) + .expect("write skill"); + let role_path = write_role_config( + &home, + "skills-role.toml", + &format!( + r#"[[skills.config]] +path = "{}" +enabled = false +"#, + skill_path.display() + ), + ) + .await; + config.agent_roles.insert( + "custom".to_string(), + AgentRoleConfig { + description: None, + config_file: Some(role_path), + }, + ); + + apply_role_to_config(&mut config, Some("custom")) + .await + .expect("custom role should apply"); + + let plugins_manager = Arc::new(PluginsManager::new(home.path().to_path_buf())); + let skills_manager = SkillsManager::new(home.path().to_path_buf(), plugins_manager); + let outcome = skills_manager.skills_for_config(&config); + let skill = outcome + .skills + .iter() + .find(|skill| skill.name == "demo-skill") + .expect("demo skill should be discovered"); + + assert_eq!(outcome.is_skill_enabled(skill), false); + } + #[test] fn spawn_tool_spec_build_deduplicates_user_defined_built_in_roles() { let user_defined_roles = BTreeMap::from([ diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index 217334b2a5..cca57d5c0f 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -266,6 +266,8 @@ impl CodexAuth { /// Returns a high-level `AccountPlanType` (e.g., Free/Plus/Pro/Team/…) /// mapped from the ID token's internal plan value. Prefer this when you /// need to make UI or product decisions based on the user's subscription. + /// When ChatGPT auth is active but the token omits the plan claim, report + /// `Unknown` instead of treating the account as invalid. pub fn account_plan_type(&self) -> Option { let map_known = |kp: &InternalKnownPlan| match kp { InternalKnownPlan::Free => AccountPlanType::Free, @@ -278,12 +280,15 @@ impl CodexAuth { InternalKnownPlan::Edu => AccountPlanType::Edu, }; - self.get_current_token_data() - .and_then(|t| t.id_token.chatgpt_plan_type) - .map(|pt| match pt { - InternalPlanType::Known(k) => map_known(&k), - InternalPlanType::Unknown(_) => AccountPlanType::Unknown, - }) + self.get_current_token_data().map(|t| { + t.id_token + .chatgpt_plan_type + .map(|pt| match pt { + InternalPlanType::Known(k) => map_known(&k), + InternalPlanType::Unknown(_) => AccountPlanType::Unknown, + }) + .unwrap_or(AccountPlanType::Unknown) + }) } /// Returns `None` if `is_chatgpt_auth()` is false. @@ -1377,7 +1382,7 @@ mod tests { let fake_jwt = write_auth_file( AuthFileParams { openai_api_key: None, - chatgpt_plan_type: "pro".to_string(), + chatgpt_plan_type: Some("pro".to_string()), chatgpt_account_id: None, }, codex_home.path(), @@ -1447,7 +1452,7 @@ mod tests { let fake_jwt = write_auth_file( AuthFileParams { openai_api_key: None, - chatgpt_plan_type: "pro".to_string(), + chatgpt_plan_type: Some("pro".to_string()), chatgpt_account_id: None, }, codex_home.path(), @@ -1528,7 +1533,7 @@ mod tests { struct AuthFileParams { openai_api_key: Option, - chatgpt_plan_type: String, + chatgpt_plan_type: Option, chatgpt_account_id: Option, } @@ -1545,11 +1550,14 @@ mod tests { typ: "JWT", }; let mut auth_payload = serde_json::json!({ - "chatgpt_plan_type": params.chatgpt_plan_type, "chatgpt_user_id": "user-12345", "user_id": "user-12345", }); + if let Some(chatgpt_plan_type) = params.chatgpt_plan_type { + auth_payload["chatgpt_plan_type"] = serde_json::Value::String(chatgpt_plan_type); + } + if let Some(chatgpt_account_id) = params.chatgpt_account_id { let org_value = serde_json::Value::String(chatgpt_account_id); auth_payload["chatgpt_account_id"] = org_value; @@ -1650,7 +1658,7 @@ mod tests { let _jwt = write_auth_file( AuthFileParams { openai_api_key: None, - chatgpt_plan_type: "pro".to_string(), + chatgpt_plan_type: Some("pro".to_string()), chatgpt_account_id: Some("org_another_org".to_string()), }, codex_home.path(), @@ -1675,7 +1683,7 @@ mod tests { let _jwt = write_auth_file( AuthFileParams { openai_api_key: None, - chatgpt_plan_type: "pro".to_string(), + chatgpt_plan_type: Some("pro".to_string()), chatgpt_account_id: Some("org_mine".to_string()), }, codex_home.path(), @@ -1729,7 +1737,7 @@ mod tests { let _jwt = write_auth_file( AuthFileParams { openai_api_key: None, - chatgpt_plan_type: "pro".to_string(), + chatgpt_plan_type: Some("pro".to_string()), chatgpt_account_id: None, }, codex_home.path(), @@ -1749,7 +1757,27 @@ mod tests { let _jwt = write_auth_file( AuthFileParams { openai_api_key: None, - chatgpt_plan_type: "mystery-tier".to_string(), + chatgpt_plan_type: Some("mystery-tier".to_string()), + chatgpt_account_id: None, + }, + codex_home.path(), + ) + .expect("failed to write auth file"); + + let auth = super::load_auth(codex_home.path(), false, AuthCredentialsStoreMode::File) + .expect("load auth") + .expect("auth available"); + + pretty_assertions::assert_eq!(auth.account_plan_type(), Some(AccountPlanType::Unknown)); + } + + #[test] + fn missing_plan_type_maps_to_unknown() { + let codex_home = tempdir().unwrap(); + let _jwt = write_auth_file( + AuthFileParams { + openai_api_key: None, + chatgpt_plan_type: None, chatgpt_account_id: None, }, codex_home.path(), diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 74a2f15c19..9e5974b487 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -20,9 +20,8 @@ //! //! ## Retry-Budget Tradeoff //! -//! V2 request prewarm is treated as the first websocket connection attempt for a turn. If it -//! fails, normal stream retry/fallback logic handles recovery on the same turn. V1 prewarm -//! remains connection-only. +//! WebSocket prewarm is treated as the first websocket connection attempt for a turn. If it +//! fails, normal stream retry/fallback logic handles recovery on the same turn. use std::collections::HashMap; use std::sync::Arc; @@ -43,7 +42,6 @@ use codex_api::MemorySummarizeOutput as ApiMemorySummarizeOutput; use codex_api::RawMemory as ApiRawMemory; use codex_api::RequestTelemetry; use codex_api::ReqwestTransport; -use codex_api::ResponseAppendWsRequest; use codex_api::ResponseCreateWsRequest; use codex_api::ResponsesApiRequest; use codex_api::ResponsesClient as ApiResponsesClient; @@ -63,6 +61,7 @@ use codex_otel::OtelManager; use codex_protocol::ThreadId; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Verbosity as VerbosityConfig; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; @@ -100,32 +99,19 @@ use crate::model_provider_info::WireApi; use crate::tools::spec::create_tools_json_for_responses_api; pub const OPENAI_BETA_HEADER: &str = "OpenAI-Beta"; -pub const OPENAI_BETA_RESPONSES_WEBSOCKETS: &str = "responses_websockets=2026-02-04"; pub const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state"; pub const X_CODEX_TURN_METADATA_HEADER: &str = "x-codex-turn-metadata"; pub const X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER: &str = "x-responsesapi-include-timing-metrics"; const RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ResponsesWebsocketVersion { - V1, - V2, -} - -pub fn ws_version_from_features(config: &Config) -> Option { - match ( - config +pub fn ws_version_from_features(config: &Config) -> bool { + config + .features + .enabled(crate::features::Feature::ResponsesWebsockets) + || config .features - .enabled(crate::features::Feature::ResponsesWebsockets), - config - .features - .enabled(crate::features::Feature::ResponsesWebsocketsV2), - ) { - (_, true) => Some(ResponsesWebsocketVersion::V2), - (true, false) => Some(ResponsesWebsocketVersion::V1), - (false, false) => None, - } + .enabled(crate::features::Feature::ResponsesWebsocketsV2) } /// Session-scoped state shared by all [`ModelClient`] clones. @@ -139,7 +125,7 @@ struct ModelClientState { provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, - responses_websocket_version: Option, + responses_websockets_enabled_by_feature: bool, enable_request_compression: bool, include_timing_metrics: bool, beta_features_header: Option, @@ -179,8 +165,8 @@ pub struct ModelClient { /// The session establishes a Responses WebSocket connection lazily and reuses it across multiple /// requests within the turn. It also caches per-turn state: /// -/// - The last full request, so subsequent calls can use `response.append` only when the current -/// request is an incremental extension of the previous one. +/// - The last full request, so subsequent calls can reuse incremental websocket request payloads +/// only when the current request is an incremental extension of the previous one. /// - The `x-codex-turn-state` sticky-routing token, which must be replayed for all requests within /// the same turn. /// @@ -207,7 +193,6 @@ pub struct ModelClientSession { struct LastResponse { response_id: String, items_added: Vec, - can_append: bool, } #[derive(Debug, Default)] @@ -234,7 +219,7 @@ impl ModelClient { provider: ModelProviderInfo, session_source: SessionSource, model_verbosity: Option, - responses_websocket_version: Option, + responses_websockets_enabled_by_feature: bool, enable_request_compression: bool, include_timing_metrics: bool, beta_features_header: Option, @@ -246,7 +231,7 @@ impl ModelClient { provider, session_source, model_verbosity, - responses_websocket_version, + responses_websockets_enabled_by_feature, enable_request_compression, include_timing_metrics, beta_features_header, @@ -315,7 +300,10 @@ impl ModelClient { instructions: &instructions, }; - let extra_headers = self.build_subagent_headers(); + let mut extra_headers = self.build_subagent_headers(); + extra_headers.extend(build_conversation_headers(Some( + self.state.conversation_id.to_string(), + ))); client .compact_input(&payload, extra_headers) .await @@ -387,25 +375,21 @@ impl ModelClient { request_telemetry } - /// Returns the active Responses-over-WebSocket version for this session. + /// Returns whether the Responses-over-WebSocket transport is active for this session. /// /// This combines provider capability and feature gating; both must be true for websocket paths /// to be eligible. /// - /// If websockets are only enabled via model preference (no explicit feature flag), default to - /// v1 behavior. - pub fn active_ws_version(&self, model_info: &ModelInfo) -> Option { + /// If websockets are only enabled via model preference (no explicit feature flag), prefer the + /// current v2 behavior. + pub fn responses_websocket_enabled(&self, model_info: &ModelInfo) -> bool { if !self.state.provider.supports_websockets || self.state.disable_websockets.load(Ordering::Relaxed) { - return None; + return false; } - match self.state.responses_websocket_version { - Some(version) => Some(version), - None if model_info.prefer_websockets => Some(ResponsesWebsocketVersion::V1), - None => None, - } + self.state.responses_websockets_enabled_by_feature || model_info.prefer_websockets } /// Returns auth + provider configuration resolved from the current session auth state. @@ -438,12 +422,10 @@ impl ModelClient { otel_manager: &OtelManager, api_provider: codex_api::Provider, api_auth: CoreAuthProvider, - ws_version: ResponsesWebsocketVersion, turn_state: Option>>, turn_metadata_header: Option<&str>, ) -> std::result::Result { - let headers = - self.build_websocket_headers(ws_version, turn_state.as_ref(), turn_metadata_header); + let headers = self.build_websocket_headers(turn_state.as_ref(), turn_metadata_header); let websocket_telemetry = ModelClientSession::build_websocket_telemetry(otel_manager); ApiWebSocketResponsesClient::new(api_provider, api_auth) .connect( @@ -461,7 +443,6 @@ impl ModelClient { /// replayed on reconnect within the same turn. fn build_websocket_headers( &self, - ws_version: ResponsesWebsocketVersion, turn_state: Option<&Arc>>, turn_metadata_header: Option<&str>, ) -> ApiHeaderMap { @@ -474,13 +455,9 @@ impl ModelClient { headers.extend(build_conversation_headers(Some( self.state.conversation_id.to_string(), ))); - let responses_websockets_beta_header = match ws_version { - ResponsesWebsocketVersion::V2 => RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE, - ResponsesWebsocketVersion::V1 => OPENAI_BETA_RESPONSES_WEBSOCKETS, - }; headers.insert( OPENAI_BETA_HEADER, - HeaderValue::from_static(responses_websockets_beta_header), + HeaderValue::from_static(RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE), ); if self.state.include_timing_metrics { headers.insert( @@ -517,6 +494,7 @@ impl ModelClientSession { model_info: &ModelInfo, effort: Option, summary: ReasoningSummaryConfig, + service_tier: Option, ) -> Result { let instructions = &prompt.base_instructions.text; let input = prompt.get_formatted_input(); @@ -566,6 +544,10 @@ impl ModelClientSession { store: provider.is_azure_responses_endpoint(), stream: true, include, + service_tier: match service_tier { + Some(ServiceTier::Fast) => Some("priority".to_string()), + _ => None, + }, prompt_cache_key, text, }; @@ -604,8 +586,9 @@ impl ModelClientSession { last_response: Option<&LastResponse>, allow_empty_delta: bool, ) -> Option> { - // Checks whether the current request is an incremental append to the previous request. - // We only append when non-input request fields are unchanged and `input` is a strict + // Checks whether the current request is an incremental extension of the previous request. + // We only reuse an incremental input delta when non-input request fields are unchanged and + // `input` is a strict // extension of the previous known input. Server-returned output items are treated as part // of the baseline so we do not resend them. let previous_request = self.websocket_session.last_request.as_ref()?; @@ -650,42 +633,26 @@ impl ModelClientSession { &mut self, payload: ResponseCreateWsRequest, request: &ResponsesApiRequest, - ws_version: ResponsesWebsocketVersion, ) -> ResponsesWsRequest { let Some(last_response) = self.get_last_response() else { return ResponsesWsRequest::ResponseCreate(payload); }; - let allow_empty_delta = matches!(ws_version, ResponsesWebsocketVersion::V2); - let Some(append_items) = - self.get_incremental_items(request, Some(&last_response), allow_empty_delta) + let Some(incremental_items) = + self.get_incremental_items(request, Some(&last_response), true) else { return ResponsesWsRequest::ResponseCreate(payload); }; - match ws_version { - ResponsesWebsocketVersion::V2 => { - if last_response.response_id.is_empty() { - trace!("incremental request failed, no previous response id"); - return ResponsesWsRequest::ResponseCreate(payload); - } - - ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { - previous_response_id: Some(last_response.response_id), - input: append_items, - ..payload - }) - } - ResponsesWebsocketVersion::V1 => { - if !last_response.can_append { - trace!("incremental request failed, can't append"); - return ResponsesWsRequest::ResponseCreate(payload); - } - ResponsesWsRequest::ResponseAppend(ResponseAppendWsRequest { - input: append_items, - client_metadata: payload.client_metadata, - }) - } + if last_response.response_id.is_empty() { + trace!("incremental request failed, no previous response id"); + return ResponsesWsRequest::ResponseCreate(payload); } + + ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { + previous_response_id: Some(last_response.response_id), + input: incremental_items, + ..payload + }) } /// Opportunistically preconnects a websocket for this turn-scoped client session. @@ -696,9 +663,9 @@ impl ModelClientSession { otel_manager: &OtelManager, model_info: &ModelInfo, ) -> std::result::Result<(), ApiError> { - let Some(ws_version) = self.client.active_ws_version(model_info) else { + if !self.client.responses_websocket_enabled(model_info) { return Ok(()); - }; + } if self.websocket_session.connection.is_some() { return Ok(()); } @@ -715,7 +682,6 @@ impl ModelClientSession { otel_manager, client_setup.api_provider, client_setup.api_auth, - ws_version, Some(Arc::clone(&self.turn_state)), None, ) @@ -729,7 +695,6 @@ impl ModelClientSession { otel_manager: &OtelManager, api_provider: codex_api::Provider, api_auth: CoreAuthProvider, - ws_version: ResponsesWebsocketVersion, turn_metadata_header: Option<&str>, options: &ApiResponsesOptions, ) -> std::result::Result<&ApiWebSocketConnection, ApiError> { @@ -751,7 +716,6 @@ impl ModelClientSession { otel_manager, api_provider, api_auth, - ws_version, Some(turn_state), turn_metadata_header, ) @@ -790,6 +754,7 @@ impl ModelClientSession { otel_manager: &OtelManager, effort: Option, summary: ReasoningSummaryConfig, + service_tier: Option, turn_metadata_header: Option<&str>, ) -> Result { if let Some(path) = &*CODEX_RS_SSE_FIXTURE { @@ -820,6 +785,7 @@ impl ModelClientSession { model_info, effort, summary, + service_tier, )?; let client = ApiResponsesClient::new( transport, @@ -851,10 +817,10 @@ impl ModelClientSession { &mut self, prompt: &Prompt, model_info: &ModelInfo, - ws_version: ResponsesWebsocketVersion, otel_manager: &OtelManager, effort: Option, summary: ReasoningSummaryConfig, + service_tier: Option, turn_metadata_header: Option<&str>, warmup: bool, ) -> Result { @@ -874,6 +840,7 @@ impl ModelClientSession { model_info, effort, summary, + service_tier, )?; let mut ws_payload = ResponseCreateWsRequest { client_metadata: build_ws_client_metadata(turn_metadata_header), @@ -888,7 +855,6 @@ impl ModelClientSession { otel_manager, client_setup.api_provider, client_setup.api_auth, - ws_version, turn_metadata_header, &options, ) @@ -909,7 +875,7 @@ impl ModelClientSession { Err(err) => return Err(map_api_error(err)), } - let ws_request = self.prepare_websocket_request(ws_payload, &request, ws_version); + let ws_request = self.prepare_websocket_request(ws_payload, &request); self.websocket_session.last_request = Some(request); let stream_result = self .websocket_session @@ -955,19 +921,13 @@ impl ModelClientSession { otel_manager: &OtelManager, effort: Option, summary: ReasoningSummaryConfig, + service_tier: Option, turn_metadata_header: Option<&str>, ) -> Result<()> { - let Some(ws_version) = self.client.active_ws_version(model_info) else { - return Ok(()); - }; - if self.websocket_session.last_request.is_some() { + if !self.client.responses_websocket_enabled(model_info) { return Ok(()); } - - if matches!(ws_version, ResponsesWebsocketVersion::V1) { - self.preconnect_websocket(otel_manager, model_info) - .await - .map_err(map_api_error)?; + if self.websocket_session.last_request.is_some() { return Ok(()); } @@ -975,10 +935,10 @@ impl ModelClientSession { .stream_responses_websocket( prompt, model_info, - ws_version, otel_manager, effort, summary, + service_tier, turn_metadata_header, true, ) @@ -1017,20 +977,21 @@ impl ModelClientSession { otel_manager: &OtelManager, effort: Option, summary: ReasoningSummaryConfig, + service_tier: Option, turn_metadata_header: Option<&str>, ) -> Result { let wire_api = self.client.state.provider.wire_api; match wire_api { WireApi::Responses => { - if let Some(ws_version) = self.client.active_ws_version(model_info) { + if self.client.responses_websocket_enabled(model_info) { match self .stream_responses_websocket( prompt, model_info, - ws_version, otel_manager, effort, summary, + service_tier, turn_metadata_header, false, ) @@ -1049,6 +1010,7 @@ impl ModelClientSession { otel_manager, effort, summary, + service_tier, turn_metadata_header, ) .await @@ -1067,7 +1029,7 @@ impl ModelClientSession { otel_manager: &OtelManager, model_info: &ModelInfo, ) -> bool { - let websocket_enabled = self.client.active_ws_version(model_info).is_some(); + let websocket_enabled = self.client.responses_websocket_enabled(model_info); let activated = self.activate_http_fallback(websocket_enabled); if activated { warn!("falling back to HTTP"); @@ -1165,7 +1127,6 @@ where Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, }) => { if let Some(usage) = &token_usage { otel_manager.sse_event_completed( @@ -1180,14 +1141,12 @@ where let _ = sender.send(LastResponse { response_id: response_id.clone(), items_added: std::mem::take(&mut items_added), - can_append, }); } if tx_event .send(Ok(ResponseEvent::Completed { response_id, token_usage, - can_append, })) .await .is_err() @@ -1317,7 +1276,7 @@ mod tests { provider, session_source, None, - None, + false, false, false, None, diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index 33fc438727..cddf99d6f5 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -84,19 +84,13 @@ fn reserialize_shell_outputs(items: &mut [ResponseItem]) { shell_call_ids.insert(call_id.clone()); } } - ResponseItem::CustomToolCallOutput { call_id, output } => { - if shell_call_ids.remove(call_id) - && let Some(structured) = parse_structured_shell_output(output) - { - *output = structured - } - } ResponseItem::FunctionCall { name, call_id, .. } if is_shell_tool_name(name) || name == "apply_patch" => { shell_call_ids.insert(call_id.clone()); } - ResponseItem::FunctionCallOutput { call_id, output } => { + ResponseItem::FunctionCallOutput { call_id, output } + | ResponseItem::CustomToolCallOutput { call_id, output } => { if shell_call_ids.remove(call_id) && let Some(structured) = output .text_content() @@ -240,6 +234,7 @@ mod tests { use codex_api::common::OpenAiVerbosity; use codex_api::common::TextControls; use codex_api::create_text_param_for_request; + use codex_protocol::models::FunctionCallOutputPayload; use pretty_assertions::assert_eq; use super::*; @@ -260,6 +255,7 @@ mod tests { stream: true, include: vec![], prompt_cache_key: None, + service_tier: None, text: Some(TextControls { verbosity: Some(OpenAiVerbosity::Low), format: None, @@ -301,6 +297,7 @@ mod tests { stream: true, include: vec![], prompt_cache_key: None, + service_tier: None, text: Some(text_controls), }; @@ -337,10 +334,69 @@ mod tests { stream: true, include: vec![], prompt_cache_key: None, + service_tier: None, text: None, }; let v = serde_json::to_value(&req).expect("json"); assert!(v.get("text").is_none()); } + + #[test] + fn reserializes_shell_outputs_for_function_and_custom_tool_calls() { + let raw_output = r#"{"output":"hello","metadata":{"exit_code":0,"duration_seconds":0.5}}"#; + let expected_output = "Exit code: 0\nWall time: 0.5 seconds\nOutput:\nhello"; + let mut items = vec![ + ResponseItem::FunctionCall { + id: None, + name: "shell".to_string(), + arguments: "{}".to_string(), + call_id: "call-1".to_string(), + }, + ResponseItem::FunctionCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload::from_text(raw_output.to_string()), + }, + ResponseItem::CustomToolCall { + id: None, + status: None, + call_id: "call-2".to_string(), + name: "apply_patch".to_string(), + input: "*** Begin Patch".to_string(), + }, + ResponseItem::CustomToolCallOutput { + call_id: "call-2".to_string(), + output: FunctionCallOutputPayload::from_text(raw_output.to_string()), + }, + ]; + + reserialize_shell_outputs(&mut items); + + assert_eq!( + items, + vec![ + ResponseItem::FunctionCall { + id: None, + name: "shell".to_string(), + arguments: "{}".to_string(), + call_id: "call-1".to_string(), + }, + ResponseItem::FunctionCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload::from_text(expected_output.to_string()), + }, + ResponseItem::CustomToolCall { + id: None, + status: None, + call_id: "call-2".to_string(), + name: "apply_patch".to_string(), + input: "*** Begin Patch".to_string(), + }, + ResponseItem::CustomToolCallOutput { + call_id: "call-2".to_string(), + output: FunctionCallOutputPayload::from_text(expected_output.to_string()), + }, + ] + ); + } } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 9fa0678d1c..c7429bbdcb 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -29,6 +29,8 @@ use crate::features::FEATURES; use crate::features::Feature; use crate::features::Features; use crate::features::maybe_push_unstable_features_warning; +#[cfg(test)] +use crate::models_manager::collaboration_mode_presets::CollaborationModesConfig; use crate::models_manager::manager::ModelsManager; use crate::parse_command::parse_command; use crate::parse_turn_item; @@ -51,6 +53,14 @@ use crate::util::error_or_panic; use crate::ws_version_from_features; use async_channel::Receiver; use async_channel::Sender; +use chrono::Local; +use chrono::Utc; +use codex_artifact_presentation::PresentationArtifactError; +use codex_artifact_presentation::PresentationArtifactExecutionRequest; +use codex_artifact_presentation::PresentationArtifactResponse; +use codex_artifact_spreadsheet::SpreadsheetArtifactError; +use codex_artifact_spreadsheet::SpreadsheetArtifactRequest; +use codex_artifact_spreadsheet::SpreadsheetArtifactResponse; use codex_hooks::HookEvent; use codex_hooks::HookEventAfterAgent; use codex_hooks::HookPayload; @@ -92,7 +102,6 @@ use codex_protocol::protocol::TurnContextNetworkItem; use codex_protocol::protocol::TurnStartedEvent; use codex_protocol::request_user_input::RequestUserInputArgs; use codex_protocol::request_user_input::RequestUserInputResponse; -use codex_protocol::skill_approval::SkillApprovalResponse; use codex_rmcp_client::ElicitationResponse; use codex_rmcp_client::OAuthCredentialsStoreMode; use codex_utils_stream_parser::AssistantTextChunk; @@ -153,12 +162,29 @@ use crate::error::Result as CodexResult; use crate::exec::StreamOutput; use codex_config::CONFIG_TOML_FILE; +mod rollout_reconstruction; +#[cfg(test)] +mod rollout_reconstruction_tests; + #[derive(Debug, PartialEq)] pub enum SteerInputError { NoActiveTurn(Vec), ExpectedTurnMismatch { expected: String, actual: String }, EmptyInput, } + +/// Notes from the previous real user turn. +/// +/// Conceptually this is the same role that `previous_model` used to fill, but +/// it can carry other prior-turn settings that matter when constructing +/// sensible state-change diffs or full-context reinjection, such as model +/// switches or detecting a prior `realtime_active -> false` transition. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PreviousTurnSettings { + pub(crate) model: String, + pub(crate) realtime_active: Option, +} + use crate::exec_policy::ExecPolicyUpdateError; use crate::feedback_tags; use crate::file_watcher::FileWatcher; @@ -166,8 +192,8 @@ use crate::file_watcher::FileWatcherEvent; use crate::git_info::get_git_repo_root; use crate::instructions::UserInstructions; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; +use crate::mcp::McpManager; use crate::mcp::auth::compute_auth_statuses; -use crate::mcp::effective_mcp_servers; use crate::mcp::maybe_prompt_and_install_mcp_dependencies; use crate::mcp::with_codex_apps_mcp; use crate::mcp_connection_manager::McpConnectionManager; @@ -181,12 +207,14 @@ use crate::mentions::build_skill_name_counts; use crate::mentions::collect_explicit_app_ids; use crate::mentions::collect_tool_mentions_from_messages; use crate::network_policy_decision::execpolicy_network_rule_amendment; +use crate::plugins::PluginsManager; use crate::project_doc::get_user_instructions; use crate::protocol::AgentMessageContentDeltaEvent; use crate::protocol::AgentReasoningSectionBreakEvent; use crate::protocol::ApplyPatchApprovalRequestEvent; use crate::protocol::AskForApproval; use crate::protocol::BackgroundEventEvent; +use crate::protocol::CompactedItem; use crate::protocol::DeprecationNoticeEvent; use crate::protocol::ErrorEvent; use crate::protocol::Event; @@ -197,7 +225,6 @@ use crate::protocol::ModelRerouteEvent; use crate::protocol::ModelRerouteReason; use crate::protocol::NetworkApprovalContext; use crate::protocol::Op; -use crate::protocol::PatchApplyStatus; use crate::protocol::PlanDeltaEvent; use crate::protocol::RateLimitSnapshot; use crate::protocol::ReasoningContentDeltaEvent; @@ -251,6 +278,7 @@ use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::handlers::SEARCH_TOOL_BM25_TOOL_NAME; use crate::tools::js_repl::JsReplHandle; +use crate::tools::js_repl::resolve_compatible_node; use crate::tools::network_approval::NetworkApprovalService; use crate::tools::network_approval::build_blocked_request_observer; use crate::tools::network_approval::build_network_policy_decider; @@ -268,6 +296,7 @@ use codex_otel::TelemetryAuthMode; 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::ServiceTier; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::ContentItem; use codex_protocol::models::DeveloperInstructions; @@ -314,6 +343,8 @@ impl Codex { auth_manager: Arc, models_manager: Arc, skills_manager: Arc, + plugins_manager: Arc, + mcp_manager: Arc, file_watcher: Arc, conversation_history: InitialHistory, session_source: SessionSource, @@ -321,10 +352,12 @@ impl Codex { dynamic_tools: Vec, persist_extended_history: bool, metrics_service_name: Option, + inherited_shell_snapshot: Option>, ) -> CodexResult { let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_event, rx_event) = async_channel::unbounded(); + plugins_manager.plugins_for_config(&config); let loaded_skills = skills_manager.skills_for_config(&config); for err in &loaded_skills.errors { @@ -341,6 +374,18 @@ impl Codex { config.features.disable(Feature::Collab); } + if config.features.enabled(Feature::JsRepl) + && let Err(err) = resolve_compatible_node(config.js_repl_node_path.as_deref()).await + { + let message = format!( + "Disabled `js_repl` for this session because the configured Node runtime is unavailable or incompatible. {err}" + ); + warn!("{message}"); + config.features.disable(Feature::JsRepl); + config.features.disable(Feature::JsReplToolsOnly); + config.startup_warnings.push(message); + } + let allowed_skills_for_implicit_invocation = loaded_skills.allowed_skills_for_implicit_invocation(); let user_instructions = @@ -351,14 +396,20 @@ impl Codex { .map_err(|err| CodexErr::Fatal(format!("failed to load rules: {err}")))?; let config = Arc::new(config); - let _ = models_manager - .list_models(crate::models_manager::manager::RefreshStrategy::OnlineIfUncached) - .await; - let model = models_manager - .get_default_model( - &config.model, - crate::models_manager::manager::RefreshStrategy::OnlineIfUncached, + let refresh_strategy = match session_source { + SessionSource::SubAgent(_) => crate::models_manager::manager::RefreshStrategy::Offline, + _ => crate::models_manager::manager::RefreshStrategy::OnlineIfUncached, + }; + if config.model.is_none() + || !matches!( + refresh_strategy, + crate::models_manager::manager::RefreshStrategy::Offline ) + { + let _ = models_manager.list_models(refresh_strategy).await; + } + let model = models_manager + .get_default_model(&config.model, refresh_strategy) .await; // Resolve base instructions for the session. Priority order: @@ -415,6 +466,7 @@ impl Codex { provider: config.model_provider.clone(), collaboration_mode, model_reasoning_summary: config.model_reasoning_summary, + service_tier: config.service_tier, developer_instructions: config.developer_instructions.clone(), user_instructions, personality: config.personality, @@ -428,9 +480,11 @@ impl Codex { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name, + app_server_client_name: None, session_source, dynamic_tools, persist_extended_history, + inherited_shell_snapshot, }; // Generate a unique ID for the lifetime of this Codex session. @@ -449,6 +503,8 @@ impl Codex { conversation_history, session_source_clone, skills_manager, + plugins_manager, + mcp_manager, file_watcher, agent_control, ) @@ -515,6 +571,18 @@ impl Codex { self.session.steer_input(input, expected_turn_id).await } + pub(crate) async fn set_app_server_client_name( + &self, + app_server_client_name: Option, + ) -> ConstraintResult<()> { + self.session + .update_settings(SessionSettingsUpdate { + app_server_client_name, + ..Default::default() + }) + .await + } + pub(crate) async fn agent_status(&self) -> AgentStatus { self.agent_status.borrow().clone() } @@ -570,6 +638,7 @@ impl TurnSkillsContext { #[derive(Debug)] pub(crate) struct TurnContext { pub(crate) sub_id: String, + pub(crate) realtime_active: bool, pub(crate) config: Arc, pub(crate) auth_manager: Option>, pub(crate) model_info: ModelInfo, @@ -582,6 +651,9 @@ pub(crate) struct TurnContext { /// the model as well as sandbox policies are resolved against this path /// instead of `std::env::current_dir()`. pub(crate) cwd: PathBuf, + pub(crate) current_date: Option, + pub(crate) timezone: Option, + pub(crate) app_server_client_name: Option, pub(crate) developer_instructions: Option, pub(crate) compact_prompt: Option, pub(crate) user_instructions: Option, @@ -654,6 +726,7 @@ impl TurnContext { Self { sub_id: self.sub_id.clone(), + realtime_active: self.realtime_active, config: Arc::new(config), auth_manager: self.auth_manager.clone(), model_info: model_info.clone(), @@ -666,6 +739,9 @@ impl TurnContext { reasoning_summary: self.reasoning_summary, session_source: self.session_source.clone(), cwd: self.cwd.clone(), + current_date: self.current_date.clone(), + timezone: self.timezone.clone(), + app_server_client_name: self.app_server_client_name.clone(), developer_instructions: self.developer_instructions.clone(), compact_prompt: self.compact_prompt.clone(), user_instructions: self.user_instructions.clone(), @@ -706,12 +782,15 @@ impl TurnContext { TurnContextItem { turn_id: Some(self.sub_id.clone()), cwd: self.cwd.clone(), + current_date: self.current_date.clone(), + timezone: self.timezone.clone(), approval_policy: self.approval_policy.value(), sandbox_policy: self.sandbox_policy.get().clone(), network: self.turn_context_network_item(), model: self.model_info.slug.clone(), personality: self.personality, collaboration_mode: Some(self.collaboration_mode.clone()), + realtime_active: Some(self.realtime_active), effort: self.reasoning_effort, summary: self.reasoning_summary, user_instructions: self.user_instructions.clone(), @@ -735,13 +814,24 @@ impl TurnContext { } } +fn local_time_context() -> (String, String) { + match iana_time_zone::get_timezone() { + Ok(timezone) => (Local::now().format("%Y-%m-%d").to_string(), timezone), + Err(_) => ( + Utc::now().format("%Y-%m-%d").to_string(), + "Etc/UTC".to_string(), + ), + } +} + #[derive(Clone)] pub(crate) struct SessionConfiguration { /// Provider identifier ("openai", "openrouter", ...). provider: ModelProviderInfo, collaboration_mode: CollaborationMode, - model_reasoning_summary: ReasoningSummaryConfig, + model_reasoning_summary: Option, + service_tier: Option, /// Developer instructions that supplement the base instructions. developer_instructions: Option, @@ -781,10 +871,12 @@ pub(crate) struct SessionConfiguration { original_config_do_not_use: Arc, /// Optional service name tag for session metrics. metrics_service_name: Option, + app_server_client_name: Option, /// Source of the session (cli, vscode, exec, mcp, ...) session_source: SessionSource, dynamic_tools: Vec, persist_extended_history: bool, + inherited_shell_snapshot: Option>, } impl SessionConfiguration { @@ -796,9 +888,11 @@ impl SessionConfiguration { ThreadConfigSnapshot { model: self.collaboration_mode.model().to_string(), model_provider_id: self.original_config_do_not_use.model_provider_id.clone(), + service_tier: self.service_tier, approval_policy: self.approval_policy.value(), sandbox_policy: self.sandbox_policy.get().clone(), cwd: self.cwd.clone(), + ephemeral: self.original_config_do_not_use.ephemeral, reasoning_effort: self.collaboration_mode.reasoning_effort(), personality: self.personality, session_source: self.session_source.clone(), @@ -811,7 +905,10 @@ impl SessionConfiguration { next_configuration.collaboration_mode = collaboration_mode; } if let Some(summary) = updates.reasoning_summary { - next_configuration.model_reasoning_summary = summary; + next_configuration.model_reasoning_summary = Some(summary); + } + if let Some(service_tier) = updates.service_tier { + next_configuration.service_tier = service_tier; } if let Some(personality) = updates.personality { next_configuration.personality = Some(personality); @@ -828,6 +925,9 @@ impl SessionConfiguration { if let Some(cwd) = updates.cwd.clone() { next_configuration.cwd = cwd; } + if let Some(app_server_client_name) = updates.app_server_client_name.clone() { + next_configuration.app_server_client_name = Some(app_server_client_name); + } Ok(next_configuration) } } @@ -840,8 +940,10 @@ pub(crate) struct SessionSettingsUpdate { pub(crate) windows_sandbox_level: Option, pub(crate) collaboration_mode: Option, pub(crate) reasoning_summary: Option, + pub(crate) service_tier: Option>, pub(crate) final_output_json_schema: Option>, pub(crate) personality: Option, + pub(crate) app_server_client_name: Option, } impl Session { @@ -909,6 +1011,7 @@ impl Session { per_turn_config.model_reasoning_effort = session_configuration.collaboration_mode.reasoning_effort(); per_turn_config.model_reasoning_summary = session_configuration.model_reasoning_summary; + per_turn_config.service_tier = session_configuration.service_tier; per_turn_config.personality = session_configuration.personality; let resolved_web_search_mode = resolve_web_search_mode_for_turn( &per_turn_config.web_search_mode, @@ -972,7 +1075,9 @@ impl Session { skills_outcome: Arc, ) -> TurnContext { let reasoning_effort = session_configuration.collaboration_mode.reasoning_effort(); - let reasoning_summary = session_configuration.model_reasoning_summary; + let reasoning_summary = session_configuration + .model_reasoning_summary + .unwrap_or(model_info.default_reasoning_summary); let otel_manager = otel_manager.clone().with_model( session_configuration.collaboration_mode.model(), model_info.slug.as_str(), @@ -1002,8 +1107,10 @@ impl Session { .features .enabled(Feature::UseLinuxSandboxBwrap), )); + let (current_date, timezone) = local_time_context(); TurnContext { sub_id, + realtime_active: false, config: per_turn_config.clone(), auth_manager: auth_manager_for_context, model_info: model_info.clone(), @@ -1013,6 +1120,9 @@ impl Session { reasoning_summary, session_source, cwd, + current_date: Some(current_date), + timezone: Some(timezone), + app_server_client_name: session_configuration.app_server_client_name.clone(), developer_instructions: session_configuration.developer_instructions.clone(), compact_prompt: session_configuration.compact_prompt.clone(), user_instructions: session_configuration.user_instructions.clone(), @@ -1049,6 +1159,8 @@ impl Session { initial_history: InitialHistory, session_source: SessionSource, skills_manager: Arc, + plugins_manager: Arc, + mcp_manager: Arc, file_watcher: Arc, agent_control: AgentControl, ) -> anyhow::Result> { @@ -1111,7 +1223,7 @@ impl Session { // // - initialize RolloutRecorder with new or resumed session info // - perform default shell discovery - // - load history metadata + // - load history metadata (skipped for subagents) let rollout_fut = async { if config.ephemeral { Ok::<_, anyhow::Error>((None, None)) @@ -1128,12 +1240,22 @@ impl Session { } }; - let history_meta_fut = crate::message_history::history_metadata(&config); + let history_meta_fut = async { + if matches!( + session_configuration.session_source, + SessionSource::SubAgent(_) + ) { + (0, 0) + } else { + crate::message_history::history_metadata(&config).await + } + }; let auth_manager_clone = Arc::clone(&auth_manager); let config_for_mcp = Arc::clone(&config); + let mcp_manager_for_mcp = Arc::clone(&mcp_manager); let auth_and_mcp_fut = async move { let auth = auth_manager_clone.auth().await; - let mcp_servers = effective_mcp_servers(&config_for_mcp, auth.as_ref()); + let mcp_servers = mcp_manager_for_mcp.effective_servers(&config_for_mcp, auth.as_ref()); let auth_statuses = compute_auth_statuses( mcp_servers.iter(), config_for_mcp.mcp_oauth_credentials_store_mode, @@ -1249,7 +1371,9 @@ impl Session { otel_manager.conversation_starts( config.model_provider.name.as_str(), session_configuration.collaboration_mode.reasoning_effort(), - config.model_reasoning_summary, + config + .model_reasoning_summary + .unwrap_or(ReasoningSummaryConfig::Auto), config.model_context_window, config.model_auto_compact_token_limit, config.permissions.approval_policy.value(), @@ -1277,13 +1401,19 @@ impl Session { }; // Create the mutable state for the Session. let shell_snapshot_tx = if config.features.enabled(Feature::ShellSnapshot) { - ShellSnapshot::start_snapshotting( - config.codex_home.clone(), - conversation_id, - session_configuration.cwd.clone(), - &mut default_shell, - otel_manager.clone(), - ) + if let Some(snapshot) = session_configuration.inherited_shell_snapshot.clone() { + let (tx, rx) = watch::channel(Some(snapshot)); + default_shell.shell_snapshot = rx; + tx + } else { + ShellSnapshot::start_snapshotting( + config.codex_home.clone(), + conversation_id, + session_configuration.cwd.clone(), + &mut default_shell, + otel_manager.clone(), + ) + } } else { let (tx, rx) = watch::channel(None); default_shell.shell_snapshot = rx; @@ -1379,8 +1509,10 @@ impl Session { otel_manager, models_manager: Arc::clone(&models_manager), tool_approvals: Mutex::new(ApprovalStore::default()), - execve_session_approvals: RwLock::new(HashSet::new()), + execve_session_approvals: RwLock::new(HashMap::new()), skills_manager, + plugins_manager, + mcp_manager, file_watcher, agent_control, network_proxy, @@ -1431,6 +1563,7 @@ impl Session { thread_name: session_configuration.thread_name.clone(), model: session_configuration.collaboration_mode.model().to_string(), model_provider_id: config.model_provider_id.clone(), + service_tier: session_configuration.service_tier, approval_policy: session_configuration.approval_policy.value(), sandbox_policy: session_configuration.sandbox_policy.get().clone(), cwd: session_configuration.cwd.clone(), @@ -1650,46 +1783,75 @@ impl Session { state.clear_connector_selection(); } + pub(crate) async fn execute_presentation_artifact( + &self, + request: PresentationArtifactExecutionRequest, + cwd: &Path, + ) -> Result { + let mut state = self.state.lock().await; + state.artifacts.presentation.execute_requests(request, cwd) + } + + pub(crate) async fn execute_spreadsheet_artifact( + &self, + request: SpreadsheetArtifactRequest, + cwd: &Path, + ) -> Result { + let mut state = self.state.lock().await; + state.artifacts.spreadsheet.execute(request, cwd) + } + async fn record_initial_history(&self, conversation_history: InitialHistory) { let turn_context = self.new_default_turn().await; self.clear_mcp_tool_selection().await; + let is_subagent = { + let state = self.state.lock().await; + matches!( + state.session_configuration.session_source, + SessionSource::SubAgent(_) + ) + }; match conversation_history { InitialHistory::New => { // Build and record initial items (user instructions + environment context) + // TODO(ccunningham): Defer initial context insertion until the first real turn + // starts so it reflects the actual first-turn settings (permissions, etc.) and + // we do not emit model-visible "diff" updates before the first user message. let items = self.build_initial_context(&turn_context).await; self.record_conversation_items(&turn_context, &items).await; { let mut state = self.state.lock().await; state.set_reference_context_item(Some(turn_context.to_turn_context_item())); } - self.set_previous_model(None).await; + self.set_previous_turn_settings(None).await; // Ensure initial items are visible to immediate readers (e.g., tests, forks). - self.flush_rollout().await; + if !is_subagent { + self.flush_rollout().await; + } } InitialHistory::Resumed(resumed_history) => { let rollout_items = resumed_history.history; let restored_tool_selection = Self::extract_mcp_tool_selection_from_rollout(&rollout_items); - let (previous_regular_turn_context_item, crossed_compaction_after_turn) = - Self::last_rollout_regular_turn_context_lookup(&rollout_items); - let previous_model = - previous_regular_turn_context_item.map(|ctx| ctx.model.clone()); - let curr = turn_context.model_info.slug.as_str(); - let reference_context_item = if !crossed_compaction_after_turn { - previous_regular_turn_context_item.cloned() - } else { - // Keep the baseline empty when compaction may have stripped the referenced - // context diffs so the first resumed regular turn fully reinjects context. - None - }; + + let reconstructed_rollout = self + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + let previous_turn_settings = reconstructed_rollout.previous_turn_settings.clone(); + self.set_previous_turn_settings(previous_turn_settings.clone()) + .await; { let mut state = self.state.lock().await; - state.set_reference_context_item(reference_context_item); + state.set_reference_context_item(reconstructed_rollout.reference_context_item); } - self.set_previous_model(previous_model.clone()).await; // If resuming, warn when the last recorded model differs from the current one. - if let Some(prev) = previous_model.as_deref().filter(|p| *p != curr) { + let curr: &str = turn_context.model_info.slug.as_str(); + if let Some(prev) = previous_turn_settings + .as_ref() + .map(|settings| settings.model.as_str()) + .filter(|model| *model != curr) + { warn!("resuming session with different model: previous={prev}, current={curr}"); self.send_event( &turn_context, @@ -1704,9 +1866,7 @@ impl Session { } // Always add response items to conversation history - let reconstructed_history = self - .reconstruct_history_from_rollout(&turn_context, &rollout_items) - .await; + let reconstructed_history = reconstructed_rollout.history; if !reconstructed_history.is_empty() { self.record_into_history(&reconstructed_history, &turn_context) .await; @@ -1724,21 +1884,30 @@ impl Session { // Defer seeding the session's initial context until the first turn starts so // turn/start overrides can be merged before we write to the rollout. - self.flush_rollout().await; + if !is_subagent { + self.flush_rollout().await; + } } InitialHistory::Forked(rollout_items) => { let restored_tool_selection = Self::extract_mcp_tool_selection_from_rollout(&rollout_items); - let (previous_regular_turn_context_item, _) = - Self::last_rollout_regular_turn_context_lookup(&rollout_items); - let previous_model = - previous_regular_turn_context_item.map(|ctx| ctx.model.clone()); - self.set_previous_model(previous_model).await; - // Always add response items to conversation history - let reconstructed_history = self + let reconstructed_rollout = self .reconstruct_history_from_rollout(&turn_context, &rollout_items) .await; + self.set_previous_turn_settings( + reconstructed_rollout.previous_turn_settings.clone(), + ) + .await; + { + let mut state = self.state.lock().await; + state.set_reference_context_item( + reconstructed_rollout.reference_context_item.clone(), + ); + } + + // Always add response items to conversation history + let reconstructed_history = reconstructed_rollout.history; if !reconstructed_history.is_empty() { self.record_into_history(&reconstructed_history, &turn_context) .await; @@ -1772,153 +1941,11 @@ impl Session { self.ensure_rollout_materialized().await; // Flush after seeding history and any persisted rollout copy. - self.flush_rollout().await; - } - } - } - - /// Returns `(last_turn_context_item, crossed_compaction_after_turn)` from the - /// rollback-adjusted rollout view. - /// - /// This relies on the invariant that only regular turns persist `TurnContextItem`. - /// `ThreadRolledBack` markers are applied so resume/fork uses the post-rollback history view. - /// - /// Returns `(None, false)` when no persisted `TurnContextItem` can be found. - /// - /// Older/minimal rollouts may only contain `RolloutItem::TurnContext` entries without turn - /// lifecycle events. In that case we fall back to the last `TurnContextItem` (plus whether a - /// later `Compacted` item appears in rollout order). - // TODO(ccunningham): Simplify this lookup by sharing rollout traversal/rollback application - // with `reconstruct_history_from_rollout` so resume/fork baseline hydration does not need a - // second bespoke rollout scan. - fn last_rollout_regular_turn_context_lookup( - rollout_items: &[RolloutItem], - ) -> (Option<&TurnContextItem>, bool) { - // Reverse scan over rollout items. `ThreadRolledBack(num_turns)` is naturally handled by - // skipping the next `num_turns` completed turn spans we encounter while walking backward. - // - // "Active turn" here means: we have seen `TurnComplete`/`TurnAborted` and are currently - // scanning backward through that completed turn until its matching `TurnStarted`. - let mut turns_to_skip_due_to_rollback = 0usize; - let mut saw_surviving_compaction_after_candidate = false; - let mut saw_turn_lifecycle_event = false; - let mut active_turn_id: Option<&str> = None; - let mut active_turn_saw_user_message = false; - let mut active_turn_context: Option<&TurnContextItem> = None; - let mut active_turn_contains_compaction = false; - - for item in rollout_items.iter().rev() { - match item { - RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => { - // Rollbacks count completed turns, not `TurnContextItem`s. We must continue - // ignoring all items inside each skipped turn until we reach its - // corresponding `TurnStarted`. - let num_turns = usize::try_from(rollback.num_turns).unwrap_or(usize::MAX); - turns_to_skip_due_to_rollback = - turns_to_skip_due_to_rollback.saturating_add(num_turns); - } - RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => { - saw_turn_lifecycle_event = true; - // Enter the reverse "turn span" for this completed turn. - active_turn_id = Some(event.turn_id.as_str()); - active_turn_saw_user_message = false; - active_turn_context = None; - active_turn_contains_compaction = false; - } - RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => { - saw_turn_lifecycle_event = true; - // Same reverse-turn handling as `TurnComplete`. Some aborted turns may not - // have a turn id; in that case we cannot match `TurnContextItem`s to them. - active_turn_id = event.turn_id.as_deref(); - active_turn_saw_user_message = false; - active_turn_context = None; - active_turn_contains_compaction = false; - } - RolloutItem::EventMsg(EventMsg::UserMessage(_)) => { - if active_turn_id.is_some() { - active_turn_saw_user_message = true; - } - } - RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => { - saw_turn_lifecycle_event = true; - if active_turn_id == Some(event.turn_id.as_str()) { - let active_turn_is_rolled_back = - active_turn_saw_user_message && turns_to_skip_due_to_rollback > 0; - if active_turn_is_rolled_back { - // `ThreadRolledBack(num_turns)` counts user turns, so only consume a - // skip once we've confirmed this reverse-scanned turn span contains a - // user message. Standalone task turns must not consume rollback skips. - turns_to_skip_due_to_rollback -= 1; - } - if !active_turn_is_rolled_back { - if let Some(context_item) = active_turn_context { - return ( - Some(context_item), - saw_surviving_compaction_after_candidate, - ); - } - // No `TurnContextItem` in this surviving turn; keep scanning older - // turns, but remember if this turn compacted so the eventual - // candidate reports "compaction happened after it". - if active_turn_contains_compaction { - saw_surviving_compaction_after_candidate = true; - } - } - active_turn_id = None; - active_turn_saw_user_message = false; - active_turn_context = None; - active_turn_contains_compaction = false; - } - } - RolloutItem::TurnContext(ctx) => { - // Capture the latest turn context seen in this reverse-scanned turn span. If - // the turn later proves to be rolled back, we discard it when we hit the - // matching `TurnStarted`. Older rollouts may have lifecycle events but omit - // `TurnContextItem.turn_id`; accept those as belonging to the active turn - // span for resume/fork hydration. - if let Some(active_id) = active_turn_id - && ctx - .turn_id - .as_deref() - .is_none_or(|turn_id| turn_id == active_id) - { - // Reverse scan sees the latest `TurnContextItem` for the turn first. - active_turn_context.get_or_insert(ctx); - } - } - RolloutItem::Compacted(_) => { - if active_turn_id.is_some() { - // Compaction inside the currently scanned turn is only "after" the - // eventual candidate if this turn has no `TurnContextItem` and we keep - // scanning into older turns. - active_turn_contains_compaction = true; - } else { - saw_surviving_compaction_after_candidate = true; - } - } - _ => {} - } - } - - // Legacy/minimal rollouts may only persist `TurnContextItem`/`Compacted` without turn - // lifecycle events. Fall back to the last `TurnContextItem` in rollout order so - // resume/fork can still hydrate `previous_model` and detect compaction-after-baseline. - if !saw_turn_lifecycle_event { - let mut saw_compaction_after_last_turn_context = false; - for item in rollout_items.iter().rev() { - match item { - RolloutItem::Compacted(_) => { - saw_compaction_after_last_turn_context = true; - } - RolloutItem::TurnContext(ctx) => { - return (Some(ctx), saw_compaction_after_last_turn_context); - } - _ => {} + if !is_subagent { + self.flush_rollout().await; } } } - - (None, false) } fn last_token_info_from_rollout(rollout_items: &[RolloutItem]) -> Option { @@ -1976,14 +2003,17 @@ impl Session { active_selected_tools } - async fn previous_model(&self) -> Option { + async fn previous_turn_settings(&self) -> Option { let state = self.state.lock().await; - state.previous_model() + state.previous_turn_settings() } - pub(crate) async fn set_previous_model(&self, previous_model: Option) { + pub(crate) async fn set_previous_turn_settings( + &self, + previous_turn_settings: Option, + ) { let mut state = self.state.lock().await; - state.set_previous_model(previous_model); + state.set_previous_turn_settings(previous_turn_settings); } fn maybe_refresh_shell_snapshot_for_cwd( @@ -1991,6 +2021,7 @@ impl Session { previous_cwd: &Path, next_cwd: &Path, codex_home: &Path, + session_source: &SessionSource, ) { if previous_cwd == next_cwd { return; @@ -2000,6 +2031,13 @@ impl Session { return; } + if matches!( + session_source, + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. }) + ) { + return; + } + ShellSnapshot::refresh_snapshot( codex_home.to_path_buf(), self.conversation_id, @@ -2021,10 +2059,16 @@ impl Session { let previous_cwd = state.session_configuration.cwd.clone(); let next_cwd = updated.cwd.clone(); let codex_home = updated.codex_home.clone(); + let session_source = updated.session_source.clone(); state.session_configuration = updated; drop(state); - self.maybe_refresh_shell_snapshot_for_cwd(&previous_cwd, &next_cwd, &codex_home); + self.maybe_refresh_shell_snapshot_for_cwd( + &previous_cwd, + &next_cwd, + &codex_home, + &session_source, + ); Ok(()) } @@ -2040,7 +2084,13 @@ impl Session { sub_id: String, updates: SessionSettingsUpdate, ) -> ConstraintResult> { - let (session_configuration, sandbox_policy_changed, previous_cwd, codex_home) = { + let ( + session_configuration, + sandbox_policy_changed, + previous_cwd, + codex_home, + session_source, + ) = { let mut state = self.state.lock().await; match state.session_configuration.clone().apply(&updates) { Ok(next) => { @@ -2048,8 +2098,15 @@ impl Session { let sandbox_policy_changed = state.session_configuration.sandbox_policy != next.sandbox_policy; let codex_home = next.codex_home.clone(); + let session_source = next.session_source.clone(); state.session_configuration = next.clone(); - (next, sandbox_policy_changed, previous_cwd, codex_home) + ( + next, + sandbox_policy_changed, + previous_cwd, + codex_home, + session_source, + ) } Err(err) => { drop(state); @@ -2070,6 +2127,7 @@ impl Session { &previous_cwd, &session_configuration.cwd, &codex_home, + &session_source, ); Ok(self @@ -2146,6 +2204,7 @@ impl Session { Arc::clone(&self.js_repl), skills_outcome, ); + turn_context.realtime_active = self.conversation.running_state().await.is_some(); if let Some(final_schema) = final_output_json_schema { turn_context.final_output_json_schema = final_schema; @@ -2294,6 +2353,8 @@ impl Session { .config_layer_stack .with_user_config(&config_toml_path, user_config); state.session_configuration.original_config_do_not_use = Arc::new(config); + self.services.skills_manager.clear_cache(); + self.services.plugins_manager.clear_cache(); } pub(crate) async fn new_default_turn_with_sub_id(&self, sub_id: String) -> Arc { @@ -2305,21 +2366,24 @@ impl Session { .await } - fn build_settings_update_items( + async fn build_settings_update_items( &self, reference_context_item: Option<&TurnContextItem>, - previous_user_turn_model: Option<&str>, current_context: &TurnContext, ) -> Vec { // TODO: Make context updates a pure diff of persisted previous/current TurnContextItem // state so replay/backtracking is deterministic. Runtime inputs that affect model-visible - // context (shell, exec policy, feature gates, previous-model bridge) should be persisted + // context (shell, exec policy, feature gates, previous-turn bridge) should be persisted // state or explicit non-state replay events. + let previous_turn_settings = { + let state = self.state.lock().await; + state.previous_turn_settings() + }; let shell = self.user_shell(); let exec_policy = self.services.exec_policy.current(); crate::context_manager::updates::build_settings_update_items( reference_context_item, - previous_user_turn_model, + previous_turn_settings.as_ref(), current_context, shell.as_ref(), exec_policy.as_ref(), @@ -2337,6 +2401,8 @@ impl Session { self.send_event_raw(event).await; self.maybe_mirror_event_text_to_realtime(&legacy_source) .await; + self.maybe_clear_realtime_handoff_for_event(&legacy_source) + .await; let show_raw_agent_reasoning = self.show_raw_agent_reasoning(); for legacy in legacy_source.as_legacy_events(show_raw_agent_reasoning) { @@ -2352,14 +2418,23 @@ impl Session { let Some(text) = realtime_text_for_event(msg) else { return; }; - if self.conversation.running_state().await.is_none() { + if self.conversation.running_state().await.is_none() + || self.conversation.active_handoff_id().await.is_none() + { return; } - if let Err(err) = self.conversation.text_in(text).await { + if let Err(err) = self.conversation.handoff_out(text).await { debug!("failed to mirror event text to realtime conversation: {err}"); } } + async fn maybe_clear_realtime_handoff_for_event(&self, msg: &EventMsg) { + if !matches!(msg, EventMsg::TurnComplete(_)) { + return; + } + self.conversation.clear_active_handoff().await; + } + pub(crate) async fn send_event_raw(&self, event: Event) { // Record the last known agent status. if let Some(status) = agent_status_from_event(&event.msg) { @@ -2589,9 +2664,13 @@ impl Session { /// Emit an exec approval request event and await the user's decision. /// - /// The request is keyed by `call_id` + `approval_id` so matching responses are delivered - /// to the correct in-flight turn. If the task is aborted, this returns the - /// default `ReviewDecision` (`Denied`). + /// The request is keyed by `call_id` + `approval_id` so matching responses + /// are delivered to the correct in-flight turn. If the task is aborted, + /// this returns the default `ReviewDecision` (`Denied`). + /// + /// Note that if `available_decisions` is `None`, then the other fields will + /// be used to derive the available decisions via + /// [ExecApprovalRequestEvent::default_available_decisions]. #[allow(clippy::too_many_arguments)] pub async fn request_command_approval( &self, @@ -2604,6 +2683,7 @@ impl Session { network_approval_context: Option, proposed_execpolicy_amendment: Option, additional_permissions: Option, + available_decisions: Option>, ) -> ReviewDecision { // command-level approvals use `call_id`. // `approval_id` is only present for subcommand callbacks (execve intercept) @@ -2637,6 +2717,14 @@ impl Session { }, ] }); + let available_decisions = available_decisions.unwrap_or_else(|| { + ExecApprovalRequestEvent::default_available_decisions( + network_approval_context.as_ref(), + proposed_execpolicy_amendment.as_ref(), + proposed_network_policy_amendments.as_deref(), + additional_permissions.as_ref(), + ) + }); let event = EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { call_id, approval_id, @@ -2648,6 +2736,7 @@ impl Session { proposed_execpolicy_amendment, proposed_network_policy_amendments, additional_permissions, + available_decisions: Some(available_decisions), parsed_cmd, }); self.send_event(turn_context, event).await; @@ -2722,40 +2811,6 @@ impl Session { rx_response.await.ok() } - pub async fn request_skill_approval( - &self, - turn_context: &TurnContext, - item_id: String, - skill_name: String, - ) -> Option { - let (tx_response, rx_response) = oneshot::channel(); - let prev_entry = { - let mut active = self.active_turn.lock().await; - match active.as_mut() { - Some(at) => { - let mut ts = at.turn_state.lock().await; - ts.insert_pending_skill_approval(item_id.clone(), tx_response) - } - None => None, - } - }; - if prev_entry.is_some() { - warn!("Overwriting existing pending skill approval for item_id: {item_id}"); - } - - self.send_event( - turn_context, - EventMsg::SkillRequestApproval( - codex_protocol::skill_approval::SkillRequestApprovalEvent { - item_id, - skill_name, - }, - ), - ) - .await; - rx_response.await.ok() - } - pub async fn notify_user_input_response( &self, sub_id: &str, @@ -2802,31 +2857,6 @@ impl Session { } } - pub async fn notify_skill_approval_response( - &self, - item_id: &str, - response: SkillApprovalResponse, - ) { - let entry = { - let mut active = self.active_turn.lock().await; - match active.as_mut() { - Some(at) => { - let mut ts = at.turn_state.lock().await; - ts.remove_pending_skill_approval(item_id) - } - None => None, - } - }; - match entry { - Some(tx_response) => { - tx_response.send(response).ok(); - } - None => { - warn!("No pending skill approval found for item_id: {item_id}"); - } - } - } - pub async fn notify_approval(&self, approval_id: &str, decision: ReviewDecision) { let entry = { let mut active = self.active_turn.lock().await; @@ -2874,42 +2904,6 @@ impl Session { self.send_raw_response_items(turn_context, items).await; } - async fn reconstruct_history_from_rollout( - &self, - turn_context: &TurnContext, - rollout_items: &[RolloutItem], - ) -> Vec { - let mut history = ContextManager::new(); - for item in rollout_items { - match item { - RolloutItem::ResponseItem(response_item) => { - history.record_items( - std::iter::once(response_item), - turn_context.truncation_policy, - ); - } - RolloutItem::Compacted(compacted) => { - if let Some(replacement) = &compacted.replacement_history { - history.replace(replacement.clone()); - } else { - let user_messages = collect_user_messages(history.raw_items()); - let rebuilt = compact::build_compacted_history( - self.build_initial_context(turn_context).await, - &user_messages, - &compacted.message, - ); - history.replace(rebuilt); - } - } - RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => { - history.drop_last_n_user_turns(rollback.num_turns); - } - _ => {} - } - } - history.raw_items().to_vec() - } - /// Append ResponseItems to the in-memory conversation history only. pub(crate) async fn record_into_history( &self, @@ -2987,6 +2981,23 @@ impl Session { state.replace_history(items, reference_context_item); } + pub(crate) async fn replace_compacted_history( + &self, + items: Vec, + reference_context_item: Option, + compacted_item: CompactedItem, + ) { + self.replace_history(items, reference_context_item.clone()) + .await; + + self.persist_rollout_items(&[RolloutItem::Compacted(compacted_item)]) + .await; + if let Some(turn_context_item) = reference_context_item { + self.persist_rollout_items(&[RolloutItem::TurnContext(turn_context_item)]) + .await; + } + } + async fn persist_rollout_response_items(&self, items: &[ResponseItem]) { let rollout_items: Vec = items .iter() @@ -3023,9 +3034,27 @@ impl Session { &self, turn_context: &TurnContext, ) -> Vec { - let mut items = Vec::::with_capacity(4); + let mut developer_sections = Vec::::with_capacity(8); + let mut contextual_user_sections = Vec::::with_capacity(2); let shell = self.user_shell(); - items.push( + let (reference_context_item, previous_turn_settings, collaboration_mode, base_instructions) = { + let state = self.state.lock().await; + ( + state.reference_context_item(), + state.previous_turn_settings(), + state.session_configuration.collaboration_mode.clone(), + state.session_configuration.base_instructions.clone(), + ) + }; + if let Some(model_switch_message) = + crate::context_manager::updates::build_model_instructions_update_item( + previous_turn_settings.as_ref(), + turn_context, + ) + { + developer_sections.push(model_switch_message.into_text()); + } + developer_sections.push( DeveloperInstructions::from_policy( turn_context.sandbox_policy.get(), turn_context.approval_policy.value(), @@ -3033,30 +3062,31 @@ impl Session { &turn_context.cwd, turn_context.features.enabled(Feature::RequestPermissions), ) - .into(), + .into_text(), ); if let Some(developer_instructions) = turn_context.developer_instructions.as_deref() { - items.push(DeveloperInstructions::new(developer_instructions.to_string()).into()); + developer_sections.push(developer_instructions.to_string()); } // Add developer instructions for memories. - if let Some(memory_prompt) = - build_memory_tool_developer_instructions(&turn_context.config.codex_home).await - && turn_context.features.enabled(Feature::MemoryTool) + if turn_context.features.enabled(Feature::MemoryTool) + && turn_context.config.memories.use_memories + && let Some(memory_prompt) = + build_memory_tool_developer_instructions(&turn_context.config.codex_home).await { - items.push(DeveloperInstructions::new(memory_prompt).into()); + developer_sections.push(memory_prompt); } // Add developer instructions from collaboration_mode if they exist and are non-empty - let (collaboration_mode, base_instructions) = { - let state = self.state.lock().await; - ( - state.session_configuration.collaboration_mode.clone(), - state.session_configuration.base_instructions.clone(), - ) - }; if let Some(collab_instructions) = DeveloperInstructions::from_collaboration_mode(&collaboration_mode) { - items.push(collab_instructions.into()); + developer_sections.push(collab_instructions.into_text()); + } + if let Some(realtime_update) = crate::context_manager::updates::build_initial_realtime_item( + reference_context_item.as_ref(), + previous_turn_settings.as_ref(), + turn_context, + ) { + developer_sections.push(realtime_update.into_text()); } if self.features.enabled(Feature::Personality) && let Some(personality) = turn_context.personality @@ -3071,34 +3101,53 @@ impl Session { personality, ) { - items.push( - DeveloperInstructions::personality_spec_message(personality_message).into(), + developer_sections.push( + DeveloperInstructions::personality_spec_message(personality_message) + .into_text(), ); } } if turn_context.features.enabled(Feature::Apps) { - items.push(DeveloperInstructions::new(render_apps_section()).into()); + developer_sections.push(render_apps_section()); } if turn_context.features.enabled(Feature::CodexGitCommit) && let Some(commit_message_instruction) = commit_message_trailer_instruction( turn_context.config.commit_attribution.as_deref(), ) { - items.push(DeveloperInstructions::new(commit_message_instruction).into()); + developer_sections.push(commit_message_instruction); } if let Some(user_instructions) = turn_context.user_instructions.as_deref() { - items.push( + contextual_user_sections.push( UserInstructions { text: user_instructions.to_string(), directory: turn_context.cwd.to_string_lossy().into_owned(), } - .into(), + .serialize_to_text(), ); } - items.push(ResponseItem::from(EnvironmentContext::from_turn_context( - turn_context, - shell.as_ref(), - ))); + let subagents = self + .services + .agent_control + .format_environment_context_subagents(self.conversation_id) + .await; + contextual_user_sections.push( + EnvironmentContext::from_turn_context(turn_context, shell.as_ref()) + .with_subagents(subagents) + .serialize_to_xml(), + ); + + let mut items = Vec::with_capacity(2); + if let Some(developer_message) = + crate::context_manager::updates::build_developer_update_item(developer_sections) + { + items.push(developer_message); + } + if let Some(contextual_user_message) = + crate::context_manager::updates::build_contextual_user_message(contextual_user_sections) + { + items.push(contextual_user_message); + } items } @@ -3124,7 +3173,8 @@ impl Session { state.reference_context_item() } - /// Persist the latest turn context snapshot and emit any required model-visible context updates. + /// Persist the latest turn context snapshot for the first real user turn and for + /// steady-state turns that emit model-visible context updates. /// /// When the reference snapshot is missing, this injects full initial context. Otherwise, it /// emits only settings diff items. @@ -3132,48 +3182,40 @@ impl Session { /// If full context is injected and a model switch occurred, this prepends the /// `` developer message so model-specific instructions are not lost. /// - /// Invariant: this is the only runtime path that writes a non-`None` - /// `reference_context_item`. Non-regular tasks intentionally do not update that - /// baseline; `reference_context_item` tracks the latest regular model turn. + /// This is the normal runtime path that establishes a new `reference_context_item`. + /// Mid-turn compaction is the other path that can re-establish that baseline when it + /// reinjects full initial context into replacement history. Other non-regular tasks + /// intentionally do not update the baseline. pub(crate) async fn record_context_updates_and_set_reference_context_item( &self, turn_context: &TurnContext, - previous_user_turn_model: Option<&str>, ) { - let reference_context_item = self.reference_context_item().await; + let reference_context_item = { + let state = self.state.lock().await; + state.reference_context_item() + }; let should_inject_full_context = reference_context_item.is_none(); let context_items = if should_inject_full_context { - let mut initial_context = self.build_initial_context(turn_context).await; - // Full reinjection bypasses the settings-diff path, so add the model-switch - // instruction explicitly when needed. Keep it before the rest of full context so - // model-specific guidance is read first. - if let Some(model_switch_item) = - crate::context_manager::updates::build_model_instructions_update_item( - previous_user_turn_model, - turn_context, - ) - { - // TODO(ccunningham): When a model switch changes the effective personality - // instructions, inject the updated personality spec alongside - // here so resume/model-switch paths can avoid forcing full reinjection. - initial_context.insert(0, model_switch_item); - } - initial_context + self.build_initial_context(turn_context).await } else { // Steady-state path: append only context diffs to minimize token overhead. - self.build_settings_update_items( - reference_context_item.as_ref(), - previous_user_turn_model, - turn_context, - ) + self.build_settings_update_items(reference_context_item.as_ref(), turn_context) + .await }; + let turn_context_item = turn_context.to_turn_context_item(); if !context_items.is_empty() { self.record_conversation_items(turn_context, &context_items) .await; } + // Persist one `TurnContextItem` per real user turn so resume/lazy replay can recover the + // latest durable baseline even when this turn emitted no model-visible context diffs. + self.persist_rollout_items(&[RolloutItem::TurnContext(turn_context_item.clone())]) + .await; + // Advance the in-memory diff baseline even when this turn emitted no model-visible + // context items. This keeps later runtime diffing aligned with the current turn state. let mut state = self.state.lock().await; - state.set_reference_context_item(Some(turn_context.to_turn_context_item())); + state.set_reference_context_item(Some(turn_context_item)); } pub(crate) async fn update_token_usage_info( @@ -3548,9 +3590,9 @@ impl Session { use_linux_sandbox_bwrap: turn_context.features.enabled(Feature::UseLinuxSandboxBwrap), }; { - let mut cancel_guard = self.services.mcp_startup_cancellation_token.lock().await; - cancel_guard.cancel(); - *cancel_guard = CancellationToken::new(); + let mut guard = self.services.mcp_startup_cancellation_token.lock().await; + guard.cancel(); + *guard = CancellationToken::new(); } let (refreshed_manager, cancel_token) = McpConnectionManager::new( &mcp_servers, @@ -3564,11 +3606,11 @@ impl Session { ) .await; { - let mut cancel_guard = self.services.mcp_startup_cancellation_token.lock().await; - if cancel_guard.is_cancelled() { + let mut guard = self.services.mcp_startup_cancellation_token.lock().await; + if guard.is_cancelled() { cancel_token.cancel(); } - *cancel_guard = cancel_token; + *guard = cancel_token; } let mut manager = self.services.mcp_connection_manager.write().await; @@ -3682,6 +3724,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv model, effort, summary, + service_tier, collaboration_mode, personality, } => { @@ -3705,6 +3748,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv windows_sandbox_level, collaboration_mode: Some(collaboration_mode), reasoning_summary: summary, + service_tier, personality, ..Default::default() }, @@ -3730,9 +3774,6 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv Op::DynamicToolResponse { id, response } => { handlers::dynamic_tool_response(&sess, id, response).await; } - Op::SkillApproval { id, response } => { - handlers::skill_approval_response(&sess, id, response).await; - } Op::AddToHistory { text } => { handlers::add_to_history(&sess, &config, text).await; } @@ -3826,7 +3867,6 @@ mod handlers { use crate::mcp::auth::compute_auth_statuses; use crate::mcp::collect_mcp_snapshot_from_manager; - use crate::mcp::effective_mcp_servers; use crate::review_prompts::resolve_review_request; use crate::rollout::session_index; use crate::tasks::CompactTask; @@ -3856,7 +3896,6 @@ mod handlers { use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::WarningEvent; use codex_protocol::request_user_input::RequestUserInputResponse; - use codex_protocol::skill_approval::SkillApprovalResponse; use crate::config::ConstraintError; use crate::config_loader::RequirementSource; @@ -3933,6 +3972,7 @@ mod handlers { model, effort, summary, + service_tier, final_output_json_schema, items, collaboration_mode, @@ -3956,9 +3996,11 @@ mod handlers { sandbox_policy: Some(sandbox_policy), windows_sandbox_level: None, collaboration_mode, - reasoning_summary: Some(summary), + reasoning_summary: summary, + service_tier, final_output_json_schema: Some(final_output_json_schema), personality, + app_server_client_name: None, }, ) } @@ -4124,14 +4166,6 @@ mod handlers { sess.notify_dynamic_tool_response(&id, response).await; } - pub async fn skill_approval_response( - sess: &Arc, - id: String, - response: SkillApprovalResponse, - ) { - sess.notify_skill_approval_response(&id, response).await; - } - pub async fn add_to_history(sess: &Arc, config: &Arc, text: String) { let id = sess.conversation_id; let config = Arc::clone(config); @@ -4191,7 +4225,10 @@ mod handlers { pub async fn list_mcp_tools(sess: &Session, config: &Arc, sub_id: String) { let mcp_connection_manager = sess.services.mcp_connection_manager.read().await; let auth = sess.services.auth_manager.auth().await; - let mcp_servers = effective_mcp_servers(config, auth.as_ref()); + let mcp_servers = sess + .services + .mcp_manager + .effective_servers(config, auth.as_ref()); let snapshot = collect_mcp_snapshot_from_manager( &mcp_connection_manager, compute_auth_statuses(mcp_servers.iter(), config.mcp_oauth_credentials_store_mode) @@ -4460,8 +4497,8 @@ mod handlers { // TODO(ccunningham): Fix rollback/backtracking baseline handling. // We clear `reference_context_item` here, but should restore the // post-rollback baseline from the surviving history/rollout instead. - // Truncating history should also invalidate/recompute `previous_model` - // so the next regular turn replays any dropped model-switch + // Truncating history should also invalidate/recompute `previous_turn_settings` + // so the next regular turn replays any dropped model/realtime // instructions. history.drop_last_n_user_turns(num_turns); @@ -4686,7 +4723,9 @@ async fn spawn_review_thread( let provider_for_context = provider.clone(); let otel_manager_for_context = otel_manager.clone(); let reasoning_effort = per_turn_config.model_reasoning_effort; - let reasoning_summary = per_turn_config.model_reasoning_summary; + let reasoning_summary = per_turn_config + .model_reasoning_summary + .unwrap_or(model_info.default_reasoning_summary); let session_source = parent_turn_context.session_source.clone(); let per_turn_config = Arc::new(per_turn_config); @@ -4703,6 +4742,7 @@ async fn spawn_review_thread( let review_turn_context = TurnContext { sub_id: review_turn_id, + realtime_active: parent_turn_context.realtime_active, config: per_turn_config, auth_manager: auth_manager_for_context, model_info: model_info.clone(), @@ -4714,6 +4754,9 @@ async fn spawn_review_thread( tools_config, features: parent_turn_context.features.clone(), ghost_snapshot: parent_turn_context.ghost_snapshot.clone(), + current_date: parent_turn_context.current_date.clone(), + timezone: parent_turn_context.timezone.clone(), + app_server_client_name: parent_turn_context.app_server_client_name.clone(), developer_instructions: None, user_instructions: None, compact_prompt: parent_turn_context.compact_prompt.clone(), @@ -4859,12 +4902,8 @@ pub(crate) async fn run_turn( let skills_outcome = Some(turn_context.turn_skills.outcome.as_ref()); - let previous_model = sess.previous_model().await; - sess.record_context_updates_and_set_reference_context_item( - turn_context.as_ref(), - previous_model.as_deref(), - ) - .await; + sess.record_context_updates_and_set_reference_context_item(turn_context.as_ref()) + .await; let available_connectors = if turn_context.config.features.enabled(Feature::Apps) { let mcp_tools = match sess @@ -4970,11 +5009,14 @@ pub(crate) async fn run_turn( let response_item: ResponseItem = initial_input_for_turn.clone().into(); sess.record_user_prompt_and_emit_turn_item(turn_context.as_ref(), &input, response_item) .await; - // Track the previous-model baseline from the regular user-turn path only so + // Track the previous-turn baseline from the regular user-turn path only so // standalone tasks (compact/shell/review/undo) cannot suppress future - // `` injections. - sess.set_previous_model(Some(turn_context.model_info.slug.clone())) - .await; + // model/realtime injections. + sess.set_previous_turn_settings(Some(PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(turn_context.realtime_active), + })) + .await; if !skill_items.is_empty() { sess.record_conversation_items(&turn_context, &skill_items) @@ -5098,6 +5140,7 @@ pub(crate) async fn run_turn( .dispatch(HookPayload { session_id: sess.conversation_id, cwd: turn_context.cwd.clone(), + client: turn_context.app_server_client_name.clone(), triggered_at: chrono::Utc::now(), hook_event: HookEvent::AfterAgent { event: HookEventAfterAgent { @@ -5221,12 +5264,12 @@ async fn maybe_run_previous_model_inline_compact( turn_context: &Arc, total_usage_tokens: i64, ) -> CodexResult { - let Some(previous_model) = sess.previous_model().await else { + let Some(previous_turn_settings) = sess.previous_turn_settings().await else { return Ok(false); }; let previous_model_turn_context = Arc::new( turn_context - .with_model(previous_model, &sess.services.models_manager) + .with_model(previous_turn_settings.model, &sess.services.models_manager) .await, ); @@ -5556,12 +5599,10 @@ async fn run_sampling_request( // transient reconnect messages. In debug builds, keep full visibility for diagnosis. let report_error = retries > 1 || cfg!(debug_assertions) - || sess + || !sess .services .model_client - .active_ws_version(&turn_context.model_info) - .is_none(); - + .responses_websocket_enabled(&turn_context.model_info); if report_error { // Surface retry information to any UI/front‑end so the // user understands what is happening instead of staring @@ -5836,46 +5877,79 @@ fn realtime_text_for_event(msg: &EventMsg) -> Option { TurnItem::AgentMessage(item) => Some(agent_message_text(item)), _ => None, }, - EventMsg::ExecCommandBegin(event) => { - let command = event.command.join(" "); - Some(format!( - "Exec command started: {command}\nWorking directory: {}", - event.cwd.display() - )) - } - EventMsg::PatchApplyBegin(event) => { - let mut files: Vec = event - .changes - .keys() - .map(|path| path.display().to_string()) - .collect(); - files.sort(); - let file_list = if files.is_empty() { - "none".to_string() - } else { - files.join(", ") - }; - Some(format!( - "apply_patch started ({count} file change(s))\nFiles: {file_list}", - count = files.len() - )) - } - EventMsg::PatchApplyEnd(event) => { - let status = match event.status { - PatchApplyStatus::Completed => "completed", - PatchApplyStatus::Failed => "failed", - PatchApplyStatus::Declined => "declined", - }; - let mut text = format!("apply_patch {status}"); - if !event.stdout.is_empty() { - text.push_str(&format!("\nstdout:\n{}", event.stdout)); - } - if !event.stderr.is_empty() { - text.push_str(&format!("\nstderr:\n{}", event.stderr)); - } - Some(text) - } - _ => None, + EventMsg::Error(_) + | EventMsg::Warning(_) + | EventMsg::RealtimeConversationStarted(_) + | EventMsg::RealtimeConversationRealtime(_) + | EventMsg::RealtimeConversationClosed(_) + | EventMsg::ModelReroute(_) + | EventMsg::ContextCompacted(_) + | EventMsg::ThreadRolledBack(_) + | EventMsg::TurnStarted(_) + | EventMsg::TurnComplete(_) + | EventMsg::TokenCount(_) + | EventMsg::UserMessage(_) + | EventMsg::AgentMessageDelta(_) + | EventMsg::AgentReasoning(_) + | EventMsg::AgentReasoningDelta(_) + | EventMsg::AgentReasoningRawContent(_) + | EventMsg::AgentReasoningRawContentDelta(_) + | EventMsg::AgentReasoningSectionBreak(_) + | EventMsg::SessionConfigured(_) + | EventMsg::ThreadNameUpdated(_) + | EventMsg::McpStartupUpdate(_) + | EventMsg::McpStartupComplete(_) + | EventMsg::McpToolCallBegin(_) + | EventMsg::McpToolCallEnd(_) + | EventMsg::WebSearchBegin(_) + | EventMsg::WebSearchEnd(_) + | EventMsg::ExecCommandBegin(_) + | EventMsg::ExecCommandOutputDelta(_) + | EventMsg::TerminalInteraction(_) + | EventMsg::ExecCommandEnd(_) + | EventMsg::PatchApplyBegin(_) + | EventMsg::PatchApplyEnd(_) + | EventMsg::ViewImageToolCall(_) + | EventMsg::ExecApprovalRequest(_) + | EventMsg::RequestUserInput(_) + | EventMsg::DynamicToolCallRequest(_) + | EventMsg::DynamicToolCallResponse(_) + | EventMsg::ElicitationRequest(_) + | EventMsg::ApplyPatchApprovalRequest(_) + | EventMsg::DeprecationNotice(_) + | EventMsg::BackgroundEvent(_) + | EventMsg::UndoStarted(_) + | EventMsg::UndoCompleted(_) + | EventMsg::StreamError(_) + | EventMsg::TurnDiff(_) + | EventMsg::GetHistoryEntryResponse(_) + | EventMsg::McpListToolsResponse(_) + | EventMsg::ListCustomPromptsResponse(_) + | EventMsg::ListSkillsResponse(_) + | EventMsg::ListRemoteSkillsResponse(_) + | EventMsg::RemoteSkillDownloaded(_) + | EventMsg::SkillsUpdateAvailable + | EventMsg::PlanUpdate(_) + | EventMsg::TurnAborted(_) + | EventMsg::ShutdownComplete + | EventMsg::EnteredReviewMode(_) + | EventMsg::ExitedReviewMode(_) + | EventMsg::RawResponseItem(_) + | EventMsg::ItemStarted(_) + | EventMsg::AgentMessageContentDelta(_) + | EventMsg::PlanDelta(_) + | EventMsg::ReasoningContentDelta(_) + | EventMsg::ReasoningRawContentDelta(_) + | EventMsg::CollabAgentSpawnBegin(_) + | EventMsg::CollabAgentSpawnEnd(_) + | EventMsg::CollabAgentInteractionBegin(_) + | EventMsg::CollabAgentInteractionEnd(_) + | EventMsg::CollabWaitingBegin(_) + | EventMsg::CollabWaitingEnd(_) + | EventMsg::CollabCloseBegin(_) + | EventMsg::CollabCloseEnd(_) + | EventMsg::CollabResumeBegin(_) + | EventMsg::CollabResumeEnd(_) => None, } } @@ -6174,11 +6248,6 @@ async fn try_run_sampling_request( prompt: &Prompt, cancellation_token: CancellationToken, ) -> CodexResult { - // Persist one TurnContext marker per sampling request (not just per user turn) so rollout - // analysis can reconstruct API-turn boundaries. `run_turn` persists model-visible context - // diffs/full reinjection earlier in the same regular turn before reaching this path. - let rollout_item = RolloutItem::TurnContext(turn_context.to_turn_context_item()); - feedback_tags!( model = turn_context.model_info.slug.clone(), approval_policy = turn_context.approval_policy.value(), @@ -6187,8 +6256,6 @@ async fn try_run_sampling_request( auth_mode = sess.services.auth_manager.auth_mode(), features = sess.features.enabled_features(), ); - - sess.persist_rollout_items(&[rollout_item]).await; let mut stream = client_session .stream( prompt, @@ -6196,6 +6263,7 @@ async fn try_run_sampling_request( &turn_context.otel_manager, turn_context.reasoning_effort, turn_context.reasoning_summary, + turn_context.config.service_tier, turn_metadata_header, ) .instrument(trace_span!("stream_request")) @@ -6375,7 +6443,6 @@ async fn try_run_sampling_request( ResponseEvent::Completed { response_id: _, token_usage, - can_append: _, } => { flush_assistant_text_segments_all( &sess, @@ -6550,6 +6617,10 @@ mod tests { use crate::protocol::TokenCountEvent; use crate::protocol::TokenUsage; use crate::protocol::TokenUsageInfo; + use crate::protocol::UserMessageEvent; + use crate::rollout::policy::EventPersistenceMode; + use crate::rollout::recorder::RolloutRecorder; + use crate::rollout::recorder::RolloutRecorderParams; use crate::state::TaskKind; use crate::tasks::SessionTask; use crate::tasks::SessionTaskContext; @@ -6612,6 +6683,23 @@ mod tests { } } + fn developer_input_texts(items: &[ResponseItem]) -> Vec<&str> { + items + .iter() + .filter_map(|item| match item { + ResponseItem::Message { role, content, .. } if role == "developer" => { + Some(content.as_slice()) + } + _ => None, + }) + .flat_map(|content| content.iter()) + .filter_map(|item| match item { + ContentItem::InputText { text } => Some(text.as_str()), + _ => None, + }) + .collect() + } + fn make_connector(id: &str, name: &str) -> AppInfo { AppInfo { id: id.to_string(), @@ -7190,7 +7278,7 @@ mod tests { .reconstruct_history_from_rollout(reconstruction_turn.as_ref(), &rollout_items) .await; - assert_eq!(expected, reconstructed); + assert_eq!(expected, reconstructed.history); } #[tokio::test] @@ -7226,7 +7314,7 @@ mod tests { .reconstruct_history_from_rollout(&turn_context, &rollout_items) .await; - assert_eq!(reconstructed, replacement_history); + assert_eq!(reconstructed.history, replacement_history); } #[tokio::test] @@ -7246,217 +7334,6 @@ mod tests { assert_eq!(expected, history.raw_items()); } - #[tokio::test] - async fn record_initial_history_resumed_hydrates_previous_model() { - let (session, turn_context) = make_session_and_context().await; - let previous_model = "previous-rollout-model"; - let previous_context_item = TurnContextItem { - turn_id: Some(turn_context.sub_id.clone()), - cwd: turn_context.cwd.clone(), - approval_policy: turn_context.approval_policy.value(), - sandbox_policy: turn_context.sandbox_policy.get().clone(), - network: None, - model: previous_model.to_string(), - personality: turn_context.personality, - collaboration_mode: Some(turn_context.collaboration_mode.clone()), - effort: turn_context.reasoning_effort, - summary: turn_context.reasoning_summary, - user_instructions: None, - developer_instructions: None, - final_output_json_schema: None, - truncation_policy: Some(turn_context.truncation_policy.into()), - }; - let rollout_items = vec![RolloutItem::TurnContext(previous_context_item)]; - - session - .record_initial_history(InitialHistory::Resumed(ResumedHistory { - conversation_id: ThreadId::default(), - history: rollout_items, - rollout_path: PathBuf::from("/tmp/resume.jsonl"), - })) - .await; - - assert_eq!( - session.previous_model().await, - Some(previous_model.to_string()) - ); - } - - #[tokio::test] - async fn record_initial_history_resumed_hydrates_previous_model_from_lifecycle_turn_with_missing_turn_context_id() - { - let (session, turn_context) = make_session_and_context().await; - let previous_model = "previous-rollout-model"; - let mut previous_context_item = TurnContextItem { - turn_id: Some(turn_context.sub_id.clone()), - cwd: turn_context.cwd.clone(), - approval_policy: turn_context.approval_policy.value(), - sandbox_policy: turn_context.sandbox_policy.get().clone(), - network: None, - model: previous_model.to_string(), - personality: turn_context.personality, - collaboration_mode: Some(turn_context.collaboration_mode.clone()), - effort: turn_context.reasoning_effort, - summary: turn_context.reasoning_summary, - user_instructions: None, - developer_instructions: None, - final_output_json_schema: None, - truncation_policy: Some(turn_context.truncation_policy.into()), - }; - let turn_id = previous_context_item - .turn_id - .clone() - .expect("turn context should have turn_id"); - previous_context_item.turn_id = None; - - let rollout_items = vec![ - RolloutItem::EventMsg(EventMsg::TurnStarted( - codex_protocol::protocol::TurnStartedEvent { - turn_id: turn_id.clone(), - model_context_window: Some(128_000), - collaboration_mode_kind: ModeKind::Default, - }, - )), - RolloutItem::EventMsg(EventMsg::UserMessage( - codex_protocol::protocol::UserMessageEvent { - message: "seed".to_string(), - images: None, - local_images: Vec::new(), - text_elements: Vec::new(), - }, - )), - RolloutItem::TurnContext(previous_context_item), - RolloutItem::EventMsg(EventMsg::TurnComplete( - codex_protocol::protocol::TurnCompleteEvent { - turn_id, - last_agent_message: None, - }, - )), - ]; - - session - .record_initial_history(InitialHistory::Resumed(ResumedHistory { - conversation_id: ThreadId::default(), - history: rollout_items, - rollout_path: PathBuf::from("/tmp/resume.jsonl"), - })) - .await; - - assert_eq!( - session.previous_model().await, - Some(previous_model.to_string()) - ); - } - - #[tokio::test] - async fn record_initial_history_resumed_rollback_skips_only_user_turns() { - let (session, turn_context) = make_session_and_context().await; - let previous_context_item = turn_context.to_turn_context_item(); - let user_turn_id = previous_context_item - .turn_id - .clone() - .expect("turn context should have turn_id"); - let standalone_turn_id = "standalone-task-turn".to_string(); - let rollout_items = vec![ - RolloutItem::EventMsg(EventMsg::TurnStarted( - codex_protocol::protocol::TurnStartedEvent { - turn_id: user_turn_id.clone(), - model_context_window: Some(128_000), - collaboration_mode_kind: ModeKind::Default, - }, - )), - RolloutItem::EventMsg(EventMsg::UserMessage( - codex_protocol::protocol::UserMessageEvent { - message: "seed".to_string(), - images: None, - local_images: Vec::new(), - text_elements: Vec::new(), - }, - )), - RolloutItem::TurnContext(previous_context_item), - RolloutItem::EventMsg(EventMsg::TurnComplete( - codex_protocol::protocol::TurnCompleteEvent { - turn_id: user_turn_id, - last_agent_message: None, - }, - )), - // Standalone task turn (no UserMessage) should not consume rollback skips. - RolloutItem::EventMsg(EventMsg::TurnStarted( - codex_protocol::protocol::TurnStartedEvent { - turn_id: standalone_turn_id.clone(), - model_context_window: Some(128_000), - collaboration_mode_kind: ModeKind::Default, - }, - )), - RolloutItem::EventMsg(EventMsg::TurnComplete( - codex_protocol::protocol::TurnCompleteEvent { - turn_id: standalone_turn_id, - last_agent_message: None, - }, - )), - RolloutItem::EventMsg(EventMsg::ThreadRolledBack( - codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, - )), - ]; - - session - .record_initial_history(InitialHistory::Resumed(ResumedHistory { - conversation_id: ThreadId::default(), - history: rollout_items, - rollout_path: PathBuf::from("/tmp/resume.jsonl"), - })) - .await; - - assert_eq!(session.previous_model().await, None); - assert!(session.reference_context_item().await.is_none()); - } - - #[tokio::test] - async fn record_initial_history_resumed_seeds_reference_context_item_without_compaction() { - let (session, turn_context) = make_session_and_context().await; - let previous_context_item = turn_context.to_turn_context_item(); - let rollout_items = vec![RolloutItem::TurnContext(previous_context_item.clone())]; - - session - .record_initial_history(InitialHistory::Resumed(ResumedHistory { - conversation_id: ThreadId::default(), - history: rollout_items, - rollout_path: PathBuf::from("/tmp/resume.jsonl"), - })) - .await; - - assert_eq!( - serde_json::to_value(session.reference_context_item().await) - .expect("serialize seeded reference context item"), - serde_json::to_value(Some(previous_context_item)) - .expect("serialize expected reference context item") - ); - } - - #[tokio::test] - async fn record_initial_history_resumed_does_not_seed_reference_context_item_after_compaction() - { - let (session, turn_context) = make_session_and_context().await; - let previous_context_item = turn_context.to_turn_context_item(); - let rollout_items = vec![ - RolloutItem::TurnContext(previous_context_item), - RolloutItem::Compacted(CompactedItem { - message: String::new(), - replacement_history: Some(Vec::new()), - }), - ]; - - session - .record_initial_history(InitialHistory::Resumed(ResumedHistory { - conversation_id: ThreadId::default(), - history: rollout_items, - rollout_path: PathBuf::from("/tmp/resume.jsonl"), - })) - .await; - - assert!(session.reference_context_item().await.is_none()); - } - #[tokio::test] async fn resumed_history_injects_initial_context_on_first_context_update_only() { let (session, turn_context) = make_session_and_context().await; @@ -7474,17 +7351,20 @@ mod tests { assert_eq!(expected, history_before_seed.raw_items()); session - .record_context_updates_and_set_reference_context_item(&turn_context, None) + .record_context_updates_and_set_reference_context_item(&turn_context) .await; expected.extend(session.build_initial_context(&turn_context).await); let history_after_seed = session.clone_history().await; assert_eq!(expected, history_after_seed.raw_items()); session - .record_context_updates_and_set_reference_context_item(&turn_context, None) + .record_context_updates_and_set_reference_context_item(&turn_context) .await; let history_after_second_seed = session.clone_history().await; - assert_eq!(expected, history_after_second_seed.raw_items()); + assert_eq!( + history_after_seed.raw_items(), + history_after_second_seed.raw_items() + ); } #[tokio::test] @@ -7646,18 +7526,21 @@ mod tests { } #[tokio::test] - async fn record_initial_history_forked_hydrates_previous_model() { + async fn record_initial_history_forked_hydrates_previous_turn_settings() { let (session, turn_context) = make_session_and_context().await; let previous_model = "forked-rollout-model"; let previous_context_item = TurnContextItem { turn_id: Some(turn_context.sub_id.clone()), cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), sandbox_policy: turn_context.sandbox_policy.get().clone(), network: None, model: previous_model.to_string(), personality: turn_context.personality, collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), effort: turn_context.reasoning_effort, summary: turn_context.reasoning_summary, user_instructions: None, @@ -7665,15 +7548,45 @@ mod tests { final_output_json_schema: None, truncation_policy: Some(turn_context.truncation_policy.into()), }; - let rollout_items = vec![RolloutItem::TurnContext(previous_context_item)]; + let turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "forked seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id, + last_agent_message: None, + }, + )), + ]; session .record_initial_history(InitialHistory::Forked(rollout_items)) .await; assert_eq!( - session.previous_model().await, - Some(previous_model.to_string()) + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: previous_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) ); } @@ -7728,8 +7641,11 @@ mod tests { }, ]; sess.record_into_history(&turn_2, tc.as_ref()).await; - sess.set_previous_model(Some("previous-regular-model".to_string())) - .await; + sess.set_previous_turn_settings(Some(PreviousTurnSettings { + model: "previous-regular-model".to_string(), + realtime_active: Some(tc.realtime_active), + })) + .await; handlers::thread_rollback(&sess, "sub-1".to_string(), 1).await; @@ -7743,8 +7659,11 @@ mod tests { let history = sess.clone_history().await; assert_eq!(expected, history.raw_items()); assert_eq!( - sess.previous_model().await, - Some("previous-regular-model".to_string()) + sess.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: "previous-regular-model".to_string(), + realtime_active: Some(tc.realtime_active), + }) ); } @@ -7841,6 +7760,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), + service_tier: None, personality: config.personality, base_instructions: config .base_instructions @@ -7855,9 +7775,11 @@ mod tests { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name: None, + app_server_client_name: None, session_source: SessionSource::Exec, dynamic_tools: Vec::new(), persist_extended_history: false, + inherited_shell_snapshot: None, }; let mut state = SessionState::new(session_configuration); @@ -7988,6 +7910,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), + service_tier: None, personality: config.personality, base_instructions: config .base_instructions @@ -8002,9 +7925,11 @@ mod tests { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name: None, + app_server_client_name: None, session_source: SessionSource::Exec, dynamic_tools: Vec::new(), persist_extended_history: false, + inherited_shell_snapshot: None, }; let mut state = SessionState::new(session_configuration); @@ -8299,6 +8224,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), + service_tier: None, personality: config.personality, base_instructions: config .base_instructions @@ -8313,9 +8239,11 @@ mod tests { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name: None, + app_server_client_name: None, session_source: SessionSource::Exec, dynamic_tools: Vec::new(), persist_extended_history: false, + inherited_shell_snapshot: None, } } @@ -8333,6 +8261,7 @@ mod tests { config.codex_home.clone(), auth_manager.clone(), None, + CollaborationModesConfig::default(), )); let model = ModelsManager::get_model_offline_for_tests(config.model.as_deref()); let model_info = @@ -8351,6 +8280,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), + service_tier: None, personality: config.personality, base_instructions: config .base_instructions @@ -8365,13 +8295,21 @@ mod tests { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name: None, + app_server_client_name: None, session_source: SessionSource::Exec, dynamic_tools: Vec::new(), persist_extended_history: false, + inherited_shell_snapshot: None, }; let (tx_event, _rx_event) = async_channel::unbounded(); let (agent_status_tx, _agent_status_rx) = watch::channel(AgentStatus::PendingInit); + let plugins_manager = Arc::new(PluginsManager::new(config.codex_home.clone())); + let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager))); + let skills_manager = Arc::new(SkillsManager::new( + config.codex_home.clone(), + Arc::clone(&plugins_manager), + )); let result = Session::new( session_configuration, Arc::clone(&config), @@ -8382,7 +8320,9 @@ mod tests { agent_status_tx, InitialHistory::New, SessionSource::Exec, - Arc::new(SkillsManager::new(config.codex_home.clone())), + skills_manager, + plugins_manager, + mcp_manager, Arc::new(FileWatcher::noop()), AgentControl::default(), ) @@ -8409,6 +8349,7 @@ mod tests { config.codex_home.clone(), auth_manager.clone(), None, + CollaborationModesConfig::default(), )); let agent_control = AgentControl::default(); let exec_policy = ExecPolicyManager::default(); @@ -8431,6 +8372,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), + service_tier: None, personality: config.personality, base_instructions: config .base_instructions @@ -8445,9 +8387,11 @@ mod tests { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name: None, + app_server_client_name: None, session_source: SessionSource::Exec, dynamic_tools: Vec::new(), persist_extended_history: false, + inherited_shell_snapshot: None, }; let per_turn_config = Session::build_per_turn_config(&session_configuration); let model_info = ModelsManager::construct_model_info_offline_for_tests( @@ -8462,7 +8406,12 @@ mod tests { ); let state = SessionState::new(session_configuration.clone()); - let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone())); + let plugins_manager = Arc::new(PluginsManager::new(config.codex_home.clone())); + let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager))); + let skills_manager = Arc::new(SkillsManager::new( + config.codex_home.clone(), + Arc::clone(&plugins_manager), + )); let network_approval = Arc::new(NetworkApprovalService::default()); let file_watcher = Arc::new(FileWatcher::noop()); @@ -8494,8 +8443,10 @@ mod tests { otel_manager: otel_manager.clone(), models_manager: Arc::clone(&models_manager), tool_approvals: Mutex::new(ApprovalStore::default()), - execve_session_approvals: RwLock::new(HashSet::new()), + execve_session_approvals: RwLock::new(HashMap::new()), skills_manager, + plugins_manager, + mcp_manager, file_watcher, agent_control, network_proxy: None, @@ -8567,6 +8518,7 @@ mod tests { config.codex_home.clone(), auth_manager.clone(), None, + CollaborationModesConfig::default(), )); let agent_control = AgentControl::default(); let exec_policy = ExecPolicyManager::default(); @@ -8589,6 +8541,7 @@ mod tests { model_reasoning_summary: config.model_reasoning_summary, developer_instructions: config.developer_instructions.clone(), user_instructions: config.user_instructions.clone(), + service_tier: None, personality: config.personality, base_instructions: config .base_instructions @@ -8603,9 +8556,11 @@ mod tests { thread_name: None, original_config_do_not_use: Arc::clone(&config), metrics_service_name: None, + app_server_client_name: None, session_source: SessionSource::Exec, dynamic_tools, persist_extended_history: false, + inherited_shell_snapshot: None, }; let per_turn_config = Session::build_per_turn_config(&session_configuration); let model_info = ModelsManager::construct_model_info_offline_for_tests( @@ -8620,7 +8575,12 @@ mod tests { ); let state = SessionState::new(session_configuration.clone()); - let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone())); + let plugins_manager = Arc::new(PluginsManager::new(config.codex_home.clone())); + let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager))); + let skills_manager = Arc::new(SkillsManager::new( + config.codex_home.clone(), + Arc::clone(&plugins_manager), + )); let network_approval = Arc::new(NetworkApprovalService::default()); let file_watcher = Arc::new(FileWatcher::noop()); @@ -8652,8 +8612,10 @@ mod tests { otel_manager: otel_manager.clone(), models_manager: Arc::clone(&models_manager), tool_approvals: Mutex::new(ApprovalStore::default()), - execve_session_approvals: RwLock::new(HashSet::new()), + execve_session_approvals: RwLock::new(HashMap::new()), skills_manager, + plugins_manager, + mcp_manager, file_watcher, agent_control, network_proxy: None, @@ -8788,9 +8750,9 @@ mod tests { } #[tokio::test] - async fn spawn_task_does_not_update_previous_model_for_non_run_turn_tasks() { + async fn spawn_task_does_not_update_previous_turn_settings_for_non_run_turn_tasks() { let (sess, tc, _rx) = make_session_and_context_with_rx().await; - sess.set_previous_model(None).await; + sess.set_previous_turn_settings(None).await; let input = vec![UserInput::Text { text: "hello".to_string(), text_elements: Vec::new(), @@ -8807,7 +8769,7 @@ mod tests { .await; sess.abort_all_tasks(TurnAbortReason::Interrupted).await; - assert_eq!(sess.previous_model().await, None); + assert_eq!(sess.previous_turn_settings().await, None); } #[tokio::test] @@ -8846,11 +8808,9 @@ mod tests { current_context.config = Arc::new(config); let reference_context_item = previous_context.to_turn_context_item(); - let update_items = session.build_settings_update_items( - Some(&reference_context_item), - None, - ¤t_context, - ); + let update_items = session + .build_settings_update_items(Some(&reference_context_item), ¤t_context) + .await; let environment_update = update_items .iter() @@ -8869,12 +8829,207 @@ mod tests { assert!(environment_update.contains("blocked.example.com")); } + #[tokio::test] + async fn build_settings_update_items_emits_environment_item_for_time_changes() { + let (session, previous_context) = make_session_and_context().await; + let previous_context = Arc::new(previous_context); + let mut current_context = previous_context + .with_model( + previous_context.model_info.slug.clone(), + &session.services.models_manager, + ) + .await; + current_context.current_date = Some("2026-02-27".to_string()); + current_context.timezone = Some("Europe/Berlin".to_string()); + + let reference_context_item = previous_context.to_turn_context_item(); + let update_items = session + .build_settings_update_items(Some(&reference_context_item), ¤t_context) + .await; + + let environment_update = update_items + .iter() + .find_map(|item| match item { + ResponseItem::Message { role, content, .. } if role == "user" => { + let [ContentItem::InputText { text }] = content.as_slice() else { + return None; + }; + text.contains("").then_some(text) + } + _ => None, + }) + .expect("environment update item should be emitted"); + assert!(environment_update.contains("2026-02-27")); + assert!(environment_update.contains("Europe/Berlin")); + } + + #[tokio::test] + async fn build_settings_update_items_emits_realtime_start_when_session_becomes_live() { + let (session, previous_context) = make_session_and_context().await; + let previous_context = Arc::new(previous_context); + let mut current_context = previous_context + .with_model( + previous_context.model_info.slug.clone(), + &session.services.models_manager, + ) + .await; + current_context.realtime_active = true; + + let update_items = session + .build_settings_update_items( + Some(&previous_context.to_turn_context_item()), + ¤t_context, + ) + .await; + + let developer_texts = developer_input_texts(&update_items); + assert!( + developer_texts + .iter() + .any(|text| text.contains("")), + "expected a realtime start update, got {developer_texts:?}" + ); + } + + #[tokio::test] + async fn build_settings_update_items_emits_realtime_end_when_session_stops_being_live() { + let (session, mut previous_context) = make_session_and_context().await; + previous_context.realtime_active = true; + let mut current_context = previous_context + .with_model( + previous_context.model_info.slug.clone(), + &session.services.models_manager, + ) + .await; + current_context.realtime_active = false; + + let update_items = session + .build_settings_update_items( + Some(&previous_context.to_turn_context_item()), + ¤t_context, + ) + .await; + + let developer_texts = developer_input_texts(&update_items); + assert!( + developer_texts + .iter() + .any(|text| text.contains("Reason: inactive")), + "expected a realtime end update, got {developer_texts:?}" + ); + } + + #[tokio::test] + async fn build_settings_update_items_uses_previous_turn_settings_for_realtime_end() { + let (session, previous_context) = make_session_and_context().await; + let mut previous_context_item = previous_context.to_turn_context_item(); + previous_context_item.realtime_active = None; + let previous_turn_settings = PreviousTurnSettings { + model: previous_context.model_info.slug.clone(), + realtime_active: Some(true), + }; + let mut current_context = previous_context + .with_model( + previous_context.model_info.slug.clone(), + &session.services.models_manager, + ) + .await; + current_context.realtime_active = false; + + session + .set_previous_turn_settings(Some(previous_turn_settings)) + .await; + let update_items = session + .build_settings_update_items(Some(&previous_context_item), ¤t_context) + .await; + + let developer_texts = developer_input_texts(&update_items); + assert!( + developer_texts + .iter() + .any(|text| text.contains("Reason: inactive")), + "expected a realtime end update from previous turn settings, got {developer_texts:?}" + ); + } + + #[tokio::test] + async fn build_initial_context_uses_previous_realtime_state() { + let (session, mut turn_context) = make_session_and_context().await; + turn_context.realtime_active = true; + + let initial_context = session.build_initial_context(&turn_context).await; + let developer_texts = developer_input_texts(&initial_context); + assert!( + developer_texts + .iter() + .any(|text| text.contains("")), + "expected initial context to describe active realtime state, got {developer_texts:?}" + ); + + let previous_context_item = turn_context.to_turn_context_item(); + { + let mut state = session.state.lock().await; + state.set_reference_context_item(Some(previous_context_item)); + } + let resumed_context = session.build_initial_context(&turn_context).await; + let resumed_developer_texts = developer_input_texts(&resumed_context); + assert!( + !resumed_developer_texts + .iter() + .any(|text| text.contains("")), + "did not expect a duplicate realtime update, got {resumed_developer_texts:?}" + ); + } + + #[tokio::test] + async fn build_initial_context_uses_previous_turn_settings_for_realtime_end() { + let (session, turn_context) = make_session_and_context().await; + let previous_turn_settings = PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(true), + }; + + session + .set_previous_turn_settings(Some(previous_turn_settings)) + .await; + let initial_context = session.build_initial_context(&turn_context).await; + let developer_texts = developer_input_texts(&initial_context); + assert!( + developer_texts + .iter() + .any(|text| text.contains("Reason: inactive")), + "expected initial context to describe an ended realtime session, got {developer_texts:?}" + ); + } + + #[tokio::test] + async fn build_initial_context_restates_realtime_start_when_reference_context_is_missing() { + let (session, mut turn_context) = make_session_and_context().await; + turn_context.realtime_active = true; + let previous_turn_settings = PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(true), + }; + + session + .set_previous_turn_settings(Some(previous_turn_settings)) + .await; + let initial_context = session.build_initial_context(&turn_context).await; + let developer_texts = developer_input_texts(&initial_context); + assert!( + developer_texts + .iter() + .any(|text| text.contains("")), + "expected initial context to restate active realtime when the reference context is missing, got {developer_texts:?}" + ); + } + #[tokio::test] async fn record_context_updates_and_set_reference_context_item_injects_full_context_when_baseline_missing() { let (session, turn_context) = make_session_and_context().await; session - .record_context_updates_and_set_reference_context_item(&turn_context, None) + .record_context_updates_and_set_reference_context_item(&turn_context) .await; let history = session.clone_history().await; let initial_context = session.build_initial_context(&turn_context).await; @@ -8905,7 +9060,7 @@ mod tests { .record_into_history(std::slice::from_ref(&compacted_summary), &turn_context) .await; session - .record_context_updates_and_set_reference_context_item(&turn_context, None) + .record_context_updates_and_set_reference_context_item(&turn_context) .await; { let mut state = session.state.lock().await; @@ -8916,7 +9071,7 @@ mod tests { .await; session - .record_context_updates_and_set_reference_context_item(&turn_context, None) + .record_context_updates_and_set_reference_context_item(&turn_context) .await; let history = session.clone_history().await; @@ -8925,6 +9080,188 @@ mod tests { assert_eq!(history.raw_items().to_vec(), expected_history); } + #[tokio::test] + async fn record_context_updates_and_set_reference_context_item_persists_baseline_without_emitting_diffs() + { + let (session, previous_context) = make_session_and_context().await; + let next_model = if previous_context.model_info.slug == "gpt-5.1" { + "gpt-5" + } else { + "gpt-5.1" + }; + let turn_context = previous_context + .with_model(next_model.to_string(), &session.services.models_manager) + .await; + let previous_context_item = previous_context.to_turn_context_item(); + { + let mut state = session.state.lock().await; + state.set_reference_context_item(Some(previous_context_item.clone())); + } + let config = session.get_config().await; + let recorder = RolloutRecorder::new( + config.as_ref(), + RolloutRecorderParams::new( + ThreadId::default(), + None, + SessionSource::Exec, + BaseInstructions::default(), + Vec::new(), + EventPersistenceMode::Limited, + ), + None, + None, + ) + .await + .expect("create rollout recorder"); + let rollout_path = recorder.rollout_path().to_path_buf(); + { + let mut rollout = session.services.rollout.lock().await; + *rollout = Some(recorder); + } + + let update_items = session + .build_settings_update_items(Some(&previous_context_item), &turn_context) + .await; + assert_eq!(update_items, Vec::new()); + + session + .record_context_updates_and_set_reference_context_item(&turn_context) + .await; + + assert_eq!( + session.clone_history().await.raw_items().to_vec(), + Vec::new() + ); + assert_eq!( + serde_json::to_value(session.reference_context_item().await) + .expect("serialize current context item"), + serde_json::to_value(Some(turn_context.to_turn_context_item())) + .expect("serialize expected context item") + ); + session.ensure_rollout_materialized().await; + session.flush_rollout().await; + + let InitialHistory::Resumed(resumed) = RolloutRecorder::get_rollout_history(&rollout_path) + .await + .expect("read rollout history") + else { + panic!("expected resumed rollout history"); + }; + let persisted_turn_context = resumed.history.iter().find_map(|item| match item { + RolloutItem::TurnContext(ctx) => Some(ctx.clone()), + _ => None, + }); + assert_eq!( + serde_json::to_value(persisted_turn_context) + .expect("serialize persisted turn context item"), + serde_json::to_value(Some(turn_context.to_turn_context_item())) + .expect("serialize expected turn context item") + ); + } + + #[tokio::test] + async fn build_initial_context_prepends_model_switch_message() { + let (session, turn_context) = make_session_and_context().await; + let previous_turn_settings = PreviousTurnSettings { + model: "previous-regular-model".to_string(), + realtime_active: None, + }; + + session + .set_previous_turn_settings(Some(previous_turn_settings)) + .await; + let initial_context = session.build_initial_context(&turn_context).await; + + let ResponseItem::Message { role, content, .. } = &initial_context[0] else { + panic!("expected developer message"); + }; + assert_eq!(role, "developer"); + let [ContentItem::InputText { text }, ..] = content.as_slice() else { + panic!("expected developer text"); + }; + assert!(text.contains("")); + } + + #[tokio::test] + async fn record_context_updates_and_set_reference_context_item_persists_full_reinjection_to_rollout() + { + let (session, previous_context) = make_session_and_context().await; + let next_model = if previous_context.model_info.slug == "gpt-5.1" { + "gpt-5" + } else { + "gpt-5.1" + }; + let turn_context = previous_context + .with_model(next_model.to_string(), &session.services.models_manager) + .await; + let config = session.get_config().await; + let recorder = RolloutRecorder::new( + config.as_ref(), + RolloutRecorderParams::new( + ThreadId::default(), + None, + SessionSource::Exec, + BaseInstructions::default(), + Vec::new(), + EventPersistenceMode::Limited, + ), + None, + None, + ) + .await + .expect("create rollout recorder"); + let rollout_path = recorder.rollout_path().to_path_buf(); + { + let mut rollout = session.services.rollout.lock().await; + *rollout = Some(recorder); + } + + session + .persist_rollout_items(&[RolloutItem::EventMsg(EventMsg::UserMessage( + UserMessageEvent { + message: "seed rollout".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + ))]) + .await; + { + let mut state = session.state.lock().await; + state.set_reference_context_item(None); + } + + session + .set_previous_turn_settings(Some(PreviousTurnSettings { + model: previous_context.model_info.slug.clone(), + realtime_active: Some(previous_context.realtime_active), + })) + .await; + session + .record_context_updates_and_set_reference_context_item(&turn_context) + .await; + session.ensure_rollout_materialized().await; + session.flush_rollout().await; + + let InitialHistory::Resumed(resumed) = RolloutRecorder::get_rollout_history(&rollout_path) + .await + .expect("read rollout history") + else { + panic!("expected resumed rollout history"); + }; + let persisted_turn_context = resumed.history.iter().find_map(|item| match item { + RolloutItem::TurnContext(ctx) => Some(ctx.clone()), + _ => None, + }); + + assert_eq!( + serde_json::to_value(persisted_turn_context) + .expect("serialize persisted turn context item"), + serde_json::to_value(Some(turn_context.to_turn_context_item())) + .expect("serialize expected turn context item") + ); + } + #[tokio::test] async fn run_user_shell_command_does_not_set_reference_context_item() { let (session, _turn_context, rx) = make_session_and_context_with_rx().await; @@ -8936,7 +9273,7 @@ mod tests { handlers::run_user_shell_command(&session, "sub-id".to_string(), "echo shell".to_string()) .await; - let deadline = StdDuration::from_secs(5); + let deadline = StdDuration::from_secs(15); let start = std::time::Instant::now(); loop { let remaining = deadline.saturating_sub(start.elapsed()); @@ -9246,7 +9583,7 @@ mod tests { let ContentItem::InputText { text } = content_item else { return false; }; - text.contains(crate::session_prefix::TURN_ABORTED_OPEN_TAG) + text.contains(crate::contextual_user_message::TURN_ABORTED_OPEN_TAG) }) }), "expected a model-visible turn aborted marker in history after interrupt" @@ -9391,8 +9728,7 @@ mod tests { .clone() .for_prompt(&reconstruction_turn.model_info.input_modalities); let user_messages1 = collect_user_messages(&snapshot1); - let rebuilt1 = - compact::build_compacted_history(initial_context.clone(), &user_messages1, summary1); + let rebuilt1 = compact::build_compacted_history(Vec::new(), &user_messages1, summary1); live_history.replace(rebuilt1); rollout_items.push(RolloutItem::Compacted(CompactedItem { message: summary1.to_string(), @@ -9434,8 +9770,7 @@ mod tests { .clone() .for_prompt(&reconstruction_turn.model_info.input_modalities); let user_messages2 = collect_user_messages(&snapshot2); - let rebuilt2 = - compact::build_compacted_history(initial_context.clone(), &user_messages2, summary2); + let rebuilt2 = compact::build_compacted_history(Vec::new(), &user_messages2, summary2); live_history.replace(rebuilt2); rollout_items.push(RolloutItem::Compacted(CompactedItem { message: summary2.to_string(), @@ -9498,23 +9833,20 @@ mod tests { let timeout_ms = 1000; let sandbox_permissions = SandboxPermissions::RequireEscalated; - let command = if cfg!(windows) { - vec![ - "cmd.exe".to_string(), - "/C".to_string(), - "echo hi".to_string(), - ] - } else { - vec![ - "/bin/sh".to_string(), - "-c".to_string(), - "echo hi".to_string(), - ] - }; let params = ExecParams { - command: command.clone(), - original_command: shlex::try_join(command.iter().map(String::as_str)) - .unwrap_or_else(|_| command.join(" ")), + command: if cfg!(windows) { + vec![ + "cmd.exe".to_string(), + "/C".to_string(), + "echo hi".to_string(), + ] + } else { + vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "echo hi".to_string(), + ] + }, cwd: turn_context.cwd.clone(), expiration: timeout_ms.into(), env: HashMap::new(), @@ -9528,7 +9860,6 @@ mod tests { let params2 = ExecParams { sandbox_permissions: SandboxPermissions::UseDefault, command: params.command.clone(), - original_command: params.original_command.clone(), cwd: params.cwd.clone(), expiration: timeout_ms.into(), env: HashMap::new(), diff --git a/codex-rs/core/src/codex/rollout_reconstruction.rs b/codex-rs/core/src/codex/rollout_reconstruction.rs new file mode 100644 index 0000000000..11ddbc1928 --- /dev/null +++ b/codex-rs/core/src/codex/rollout_reconstruction.rs @@ -0,0 +1,297 @@ +use super::*; + +// Return value of `Session::reconstruct_history_from_rollout`, bundling the rebuilt history with +// the resume/fork hydration metadata derived from the same replay. +#[derive(Debug)] +pub(super) struct RolloutReconstruction { + pub(super) history: Vec, + pub(super) previous_turn_settings: Option, + pub(super) reference_context_item: Option, +} + +#[derive(Debug, Default)] +enum TurnReferenceContextItem { + /// No `TurnContextItem` has been seen for this replay span yet. + /// + /// This differs from `Cleared`: `NeverSet` means there is no evidence this turn ever + /// established a baseline, while `Cleared` means a baseline existed and a later compaction + /// invalidated it. Only the latter must emit an explicit clearing segment for resume/fork + /// hydration. + #[default] + NeverSet, + /// A previously established baseline was invalidated by later compaction. + Cleared, + /// The latest baseline established by this replay span. + Latest(Box), +} + +#[derive(Debug, Default)] +struct ActiveReplaySegment<'a> { + turn_id: Option, + counts_as_user_turn: bool, + previous_turn_settings: Option, + reference_context_item: TurnReferenceContextItem, + base_replacement_history: Option<&'a [ResponseItem]>, +} + +fn turn_ids_are_compatible(active_turn_id: Option<&str>, item_turn_id: Option<&str>) -> bool { + active_turn_id + .is_none_or(|turn_id| item_turn_id.is_none_or(|item_turn_id| item_turn_id == turn_id)) +} + +fn finalize_active_segment<'a>( + active_segment: ActiveReplaySegment<'a>, + base_replacement_history: &mut Option<&'a [ResponseItem]>, + previous_turn_settings: &mut Option, + reference_context_item: &mut TurnReferenceContextItem, + pending_rollback_turns: &mut usize, +) { + // Thread rollback drops the newest surviving real user-message boundaries. In replay, that + // means skipping the next finalized segments that contain a non-contextual + // `EventMsg::UserMessage`. + if *pending_rollback_turns > 0 { + if active_segment.counts_as_user_turn { + *pending_rollback_turns -= 1; + } + return; + } + + // A surviving replacement-history checkpoint is a complete history base. Once we + // know the newest surviving one, older rollout items do not affect rebuilt history. + if base_replacement_history.is_none() + && let Some(segment_base_replacement_history) = active_segment.base_replacement_history + { + *base_replacement_history = Some(segment_base_replacement_history); + } + + // `previous_turn_settings` come from the newest surviving user turn that established them. + if previous_turn_settings.is_none() && active_segment.counts_as_user_turn { + *previous_turn_settings = active_segment.previous_turn_settings; + } + + // `reference_context_item` comes from the newest surviving user turn baseline, or + // from a surviving compaction that explicitly cleared that baseline. + if matches!(reference_context_item, TurnReferenceContextItem::NeverSet) + && (active_segment.counts_as_user_turn + || matches!( + active_segment.reference_context_item, + TurnReferenceContextItem::Cleared + )) + { + *reference_context_item = active_segment.reference_context_item; + } +} + +impl Session { + pub(super) async fn reconstruct_history_from_rollout( + &self, + turn_context: &TurnContext, + rollout_items: &[RolloutItem], + ) -> RolloutReconstruction { + // Replay metadata should already match the shape of the future lazy reverse loader, even + // while history materialization still uses an eager bridge. Scan newest-to-oldest, + // stopping once a surviving replacement-history checkpoint and the required resume metadata + // are both known; then replay only the buffered surviving tail forward to preserve exact + // history semantics. + let mut base_replacement_history: Option<&[ResponseItem]> = None; + let mut previous_turn_settings = None; + let mut reference_context_item = TurnReferenceContextItem::NeverSet; + // Rollback is "drop the newest N user turns". While scanning in reverse, that becomes + // "skip the next N user-turn segments we finalize". + let mut pending_rollback_turns = 0usize; + // Borrowed suffix of rollout items newer than the newest surviving replacement-history + // checkpoint. If no such checkpoint exists, this remains the full rollout. + let mut rollout_suffix = rollout_items; + // Reverse replay accumulates rollout items into the newest in-progress turn segment until + // we hit its matching `TurnStarted`, at which point the segment can be finalized. + let mut active_segment: Option> = None; + + for (index, item) in rollout_items.iter().enumerate().rev() { + match item { + RolloutItem::Compacted(compacted) => { + let active_segment = + active_segment.get_or_insert_with(ActiveReplaySegment::default); + // Looking backward, compaction clears any older baseline unless a newer + // `TurnContextItem` in this same segment has already re-established it. + if matches!( + active_segment.reference_context_item, + TurnReferenceContextItem::NeverSet + ) { + active_segment.reference_context_item = TurnReferenceContextItem::Cleared; + } + if active_segment.base_replacement_history.is_none() + && let Some(replacement_history) = &compacted.replacement_history + { + active_segment.base_replacement_history = Some(replacement_history); + rollout_suffix = &rollout_items[index + 1..]; + } + } + RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => { + pending_rollback_turns = pending_rollback_turns + .saturating_add(usize::try_from(rollback.num_turns).unwrap_or(usize::MAX)); + } + RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => { + let active_segment = + active_segment.get_or_insert_with(ActiveReplaySegment::default); + // Reverse replay often sees `TurnComplete` before any turn-scoped metadata. + // Capture the turn id early so later `TurnContext` / abort items can match it. + if active_segment.turn_id.is_none() { + active_segment.turn_id = Some(event.turn_id.clone()); + } + } + RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => { + if let Some(active_segment) = active_segment.as_mut() { + if active_segment.turn_id.is_none() + && let Some(turn_id) = &event.turn_id + { + active_segment.turn_id = Some(turn_id.clone()); + } + } else if let Some(turn_id) = &event.turn_id { + active_segment = Some(ActiveReplaySegment { + turn_id: Some(turn_id.clone()), + ..Default::default() + }); + } + } + RolloutItem::EventMsg(EventMsg::UserMessage(_)) => { + let active_segment = + active_segment.get_or_insert_with(ActiveReplaySegment::default); + active_segment.counts_as_user_turn = true; + } + RolloutItem::TurnContext(ctx) => { + let active_segment = + active_segment.get_or_insert_with(ActiveReplaySegment::default); + // `TurnContextItem` can attach metadata to an existing segment, but only a + // real `UserMessage` event should make the segment count as a user turn. + if active_segment.turn_id.is_none() { + active_segment.turn_id = ctx.turn_id.clone(); + } + if turn_ids_are_compatible( + active_segment.turn_id.as_deref(), + ctx.turn_id.as_deref(), + ) { + active_segment.previous_turn_settings = Some(PreviousTurnSettings { + model: ctx.model.clone(), + realtime_active: ctx.realtime_active, + }); + if matches!( + active_segment.reference_context_item, + TurnReferenceContextItem::NeverSet + ) { + active_segment.reference_context_item = + TurnReferenceContextItem::Latest(Box::new(ctx.clone())); + } + } + } + RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => { + // `TurnStarted` is the oldest boundary of the active reverse segment. + if active_segment.as_ref().is_some_and(|active_segment| { + turn_ids_are_compatible( + active_segment.turn_id.as_deref(), + Some(event.turn_id.as_str()), + ) + }) && let Some(active_segment) = active_segment.take() + { + finalize_active_segment( + active_segment, + &mut base_replacement_history, + &mut previous_turn_settings, + &mut reference_context_item, + &mut pending_rollback_turns, + ); + } + } + RolloutItem::ResponseItem(_) + | RolloutItem::EventMsg(_) + | RolloutItem::SessionMeta(_) => {} + } + + if base_replacement_history.is_some() + && previous_turn_settings.is_some() + && !matches!(reference_context_item, TurnReferenceContextItem::NeverSet) + { + // At this point we have both eager resume metadata values and the replacement- + // history base for the surviving tail, so older rollout items cannot affect this + // result. + break; + } + } + + if let Some(active_segment) = active_segment.take() { + finalize_active_segment( + active_segment, + &mut base_replacement_history, + &mut previous_turn_settings, + &mut reference_context_item, + &mut pending_rollback_turns, + ); + } + + let mut history = ContextManager::new(); + let mut saw_legacy_compaction_without_replacement_history = false; + if let Some(base_replacement_history) = base_replacement_history { + history.replace(base_replacement_history.to_vec()); + } + // Materialize exact history semantics from the replay-derived suffix. The eventual lazy + // design should keep this same replay shape, but drive it from a resumable reverse source + // instead of an eagerly loaded `&[RolloutItem]`. + for item in rollout_suffix { + match item { + RolloutItem::ResponseItem(response_item) => { + history.record_items( + std::iter::once(response_item), + turn_context.truncation_policy, + ); + } + RolloutItem::Compacted(compacted) => { + if let Some(replacement_history) = &compacted.replacement_history { + // This should actually never happen, because the reverse loop above (to build rollout_suffix) + // should stop before any compaction that has Some replacement_history + history.replace(replacement_history.clone()); + } else { + saw_legacy_compaction_without_replacement_history = true; + // Legacy rollouts without `replacement_history` should rebuild the + // historical TurnContext at the correct insertion point from persisted + // `TurnContextItem`s. These are rare enough that we currently just clear + // `reference_context_item`, reinject canonical context at the end of the + // resumed conversation, and accept the temporary out-of-distribution + // prompt shape. + // TODO(ccunningham): if we drop support for None replacement_history compaction items, + // we can get rid of this second loop entirely and just build `history` directly in the first loop. + let user_messages = collect_user_messages(history.raw_items()); + let rebuilt = compact::build_compacted_history( + Vec::new(), + &user_messages, + &compacted.message, + ); + history.replace(rebuilt); + } + } + RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => { + history.drop_last_n_user_turns(rollback.num_turns); + } + RolloutItem::EventMsg(_) + | RolloutItem::TurnContext(_) + | RolloutItem::SessionMeta(_) => {} + } + } + + let reference_context_item = match reference_context_item { + TurnReferenceContextItem::NeverSet | TurnReferenceContextItem::Cleared => None, + TurnReferenceContextItem::Latest(turn_reference_context_item) => { + Some(*turn_reference_context_item) + } + }; + let reference_context_item = if saw_legacy_compaction_without_replacement_history { + None + } else { + reference_context_item + }; + + RolloutReconstruction { + history: history.raw_items().to_vec(), + previous_turn_settings, + reference_context_item, + } + } +} diff --git a/codex-rs/core/src/codex/rollout_reconstruction_tests.rs b/codex-rs/core/src/codex/rollout_reconstruction_tests.rs new file mode 100644 index 0000000000..97dbcdd9c5 --- /dev/null +++ b/codex-rs/core/src/codex/rollout_reconstruction_tests.rs @@ -0,0 +1,1283 @@ +use super::*; + +use crate::protocol::CompactedItem; +use crate::protocol::InitialHistory; +use crate::protocol::ResumedHistory; +use codex_protocol::ThreadId; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use pretty_assertions::assert_eq; +use std::path::PathBuf; + +fn user_message(text: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: text.to_string(), + }], + end_turn: None, + phase: None, + } +} + +fn assistant_message(text: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: text.to_string(), + }], + end_turn: None, + phase: None, + } +} + +#[tokio::test] +async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previous_turn_settings() +{ + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let rollout_items = vec![RolloutItem::TurnContext(previous_context_item)]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!(session.previous_turn_settings().await, None); + assert!(session.reference_context_item().await.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lifecycle_turn_with_missing_turn_context_id() + { + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let mut previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + previous_context_item.turn_id = None; + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id, + last_agent_message: None, + }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: previous_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) + ); +} + +#[tokio::test] +async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_completed_turns() { + let (session, turn_context) = make_session_and_context().await; + let first_context_item = turn_context.to_turn_context_item(); + let first_turn_id = first_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let mut rolled_back_context_item = first_context_item.clone(); + rolled_back_context_item.turn_id = Some("rolled-back-turn".to_string()); + rolled_back_context_item.model = "rolled-back-model".to_string(); + let rolled_back_turn_id = rolled_back_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let turn_one_user = user_message("turn 1 user"); + let turn_one_assistant = assistant_message("turn 1 assistant"); + let turn_two_user = user_message("turn 2 user"); + let turn_two_assistant = assistant_message("turn 2 assistant"); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: first_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "turn 1 user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(first_context_item.clone()), + RolloutItem::ResponseItem(turn_one_user.clone()), + RolloutItem::ResponseItem(turn_one_assistant.clone()), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: first_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: rolled_back_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "turn 2 user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(rolled_back_context_item), + RolloutItem::ResponseItem(turn_two_user), + RolloutItem::ResponseItem(turn_two_assistant), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: rolled_back_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, + )), + ]; + + let reconstructed = session + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + + assert_eq!( + reconstructed.history, + vec![turn_one_user, turn_one_assistant] + ); + assert_eq!( + reconstructed.previous_turn_settings, + Some(PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(reconstructed.reference_context_item) + .expect("serialize reconstructed reference context item"), + serde_json::to_value(Some(first_context_item)) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_incomplete_turn() { + let (session, turn_context) = make_session_and_context().await; + let first_context_item = turn_context.to_turn_context_item(); + let first_turn_id = first_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let incomplete_turn_id = "incomplete-rolled-back-turn".to_string(); + let turn_one_user = user_message("turn 1 user"); + let turn_one_assistant = assistant_message("turn 1 assistant"); + let turn_two_user = user_message("turn 2 user"); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: first_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "turn 1 user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(first_context_item.clone()), + RolloutItem::ResponseItem(turn_one_user.clone()), + RolloutItem::ResponseItem(turn_one_assistant.clone()), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: first_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: incomplete_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "turn 2 user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::ResponseItem(turn_two_user), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, + )), + ]; + + let reconstructed = session + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + + assert_eq!( + reconstructed.history, + vec![turn_one_user, turn_one_assistant] + ); + assert_eq!( + reconstructed.previous_turn_settings, + Some(PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(reconstructed.reference_context_item) + .expect("serialize reconstructed reference context item"), + serde_json::to_value(Some(first_context_item)) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn reconstruct_history_rollback_skips_non_user_turns_for_history_and_metadata() { + let (session, turn_context) = make_session_and_context().await; + let first_context_item = turn_context.to_turn_context_item(); + let first_turn_id = first_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let second_turn_id = "rolled-back-user-turn".to_string(); + let standalone_turn_id = "standalone-turn".to_string(); + let turn_one_user = user_message("turn 1 user"); + let turn_one_assistant = assistant_message("turn 1 assistant"); + let turn_two_user = user_message("turn 2 user"); + let turn_two_assistant = assistant_message("turn 2 assistant"); + let standalone_assistant = assistant_message("standalone assistant"); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: first_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "turn 1 user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(first_context_item.clone()), + RolloutItem::ResponseItem(turn_one_user.clone()), + RolloutItem::ResponseItem(turn_one_assistant.clone()), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: first_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: second_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "turn 2 user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::ResponseItem(turn_two_user), + RolloutItem::ResponseItem(turn_two_assistant), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: second_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: standalone_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::ResponseItem(standalone_assistant), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: standalone_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, + )), + ]; + + let reconstructed = session + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + + assert_eq!( + reconstructed.history, + vec![turn_one_user, turn_one_assistant] + ); + assert_eq!( + reconstructed.previous_turn_settings, + Some(PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(reconstructed.reference_context_item) + .expect("serialize reconstructed reference context item"), + serde_json::to_value(Some(first_context_item)) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn reconstruct_history_rollback_clears_history_and_metadata_when_exceeding_user_turns() { + let (session, turn_context) = make_session_and_context().await; + let only_context_item = turn_context.to_turn_context_item(); + let only_turn_id = only_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: only_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "only user".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(only_context_item), + RolloutItem::ResponseItem(user_message("only user")), + RolloutItem::ResponseItem(assistant_message("only assistant")), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: only_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 99 }, + )), + ]; + + let reconstructed = session + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + + assert_eq!(reconstructed.history, Vec::new()); + assert_eq!(reconstructed.previous_turn_settings, None); + assert!(reconstructed.reference_context_item.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_rollback_skips_only_user_turns() { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let user_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let standalone_turn_id = "standalone-task-turn".to_string(); + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: user_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: user_turn_id, + last_agent_message: None, + }, + )), + // Standalone task turn (no UserMessage) should not consume rollback skips. + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: standalone_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: standalone_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!(session.previous_turn_settings().await, None); + assert!(session.reference_context_item().await.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_compaction_metadata() { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let previous_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let incomplete_turn_id = "incomplete-compacted-user-turn".to_string(); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: previous_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item.clone()), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: previous_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: incomplete_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "rolled back".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + codex_protocol::protocol::ThreadRolledBackEvent { num_turns: 1 }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(session.reference_context_item().await) + .expect("serialize seeded reference context item"), + serde_json::to_value(Some(previous_context_item)) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn record_initial_history_resumed_bare_turn_context_does_not_seed_reference_context_item() { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let rollout_items = vec![RolloutItem::TurnContext(previous_context_item.clone())]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert!(session.reference_context_item().await.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_does_not_seed_reference_context_item_after_compaction() { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let rollout_items = vec![ + RolloutItem::TurnContext(previous_context_item), + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!(session.previous_turn_settings().await, None); + assert!(session.reference_context_item().await.is_none()); +} + +#[tokio::test] +async fn reconstruct_history_legacy_compaction_without_replacement_history_does_not_inject_current_initial_context() + { + let (session, turn_context) = make_session_and_context().await; + let rollout_items = vec![ + RolloutItem::ResponseItem(user_message("before compact")), + RolloutItem::ResponseItem(assistant_message("assistant reply")), + RolloutItem::Compacted(CompactedItem { + message: "legacy summary".to_string(), + replacement_history: None, + }), + ]; + + let reconstructed = session + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + + assert_eq!( + reconstructed.history, + vec![ + user_message("before compact"), + user_message("legacy summary"), + ] + ); + assert!(reconstructed.reference_context_item.is_none()); +} + +#[tokio::test] +async fn reconstruct_history_legacy_compaction_without_replacement_history_clears_later_reference_context_item() + { + let (session, turn_context) = make_session_and_context().await; + let current_context_item = turn_context.to_turn_context_item(); + let current_turn_id = current_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let rollout_items = vec![ + RolloutItem::ResponseItem(user_message("before compact")), + RolloutItem::Compacted(CompactedItem { + message: "legacy summary".to_string(), + replacement_history: None, + }), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: current_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "after legacy compact".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(current_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: current_turn_id, + last_agent_message: None, + }, + )), + ]; + + let reconstructed = session + .reconstruct_history_from_rollout(&turn_context, &rollout_items) + .await; + + assert!(reconstructed.reference_context_item.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_turn_context_after_compaction_reestablishes_reference_context_item() + { + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let previous_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: previous_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + // Compaction clears baseline until a later TurnContextItem re-establishes it. + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: previous_turn_id, + last_agent_message: None, + }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: previous_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(session.reference_context_item().await) + .expect("serialize seeded reference context item"), + serde_json::to_value(Some(TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + })) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_turn_for_compaction_accounting() + { + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let previous_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let aborted_turn_id = "aborted-turn-without-id".to_string(); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: previous_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: previous_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: aborted_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "aborted".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::EventMsg(EventMsg::TurnAborted( + codex_protocol::protocol::TurnAbortedEvent { + turn_id: None, + reason: TurnAbortReason::Interrupted, + }, + )), + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: previous_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert!(session.reference_context_item().await.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_for_later_turn_context() + { + let (session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let previous_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let current_model = "current-rollout-model"; + let current_turn_id = "current-turn".to_string(); + let unmatched_abort_turn_id = "other-turn".to_string(); + let current_context_item = TurnContextItem { + turn_id: Some(current_turn_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: current_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: previous_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: previous_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: current_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "current".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::EventMsg(EventMsg::TurnAborted( + codex_protocol::protocol::TurnAbortedEvent { + turn_id: Some(unmatched_abort_turn_id), + reason: TurnAbortReason::Interrupted, + }, + )), + RolloutItem::TurnContext(current_context_item.clone()), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: current_turn_id, + last_agent_message: None, + }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: current_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(session.reference_context_item().await) + .expect("serialize seeded reference context item"), + serde_json::to_value(Some(current_context_item)) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clears_reference_context_item() + { + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let previous_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let incomplete_turn_id = "trailing-incomplete-turn".to_string(); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: previous_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: previous_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: incomplete_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "incomplete".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: previous_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert!(session.reference_context_item().await.is_none()); +} + +#[tokio::test] +async fn record_initial_history_resumed_trailing_incomplete_turn_preserves_turn_context_item() { + let (session, turn_context) = make_session_and_context().await; + let current_context_item = turn_context.to_turn_context_item(); + let current_turn_id = current_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: current_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "incomplete".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(current_context_item.clone()), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: turn_context.model_info.slug.clone(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert_eq!( + serde_json::to_value(session.reference_context_item().await) + .expect("serialize seeded reference context item"), + serde_json::to_value(Some(current_context_item)) + .expect("serialize expected reference context item") + ); +} + +#[tokio::test] +async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clears_reference_context_item() + { + let (session, turn_context) = make_session_and_context().await; + let previous_model = "previous-rollout-model"; + let previous_context_item = TurnContextItem { + turn_id: Some(turn_context.sub_id.clone()), + cwd: turn_context.cwd.clone(), + current_date: turn_context.current_date.clone(), + timezone: turn_context.timezone.clone(), + approval_policy: turn_context.approval_policy.value(), + sandbox_policy: turn_context.sandbox_policy.get().clone(), + network: None, + model: previous_model.to_string(), + personality: turn_context.personality, + collaboration_mode: Some(turn_context.collaboration_mode.clone()), + realtime_active: Some(turn_context.realtime_active), + effort: turn_context.reasoning_effort, + summary: turn_context.reasoning_summary, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: Some(turn_context.truncation_policy.into()), + }; + let previous_turn_id = previous_context_item + .turn_id + .clone() + .expect("turn context should have turn_id"); + let compacted_incomplete_turn_id = "compacted-incomplete-turn".to_string(); + let replacing_turn_id = "replacing-turn".to_string(); + + let rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: previous_turn_id.clone(), + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "seed".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::TurnContext(previous_context_item), + RolloutItem::EventMsg(EventMsg::TurnComplete( + codex_protocol::protocol::TurnCompleteEvent { + turn_id: previous_turn_id, + last_agent_message: None, + }, + )), + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: compacted_incomplete_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + RolloutItem::EventMsg(EventMsg::UserMessage( + codex_protocol::protocol::UserMessageEvent { + message: "compacted".to_string(), + images: None, + local_images: Vec::new(), + text_elements: Vec::new(), + }, + )), + RolloutItem::Compacted(CompactedItem { + message: String::new(), + replacement_history: Some(Vec::new()), + }), + // A newer TurnStarted replaces the incomplete compacted turn without a matching + // completion/abort for the old one. + RolloutItem::EventMsg(EventMsg::TurnStarted( + codex_protocol::protocol::TurnStartedEvent { + turn_id: replacing_turn_id, + model_context_window: Some(128_000), + collaboration_mode_kind: ModeKind::Default, + }, + )), + ]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: ThreadId::default(), + history: rollout_items, + rollout_path: PathBuf::from("/tmp/resume.jsonl"), + })) + .await; + + assert_eq!( + session.previous_turn_settings().await, + Some(PreviousTurnSettings { + model: previous_model.to_string(), + realtime_active: Some(turn_context.realtime_active), + }) + ); + assert!(session.reference_context_item().await.is_none()); +} diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index c1fb31ebd1..1e8dd71419 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -53,6 +53,8 @@ pub(crate) async fn run_codex_thread_interactive( auth_manager, models_manager, Arc::clone(&parent_session.services.skills_manager), + Arc::clone(&parent_session.services.plugins_manager), + Arc::clone(&parent_session.services.mcp_manager), Arc::clone(&parent_session.services.file_watcher), initial_history.unwrap_or(InitialHistory::New), SessionSource::SubAgent(SubAgentSource::Review), @@ -60,6 +62,7 @@ pub(crate) async fn run_codex_thread_interactive( Vec::new(), false, None, + None, ) .await?; let codex = Arc::new(codex); @@ -322,6 +325,7 @@ async fn handle_exec_approval( network_approval_context, proposed_execpolicy_amendment, additional_permissions, + available_decisions, .. } = event; // Race approval with cancellation and timeout to avoid hangs. @@ -335,6 +339,7 @@ async fn handle_exec_approval( network_approval_context, proposed_execpolicy_amendment, additional_permissions, + available_decisions, ); let decision = await_approval_with_cancel( approval_fut, diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index b493075d4a..c4fc1e0875 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -1,6 +1,7 @@ use crate::agent::AgentStatus; use crate::codex::Codex; use crate::codex::SteerInputError; +use crate::config::ConstraintResult; use crate::error::Result as CodexResult; use crate::features::Feature; use crate::file_watcher::WatchRegistration; @@ -8,6 +9,7 @@ use crate::protocol::Event; use crate::protocol::Op; use crate::protocol::Submission; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::ServiceTier; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; @@ -26,9 +28,11 @@ use crate::state_db::StateDbHandle; pub struct ThreadConfigSnapshot { pub model: String, pub model_provider_id: String, + pub service_tier: Option, pub approval_policy: AskForApproval, pub sandbox_policy: SandboxPolicy, pub cwd: PathBuf, + pub ephemeral: bool, pub reasoning_effort: Option, pub personality: Option, pub session_source: SessionSource, @@ -67,6 +71,15 @@ impl CodexThread { self.codex.steer_input(input, expected_turn_id).await } + pub async fn set_app_server_client_name( + &self, + app_server_client_name: Option, + ) -> ConstraintResult<()> { + self.codex + .set_app_server_client_name(app_server_client_name) + .await + } + /// Use sparingly: this is intended to be removed soon. pub async fn submit_with_id(&self, sub: Submission) -> CodexResult<()> { self.codex.submit_with_id(sub).await diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index 43ee08fd4f..6c7dbb1050 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -4,10 +4,11 @@ use crate::ModelProviderInfo; use crate::Prompt; use crate::client::ModelClientSession; use crate::client_common::ResponseEvent; +#[cfg(test)] +use crate::codex::PreviousTurnSettings; use crate::codex::Session; use crate::codex::TurnContext; use crate::codex::get_last_assistant_message_from_turn; -use crate::context_manager::ContextManager; use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::protocol::CompactedItem; @@ -23,7 +24,6 @@ use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::RolloutItem; use codex_protocol::user_input::UserInput; use futures::prelude::*; use tracing::error; @@ -51,43 +51,6 @@ pub(crate) fn should_use_remote_compact_task(provider: &ModelProviderInfo) -> bo provider.is_openai() } -fn is_model_switch_developer_message(item: &ResponseItem) -> bool { - match item { - ResponseItem::Message { role, content, .. } if role == "developer" => { - matches!( - content.as_slice(), - [ContentItem::InputText { text }] if text.starts_with("\n") - ) - } - _ => false, - } -} - -pub(crate) fn extract_trailing_model_switch_update_for_compaction_request( - history: &mut ContextManager, -) -> Option { - let history_items = history.raw_items(); - let last_user_turn_boundary_index = history_items - .iter() - .rposition(crate::context_manager::is_user_turn_boundary); - let model_switch_index = history_items - .iter() - .enumerate() - .rev() - .find_map(|(i, item)| { - let is_trailing = last_user_turn_boundary_index.is_none_or(|boundary| i > boundary); - if is_trailing && is_model_switch_developer_message(item) { - Some(i) - } else { - None - } - })?; - let mut replacement = history_items.to_vec(); - let model_switch_item = replacement.remove(model_switch_index); - history.replace(replacement); - Some(model_switch_item) -} - pub(crate) async fn run_inline_auto_compact_task( sess: Arc, turn_context: Arc, @@ -136,10 +99,6 @@ async fn run_compact_task_inner( let initial_input_for_turn: ResponseInputItem = ResponseInputItem::from(input); let mut history = sess.clone_history().await; - // Keep compaction prompts in-distribution: if a model-switch update was injected at the - // tail of history (between turns), exclude it from the compaction request payload. - let stripped_model_switch_item = - extract_trailing_model_switch_update_for_compaction_request(&mut history); history.record_items( &[initial_input_for_turn.into()], turn_context.truncation_policy, @@ -150,7 +109,8 @@ async fn run_compact_task_inner( let max_retries = turn_context.provider.stream_max_retries(); let mut retries = 0; let mut client_session = sess.services.model_client.new_session(); - // Reuse one client session so turn-scoped state (sticky routing, websocket append tracking) + // Reuse one client session so turn-scoped state (sticky routing, websocket incremental + // request tracking) // survives retries within this compact turn. loop { @@ -244,11 +204,6 @@ async fn run_compact_task_inner( new_history = insert_initial_context_before_last_real_user_or_summary(new_history, initial_context); } - // Reattach the stripped model-switch update only after successful compaction so the model - // still sees the switch instructions on the next real sampling request. - if let Some(model_switch_item) = stripped_model_switch_item { - new_history.push(model_switch_item); - } let ghost_snapshots: Vec = history_items .iter() .filter(|item| matches!(item, ResponseItem::GhostSnapshot { .. })) @@ -259,16 +214,14 @@ async fn run_compact_task_inner( InitialContextInjection::DoNotInject => None, InitialContextInjection::BeforeLastUserMessage => Some(turn_context.to_turn_context_item()), }; - sess.replace_history(new_history.clone(), reference_context_item) + let compacted_item = CompactedItem { + message: summary_text.clone(), + replacement_history: Some(new_history.clone()), + }; + sess.replace_compacted_history(new_history, reference_context_item, compacted_item) .await; sess.recompute_token_usage(&turn_context).await; - let rollout_item = RolloutItem::Compacted(CompactedItem { - message: summary_text.clone(), - replacement_history: Some(new_history), - }); - sess.persist_rollout_items(&[rollout_item]).await; - sess.emit_turn_item_completed(&turn_context, compaction_item) .await; let warning = EventMsg::Warning(WarningEvent { @@ -450,6 +403,7 @@ async fn drain_to_completed( &turn_context.otel_manager, turn_context.reasoning_effort, turn_context.reasoning_summary, + turn_context.config.service_tier, turn_metadata_header, ) .await?; @@ -491,8 +445,12 @@ mod tests { async fn process_compacted_history_with_test_session( compacted_history: Vec, + previous_turn_settings: Option<&PreviousTurnSettings>, ) -> (Vec, Vec) { let (session, turn_context) = crate::codex::make_session_and_context().await; + session + .set_previous_turn_settings(previous_turn_settings.cloned()) + .await; let initial_context = session.build_initial_context(&turn_context).await; let refreshed = crate::compact_remote::process_compacted_history( &session, @@ -534,107 +492,6 @@ mod tests { assert_eq!(None, joined); } - #[test] - fn extract_trailing_model_switch_update_for_compaction_request_removes_trailing_item() { - let mut history = ContextManager::new(); - history.replace(vec![ - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "USER_MESSAGE".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "assistant".to_string(), - content: vec![ContentItem::OutputText { - text: "ASSISTANT_REPLY".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "\nNEW_MODEL_INSTRUCTIONS".to_string(), - }], - end_turn: None, - phase: None, - }, - ]); - - let model_switch_item = - extract_trailing_model_switch_update_for_compaction_request(&mut history); - - assert_eq!(history.raw_items().len(), 2); - assert!(model_switch_item.is_some()); - assert!( - history - .raw_items() - .iter() - .all(|item| !is_model_switch_developer_message(item)) - ); - } - - #[test] - fn extract_trailing_model_switch_update_for_compaction_request_keeps_historical_item() { - let mut history = ContextManager::new(); - history.replace(vec![ - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "FIRST_USER_MESSAGE".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "developer".to_string(), - content: vec![ContentItem::InputText { - text: "\nOLDER_MODEL_INSTRUCTIONS".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "assistant".to_string(), - content: vec![ContentItem::OutputText { - text: "ASSISTANT_REPLY".to_string(), - }], - end_turn: None, - phase: None, - }, - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "SECOND_USER_MESSAGE".to_string(), - }], - end_turn: None, - phase: None, - }, - ]); - - let model_switch_item = - extract_trailing_model_switch_update_for_compaction_request(&mut history); - - assert_eq!(history.raw_items().len(), 4); - assert!(model_switch_item.is_none()); - assert!( - history - .raw_items() - .iter() - .any(is_model_switch_developer_message) - ); - } - #[test] fn collect_user_messages_extracts_user_text_only() { let items = vec![ @@ -802,7 +659,7 @@ do things }, ]; let (refreshed, mut expected) = - process_compacted_history_with_test_session(compacted_history).await; + process_compacted_history_with_test_session(compacted_history, None).await; expected.push(ResponseItem::Message { id: None, role: "user".to_string(), @@ -827,7 +684,7 @@ do things phase: None, }]; let (refreshed, mut expected) = - process_compacted_history_with_test_session(compacted_history).await; + process_compacted_history_with_test_session(compacted_history, None).await; expected.push(ResponseItem::Message { id: None, role: "user".to_string(), @@ -903,7 +760,7 @@ keep me updated }, ]; let (refreshed, mut expected) = - process_compacted_history_with_test_session(compacted_history).await; + process_compacted_history_with_test_session(compacted_history, None).await; expected.push(ResponseItem::Message { id: None, role: "user".to_string(), @@ -949,7 +806,7 @@ keep me updated ]; let (refreshed, initial_context) = - process_compacted_history_with_test_session(compacted_history).await; + process_compacted_history_with_test_session(compacted_history, None).await; let mut expected = vec![ ResponseItem::Message { id: None, @@ -983,6 +840,50 @@ keep me updated assert_eq!(refreshed, expected); } + #[tokio::test] + async fn process_compacted_history_reinjects_model_switch_message() { + let compacted_history = vec![ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "summary".to_string(), + }], + end_turn: None, + phase: None, + }]; + let previous_turn_settings = PreviousTurnSettings { + model: "previous-regular-model".to_string(), + realtime_active: None, + }; + + let (refreshed, initial_context) = process_compacted_history_with_test_session( + compacted_history, + Some(&previous_turn_settings), + ) + .await; + + let ResponseItem::Message { role, content, .. } = &initial_context[0] else { + panic!("expected developer message"); + }; + assert_eq!(role, "developer"); + let [ContentItem::InputText { text }, ..] = content.as_slice() else { + panic!("expected developer text"); + }; + assert!(text.contains("")); + + let mut expected = initial_context; + expected.push(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "summary".to_string(), + }], + end_turn: None, + phase: None, + }); + assert_eq!(refreshed, expected); + } + #[test] fn insert_initial_context_before_last_real_user_or_summary_keeps_summary_last() { let compacted_history = vec![ diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index 2a9106c722..6d8368bce4 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -4,7 +4,6 @@ use crate::Prompt; use crate::codex::Session; use crate::codex::TurnContext; use crate::compact::InitialContextInjection; -use crate::compact::extract_trailing_model_switch_update_for_compaction_request; use crate::compact::insert_initial_context_before_last_real_user_or_summary; use crate::context_manager::ContextManager; use crate::context_manager::TotalTokenUsageBreakdown; @@ -14,7 +13,6 @@ use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::protocol::CompactedItem; use crate::protocol::EventMsg; -use crate::protocol::RolloutItem; use crate::protocol::TurnStartedEvent; use codex_protocol::items::ContextCompactionItem; use codex_protocol::items::TurnItem; @@ -73,10 +71,6 @@ async fn run_remote_compact_task_inner_impl( sess.emit_turn_item_started(turn_context, &compaction_item) .await; let mut history = sess.clone_history().await; - // Keep compaction prompts in-distribution: if a model-switch update was injected at the - // tail of history (between turns), exclude it from the compaction request payload. - let stripped_model_switch_item = - extract_trailing_model_switch_update_for_compaction_request(&mut history); let base_instructions = sess.get_base_instructions().await; let deleted_items = trim_function_call_history_to_fit_context_window( &mut history, @@ -90,7 +84,6 @@ async fn run_remote_compact_task_inner_impl( "trimmed history items before remote compaction" ); } - // Required to keep `/undo` available after compaction let ghost_snapshots: Vec = history .raw_items() @@ -136,11 +129,6 @@ async fn run_remote_compact_task_inner_impl( initial_context_injection, ) .await; - // Reattach the stripped model-switch update only after successful compaction so the model - // still sees the switch instructions on the next real sampling request. - if let Some(model_switch_item) = stripped_model_switch_item { - new_history.push(model_switch_item); - } if !ghost_snapshots.is_empty() { new_history.extend(ghost_snapshots); @@ -149,16 +137,13 @@ async fn run_remote_compact_task_inner_impl( InitialContextInjection::DoNotInject => None, InitialContextInjection::BeforeLastUserMessage => Some(turn_context.to_turn_context_item()), }; - sess.replace_history(new_history.clone(), reference_context_item) - .await; - sess.recompute_token_usage(turn_context).await; - let compacted_item = CompactedItem { message: String::new(), - replacement_history: Some(new_history), + replacement_history: Some(new_history.clone()), }; - sess.persist_rollout_items(&[RolloutItem::Compacted(compacted_item)]) + sess.replace_compacted_history(new_history, reference_context_item, compacted_item) .await; + sess.recompute_token_usage(turn_context).await; sess.emit_turn_item_completed(turn_context, compaction_item) .await; @@ -205,10 +190,12 @@ pub(crate) async fn process_compacted_history( fn should_keep_compacted_history_item(item: &ResponseItem) -> bool { match item { ResponseItem::Message { role, .. } if role == "developer" => false, - ResponseItem::Message { role, .. } if role == "user" => matches!( - crate::event_mapping::parse_turn_item(item), - Some(TurnItem::UserMessage(_)) - ), + ResponseItem::Message { role, .. } if role == "user" => { + matches!( + crate::event_mapping::parse_turn_item(item), + Some(TurnItem::UserMessage(_)) + ) + } ResponseItem::Message { role, .. } if role == "assistant" => true, ResponseItem::Message { .. } => false, ResponseItem::Compaction { .. } => true, diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index fceb965998..cf139d3a5e 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -5,9 +5,11 @@ use crate::path_utils::write_atomically; use anyhow::Context; use codex_config::CONFIG_TOML_FILE; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::TrustLevel; use codex_protocol::openai_models::ReasoningEffort; use std::collections::BTreeMap; +use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; use tokio::task; @@ -25,6 +27,8 @@ pub enum ConfigEdit { model: Option, effort: Option, }, + /// Update the service tier preference for future turns. + SetServiceTier { service_tier: Option }, /// Update the active (or default) model personality. SetModelPersonality { personality: Option }, /// Toggle the acknowledgement flag under `[notice]`. @@ -75,6 +79,27 @@ pub fn status_line_items_edit(items: &[String]) -> ConfigEdit { } } +pub fn model_availability_nux_count_edits(shown_count: &HashMap) -> Vec { + let mut shown_count_entries: Vec<_> = shown_count.iter().collect(); + shown_count_entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right)); + + let mut edits = vec![ConfigEdit::ClearPath { + segments: vec!["tui".to_string(), "model_availability_nux".to_string()], + }]; + for (model_slug, count) in shown_count_entries { + edits.push(ConfigEdit::SetPath { + segments: vec![ + "tui".to_string(), + "model_availability_nux".to_string(), + model_slug.clone(), + ], + value: value(i64::from(*count)), + }); + } + + edits +} + // TODO(jif) move to a dedicated file mod document_helpers { use crate::config::types::McpServerConfig; @@ -195,6 +220,11 @@ mod document_helpers { { entry["scopes"] = array_from_iter(scopes.iter().cloned()); } + if let Some(resource) = &config.oauth_resource + && !resource.is_empty() + { + entry["oauth_resource"] = value(resource.clone()); + } entry } @@ -300,6 +330,10 @@ impl ConfigDocument { ); mutated }), + ConfigEdit::SetServiceTier { service_tier } => Ok(self.write_profile_value( + &["service_tier"], + service_tier.map(|service_tier| value(service_tier.to_string())), + )), ConfigEdit::SetModelPersonality { personality } => Ok(self.write_profile_value( &["personality"], personality.map(|personality| value(personality.to_string())), @@ -747,6 +781,11 @@ impl ConfigEditsBuilder { self } + pub fn set_service_tier(mut self, service_tier: Option) -> Self { + self.edits.push(ConfigEdit::SetServiceTier { service_tier }); + self + } + pub fn set_personality(mut self, personality: Option) -> Self { self.edits .push(ConfigEdit::SetModelPersonality { personality }); @@ -794,6 +833,12 @@ impl ConfigEditsBuilder { self } + pub fn set_model_availability_nux_count(mut self, shown_count: &HashMap) -> Self { + self.edits + .extend(model_availability_nux_count_edits(shown_count)); + self + } + pub fn replace_mcp_servers(mut self, servers: &BTreeMap) -> Self { self.edits .push(ConfigEdit::ReplaceMcpServers(servers.clone())); @@ -839,6 +884,30 @@ impl ConfigEditsBuilder { self } + pub fn set_realtime_microphone(mut self, microphone: Option<&str>) -> Self { + let segments = vec!["audio".to_string(), "microphone".to_string()]; + match microphone { + Some(microphone) => self.edits.push(ConfigEdit::SetPath { + segments, + value: value(microphone), + }), + None => self.edits.push(ConfigEdit::ClearPath { segments }), + } + self + } + + pub fn set_realtime_speaker(mut self, speaker: Option<&str>) -> Self { + let segments = vec!["audio".to_string(), "speaker".to_string()]; + match speaker { + Some(speaker) => self.edits.push(ConfigEdit::SetPath { + segments, + value: value(speaker), + }), + None => self.edits.push(ConfigEdit::ClearPath { segments }), + } + self + } + pub fn clear_legacy_windows_sandbox_keys(mut self) -> Self { for key in [ "experimental_windows_sandbox", @@ -934,6 +1003,25 @@ model_reasoning_effort = "high" assert_eq!(contents, "enabled = true\n"); } + #[test] + fn set_model_availability_nux_count_writes_shown_count() { + let tmp = tempdir().expect("tmpdir"); + let codex_home = tmp.path(); + let shown_count = HashMap::from([("gpt-foo".to_string(), 4)]); + + ConfigEditsBuilder::new(codex_home) + .set_model_availability_nux_count(&shown_count) + .apply_blocking() + .expect("persist"); + + let contents = + std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config"); + let expected = r#"[tui.model_availability_nux] +gpt-foo = 4 +"#; + assert_eq!(contents, expected); + } + #[test] fn set_skill_config_writes_disabled_entry() { let tmp = tempdir().expect("tmpdir"); @@ -1441,6 +1529,7 @@ gpt-5 = "gpt-5.1" enabled_tools: Some(vec!["one".to_string(), "two".to_string()]), disabled_tools: None, scopes: None, + oauth_resource: None, }, ); @@ -1465,6 +1554,7 @@ gpt-5 = "gpt-5.1" enabled_tools: None, disabled_tools: Some(vec!["forbidden".to_string()]), scopes: None, + oauth_resource: Some("https://resource.example.com".to_string()), }, ); @@ -1483,6 +1573,7 @@ bearer_token_env_var = \"TOKEN\" enabled = false startup_timeout_sec = 5.0 disabled_tools = [\"forbidden\"] +oauth_resource = \"https://resource.example.com\" [mcp_servers.http.http_headers] Z-Header = \"z\" @@ -1532,6 +1623,7 @@ foo = { command = "cmd" } enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); @@ -1578,6 +1670,7 @@ foo = { command = "cmd" } # keep me enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); @@ -1623,6 +1716,7 @@ foo = { command = "cmd", args = ["--flag"] } # keep me enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); @@ -1669,6 +1763,7 @@ foo = { command = "cmd" } enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); @@ -1804,6 +1899,50 @@ model_reasoning_effort = "high" assert_eq!(notice, Some(true)); } + #[test] + fn blocking_builder_set_realtime_audio_persists_and_clears() { + let tmp = tempdir().expect("tmpdir"); + let codex_home = tmp.path(); + + ConfigEditsBuilder::new(codex_home) + .set_realtime_microphone(Some("USB Mic")) + .set_realtime_speaker(Some("Desk Speakers")) + .apply_blocking() + .expect("persist realtime audio"); + + let raw = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config"); + let config: TomlValue = toml::from_str(&raw).expect("parse config"); + let realtime_audio = config + .get("audio") + .and_then(TomlValue::as_table) + .expect("audio table should exist"); + assert_eq!( + realtime_audio.get("microphone").and_then(TomlValue::as_str), + Some("USB Mic") + ); + assert_eq!( + realtime_audio.get("speaker").and_then(TomlValue::as_str), + Some("Desk Speakers") + ); + + ConfigEditsBuilder::new(codex_home) + .set_realtime_microphone(None) + .apply_blocking() + .expect("clear realtime microphone"); + + let raw = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config"); + let config: TomlValue = toml::from_str(&raw).expect("parse config"); + let realtime_audio = config + .get("audio") + .and_then(TomlValue::as_table) + .expect("audio table should exist"); + assert_eq!(realtime_audio.get("microphone"), None); + assert_eq!( + realtime_audio.get("speaker").and_then(TomlValue::as_str), + Some("Desk Speakers") + ); + } + #[test] fn replace_mcp_servers_blocking_clears_table_when_empty() { let tmp = tempdir().expect("tmpdir"); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index eed20772f1..74eee08bf1 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -9,12 +9,14 @@ use crate::config::types::McpServerDisabledReason; use crate::config::types::McpServerTransportConfig; use crate::config::types::MemoriesConfig; use crate::config::types::MemoriesToml; +use crate::config::types::ModelAvailabilityNuxConfig; use crate::config::types::Notice; use crate::config::types::NotificationMethod; use crate::config::types::Notifications; use crate::config::types::OtelConfig; use crate::config::types::OtelConfigToml; use crate::config::types::OtelExporterKind; +use crate::config::types::PluginConfig; use crate::config::types::SandboxWorkspaceWrite; use crate::config::types::ShellEnvironmentPolicy; use crate::config::types::ShellEnvironmentPolicyToml; @@ -49,8 +51,6 @@ use crate::project_doc::LOCAL_PROJECT_DOC_FILENAME; use crate::protocol::AskForApproval; use crate::protocol::ReadOnlyAccess; use crate::protocol::SandboxPolicy; -#[cfg(target_os = "macos")] -use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; use crate::unified_exec::DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS; use crate::unified_exec::MIN_EMPTY_YIELD_TIME_MS; use crate::windows_sandbox::WindowsSandboxLevelExt; @@ -62,10 +62,12 @@ use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::TrustLevel; use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::models::MacOsSeatbeltProfileExtensions; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_rmcp_client::OAuthCredentialsStoreMode; @@ -82,8 +84,6 @@ use std::path::Path; use std::path::PathBuf; #[cfg(test)] use tempfile::tempdir; -#[cfg(not(target_os = "macos"))] -type MacOsSeatbeltProfileExtensions = (); use crate::config::permissions::network_proxy_config_from_permissions; use crate::config::profile::ConfigProfile; @@ -186,6 +186,9 @@ pub struct Config { /// Optional override of model selection. pub model: Option, + /// Effective service tier preference for new turns. + pub service_tier: Option, + /// Model used specifically for review sessions. pub review_model: Option, @@ -279,6 +282,9 @@ pub struct Config { /// Show startup tooltips in the TUI welcome screen. pub show_tooltips: bool, + /// Persisted startup availability NUX state for model tooltips. + pub model_availability_nux: ModelAvailabilityNuxConfig, + /// Start the TUI in the specified collaboration mode (plan/default). /// Controls whether the TUI uses the terminal's alternate screen buffer. @@ -412,9 +418,9 @@ pub struct Config { /// global default"). pub plan_mode_reasoning_effort: Option, - /// If not "none", the value to use for `reasoning.summary` when making a - /// request using the Responses API. - pub model_reasoning_summary: ReasoningSummary, + /// Optional value to use for `reasoning.summary` when making a request + /// using the Responses API. When unset, the model catalog default is used. + pub model_reasoning_summary: Option, /// Optional override to force-enable reasoning summaries for the configured model. pub model_supports_reasoning_summaries: Option, @@ -429,13 +435,20 @@ pub struct Config { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: String, + /// Machine-local realtime audio device preferences used by realtime voice. + pub realtime_audio: RealtimeAudioConfig, + /// Experimental / do not use. Overrides only the realtime conversation - /// websocket transport base URL (the `Op::RealtimeConversation` `/ws` + /// websocket transport base URL (the `Op::RealtimeConversation` + /// `/v1/realtime` /// connection) without changing normal provider HTTP requests. pub experimental_realtime_ws_base_url: Option, + /// Experimental / do not use. Selects the realtime websocket model/snapshot + /// used for the `Op::RealtimeConversation` connection. + pub experimental_realtime_ws_model: Option, /// Experimental / do not use. Overrides only the realtime conversation - /// websocket transport backend prompt (the `Op::RealtimeConversation` - /// `/ws` session.create backend_prompt) without changing normal prompts. + /// websocket transport instructions (the `Op::RealtimeConversation` + /// `/ws` session.update instructions) without changing normal prompts. pub experimental_realtime_ws_backend_prompt: Option, /// When set, restricts ChatGPT login to a specific workspace identifier. pub forced_chatgpt_workspace_id: Option, @@ -1175,16 +1188,27 @@ pub struct ConfigToml { /// Optionally specify a personality for the model pub personality: Option, + /// Optional explicit service tier preference for new turns. + pub service_tier: Option, + /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: Option, + /// Machine-local realtime audio device preferences used by realtime voice. + #[serde(default)] + pub audio: Option, + /// Experimental / do not use. Overrides only the realtime conversation - /// websocket transport base URL (the `Op::RealtimeConversation` `/ws` + /// websocket transport base URL (the `Op::RealtimeConversation` + /// `/v1/realtime` /// connection) without changing normal provider HTTP requests. pub experimental_realtime_ws_base_url: Option, + /// Experimental / do not use. Selects the realtime websocket model/snapshot + /// used for the `Op::RealtimeConversation` connection. + pub experimental_realtime_ws_model: Option, /// Experimental / do not use. Overrides only the realtime conversation - /// websocket transport backend prompt (the `Op::RealtimeConversation` - /// `/ws` session.create backend_prompt) without changing normal prompts. + /// websocket transport instructions (the `Op::RealtimeConversation` + /// `/ws` session.update instructions) without changing normal prompts. pub experimental_realtime_ws_backend_prompt: Option, pub projects: Option>, @@ -1203,6 +1227,10 @@ pub struct ConfigToml { /// User-level skill config entries keyed by SKILL.md path. pub skills: Option, + /// User-level plugin config entries keyed by plugin name. + #[serde(default)] + pub plugins: HashMap, + /// Centralized feature flags (new). Prefer this over individual toggles. #[serde(default)] // Injects known feature keys into the schema and forbids unknown keys. @@ -1309,6 +1337,19 @@ impl ProjectConfig { } } +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RealtimeAudioConfig { + pub microphone: Option, + pub speaker: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RealtimeAudioToml { + pub microphone: Option, + pub speaker: Option, +} + #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct ToolsToml { @@ -1524,6 +1565,7 @@ pub struct ConfigOverrides { pub approval_policy: Option, pub sandbox_mode: Option, pub model_provider: Option, + pub service_tier: Option>, pub config_profile: Option, pub codex_linux_sandbox_exe: Option, pub main_execve_wrapper_exe: Option, @@ -1654,6 +1696,7 @@ impl Config { approval_policy: approval_policy_override, sandbox_mode, model_provider, + service_tier: service_tier_override, config_profile: config_profile_key, codex_linux_sandbox_exe, main_execve_wrapper_exe, @@ -1914,6 +1957,16 @@ impl Config { let forced_login_method = cfg.forced_login_method; let model = model.or(config_profile.model).or(cfg.model); + let service_tier = if features.enabled(Feature::FastMode) { + service_tier_override.unwrap_or_else(|| { + config_profile + .service_tier + .or(cfg.service_tier) + .filter(|tier| matches!(tier, ServiceTier::Fast)) + }) + } else { + None + }; let compact_prompt = compact_prompt.or(cfg.compact_prompt).and_then(|value| { let trimmed = value.trim(); @@ -2060,6 +2113,7 @@ impl Config { let config = Self { model, + service_tier, review_model, model_context_window: cfg.model_context_window, model_auto_compact_token_limit: cfg.model_auto_compact_token_limit, @@ -2141,8 +2195,7 @@ impl Config { .or(cfg.plan_mode_reasoning_effort), model_reasoning_summary: config_profile .model_reasoning_summary - .or(cfg.model_reasoning_summary) - .unwrap_or_default(), + .or(cfg.model_reasoning_summary), model_supports_reasoning_summaries: cfg.model_supports_reasoning_summaries, model_catalog, model_verbosity: config_profile.model_verbosity.or(cfg.model_verbosity), @@ -2150,7 +2203,14 @@ impl Config { .chatgpt_base_url .or(cfg.chatgpt_base_url) .unwrap_or("https://chatgpt.com/backend-api/".to_string()), + realtime_audio: cfg + .audio + .map_or_else(RealtimeAudioConfig::default, |audio| RealtimeAudioConfig { + microphone: audio.microphone, + speaker: audio.speaker, + }), experimental_realtime_ws_base_url: cfg.experimental_realtime_ws_base_url, + experimental_realtime_ws_model: cfg.experimental_realtime_ws_model, experimental_realtime_ws_backend_prompt: cfg.experimental_realtime_ws_backend_prompt, forced_chatgpt_workspace_id, forced_login_method, @@ -2191,6 +2251,11 @@ impl Config { .unwrap_or_default(), animations: cfg.tui.as_ref().map(|t| t.animations).unwrap_or(true), show_tooltips: cfg.tui.as_ref().map(|t| t.show_tooltips).unwrap_or(true), + model_availability_nux: cfg + .tui + .as_ref() + .map(|t| t.model_availability_nux.clone()) + .unwrap_or_default(), tui_alternate_screen: cfg .tui .as_ref() @@ -2379,6 +2444,7 @@ mod tests { use crate::config::types::McpServerTransportConfig; use crate::config::types::MemoriesConfig; use crate::config::types::MemoriesToml; + use crate::config::types::ModelAvailabilityNuxConfig; use crate::config::types::NotificationMethod; use crate::config::types::Notifications; use crate::config_loader::RequirementSource; @@ -2411,6 +2477,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, } } @@ -2430,6 +2497,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, } } @@ -2466,23 +2534,31 @@ persistence = "none" let memories = r#" [memories] -max_raw_memories_for_global = 512 +no_memories_if_mcp_or_web_search = true +generate_memories = false +use_memories = false +max_raw_memories_for_consolidation = 512 +max_unused_days = 21 max_rollout_age_days = 42 max_rollouts_per_startup = 9 min_rollout_idle_hours = 24 -phase_1_model = "gpt-5-mini" -phase_2_model = "gpt-5" +extract_model = "gpt-5-mini" +consolidation_model = "gpt-5" "#; let memories_cfg = toml::from_str::(memories).expect("TOML deserialization should succeed"); assert_eq!( Some(MemoriesToml { - max_raw_memories_for_global: Some(512), + no_memories_if_mcp_or_web_search: Some(true), + generate_memories: Some(false), + use_memories: Some(false), + max_raw_memories_for_consolidation: Some(512), + max_unused_days: Some(21), max_rollout_age_days: Some(42), max_rollouts_per_startup: Some(9), min_rollout_idle_hours: Some(24), - phase_1_model: Some("gpt-5-mini".to_string()), - phase_2_model: Some("gpt-5".to_string()), + extract_model: Some("gpt-5-mini".to_string()), + consolidation_model: Some("gpt-5".to_string()), }), memories_cfg.memories ); @@ -2496,16 +2572,65 @@ phase_2_model = "gpt-5" assert_eq!( config.memories, MemoriesConfig { - max_raw_memories_for_global: 512, + no_memories_if_mcp_or_web_search: true, + generate_memories: false, + use_memories: false, + max_raw_memories_for_consolidation: 512, + max_unused_days: 21, max_rollout_age_days: 42, max_rollouts_per_startup: 9, min_rollout_idle_hours: 24, - phase_1_model: Some("gpt-5-mini".to_string()), - phase_2_model: Some("gpt-5".to_string()), + extract_model: Some("gpt-5-mini".to_string()), + consolidation_model: Some("gpt-5".to_string()), } ); } + #[test] + fn config_toml_deserializes_model_availability_nux() { + let toml = r#" +[tui.model_availability_nux] +"gpt-foo" = 2 +"gpt-bar" = 4 +"#; + let cfg: ConfigToml = + toml::from_str(toml).expect("TOML deserialization should succeed for TUI NUX"); + + assert_eq!( + cfg.tui.expect("tui config should deserialize"), + Tui { + notifications: Notifications::default(), + notification_method: NotificationMethod::default(), + animations: true, + show_tooltips: true, + alternate_screen: AltScreenMode::default(), + status_line: None, + theme: None, + model_availability_nux: ModelAvailabilityNuxConfig { + shown_count: HashMap::from([ + ("gpt-bar".to_string(), 4), + ("gpt-foo".to_string(), 2), + ]), + }, + } + ); + } + + #[test] + fn runtime_config_defaults_model_availability_nux() { + let cfg = Config::load_from_base_config_with_overrides( + ConfigToml::default(), + ConfigOverrides::default(), + tempdir().expect("tempdir").path().to_path_buf(), + ) + .expect("load config"); + + assert_eq!( + cfg.model_availability_nux, + ModelAvailabilityNuxConfig::default() + ); + } + #[test] fn config_toml_deserializes_permissions_network() { let toml = r#" @@ -2640,6 +2765,7 @@ theme = "dracula" alternate_screen: AltScreenMode::Auto, status_line: None, theme: None, + model_availability_nux: ModelAvailabilityNuxConfig::default(), } ); } @@ -3464,6 +3590,7 @@ profile = "project" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); @@ -3621,6 +3748,7 @@ bearer_token = "secret" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -3692,6 +3820,7 @@ ZIG_VAR = "3" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -3743,6 +3872,7 @@ ZIG_VAR = "3" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -3792,6 +3922,7 @@ ZIG_VAR = "3" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -3857,6 +3988,7 @@ startup_timeout_sec = 2.0 enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); apply_blocking( @@ -3934,6 +4066,7 @@ X-Auth = "DOCS_AUTH" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -3964,6 +4097,7 @@ X-Auth = "DOCS_AUTH" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); apply_blocking( @@ -4032,6 +4166,7 @@ url = "https://example.com/mcp" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ), ( @@ -4052,6 +4187,7 @@ url = "https://example.com/mcp" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ), ]); @@ -4135,6 +4271,7 @@ url = "https://example.com/mcp" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -4180,6 +4317,7 @@ url = "https://example.com/mcp" enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -4225,6 +4363,7 @@ url = "https://example.com/mcp" enabled_tools: Some(vec!["allowed".to_string()]), disabled_tools: Some(vec!["blocked".to_string()]), scopes: None, + oauth_resource: None, }, )]); @@ -4253,6 +4392,51 @@ url = "https://example.com/mcp" Ok(()) } + #[tokio::test] + async fn replace_mcp_servers_streamable_http_serializes_oauth_resource() -> anyhow::Result<()> { + let codex_home = TempDir::new()?; + + let servers = BTreeMap::from([( + "docs".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url: "https://example.com/mcp".to_string(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }, + enabled: true, + required: false, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth_resource: Some("https://resource.example.com".to_string()), + }, + )]); + + apply_blocking( + codex_home.path(), + None, + &[ConfigEdit::ReplaceMcpServers(servers.clone())], + )?; + + let config_path = codex_home.path().join(CONFIG_TOML_FILE); + let serialized = std::fs::read_to_string(&config_path)?; + assert!(serialized.contains(r#"oauth_resource = "https://resource.example.com""#)); + + let loaded = load_global_mcp_servers(codex_home.path()).await?; + let docs = loaded.get("docs").expect("docs entry"); + assert_eq!( + docs.oauth_resource.as_deref(), + Some("https://resource.example.com") + ); + + Ok(()) + } + #[tokio::test] async fn set_model_updates_defaults() -> anyhow::Result<()> { let codex_home = TempDir::new()?; @@ -4714,6 +4898,7 @@ model_verbosity = "high" review_model: None, model_context_window: None, model_auto_compact_token_limit: None, + service_tier: None, model_provider_id: "openai".to_string(), model_provider: fixture.openai_provider.clone(), permissions: Permissions { @@ -4761,13 +4946,15 @@ model_verbosity = "high" show_raw_agent_reasoning: false, model_reasoning_effort: Some(ReasoningEffort::High), plan_mode_reasoning_effort: None, - model_reasoning_summary: ReasoningSummary::Detailed, + model_reasoning_summary: Some(ReasoningSummary::Detailed), model_supports_reasoning_summaries: None, model_catalog: None, model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_model: None, experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, @@ -4792,6 +4979,7 @@ model_verbosity = "high" tui_notification_method: Default::default(), animations: true, show_tooltips: true, + model_availability_nux: ModelAvailabilityNuxConfig::default(), analytics_enabled: Some(true), feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, @@ -4840,6 +5028,7 @@ model_verbosity = "high" review_model: None, model_context_window: None, model_auto_compact_token_limit: None, + service_tier: None, model_provider_id: "openai-custom".to_string(), model_provider: fixture.openai_custom_provider.clone(), permissions: Permissions { @@ -4887,13 +5076,15 @@ model_verbosity = "high" show_raw_agent_reasoning: false, model_reasoning_effort: None, plan_mode_reasoning_effort: None, - model_reasoning_summary: ReasoningSummary::default(), + model_reasoning_summary: None, model_supports_reasoning_summaries: None, model_catalog: None, model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_model: None, experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, @@ -4918,6 +5109,7 @@ model_verbosity = "high" tui_notification_method: Default::default(), animations: true, show_tooltips: true, + model_availability_nux: ModelAvailabilityNuxConfig::default(), analytics_enabled: Some(true), feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, @@ -4964,6 +5156,7 @@ model_verbosity = "high" review_model: None, model_context_window: None, model_auto_compact_token_limit: None, + service_tier: None, model_provider_id: "openai".to_string(), model_provider: fixture.openai_provider.clone(), permissions: Permissions { @@ -5011,13 +5204,15 @@ model_verbosity = "high" show_raw_agent_reasoning: false, model_reasoning_effort: None, plan_mode_reasoning_effort: None, - model_reasoning_summary: ReasoningSummary::default(), + model_reasoning_summary: None, model_supports_reasoning_summaries: None, model_catalog: None, model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_model: None, experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, @@ -5042,6 +5237,7 @@ model_verbosity = "high" tui_notification_method: Default::default(), animations: true, show_tooltips: true, + model_availability_nux: ModelAvailabilityNuxConfig::default(), analytics_enabled: Some(false), feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, @@ -5074,6 +5270,7 @@ model_verbosity = "high" review_model: None, model_context_window: None, model_auto_compact_token_limit: None, + service_tier: None, model_provider_id: "openai".to_string(), model_provider: fixture.openai_provider.clone(), permissions: Permissions { @@ -5121,13 +5318,15 @@ model_verbosity = "high" show_raw_agent_reasoning: false, model_reasoning_effort: Some(ReasoningEffort::High), plan_mode_reasoning_effort: None, - model_reasoning_summary: ReasoningSummary::Detailed, + model_reasoning_summary: Some(ReasoningSummary::Detailed), model_supports_reasoning_summaries: None, model_catalog: None, model_verbosity: Some(Verbosity::High), personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), + realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_ws_base_url: None, + experimental_realtime_ws_model: None, experimental_realtime_ws_backend_prompt: None, base_instructions: None, developer_instructions: None, @@ -5152,6 +5351,7 @@ model_verbosity = "high" tui_notification_method: Default::default(), animations: true, show_tooltips: true, + model_availability_nux: ModelAvailabilityNuxConfig::default(), analytics_enabled: Some(true), feedback_enabled: true, tui_alternate_screen: AltScreenMode::Auto, @@ -5766,12 +5966,12 @@ mcp_oauth_callback_url = "https://example.com/callback" let config = ConfigBuilder::default() .codex_home(codex_home.path().to_path_buf()) .cloud_requirements(CloudRequirementsLoader::new(async { - Some(crate::config_loader::ConfigRequirementsToml { + Ok(Some(crate::config_loader::ConfigRequirementsToml { allowed_sandbox_modes: Some(vec![ crate::config_loader::SandboxModeRequirement::ReadOnly, ]), ..Default::default() - }) + })) })) .build() .await?; @@ -5807,9 +6007,9 @@ mcp_oauth_callback_url = "https://example.com/callback" let config = ConfigBuilder::default() .codex_home(codex_home.path().to_path_buf()) .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cloud_requirements(CloudRequirementsLoader::new( - async move { Some(requirements) }, - )) + .cloud_requirements(CloudRequirementsLoader::new(async move { + Ok(Some(requirements)) + })) .build() .await?; assert_eq!( @@ -5833,12 +6033,12 @@ mcp_oauth_callback_url = "https://example.com/callback" .codex_home(codex_home.path().to_path_buf()) .fallback_cwd(Some(codex_home.path().to_path_buf())) .cloud_requirements(CloudRequirementsLoader::new(async { - Some(crate::config_loader::ConfigRequirementsToml { + Ok(Some(crate::config_loader::ConfigRequirementsToml { allowed_web_search_modes: Some(vec![ crate::config_loader::WebSearchModeRequirement::Cached, ]), ..Default::default() - }) + })) })) .build() .await?; @@ -5874,10 +6074,10 @@ trust_level = "untrusted" .codex_home(codex_home.path().to_path_buf()) .fallback_cwd(Some(workspace.path().to_path_buf())) .cloud_requirements(CloudRequirementsLoader::new(async { - Some(crate::config_loader::ConfigRequirementsToml { + Ok(Some(crate::config_loader::ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), ..Default::default() - }) + })) })) .build() .await?; @@ -5903,10 +6103,10 @@ trust_level = "untrusted" .codex_home(codex_home.path().to_path_buf()) .fallback_cwd(Some(codex_home.path().to_path_buf())) .cloud_requirements(CloudRequirementsLoader::new(async { - Some(crate::config_loader::ConfigRequirementsToml { + Ok(Some(crate::config_loader::ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::OnRequest]), ..Default::default() - }) + })) })) .build() .await?; @@ -6131,6 +6331,67 @@ experimental_realtime_ws_backend_prompt = "prompt from config" ); Ok(()) } + + #[test] + fn experimental_realtime_ws_model_loads_from_config_toml() -> std::io::Result<()> { + let cfg: ConfigToml = toml::from_str( + r#" +experimental_realtime_ws_model = "realtime-test-model" +"#, + ) + .expect("TOML deserialization should succeed"); + + assert_eq!( + cfg.experimental_realtime_ws_model.as_deref(), + Some("realtime-test-model") + ); + + let codex_home = TempDir::new()?; + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!( + config.experimental_realtime_ws_model.as_deref(), + Some("realtime-test-model") + ); + Ok(()) + } + + #[test] + fn realtime_audio_loads_from_config_toml() -> std::io::Result<()> { + let cfg: ConfigToml = toml::from_str( + r#" +[audio] +microphone = "USB Mic" +speaker = "Desk Speakers" +"#, + ) + .expect("TOML deserialization should succeed"); + + let realtime_audio = cfg + .audio + .as_ref() + .expect("realtime audio config should be present"); + assert_eq!(realtime_audio.microphone.as_deref(), Some("USB Mic")); + assert_eq!(realtime_audio.speaker.as_deref(), Some("Desk Speakers")); + + let codex_home = TempDir::new()?; + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!(config.realtime_audio.microphone.as_deref(), Some("USB Mic")); + assert_eq!( + config.realtime_audio.speaker.as_deref(), + Some("Desk Speakers") + ); + Ok(()) + } } #[cfg(test)] diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index 61b02adcd0..6d4cd23090 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -8,6 +8,7 @@ use crate::config::types::WindowsToml; use crate::protocol::AskForApproval; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; use codex_protocol::openai_models::ReasoningEffort; @@ -18,6 +19,7 @@ use codex_protocol::openai_models::ReasoningEffort; #[schemars(deny_unknown_fields)] pub struct ConfigProfile { pub model: Option, + pub service_tier: Option, /// The key in the `model_providers` map identifying the /// [`ModelProviderInfo`] to use. pub model_provider: Option, diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 678766e807..8fd5b109d0 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -7,6 +7,7 @@ use crate::config_loader::RequirementSource; pub use codex_protocol::config_types::AltScreenMode; pub use codex_protocol::config_types::ModeKind; pub use codex_protocol::config_types::Personality; +pub use codex_protocol::config_types::ServiceTier; pub use codex_protocol::config_types::WebSearchMode; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::BTreeMap; @@ -26,7 +27,8 @@ pub const DEFAULT_OTEL_ENVIRONMENT: &str = "dev"; pub const DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP: usize = 16; pub const DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS: i64 = 30; pub const DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS: i64 = 6; -pub const DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL: usize = 1_024; +pub const DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION: usize = 256; +pub const DEFAULT_MEMORIES_MAX_UNUSED_DAYS: i64 = 30; #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "kebab-case")] @@ -98,6 +100,10 @@ pub struct McpServerConfig { /// Optional OAuth scopes to request during MCP login. #[serde(default, skip_serializing_if = "Option::is_none")] pub scopes: Option>, + + /// Optional OAuth resource parameter to include during MCP login (RFC 8707). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oauth_resource: Option, } // Raw MCP config shape used for deserialization and JSON Schema generation. @@ -142,6 +148,8 @@ pub(crate) struct RawMcpServerConfig { pub disabled_tools: Option>, #[serde(default)] pub scopes: Option>, + #[serde(default)] + pub oauth_resource: Option, } impl<'de> Deserialize<'de> for McpServerConfig { @@ -165,6 +173,7 @@ impl<'de> Deserialize<'de> for McpServerConfig { let enabled_tools = raw.enabled_tools.clone(); let disabled_tools = raw.disabled_tools.clone(); let scopes = raw.scopes.clone(); + let oauth_resource = raw.oauth_resource.clone(); fn throw_if_set(transport: &str, field: &str, value: Option<&T>) -> Result<(), E> where @@ -188,6 +197,7 @@ impl<'de> Deserialize<'de> for McpServerConfig { throw_if_set("stdio", "bearer_token", raw.bearer_token.as_ref())?; throw_if_set("stdio", "http_headers", raw.http_headers.as_ref())?; throw_if_set("stdio", "env_http_headers", raw.env_http_headers.as_ref())?; + throw_if_set("stdio", "oauth_resource", raw.oauth_resource.as_ref())?; McpServerTransportConfig::Stdio { command, args: raw.args.clone().unwrap_or_default(), @@ -221,6 +231,7 @@ impl<'de> Deserialize<'de> for McpServerConfig { enabled_tools, disabled_tools, scopes, + oauth_resource, }) } } @@ -361,8 +372,16 @@ pub struct FeedbackConfigToml { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct MemoriesToml { + /// When `true`, web searches and MCP tool calls mark the thread `memory_mode` as `"polluted"`. + pub no_memories_if_mcp_or_web_search: Option, + /// When `false`, newly created threads are stored with `memory_mode = "disabled"` in the state DB. + pub generate_memories: Option, + /// When `false`, skip injecting memory usage instructions into developer prompts. + pub use_memories: Option, /// Maximum number of recent raw memories retained for global consolidation. - pub max_raw_memories_for_global: Option, + pub max_raw_memories_for_consolidation: Option, + /// Maximum number of days since a memory was last used before it becomes ineligible for phase 2 selection. + pub max_unused_days: Option, /// Maximum age of the threads used for memories. pub max_rollout_age_days: Option, /// Maximum number of rollout candidates processed per pass. @@ -370,31 +389,39 @@ pub struct MemoriesToml { /// Minimum idle time between last thread activity and memory creation (hours). > 12h recommended. pub min_rollout_idle_hours: Option, /// Model used for thread summarisation. - pub phase_1_model: Option, + pub extract_model: Option, /// Model used for memory consolidation. - pub phase_2_model: Option, + pub consolidation_model: Option, } /// Effective memories settings after defaults are applied. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MemoriesConfig { - pub max_raw_memories_for_global: usize, + pub no_memories_if_mcp_or_web_search: bool, + pub generate_memories: bool, + pub use_memories: bool, + pub max_raw_memories_for_consolidation: usize, + pub max_unused_days: i64, pub max_rollout_age_days: i64, pub max_rollouts_per_startup: usize, pub min_rollout_idle_hours: i64, - pub phase_1_model: Option, - pub phase_2_model: Option, + pub extract_model: Option, + pub consolidation_model: Option, } impl Default for MemoriesConfig { fn default() -> Self { Self { - max_raw_memories_for_global: DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL, + no_memories_if_mcp_or_web_search: false, + generate_memories: true, + use_memories: true, + max_raw_memories_for_consolidation: DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, + max_unused_days: DEFAULT_MEMORIES_MAX_UNUSED_DAYS, max_rollout_age_days: DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS, max_rollouts_per_startup: DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP, min_rollout_idle_hours: DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS, - phase_1_model: None, - phase_2_model: None, + extract_model: None, + consolidation_model: None, } } } @@ -403,10 +430,19 @@ impl From for MemoriesConfig { fn from(toml: MemoriesToml) -> Self { let defaults = Self::default(); Self { - max_raw_memories_for_global: toml - .max_raw_memories_for_global - .unwrap_or(defaults.max_raw_memories_for_global) + no_memories_if_mcp_or_web_search: toml + .no_memories_if_mcp_or_web_search + .unwrap_or(defaults.no_memories_if_mcp_or_web_search), + generate_memories: toml.generate_memories.unwrap_or(defaults.generate_memories), + use_memories: toml.use_memories.unwrap_or(defaults.use_memories), + max_raw_memories_for_consolidation: toml + .max_raw_memories_for_consolidation + .unwrap_or(defaults.max_raw_memories_for_consolidation) .min(4096), + max_unused_days: toml + .max_unused_days + .unwrap_or(defaults.max_unused_days) + .clamp(0, 365), max_rollout_age_days: toml .max_rollout_age_days .unwrap_or(defaults.max_rollout_age_days) @@ -419,8 +455,8 @@ impl From for MemoriesConfig { .min_rollout_idle_hours .unwrap_or(defaults.min_rollout_idle_hours) .clamp(1, 48), - phase_1_model: toml.phase_1_model, - phase_2_model: toml.phase_2_model, + extract_model: toml.extract_model, + consolidation_model: toml.consolidation_model, } } } @@ -639,6 +675,14 @@ impl fmt::Display for NotificationMethod { } } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ModelAvailabilityNuxConfig { + /// Number of times a startup availability NUX has been shown per model slug. + #[serde(default, flatten)] + pub shown_count: HashMap, +} + /// Collection of settings that are specific to the TUI. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -688,6 +732,10 @@ pub struct Tui { /// Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes. #[serde(default)] pub theme: Option, + + /// Startup tooltip availability NUX state persisted by the TUI. + #[serde(default)] + pub model_availability_nux: ModelAvailabilityNuxConfig, } const fn default_true() -> bool { @@ -727,6 +775,14 @@ pub struct SkillConfig { pub enabled: bool, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct PluginConfig { + pub path: AbsolutePathBuf, + #[serde(default = "default_enabled")] + pub enabled: bool, +} + #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct SkillsConfig { @@ -1084,6 +1140,22 @@ mod tests { ); } + #[test] + fn deserialize_streamable_http_server_config_with_oauth_resource() { + let cfg: McpServerConfig = toml::from_str( + r#" + url = "https://example.com/mcp" + oauth_resource = "https://api.example.com" + "#, + ) + .expect("should deserialize http config with oauth_resource"); + + assert_eq!( + cfg.oauth_resource, + Some("https://api.example.com".to_string()) + ); + } + #[test] fn deserialize_server_config_with_tool_filters() { let cfg: McpServerConfig = toml::from_str( @@ -1138,6 +1210,20 @@ mod tests { "#, ) .expect_err("should reject env_http_headers for stdio transport"); + + let err = toml::from_str::( + r#" + command = "echo" + oauth_resource = "https://api.example.com" + "#, + ) + .expect_err("should reject oauth_resource for stdio transport"); + + assert!( + err.to_string() + .contains("oauth_resource is not supported for stdio"), + "unexpected error: {err}" + ); } #[test] diff --git a/codex-rs/core/src/config_loader/mod.rs b/codex-rs/core/src/config_loader/mod.rs index 70014c03b8..63b3be48e9 100644 --- a/codex-rs/core/src/config_loader/mod.rs +++ b/codex-rs/core/src/config_loader/mod.rs @@ -6,7 +6,6 @@ mod macos; mod tests; use crate::config::ConfigToml; -use crate::config::deserialize_config_toml_with_base; use crate::config_loader::layer_io::LoadedConfigLayers; use crate::git_info::resolve_root_git_project_for_trust; use codex_app_server_protocol::ConfigLayerSource; @@ -25,6 +24,7 @@ use std::path::Path; use std::path::PathBuf; use toml::Value as TomlValue; +pub use codex_config::CloudRequirementsLoadError; pub use codex_config::CloudRequirementsLoader; pub use codex_config::ConfigError; pub use codex_config::ConfigLayerEntry; @@ -116,7 +116,7 @@ pub async fn load_config_layers_state( ) -> io::Result { let mut config_requirements_toml = ConfigRequirementsWithSources::default(); - if let Some(requirements) = cloud_requirements.get().await { + if let Some(requirements) = cloud_requirements.get().await.map_err(io::Error::other)? { config_requirements_toml .merge_unset_fields(RequirementSource::CloudRequirements, requirements); } @@ -575,6 +575,11 @@ struct ProjectTrustContext { user_config_file: AbsolutePathBuf, } +#[derive(Deserialize)] +struct ProjectTrustConfigToml { + projects: Option>, +} + struct ProjectTrustDecision { trust_level: Option, trust_key: String, @@ -665,10 +670,16 @@ async fn project_trust_context( config_base_dir: &Path, user_config_file: &AbsolutePathBuf, ) -> io::Result { - let config_toml = deserialize_config_toml_with_base(merged_config.clone(), config_base_dir)?; + let project_trust_config: ProjectTrustConfigToml = { + let _guard = AbsolutePathBufGuard::new(config_base_dir); + merged_config + .clone() + .try_into() + .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))? + }; let project_root = find_project_root(cwd, project_root_markers).await?; - let projects = config_toml.projects.unwrap_or_default(); + let projects = project_trust_config.projects.unwrap_or_default(); let project_root_key = project_root.as_path().to_string_lossy().to_string(); let repo_root = resolve_root_git_project_for_trust(cwd.as_path()); diff --git a/codex-rs/core/src/config_loader/tests.rs b/codex-rs/core/src/config_loader/tests.rs index 3eab05ba18..983acbe8d1 100644 --- a/codex-rs/core/src/config_loader/tests.rs +++ b/codex-rs/core/src/config_loader/tests.rs @@ -5,6 +5,7 @@ use crate::config::ConfigOverrides; use crate::config::ConfigToml; use crate::config::ConstraintError; use crate::config::ProjectConfig; +use crate::config_loader::CloudRequirementsLoadError; use crate::config_loader::CloudRequirementsLoader; use crate::config_loader::ConfigLayerEntry; use crate::config_loader::ConfigLoadError; @@ -576,7 +577,7 @@ allowed_approval_policies = ["on-request"] ..LoaderOverrides::default() }, CloudRequirementsLoader::new(async { - Some(ConfigRequirementsToml { + Ok(Some(ConfigRequirementsToml { allowed_approval_policies: Some(vec![AskForApproval::Never]), allowed_sandbox_modes: None, allowed_web_search_modes: None, @@ -584,7 +585,7 @@ allowed_approval_policies = ["on-request"] rules: None, enforce_residency: None, network: None, - }) + })) }), ) .await?; @@ -671,7 +672,7 @@ async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()> network: None, }; let expected = requirements.clone(); - let cloud_requirements = CloudRequirementsLoader::new(async move { Some(requirements) }); + let cloud_requirements = CloudRequirementsLoader::new(async move { Ok(Some(requirements)) }); let layers = load_config_layers_state( &codex_home, @@ -702,6 +703,31 @@ async fn load_config_layers_includes_cloud_requirements() -> anyhow::Result<()> Ok(()) } +#[tokio::test] +async fn load_config_layers_fails_when_cloud_requirements_loader_fails() -> anyhow::Result<()> { + let tmp = tempdir()?; + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&codex_home).await?; + let cwd = AbsolutePathBuf::from_absolute_path(tmp.path())?; + + let err = load_config_layers_state( + &codex_home, + Some(cwd), + &[] as &[(String, TomlValue)], + LoaderOverrides::default(), + CloudRequirementsLoader::new(async { + Err(CloudRequirementsLoadError::new("cloud requirements failed")) + }), + ) + .await + .expect_err("cloud requirements failure should fail closed"); + + assert_eq!(err.kind(), std::io::ErrorKind::Other); + assert!(err.to_string().contains("cloud requirements failed")); + + Ok(()) +} + #[tokio::test] async fn project_layers_prefer_closest_cwd() -> std::io::Result<()> { let tmp = tempdir()?; @@ -1088,6 +1114,91 @@ async fn project_layers_disabled_when_untrusted_or_unknown() -> std::io::Result< Ok(()) } +#[tokio::test] +async fn cli_override_can_update_project_local_mcp_server_when_project_is_trusted() +-> std::io::Result<()> { + let tmp = tempdir()?; + let project_root = tmp.path().join("project"); + let nested = project_root.join("child"); + let dot_codex = project_root.join(".codex"); + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&nested).await?; + tokio::fs::create_dir_all(&dot_codex).await?; + tokio::fs::create_dir_all(&codex_home).await?; + tokio::fs::write(project_root.join(".git"), "gitdir: here").await?; + tokio::fs::write( + dot_codex.join(CONFIG_TOML_FILE), + r#" +[mcp_servers.sentry] +url = "https://mcp.sentry.dev/mcp" +enabled = false +"#, + ) + .await?; + make_config_for_test(&codex_home, &project_root, TrustLevel::Trusted, None).await?; + + let config = ConfigBuilder::default() + .codex_home(codex_home) + .cli_overrides(vec![( + "mcp_servers.sentry.enabled".to_string(), + TomlValue::Boolean(true), + )]) + .fallback_cwd(Some(nested)) + .build() + .await?; + + let server = config + .mcp_servers + .get() + .get("sentry") + .expect("trusted project MCP server should load"); + assert!(server.enabled); + + Ok(()) +} + +#[tokio::test] +async fn cli_override_for_disabled_project_local_mcp_server_returns_invalid_transport() +-> std::io::Result<()> { + let tmp = tempdir()?; + let project_root = tmp.path().join("project"); + let nested = project_root.join("child"); + let dot_codex = project_root.join(".codex"); + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&nested).await?; + tokio::fs::create_dir_all(&dot_codex).await?; + tokio::fs::create_dir_all(&codex_home).await?; + tokio::fs::write(project_root.join(".git"), "gitdir: here").await?; + tokio::fs::write( + dot_codex.join(CONFIG_TOML_FILE), + r#" +[mcp_servers.sentry] +url = "https://mcp.sentry.dev/mcp" +enabled = false +"#, + ) + .await?; + + let err = ConfigBuilder::default() + .codex_home(codex_home) + .cli_overrides(vec![( + "mcp_servers.sentry.enabled".to_string(), + TomlValue::Boolean(true), + )]) + .fallback_cwd(Some(nested)) + .build() + .await + .expect_err("untrusted project layer should not provide MCP transport"); + + assert!( + err.to_string().contains("invalid transport") + && err.to_string().contains("mcp_servers.sentry"), + "unexpected error: {err}" + ); + + Ok(()) +} + #[tokio::test] async fn invalid_project_config_ignored_when_untrusted_or_unknown() -> std::io::Result<()> { let tmp = tempdir()?; @@ -1390,6 +1501,7 @@ prefix_rules = [ matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["rm"]), decision: Decision::Forbidden, + resolved_program: None, justification: None, }], } @@ -1415,6 +1527,7 @@ prefix_rules = [ matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "status"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }], } @@ -1426,6 +1539,7 @@ prefix_rules = [ matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["hg", "status"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }], } @@ -1509,6 +1623,7 @@ prefix_rules = [] matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["rm".to_string()], decision: Decision::Forbidden, + resolved_program: None, justification: None, }], } @@ -1547,6 +1662,7 @@ prefix_rules = [] matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["rm".to_string()], decision: Decision::Forbidden, + resolved_program: None, justification: None, }], } @@ -1561,6 +1677,7 @@ prefix_rules = [] matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["git".to_string(), "push".to_string()], decision: Decision::Prompt, + resolved_program: None, justification: None, }], } diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index f6f7198f6e..e4b7755abf 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -1,14 +1,11 @@ use crate::codex::TurnContext; use crate::context_manager::normalize; -use crate::instructions::SkillInstructions; -use crate::instructions::UserInstructions; -use crate::session_prefix::is_session_prefix; +use crate::event_mapping::is_contextual_user_message_content; use crate::truncate::TruncationPolicy; use crate::truncate::approx_token_count; use crate::truncate::approx_tokens_from_byte_count_i64; use crate::truncate::truncate_function_output_items_with_policy; use crate::truncate::truncate_text; -use crate::user_shell_command::is_user_shell_command_text; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputBody; @@ -347,32 +344,21 @@ impl ContextManager { let policy_with_serialization_budget = policy * 1.2; match item { ResponseItem::FunctionCallOutput { call_id, output } => { - let body = match &output.body { - FunctionCallOutputBody::Text(content) => FunctionCallOutputBody::Text( - truncate_text(content, policy_with_serialization_budget), - ), - FunctionCallOutputBody::ContentItems(items) => { - FunctionCallOutputBody::ContentItems( - truncate_function_output_items_with_policy( - items, - policy_with_serialization_budget, - ), - ) - } - }; ResponseItem::FunctionCallOutput { call_id: call_id.clone(), - output: FunctionCallOutputPayload { - body, - success: output.success, - }, + output: truncate_function_output_payload( + output, + policy_with_serialization_budget, + ), } } ResponseItem::CustomToolCallOutput { call_id, output } => { - let truncated = truncate_text(output, policy_with_serialization_budget); ResponseItem::CustomToolCallOutput { call_id: call_id.clone(), - output: truncated, + output: truncate_function_output_payload( + output, + policy_with_serialization_budget, + ), } } ResponseItem::Message { .. } @@ -388,6 +374,25 @@ impl ContextManager { } } +fn truncate_function_output_payload( + output: &FunctionCallOutputPayload, + policy: TruncationPolicy, +) -> FunctionCallOutputPayload { + let body = match &output.body { + FunctionCallOutputBody::Text(content) => { + FunctionCallOutputBody::Text(truncate_text(content, policy)) + } + FunctionCallOutputBody::ContentItems(items) => FunctionCallOutputBody::ContentItems( + truncate_function_output_items_with_policy(items, policy), + ), + }; + + FunctionCallOutputPayload { + body, + success: output.success, + } +} + /// API messages include every non-system item (user/assistant messages, reasoning, /// tool calls, tool outputs, shell calls, and web-search calls). fn is_api_message(message: &ResponseItem) -> bool { @@ -511,7 +516,8 @@ fn image_data_url_estimate_adjustment(item: &ResponseItem) -> (i64, i64) { } } } - ResponseItem::FunctionCallOutput { output, .. } => { + ResponseItem::FunctionCallOutput { output, .. } + | ResponseItem::CustomToolCallOutput { output, .. } => { if let FunctionCallOutputBody::ContentItems(items) = &output.body { for content_item in items { if let FunctionCallOutputContentItem::InputImage { image_url } = content_item { @@ -554,33 +560,7 @@ pub(crate) fn is_user_turn_boundary(item: &ResponseItem) -> bool { return false; }; - if role != "user" { - return false; - } - - if UserInstructions::is_user_instructions(content) - || SkillInstructions::is_skill_instructions(content) - { - return false; - } - - for content_item in content { - match content_item { - ContentItem::InputText { text } => { - if is_session_prefix(text) || is_user_shell_command_text(text) { - return false; - } - } - ContentItem::OutputText { text } => { - if is_session_prefix(text) { - return false; - } - } - ContentItem::InputImage { .. } => {} - } - } - - true + role == "user" && !is_contextual_user_message_content(content) } fn user_message_positions(items: &[ResponseItem]) -> Vec { diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index 3e11dae40a..798abc7675 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -67,7 +67,7 @@ fn user_input_text_msg(text: &str) -> ResponseItem { fn custom_tool_call_output(call_id: &str, output: &str) -> ResponseItem { ResponseItem::CustomToolCallOutput { call_id: call_id.to_string(), - output: output.to_string(), + output: FunctionCallOutputPayload::from_text(output.to_string()), } } @@ -279,6 +279,24 @@ fn for_prompt_strips_images_when_model_does_not_support_images() { }, ]), }, + ResponseItem::CustomToolCall { + id: None, + status: None, + call_id: "tool-1".to_string(), + name: "js_repl".to_string(), + input: "view_image".to_string(), + }, + ResponseItem::CustomToolCallOutput { + call_id: "tool-1".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputText { + text: "js repl result".to_string(), + }, + FunctionCallOutputContentItem::InputImage { + image_url: "https://example.com/js-repl-result.png".to_string(), + }, + ]), + }, ]; let history = create_history_with_items(items); let text_only_modalities = vec![InputModality::Text]; @@ -321,6 +339,25 @@ fn for_prompt_strips_images_when_model_does_not_support_images() { }, ]), }, + ResponseItem::CustomToolCall { + id: None, + status: None, + call_id: "tool-1".to_string(), + name: "js_repl".to_string(), + input: "view_image".to_string(), + }, + ResponseItem::CustomToolCallOutput { + call_id: "tool-1".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputText { + text: "js repl result".to_string(), + }, + FunctionCallOutputContentItem::InputText { + text: "image content omitted because you do not support image input" + .to_string(), + }, + ]), + }, ]; assert_eq!(stripped, expected); @@ -563,7 +600,6 @@ fn drop_last_n_user_turns_preserves_prefix() { fn drop_last_n_user_turns_ignores_session_prefix_user_messages() { let items = vec![ user_input_text_msg("ctx"), - user_input_text_msg("do the thing"), user_input_text_msg( "# AGENTS.md instructions for test_directory\n\n\ntest_text\n", ), @@ -586,7 +622,6 @@ fn drop_last_n_user_turns_ignores_session_prefix_user_messages() { let expected_prefix_and_first_turn = vec![ user_input_text_msg("ctx"), - user_input_text_msg("do the thing"), user_input_text_msg( "# AGENTS.md instructions for test_directory\n\n\ntest_text\n", ), @@ -608,7 +643,6 @@ fn drop_last_n_user_turns_ignores_session_prefix_user_messages() { let expected_prefix_only = vec![ user_input_text_msg("ctx"), - user_input_text_msg("do the thing"), user_input_text_msg( "# AGENTS.md instructions for test_directory\n\n\ntest_text\n", ), @@ -623,7 +657,6 @@ fn drop_last_n_user_turns_ignores_session_prefix_user_messages() { let mut history = create_history_with_items(vec![ user_input_text_msg("ctx"), - user_input_text_msg("do the thing"), user_input_text_msg( "# AGENTS.md instructions for test_directory\n\n\ntest_text\n", ), @@ -644,7 +677,6 @@ fn drop_last_n_user_turns_ignores_session_prefix_user_messages() { let mut history = create_history_with_items(vec![ user_input_text_msg("ctx"), - user_input_text_msg("do the thing"), user_input_text_msg( "# AGENTS.md instructions for test_directory\n\n\ntest_text\n", ), @@ -676,7 +708,7 @@ fn remove_first_item_handles_custom_tool_pair() { }, ResponseItem::CustomToolCallOutput { call_id: "tool-1".to_string(), - output: "ok".to_string(), + output: FunctionCallOutputPayload::from_text("ok".to_string()), }, ]; let mut h = create_history_with_items(items); @@ -755,7 +787,7 @@ fn record_items_truncates_custom_tool_call_output_content() { let long_output = line.repeat(2_500); let item = ResponseItem::CustomToolCallOutput { call_id: "tool-200".to_string(), - output: long_output.clone(), + output: FunctionCallOutputPayload::from_text(long_output.clone()), }; history.record_items([&item], policy); @@ -763,7 +795,8 @@ fn record_items_truncates_custom_tool_call_output_content() { assert_eq!(history.items.len(), 1); match &history.items[0] { ResponseItem::CustomToolCallOutput { output, .. } => { - assert_ne!(output, &long_output); + let output = output.text_content().unwrap_or_default(); + assert_ne!(output, long_output); assert!( output.contains("tokens truncated"), "expected token-based truncation marker, got {output}" @@ -954,7 +987,7 @@ fn normalize_adds_missing_output_for_custom_tool_call() { }, ResponseItem::CustomToolCallOutput { call_id: "tool-x".to_string(), - output: "aborted".to_string(), + output: FunctionCallOutputPayload::from_text("aborted".to_string()), }, ] ); @@ -1021,7 +1054,7 @@ fn normalize_removes_orphan_function_call_output() { fn normalize_removes_orphan_custom_tool_call_output() { let items = vec![ResponseItem::CustomToolCallOutput { call_id: "orphan-2".to_string(), - output: "ok".to_string(), + output: FunctionCallOutputPayload::from_text("ok".to_string()), }]; let mut h = create_history_with_items(items); @@ -1094,7 +1127,7 @@ fn normalize_mixed_inserts_and_removals() { }, ResponseItem::CustomToolCallOutput { call_id: "t1".to_string(), - output: "aborted".to_string(), + output: FunctionCallOutputPayload::from_text("aborted".to_string()), }, ResponseItem::LocalShellCall { id: None, @@ -1196,7 +1229,7 @@ fn normalize_removes_orphan_function_call_output_panics_in_debug() { fn normalize_removes_orphan_custom_tool_call_output_panics_in_debug() { let items = vec![ResponseItem::CustomToolCallOutput { call_id: "orphan-2".to_string(), - output: "ok".to_string(), + output: FunctionCallOutputPayload::from_text("ok".to_string()), }]; let mut h = create_history_with_items(items); h.normalize_history(&default_input_modalities()); @@ -1299,6 +1332,28 @@ fn image_data_url_payload_does_not_dominate_function_call_output_estimate() { assert!(estimated < raw_len); } +#[test] +fn image_data_url_payload_does_not_dominate_custom_tool_call_output_estimate() { + let payload = "C".repeat(50_000); + let image_url = format!("data:image/png;base64,{payload}"); + let item = ResponseItem::CustomToolCallOutput { + call_id: "call-js-repl".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputText { + text: "Screenshot captured".to_string(), + }, + FunctionCallOutputContentItem::InputImage { image_url }, + ]), + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let expected = raw_len - payload.len() as i64 + IMAGE_BYTES_ESTIMATE; + + assert_eq!(estimated, expected); + assert!(estimated < raw_len); +} + #[test] fn non_base64_image_urls_are_unchanged() { let message_item = ResponseItem::Message { diff --git a/codex-rs/core/src/context_manager/normalize.rs b/codex-rs/core/src/context_manager/normalize.rs index a4fe9e64fd..572ac51fc8 100644 --- a/codex-rs/core/src/context_manager/normalize.rs +++ b/codex-rs/core/src/context_manager/normalize.rs @@ -1,7 +1,6 @@ use std::collections::HashSet; use codex_protocol::models::ContentItem; -use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseItem; @@ -35,10 +34,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec) { idx, ResponseItem::FunctionCallOutput { call_id: call_id.clone(), - output: FunctionCallOutputPayload { - body: FunctionCallOutputBody::Text("aborted".to_string()), - ..Default::default() - }, + output: FunctionCallOutputPayload::from_text("aborted".to_string()), }, )); } @@ -59,7 +55,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec) { idx, ResponseItem::CustomToolCallOutput { call_id: call_id.clone(), - output: "aborted".to_string(), + output: FunctionCallOutputPayload::from_text("aborted".to_string()), }, )); } @@ -82,10 +78,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec) { idx, ResponseItem::FunctionCallOutput { call_id: call_id.clone(), - output: FunctionCallOutputPayload { - body: FunctionCallOutputBody::Text("aborted".to_string()), - ..Default::default() - }, + output: FunctionCallOutputPayload::from_text("aborted".to_string()), }, )); } @@ -245,7 +238,8 @@ pub(crate) fn strip_images_when_unsupported( } *content = normalized_content; } - ResponseItem::FunctionCallOutput { output, .. } => { + ResponseItem::FunctionCallOutput { output, .. } + | ResponseItem::CustomToolCallOutput { output, .. } => { if let Some(content_items) = output.content_items_mut() { let mut normalized_content_items = Vec::with_capacity(content_items.len()); for content_item in content_items.iter() { diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index 54c5667d4d..63deb5c808 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -1,9 +1,11 @@ +use crate::codex::PreviousTurnSettings; use crate::codex::TurnContext; use crate::environment_context::EnvironmentContext; use crate::features::Feature; use crate::shell::Shell; use codex_execpolicy::Policy; use codex_protocol::config_types::Personality; +use codex_protocol::models::ContentItem; use codex_protocol::models::DeveloperInstructions; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; @@ -30,7 +32,7 @@ fn build_permissions_update_item( previous: Option<&TurnContextItem>, next: &TurnContext, exec_policy: &Policy, -) -> Option { +) -> Option { let prev = previous?; if prev.sandbox_policy == *next.sandbox_policy.get() && prev.approval_policy == next.approval_policy.value() @@ -38,37 +40,63 @@ fn build_permissions_update_item( return None; } - Some( - DeveloperInstructions::from_policy( - next.sandbox_policy.get(), - next.approval_policy.value(), - exec_policy, - &next.cwd, - next.features.enabled(Feature::RequestPermissions), - ) - .into(), - ) + Some(DeveloperInstructions::from_policy( + next.sandbox_policy.get(), + next.approval_policy.value(), + exec_policy, + &next.cwd, + next.features.enabled(Feature::RequestPermissions), + )) } fn build_collaboration_mode_update_item( previous: Option<&TurnContextItem>, next: &TurnContext, -) -> Option { +) -> Option { let prev = previous?; if prev.collaboration_mode.as_ref() != Some(&next.collaboration_mode) { // If the next mode has empty developer instructions, this returns None and we emit no // update, so prior collaboration instructions remain in the prompt history. - Some(DeveloperInstructions::from_collaboration_mode(&next.collaboration_mode)?.into()) + Some(DeveloperInstructions::from_collaboration_mode( + &next.collaboration_mode, + )?) } else { None } } +pub(crate) fn build_realtime_update_item( + previous: Option<&TurnContextItem>, + previous_turn_settings: Option<&PreviousTurnSettings>, + next: &TurnContext, +) -> Option { + match ( + previous.and_then(|item| item.realtime_active), + next.realtime_active, + ) { + (Some(true), false) => Some(DeveloperInstructions::realtime_end_message("inactive")), + (Some(false), true) | (None, true) => Some(DeveloperInstructions::realtime_start_message()), + (Some(true), true) | (Some(false), false) => None, + (None, false) => previous_turn_settings + .and_then(|settings| settings.realtime_active) + .filter(|realtime_active| *realtime_active) + .map(|_| DeveloperInstructions::realtime_end_message("inactive")), + } +} + +pub(crate) fn build_initial_realtime_item( + previous: Option<&TurnContextItem>, + previous_turn_settings: Option<&PreviousTurnSettings>, + next: &TurnContext, +) -> Option { + build_realtime_update_item(previous, previous_turn_settings, next) +} + fn build_personality_update_item( previous: Option<&TurnContextItem>, next: &TurnContext, personality_feature_enabled: bool, -) -> Option { +) -> Option { if !personality_feature_enabled { return None; } @@ -82,8 +110,7 @@ fn build_personality_update_item( { let model_info = &next.model_info; let personality_message = personality_message_for(model_info, personality); - personality_message - .map(|message| DeveloperInstructions::personality_spec_message(message).into()) + personality_message.map(DeveloperInstructions::personality_spec_message) } else { None } @@ -101,11 +128,11 @@ pub(crate) fn personality_message_for( } pub(crate) fn build_model_instructions_update_item( - previous_user_turn_model: Option<&str>, + previous_turn_settings: Option<&PreviousTurnSettings>, next: &TurnContext, -) -> Option { - let previous_model = previous_user_turn_model?; - if previous_model == next.model_info.slug { +) -> Option { + let previous_turn_settings = previous_turn_settings?; + if previous_turn_settings.model == next.model_info.slug { return None; } @@ -114,40 +141,67 @@ pub(crate) fn build_model_instructions_update_item( return None; } - Some(DeveloperInstructions::model_switch_message(model_instructions).into()) + Some(DeveloperInstructions::model_switch_message( + model_instructions, + )) +} + +pub(crate) fn build_developer_update_item(text_sections: Vec) -> Option { + build_text_message("developer", text_sections) +} + +pub(crate) fn build_contextual_user_message(text_sections: Vec) -> Option { + build_text_message("user", text_sections) +} + +fn build_text_message(role: &str, text_sections: Vec) -> Option { + if text_sections.is_empty() { + return None; + } + + let content = text_sections + .into_iter() + .map(|text| ContentItem::InputText { text }) + .collect(); + + Some(ResponseItem::Message { + id: None, + role: role.to_string(), + content, + end_turn: None, + phase: None, + }) } pub(crate) fn build_settings_update_items( previous: Option<&TurnContextItem>, - previous_user_turn_model: Option<&str>, + previous_turn_settings: Option<&PreviousTurnSettings>, next: &TurnContext, shell: &Shell, exec_policy: &Policy, personality_feature_enabled: bool, ) -> Vec { - let mut update_items = Vec::new(); + let contextual_user_message = build_environment_update_item(previous, next, shell); + let developer_update_sections = [ + // Keep model-switch instructions first so model-specific guidance is read before + // any other context diffs on this turn. + build_model_instructions_update_item(previous_turn_settings, next), + build_permissions_update_item(previous, next, exec_policy), + build_collaboration_mode_update_item(previous, next), + build_realtime_update_item(previous, previous_turn_settings, next), + build_personality_update_item(previous, next, personality_feature_enabled), + ] + .into_iter() + .flatten() + .map(DeveloperInstructions::into_text) + .collect(); - // Keep model-switch instructions first so model-specific guidance is read before - // any other context diffs on this turn. - if let Some(model_instructions_item) = - build_model_instructions_update_item(previous_user_turn_model, next) - { - update_items.push(model_instructions_item); + let mut items = Vec::with_capacity(2); + if let Some(developer_message) = build_developer_update_item(developer_update_sections) { + items.push(developer_message); } - if let Some(env_item) = build_environment_update_item(previous, next, shell) { - update_items.push(env_item); + if let Some(contextual_user_message) = contextual_user_message { + items.push(contextual_user_message); } - if let Some(permissions_item) = build_permissions_update_item(previous, next, exec_policy) { - update_items.push(permissions_item); - } - if let Some(collaboration_mode_item) = build_collaboration_mode_update_item(previous, next) { - update_items.push(collaboration_mode_item); - } - if let Some(personality_item) = - build_personality_update_item(previous, next, personality_feature_enabled) - { - update_items.push(personality_item); - } - - update_items + items } diff --git a/codex-rs/core/src/contextual_user_message.rs b/codex-rs/core/src/contextual_user_message.rs new file mode 100644 index 0000000000..51a2d23ea9 --- /dev/null +++ b/codex-rs/core/src/contextual_user_message.rs @@ -0,0 +1,139 @@ +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::ENVIRONMENT_CONTEXT_CLOSE_TAG; +use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; + +pub(crate) const AGENTS_MD_START_MARKER: &str = "# AGENTS.md instructions for "; +pub(crate) const AGENTS_MD_END_MARKER: &str = ""; +pub(crate) const SKILL_OPEN_TAG: &str = ""; +pub(crate) const SKILL_CLOSE_TAG: &str = ""; +pub(crate) const USER_SHELL_COMMAND_OPEN_TAG: &str = ""; +pub(crate) const USER_SHELL_COMMAND_CLOSE_TAG: &str = ""; +pub(crate) const TURN_ABORTED_OPEN_TAG: &str = ""; +pub(crate) const TURN_ABORTED_CLOSE_TAG: &str = ""; +pub(crate) const SUBAGENT_NOTIFICATION_OPEN_TAG: &str = ""; +pub(crate) const SUBAGENT_NOTIFICATION_CLOSE_TAG: &str = ""; + +#[derive(Clone, Copy)] +pub(crate) struct ContextualUserFragmentDefinition { + start_marker: &'static str, + end_marker: &'static str, +} + +impl ContextualUserFragmentDefinition { + pub(crate) const fn new(start_marker: &'static str, end_marker: &'static str) -> Self { + Self { + start_marker, + end_marker, + } + } + + pub(crate) fn matches_text(&self, text: &str) -> bool { + let trimmed = text.trim_start(); + let starts_with_marker = trimmed + .get(..self.start_marker.len()) + .is_some_and(|candidate| candidate.eq_ignore_ascii_case(self.start_marker)); + let trimmed = trimmed.trim_end(); + let ends_with_marker = trimmed + .get(trimmed.len().saturating_sub(self.end_marker.len())..) + .is_some_and(|candidate| candidate.eq_ignore_ascii_case(self.end_marker)); + starts_with_marker && ends_with_marker + } + + pub(crate) const fn start_marker(&self) -> &'static str { + self.start_marker + } + + pub(crate) const fn end_marker(&self) -> &'static str { + self.end_marker + } + + pub(crate) fn wrap(&self, body: String) -> String { + format!("{}\n{}\n{}", self.start_marker, body, self.end_marker) + } + + pub(crate) fn into_message(self, text: String) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { text }], + end_turn: None, + phase: None, + } + } +} + +pub(crate) const AGENTS_MD_FRAGMENT: ContextualUserFragmentDefinition = + ContextualUserFragmentDefinition::new(AGENTS_MD_START_MARKER, AGENTS_MD_END_MARKER); +pub(crate) const ENVIRONMENT_CONTEXT_FRAGMENT: ContextualUserFragmentDefinition = + ContextualUserFragmentDefinition::new( + ENVIRONMENT_CONTEXT_OPEN_TAG, + ENVIRONMENT_CONTEXT_CLOSE_TAG, + ); +pub(crate) const SKILL_FRAGMENT: ContextualUserFragmentDefinition = + ContextualUserFragmentDefinition::new(SKILL_OPEN_TAG, SKILL_CLOSE_TAG); +pub(crate) const USER_SHELL_COMMAND_FRAGMENT: ContextualUserFragmentDefinition = + ContextualUserFragmentDefinition::new( + USER_SHELL_COMMAND_OPEN_TAG, + USER_SHELL_COMMAND_CLOSE_TAG, + ); +pub(crate) const TURN_ABORTED_FRAGMENT: ContextualUserFragmentDefinition = + ContextualUserFragmentDefinition::new(TURN_ABORTED_OPEN_TAG, TURN_ABORTED_CLOSE_TAG); +pub(crate) const SUBAGENT_NOTIFICATION_FRAGMENT: ContextualUserFragmentDefinition = + ContextualUserFragmentDefinition::new( + SUBAGENT_NOTIFICATION_OPEN_TAG, + SUBAGENT_NOTIFICATION_CLOSE_TAG, + ); + +const CONTEXTUAL_USER_FRAGMENTS: &[ContextualUserFragmentDefinition] = &[ + AGENTS_MD_FRAGMENT, + ENVIRONMENT_CONTEXT_FRAGMENT, + SKILL_FRAGMENT, + USER_SHELL_COMMAND_FRAGMENT, + TURN_ABORTED_FRAGMENT, + SUBAGENT_NOTIFICATION_FRAGMENT, +]; + +pub(crate) fn is_contextual_user_fragment(content_item: &ContentItem) -> bool { + let ContentItem::InputText { text } = content_item else { + return false; + }; + CONTEXTUAL_USER_FRAGMENTS + .iter() + .any(|definition| definition.matches_text(text)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_environment_context_fragment() { + assert!(is_contextual_user_fragment(&ContentItem::InputText { + text: "\n/tmp\n".to_string(), + })); + } + + #[test] + fn detects_agents_instructions_fragment() { + assert!(is_contextual_user_fragment(&ContentItem::InputText { + text: "# AGENTS.md instructions for /tmp\n\n\nbody\n" + .to_string(), + })); + } + + #[test] + fn detects_subagent_notification_fragment_case_insensitively() { + assert!( + SUBAGENT_NOTIFICATION_FRAGMENT + .matches_text("{}") + ); + } + + #[test] + fn ignores_regular_user_text() { + assert!(!is_contextual_user_fragment(&ContentItem::InputText { + text: "hello".to_string(), + })); + } +} diff --git a/codex-rs/core/src/environment_context.rs b/codex-rs/core/src/environment_context.rs index 3c6df40adb..3e9ed871e3 100644 --- a/codex-rs/core/src/environment_context.rs +++ b/codex-rs/core/src/environment_context.rs @@ -1,9 +1,7 @@ use crate::codex::TurnContext; +use crate::contextual_user_message::ENVIRONMENT_CONTEXT_FRAGMENT; use crate::shell::Shell; -use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::ENVIRONMENT_CONTEXT_CLOSE_TAG; -use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::TurnContextNetworkItem; use serde::Deserialize; @@ -15,7 +13,10 @@ use std::path::PathBuf; pub(crate) struct EnvironmentContext { pub cwd: Option, pub shell: Shell, + pub current_date: Option, + pub timezone: Option, pub network: Option, + pub subagents: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] @@ -25,11 +26,21 @@ pub(crate) struct NetworkContext { } impl EnvironmentContext { - pub fn new(cwd: Option, shell: Shell, network: Option) -> Self { + pub fn new( + cwd: Option, + shell: Shell, + current_date: Option, + timezone: Option, + network: Option, + subagents: Option, + ) -> Self { Self { cwd, shell, + current_date, + timezone, network, + subagents, } } @@ -39,11 +50,17 @@ impl EnvironmentContext { pub fn equals_except_shell(&self, other: &EnvironmentContext) -> bool { let EnvironmentContext { cwd, + current_date, + timezone, network, - // should compare all fields except shell + subagents, shell: _, } = other; - self.cwd == *cwd && self.network == *network + self.cwd == *cwd + && self.current_date == *current_date + && self.timezone == *timezone + && self.network == *network + && self.subagents == *subagents } pub fn diff_from_turn_context_item( @@ -58,19 +75,24 @@ impl EnvironmentContext { } else { None }; + let current_date = after.current_date.clone(); + let timezone = after.timezone.clone(); let network = if before_network != after_network { after_network } else { before_network }; - EnvironmentContext::new(cwd, shell.clone(), network) + EnvironmentContext::new(cwd, shell.clone(), current_date, timezone, network, None) } pub fn from_turn_context(turn_context: &TurnContext, shell: &Shell) -> Self { Self::new( Some(turn_context.cwd.clone()), shell.clone(), + turn_context.current_date.clone(), + turn_context.timezone.clone(), Self::network_from_turn_context(turn_context), + None, ) } @@ -78,10 +100,20 @@ impl EnvironmentContext { Self::new( Some(turn_context_item.cwd.clone()), shell.clone(), + turn_context_item.current_date.clone(), + turn_context_item.timezone.clone(), Self::network_from_turn_context_item(turn_context_item), + None, ) } + pub fn with_subagents(mut self, subagents: String) -> Self { + if !subagents.is_empty() { + self.subagents = Some(subagents); + } + self + } + fn network_from_turn_context(turn_context: &TurnContext) -> Option { let network = turn_context .config @@ -122,13 +154,19 @@ impl EnvironmentContext { /// /// ``` pub fn serialize_to_xml(self) -> String { - let mut lines = vec![ENVIRONMENT_CONTEXT_OPEN_TAG.to_string()]; + let mut lines = Vec::new(); if let Some(cwd) = self.cwd { lines.push(format!(" {}", cwd.to_string_lossy())); } let shell_name = self.shell.name(); lines.push(format!(" {shell_name}")); + if let Some(current_date) = self.current_date { + lines.push(format!(" {current_date}")); + } + if let Some(timezone) = self.timezone { + lines.push(format!(" {timezone}")); + } match self.network { Some(ref network) => { lines.push(" ".to_string()); @@ -145,22 +183,18 @@ impl EnvironmentContext { // lines.push(" ".to_string()); } } - lines.push(ENVIRONMENT_CONTEXT_CLOSE_TAG.to_string()); - lines.join("\n") + if let Some(subagents) = self.subagents { + lines.push(" ".to_string()); + lines.extend(subagents.lines().map(|line| format!(" {line}"))); + lines.push(" ".to_string()); + } + ENVIRONMENT_CONTEXT_FRAGMENT.wrap(lines.join("\n")) } } impl From for ResponseItem { fn from(ec: EnvironmentContext) -> Self { - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: ec.serialize_to_xml(), - }], - end_turn: None, - phase: None, - } + ENVIRONMENT_CONTEXT_FRAGMENT.into_message(ec.serialize_to_xml()) } } @@ -183,12 +217,21 @@ mod tests { #[test] fn serialize_workspace_write_environment_context() { let cwd = test_path_buf("/repo"); - let context = EnvironmentContext::new(Some(cwd.clone()), fake_shell(), None); + let context = EnvironmentContext::new( + Some(cwd.clone()), + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + None, + None, + ); let expected = format!( r#" {cwd} bash + 2026-02-26 + America/Los_Angeles "#, cwd = cwd.display(), ); @@ -202,13 +245,21 @@ mod tests { allowed_domains: vec!["api.example.com".to_string(), "*.openai.com".to_string()], denied_domains: vec!["blocked.example.com".to_string()], }; - let context = - EnvironmentContext::new(Some(test_path_buf("/repo")), fake_shell(), Some(network)); + let context = EnvironmentContext::new( + Some(test_path_buf("/repo")), + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + Some(network), + None, + ); let expected = format!( r#" {} bash + 2026-02-26 + America/Los_Angeles api.example.com *.openai.com @@ -223,10 +274,19 @@ mod tests { #[test] fn serialize_read_only_environment_context() { - let context = EnvironmentContext::new(None, fake_shell(), None); + let context = EnvironmentContext::new( + None, + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + None, + None, + ); let expected = r#" bash + 2026-02-26 + America/Los_Angeles "#; assert_eq!(context.serialize_to_xml(), expected); @@ -234,10 +294,19 @@ mod tests { #[test] fn serialize_external_sandbox_environment_context() { - let context = EnvironmentContext::new(None, fake_shell(), None); + let context = EnvironmentContext::new( + None, + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + None, + None, + ); let expected = r#" bash + 2026-02-26 + America/Los_Angeles "#; assert_eq!(context.serialize_to_xml(), expected); @@ -245,10 +314,19 @@ mod tests { #[test] fn serialize_external_sandbox_with_restricted_network_environment_context() { - let context = EnvironmentContext::new(None, fake_shell(), None); + let context = EnvironmentContext::new( + None, + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + None, + None, + ); let expected = r#" bash + 2026-02-26 + America/Los_Angeles "#; assert_eq!(context.serialize_to_xml(), expected); @@ -256,10 +334,19 @@ mod tests { #[test] fn serialize_full_access_environment_context() { - let context = EnvironmentContext::new(None, fake_shell(), None); + let context = EnvironmentContext::new( + None, + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + None, + None, + ); let expected = r#" bash + 2026-02-26 + America/Los_Angeles "#; assert_eq!(context.serialize_to_xml(), expected); @@ -267,23 +354,65 @@ mod tests { #[test] fn equals_except_shell_compares_cwd() { - let context1 = EnvironmentContext::new(Some(PathBuf::from("/repo")), fake_shell(), None); - let context2 = EnvironmentContext::new(Some(PathBuf::from("/repo")), fake_shell(), None); + let context1 = EnvironmentContext::new( + Some(PathBuf::from("/repo")), + fake_shell(), + None, + None, + None, + None, + ); + let context2 = EnvironmentContext::new( + Some(PathBuf::from("/repo")), + fake_shell(), + None, + None, + None, + None, + ); assert!(context1.equals_except_shell(&context2)); } #[test] fn equals_except_shell_ignores_sandbox_policy() { - let context1 = EnvironmentContext::new(Some(PathBuf::from("/repo")), fake_shell(), None); - let context2 = EnvironmentContext::new(Some(PathBuf::from("/repo")), fake_shell(), None); + let context1 = EnvironmentContext::new( + Some(PathBuf::from("/repo")), + fake_shell(), + None, + None, + None, + None, + ); + let context2 = EnvironmentContext::new( + Some(PathBuf::from("/repo")), + fake_shell(), + None, + None, + None, + None, + ); assert!(context1.equals_except_shell(&context2)); } #[test] fn equals_except_shell_compares_cwd_differences() { - let context1 = EnvironmentContext::new(Some(PathBuf::from("/repo1")), fake_shell(), None); - let context2 = EnvironmentContext::new(Some(PathBuf::from("/repo2")), fake_shell(), None); + let context1 = EnvironmentContext::new( + Some(PathBuf::from("/repo1")), + fake_shell(), + None, + None, + None, + None, + ); + let context2 = EnvironmentContext::new( + Some(PathBuf::from("/repo2")), + fake_shell(), + None, + None, + None, + None, + ); assert!(!context1.equals_except_shell(&context2)); } @@ -298,6 +427,9 @@ mod tests { shell_snapshot: crate::shell::empty_shell_snapshot_receiver(), }, None, + None, + None, + None, ); let context2 = EnvironmentContext::new( Some(PathBuf::from("/repo")), @@ -307,8 +439,39 @@ mod tests { shell_snapshot: crate::shell::empty_shell_snapshot_receiver(), }, None, + None, + None, + None, ); assert!(context1.equals_except_shell(&context2)); } + + #[test] + fn serialize_environment_context_with_subagents() { + let context = EnvironmentContext::new( + Some(test_path_buf("/repo")), + fake_shell(), + Some("2026-02-26".to_string()), + Some("America/Los_Angeles".to_string()), + None, + Some("- agent-1: atlas\n- agent-2".to_string()), + ); + + let expected = format!( + r#" + {} + bash + 2026-02-26 + America/Los_Angeles + + - agent-1: atlas + - agent-2 + +"#, + test_path_buf("/repo").display() + ); + + assert_eq!(context.serialize_to_xml(), expected); + } } diff --git a/codex-rs/core/src/event_mapping.rs b/codex-rs/core/src/event_mapping.rs index 16f7e1c47a..afffdb0f1d 100644 --- a/codex-rs/core/src/event_mapping.rs +++ b/codex-rs/core/src/event_mapping.rs @@ -18,16 +18,15 @@ use codex_protocol::user_input::UserInput; use tracing::warn; use uuid::Uuid; -use crate::instructions::SkillInstructions; -use crate::instructions::UserInstructions; -use crate::session_prefix::is_session_prefix; -use crate::user_shell_command::is_user_shell_command_text; +use crate::contextual_user_message::is_contextual_user_fragment; use crate::web_search::web_search_action_detail; +pub(crate) fn is_contextual_user_message_content(message: &[ContentItem]) -> bool { + message.iter().any(is_contextual_user_fragment) +} + fn parse_user_message(message: &[ContentItem]) -> Option { - if UserInstructions::is_user_instructions(message) - || SkillInstructions::is_skill_instructions(message) - { + if is_contextual_user_message_content(message) { return None; } @@ -44,9 +43,6 @@ fn parse_user_message(message: &[ContentItem]) -> Option { { continue; } - if is_session_prefix(text) || is_user_shell_command_text(text) { - return None; - } content.push(UserInput::Text { text: text.clone(), // Model input content does not carry UI element ranges. @@ -59,9 +55,6 @@ fn parse_user_message(message: &[ContentItem]) -> Option { }); } ContentItem::OutputText { text } => { - if is_session_prefix(text) { - return None; - } warn!("Output text in user message: {}", text); } } @@ -299,7 +292,7 @@ mod tests { id: None, role: "user".to_string(), content: vec![ContentItem::InputText { - text: "test_text".to_string(), + text: "# AGENTS.md instructions for test_directory\n\n\ntest_text\n".to_string(), }], end_turn: None, phase: None, @@ -341,6 +334,22 @@ mod tests { end_turn: None, phase: None, }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ + ContentItem::InputText { + text: "ctx".to_string(), + }, + ContentItem::InputText { + text: + "# AGENTS.md instructions for dir\n\n\nbody\n" + .to_string(), + }, + ], + end_turn: None, + phase: None, + }, ]; for item in items { diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 1d1169303c..01c559c1c5 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -62,7 +62,6 @@ pub(crate) const MAX_EXEC_OUTPUT_DELTAS_PER_CALL: usize = 10_000; #[derive(Debug)] pub struct ExecParams { pub command: Vec, - pub original_command: String, pub cwd: PathBuf, pub expiration: ExecExpiration, pub env: HashMap, @@ -181,7 +180,6 @@ pub async fn process_exec_tool_call( let ExecParams { command, - original_command: _, cwd, mut env, expiration, @@ -221,6 +219,8 @@ pub async fn process_exec_tool_call( enforce_managed_network, network: network.as_ref(), sandbox_policy_cwd: sandbox_cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, codex_linux_sandbox_exe: codex_linux_sandbox_exe.as_ref(), use_linux_sandbox_bwrap, windows_sandbox_level, @@ -251,8 +251,6 @@ pub(crate) async fn execute_exec_env( } = env; let params = ExecParams { - original_command: shlex::try_join(command.iter().map(String::as_str)) - .unwrap_or_else(|_| command.join(" ")), command, cwd, expiration, @@ -523,9 +521,6 @@ pub(crate) mod errors { SandboxTransformError::SeatbeltUnavailable => CodexErr::UnsupportedOperation( "seatbelt sandbox is only available on macOS".to_string(), ), - SandboxTransformError::InvalidAdditionalPermissionsPath(path) => { - CodexErr::InvalidRequest(format!("invalid additional_permissions path: {path}")) - } } } } @@ -1125,8 +1120,6 @@ mod tests { ]; let env: HashMap = std::env::vars().collect(); let params = ExecParams { - original_command: shlex::try_join(command.iter().map(String::as_str)) - .unwrap_or_else(|_| command.join(" ")), command, cwd: std::env::current_dir()?, expiration: 500.into(), @@ -1180,8 +1173,6 @@ mod tests { let cancel_token = CancellationToken::new(); let cancel_tx = cancel_token.clone(); let params = ExecParams { - original_command: shlex::try_join(command.iter().map(String::as_str)) - .unwrap_or_else(|_| command.join(" ")), command, cwd: cwd.clone(), expiration: ExecExpiration::Cancellation(cancel_token), diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index e390996c4e..69a7cb933d 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -13,6 +13,7 @@ use codex_execpolicy::AmendError; use codex_execpolicy::Decision; use codex_execpolicy::Error as ExecPolicyRuleError; use codex_execpolicy::Evaluation; +use codex_execpolicy::MatchOptions; use codex_execpolicy::NetworkRuleProtocol; use codex_execpolicy::Policy; use codex_execpolicy::PolicyParser; @@ -221,7 +222,14 @@ impl ExecPolicyManager { used_complex_parsing, ) }; - let evaluation = exec_policy.check_multiple(commands.iter(), &exec_policy_fallback); + let match_options = MatchOptions { + resolve_host_executables: true, + }; + let evaluation = exec_policy.check_multiple_with_options( + commands.iter(), + &exec_policy_fallback, + &match_options, + ); let requested_amendment = derive_requested_execpolicy_amendment_from_prefix_rule( prefix_rule.as_ref(), @@ -229,6 +237,7 @@ impl ExecPolicyManager { exec_policy.as_ref(), &commands, &exec_policy_fallback, + &match_options, ); match evaluation.decision { @@ -472,17 +481,7 @@ pub async fn load_exec_policy(config_stack: &ConfigLayerStack) -> Result], exec_policy_fallback: &impl Fn(&[String]) -> Decision, + match_options: &MatchOptions, ) -> Option { let prefix_rule = prefix_rule?; if prefix_rule.is_empty() { @@ -666,6 +666,7 @@ fn derive_requested_execpolicy_amendment_from_prefix_rule( &amendment.command, commands, exec_policy_fallback, + match_options, ) { Some(amendment) } else { @@ -678,6 +679,7 @@ fn prefix_rule_would_approve_all_commands( prefix_rule: &[String], commands: &[Vec], exec_policy_fallback: &impl Fn(&[String]) -> Decision, + match_options: &MatchOptions, ) -> bool { let mut policy_with_prefix_rule = exec_policy.clone(); if policy_with_prefix_rule @@ -689,7 +691,7 @@ fn prefix_rule_would_approve_all_commands( commands.iter().all(|command| { policy_with_prefix_rule - .check(command, exec_policy_fallback) + .check_with_options(command, exec_policy_fallback, match_options) .decision == Decision::Allow }) @@ -827,6 +829,7 @@ mod tests { use pretty_assertions::assert_eq; use std::fs; use std::path::Path; + use std::path::PathBuf; use std::sync::Arc; use tempfile::tempdir; use toml::Value as TomlValue; @@ -846,6 +849,31 @@ mod tests { .expect("ConfigLayerStack") } + fn host_absolute_path(segments: &[&str]) -> String { + let mut path = if cfg!(windows) { + PathBuf::from(r"C:\") + } else { + PathBuf::from("/") + }; + for segment in segments { + path.push(segment); + } + path.to_string_lossy().into_owned() + } + + fn host_program_path(name: &str) -> String { + let executable_name = if cfg!(windows) { + format!("{name}.exe") + } else { + name.to_string() + }; + host_absolute_path(&["usr", "bin", &executable_name]) + } + + fn starlark_string(value: &str) -> String { + value.replace('\\', "\\\\").replace('"', "\\\"") + } + #[tokio::test] async fn returns_empty_policy_when_no_policy_files_exist() { let temp_dir = tempdir().expect("create temp dir"); @@ -949,6 +977,7 @@ mod tests { matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["rm".to_string()], decision: Decision::Forbidden, + resolved_program: None, justification: None, }], }, @@ -991,6 +1020,59 @@ mod tests { Ok(()) } + #[tokio::test] + async fn preserves_host_executables_when_requirements_overlay_is_present() -> anyhow::Result<()> + { + let temp_dir = tempdir()?; + let policy_dir = temp_dir.path().join(RULES_DIR_NAME); + fs::create_dir_all(&policy_dir)?; + let git_path = host_absolute_path(&["usr", "bin", "git"]); + let git_path_literal = starlark_string(&git_path); + fs::write( + policy_dir.join("host.rules"), + format!( + r#" +host_executable(name = "git", paths = ["{git_path_literal}"]) +"# + ), + )?; + + let mut requirements_exec_policy = Policy::empty(); + requirements_exec_policy.add_network_rule( + "blocked.example.com", + codex_execpolicy::NetworkRuleProtocol::Https, + Decision::Forbidden, + None, + )?; + + let requirements = ConfigRequirements { + exec_policy: Some(codex_config::Sourced::new( + codex_config::RequirementsExecPolicy::new(requirements_exec_policy), + codex_config::RequirementSource::Unknown, + )), + ..ConfigRequirements::default() + }; + let dot_codex_folder = AbsolutePathBuf::from_absolute_path(temp_dir.path())?; + let layer = ConfigLayerEntry::new( + ConfigLayerSource::Project { dot_codex_folder }, + TomlValue::Table(Default::default()), + ); + let config_stack = + ConfigLayerStack::new(vec![layer], requirements, ConfigRequirementsToml::default())?; + + let policy = load_exec_policy(&config_stack).await?; + + assert_eq!( + policy + .host_executables() + .get("git") + .expect("missing git host executable") + .as_ref(), + [AbsolutePathBuf::try_from(git_path)?] + ); + Ok(()) + } + #[tokio::test] async fn ignores_policies_outside_policy_dir() { let temp_dir = tempdir().expect("create temp dir"); @@ -1106,6 +1188,7 @@ mod tests { matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["rm".to_string()], decision: Decision::Forbidden, + resolved_program: None, justification: None, }], }, @@ -1117,6 +1200,7 @@ mod tests { matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["ls".to_string()], decision: Decision::Prompt, + resolved_program: None, justification: None, }], }, @@ -1335,6 +1419,115 @@ prefix_rule( ); } + #[tokio::test] + async fn absolute_path_exec_approval_requirement_matches_host_executable_rules() { + let git_path = host_program_path("git"); + let git_path_literal = starlark_string(&git_path); + let policy_src = format!( + r#" +host_executable(name = "git", paths = ["{git_path_literal}"]) +prefix_rule(pattern=["git"], decision="allow") +"# + ); + let mut parser = PolicyParser::new(); + parser + .parse("test.rules", &policy_src) + .expect("parse policy"); + let manager = ExecPolicyManager::new(Arc::new(parser.build())); + let command = vec![git_path, "status".to_string()]; + + let requirement = manager + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::new_read_only_policy(), + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) + .await; + + assert_eq!( + requirement, + ExecApprovalRequirement::Skip { + bypass_sandbox: true, + proposed_execpolicy_amendment: None, + } + ); + } + + #[tokio::test] + async fn absolute_path_exec_approval_requirement_ignores_disallowed_host_executable_paths() { + let allowed_git_path = host_program_path("git"); + let disallowed_git_path = host_absolute_path(&[ + "opt", + "homebrew", + "bin", + if cfg!(windows) { "git.exe" } else { "git" }, + ]); + let allowed_git_path_literal = starlark_string(&allowed_git_path); + let policy_src = format!( + r#" +host_executable(name = "git", paths = ["{allowed_git_path_literal}"]) +prefix_rule(pattern=["git"], decision="prompt") +"# + ); + let mut parser = PolicyParser::new(); + parser + .parse("test.rules", &policy_src) + .expect("parse policy"); + let manager = ExecPolicyManager::new(Arc::new(parser.build())); + let command = vec![disallowed_git_path, "status".to_string()]; + + let requirement = manager + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::new_read_only_policy(), + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }) + .await; + + assert_eq!( + requirement, + ExecApprovalRequirement::Skip { + bypass_sandbox: false, + proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)), + } + ); + } + + #[tokio::test] + async fn requested_prefix_rule_can_approve_absolute_path_commands() { + let command = vec![ + host_program_path("cargo"), + "install".to_string(), + "cargo-insta".to_string(), + ]; + let manager = ExecPolicyManager::default(); + + let requirement = manager + .create_exec_approval_requirement_for_command(ExecApprovalRequest { + command: &command, + approval_policy: AskForApproval::UnlessTrusted, + sandbox_policy: &SandboxPolicy::new_read_only_policy(), + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: Some(vec!["cargo".to_string(), "install".to_string()]), + }) + .await; + + assert_eq!( + requirement, + ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ + "cargo".to_string(), + "install".to_string(), + ])), + } + ); + } + #[tokio::test] async fn exec_approval_requirement_respects_approval_policy() { let policy_src = r#"prefix_rule(pattern=["rm"], decision="prompt")"#; @@ -1889,6 +2082,7 @@ prefix_rule( &Policy::empty(), &commands, &|_: &[String]| Decision::Allow, + &MatchOptions::default(), ) } @@ -1983,6 +2177,7 @@ prefix_rule( let matched_rules_prompt = vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["cargo".to_string()], decision: Decision::Prompt, + resolved_program: None, justification: None, }]; assert_eq!( @@ -1996,6 +2191,7 @@ prefix_rule( let matched_rules_allow = vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["cargo".to_string()], decision: Decision::Allow, + resolved_program: None, justification: None, }]; assert_eq!( @@ -2009,6 +2205,7 @@ prefix_rule( let matched_rules_forbidden = vec![RuleMatch::PrefixRuleMatch { matched_prefix: vec!["cargo".to_string()], decision: Decision::Forbidden, + resolved_program: None, justification: None, }]; assert_eq!( diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 546652ae60..d76c2dfc42 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -127,21 +127,28 @@ pub enum Feature { Collab, /// Enable apps. Apps, + /// Enable plugins. + Plugins, /// Route apps MCP calls through the configured gateway. AppsMcpGateway, /// Allow prompting and installing missing MCP dependencies. SkillMcpDependencyInstall, /// Prompt for missing skill env var dependencies. SkillEnvVarDependencyPrompt, - /// Emit skill approval test prompts/events. - SkillApproval, /// Steer feature flag - when enabled, Enter submits immediately instead of queuing. + /// Kept for config backward compatibility; behavior is always steer-enabled. Steer, + /// Allow request_user_input in Default collaboration mode. + DefaultModeRequestUserInput, /// Enable collaboration modes (Plan, Default). /// Kept for config backward compatibility; behavior is always collaboration-modes-enabled. CollaborationModes, /// Enable personality selection in the TUI. Personality, + /// Enable native artifact tools. + Artifact, + /// Enable Fast mode selection in the TUI and request layer. + FastMode, /// Enable voice transcription in the TUI composer. VoiceTranscription, /// Enable experimental realtime voice conversation mode in the TUI. @@ -462,7 +469,7 @@ pub const FEATURES: &[FeatureSpec] = &[ key: "js_repl", stage: Stage::Experimental { name: "JavaScript REPL", - menu_description: "Enable a persistent Node-backed JavaScript REPL for interactive website debugging and other inline JavaScript execution capabilities. Requires Node >= v24.13.1 installed.", + menu_description: "Enable a persistent Node-backed JavaScript REPL for interactive website debugging and other inline JavaScript execution capabilities. Requires Node >= v22.22.0 installed.", announcement: "NEW: JavaScript REPL is now available in /experimental. Enable it, then start a new chat or restart Codex to use it.", }, default_enabled: false, @@ -609,6 +616,12 @@ pub const FEATURES: &[FeatureSpec] = &[ }, default_enabled: false, }, + FeatureSpec { + id: Feature::Plugins, + key: "plugins", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::AppsMcpGateway, key: "apps_mcp_gateway", @@ -627,18 +640,18 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, - FeatureSpec { - id: Feature::SkillApproval, - key: "skill_approval", - stage: Stage::UnderDevelopment, - default_enabled: false, - }, FeatureSpec { id: Feature::Steer, key: "steer", - stage: Stage::Stable, + stage: Stage::Removed, default_enabled: true, }, + FeatureSpec { + id: Feature::DefaultModeRequestUserInput, + key: "default_mode_request_user_input", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::CollaborationModes, key: "collaboration_modes", @@ -651,6 +664,18 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Stable, default_enabled: true, }, + FeatureSpec { + id: Feature::Artifact, + key: "artifact", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, + FeatureSpec { + id: Feature::FastMode, + key: "fast_mode", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::VoiceTranscription, key: "voice_transcription", diff --git a/codex-rs/core/src/file_watcher.rs b/codex-rs/core/src/file_watcher.rs index ab0b175db1..f44a431568 100644 --- a/codex-rs/core/src/file_watcher.rs +++ b/codex-rs/core/src/file_watcher.rs @@ -23,7 +23,7 @@ use tokio::time::sleep_until; use tracing::warn; use crate::config::Config; -use crate::skills::loader::skill_roots_from_layer_stack_with_agents; +use crate::skills::SkillsManager; #[derive(Debug, Clone, PartialEq, Eq)] pub enum FileWatcherEvent { @@ -143,12 +143,16 @@ impl FileWatcher { self.tx.subscribe() } - pub(crate) fn register_config(self: &Arc, config: &Config) -> WatchRegistration { - let deduped_roots: HashSet = - skill_roots_from_layer_stack_with_agents(&config.config_layer_stack, &config.cwd) - .into_iter() - .map(|root| root.path) - .collect(); + pub(crate) fn register_config( + self: &Arc, + config: &Config, + skills_manager: &SkillsManager, + ) -> WatchRegistration { + let deduped_roots: HashSet = skills_manager + .skill_roots_for_config(config) + .into_iter() + .map(|root| root.path) + .collect(); let mut registered_roots: Vec = deduped_roots.into_iter().collect(); registered_roots.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str())); for root in ®istered_roots { diff --git a/codex-rs/core/src/instructions/mod.rs b/codex-rs/core/src/instructions/mod.rs index 9da925ac74..9f1d95d2f6 100644 --- a/codex-rs/core/src/instructions/mod.rs +++ b/codex-rs/core/src/instructions/mod.rs @@ -1,6 +1,5 @@ mod user_instructions; pub(crate) use user_instructions::SkillInstructions; -pub use user_instructions::USER_INSTRUCTIONS_OPEN_TAG_LEGACY; pub use user_instructions::USER_INSTRUCTIONS_PREFIX; pub(crate) use user_instructions::UserInstructions; diff --git a/codex-rs/core/src/instructions/user_instructions.rs b/codex-rs/core/src/instructions/user_instructions.rs index 525834847e..09e6e4c2f7 100644 --- a/codex-rs/core/src/instructions/user_instructions.rs +++ b/codex-rs/core/src/instructions/user_instructions.rs @@ -1,12 +1,12 @@ use serde::Deserialize; use serde::Serialize; -use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; -pub const USER_INSTRUCTIONS_OPEN_TAG_LEGACY: &str = ""; +use crate::contextual_user_message::AGENTS_MD_FRAGMENT; +use crate::contextual_user_message::SKILL_FRAGMENT; + pub const USER_INSTRUCTIONS_PREFIX: &str = "# AGENTS.md instructions for "; -pub const SKILL_INSTRUCTIONS_PREFIX: &str = " bool { - if let [ContentItem::InputText { text }] = message { - text.starts_with(USER_INSTRUCTIONS_PREFIX) - || text.starts_with(USER_INSTRUCTIONS_OPEN_TAG_LEGACY) - } else { - false - } + pub(crate) fn serialize_to_text(&self) -> String { + format!( + "{prefix}{directory}\n\n\n{contents}\n{suffix}", + prefix = AGENTS_MD_FRAGMENT.start_marker(), + directory = self.directory, + contents = self.text, + suffix = AGENTS_MD_FRAGMENT.end_marker(), + ) } } impl From for ResponseItem { fn from(ui: UserInstructions) -> Self { - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: format!( - "{USER_INSTRUCTIONS_PREFIX}{directory}\n\n\n{contents}\n", - directory = ui.directory, - contents = ui.text - ), - }], - end_turn: None, - phase: None, - } + AGENTS_MD_FRAGMENT.into_message(ui.serialize_to_text()) } } @@ -52,36 +41,21 @@ pub(crate) struct SkillInstructions { pub contents: String, } -impl SkillInstructions { - pub fn is_skill_instructions(message: &[ContentItem]) -> bool { - if let [ContentItem::InputText { text }] = message { - text.starts_with(SKILL_INSTRUCTIONS_PREFIX) - } else { - false - } - } -} +impl SkillInstructions {} impl From for ResponseItem { fn from(si: SkillInstructions) -> Self { - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: format!( - "\n{}\n{}\n{}\n", - si.name, si.path, si.contents - ), - }], - end_turn: None, - phase: None, - } + SKILL_FRAGMENT.into_message(SKILL_FRAGMENT.wrap(format!( + "{}\n{}\n{}", + si.name, si.path, si.contents + ))) } } #[cfg(test)] mod tests { use super::*; + use codex_protocol::models::ContentItem; use pretty_assertions::assert_eq; #[test] @@ -110,21 +84,10 @@ mod tests { #[test] fn test_is_user_instructions() { - assert!(UserInstructions::is_user_instructions( - &[ContentItem::InputText { - text: "# AGENTS.md instructions for test_directory\n\n\ntest_text\n".to_string(), - }] + assert!(AGENTS_MD_FRAGMENT.matches_text( + "# AGENTS.md instructions for test_directory\n\n\ntest_text\n" )); - assert!(UserInstructions::is_user_instructions(&[ - ContentItem::InputText { - text: "test_text".to_string(), - } - ])); - assert!(!UserInstructions::is_user_instructions(&[ - ContentItem::InputText { - text: "test_text".to_string(), - } - ])); + assert!(!AGENTS_MD_FRAGMENT.matches_text("test_text")); } #[test] @@ -154,16 +117,9 @@ mod tests { #[test] fn test_is_skill_instructions() { - assert!(SkillInstructions::is_skill_instructions(&[ - ContentItem::InputText { - text: "\ndemo-skill\nskills/demo/SKILL.md\nbody\n" - .to_string(), - } - ])); - assert!(!SkillInstructions::is_skill_instructions(&[ - ContentItem::InputText { - text: "regular text".to_string(), - } - ])); + assert!(SKILL_FRAGMENT.matches_text( + "\ndemo-skill\nskills/demo/SKILL.md\nbody\n" + )); + assert!(!SKILL_FRAGMENT.matches_text("regular text")); } } diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index c34f33f394..828bbe214a 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -27,6 +27,7 @@ pub mod config; pub mod config_loader; pub mod connectors; mod context_manager; +mod contextual_user_message; pub mod custom_prompts; pub mod env; mod environment_context; @@ -56,6 +57,7 @@ mod message_history; mod model_provider_info; pub mod path_utils; pub mod personality_migration; +pub mod plugins; mod sandbox_tags; pub mod sandboxing; mod session_prefix; @@ -114,6 +116,7 @@ pub use rollout::RolloutRecorder; pub use rollout::RolloutRecorderParams; pub use rollout::SESSIONS_SUBDIR; pub use rollout::SessionMeta; +pub use rollout::append_thread_name; pub use rollout::find_archived_thread_path_by_id_str; #[deprecated(note = "use find_thread_path_by_id_str")] pub use rollout::find_conversation_path_by_id_str; @@ -144,7 +147,6 @@ pub(crate) use codex_shell_command::powershell; pub use client::ModelClient; pub use client::ModelClientSession; -pub use client::ResponsesWebsocketVersion; pub use client::X_CODEX_TURN_METADATA_HEADER; pub use client::ws_version_from_features; pub use client_common::Prompt; diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 3abe4e9233..4edb45c462 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -5,6 +5,7 @@ pub(crate) use skill_dependencies::maybe_prompt_and_install_mcp_dependencies; use std::collections::HashMap; use std::env; use std::path::PathBuf; +use std::sync::Arc; use std::time::Duration; use async_channel::unbounded; @@ -25,6 +26,7 @@ use crate::mcp::auth::compute_auth_statuses; use crate::mcp_connection_manager::McpConnectionManager; use crate::mcp_connection_manager::SandboxState; use crate::mcp_connection_manager::codex_apps_tools_cache_key; +use crate::plugins::PluginsManager; const MCP_TOOL_NAME_PREFIX: &str = "mcp"; const MCP_TOOL_NAME_DELIMITER: &str = "__"; @@ -139,6 +141,7 @@ fn codex_apps_mcp_server_config(config: &Config, auth: Option<&CodexAuth>) -> Mc enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, } } @@ -159,12 +162,48 @@ pub(crate) fn with_codex_apps_mcp( servers } -pub(crate) fn effective_mcp_servers( +pub struct McpManager { + plugins_manager: Arc, +} + +impl McpManager { + pub fn new(plugins_manager: Arc) -> Self { + Self { plugins_manager } + } + + pub fn configured_servers(&self, config: &Config) -> HashMap { + configured_mcp_servers(config, self.plugins_manager.as_ref()) + } + + pub fn effective_servers( + &self, + config: &Config, + auth: Option<&CodexAuth>, + ) -> HashMap { + effective_mcp_servers(config, auth, self.plugins_manager.as_ref()) + } +} + +fn configured_mcp_servers( + config: &Config, + plugins_manager: &PluginsManager, +) -> HashMap { + let loaded_plugins = plugins_manager.plugins_for_config(config); + let mut servers = config.mcp_servers.get().clone(); + for (name, plugin_server) in loaded_plugins.effective_mcp_servers() { + servers.entry(name).or_insert(plugin_server); + } + servers +} + +fn effective_mcp_servers( config: &Config, auth: Option<&CodexAuth>, + plugins_manager: &PluginsManager, ) -> HashMap { + let servers = configured_mcp_servers(config, plugins_manager); with_codex_apps_mcp( - config.mcp_servers.get().clone(), + servers, config.features.enabled(Feature::Apps), auth, config, @@ -178,7 +217,8 @@ pub async fn collect_mcp_snapshot(config: &Config) -> McpListToolsResponseEvent config.cli_auth_credentials_store_mode, ); let auth = auth_manager.auth().await; - let mcp_servers = effective_mcp_servers(config, auth.as_ref()); + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let mcp_servers = mcp_manager.effective_servers(config, auth.as_ref()); if mcp_servers.is_empty() { return McpListToolsResponseEvent { tools: HashMap::new(), @@ -365,7 +405,38 @@ pub(crate) async fn collect_mcp_snapshot_from_manager( #[cfg(test)] mod tests { use super::*; + use crate::config::CONFIG_TOML_FILE; + use crate::config::ConfigBuilder; use pretty_assertions::assert_eq; + use std::fs; + use std::path::Path; + use toml::Value; + + fn write_file(path: &Path, contents: &str) { + fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap(); + fs::write(path, contents).unwrap(); + } + + fn plugin_config_toml(plugin_root: &Path) -> String { + let mut root = toml::map::Map::new(); + + let mut features = toml::map::Map::new(); + features.insert("plugins".to_string(), Value::Boolean(true)); + root.insert("features".to_string(), Value::Table(features)); + + let mut plugin = toml::map::Map::new(); + plugin.insert( + "path".to_string(), + Value::String(plugin_root.display().to_string()), + ); + plugin.insert("enabled".to_string(), Value::Boolean(true)); + + let mut plugins = toml::map::Map::new(); + plugins.insert("sample".to_string(), Value::Table(plugin)); + root.insert("plugins".to_string(), Value::Table(plugins)); + + toml::to_string(&Value::Table(root)).expect("plugin test config should serialize") + } fn make_tool(name: &str) -> Tool { Tool { @@ -541,4 +612,84 @@ mod tests { let expected_url = format!("{OPENAI_CONNECTORS_MCP_BASE_URL}{OPENAI_CONNECTORS_MCP_PATH}"); assert_eq!(url, &expected_url); } + + #[tokio::test] + async fn effective_mcp_servers_include_plugins_without_overriding_user_config() { + let codex_home = tempfile::tempdir().expect("tempdir"); + let plugin_root = codex_home.path().join("plugin-sample"); + write_file( + &plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ); + write_file( + &plugin_root.join(".mcp.json"), + r#"{ + "mcpServers": { + "sample": { + "type": "http", + "url": "https://plugin.example/mcp" + }, + "docs": { + "type": "http", + "url": "https://docs.example/mcp" + } + } +}"#, + ); + write_file( + &codex_home.path().join(CONFIG_TOML_FILE), + &plugin_config_toml(&plugin_root), + ); + + let mut config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .build() + .await + .expect("config should load"); + + let mut configured_servers = config.mcp_servers.get().clone(); + configured_servers.insert( + "sample".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url: "https://user.example/mcp".to_string(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }, + enabled: true, + required: false, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth_resource: None, + }, + ); + config + .mcp_servers + .set(configured_servers) + .expect("test config should accept MCP servers"); + + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let effective = mcp_manager.effective_servers(&config, None); + + let sample = effective.get("sample").expect("user server should exist"); + let docs = effective.get("docs").expect("plugin server should exist"); + + match &sample.transport { + McpServerTransportConfig::StreamableHttp { url, .. } => { + assert_eq!(url, "https://user.example/mcp"); + } + other => panic!("expected streamable http transport, got {other:?}"), + } + match &docs.transport { + McpServerTransportConfig::StreamableHttp { url, .. } => { + assert_eq!(url, "https://docs.example/mcp"); + } + other => panic!("expected streamable http transport, got {other:?}"), + } + } } diff --git a/codex-rs/core/src/mcp/skill_dependencies.rs b/codex-rs/core/src/mcp/skill_dependencies.rs index 1969bc6322..f15bb6ec57 100644 --- a/codex-rs/core/src/mcp/skill_dependencies.rs +++ b/codex-rs/core/src/mcp/skill_dependencies.rs @@ -13,7 +13,6 @@ use tracing::warn; use super::auth::McpOAuthLoginSupport; use super::auth::oauth_login_support; -use super::effective_mcp_servers; use crate::codex::Session; use crate::codex::TurnContext; use crate::config::Config; @@ -149,7 +148,10 @@ pub(crate) async fn maybe_prompt_and_install_mcp_dependencies( return; } - let installed = config.mcp_servers.get().clone(); + let installed = sess + .services + .mcp_manager + .configured_servers(config.as_ref()); let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed); if missing.is_empty() { return; @@ -178,7 +180,7 @@ pub(crate) async fn maybe_install_mcp_dependencies( } let codex_home = config.codex_home.clone(); - let installed = config.mcp_servers.get().clone(); + let installed = sess.services.mcp_manager.configured_servers(config); let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed); if missing.is_empty() { return; @@ -241,6 +243,7 @@ pub(crate) async fn maybe_install_mcp_dependencies( oauth_config.http_headers, oauth_config.env_http_headers, &[], + server_config.oauth_resource.as_deref(), config.mcp_oauth_callback_port, config.mcp_oauth_callback_url.as_deref(), ) @@ -253,7 +256,10 @@ pub(crate) async fn maybe_install_mcp_dependencies( // Refresh from the effective merged MCP map (global + repo + managed) and // overlay the updated global servers so we don't drop repo-scoped servers. let auth = sess.services.auth_manager.auth().await; - let mut refresh_servers = effective_mcp_servers(config, auth.as_ref()); + let mut refresh_servers = sess + .services + .mcp_manager + .effective_servers(config, auth.as_ref()); for (name, server_config) in &servers { refresh_servers .entry(name.clone()) @@ -387,6 +393,7 @@ fn mcp_dependency_to_server_config( enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }); } @@ -411,6 +418,7 @@ fn mcp_dependency_to_server_config( enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }); } @@ -434,7 +442,6 @@ mod tests { dependencies: Some(SkillDependencies { tools }), policy: None, permission_profile: None, - permissions: None, path_to_skills_md: PathBuf::from("skill"), scope: SkillScope::User, } @@ -468,6 +475,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); @@ -516,6 +524,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, )]); diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 12e3d325d3..2d22351d1f 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -2115,6 +2115,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, auth_status: McpAuthStatus::Unsupported, }; @@ -2162,6 +2163,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, auth_status: McpAuthStatus::Unsupported, }; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 63f83bb3f8..f76eddec6a 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -15,6 +15,7 @@ use crate::protocol::EventMsg; use crate::protocol::McpInvocation; use crate::protocol::McpToolCallBeginEvent; use crate::protocol::McpToolCallEndEvent; +use crate::state_db; use codex_protocol::mcp::CallToolResult; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputPayload; @@ -121,6 +122,7 @@ pub(crate) async fn handle_mcp_tool_call( }); notify_mcp_tool_call_event(sess.as_ref(), turn_context, tool_call_begin_event) .await; + maybe_mark_thread_memory_mode_polluted(sess.as_ref(), turn_context).await; let start = Instant::now(); let result = sess @@ -189,6 +191,7 @@ pub(crate) async fn handle_mcp_tool_call( invocation: invocation.clone(), }); notify_mcp_tool_call_event(sess.as_ref(), turn_context, tool_call_begin_event).await; + maybe_mark_thread_memory_mode_polluted(sess.as_ref(), turn_context).await; let start = Instant::now(); // Perform the tool call. @@ -224,6 +227,22 @@ pub(crate) async fn handle_mcp_tool_call( ResponseInputItem::McpToolCallOutput { call_id, result } } +async fn maybe_mark_thread_memory_mode_polluted(sess: &Session, turn_context: &TurnContext) { + if !turn_context + .config + .memories + .no_memories_if_mcp_or_web_search + { + return; + } + state_db::mark_thread_memory_mode_polluted( + sess.services.state_db.as_deref(), + sess.conversation_id, + "mcp_tool_call", + ) + .await; +} + fn sanitize_mcp_tool_result_for_model( supports_image_input: bool, result: Result, diff --git a/codex-rs/core/src/memories/README.md b/codex-rs/core/src/memories/README.md index c19a0c6806..0a49b58316 100644 --- a/codex-rs/core/src/memories/README.md +++ b/codex-rs/core/src/memories/README.md @@ -59,7 +59,14 @@ Phase 2 consolidates the latest stage-1 outputs into the filesystem memory artif What it does: - claims a single global phase-2 job (so only one consolidation runs at a time) -- loads a bounded set of the most recent stage-1 outputs from the state DB (the per-rollout memories produced by Phase 1, used as the consolidation input set) +- loads a bounded set of stage-1 outputs from the state DB using phase-2 + selection rules: + - ignores memories whose `last_usage` falls outside the configured + `max_unused_days` window + - for memories with no `last_usage`, falls back to `generated_at` so fresh + never-used memories can still be selected + - ranks eligible memories by `usage_count` first, then by the most recent + `last_usage` / `generated_at` - computes a completion watermark from the claimed watermark + newest input timestamps - syncs local memory artifacts under the memories root: - `raw_memories.md` (merged raw memories, latest first) @@ -70,11 +77,31 @@ What it does: If there is input, it then: - spawns an internal consolidation sub-agent +- builds the Phase 2 prompt with a diff of the current Phase 1 input + selection versus the last successful Phase 2 selection (`added`, + `retained`, `removed`) - runs it with no approvals, no network, and local write access only - disables collab for that agent (to prevent recursive delegation) - watches the agent status and heartbeats the global job lease while it runs - marks the phase-2 job success/failure in the state DB when the agent finishes +Selection diff behavior: + +- successful Phase 2 runs mark the exact stage-1 snapshots they consumed with + `selected_for_phase2 = 1` and persist the matching + `selected_for_phase2_source_updated_at` +- Phase 1 upserts preserve the previous `selected_for_phase2` baseline until + the next successful Phase 2 run rewrites it +- the next Phase 2 run compares the current top-N stage-1 inputs against that + prior snapshot selection to label inputs as `added` or `retained`; a + refreshed thread stays `added` until Phase 2 successfully selects its newer + snapshot +- rows that were previously selected but still exist outside the current top-N + selection are surfaced as `removed` +- before the agent starts, local `rollout_summaries/` and `raw_memories.md` + keep the union of the current selection and the previous successful + selection, so removed-thread evidence stays available during forgetting + Watermark behavior: - The global phase-2 job claim includes an input watermark representing the latest input timestamp known when the job was claimed. diff --git a/codex-rs/core/src/memories/phase1.rs b/codex-rs/core/src/memories/phase1.rs index d2fb6d11f4..7e1aa46136 100644 --- a/codex-rs/core/src/memories/phase1.rs +++ b/codex-rs/core/src/memories/phase1.rs @@ -13,6 +13,7 @@ use crate::rollout::policy::should_persist_response_item_for_memories; use codex_api::ResponseEvent; use codex_otel::OtelManager; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; +use codex_protocol::config_types::ServiceTier; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; @@ -36,6 +37,7 @@ pub(in crate::memories) struct RequestContext { pub(in crate::memories) otel_manager: OtelManager, pub(in crate::memories) reasoning_effort: Option, pub(in crate::memories) reasoning_summary: ReasoningSummaryConfig, + pub(in crate::memories) service_tier: Option, pub(in crate::memories) turn_metadata_header: Option, } @@ -144,6 +146,7 @@ impl RequestContext { otel_manager: turn_context.otel_manager.clone(), reasoning_effort: Some(phase_one::REASONING_EFFORT), reasoning_summary: turn_context.reasoning_summary, + service_tier: turn_context.config.service_tier, } } } @@ -193,7 +196,7 @@ async fn claim_startup_jobs( async fn build_request_context(session: &Arc, config: &Config) -> RequestContext { let model_name = config .memories - .phase_1_model + .extract_model .clone() .unwrap_or(phase_one::MODEL.to_string()); let model = session @@ -322,6 +325,7 @@ mod job { &stage_one_context.otel_manager, stage_one_context.reasoning_effort, stage_one_context.reasoning_summary, + stage_one_context.service_tier, stage_one_context.turn_metadata_header.as_deref(), ) .await?; diff --git a/codex-rs/core/src/memories/phase2.rs b/codex-rs/core/src/memories/phase2.rs index 6794a4574f..ff13e4f64c 100644 --- a/codex-rs/core/src/memories/phase2.rs +++ b/codex-rs/core/src/memories/phase2.rs @@ -8,6 +8,7 @@ use crate::memories::metrics; use crate::memories::phase_two; use crate::memories::prompts::build_consolidation_prompt; use crate::memories::storage::rebuild_raw_memories_file_from_memories; +use crate::memories::storage::rollout_summary_file_stem; use crate::memories::storage::sync_rollout_summaries_from_memories; use codex_config::Constrained; use codex_protocol::ThreadId; @@ -17,8 +18,10 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; use codex_protocol::user_input::UserInput; +use codex_state::Stage1Output; use codex_state::StateRuntime; use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::HashSet; use std::sync::Arc; use std::time::Duration; use tokio::sync::watch; @@ -49,7 +52,8 @@ pub(super) async fn run(session: &Arc, config: Arc) { return; }; let root = memory_root(&config.codex_home); - let max_raw_memories = config.memories.max_raw_memories_for_global; + let max_raw_memories = config.memories.max_raw_memories_for_consolidation; + let max_unused_days = config.memories.max_unused_days; // 1. Claim the job. let claim = match job::claim(session, db).await { @@ -73,21 +77,27 @@ pub(super) async fn run(session: &Arc, config: Arc) { }; // 3. Query the memories - let raw_memories = match db.list_stage1_outputs_for_global(max_raw_memories).await { - Ok(memories) => memories, + let selection = match db + .get_phase2_input_selection(max_raw_memories, max_unused_days) + .await + { + Ok(selection) => selection, Err(err) => { tracing::error!("failed to list stage1 outputs from global: {}", err); job::failed(session, db, &claim, "failed_load_stage1_outputs").await; return; } }; + let raw_memories = selection.selected.to_vec(); + let artifact_memories = artifact_memories_for_phase2(&selection); let new_watermark = get_watermark(claim.watermark, &raw_memories); // 4. Update the file system by syncing the raw memories with the one extracted from DB at // step 3 // [`rollout_summaries/`] if let Err(err) = - sync_rollout_summaries_from_memories(&root, &raw_memories, max_raw_memories).await + sync_rollout_summaries_from_memories(&root, &artifact_memories, artifact_memories.len()) + .await { tracing::error!("failed syncing local memory artifacts for global consolidation: {err}"); job::failed(session, db, &claim, "failed_sync_artifacts").await; @@ -95,7 +105,8 @@ pub(super) async fn run(session: &Arc, config: Arc) { } // [`raw_memories.md`] if let Err(err) = - rebuild_raw_memories_file_from_memories(&root, &raw_memories, max_raw_memories).await + rebuild_raw_memories_file_from_memories(&root, &artifact_memories, artifact_memories.len()) + .await { tracing::error!("failed syncing local memory artifacts for global consolidation: {err}"); job::failed(session, db, &claim, "failed_rebuild_raw_memories").await; @@ -103,12 +114,20 @@ pub(super) async fn run(session: &Arc, config: Arc) { } if raw_memories.is_empty() { // We check only after sync of the file system. - job::succeed(session, db, &claim, new_watermark, "succeeded_no_input").await; + job::succeed( + session, + db, + &claim, + new_watermark, + &[], + "succeeded_no_input", + ) + .await; return; } // 5. Spawn the agent - let prompt = agent::get_prompt(config); + let prompt = agent::get_prompt(config, &selection); let source = SessionSource::SubAgent(SubAgentSource::MemoryConsolidation); let thread_id = match session .services @@ -129,6 +148,7 @@ pub(super) async fn run(session: &Arc, config: Arc) { session, claim, new_watermark, + raw_memories.clone(), thread_id, phase_two_e2e_timer, ); @@ -140,6 +160,22 @@ pub(super) async fn run(session: &Arc, config: Arc) { emit_metrics(session, counters); } +fn artifact_memories_for_phase2( + selection: &codex_state::Phase2InputSelection, +) -> Vec { + let mut seen = HashSet::new(); + let mut memories = selection.selected.clone(); + for memory in &selection.selected { + seen.insert(rollout_summary_file_stem(memory)); + } + for memory in &selection.previous_selected { + if seen.insert(rollout_summary_file_stem(memory)) { + memories.push(memory.clone()); + } + } + memories +} + mod job { use super::*; @@ -205,6 +241,7 @@ mod job { db: &StateRuntime, claim: &Claim, completion_watermark: i64, + selected_outputs: &[codex_state::Stage1Output], reason: &'static str, ) { session.services.otel_manager.counter( @@ -213,7 +250,7 @@ mod job { &[("status", reason)], ); let _ = db - .mark_global_phase2_job_succeeded(&claim.token, completion_watermark) + .mark_global_phase2_job_succeeded(&claim.token, completion_watermark, selected_outputs) .await; } } @@ -257,7 +294,7 @@ mod agent { agent_config.model = Some( config .memories - .phase_2_model + .consolidation_model .clone() .unwrap_or(phase_two::MODEL.to_string()), ); @@ -266,9 +303,12 @@ mod agent { Some(agent_config) } - pub(super) fn get_prompt(config: Arc) -> Vec { + pub(super) fn get_prompt( + config: Arc, + selection: &codex_state::Phase2InputSelection, + ) -> Vec { let root = memory_root(&config.codex_home); - let prompt = build_consolidation_prompt(&root); + let prompt = build_consolidation_prompt(&root, selection); vec![UserInput::Text { text: prompt, text_elements: vec![], @@ -280,6 +320,7 @@ mod agent { session: &Arc, claim: Claim, new_watermark: i64, + selected_outputs: Vec, thread_id: ThreadId, phase_two_e2e_timer: Option, ) { @@ -316,7 +357,15 @@ mod agent { if let Some(token_usage) = agent_control.get_total_token_usage(thread_id).await { emit_token_usage_metrics(&session, &token_usage); } - job::succeed(&session, &db, &claim, new_watermark, "succeeded").await; + job::succeed( + &session, + &db, + &claim, + new_watermark, + &selected_outputs, + "succeeded", + ) + .await; } else { job::failed(&session, &db, &claim, "failed_agent").await; } diff --git a/codex-rs/core/src/memories/prompts.rs b/codex-rs/core/src/memories/prompts.rs index 9a3ea6a92d..35cfe1edf0 100644 --- a/codex-rs/core/src/memories/prompts.rs +++ b/codex-rs/core/src/memories/prompts.rs @@ -1,19 +1,123 @@ use crate::memories::memory_root; use crate::memories::phase_one; +use crate::memories::storage::rollout_summary_file_stem_from_parts; use crate::truncate::TruncationPolicy; use crate::truncate::truncate_text; +use askama::Template; use codex_protocol::openai_models::ModelInfo; +use codex_state::Phase2InputSelection; +use codex_state::Stage1Output; +use codex_state::Stage1OutputRef; use std::path::Path; use tokio::fs; +use tracing::warn; -const CONSOLIDATION_TEMPLATE: &str = include_str!("../../templates/memories/consolidation.md"); -const STAGE_ONE_INPUT_TEMPLATE: &str = include_str!("../../templates/memories/stage_one_input.md"); -const READ_PATH_TEMPLATE: &str = include_str!("../../templates/memories/read_path.md"); +#[derive(Template)] +#[template(path = "memories/consolidation.md", escape = "none")] +struct ConsolidationPromptTemplate<'a> { + memory_root: &'a str, + phase2_input_selection: &'a str, +} + +#[derive(Template)] +#[template(path = "memories/stage_one_input.md", escape = "none")] +struct StageOneInputTemplate<'a> { + rollout_path: &'a str, + rollout_cwd: &'a str, + rollout_contents: &'a str, +} + +#[derive(Template)] +#[template(path = "memories/read_path.md", escape = "none")] +struct MemoryToolDeveloperInstructionsTemplate<'a> { + base_path: &'a str, + memory_summary: &'a str, +} /// Builds the consolidation subagent prompt for a specific memory root. -pub(super) fn build_consolidation_prompt(memory_root: &Path) -> String { +pub(super) fn build_consolidation_prompt( + memory_root: &Path, + selection: &Phase2InputSelection, +) -> String { let memory_root = memory_root.display().to_string(); - CONSOLIDATION_TEMPLATE.replace("{{ memory_root }}", &memory_root) + let phase2_input_selection = render_phase2_input_selection(selection); + let template = ConsolidationPromptTemplate { + memory_root: &memory_root, + phase2_input_selection: &phase2_input_selection, + }; + template.render().unwrap_or_else(|err| { + warn!("failed to render memories consolidation prompt template: {err}"); + format!( + "## Memory Phase 2 (Consolidation)\nConsolidate Codex memories in: {memory_root}\n\n{phase2_input_selection}" + ) + }) +} + +fn render_phase2_input_selection(selection: &Phase2InputSelection) -> String { + let retained = selection.retained_thread_ids.len(); + let added = selection.selected.len().saturating_sub(retained); + let selected = if selection.selected.is_empty() { + "- none".to_string() + } else { + selection + .selected + .iter() + .map(|item| { + render_selected_input_line( + item, + selection.retained_thread_ids.contains(&item.thread_id), + ) + }) + .collect::>() + .join("\n") + }; + let removed = if selection.removed.is_empty() { + "- none".to_string() + } else { + selection + .removed + .iter() + .map(render_removed_input_line) + .collect::>() + .join("\n") + }; + + format!( + "- selected inputs this run: {}\n- newly added since the last successful Phase 2 run: {added}\n- retained from the last successful Phase 2 run: {retained}\n- removed from the last successful Phase 2 run: {}\n\nCurrent selected Phase 1 inputs:\n{selected}\n\nRemoved from the last successful Phase 2 selection:\n{removed}\n", + selection.selected.len(), + selection.removed.len(), + ) +} + +fn render_selected_input_line(item: &Stage1Output, retained: bool) -> String { + let status = if retained { "retained" } else { "added" }; + let rollout_summary_file = format!( + "rollout_summaries/{}.md", + rollout_summary_file_stem_from_parts( + item.thread_id, + item.source_updated_at, + item.rollout_slug.as_deref(), + ) + ); + format!( + "- [{status}] thread_id={}, rollout_summary_file={rollout_summary_file}", + item.thread_id + ) +} + +fn render_removed_input_line(item: &Stage1OutputRef) -> String { + let rollout_summary_file = format!( + "rollout_summaries/{}.md", + rollout_summary_file_stem_from_parts( + item.thread_id, + item.source_updated_at, + item.rollout_slug.as_deref(), + ) + ); + format!( + "- thread_id={}, rollout_summary_file={rollout_summary_file}", + item.thread_id + ) } /// Builds the stage-1 user message containing rollout metadata and content. @@ -40,10 +144,12 @@ pub(super) fn build_stage_one_input_message( let rollout_path = rollout_path.display().to_string(); let rollout_cwd = rollout_cwd.display().to_string(); - Ok(STAGE_ONE_INPUT_TEMPLATE - .replace("{{ rollout_path }}", &rollout_path) - .replace("{{ rollout_cwd }}", &rollout_cwd) - .replace("{{ rollout_contents }}", &truncated_rollout_contents)) + Ok(StageOneInputTemplate { + rollout_path: &rollout_path, + rollout_cwd: &rollout_cwd, + rollout_contents: &truncated_rollout_contents, + } + .render()?) } /// Build prompt used for read path. This prompt must be added to the developer instructions. In @@ -65,11 +171,11 @@ pub(crate) async fn build_memory_tool_developer_instructions(codex_home: &Path) return None; } let base_path = base_path.display().to_string(); - Some( - READ_PATH_TEMPLATE - .replace("{{ base_path }}", &base_path) - .replace("{{ memory_summary }}", &memory_summary), - ) + let template = MemoryToolDeveloperInstructionsTemplate { + base_path: &base_path, + memory_summary: &memory_summary, + }; + template.render().ok() } #[cfg(test)] diff --git a/codex-rs/core/src/memories/storage.rs b/codex-rs/core/src/memories/storage.rs index 1a07dbe9b8..68f75a095f 100644 --- a/codex-rs/core/src/memories/storage.rs +++ b/codex-rs/core/src/memories/storage.rs @@ -13,21 +13,21 @@ use crate::memories::rollout_summaries_dir; pub(super) async fn rebuild_raw_memories_file_from_memories( root: &Path, memories: &[Stage1Output], - max_raw_memories_for_global: usize, + max_raw_memories_for_consolidation: usize, ) -> std::io::Result<()> { ensure_layout(root).await?; - rebuild_raw_memories_file(root, memories, max_raw_memories_for_global).await + rebuild_raw_memories_file(root, memories, max_raw_memories_for_consolidation).await } /// Syncs canonical rollout summary files from DB-backed stage-1 output rows. pub(super) async fn sync_rollout_summaries_from_memories( root: &Path, memories: &[Stage1Output], - max_raw_memories_for_global: usize, + max_raw_memories_for_consolidation: usize, ) -> std::io::Result<()> { ensure_layout(root).await?; - let retained = retained_memories(memories, max_raw_memories_for_global); + let retained = retained_memories(memories, max_raw_memories_for_consolidation); let keep = retained .iter() .map(rollout_summary_file_stem) @@ -62,9 +62,9 @@ pub(super) async fn sync_rollout_summaries_from_memories( async fn rebuild_raw_memories_file( root: &Path, memories: &[Stage1Output], - max_raw_memories_for_global: usize, + max_raw_memories_for_consolidation: usize, ) -> std::io::Result<()> { - let retained = retained_memories(memories, max_raw_memories_for_global); + let retained = retained_memories(memories, max_raw_memories_for_consolidation); let mut body = String::from("# Raw Memories\n\n"); if retained.is_empty() { @@ -82,6 +82,8 @@ async fn rebuild_raw_memories_file( ) .map_err(raw_memories_format_error)?; writeln!(body, "cwd: {}", memory.cwd.display()).map_err(raw_memories_format_error)?; + writeln!(body, "rollout_path: {}", memory.rollout_path.display()) + .map_err(raw_memories_format_error)?; let rollout_summary_file = format!("{}.md", rollout_summary_file_stem(memory)); writeln!(body, "rollout_summary_file: {rollout_summary_file}") .map_err(raw_memories_format_error)?; @@ -138,7 +140,12 @@ async fn write_rollout_summary_for_thread( memory.source_updated_at.to_rfc3339() ) .map_err(rollout_summary_format_error)?; + writeln!(body, "rollout_path: {}", memory.rollout_path.display()) + .map_err(rollout_summary_format_error)?; writeln!(body, "cwd: {}", memory.cwd.display()).map_err(rollout_summary_format_error)?; + if let Some(git_branch) = memory.git_branch.as_deref() { + writeln!(body, "git_branch: {git_branch}").map_err(rollout_summary_format_error)?; + } writeln!(body).map_err(rollout_summary_format_error)?; body.push_str(&memory.rollout_summary); body.push('\n'); @@ -148,9 +155,9 @@ async fn write_rollout_summary_for_thread( fn retained_memories( memories: &[Stage1Output], - max_raw_memories_for_global: usize, + max_raw_memories_for_consolidation: usize, ) -> &[Stage1Output] { - &memories[..memories.len().min(max_raw_memories_for_global)] + &memories[..memories.len().min(max_raw_memories_for_consolidation)] } fn raw_memories_format_error(err: std::fmt::Error) -> std::io::Error { @@ -267,7 +274,9 @@ mod tests { raw_memory: "raw memory".to_string(), rollout_summary: "summary".to_string(), rollout_slug: rollout_slug.map(ToString::to_string), + rollout_path: PathBuf::from("/tmp/rollout.jsonl"), cwd: PathBuf::from("/tmp/workspace"), + git_branch: None, generated_at: Utc.timestamp_opt(124, 0).single().expect("timestamp"), } } diff --git a/codex-rs/core/src/memories/tests.rs b/codex-rs/core/src/memories/tests.rs index b47e7f8aab..0ebc0b8f16 100644 --- a/codex-rs/core/src/memories/tests.rs +++ b/codex-rs/core/src/memories/tests.rs @@ -1,6 +1,6 @@ use super::storage::rebuild_raw_memories_file_from_memories; use super::storage::sync_rollout_summaries_from_memories; -use crate::config::types::DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL; +use crate::config::types::DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION; use crate::memories::ensure_layout; use crate::memories::memory_root; use crate::memories::raw_memories_file; @@ -86,21 +86,23 @@ async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only raw_memory: "raw memory".to_string(), rollout_summary: "short summary".to_string(), rollout_slug: None, + rollout_path: PathBuf::from("/tmp/rollout-100.jsonl"), cwd: PathBuf::from("/tmp/workspace"), + git_branch: None, generated_at: Utc.timestamp_opt(101, 0).single().expect("timestamp"), }]; sync_rollout_summaries_from_memories( &root, &memories, - DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL, + DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, ) .await .expect("sync rollout summaries"); rebuild_raw_memories_file_from_memories( &root, &memories, - DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL, + DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, ) .await .expect("rebuild raw memories"); @@ -135,6 +137,7 @@ async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only assert!(raw_memories.contains("raw memory")); assert!(raw_memories.contains(&keep_id)); assert!(raw_memories.contains("cwd: /tmp/workspace")); + assert!(raw_memories.contains("rollout_path: /tmp/rollout-100.jsonl")); assert!(raw_memories.contains(&format!( "rollout_summary_file: {canonical_rollout_summary_file}" ))); @@ -150,6 +153,10 @@ async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only .find("cwd: /tmp/workspace") .map(|offset| thread_pos + offset) .expect("cwd should exist after thread header"); + let rollout_path_pos = raw_memories[thread_pos..] + .find("rollout_path: /tmp/rollout-100.jsonl") + .map(|offset| thread_pos + offset) + .expect("rollout_path should exist after thread header"); let file_pos = raw_memories[thread_pos..] .find(&format!( "rollout_summary_file: {canonical_rollout_summary_file}" @@ -158,7 +165,8 @@ async fn sync_rollout_summaries_and_raw_memories_file_keeps_latest_memories_only .expect("rollout_summary_file should exist after thread header"); assert!(thread_pos < updated_pos); assert!(updated_pos < cwd_pos); - assert!(cwd_pos < file_pos); + assert!(cwd_pos < rollout_path_pos); + assert!(rollout_path_pos < file_pos); } #[tokio::test] @@ -184,14 +192,16 @@ async fn sync_rollout_summaries_uses_timestamp_hash_and_sanitized_slug_filename( raw_memory: "raw memory".to_string(), rollout_summary: "short summary".to_string(), rollout_slug: Some("Unsafe Slug/With Spaces & Symbols + EXTRA_LONG_12345".to_string()), + rollout_path: PathBuf::from("/tmp/rollout-200.jsonl"), cwd: PathBuf::from("/tmp/workspace"), + git_branch: Some("feature/memory-branch".to_string()), generated_at: Utc.timestamp_opt(201, 0).single().expect("timestamp"), }]; sync_rollout_summaries_from_memories( &root, &memories, - DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL, + DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, ) .await .expect("sync rollout summaries"); @@ -239,6 +249,8 @@ async fn sync_rollout_summaries_uses_timestamp_hash_and_sanitized_slug_filename( .await .expect("read rollout summary"); assert!(summary.contains(&format!("thread_id: {thread_id}"))); + assert!(summary.contains("rollout_path: /tmp/rollout-200.jsonl")); + assert!(summary.contains("git_branch: feature/memory-branch")); assert!( !tokio::fs::try_exists(&stale_unslugged_path) .await @@ -283,21 +295,23 @@ task_outcome: success .to_string(), rollout_summary: "short summary".to_string(), rollout_slug: Some("Unsafe Slug/With Spaces & Symbols + EXTRA_LONG_12345".to_string()), + rollout_path: PathBuf::from("/tmp/rollout-200.jsonl"), cwd: PathBuf::from("/tmp/workspace"), + git_branch: None, generated_at: Utc.timestamp_opt(201, 0).single().expect("timestamp"), }]; sync_rollout_summaries_from_memories( &root, &memories, - DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL, + DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, ) .await .expect("sync rollout summaries"); rebuild_raw_memories_file_from_memories( &root, &memories, - DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_GLOBAL, + DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, ) .await .expect("rebuild raw memories"); @@ -316,6 +330,12 @@ task_outcome: success let raw_memories = tokio::fs::read_to_string(raw_memories_file(&root)) .await .expect("read raw memories"); + let summary = tokio::fs::read_to_string( + rollout_summaries_dir(&root).join(canonical_rollout_summary_file), + ) + .await + .expect("read rollout summary"); + assert!(summary.contains("rollout_path: /tmp/rollout-200.jsonl")); assert!(raw_memories.contains(&format!( "rollout_summary_file: {canonical_rollout_summary_file}" ))); @@ -360,7 +380,9 @@ mod phase2 { raw_memory: "raw memory".to_string(), rollout_summary: "rollout summary".to_string(), rollout_slug: None, + rollout_path: PathBuf::from("/tmp/rollout-summary.jsonl"), cwd: PathBuf::from("/tmp/workspace"), + git_branch: None, generated_at: chrono::DateTime::::from_timestamp(source_updated_at + 1, 0) .expect("valid generated_at timestamp"), } @@ -542,7 +564,7 @@ mod phase2 { #[tokio::test] async fn dispatch_reclaims_stale_global_lock_and_starts_consolidation() { let harness = DispatchHarness::new().await; - harness.seed_stage1_output(100).await; + harness.seed_stage1_output(Utc::now().timestamp()).await; let stale_claim = harness .state_db @@ -556,12 +578,18 @@ mod phase2 { phase2::run(&harness.session, Arc::clone(&harness.config)).await; - let running_claim = harness + let post_dispatch_claim = harness .state_db .try_claim_global_phase2_job(ThreadId::new(), 3_600) .await - .expect("claim while running"); - pretty_assertions::assert_eq!(running_claim, Phase2JobClaimOutcome::SkippedRunning); + .expect("claim after stale lock dispatch"); + assert!( + matches!( + post_dispatch_claim, + Phase2JobClaimOutcome::SkippedRunning | Phase2JobClaimOutcome::SkippedNotDirty + ), + "stale-lock dispatch should either keep the reclaimed job running or finish it before re-claim" + ); let user_input_ops = harness.user_input_ops_count(); pretty_assertions::assert_eq!(user_input_ops, 1); diff --git a/codex-rs/core/src/models_manager/collaboration_mode_presets.rs b/codex-rs/core/src/models_manager/collaboration_mode_presets.rs index 7b900609b3..5c5b212403 100644 --- a/codex-rs/core/src/models_manager/collaboration_mode_presets.rs +++ b/codex-rs/core/src/models_manager/collaboration_mode_presets.rs @@ -8,9 +8,23 @@ const COLLABORATION_MODE_DEFAULT: &str = include_str!("../../templates/collaboration_mode/default.md"); const KNOWN_MODE_NAMES_PLACEHOLDER: &str = "{{KNOWN_MODE_NAMES}}"; const REQUEST_USER_INPUT_AVAILABILITY_PLACEHOLDER: &str = "{{REQUEST_USER_INPUT_AVAILABILITY}}"; +const ASKING_QUESTIONS_GUIDANCE_PLACEHOLDER: &str = "{{ASKING_QUESTIONS_GUIDANCE}}"; -pub(crate) fn builtin_collaboration_mode_presets() -> Vec { - vec![plan_preset(), default_preset()] +/// Stores feature flags that control collaboration-mode behavior. +/// +/// Keep mode-related flags here so new collaboration-mode capabilities can be +/// added without large cross-cutting diffs to constructor and call-site +/// signatures. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CollaborationModesConfig { + /// Enables `request_user_input` availability in Default mode. + pub default_mode_request_user_input: bool, +} + +pub(crate) fn builtin_collaboration_mode_presets( + collaboration_modes_config: CollaborationModesConfig, +) -> Vec { + vec![plan_preset(), default_preset(collaboration_modes_config)] } fn plan_preset() -> CollaborationModeMask { @@ -23,26 +37,35 @@ fn plan_preset() -> CollaborationModeMask { } } -fn default_preset() -> CollaborationModeMask { +fn default_preset(collaboration_modes_config: CollaborationModesConfig) -> CollaborationModeMask { CollaborationModeMask { name: ModeKind::Default.display_name().to_string(), mode: Some(ModeKind::Default), model: None, reasoning_effort: None, - developer_instructions: Some(Some(default_mode_instructions())), + developer_instructions: Some(Some(default_mode_instructions(collaboration_modes_config))), } } -fn default_mode_instructions() -> String { +fn default_mode_instructions(collaboration_modes_config: CollaborationModesConfig) -> String { let known_mode_names = format_mode_names(&TUI_VISIBLE_COLLABORATION_MODES); - let request_user_input_availability = - request_user_input_availability_message(ModeKind::Default); + let request_user_input_availability = request_user_input_availability_message( + ModeKind::Default, + collaboration_modes_config.default_mode_request_user_input, + ); + let asking_questions_guidance = asking_questions_guidance_message( + collaboration_modes_config.default_mode_request_user_input, + ); COLLABORATION_MODE_DEFAULT .replace(KNOWN_MODE_NAMES_PLACEHOLDER, &known_mode_names) .replace( REQUEST_USER_INPUT_AVAILABILITY_PLACEHOLDER, &request_user_input_availability, ) + .replace( + ASKING_QUESTIONS_GUIDANCE_PLACEHOLDER, + &asking_questions_guidance, + ) } fn format_mode_names(modes: &[ModeKind]) -> String { @@ -55,9 +78,14 @@ fn format_mode_names(modes: &[ModeKind]) -> String { } } -fn request_user_input_availability_message(mode: ModeKind) -> String { +fn request_user_input_availability_message( + mode: ModeKind, + default_mode_request_user_input: bool, +) -> String { let mode_name = mode.display_name(); - if mode.allows_request_user_input() { + if mode.allows_request_user_input() + || (default_mode_request_user_input && mode == ModeKind::Default) + { format!("The `request_user_input` tool is available in {mode_name} mode.") } else { format!( @@ -66,6 +94,14 @@ fn request_user_input_availability_message(mode: ModeKind) -> String { } } +fn asking_questions_guidance_message(default_mode_request_user_input: bool) -> String { + if default_mode_request_user_input { + "In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, prefer using the `request_user_input` tool rather than writing a multiple choice question as a textual assistant message. Never write a multiple choice question as a textual assistant message.".to_string() + } else { + "In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.".to_string() + } +} + #[cfg(test)] mod tests { use super::*; @@ -74,7 +110,10 @@ mod tests { #[test] fn preset_names_use_mode_display_names() { assert_eq!(plan_preset().name, ModeKind::Plan.display_name()); - assert_eq!(default_preset().name, ModeKind::Default.display_name()); + assert_eq!( + default_preset(CollaborationModesConfig::default()).name, + ModeKind::Default.display_name() + ); assert_eq!( plan_preset().reasoning_effort, Some(Some(ReasoningEffort::Medium)) @@ -83,20 +122,38 @@ mod tests { #[test] fn default_mode_instructions_replace_mode_names_placeholder() { - let default_instructions = default_preset() - .developer_instructions - .expect("default preset should include instructions") - .expect("default instructions should be set"); + let default_instructions = default_preset(CollaborationModesConfig { + default_mode_request_user_input: true, + }) + .developer_instructions + .expect("default preset should include instructions") + .expect("default instructions should be set"); assert!(!default_instructions.contains(KNOWN_MODE_NAMES_PLACEHOLDER)); assert!(!default_instructions.contains(REQUEST_USER_INPUT_AVAILABILITY_PLACEHOLDER)); + assert!(!default_instructions.contains(ASKING_QUESTIONS_GUIDANCE_PLACEHOLDER)); let known_mode_names = format_mode_names(&TUI_VISIBLE_COLLABORATION_MODES); let expected_snippet = format!("Known mode names are {known_mode_names}."); assert!(default_instructions.contains(&expected_snippet)); let expected_availability_message = - request_user_input_availability_message(ModeKind::Default); + request_user_input_availability_message(ModeKind::Default, true); assert!(default_instructions.contains(&expected_availability_message)); + assert!(default_instructions.contains("prefer using the `request_user_input` tool")); + } + + #[test] + fn default_mode_instructions_use_plain_text_questions_when_feature_disabled() { + let default_instructions = default_preset(CollaborationModesConfig::default()) + .developer_instructions + .expect("default preset should include instructions") + .expect("default instructions should be set"); + + assert!(!default_instructions.contains("prefer using the `request_user_input` tool")); + assert!( + default_instructions + .contains("ask the user directly with a concise plain-text question") + ); } } diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index fac1991b10..1d7309020e 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -8,6 +8,7 @@ use crate::default_client::build_reqwest_client; use crate::error::CodexErr; use crate::error::Result as CoreResult; use crate::model_provider_info::ModelProviderInfo; +use crate::models_manager::collaboration_mode_presets::CollaborationModesConfig; use crate::models_manager::collaboration_mode_presets::builtin_collaboration_mode_presets; use crate::models_manager::model_info; use codex_api::ModelsClient; @@ -55,6 +56,7 @@ enum CatalogMode { pub struct ModelsManager { remote_models: RwLock>, catalog_mode: CatalogMode, + collaboration_modes_config: CollaborationModesConfig, auth_manager: Arc, etag: RwLock>, cache_manager: ModelsCacheManager, @@ -71,6 +73,7 @@ impl ModelsManager { codex_home: PathBuf, auth_manager: Arc, model_catalog: Option, + collaboration_modes_config: CollaborationModesConfig, ) -> Self { let cache_path = codex_home.join(MODEL_CACHE_FILE); let cache_manager = ModelsCacheManager::new(cache_path, DEFAULT_MODEL_CACHE_TTL); @@ -88,6 +91,7 @@ impl ModelsManager { Self { remote_models: RwLock::new(remote_models), catalog_mode, + collaboration_modes_config, auth_manager, etag: RwLock::new(None), cache_manager, @@ -110,7 +114,14 @@ impl ModelsManager { /// /// Returns a static set of presets seeded with the configured model. pub fn list_collaboration_modes(&self) -> Vec { - builtin_collaboration_mode_presets() + self.list_collaboration_modes_for_config(self.collaboration_modes_config) + } + + pub fn list_collaboration_modes_for_config( + &self, + collaboration_modes_config: CollaborationModesConfig, + ) -> Vec { + builtin_collaboration_mode_presets(collaboration_modes_config) } /// Attempt to list models without blocking, using the current cached state. @@ -378,6 +389,7 @@ impl ModelsManager { .unwrap_or_else(|err| panic!("failed to load bundled models.json: {err}")), ), catalog_mode: CatalogMode::Default, + collaboration_modes_config: CollaborationModesConfig::default(), auth_manager, etag: RwLock::new(None), cache_manager, @@ -504,7 +516,12 @@ mod tests { .expect("load default test config"); let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); - let manager = ModelsManager::new(codex_home.path().to_path_buf(), auth_manager, None); + let manager = ModelsManager::new( + codex_home.path().to_path_buf(), + auth_manager, + None, + CollaborationModesConfig::default(), + ); let known_slug = manager .get_remote_models() .await @@ -541,6 +558,7 @@ mod tests { Some(ModelsResponse { models: vec![remote_model("gpt-overlay", "Overlay", 0)], }), + CollaborationModesConfig::default(), ); let model_info = manager @@ -564,7 +582,12 @@ mod tests { .expect("load default test config"); let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); - let manager = ModelsManager::new(codex_home.path().to_path_buf(), auth_manager, None); + let manager = ModelsManager::new( + codex_home.path().to_path_buf(), + auth_manager, + None, + CollaborationModesConfig::default(), + ); let known_slug = manager .get_remote_models() .await @@ -590,7 +613,12 @@ mod tests { .expect("load default test config"); let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); - let manager = ModelsManager::new(codex_home.path().to_path_buf(), auth_manager, None); + let manager = ModelsManager::new( + codex_home.path().to_path_buf(), + auth_manager, + None, + CollaborationModesConfig::default(), + ); let known_slug = manager .get_remote_models() .await diff --git a/codex-rs/core/src/models_manager/model_info.rs b/codex-rs/core/src/models_manager/model_info.rs index 19a945f951..4824e4cd11 100644 --- a/codex-rs/core/src/models_manager/model_info.rs +++ b/codex-rs/core/src/models_manager/model_info.rs @@ -1,3 +1,4 @@ +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelInstructionsVariables; @@ -68,10 +69,12 @@ pub(crate) fn model_info_from_slug(slug: &str) -> ModelInfo { visibility: ModelVisibility::None, supported_in_api: true, priority: 99, + availability_nux: None, upgrade: None, base_instructions: BASE_INSTRUCTIONS.to_string(), model_messages: local_personality_messages_for_slug(slug), supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, apply_patch_tool_type: None, diff --git a/codex-rs/core/src/personality_migration.rs b/codex-rs/core/src/personality_migration.rs index c207295e96..934ff89379 100644 --- a/codex-rs/core/src/personality_migration.rs +++ b/codex-rs/core/src/personality_migration.rs @@ -177,6 +177,7 @@ mod tests { model_provider: None, base_instructions: None, dynamic_tools: None, + memory_mode: None, }, git: None, }; diff --git a/codex-rs/core/src/plugins.rs b/codex-rs/core/src/plugins.rs new file mode 100644 index 0000000000..890d15a323 --- /dev/null +++ b/codex-rs/core/src/plugins.rs @@ -0,0 +1,627 @@ +use crate::config::Config; +use crate::config::ConfigToml; +use crate::config::profile::ConfigProfile; +use crate::config::types::McpServerConfig; +use crate::config::types::PluginConfig; +use crate::config_loader::ConfigLayerStack; +use crate::features::Feature; +use crate::features::FeatureOverrides; +use crate::features::Features; +use codex_utils_absolute_path::AbsolutePathBuf; +use serde::Deserialize; +use serde_json::Map as JsonMap; +use serde_json::Value as JsonValue; +use std::collections::HashMap; +use std::fs; +use std::path::Path; +use std::path::PathBuf; +use std::sync::RwLock; +use tracing::warn; + +const PLUGIN_MANIFEST_PATH: &str = ".codex-plugin/plugin.json"; +const DEFAULT_SKILLS_DIR_NAME: &str = "skills"; +const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json"; + +#[derive(Debug, Clone, PartialEq)] +pub struct LoadedPlugin { + pub config_name: String, + pub manifest_name: Option, + pub root: AbsolutePathBuf, + pub enabled: bool, + pub skill_roots: Vec, + pub mcp_servers: HashMap, + pub error: Option, +} + +impl LoadedPlugin { + fn is_active(&self) -> bool { + self.enabled && self.error.is_none() + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct PluginLoadOutcome { + pub plugins: Vec, +} + +impl PluginLoadOutcome { + pub fn effective_skill_roots(&self) -> Vec { + let mut skill_roots: Vec = self + .plugins + .iter() + .filter(|plugin| plugin.is_active()) + .flat_map(|plugin| plugin.skill_roots.iter().cloned()) + .collect(); + skill_roots.sort_unstable(); + skill_roots.dedup(); + skill_roots + } + + pub fn effective_mcp_servers(&self) -> HashMap { + let mut mcp_servers = HashMap::new(); + for plugin in self.plugins.iter().filter(|plugin| plugin.is_active()) { + for (name, config) in &plugin.mcp_servers { + mcp_servers + .entry(name.clone()) + .or_insert_with(|| config.clone()); + } + } + mcp_servers + } +} + +pub struct PluginsManager { + cache_by_cwd: RwLock>, +} + +impl PluginsManager { + pub fn new(_codex_home: PathBuf) -> Self { + Self { + cache_by_cwd: RwLock::new(HashMap::new()), + } + } + + pub fn plugins_for_config(&self, config: &Config) -> PluginLoadOutcome { + self.plugins_for_layer_stack(&config.cwd, &config.config_layer_stack, false) + } + + pub fn plugins_for_layer_stack( + &self, + cwd: &Path, + config_layer_stack: &ConfigLayerStack, + force_reload: bool, + ) -> PluginLoadOutcome { + if !plugins_feature_enabled_from_stack(config_layer_stack) { + let mut cache = match self.cache_by_cwd.write() { + Ok(cache) => cache, + Err(err) => err.into_inner(), + }; + cache.insert(cwd.to_path_buf(), PluginLoadOutcome::default()); + return PluginLoadOutcome::default(); + } + + if !force_reload && let Some(outcome) = self.cached_outcome_for_cwd(cwd) { + return outcome; + } + + let outcome = load_plugins_from_layer_stack(config_layer_stack); + log_plugin_load_errors(&outcome); + let mut cache = match self.cache_by_cwd.write() { + Ok(cache) => cache, + Err(err) => err.into_inner(), + }; + cache.insert(cwd.to_path_buf(), outcome.clone()); + outcome + } + + pub fn clear_cache(&self) { + let mut cache_by_cwd = match self.cache_by_cwd.write() { + Ok(cache) => cache, + Err(err) => err.into_inner(), + }; + cache_by_cwd.clear(); + } + + fn cached_outcome_for_cwd(&self, cwd: &Path) -> Option { + match self.cache_by_cwd.read() { + Ok(cache) => cache.get(cwd).cloned(), + Err(err) => err.into_inner().get(cwd).cloned(), + } + } +} + +fn plugins_feature_enabled_from_stack(config_layer_stack: &ConfigLayerStack) -> bool { + let effective_config = config_layer_stack.effective_config(); + let Ok(config_toml) = effective_config.try_into::() else { + warn!("failed to deserialize config when checking plugin feature flag"); + return false; + }; + let config_profile = config_toml + .get_config_profile(config_toml.profile.clone()) + .unwrap_or_else(|_| ConfigProfile::default()); + let features = + Features::from_config(&config_toml, &config_profile, FeatureOverrides::default()); + features.enabled(Feature::Plugins) +} + +fn log_plugin_load_errors(outcome: &PluginLoadOutcome) { + for plugin in outcome + .plugins + .iter() + .filter(|plugin| plugin.error.is_some()) + { + if let Some(error) = plugin.error.as_deref() { + warn!( + plugin = plugin.config_name, + path = %plugin.root.display(), + "failed to load plugin: {error}" + ); + } + } +} + +#[derive(Debug, Default, Deserialize)] +struct PluginManifest { + name: String, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PluginMcpFile { + #[serde(default)] + mcp_servers: HashMap, +} + +pub fn load_plugins_from_layer_stack(config_layer_stack: &ConfigLayerStack) -> PluginLoadOutcome { + let mut configured_plugins: Vec<_> = configured_plugins_from_stack(config_layer_stack) + .into_iter() + .collect(); + configured_plugins.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); + + let mut plugins = Vec::with_capacity(configured_plugins.len()); + let mut seen_mcp_server_names = HashMap::::new(); + for (configured_name, plugin) in configured_plugins { + let loaded_plugin = load_plugin(configured_name.clone(), &plugin); + for name in loaded_plugin.mcp_servers.keys() { + if let Some(previous_plugin) = + seen_mcp_server_names.insert(name.clone(), configured_name.clone()) + { + warn!( + plugin = configured_name, + previous_plugin, + server = name, + "skipping duplicate plugin MCP server name" + ); + } + } + plugins.push(loaded_plugin); + } + + PluginLoadOutcome { plugins } +} + +pub(crate) fn plugin_namespace_for_skill_path(path: &Path) -> Option { + for ancestor in path.ancestors() { + if let Some(manifest) = load_plugin_manifest(ancestor) { + return Some(plugin_manifest_name(&manifest, ancestor)); + } + } + + None +} + +fn configured_plugins_from_stack( + config_layer_stack: &ConfigLayerStack, +) -> HashMap { + let effective_config = config_layer_stack.effective_config(); + let Some(plugins_value) = effective_config.get("plugins") else { + return HashMap::new(); + }; + match plugins_value.clone().try_into() { + Ok(plugins) => plugins, + Err(err) => { + warn!("invalid plugins config: {err}"); + HashMap::new() + } + } +} + +fn load_plugin(config_name: String, plugin: &PluginConfig) -> LoadedPlugin { + let plugin_root = plugin.path.clone(); + let mut loaded_plugin = LoadedPlugin { + config_name, + manifest_name: None, + root: plugin_root.clone(), + enabled: plugin.enabled, + skill_roots: Vec::new(), + mcp_servers: HashMap::new(), + error: None, + }; + + if !plugin.enabled { + return loaded_plugin; + } + + if !plugin_root.as_path().is_dir() { + loaded_plugin.error = Some("path does not exist or is not a directory".to_string()); + return loaded_plugin; + } + + let Some(manifest) = load_plugin_manifest(plugin_root.as_path()) else { + loaded_plugin.error = Some("missing or invalid .codex-plugin/plugin.json".to_string()); + return loaded_plugin; + }; + + loaded_plugin.manifest_name = Some(plugin_manifest_name(&manifest, plugin_root.as_path())); + loaded_plugin.skill_roots = default_skill_roots(plugin_root.as_path()); + let mut mcp_servers = HashMap::new(); + for mcp_config_path in default_mcp_config_paths(plugin_root.as_path()) { + let plugin_mcp = load_mcp_servers_from_file(plugin_root.as_path(), &mcp_config_path); + for (name, config) in plugin_mcp.mcp_servers { + if mcp_servers.insert(name.clone(), config).is_some() { + warn!( + plugin = %plugin_root.display(), + path = %mcp_config_path.display(), + server = name, + "plugin MCP file overwrote an earlier server definition" + ); + } + } + } + loaded_plugin.mcp_servers = mcp_servers; + loaded_plugin +} + +fn load_plugin_manifest(plugin_root: &Path) -> Option { + let manifest_path = plugin_root.join(PLUGIN_MANIFEST_PATH); + if !manifest_path.is_file() { + return None; + } + let contents = fs::read_to_string(&manifest_path).ok()?; + match serde_json::from_str(&contents) { + Ok(manifest) => Some(manifest), + Err(err) => { + warn!( + path = %manifest_path.display(), + "failed to parse plugin manifest: {err}" + ); + None + } + } +} + +fn plugin_manifest_name(manifest: &PluginManifest, plugin_root: &Path) -> String { + plugin_root + .file_name() + .and_then(|name| name.to_str()) + .filter(|_| manifest.name.trim().is_empty()) + .unwrap_or(&manifest.name) + .to_string() +} + +fn default_skill_roots(plugin_root: &Path) -> Vec { + let skills_dir = plugin_root.join(DEFAULT_SKILLS_DIR_NAME); + if skills_dir.is_dir() { + vec![skills_dir] + } else { + Vec::new() + } +} + +fn default_mcp_config_paths(plugin_root: &Path) -> Vec { + let mut paths = Vec::new(); + let default_path = plugin_root.join(DEFAULT_MCP_CONFIG_FILE); + if default_path.is_file() { + paths.push(default_path); + } + paths.sort_unstable(); + paths.dedup(); + paths +} + +fn load_mcp_servers_from_file(plugin_root: &Path, mcp_config_path: &Path) -> PluginMcpDiscovery { + let Ok(contents) = fs::read_to_string(mcp_config_path) else { + return PluginMcpDiscovery::default(); + }; + let parsed = match serde_json::from_str::(&contents) { + Ok(parsed) => parsed, + Err(err) => { + warn!( + path = %mcp_config_path.display(), + "failed to parse plugin MCP config: {err}" + ); + return PluginMcpDiscovery::default(); + } + }; + normalize_plugin_mcp_servers( + plugin_root, + parsed.mcp_servers, + mcp_config_path.to_string_lossy().as_ref(), + ) +} + +fn normalize_plugin_mcp_servers( + plugin_root: &Path, + plugin_mcp_servers: HashMap, + source: &str, +) -> PluginMcpDiscovery { + let mut mcp_servers = HashMap::new(); + + for (name, config_value) in plugin_mcp_servers { + let normalized = normalize_plugin_mcp_server_value(plugin_root, config_value); + match serde_json::from_value::(JsonValue::Object(normalized)) { + Ok(config) => { + mcp_servers.insert(name, config); + } + Err(err) => { + warn!( + plugin = %plugin_root.display(), + server = name, + "failed to parse plugin MCP server from {source}: {err}" + ); + } + } + } + + PluginMcpDiscovery { mcp_servers } +} + +fn normalize_plugin_mcp_server_value( + plugin_root: &Path, + value: JsonValue, +) -> JsonMap { + let mut object = match value { + JsonValue::Object(object) => object, + _ => return JsonMap::new(), + }; + + if let Some(JsonValue::String(transport_type)) = object.remove("type") { + match transport_type.as_str() { + "http" | "streamable_http" | "streamable-http" => {} + "stdio" => {} + other => { + warn!( + plugin = %plugin_root.display(), + transport = other, + "plugin MCP server uses an unknown transport type" + ); + } + } + } + + if let Some(JsonValue::Object(oauth)) = object.remove("oauth") + && oauth.contains_key("callbackPort") + { + warn!( + plugin = %plugin_root.display(), + "plugin MCP server OAuth callbackPort is ignored; Codex uses global MCP OAuth callback settings" + ); + } + + if let Some(JsonValue::String(cwd)) = object.get("cwd") + && !Path::new(cwd).is_absolute() + { + object.insert( + "cwd".to_string(), + JsonValue::String(plugin_root.join(cwd).display().to_string()), + ); + } + + object +} + +#[derive(Debug, Default)] +struct PluginMcpDiscovery { + mcp_servers: HashMap, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::CONFIG_TOML_FILE; + use crate::config::ConfigBuilder; + use crate::config::types::McpServerTransportConfig; + use pretty_assertions::assert_eq; + use tempfile::TempDir; + use toml::Value; + + fn write_file(path: &Path, contents: &str) { + fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap(); + fs::write(path, contents).unwrap(); + } + + fn plugin_config_toml( + plugin_root: &Path, + enabled: bool, + plugins_feature_enabled: bool, + ) -> String { + let mut root = toml::map::Map::new(); + + let mut features = toml::map::Map::new(); + features.insert( + "plugins".to_string(), + Value::Boolean(plugins_feature_enabled), + ); + root.insert("features".to_string(), Value::Table(features)); + + let mut plugin = toml::map::Map::new(); + plugin.insert( + "path".to_string(), + Value::String(plugin_root.display().to_string()), + ); + plugin.insert("enabled".to_string(), Value::Boolean(enabled)); + + let mut plugins = toml::map::Map::new(); + plugins.insert("sample".to_string(), Value::Table(plugin)); + root.insert("plugins".to_string(), Value::Table(plugins)); + + toml::to_string(&Value::Table(root)).expect("plugin test config should serialize") + } + + async fn load_plugins_from_config(config_toml: &str, codex_home: &Path) -> PluginLoadOutcome { + write_file(&codex_home.join(CONFIG_TOML_FILE), config_toml); + let config = ConfigBuilder::default() + .codex_home(codex_home.to_path_buf()) + .build() + .await + .expect("config should load"); + PluginsManager::new(codex_home.to_path_buf()).plugins_for_config(&config) + } + + #[tokio::test] + async fn load_plugins_loads_default_skills_and_mcp_servers() { + let codex_home = TempDir::new().unwrap(); + let plugin_root = codex_home.path().join("plugin-sample"); + + write_file( + &plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ); + write_file( + &plugin_root.join("skills/sample-search/SKILL.md"), + "---\nname: sample-search\ndescription: search sample data\n---\n", + ); + write_file( + &plugin_root.join(".mcp.json"), + r#"{ + "mcpServers": { + "sample": { + "type": "http", + "url": "https://sample.example/mcp", + "oauth": { + "clientId": "client-id", + "callbackPort": 3118 + } + } + } +}"#, + ); + + let outcome = load_plugins_from_config( + &plugin_config_toml(&plugin_root, true, true), + codex_home.path(), + ) + .await; + + assert_eq!( + outcome.plugins, + vec![LoadedPlugin { + config_name: "sample".to_string(), + manifest_name: Some("sample".to_string()), + root: AbsolutePathBuf::try_from(plugin_root.clone()).unwrap(), + enabled: true, + skill_roots: vec![plugin_root.join("skills")], + mcp_servers: HashMap::from([( + "sample".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url: "https://sample.example/mcp".to_string(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + }, + enabled: true, + required: false, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth_resource: None, + }, + )]), + error: None, + }] + ); + assert_eq!( + outcome.effective_skill_roots(), + vec![plugin_root.join("skills")] + ); + assert_eq!(outcome.effective_mcp_servers().len(), 1); + } + + #[tokio::test] + async fn load_plugins_preserves_disabled_plugins_without_effective_contributions() { + let codex_home = TempDir::new().unwrap(); + let plugin_root = codex_home.path().join("plugin-sample"); + + write_file( + &plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ); + write_file( + &plugin_root.join(".mcp.json"), + r#"{ + "mcpServers": { + "sample": { + "type": "http", + "url": "https://sample.example/mcp" + } + } +}"#, + ); + + let outcome = load_plugins_from_config( + &plugin_config_toml(&plugin_root, false, true), + codex_home.path(), + ) + .await; + + assert_eq!( + outcome.plugins, + vec![LoadedPlugin { + config_name: "sample".to_string(), + manifest_name: None, + root: AbsolutePathBuf::try_from(plugin_root).unwrap(), + enabled: false, + skill_roots: Vec::new(), + mcp_servers: HashMap::new(), + error: None, + }] + ); + assert!(outcome.effective_skill_roots().is_empty()); + assert!(outcome.effective_mcp_servers().is_empty()); + } + + #[test] + fn plugin_namespace_for_skill_path_uses_manifest_name() { + let codex_home = TempDir::new().unwrap(); + let plugin_root = codex_home.path().join("plugins/sample"); + let skill_path = plugin_root.join("skills/search/SKILL.md"); + + write_file( + &plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ); + write_file(&skill_path, "---\ndescription: search\n---\n"); + + assert_eq!( + plugin_namespace_for_skill_path(&skill_path), + Some("sample".to_string()) + ); + } + + #[tokio::test] + async fn load_plugins_returns_empty_when_feature_disabled() { + let codex_home = TempDir::new().unwrap(); + let plugin_root = codex_home.path().join("plugin-sample"); + + write_file( + &plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ); + write_file( + &plugin_root.join("skills/sample-search/SKILL.md"), + "---\nname: sample-search\ndescription: search sample data\n---\n", + ); + + let outcome = load_plugins_from_config( + &plugin_config_toml(&plugin_root, true, false), + codex_home.path(), + ) + .await; + + assert_eq!(outcome, PluginLoadOutcome::default()); + } +} diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index 47a4354e2d..8842c41c96 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -1,5 +1,6 @@ use crate::CodexAuth; use crate::api_bridge::map_api_error; +use crate::auth::read_openai_api_key_from_env; use crate::codex::Session; use crate::default_client::default_headers; use crate::error::CodexErr; @@ -24,27 +25,72 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RealtimeConversationClosedEvent; use codex_protocol::protocol::RealtimeConversationRealtimeEvent; use codex_protocol::protocol::RealtimeConversationStartedEvent; +use codex_protocol::protocol::RealtimeHandoffRequested; use http::HeaderMap; -use serde_json::Value; +use http::HeaderValue; +use http::header::AUTHORIZATION; use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use tokio::sync::Mutex; use tokio::task::JoinHandle; +use tracing::debug; use tracing::error; +use tracing::info; use tracing::warn; const AUDIO_IN_QUEUE_CAPACITY: usize = 256; -const TEXT_IN_QUEUE_CAPACITY: usize = 64; +const USER_TEXT_IN_QUEUE_CAPACITY: usize = 64; +const HANDOFF_OUT_QUEUE_CAPACITY: usize = 64; const OUTPUT_EVENTS_QUEUE_CAPACITY: usize = 256; pub(crate) struct RealtimeConversationManager { state: Mutex>, } +#[derive(Clone, Debug)] +struct RealtimeHandoffState { + output_tx: Sender, + active_handoff: Arc>>, +} + +#[derive(Debug, PartialEq, Eq)] +struct HandoffOutput { + handoff_id: String, + output_text: String, +} + +impl RealtimeHandoffState { + fn new(output_tx: Sender) -> Self { + Self { + output_tx, + active_handoff: Arc::new(Mutex::new(None)), + } + } + + async fn send_output(&self, output_text: String) -> CodexResult<()> { + let Some(handoff_id) = self.active_handoff.lock().await.clone() else { + return Ok(()); + }; + + self.output_tx + .send(HandoffOutput { + handoff_id, + output_text, + }) + .await + .map_err(|_| CodexErr::InvalidRequest("conversation is not running".to_string()))?; + Ok(()) + } +} + #[allow(dead_code)] struct ConversationState { audio_tx: Sender, - text_tx: Sender, + user_text_tx: Sender, + handoff: RealtimeHandoffState, task: JoinHandle<()>, + realtime_active: Arc, } #[allow(dead_code)] @@ -57,7 +103,9 @@ impl RealtimeConversationManager { pub(crate) async fn running_state(&self) -> Option<()> { let state = self.state.lock().await; - state.as_ref().map(|_| ()) + state + .as_ref() + .and_then(|state| state.realtime_active.load(Ordering::Relaxed).then_some(())) } pub(crate) async fn start( @@ -65,18 +113,24 @@ impl RealtimeConversationManager { api_provider: ApiProvider, extra_headers: Option, prompt: String, + model: Option, session_id: Option, - ) -> CodexResult> { + ) -> CodexResult<(Receiver, Arc)> { let previous_state = { let mut guard = self.state.lock().await; guard.take() }; if let Some(state) = previous_state { + state.realtime_active.store(false, Ordering::Relaxed); state.task.abort(); let _ = state.task.await; } - let session_config = RealtimeSessionConfig { prompt, session_id }; + let session_config = RealtimeSessionConfig { + instructions: prompt, + model, + session_id, + }; let client = RealtimeWebsocketClient::new(api_provider); let connection = client .connect( @@ -91,19 +145,34 @@ impl RealtimeConversationManager { let events = connection.events(); let (audio_tx, audio_rx) = async_channel::bounded::(AUDIO_IN_QUEUE_CAPACITY); - let (text_tx, text_rx) = async_channel::bounded::(TEXT_IN_QUEUE_CAPACITY); + let (user_text_tx, user_text_rx) = + async_channel::bounded::(USER_TEXT_IN_QUEUE_CAPACITY); + let (handoff_output_tx, handoff_output_rx) = + async_channel::bounded::(HANDOFF_OUT_QUEUE_CAPACITY); let (events_tx, events_rx) = async_channel::bounded::(OUTPUT_EVENTS_QUEUE_CAPACITY); - let task = spawn_realtime_input_task(writer, events, text_rx, audio_rx, events_tx); + let realtime_active = Arc::new(AtomicBool::new(true)); + let handoff = RealtimeHandoffState::new(handoff_output_tx); + let task = spawn_realtime_input_task( + writer, + events, + user_text_rx, + handoff_output_rx, + audio_rx, + events_tx, + handoff.clone(), + ); let mut guard = self.state.lock().await; *guard = Some(ConversationState { audio_tx, - text_tx, + user_text_tx, + handoff, task, + realtime_active: Arc::clone(&realtime_active), }); - Ok(events_rx) + Ok((events_rx, realtime_active)) } pub(crate) async fn audio_in(&self, frame: RealtimeAudioFrame) -> CodexResult<()> { @@ -133,7 +202,7 @@ impl RealtimeConversationManager { pub(crate) async fn text_in(&self, text: String) -> CodexResult<()> { let sender = { let guard = self.state.lock().await; - guard.as_ref().map(|state| state.text_tx.clone()) + guard.as_ref().map(|state| state.user_text_tx.clone()) }; let Some(sender) = sender else { @@ -149,6 +218,38 @@ impl RealtimeConversationManager { Ok(()) } + pub(crate) async fn handoff_out(&self, output_text: String) -> CodexResult<()> { + let handoff = { + let guard = self.state.lock().await; + let Some(state) = guard.as_ref() else { + return Err(CodexErr::InvalidRequest( + "conversation is not running".to_string(), + )); + }; + state.handoff.clone() + }; + + handoff.send_output(output_text).await + } + + pub(crate) async fn active_handoff_id(&self) -> Option { + let handoff = { + let guard = self.state.lock().await; + guard.as_ref().map(|state| state.handoff.clone()) + }?; + handoff.active_handoff.lock().await.clone() + } + + pub(crate) async fn clear_active_handoff(&self) { + let handoff = { + let guard = self.state.lock().await; + guard.as_ref().map(|state| state.handoff.clone()) + }; + if let Some(handoff) = handoff { + *handoff.active_handoff.lock().await = None; + } + } + pub(crate) async fn shutdown(&self) -> CodexResult<()> { let state = { let mut guard = self.state.lock().await; @@ -156,6 +257,7 @@ impl RealtimeConversationManager { }; if let Some(state) = state { + state.realtime_active.store(false, Ordering::Relaxed); state.task.abort(); let _ = state.task.await; } @@ -170,7 +272,8 @@ pub(crate) async fn handle_start( ) -> CodexResult<()> { let provider = sess.provider().await; let auth = sess.services.auth_manager.auth().await; - let mut api_provider = provider.to_api_provider(auth.as_ref().map(CodexAuth::auth_mode))?; + let realtime_api_key = realtime_api_key(auth.as_ref(), &provider)?; + let mut api_provider = provider.to_api_provider(Some(crate::auth::AuthMode::ApiKey))?; let config = sess.get_config().await; if let Some(realtime_ws_base_url) = &config.experimental_realtime_ws_base_url { api_provider.base_url = realtime_ws_base_url.clone(); @@ -179,22 +282,35 @@ pub(crate) async fn handle_start( .experimental_realtime_ws_backend_prompt .clone() .unwrap_or(params.prompt); + let model = config.experimental_realtime_ws_model.clone(); let requested_session_id = params .session_id .or_else(|| Some(sess.conversation_id.to_string())); - let events_rx = match sess + let extra_headers = + realtime_request_headers(requested_session_id.as_deref(), realtime_api_key.as_str())?; + info!("starting realtime conversation"); + let (events_rx, realtime_active) = match sess .conversation - .start(api_provider, None, prompt, requested_session_id.clone()) + .start( + api_provider, + extra_headers, + prompt, + model, + requested_session_id.clone(), + ) .await { Ok(events_rx) => events_rx, Err(err) => { + error!("failed to start realtime conversation: {err}"); send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::Other).await; return Ok(()); } }; + info!("realtime conversation started"); + sess.send_event_raw(Event { id: sub_id.clone(), msg: EventMsg::RealtimeConversationStarted(RealtimeConversationStartedEvent { @@ -210,13 +326,15 @@ pub(crate) async fn handle_start( msg, }; while let Ok(event) = events_rx.recv().await { + debug!(conversation_id = %sess_clone.conversation_id, "received realtime conversation event"); let maybe_routed_text = match &event { - RealtimeEvent::ConversationItemAdded(item) => { - realtime_text_from_conversation_item(item) + RealtimeEvent::HandoffRequested(handoff) => { + realtime_text_from_handoff_request(handoff) } _ => None, }; if let Some(text) = maybe_routed_text { + debug!(text = %text, "[realtime-text] realtime conversation text output"); let sess_for_routed_text = Arc::clone(&sess_clone); sess_for_routed_text.route_realtime_text_input(text).await; } @@ -228,7 +346,8 @@ pub(crate) async fn handle_start( ))) .await; } - if let Some(()) = sess_clone.conversation.running_state().await { + if realtime_active.swap(false, Ordering::Relaxed) { + info!("realtime conversation transport closed"); sess_clone .send_event_raw(ev(EventMsg::RealtimeConversationClosed( RealtimeConversationClosedEvent { @@ -248,30 +367,62 @@ pub(crate) async fn handle_audio( params: ConversationAudioParams, ) { if let Err(err) = sess.conversation.audio_in(params.frame).await { + error!("failed to append realtime audio: {err}"); send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::BadRequest).await; } } -fn realtime_text_from_conversation_item(item: &Value) -> Option { - match item.get("type").and_then(Value::as_str) { - Some("message") => { - if item.get("role").and_then(Value::as_str) != Some("assistant") { - return None; - } - let content = item.get("content")?.as_array()?; - let text = content - .iter() - .filter(|entry| entry.get("type").and_then(Value::as_str) == Some("text")) - .filter_map(|entry| entry.get("text").and_then(Value::as_str)) - .collect::(); - if text.is_empty() { None } else { Some(text) } - } - Some("spawn_transcript") => item - .get("delta_user_transcript") - .and_then(Value::as_str) - .and_then(|text| (!text.is_empty()).then(|| text.to_string())), - Some(_) | None => None, +fn realtime_text_from_handoff_request(handoff: &RealtimeHandoffRequested) -> Option { + (!handoff.input_transcript.is_empty()).then(|| handoff.input_transcript.clone()) +} + +fn realtime_api_key( + auth: Option<&CodexAuth>, + provider: &crate::ModelProviderInfo, +) -> CodexResult { + if let Some(api_key) = provider.api_key()? { + return Ok(api_key); } + + if let Some(token) = provider.experimental_bearer_token.clone() { + return Ok(token); + } + + if let Some(api_key) = auth.and_then(CodexAuth::api_key) { + return Ok(api_key.to_string()); + } + + // TODO(aibrahim): Remove this temporary fallback once realtime auth no longer + // requires API key auth for ChatGPT/SIWC sessions. + if provider.is_openai() + && let Some(api_key) = read_openai_api_key_from_env() + { + return Ok(api_key); + } + + Err(CodexErr::InvalidRequest( + "realtime conversation requires API key auth".to_string(), + )) +} + +fn realtime_request_headers( + session_id: Option<&str>, + api_key: &str, +) -> CodexResult> { + let mut headers = HeaderMap::new(); + + if let Some(session_id) = session_id + && let Ok(session_id) = HeaderValue::from_str(session_id) + { + headers.insert("x-session-id", session_id); + } + + let auth_value = HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|err| { + CodexErr::InvalidRequest(format!("invalid realtime api key header: {err}")) + })?; + headers.insert(AUTHORIZATION, auth_value); + + Ok(Some(headers)) } pub(crate) async fn handle_text( @@ -279,7 +430,10 @@ pub(crate) async fn handle_text( sub_id: String, params: ConversationTextParams, ) { + debug!(text = %params.text, "[realtime-text] appending realtime conversation text input"); + if let Err(err) = sess.conversation.text_in(params.text).await { + error!("failed to append realtime text: {err}"); send_conversation_error(sess, sub_id, err.to_string(), CodexErrorInfo::BadRequest).await; } } @@ -304,14 +458,16 @@ pub(crate) async fn handle_close(sess: &Arc, sub_id: String) { fn spawn_realtime_input_task( writer: RealtimeWebsocketWriter, events: RealtimeWebsocketEvents, - text_rx: Receiver, + user_text_rx: Receiver, + handoff_output_rx: Receiver, audio_rx: Receiver, events_tx: Sender, + handoff_state: RealtimeHandoffState, ) -> JoinHandle<()> { tokio::spawn(async move { loop { tokio::select! { - text = text_rx.recv() => { + text = user_text_rx.recv() => { match text { Ok(text) => { if let Err(err) = writer.send_conversation_item_create(text).await { @@ -323,9 +479,31 @@ fn spawn_realtime_input_task( Err(_) => break, } } + handoff_output = handoff_output_rx.recv() => { + match handoff_output { + Ok(HandoffOutput { + handoff_id, + output_text, + }) => { + if let Err(err) = writer + .send_conversation_handoff_append(handoff_id, output_text) + .await + { + let mapped_error = map_api_error(err); + warn!("failed to send handoff output: {mapped_error}"); + break; + } + } + Err(_) => break, + } + } event = events.next_event() => { match event { Ok(Some(event)) => { + if let RealtimeEvent::HandoffRequested(handoff) = &event { + *handoff_state.active_handoff.lock().await = + Some(handoff.handoff_id.clone()); + } let should_stop = matches!(&event, RealtimeEvent::Error(_)); if events_tx.send(event).await.is_err() { break; @@ -392,82 +570,98 @@ async fn send_conversation_error( #[cfg(test)] mod tests { - use super::realtime_text_from_conversation_item; + use super::HandoffOutput; + use super::RealtimeHandoffState; + use super::realtime_text_from_handoff_request; + use async_channel::bounded; + use codex_protocol::protocol::RealtimeHandoffMessage; + use codex_protocol::protocol::RealtimeHandoffRequested; use pretty_assertions::assert_eq; - use serde_json::json; #[test] - fn extracts_text_from_assistant_message_items_only() { - let assistant = json!({ - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "hello"}], - }); + fn extracts_text_from_handoff_request_input_transcript() { + let handoff = RealtimeHandoffRequested { + handoff_id: "handoff_1".to_string(), + item_id: "item_1".to_string(), + input_transcript: "hello".to_string(), + messages: vec![RealtimeHandoffMessage { + role: "user".to_string(), + text: "hello".to_string(), + }], + }; assert_eq!( - realtime_text_from_conversation_item(&assistant), + realtime_text_from_handoff_request(&handoff), Some("hello".to_string()) ); - - let user = json!({ - "type": "message", - "role": "user", - "content": [{"type": "text", "text": "world"}], - }); - assert_eq!(realtime_text_from_conversation_item(&user), None); } #[test] - fn extracts_and_concatenates_text_entries_only() { - let item = json!({ - "type": "message", - "role": "assistant", - "content": [ - {"type": "text", "text": "a"}, - {"type": "ignored", "text": "x"}, - {"type": "text", "text": "b"} - ], - }); - assert_eq!( - realtime_text_from_conversation_item(&item), - Some("ab".to_string()) - ); + fn ignores_empty_handoff_request_input_transcript() { + let handoff = RealtimeHandoffRequested { + handoff_id: "handoff_1".to_string(), + item_id: "item_1".to_string(), + input_transcript: String::new(), + messages: vec![], + }; + assert_eq!(realtime_text_from_handoff_request(&handoff), None); } - #[test] - fn ignores_non_message_or_missing_text() { - let non_message = json!({ - "type": "tool_call", - "content": [{"type": "text", "text": "nope"}], - }); - assert_eq!(realtime_text_from_conversation_item(&non_message), None); + #[tokio::test] + async fn clears_active_handoff_explicitly() { + let (tx, _rx) = bounded(1); + let state = RealtimeHandoffState::new(tx); - let no_text = json!({ - "type": "message", - "role": "assistant", - "content": [{"type": "other", "value": 1}], - }); - assert_eq!(realtime_text_from_conversation_item(&no_text), None); - - let empty_spawn_transcript = json!({ - "type": "spawn_transcript", - "delta_user_transcript": "", - }); + *state.active_handoff.lock().await = Some("handoff_1".to_string()); assert_eq!( - realtime_text_from_conversation_item(&empty_spawn_transcript), - None + state.active_handoff.lock().await.clone(), + Some("handoff_1".to_string()) ); + + *state.active_handoff.lock().await = None; + assert_eq!(state.active_handoff.lock().await.clone(), None); } - #[test] - fn extracts_text_from_spawn_transcript_items() { - let item = json!({ - "type": "spawn_transcript", - "delta_user_transcript": "delegate from transcript", - "backend_prompt_messages": [{"role": "user", "content": "delegate from transcript"}], - }); + #[tokio::test] + async fn sends_multiple_handoff_outputs_until_cleared() { + let (tx, rx) = bounded(4); + let state = RealtimeHandoffState::new(tx); + + state + .send_output("ignored".to_string()) + .await + .expect("send"); + assert!(rx.is_empty()); + + *state.active_handoff.lock().await = Some("handoff_1".to_string()); + state.send_output("result".to_string()).await.expect("send"); + state + .send_output("result 2".to_string()) + .await + .expect("send"); + + let output_1 = rx.recv().await.expect("recv"); assert_eq!( - realtime_text_from_conversation_item(&item), - Some("delegate from transcript".to_string()) + output_1, + HandoffOutput { + handoff_id: "handoff_1".to_string(), + output_text: "result".to_string(), + } ); + + let output_2 = rx.recv().await.expect("recv"); + assert_eq!( + output_2, + HandoffOutput { + handoff_id: "handoff_1".to_string(), + output_text: "result 2".to_string(), + } + ); + + *state.active_handoff.lock().await = None; + state + .send_output("ignored after clear".to_string()) + .await + .expect("send"); + assert!(rx.is_empty()); } } diff --git a/codex-rs/core/src/rollout/metadata.rs b/codex-rs/core/src/rollout/metadata.rs index 9196931daf..0bee69b6aa 100644 --- a/codex-rs/core/src/rollout/metadata.rs +++ b/codex-rs/core/src/rollout/metadata.rs @@ -2,6 +2,7 @@ use crate::config::Config; use crate::rollout; use crate::rollout::list::parse_timestamp_uuid_from_filename; use crate::rollout::recorder::RolloutRecorder; +use crate::state_db::normalize_cwd_for_state_db; use chrono::DateTime; use chrono::NaiveDateTime; use chrono::Timelike; @@ -129,6 +130,13 @@ pub(crate) async fn extract_metadata_from_rollout( } Ok(ExtractionOutcome { metadata, + memory_mode: items.iter().rev().find_map(|item| match item { + RolloutItem::SessionMeta(meta_line) => meta_line.meta.memory_mode.clone(), + RolloutItem::ResponseItem(_) + | RolloutItem::Compacted(_) + | RolloutItem::TurnContext(_) + | RolloutItem::EventMsg(_) => None, + }), parse_errors, }) } @@ -272,6 +280,8 @@ pub(crate) async fn backfill_sessions( ); } let mut metadata = outcome.metadata; + metadata.cwd = normalize_cwd_for_state_db(&metadata.cwd); + let memory_mode = outcome.memory_mode.unwrap_or_else(|| "enabled".to_string()); if rollout.archived && metadata.archived_at.is_none() { let fallback_archived_at = metadata.updated_at; metadata.archived_at = file_modified_time_utc(&rollout.path) @@ -282,6 +292,17 @@ pub(crate) async fn backfill_sessions( stats.failed = stats.failed.saturating_add(1); warn!("failed to upsert rollout {}: {err}", rollout.path.display()); } else { + if let Err(err) = runtime + .set_thread_memory_mode(metadata.id, memory_mode.as_str()) + .await + { + stats.failed = stats.failed.saturating_add(1); + warn!( + "failed to restore memory mode for {}: {err}", + rollout.path.display() + ); + continue; + } stats.upserted = stats.upserted.saturating_add(1); if let Ok(meta_line) = rollout::list::read_session_meta_line(&rollout.path).await @@ -519,6 +540,7 @@ mod tests { model_provider: Some("openai".to_string()), base_instructions: None, dynamic_tools: None, + memory_mode: None, }; let session_meta_line = SessionMetaLine { meta: session_meta, @@ -543,9 +565,71 @@ mod tests { expected.updated_at = file_modified_time_utc(&path).await.expect("mtime"); assert_eq!(outcome.metadata, expected); + assert_eq!(outcome.memory_mode, None); assert_eq!(outcome.parse_errors, 0); } + #[tokio::test] + async fn extract_metadata_from_rollout_returns_latest_memory_mode() { + let dir = tempdir().expect("tempdir"); + let uuid = Uuid::new_v4(); + let id = ThreadId::from_string(&uuid.to_string()).expect("thread id"); + let path = dir + .path() + .join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl")); + + let session_meta = SessionMeta { + id, + forked_from_id: None, + timestamp: "2026-01-27T12:34:56Z".to_string(), + cwd: dir.path().to_path_buf(), + originator: "cli".to_string(), + cli_version: "0.0.0".to_string(), + source: SessionSource::default(), + agent_nickname: None, + agent_role: None, + model_provider: Some("openai".to_string()), + base_instructions: None, + dynamic_tools: None, + memory_mode: None, + }; + let polluted_meta = SessionMeta { + memory_mode: Some("polluted".to_string()), + ..session_meta.clone() + }; + let lines = vec![ + RolloutLine { + timestamp: "2026-01-27T12:34:56Z".to_string(), + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: session_meta, + git: None, + }), + }, + RolloutLine { + timestamp: "2026-01-27T12:35:00Z".to_string(), + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: polluted_meta, + git: None, + }), + }, + ]; + let mut file = File::create(&path).expect("create rollout"); + for line in lines { + writeln!( + file, + "{}", + serde_json::to_string(&line).expect("serialize rollout line") + ) + .expect("write rollout line"); + } + + let outcome = extract_metadata_from_rollout(&path, "openai", None) + .await + .expect("extract"); + + assert_eq!(outcome.memory_mode.as_deref(), Some("polluted")); + } + #[test] fn builder_from_items_falls_back_to_filename() { let dir = tempdir().expect("tempdir"); @@ -646,11 +730,62 @@ mod tests { assert!(state.last_success_at.is_some()); } + #[tokio::test] + async fn backfill_sessions_normalizes_cwd_before_upsert() { + let dir = tempdir().expect("tempdir"); + let codex_home = dir.path().to_path_buf(); + let thread_uuid = Uuid::new_v4(); + let session_cwd = codex_home.join("."); + let rollout_path = write_rollout_in_sessions_with_cwd( + codex_home.as_path(), + "2026-01-27T12-34-56", + "2026-01-27T12:34:56Z", + thread_uuid, + session_cwd.clone(), + ); + + let runtime = + codex_state::StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let mut config = crate::config::test_config(); + config.codex_home = codex_home.clone(); + config.model_provider_id = "test-provider".to_string(); + backfill_sessions(runtime.as_ref(), &config, None).await; + + let thread_id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id"); + let stored = runtime + .get_thread(thread_id) + .await + .expect("get thread") + .expect("thread should be backfilled"); + + assert_eq!(stored.rollout_path, rollout_path); + assert_eq!(stored.cwd, normalize_cwd_for_state_db(&session_cwd)); + } + fn write_rollout_in_sessions( codex_home: &Path, filename_ts: &str, event_ts: &str, thread_uuid: Uuid, + ) -> PathBuf { + write_rollout_in_sessions_with_cwd( + codex_home, + filename_ts, + event_ts, + thread_uuid, + codex_home.to_path_buf(), + ) + } + + fn write_rollout_in_sessions_with_cwd( + codex_home: &Path, + filename_ts: &str, + event_ts: &str, + thread_uuid: Uuid, + cwd: PathBuf, ) -> PathBuf { let id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id"); let sessions_dir = codex_home.join("sessions"); @@ -660,7 +795,7 @@ mod tests { id, forked_from_id: None, timestamp: event_ts.to_string(), - cwd: codex_home.to_path_buf(), + cwd, originator: "cli".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::default(), @@ -669,6 +804,7 @@ mod tests { model_provider: Some("test-provider".to_string()), base_instructions: None, dynamic_tools: None, + memory_mode: None, }; let session_meta_line = SessionMetaLine { meta: session_meta, diff --git a/codex-rs/core/src/rollout/mod.rs b/codex-rs/core/src/rollout/mod.rs index 5e6bd9bbff..31ee26dcaa 100644 --- a/codex-rs/core/src/rollout/mod.rs +++ b/codex-rs/core/src/rollout/mod.rs @@ -24,6 +24,7 @@ pub use list::find_thread_path_by_id_str as find_conversation_path_by_id_str; pub use list::rollout_date_parts; pub use recorder::RolloutRecorder; pub use recorder::RolloutRecorderParams; +pub use session_index::append_thread_name; pub use session_index::find_thread_name_by_id; pub use session_index::find_thread_path_by_name_str; diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 8232330232..4c76bc54f6 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -120,7 +120,9 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { | EventMsg::CollabAgentInteractionEnd(_) | EventMsg::CollabWaitingEnd(_) | EventMsg::CollabCloseEnd(_) - | EventMsg::CollabResumeEnd(_) => Some(EventPersistenceMode::Extended), + | EventMsg::CollabResumeEnd(_) + | EventMsg::DynamicToolCallRequest(_) + | EventMsg::DynamicToolCallResponse(_) => Some(EventPersistenceMode::Extended), EventMsg::Warning(_) | EventMsg::RealtimeConversationStarted(_) | EventMsg::RealtimeConversationRealtime(_) @@ -139,9 +141,7 @@ fn event_msg_persistence_mode(ev: &EventMsg) -> Option { | EventMsg::TerminalInteraction(_) | EventMsg::ExecCommandOutputDelta(_) | EventMsg::ExecApprovalRequest(_) - | EventMsg::SkillRequestApproval(_) | EventMsg::RequestUserInput(_) - | EventMsg::DynamicToolCallRequest(_) | EventMsg::ElicitationRequest(_) | EventMsg::ApplyPatchApprovalRequest(_) | EventMsg::BackgroundEvent(_) diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index d612bd14e5..7602b75c6a 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -326,7 +326,9 @@ impl RolloutRecorder { else { break; }; - if let Some(path) = select_resume_path_from_db_page(&db_page, filter_cwd) { + if let Some(path) = + select_resume_path_from_db_page(&db_page, filter_cwd, default_provider).await + { return Ok(Some(path)); } db_cursor = db_page.next_anchor.map(Into::into); @@ -348,7 +350,7 @@ impl RolloutRecorder { default_provider, ) .await?; - if let Some(path) = select_resume_path(&page, filter_cwd) { + if let Some(path) = select_resume_path(&page, filter_cwd, default_provider).await { return Ok(Some(path)); } cursor = page.next_cursor; @@ -410,6 +412,8 @@ impl RolloutRecorder { } else { Some(dynamic_tools) }, + memory_mode: (!config.memories.generate_memories) + .then_some("disabled".to_string()), }; ( @@ -458,6 +462,7 @@ impl RolloutRecorder { state_db_ctx.clone(), state_builder, config.model_provider_id.clone(), + config.memories.generate_memories, )); Ok(Self { @@ -709,6 +714,7 @@ async fn rollout_writer( state_db_ctx: Option, mut state_builder: Option, default_provider: String, + generate_memories: bool, ) -> std::io::Result<()> { let mut writer = file.map(|file| JsonlWriter { file }); let mut buffered_items = Vec::::new(); @@ -729,6 +735,7 @@ async fn rollout_writer( state_db_ctx.as_deref(), &mut state_builder, default_provider.as_str(), + generate_memories, ) .await?; } @@ -782,6 +789,7 @@ async fn rollout_writer( state_db_ctx.as_deref(), &mut state_builder, default_provider.as_str(), + generate_memories, ) .await?; } @@ -829,6 +837,7 @@ async fn rollout_writer( Ok(()) } +#[allow(clippy::too_many_arguments)] async fn write_session_meta( mut writer: Option<&mut JsonlWriter>, session_meta: SessionMeta, @@ -837,6 +846,7 @@ async fn write_session_meta( state_db_ctx: Option<&StateRuntime>, state_builder: &mut Option, default_provider: &str, + generate_memories: bool, ) -> std::io::Result<()> { let git_info = collect_git_info(cwd).await; let session_meta_line = SessionMetaLine { @@ -858,6 +868,7 @@ async fn write_session_meta( state_builder.as_ref(), std::slice::from_ref(&rollout_item), None, + (!generate_memories).then_some("disabled"), ) .await; Ok(()) @@ -886,6 +897,7 @@ async fn write_and_reconcile_items( state_builder.as_ref(), items, "rollout_writer", + None, ) .await; Ok(()) @@ -961,35 +973,79 @@ impl From for ThreadsPage { } } -fn select_resume_path(page: &ThreadsPage, filter_cwd: Option<&Path>) -> Option { +async fn select_resume_path( + page: &ThreadsPage, + filter_cwd: Option<&Path>, + default_provider: &str, +) -> Option { match filter_cwd { - Some(cwd) => page.items.iter().find_map(|item| { - if item - .cwd - .as_ref() - .is_some_and(|session_cwd| cwd_matches(session_cwd, cwd)) - { - Some(item.path.clone()) - } else { - None + Some(cwd) => { + for item in &page.items { + if resume_candidate_matches_cwd( + item.path.as_path(), + item.cwd.as_deref(), + cwd, + default_provider, + ) + .await + { + return Some(item.path.clone()); + } } - }), + None + } None => page.items.first().map(|item| item.path.clone()), } } -fn select_resume_path_from_db_page( +async fn resume_candidate_matches_cwd( + rollout_path: &Path, + cached_cwd: Option<&Path>, + cwd: &Path, + default_provider: &str, +) -> bool { + if cached_cwd.is_some_and(|session_cwd| cwd_matches(session_cwd, cwd)) { + return true; + } + + if let Ok((items, _, _)) = RolloutRecorder::load_rollout_items(rollout_path).await + && let Some(latest_turn_context_cwd) = items.iter().rev().find_map(|item| match item { + RolloutItem::TurnContext(turn_context) => Some(turn_context.cwd.as_path()), + RolloutItem::SessionMeta(_) + | RolloutItem::ResponseItem(_) + | RolloutItem::Compacted(_) + | RolloutItem::EventMsg(_) => None, + }) + { + return cwd_matches(latest_turn_context_cwd, cwd); + } + + metadata::extract_metadata_from_rollout(rollout_path, default_provider, None) + .await + .is_ok_and(|outcome| cwd_matches(outcome.metadata.cwd.as_path(), cwd)) +} + +async fn select_resume_path_from_db_page( page: &codex_state::ThreadsPage, filter_cwd: Option<&Path>, + default_provider: &str, ) -> Option { match filter_cwd { - Some(cwd) => page.items.iter().find_map(|item| { - if cwd_matches(item.cwd.as_path(), cwd) { - Some(item.rollout_path.clone()) - } else { - None + Some(cwd) => { + for item in &page.items { + if resume_candidate_matches_cwd( + item.rollout_path.as_path(), + Some(item.cwd.as_path()), + cwd, + default_provider, + ) + .await + { + return Some(item.rollout_path.clone()); + } } - }), + None + } None => page.items.first().map(|item| item.rollout_path.clone()), } } @@ -1010,8 +1066,12 @@ mod tests { use crate::config::ConfigBuilder; use crate::features::Feature; use chrono::TimeZone; + use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; use codex_protocol::protocol::AgentMessageEvent; + use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; + use codex_protocol::protocol::SandboxPolicy; + use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::UserMessageEvent; use pretty_assertions::assert_eq; use std::fs::File; @@ -1320,4 +1380,50 @@ mod tests { assert_eq!(repaired_path, Some(real_path)); Ok(()) } + + #[tokio::test] + async fn resume_candidate_matches_cwd_reads_latest_turn_context() -> std::io::Result<()> { + let home = TempDir::new().expect("temp dir"); + let stale_cwd = home.path().join("stale"); + let latest_cwd = home.path().join("latest"); + fs::create_dir_all(&stale_cwd)?; + fs::create_dir_all(&latest_cwd)?; + + let path = write_session_file(home.path(), "2025-01-03T13-00-00", Uuid::from_u128(9012))?; + let mut file = std::fs::OpenOptions::new().append(true).open(&path)?; + let turn_context = RolloutLine { + timestamp: "2025-01-03T13:00:01Z".to_string(), + item: RolloutItem::TurnContext(TurnContextItem { + turn_id: Some("turn-1".to_string()), + cwd: latest_cwd.clone(), + current_date: None, + timezone: None, + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + network: None, + model: "test-model".to_string(), + personality: None, + collaboration_mode: None, + realtime_active: None, + effort: None, + summary: ReasoningSummaryConfig::Auto, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: None, + }), + }; + writeln!(file, "{}", serde_json::to_string(&turn_context)?)?; + + assert!( + resume_candidate_matches_cwd( + path.as_path(), + Some(stale_cwd.as_path()), + latest_cwd.as_path(), + "test-provider", + ) + .await + ); + Ok(()) + } } diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index 0eabaee745..14266285f4 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -1109,6 +1109,7 @@ async fn test_updated_at_uses_file_mtime() -> Result<()> { model_provider: Some("test-provider".into()), base_instructions: None, dynamic_tools: None, + memory_mode: None, }, git: None, }), diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index 56c7bff6a6..bbd73749e4 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -17,7 +17,7 @@ use crate::protocol::SandboxPolicy; #[cfg(target_os = "macos")] use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; #[cfg(target_os = "macos")] -use crate::seatbelt::create_seatbelt_command_args; +use crate::seatbelt::create_seatbelt_command_args_with_extensions; #[cfg(target_os = "macos")] use crate::spawn::CODEX_SANDBOX_ENV_VAR; use crate::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; @@ -25,6 +25,8 @@ use crate::tools::sandboxing::SandboxablePreference; use codex_network_proxy::NetworkProxy; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::FileSystemPermissions; +#[cfg(target_os = "macos")] +use codex_protocol::models::MacOsSeatbeltProfileExtensions; use codex_protocol::models::PermissionProfile; pub use codex_protocol::models::SandboxPermissions; use codex_protocol::protocol::ReadOnlyAccess; @@ -73,6 +75,8 @@ pub(crate) struct SandboxTransformRequest<'a> { // to make shared ownership explicit across runtime/sandbox plumbing. pub network: Option<&'a NetworkProxy>, pub sandbox_policy_cwd: &'a Path, + #[cfg(target_os = "macos")] + pub macos_seatbelt_profile_extensions: Option<&'a MacOsSeatbeltProfileExtensions>, pub codex_linux_sandbox_exe: Option<&'a PathBuf>, pub use_linux_sandbox_bwrap: bool, pub windows_sandbox_level: WindowsSandboxLevel, @@ -88,8 +92,6 @@ pub enum SandboxPreference { pub(crate) enum SandboxTransformError { #[error("missing codex-linux-sandbox executable path")] MissingLinuxSandboxExecutable, - #[error("invalid additional permissions path: {0}")] - InvalidAdditionalPermissionsPath(String), #[cfg(not(target_os = "macos"))] #[error("seatbelt sandbox is only available on macOS")] SeatbeltUnavailable, @@ -97,19 +99,16 @@ pub(crate) enum SandboxTransformError { pub(crate) fn normalize_additional_permissions( additional_permissions: PermissionProfile, - command_cwd: &Path, ) -> Result { let Some(file_system) = additional_permissions.file_system else { return Ok(PermissionProfile::default()); }; let read = file_system .read - .map(|paths| normalize_permission_paths(paths, command_cwd, "file_system.read")) - .transpose()?; + .map(|paths| normalize_permission_paths(paths, "file_system.read")); let write = file_system .write - .map(|paths| normalize_permission_paths(paths, command_cwd, "file_system.write")) - .transpose()?; + .map(|paths| normalize_permission_paths(paths, "file_system.write")); Ok(PermissionProfile { file_system: Some(FileSystemPermissions { read, write }), ..Default::default() @@ -117,48 +116,25 @@ pub(crate) fn normalize_additional_permissions( } fn normalize_permission_paths( - paths: Vec, - command_cwd: &Path, - permission_kind: &str, -) -> Result, String> { + paths: Vec, + _permission_kind: &str, +) -> Vec { let mut out = Vec::with_capacity(paths.len()); let mut seen = HashSet::new(); for path in paths { - if path.as_os_str().is_empty() { - return Err(format!("{permission_kind} contains an empty path")); - } - - let resolved = if path.is_absolute() { - AbsolutePathBuf::from_absolute_path(path.clone()).map_err(|err| { - format!( - "{permission_kind} path `{}` is invalid: {err}", - path.display() - ) - })? - } else { - AbsolutePathBuf::resolve_path_against_base(&path, command_cwd).map_err(|err| { - format!( - "{permission_kind} path `{}` cannot be resolved against cwd `{}`: {err}", - path.display(), - command_cwd.display() - ) - })? - }; - - let canonicalized = resolved + let canonicalized = path .as_path() .canonicalize() .ok() .and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok()) - .unwrap_or(resolved); - let canonicalized = canonicalized.to_path_buf(); + .unwrap_or(path); if seen.insert(canonicalized.clone()) { out.push(canonicalized); } } - Ok(out) + out } fn dedup_absolute_paths(paths: Vec) -> Vec { @@ -174,37 +150,23 @@ fn dedup_absolute_paths(paths: Vec) -> Vec { fn additional_permission_roots( additional_permissions: &PermissionProfile, -) -> Result<(Vec, Vec), SandboxTransformError> { - let to_abs = |paths: &[PathBuf]| { - let mut out = Vec::with_capacity(paths.len()); - for path in paths { - let absolute = AbsolutePathBuf::from_absolute_path(path.clone()).map_err(|err| { - SandboxTransformError::InvalidAdditionalPermissionsPath(format!( - "`{}`: {err}", - path.display() - )) - })?; - out.push(absolute); - } - Ok(dedup_absolute_paths(out)) - }; - - Ok(( - to_abs( +) -> (Vec, Vec) { + ( + dedup_absolute_paths( additional_permissions .file_system .as_ref() - .and_then(|file_system| file_system.read.as_deref()) + .and_then(|file_system| file_system.read.clone()) .unwrap_or_default(), - )?, - to_abs( + ), + dedup_absolute_paths( additional_permissions .file_system .as_ref() - .and_then(|file_system| file_system.write.as_deref()) + .and_then(|file_system| file_system.write.clone()) .unwrap_or_default(), - )?, - )) + ), + ) } fn merge_read_only_access_with_additional_reads( @@ -235,7 +197,7 @@ fn sandbox_policy_with_additional_permissions( return Ok(sandbox_policy.clone()); } - let (extra_reads, extra_writes) = additional_permission_roots(additional_permissions)?; + let (extra_reads, extra_writes) = additional_permission_roots(additional_permissions); let policy = match sandbox_policy { SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } => { @@ -342,6 +304,8 @@ impl SandboxManager { enforce_managed_network, network, sandbox_policy_cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions, codex_linux_sandbox_exe, use_linux_sandbox_bwrap, windows_sandbox_level, @@ -370,12 +334,13 @@ impl SandboxManager { SandboxType::MacosSeatbelt => { let mut seatbelt_env = HashMap::new(); seatbelt_env.insert(CODEX_SANDBOX_ENV_VAR.to_string(), "seatbelt".to_string()); - let mut args = create_seatbelt_command_args( + let mut args = create_seatbelt_command_args_with_extensions( command.clone(), &effective_policy, sandbox_policy_cwd, enforce_managed_network, network, + macos_seatbelt_profile_extensions, ); let mut full_command = Vec::with_capacity(1 + args.len()); full_command.push(MACOS_PATH_TO_SEATBELT_EXECUTABLE.to_string()); diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index d3f630738e..c9c2801209 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -581,6 +581,57 @@ mod tests { assert!(policy.contains("com.apple.CalendarAgent")); } + #[test] + fn bundle_id_automation_keeps_lsopen_denied() { + let tmp = TempDir::new().expect("tempdir"); + let cwd = tmp.path().join("cwd"); + fs::create_dir_all(&cwd).expect("create cwd"); + + let args = create_seatbelt_command_args_with_extensions( + vec![ + "/usr/bin/python3".to_string(), + "-c".to_string(), + r#"import ctypes +import os +import sys +lib = ctypes.CDLL("/usr/lib/libsandbox.1.dylib") +lib.sandbox_check.restype = ctypes.c_int +allowed = lib.sandbox_check(os.getpid(), b"lsopen", 0) == 0 +sys.exit(0 if allowed else 13) +"# + .to_string(), + ], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + Some(&MacOsSeatbeltProfileExtensions { + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + ..Default::default() + }), + ); + + let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + .args(&args) + .current_dir(&cwd) + .output() + .expect("execute seatbelt command"); + + let stderr = String::from_utf8_lossy(&output.stderr); + if stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted") { + return; + } + + assert_eq!( + Some(13), + output.status.code(), + "lsopen should remain denied even with bundle-scoped automation\nstdout: {}\nstderr: {stderr}", + String::from_utf8_lossy(&output.stdout), + ); + } + #[test] fn seatbelt_args_without_extension_profile_keep_legacy_preferences_read_access() { let cwd = std::env::temp_dir(); diff --git a/codex-rs/core/src/seatbelt_permissions.rs b/codex-rs/core/src/seatbelt_permissions.rs index aacc3a7784..93bc0965aa 100644 --- a/codex-rs/core/src/seatbelt_permissions.rs +++ b/codex-rs/core/src/seatbelt_permissions.rs @@ -3,34 +3,9 @@ use std::collections::BTreeSet; use std::path::PathBuf; -#[allow(dead_code)] -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub enum MacOsPreferencesPermission { - // IMPORTANT: ReadOnly needs to be the default because it's the security-sensitive default. - // it's important for allowing cf prefs to work. - #[default] - ReadOnly, - ReadWrite, - None, -} - -#[allow(dead_code)] -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub enum MacOsAutomationPermission { - #[default] - None, - All, - BundleIds(Vec), -} - -#[allow(dead_code)] -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct MacOsSeatbeltProfileExtensions { - pub macos_preferences: MacOsPreferencesPermission, - pub macos_automation: MacOsAutomationPermission, - pub macos_accessibility: bool, - pub macos_calendar: bool, -} +pub use codex_protocol::models::MacOsAutomationPermission; +pub use codex_protocol::models::MacOsPreferencesPermission; +pub use codex_protocol::models::MacOsSeatbeltProfileExtensions; #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct SeatbeltExtensionPolicy { @@ -38,25 +13,26 @@ pub(crate) struct SeatbeltExtensionPolicy { pub(crate) dir_params: Vec<(String, PathBuf)>, } -impl MacOsSeatbeltProfileExtensions { - pub fn normalized(&self) -> Self { - let mut normalized = self.clone(); - if let MacOsAutomationPermission::BundleIds(bundle_ids) = &self.macos_automation { - let bundle_ids = normalize_bundle_ids(bundle_ids); - normalized.macos_automation = if bundle_ids.is_empty() { - MacOsAutomationPermission::None - } else { - MacOsAutomationPermission::BundleIds(bundle_ids) - }; - } - normalized +fn normalized_extensions( + extensions: &MacOsSeatbeltProfileExtensions, +) -> MacOsSeatbeltProfileExtensions { + let mut normalized = extensions.clone(); + if let MacOsAutomationPermission::BundleIds(bundle_ids) = &extensions.macos_automation { + let bundle_ids = normalize_bundle_ids(bundle_ids); + normalized.macos_automation = if bundle_ids.is_empty() { + MacOsAutomationPermission::None + } else { + MacOsAutomationPermission::BundleIds(bundle_ids) + }; } + + normalized } pub(crate) fn build_seatbelt_extensions( extensions: &MacOsSeatbeltProfileExtensions, ) -> SeatbeltExtensionPolicy { - let extensions = extensions.normalized(); + let extensions = normalized_extensions(extensions); let mut clauses = Vec::new(); match extensions.macos_preferences { @@ -106,7 +82,7 @@ pub(crate) fn build_seatbelt_extensions( MacOsAutomationPermission::BundleIds(bundle_ids) => { if !bundle_ids.is_empty() { clauses.push( - "(allow mach-lookup (global-name \"com.apple.coreservices.appleevents\"))" + "(allow mach-lookup\n (global-name \"com.apple.coreservices.launchservicesd\")\n (global-name \"com.apple.coreservices.appleevents\"))" .to_string(), ); let destinations = bundle_ids diff --git a/codex-rs/core/src/session_prefix.rs b/codex-rs/core/src/session_prefix.rs index 5f8516ba93..db3ac00a6d 100644 --- a/codex-rs/core/src/session_prefix.rs +++ b/codex-rs/core/src/session_prefix.rs @@ -1,28 +1,8 @@ use codex_protocol::protocol::AgentStatus; -/// Helpers for identifying model-visible "session prefix" messages. -/// -/// A session prefix is a user-role message that carries configuration or state needed by -/// follow-up turns (e.g. ``, ``). These items are persisted in -/// history so the model can see them, but they are not user intent and must not create user-turn -/// boundaries. -pub(crate) const ENVIRONMENT_CONTEXT_OPEN_TAG: &str = ""; -pub(crate) const TURN_ABORTED_OPEN_TAG: &str = ""; -pub(crate) const SUBAGENT_NOTIFICATION_OPEN_TAG: &str = ""; -pub(crate) const SUBAGENT_NOTIFICATION_CLOSE_TAG: &str = ""; - -fn starts_with_ascii_case_insensitive(text: &str, prefix: &str) -> bool { - text.get(..prefix.len()) - .is_some_and(|candidate| candidate.eq_ignore_ascii_case(prefix)) -} - -/// Returns true if `text` starts with a session prefix marker (case-insensitive). -pub(crate) fn is_session_prefix(text: &str) -> bool { - let trimmed = text.trim_start(); - starts_with_ascii_case_insensitive(trimmed, ENVIRONMENT_CONTEXT_OPEN_TAG) - || starts_with_ascii_case_insensitive(trimmed, TURN_ABORTED_OPEN_TAG) - || starts_with_ascii_case_insensitive(trimmed, SUBAGENT_NOTIFICATION_OPEN_TAG) -} +/// Helpers for model-visible session state markers that are stored in user-role +/// messages but are not user intent. +use crate::contextual_user_message::SUBAGENT_NOTIFICATION_FRAGMENT; pub(crate) fn format_subagent_notification_message(agent_id: &str, status: &AgentStatus) -> String { let payload_json = serde_json::json!({ @@ -30,19 +10,12 @@ pub(crate) fn format_subagent_notification_message(agent_id: &str, status: &Agen "status": status, }) .to_string(); - format!("{SUBAGENT_NOTIFICATION_OPEN_TAG}\n{payload_json}\n{SUBAGENT_NOTIFICATION_CLOSE_TAG}") + SUBAGENT_NOTIFICATION_FRAGMENT.wrap(payload_json) } -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn is_session_prefix_is_case_insensitive() { - assert_eq!( - is_session_prefix("{}"), - true - ); +pub(crate) fn format_subagent_context_line(agent_id: &str, agent_nickname: Option<&str>) -> String { + match agent_nickname.filter(|nickname| !nickname.is_empty()) { + Some(agent_nickname) => format!("- {agent_id}: {agent_nickname}"), + None => format!("- {agent_id}"), } } diff --git a/codex-rs/core/src/shell_snapshot.rs b/codex-rs/core/src/shell_snapshot.rs index 7dc122e931..291129f977 100644 --- a/codex-rs/core/src/shell_snapshot.rs +++ b/codex-rs/core/src/shell_snapshot.rs @@ -360,19 +360,17 @@ alias_count=$(alias -p | wc -l | tr -d ' ') echo "# aliases $alias_count" alias -p echo '' -export_lines=$(export -p | awk ' -/^(export|declare -x|typeset -x) / { - line=$0 - name=line - sub(/^(export|declare -x|typeset -x) /, "", name) - sub(/=.*/, "", name) - if (name ~ /^(EXCLUDED_EXPORTS)$/) { - next - } - if (name ~ /^[A-Za-z_][A-Za-z0-9_]*$/) { - print line - } -}') +export_lines=$( + while IFS= read -r name; do + if [[ "$name" =~ ^(EXCLUDED_EXPORTS)$ ]]; then + continue + fi + if [[ ! "$name" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then + continue + fi + declare -xp "$name" 2>/dev/null || true + done < <(compgen -e) +) export_count=$(printf '%s\n' "$export_lines" | sed '/^$/d' | wc -l | tr -d ' ') echo "# exports $export_count" if [ -n "$export_lines" ]; then @@ -671,6 +669,46 @@ mod tests { Ok(()) } + #[cfg(unix)] + #[test] + fn bash_snapshot_preserves_multiline_exports() -> Result<()> { + let multiline_cert = "-----BEGIN CERTIFICATE-----\nabc\n-----END CERTIFICATE-----"; + let output = Command::new("/bin/bash") + .arg("-c") + .arg(bash_snapshot_script()) + .env("BASH_ENV", "/dev/null") + .env("MULTILINE_CERT", multiline_cert) + .output()?; + + assert!(output.status.success()); + + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("MULTILINE_CERT=") || stdout.contains("MULTILINE_CERT"), + "snapshot should include the multiline export name" + ); + + let dir = tempdir()?; + let snapshot_path = dir.path().join("snapshot.sh"); + std::fs::write(&snapshot_path, stdout.as_bytes())?; + + let validate = Command::new("/bin/bash") + .arg("-c") + .arg("set -e; . \"$1\"") + .arg("bash") + .arg(&snapshot_path) + .env("BASH_ENV", "/dev/null") + .output()?; + + assert!( + validate.status.success(), + "snapshot validation failed: {}", + String::from_utf8_lossy(&validate.stderr) + ); + + Ok(()) + } + #[cfg(unix)] #[tokio::test] async fn try_new_creates_and_deletes_snapshot_file() -> Result<()> { diff --git a/codex-rs/core/src/skills/injection.rs b/codex-rs/core/src/skills/injection.rs index e7856897a2..e293aac59f 100644 --- a/codex-rs/core/src/skills/injection.rs +++ b/codex-rs/core/src/skills/injection.rs @@ -464,7 +464,7 @@ fn text_mentions_skill(text: &str, skill_name: &str) -> bool { } fn is_mention_name_char(byte: u8) -> bool { - matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') + matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-' | b':') } #[cfg(test)] @@ -483,7 +483,6 @@ mod tests { dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: PathBuf::from(path), scope: codex_protocol::protocol::SkillScope::User, } @@ -586,6 +585,15 @@ mod tests { ); } + #[test] + fn extract_tool_mentions_keeps_plugin_skill_namespaces() { + assert_mentions( + "use $slack:search and $alpha", + &["alpha", "slack:search"], + &[], + ); + } + #[test] fn collect_explicit_skill_mentions_text_respects_skill_order() { let alpha = make_skill("alpha-skill", "/tmp/alpha"); diff --git a/codex-rs/core/src/skills/invocation_utils.rs b/codex-rs/core/src/skills/invocation_utils.rs index 5e6a851db6..36bb0c3caa 100644 --- a/codex-rs/core/src/skills/invocation_utils.rs +++ b/codex-rs/core/src/skills/invocation_utils.rs @@ -7,21 +7,8 @@ use crate::analytics_client::SkillInvocation; use crate::analytics_client::build_track_events_context; use crate::codex::Session; use crate::codex::TurnContext; -use crate::features::Feature; use crate::skills::SkillLoadOutcome; use crate::skills::SkillMetadata; -use codex_protocol::protocol::ReviewDecision; -use serde::Serialize; - -pub(crate) const SKILL_APPROVAL_DECLINED_MESSAGE: &str = - "This script is part of the skill and the user declined the skill usage"; - -#[derive(Debug, Serialize)] -struct SkillApprovalCacheKey { - skill_name: String, - skill_path: PathBuf, - skill_scope: codex_protocol::protocol::SkillScope, -} pub(crate) fn build_implicit_skill_path_indexes( skills: Vec, @@ -54,11 +41,8 @@ fn detect_implicit_skill_invocation_for_command( let workdir = normalize_path(workdir.as_path()); let tokens = tokenize_command(command); - if let Some(candidate) = detect_implicit_skill_script_invocation_for_tokens( - outcome, - tokens.as_slice(), - workdir.as_path(), - ) { + if let Some(candidate) = detect_skill_script_run(outcome, tokens.as_slice(), workdir.as_path()) + { return Some(candidate); } @@ -69,82 +53,6 @@ fn detect_implicit_skill_invocation_for_command( None } -pub(crate) fn detect_implicit_skill_script_invocation_for_command( - outcome: &SkillLoadOutcome, - command: &str, - workdir: &Path, -) -> Option { - let tokens = tokenize_command(command); - - detect_implicit_skill_script_invocation_for_tokens(outcome, tokens.as_slice(), workdir) -} - -pub(crate) fn detect_implicit_skill_script_invocation_for_tokens( - outcome: &SkillLoadOutcome, - command: &[String], - workdir: &Path, -) -> Option { - detect_skill_script_run(outcome, command, workdir) -} - -fn tokenize_command(command: &str) -> Vec { - shlex::split(command).unwrap_or_else(|| { - command - .split_whitespace() - .map(std::string::ToString::to_string) - .collect() - }) -} - -pub(crate) async fn ensure_skill_approval_for_command( - sess: &Session, - turn_context: &TurnContext, - item_id: &str, - command: &str, - workdir: &Path, -) -> bool { - if !turn_context.features.enabled(Feature::SkillApproval) { - return true; - } - - let workdir = normalize_path(workdir); - let Some(skill) = detect_implicit_skill_script_invocation_for_command( - turn_context.turn_skills.outcome.as_ref(), - command, - workdir.as_path(), - ) else { - return true; - }; - - let cache_key = SkillApprovalCacheKey { - skill_name: skill.name.clone(), - skill_path: skill.path_to_skills_md.clone(), - skill_scope: skill.scope, - }; - let already_approved = { - let store = sess.services.tool_approvals.lock().await; - matches!( - store.get(&cache_key), - Some(ReviewDecision::ApprovedForSession) - ) - }; - if already_approved { - return true; - } - - let approved = sess - .request_skill_approval(turn_context, item_id.to_string(), skill.name) - .await - .is_some_and(|response| response.approved); - if !approved { - return false; - } - - let mut store = sess.services.tool_approvals.lock().await; - store.put(cache_key, ReviewDecision::ApprovedForSession); - true -} - pub(crate) async fn maybe_emit_implicit_skill_invocation( sess: &Session, turn_context: &TurnContext, @@ -207,6 +115,15 @@ pub(crate) async fn maybe_emit_implicit_skill_invocation( ); } +fn tokenize_command(command: &str) -> Vec { + shlex::split(command).unwrap_or_else(|| { + command + .split_whitespace() + .map(std::string::ToString::to_string) + .collect() + }) +} + fn script_run_token(tokens: &[String]) -> Option<&str> { const RUNNERS: [&str; 10] = [ "python", "python3", "bash", "zsh", "sh", "node", "deno", "ruby", "perl", "pwsh", @@ -317,7 +234,6 @@ fn normalize_path(path: &Path) -> PathBuf { mod tests { use super::SkillLoadOutcome; use super::SkillMetadata; - use super::detect_implicit_skill_script_invocation_for_command; use super::detect_skill_doc_read; use super::detect_skill_script_run; use super::normalize_path; @@ -337,7 +253,6 @@ mod tests { dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: skill_doc_path, scope: codex_protocol::protocol::SkillScope::User, } @@ -438,50 +353,4 @@ mod tests { Some("test-skill".to_string()) ); } - - #[test] - fn implicit_skill_script_invocation_matches_command() { - let skill_doc_path = PathBuf::from("/tmp/skill-test/SKILL.md"); - let scripts_dir = normalize_path(Path::new("/tmp/skill-test/scripts")); - let skill = test_skill_metadata(skill_doc_path); - let outcome = SkillLoadOutcome { - implicit_skills_by_scripts_dir: Arc::new(HashMap::from([(scripts_dir, skill)])), - implicit_skills_by_doc_path: Arc::new(HashMap::new()), - ..Default::default() - }; - - let found = detect_implicit_skill_script_invocation_for_command( - &outcome, - "python scripts/fetch_comments.py", - Path::new("/tmp/skill-test"), - ); - - assert_eq!( - found.map(|value| value.name), - Some("test-skill".to_string()) - ); - } - - #[test] - fn implicit_skill_script_invocation_ignores_doc_reads() { - let skill_doc_path = PathBuf::from("/tmp/skill-test/SKILL.md"); - let normalized_skill_doc_path = normalize_path(skill_doc_path.as_path()); - let skill = test_skill_metadata(skill_doc_path); - let outcome = SkillLoadOutcome { - implicit_skills_by_scripts_dir: Arc::new(HashMap::new()), - implicit_skills_by_doc_path: Arc::new(HashMap::from([( - normalized_skill_doc_path, - skill, - )])), - ..Default::default() - }; - - let found = detect_implicit_skill_script_invocation_for_command( - &outcome, - "cat SKILL.md", - Path::new("/tmp/skill-test"), - ); - - assert_eq!(found, None); - } } diff --git a/codex-rs/core/src/skills/loader.rs b/codex-rs/core/src/skills/loader.rs index a1aa3c630e..bfa22cf01b 100644 --- a/codex-rs/core/src/skills/loader.rs +++ b/codex-rs/core/src/skills/loader.rs @@ -1,10 +1,9 @@ -use crate::config::Config; -use crate::config::Permissions; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigLayerStackOrdering; use crate::config_loader::default_project_root_markers; use crate::config_loader::merge_toml_values; use crate::config_loader::project_root_markers_from_config; +use crate::plugins::plugin_namespace_for_skill_path; use crate::skills::model::SkillDependencies; use crate::skills::model::SkillError; use crate::skills::model::SkillInterface; @@ -12,11 +11,11 @@ use crate::skills::model::SkillLoadOutcome; use crate::skills::model::SkillMetadata; use crate::skills::model::SkillPolicy; use crate::skills::model::SkillToolDependency; -use crate::skills::permissions::compile_permission_profile; use crate::skills::system::system_cache_root_dir; use codex_app_server_protocol::ConfigLayerSource; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::SkillScope; +use codex_utils_absolute_path::AbsolutePathBufGuard; use dirs::home_dir; use dunce::canonicalize as canonicalize_path; use serde::Deserialize; @@ -31,10 +30,15 @@ use std::path::PathBuf; use toml::Value as TomlValue; use tracing::error; +#[cfg(test)] +use crate::config::Config; + #[derive(Debug, Deserialize)] struct SkillFrontmatter { - name: String, - description: String, + #[serde(default)] + name: Option, + #[serde(default)] + description: Option, #[serde(default)] metadata: SkillFrontmatterMetadata, } @@ -63,7 +67,6 @@ struct LoadedSkillMetadata { dependencies: Option, policy: Option, permission_profile: Option, - permissions: Option, } #[derive(Debug, Default, Deserialize)] @@ -145,20 +148,6 @@ impl fmt::Display for SkillParseError { impl Error for SkillParseError {} -pub fn load_skills(config: &Config) -> SkillLoadOutcome { - load_skills_with_home_dir(config, home_dir().as_deref()) -} - -fn load_skills_with_home_dir(config: &Config, home_dir: Option<&Path>) -> SkillLoadOutcome { - let mut roots = skill_roots_from_layer_stack_inner(&config.config_layer_stack, home_dir); - roots.extend(repo_agents_skill_roots( - &config.config_layer_stack, - &config.cwd, - )); - dedupe_skill_roots_by_path(&mut roots); - load_skills_from_roots(roots) -} - pub(crate) struct SkillRoot { pub(crate) path: PathBuf, pub(crate) scope: SkillScope, @@ -198,6 +187,35 @@ where outcome } +pub(crate) fn skill_roots( + config_layer_stack: &ConfigLayerStack, + cwd: &Path, + plugin_skill_roots: Vec, +) -> Vec { + skill_roots_with_home_dir( + config_layer_stack, + cwd, + home_dir().as_deref(), + plugin_skill_roots, + ) +} + +fn skill_roots_with_home_dir( + config_layer_stack: &ConfigLayerStack, + cwd: &Path, + home_dir: Option<&Path>, + plugin_skill_roots: Vec, +) -> Vec { + let mut roots = skill_roots_from_layer_stack_inner(config_layer_stack, home_dir); + roots.extend(plugin_skill_roots.into_iter().map(|path| SkillRoot { + path, + scope: SkillScope::User, + })); + roots.extend(repo_agents_skill_roots(config_layer_stack, cwd)); + dedupe_skill_roots_by_path(&mut roots); + roots +} + fn skill_roots_from_layer_stack_inner( config_layer_stack: &ConfigLayerStack, home_dir: Option<&Path>, @@ -259,34 +277,6 @@ fn skill_roots_from_layer_stack_inner( roots } -#[cfg(test)] -fn skill_roots(config: &Config) -> Vec { - skill_roots_from_layer_stack_with_agents(&config.config_layer_stack, &config.cwd) -} - -#[cfg(test)] -pub(crate) fn skill_roots_from_layer_stack( - config_layer_stack: &ConfigLayerStack, - home_dir: Option<&Path>, -) -> Vec { - skill_roots_from_layer_stack_inner(config_layer_stack, home_dir) -} - -pub(crate) fn skill_roots_from_layer_stack_with_agents( - config_layer_stack: &ConfigLayerStack, - cwd: &Path, -) -> Vec { - let mut roots = skill_roots_from_layer_stack_inner(config_layer_stack, home_dir().as_deref()); - roots.extend(repo_agents_skill_roots(config_layer_stack, cwd)); - dedupe_skill_roots_by_path(&mut roots); - roots -} - -fn dedupe_skill_roots_by_path(roots: &mut Vec) { - let mut seen: HashSet = HashSet::new(); - roots.retain(|root| seen.insert(root.path.clone())); -} - fn repo_agents_skill_roots(config_layer_stack: &ConfigLayerStack, cwd: &Path) -> Vec { let project_root_markers = project_root_markers_from_stack(config_layer_stack); let project_root = find_project_root(cwd, &project_root_markers); @@ -360,6 +350,11 @@ fn dirs_between_project_root_and_cwd(cwd: &Path, project_root: &Path) -> Vec) { + let mut seen: HashSet = HashSet::new(); + roots.retain(|root| seen.insert(root.path.clone())); +} + fn discover_skills_under_root(root: &Path, scope: SkillScope, outcome: &mut SkillLoadOutcome) { let Ok(root) = canonicalize_path(root) else { return; @@ -507,8 +502,18 @@ fn parse_skill_file(path: &Path, scope: SkillScope) -> Result Result Result String { + path.parent() + .and_then(Path::file_name) + .and_then(|name| name.to_str()) + .map(sanitize_single_line) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| "skill".to_string()) +} + +fn namespaced_skill_name(path: &Path, base_name: &str) -> String { + plugin_namespace_for_skill_path(path) + .map(|namespace| format!("{namespace}:{base_name}")) + .unwrap_or_else(|| base_name.to_string()) +} + fn load_skill_metadata(skill_path: &Path) -> LoadedSkillMetadata { // Fail open: optional metadata should not block loading SKILL.md. let Some(skill_dir) = skill_path.parent() else { @@ -573,15 +591,18 @@ fn load_skill_metadata(skill_path: &Path) -> LoadedSkillMetadata { } }; - let parsed: SkillMetadataFile = match serde_yaml::from_str(&contents) { - Ok(parsed) => parsed, - Err(error) => { - tracing::warn!( - "ignoring {path}: invalid {label}: {error}", - path = metadata_path.display(), - label = SKILLS_METADATA_FILENAME - ); - return LoadedSkillMetadata::default(); + let parsed: SkillMetadataFile = { + let _guard = AbsolutePathBufGuard::new(skill_dir); + match serde_yaml::from_str(&contents) { + Ok(parsed) => parsed, + Err(error) => { + tracing::warn!( + "ignoring {path}: invalid {label}: {error}", + path = metadata_path.display(), + label = SKILLS_METADATA_FILENAME + ); + return LoadedSkillMetadata::default(); + } } }; @@ -591,14 +612,11 @@ fn load_skill_metadata(skill_path: &Path) -> LoadedSkillMetadata { policy, permissions, } = parsed; - let permission_profile = permissions.clone().filter(|profile| !profile.is_empty()); - LoadedSkillMetadata { interface: resolve_interface(interface, skill_dir), dependencies: resolve_dependencies(dependencies), policy: resolve_policy(policy), - permission_profile, - permissions: compile_permission_profile(skill_dir, permissions), + permission_profile: permissions.filter(|profile| !profile.is_empty()), } } @@ -824,6 +842,13 @@ fn extract_frontmatter(contents: &str) -> Option { Some(frontmatter_lines.join("\n")) } +#[cfg(test)] +pub(crate) fn skill_roots_from_layer_stack( + config_layer_stack: &ConfigLayerStack, + home_dir: Option<&Path>, +) -> Vec { + skill_roots_with_home_dir(config_layer_stack, Path::new("."), home_dir, Vec::new()) +} #[cfg(test)] mod tests { @@ -831,9 +856,7 @@ mod tests { use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; use crate::config::ConfigToml; - use crate::config::Constrained; use crate::config::ProjectConfig; - use crate::config::types::ShellEnvironmentPolicy; use crate::config_loader::ConfigLayerEntry; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigRequirements; @@ -893,7 +916,12 @@ mod tests { fn load_skills_for_test(config: &Config) -> SkillLoadOutcome { // Keep unit tests hermetic by never scanning the real `$HOME/.agents/skills`. - super::load_skills_with_home_dir(config, None) + super::load_skills_from_roots(super::skill_roots_with_home_dir( + &config.config_layer_stack, + &config.cwd, + None, + Vec::new(), + )) } fn mark_as_git_repo(dir: &Path) { @@ -1062,7 +1090,6 @@ mod tests { dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1101,6 +1128,15 @@ mod tests { path } + fn write_raw_skill_at(root: &Path, dir: &str, frontmatter: &str) -> PathBuf { + let skill_dir = root.join(dir); + fs::create_dir_all(&skill_dir).unwrap(); + let path = skill_dir.join(SKILLS_FILENAME); + let content = format!("---\n{frontmatter}\n---\n\n# Body\n"); + fs::write(&path, content).unwrap(); + path + } + fn write_skill_metadata_at(skill_dir: &Path, contents: &str) -> PathBuf { let path = skill_dir .join(SKILLS_METADATA_DIR) @@ -1211,7 +1247,6 @@ mod tests { }), policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1268,7 +1303,6 @@ interface: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(skill_path.as_path()), scope: SkillScope::User, }] @@ -1376,50 +1410,18 @@ permissions: Some(PermissionProfile { network: Some(true), file_system: Some(FileSystemPermissions { - read: Some(vec![PathBuf::from("./data")]), - write: Some(vec![PathBuf::from("./output")]), + read: Some(vec![ + AbsolutePathBuf::try_from(normalized(skill_dir.join("data").as_path())) + .expect("absolute data path"), + ]), + write: Some(vec![ + AbsolutePathBuf::try_from(normalized(skill_dir.join("output").as_path())) + .expect("absolute output path"), + ]), }), macos: None, }) ); - #[cfg(target_os = "macos")] - let macos_seatbelt_profile_extensions = - Some(crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions::default()); - #[cfg(not(target_os = "macos"))] - let macos_seatbelt_profile_extensions = None; - assert_eq!( - outcome.skills[0].permissions, - Some(Permissions { - approval_policy: Constrained::allow_any(crate::protocol::AskForApproval::Never), - sandbox_policy: Constrained::allow_any( - crate::protocol::SandboxPolicy::WorkspaceWrite { - writable_roots: vec![ - AbsolutePathBuf::try_from(normalized( - skill_dir.join("output").as_path(), - )) - .expect("absolute output path") - ], - read_only_access: crate::protocol::ReadOnlyAccess::Restricted { - include_platform_defaults: true, - readable_roots: vec![ - AbsolutePathBuf::try_from(normalized( - skill_dir.join("data").as_path(), - )) - .expect("absolute data path") - ], - }, - network_access: true, - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - } - ), - network: None, - allow_login_shell: true, - shell_environment_policy: ShellEnvironmentPolicy::default(), - windows_sandbox_mode: None, - macos_seatbelt_profile_extensions, - }) - ); } #[tokio::test] @@ -1444,34 +1446,7 @@ permissions: {} outcome.errors ); assert_eq!(outcome.skills.len(), 1); - #[cfg(target_os = "macos")] - let expected = Some(Permissions { - approval_policy: Constrained::allow_any(crate::protocol::AskForApproval::Never), - sandbox_policy: Constrained::allow_any( - crate::protocol::SandboxPolicy::new_read_only_policy(), - ), - network: None, - allow_login_shell: true, - shell_environment_policy: ShellEnvironmentPolicy::default(), - windows_sandbox_mode: None, - macos_seatbelt_profile_extensions: Some( - crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions::default(), - ), - }); - #[cfg(not(target_os = "macos"))] - let expected = Some(Permissions { - approval_policy: Constrained::allow_any(crate::protocol::AskForApproval::Never), - sandbox_policy: Constrained::allow_any( - crate::protocol::SandboxPolicy::new_read_only_policy(), - ), - network: None, - allow_login_shell: true, - shell_environment_policy: ShellEnvironmentPolicy::default(), - windows_sandbox_mode: None, - macos_seatbelt_profile_extensions: None, - }); assert_eq!(outcome.skills[0].permission_profile, None); - assert_eq!(outcome.skills[0].permissions, expected); } #[cfg(target_os = "macos")] @@ -1503,24 +1478,21 @@ permissions: outcome.errors ); assert_eq!(outcome.skills.len(), 1); - let profile = outcome.skills[0] - .permissions - .as_ref() - .expect("permission profile"); assert_eq!( - profile.macos_seatbelt_profile_extensions, - Some( - crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions { - macos_preferences: - crate::seatbelt_permissions::MacOsPreferencesPermission::ReadWrite, - macos_automation: - crate::seatbelt_permissions::MacOsAutomationPermission::BundleIds(vec![ - "com.apple.Notes".to_string() - ],), - macos_accessibility: true, - macos_calendar: true, - } - ) + outcome.skills[0].permission_profile, + Some(PermissionProfile { + macos: Some(codex_protocol::models::MacOsPermissions { + preferences: Some(codex_protocol::models::MacOsPreferencesValue::Mode( + "readwrite".to_string(), + ),), + automations: Some(codex_protocol::models::MacOsAutomationValue::BundleIds( + vec!["com.apple.Notes".to_string()], + )), + accessibility: Some(true), + calendar: Some(true), + }), + ..Default::default() + }) ); } @@ -1554,17 +1526,19 @@ permissions: ); assert_eq!(outcome.skills.len(), 1); assert_eq!( - outcome.skills[0].permissions, - Some(Permissions { - approval_policy: Constrained::allow_any(crate::protocol::AskForApproval::Never), - sandbox_policy: Constrained::allow_any( - crate::protocol::SandboxPolicy::new_read_only_policy(), - ), - network: None, - allow_login_shell: true, - shell_environment_policy: ShellEnvironmentPolicy::default(), - windows_sandbox_mode: None, - macos_seatbelt_profile_extensions: None, + outcome.skills[0].permission_profile, + Some(PermissionProfile { + macos: Some(codex_protocol::models::MacOsPermissions { + preferences: Some(codex_protocol::models::MacOsPreferencesValue::Mode( + "readwrite".to_string(), + )), + automations: Some(codex_protocol::models::MacOsAutomationValue::BundleIds( + vec!["com.apple.Notes".to_string()], + )), + accessibility: Some(true), + calendar: Some(true), + }), + ..Default::default() }) ); } @@ -1614,7 +1588,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1656,7 +1629,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1711,7 +1683,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1754,7 +1725,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1800,7 +1770,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&shared_skill_path), scope: SkillScope::User, }] @@ -1862,7 +1831,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -1900,7 +1868,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&shared_skill_path), scope: SkillScope::Admin, }] @@ -1942,7 +1909,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&linked_skill_path), scope: SkillScope::Repo, }] @@ -2011,7 +1977,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&within_depth_path), scope: SkillScope::User, }] @@ -2040,7 +2005,81 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, + path_to_skills_md: normalized(&skill_path), + scope: SkillScope::User, + }] + ); + } + + #[tokio::test] + async fn falls_back_to_directory_name_when_skill_name_is_missing() { + let codex_home = tempfile::tempdir().expect("tempdir"); + let skill_path = write_raw_skill_at( + &codex_home.path().join("skills"), + "directory-derived", + "description: fallback name", + ); + let cfg = make_config(&codex_home).await; + + let outcome = load_skills_for_test(&cfg); + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![SkillMetadata { + name: "directory-derived".to_string(), + description: "fallback name".to_string(), + short_description: None, + interface: None, + dependencies: None, + policy: None, + permission_profile: None, + path_to_skills_md: normalized(&skill_path), + scope: SkillScope::User, + }] + ); + } + + #[tokio::test] + async fn namespaces_plugin_skills_using_plugin_name() { + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("plugins/sample"); + let skill_path = write_raw_skill_at( + &plugin_root.join("skills"), + "sample-search", + "description: search sample data", + ); + fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); + fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ) + .unwrap(); + + let outcome = load_skills_from_roots([SkillRoot { + path: plugin_root.join("skills"), + scope: SkillScope::User, + }]); + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![SkillMetadata { + name: "sample:sample-search".to_string(), + description: "search sample data".to_string(), + short_description: None, + interface: None, + dependencies: None, + policy: None, + permission_profile: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -2073,7 +2112,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::User, }] @@ -2187,7 +2225,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -2224,7 +2261,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -2279,7 +2315,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&nested_skill_path), scope: SkillScope::Repo, }, @@ -2291,7 +2326,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&root_skill_path), scope: SkillScope::Repo, }, @@ -2332,7 +2366,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -2371,7 +2404,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -2414,7 +2446,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&repo_skill_path), scope: SkillScope::Repo, }, @@ -2426,7 +2457,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&user_skill_path), scope: SkillScope::User, }, @@ -2492,7 +2522,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: first_path, scope: SkillScope::Repo, }, @@ -2504,7 +2533,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: second_path, scope: SkillScope::Repo, }, @@ -2577,7 +2605,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::Repo, }] @@ -2637,7 +2664,6 @@ permissions: dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: normalized(&skill_path), scope: SkillScope::System, }] @@ -2649,10 +2675,11 @@ permissions: let codex_home = tempfile::tempdir().expect("tempdir"); let cfg = make_config(&codex_home).await; - let scopes: Vec = skill_roots(&cfg) - .into_iter() - .map(|root| root.scope) - .collect(); + let scopes: Vec = + super::skill_roots(&cfg.config_layer_stack, &cfg.cwd, Vec::new()) + .into_iter() + .map(|root| root.scope) + .collect(); let mut expected = vec![SkillScope::User, SkillScope::System]; if home_dir().is_some() { expected.insert(1, SkillScope::User); diff --git a/codex-rs/core/src/skills/manager.rs b/codex-rs/core/src/skills/manager.rs index fa00fac41f..a2fff8f932 100644 --- a/codex-rs/core/src/skills/manager.rs +++ b/codex-rs/core/src/skills/manager.rs @@ -5,6 +5,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::sync::RwLock; +use codex_app_server_protocol::ConfigLayerSource; use codex_protocol::protocol::SkillScope; use codex_utils_absolute_path::AbsolutePathBuf; use toml::Value as TomlValue; @@ -14,28 +15,32 @@ use tracing::warn; use crate::config::Config; use crate::config::types::SkillsConfig; use crate::config_loader::CloudRequirementsLoader; +use crate::config_loader::ConfigLayerStackOrdering; use crate::config_loader::LoaderOverrides; use crate::config_loader::load_config_layers_state; +use crate::plugins::PluginsManager; use crate::skills::SkillLoadOutcome; use crate::skills::build_implicit_skill_path_indexes; use crate::skills::loader::SkillRoot; use crate::skills::loader::load_skills_from_roots; -use crate::skills::loader::skill_roots_from_layer_stack_with_agents; +use crate::skills::loader::skill_roots; use crate::skills::system::install_system_skills; pub struct SkillsManager { codex_home: PathBuf, + plugins_manager: Arc, cache_by_cwd: RwLock>, } impl SkillsManager { - pub fn new(codex_home: PathBuf) -> Self { + pub fn new(codex_home: PathBuf, plugins_manager: Arc) -> Self { if let Err(err) = install_system_skills(&codex_home) { tracing::error!("failed to install system skills: {err}"); } Self { codex_home, + plugins_manager, cache_by_cwd: RwLock::new(HashMap::new()), } } @@ -48,14 +53,9 @@ impl SkillsManager { return outcome; } - let roots = - skill_roots_from_layer_stack_with_agents(&config.config_layer_stack, &config.cwd); - let mut outcome = load_skills_from_roots(roots); - outcome.disabled_paths = disabled_paths_from_stack(&config.config_layer_stack); - let (by_scripts_dir, by_doc_path) = - build_implicit_skill_path_indexes(outcome.allowed_skills_for_implicit_invocation()); - outcome.implicit_skills_by_scripts_dir = Arc::new(by_scripts_dir); - outcome.implicit_skills_by_doc_path = Arc::new(by_doc_path); + let roots = self.skill_roots_for_config(config); + let outcome = + finalize_skill_outcome(load_skills_from_roots(roots), &config.config_layer_stack); let mut cache = match self.cache_by_cwd.write() { Ok(cache) => cache, Err(err) => err.into_inner(), @@ -64,6 +64,15 @@ impl SkillsManager { outcome } + pub(crate) fn skill_roots_for_config(&self, config: &Config) -> Vec { + let loaded_plugins = self.plugins_manager.plugins_for_config(config); + skill_roots( + &config.config_layer_stack, + &config.cwd, + loaded_plugins.effective_skill_roots(), + ) + } + pub async fn skills_for_cwd(&self, cwd: &Path, force_reload: bool) -> SkillLoadOutcome { if !force_reload && let Some(outcome) = self.cached_outcome_for_cwd(cwd) { return outcome; @@ -119,7 +128,14 @@ impl SkillsManager { } }; - let mut roots = skill_roots_from_layer_stack_with_agents(&config_layer_stack, cwd); + let loaded_plugins = + self.plugins_manager + .plugins_for_layer_stack(cwd, &config_layer_stack, force_reload); + let mut roots = skill_roots( + &config_layer_stack, + cwd, + loaded_plugins.effective_skill_roots(), + ); roots.extend( normalized_extra_user_roots .iter() @@ -130,11 +146,13 @@ impl SkillsManager { }), ); let mut outcome = load_skills_from_roots(roots); - outcome.disabled_paths = disabled_paths_from_stack(&config_layer_stack); - let (by_scripts_dir, by_doc_path) = - build_implicit_skill_path_indexes(outcome.allowed_skills_for_implicit_invocation()); - outcome.implicit_skills_by_scripts_dir = Arc::new(by_scripts_dir); - outcome.implicit_skills_by_doc_path = Arc::new(by_doc_path); + if !extra_user_roots.is_empty() { + // When extra user roots are provided, skip system skills before caching the result. + outcome + .skills + .retain(|skill| skill.scope != SkillScope::System); + } + let outcome = finalize_skill_outcome(outcome, &config_layer_stack); let mut cache = match self.cache_by_cwd.write() { Ok(cache) => cache, Err(err) => err.into_inner(), @@ -166,24 +184,31 @@ fn disabled_paths_from_stack( ) -> HashSet { let mut disabled = HashSet::new(); let mut configs = HashMap::new(); - // Skills config is user-layer only for now; higher-precedence layers are ignored. - let Some(user_layer) = config_layer_stack.get_user_layer() else { - return disabled; - }; - let Some(skills_value) = user_layer.config.get("skills") else { - return disabled; - }; - let skills: SkillsConfig = match skills_value.clone().try_into() { - Ok(skills) => skills, - Err(err) => { - warn!("invalid skills config: {err}"); - return disabled; + for layer in + config_layer_stack.get_layers(ConfigLayerStackOrdering::LowestPrecedenceFirst, true) + { + if !matches!( + layer.name, + ConfigLayerSource::User { .. } | ConfigLayerSource::SessionFlags + ) { + continue; } - }; - for entry in skills.config { - let path = normalize_override_path(entry.path.as_path()); - configs.insert(path, entry.enabled); + let Some(skills_value) = layer.config.get("skills") else { + continue; + }; + let skills: SkillsConfig = match skills_value.clone().try_into() { + Ok(skills) => skills, + Err(err) => { + warn!("invalid skills config: {err}"); + continue; + } + }; + + for entry in skills.config { + let path = normalize_override_path(entry.path.as_path()); + configs.insert(path, entry.enabled); + } } for (path, enabled) in configs { @@ -195,6 +220,18 @@ fn disabled_paths_from_stack( disabled } +fn finalize_skill_outcome( + mut outcome: SkillLoadOutcome, + config_layer_stack: &crate::config_loader::ConfigLayerStack, +) -> SkillLoadOutcome { + outcome.disabled_paths = disabled_paths_from_stack(config_layer_stack); + let (by_scripts_dir, by_doc_path) = + build_implicit_skill_path_indexes(outcome.allowed_skills_for_implicit_invocation()); + outcome.implicit_skills_by_scripts_dir = Arc::new(by_scripts_dir); + outcome.implicit_skills_by_doc_path = Arc::new(by_doc_path); + outcome +} + fn normalize_override_path(path: &Path) -> PathBuf { dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } @@ -214,6 +251,10 @@ mod tests { use super::*; use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; + use crate::config_loader::ConfigLayerEntry; + use crate::config_loader::ConfigLayerStack; + use crate::config_loader::ConfigRequirementsToml; + use crate::plugins::PluginsManager; use pretty_assertions::assert_eq; use std::fs; use std::path::PathBuf; @@ -241,7 +282,8 @@ mod tests { .await .expect("defaults for test should always succeed"); - let skills_manager = SkillsManager::new(codex_home.path().to_path_buf()); + let plugins_manager = Arc::new(PluginsManager::new(codex_home.path().to_path_buf())); + let skills_manager = SkillsManager::new(codex_home.path().to_path_buf(), plugins_manager); write_user_skill(&codex_home, "a", "skill-a", "from a"); let outcome1 = skills_manager.skills_for_config(&cfg); @@ -274,7 +316,8 @@ mod tests { .await .expect("defaults for test should always succeed"); - let skills_manager = SkillsManager::new(codex_home.path().to_path_buf()); + let plugins_manager = Arc::new(PluginsManager::new(codex_home.path().to_path_buf())); + let skills_manager = SkillsManager::new(codex_home.path().to_path_buf(), plugins_manager); let _ = skills_manager.skills_for_config(&config); write_user_skill(&extra_root, "x", "extra-skill", "from extra root"); @@ -317,7 +360,8 @@ mod tests { .await .expect("defaults for test should always succeed"); - let skills_manager = SkillsManager::new(codex_home.path().to_path_buf()); + let plugins_manager = Arc::new(PluginsManager::new(codex_home.path().to_path_buf())); + let skills_manager = SkillsManager::new(codex_home.path().to_path_buf(), plugins_manager); let _ = skills_manager.skills_for_config(&config); write_user_skill(&extra_root_a, "x", "extra-skill-a", "from extra root a"); @@ -396,4 +440,85 @@ mod tests { assert_eq!(first, second); } + + #[cfg_attr(windows, ignore)] + #[test] + fn disabled_paths_from_stack_allows_session_flags_to_override_user_layer() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let skill_path = tempdir.path().join("skills").join("demo").join("SKILL.md"); + let user_file = AbsolutePathBuf::try_from(tempdir.path().join("config.toml")) + .expect("user config path should be absolute"); + let user_layer = ConfigLayerEntry::new( + ConfigLayerSource::User { file: user_file }, + toml::from_str(&format!( + r#"[[skills.config]] +path = "{}" +enabled = false +"#, + skill_path.display() + )) + .expect("user layer toml"), + ); + let session_layer = ConfigLayerEntry::new( + ConfigLayerSource::SessionFlags, + toml::from_str(&format!( + r#"[[skills.config]] +path = "{}" +enabled = true +"#, + skill_path.display() + )) + .expect("session layer toml"), + ); + let stack = ConfigLayerStack::new( + vec![user_layer, session_layer], + Default::default(), + ConfigRequirementsToml::default(), + ) + .expect("valid config layer stack"); + + assert_eq!(disabled_paths_from_stack(&stack), HashSet::new()); + } + + #[cfg_attr(windows, ignore)] + #[test] + fn disabled_paths_from_stack_allows_session_flags_to_disable_user_enabled_skill() { + let tempdir = tempfile::tempdir().expect("tempdir"); + let skill_path = tempdir.path().join("skills").join("demo").join("SKILL.md"); + let user_file = AbsolutePathBuf::try_from(tempdir.path().join("config.toml")) + .expect("user config path should be absolute"); + let user_layer = ConfigLayerEntry::new( + ConfigLayerSource::User { file: user_file }, + toml::from_str(&format!( + r#"[[skills.config]] +path = "{}" +enabled = true +"#, + skill_path.display() + )) + .expect("user layer toml"), + ); + let session_layer = ConfigLayerEntry::new( + ConfigLayerSource::SessionFlags, + toml::from_str(&format!( + r#"[[skills.config]] +path = "{}" +enabled = false +"#, + skill_path.display() + )) + .expect("session layer toml"), + ); + let stack = ConfigLayerStack::new( + vec![user_layer, session_layer], + Default::default(), + ConfigRequirementsToml::default(), + ) + .expect("valid config layer stack"); + + assert_eq!( + disabled_paths_from_stack(&stack), + HashSet::from([skill_path]) + ); + } } diff --git a/codex-rs/core/src/skills/mod.rs b/codex-rs/core/src/skills/mod.rs index 6fccd71ccf..2dc7e11c33 100644 --- a/codex-rs/core/src/skills/mod.rs +++ b/codex-rs/core/src/skills/mod.rs @@ -14,11 +14,8 @@ pub(crate) use env_var_dependencies::resolve_skill_dependencies_for_turn; pub(crate) use injection::SkillInjections; pub(crate) use injection::build_skill_injections; pub(crate) use injection::collect_explicit_skill_mentions; -pub(crate) use invocation_utils::SKILL_APPROVAL_DECLINED_MESSAGE; pub(crate) use invocation_utils::build_implicit_skill_path_indexes; -pub(crate) use invocation_utils::ensure_skill_approval_for_command; pub(crate) use invocation_utils::maybe_emit_implicit_skill_invocation; -pub use loader::load_skills; pub use manager::SkillsManager; pub use model::SkillError; pub use model::SkillLoadOutcome; diff --git a/codex-rs/core/src/skills/model.rs b/codex-rs/core/src/skills/model.rs index ddb1dd2638..525ea28da3 100644 --- a/codex-rs/core/src/skills/model.rs +++ b/codex-rs/core/src/skills/model.rs @@ -3,7 +3,6 @@ use std::collections::HashSet; use std::path::PathBuf; use std::sync::Arc; -use crate::config::Permissions; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::SkillScope; @@ -16,8 +15,6 @@ pub struct SkillMetadata { pub dependencies: Option, pub policy: Option, pub permission_profile: Option, - // This is an experimental field. - pub permissions: Option, /// Path to the SKILLS.md file that declares this skill. pub path_to_skills_md: PathBuf, pub scope: SkillScope, diff --git a/codex-rs/core/src/skills/permissions.rs b/codex-rs/core/src/skills/permissions.rs index 4019a31079..1d0e6c82ad 100644 --- a/codex-rs/core/src/skills/permissions.rs +++ b/codex-rs/core/src/skills/permissions.rs @@ -1,32 +1,42 @@ +#[cfg(any(unix, test))] use std::collections::HashSet; -use std::path::Component; -use std::path::Path; -use std::path::PathBuf; #[cfg(target_os = "macos")] use codex_protocol::models::MacOsAutomationValue; +#[cfg(any(unix, test))] use codex_protocol::models::MacOsPermissions; #[cfg(target_os = "macos")] use codex_protocol::models::MacOsPreferencesValue; +#[cfg(any(unix, test))] +use codex_protocol::models::MacOsSeatbeltProfileExtensions; +#[cfg(any(unix, test))] use codex_protocol::models::PermissionProfile; +#[cfg(any(unix, test))] use codex_utils_absolute_path::AbsolutePathBuf; -use dirs::home_dir; +#[cfg(any(unix, test))] use dunce::canonicalize as canonicalize_path; +#[cfg(any(unix, test))] use tracing::warn; +#[cfg(any(unix, test))] use crate::config::Constrained; +#[cfg(any(unix, test))] use crate::config::Permissions; +#[cfg(any(unix, test))] use crate::config::types::ShellEnvironmentPolicy; +#[cfg(any(unix, test))] use crate::protocol::AskForApproval; +#[cfg(any(unix, test))] use crate::protocol::ReadOnlyAccess; +#[cfg(any(unix, test))] use crate::protocol::SandboxPolicy; -#[cfg(target_os = "macos")] -use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; -#[cfg(not(target_os = "macos"))] -type MacOsSeatbeltProfileExtensions = (); +/// Compiles a skill `PermissionProfile` for the Unix shell escalation path. +/// +/// Normal Windows builds do not currently call this helper, so it is only +/// compiled on Unix and in tests. +#[cfg(any(unix, test))] pub(crate) fn compile_permission_profile( - skill_dir: &Path, permissions: Option, ) -> Option { let PermissionProfile { @@ -36,12 +46,10 @@ pub(crate) fn compile_permission_profile( } = permissions?; let file_system = file_system.unwrap_or_default(); let fs_read = normalize_permission_paths( - skill_dir, file_system.read.as_deref().unwrap_or_default(), "permissions.file_system.read", ); let fs_write = normalize_permission_paths( - skill_dir, file_system.write.as_deref().unwrap_or_default(), "permissions.file_system.write", ); @@ -86,16 +94,13 @@ pub(crate) fn compile_permission_profile( }) } -fn normalize_permission_paths( - skill_dir: &Path, - values: &[PathBuf], - field: &str, -) -> Vec { +#[cfg(any(unix, test))] +fn normalize_permission_paths(values: &[AbsolutePathBuf], field: &str) -> Vec { let mut paths = Vec::new(); let mut seen = HashSet::new(); for value in values { - let Some(path) = normalize_permission_path(skill_dir, value, field) else { + let Some(path) = normalize_permission_path(value, field) else { continue; }; if seen.insert(path.clone()) { @@ -106,26 +111,9 @@ fn normalize_permission_paths( paths } -fn normalize_permission_path( - skill_dir: &Path, - value: &Path, - field: &str, -) -> Option { - let value = value.to_string_lossy(); - let trimmed = value.trim(); - if trimmed.is_empty() { - warn!("ignoring {field}: value is empty"); - return None; - } - - let expanded = expand_home(trimmed); - let absolute = if expanded.is_absolute() { - expanded - } else { - skill_dir.join(expanded) - }; - let normalized = normalize_lexically(&absolute); - let canonicalized = canonicalize_path(&normalized).unwrap_or(normalized); +#[cfg(any(unix, test))] +fn normalize_permission_path(value: &AbsolutePathBuf, field: &str) -> Option { + let canonicalized = canonicalize_path(value.as_path()).unwrap_or_else(|_| value.to_path_buf()); match AbsolutePathBuf::from_absolute_path(&canonicalized) { Ok(path) => Some(path), Err(error) => { @@ -135,21 +123,6 @@ fn normalize_permission_path( } } -fn expand_home(path: &str) -> PathBuf { - if path == "~" { - if let Some(home) = home_dir() { - return home; - } - return PathBuf::from(path); - } - if let Some(rest) = path.strip_prefix("~/") - && let Some(home) = home_dir() - { - return home.join(rest); - } - PathBuf::from(path) -} - #[cfg(target_os = "macos")] fn build_macos_seatbelt_profile_extensions( permissions: &MacOsPermissions, @@ -229,29 +202,13 @@ fn resolve_macos_automation_permission( } } -#[cfg(not(target_os = "macos"))] +#[cfg(all(not(target_os = "macos"), any(unix, test)))] fn build_macos_seatbelt_profile_extensions( _: &MacOsPermissions, ) -> Option { None } -fn normalize_lexically(path: &Path) -> PathBuf { - let mut normalized = PathBuf::new(); - for component in path.components() { - match component { - Component::CurDir => {} - Component::ParentDir => { - normalized.pop(); - } - Component::RootDir | Component::Prefix(_) | Component::Normal(_) => { - normalized.push(component.as_os_str()); - } - } - } - normalized -} - #[cfg(test)] mod tests { use super::compile_permission_profile; @@ -272,7 +229,11 @@ mod tests { use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::fs; - use std::path::PathBuf; + use std::path::Path; + + fn absolute_path(path: &Path) -> AbsolutePathBuf { + AbsolutePathBuf::try_from(path).expect("absolute path") + } #[test] fn compile_permission_profile_normalizes_paths() { @@ -282,21 +243,18 @@ mod tests { let read_dir = skill_dir.join("data"); fs::create_dir_all(&read_dir).expect("read dir"); - let profile = compile_permission_profile( - &skill_dir, - Some(PermissionProfile { - network: Some(true), - file_system: Some(FileSystemPermissions { - read: Some(vec![ - PathBuf::from("./data"), - PathBuf::from("./data"), - PathBuf::from("scripts/../data"), - ]), - write: Some(vec![PathBuf::from("./output")]), - }), - ..Default::default() + let profile = compile_permission_profile(Some(PermissionProfile { + network: Some(true), + file_system: Some(FileSystemPermissions { + read: Some(vec![ + absolute_path(&skill_dir.join("data")), + absolute_path(&skill_dir.join("data")), + absolute_path(&skill_dir.join("scripts/../data")), + ]), + write: Some(vec![absolute_path(&skill_dir.join("output"))]), }), - ) + ..Default::default() + })) .expect("profile"); assert_eq!( @@ -341,7 +299,7 @@ mod tests { let skill_dir = tempdir.path().join("skill"); fs::create_dir_all(&skill_dir).expect("skill dir"); - let profile = compile_permission_profile(&skill_dir, None); + let profile = compile_permission_profile(None); assert_eq!(profile, None); } @@ -352,13 +310,10 @@ mod tests { let skill_dir = tempdir.path().join("skill"); fs::create_dir_all(&skill_dir).expect("skill dir"); - let profile = compile_permission_profile( - &skill_dir, - Some(PermissionProfile { - network: Some(true), - ..Default::default() - }), - ) + let profile = compile_permission_profile(Some(PermissionProfile { + network: Some(true), + ..Default::default() + })) .expect("profile"); assert_eq!( @@ -387,17 +342,14 @@ mod tests { let read_dir = skill_dir.join("data"); fs::create_dir_all(&read_dir).expect("read dir"); - let profile = compile_permission_profile( - &skill_dir, - Some(PermissionProfile { - network: Some(true), - file_system: Some(FileSystemPermissions { - read: Some(vec![PathBuf::from("./data")]), - write: Some(Vec::new()), - }), - ..Default::default() + let profile = compile_permission_profile(Some(PermissionProfile { + network: Some(true), + file_system: Some(FileSystemPermissions { + read: Some(vec![absolute_path(&skill_dir.join("data"))]), + write: Some(Vec::new()), }), - ) + ..Default::default() + })) .expect("profile"); assert_eq!( @@ -436,20 +388,17 @@ mod tests { let skill_dir = tempdir.path().join("skill"); fs::create_dir_all(&skill_dir).expect("skill dir"); - let profile = compile_permission_profile( - &skill_dir, - Some(PermissionProfile { - macos: Some(MacOsPermissions { - preferences: Some(MacOsPreferencesValue::Mode("readwrite".to_string())), - automations: Some(MacOsAutomationValue::BundleIds(vec![ - "com.apple.Notes".to_string(), - ])), - accessibility: Some(true), - calendar: Some(true), - }), - ..Default::default() + let profile = compile_permission_profile(Some(PermissionProfile { + macos: Some(MacOsPermissions { + preferences: Some(MacOsPreferencesValue::Mode("readwrite".to_string())), + automations: Some(MacOsAutomationValue::BundleIds(vec![ + "com.apple.Notes".to_string(), + ])), + accessibility: Some(true), + calendar: Some(true), }), - ) + ..Default::default() + })) .expect("profile"); assert_eq!( @@ -476,8 +425,8 @@ mod tests { let skill_dir = tempdir.path().join("skill"); fs::create_dir_all(&skill_dir).expect("skill dir"); - let profile = compile_permission_profile(&skill_dir, Some(PermissionProfile::default())) - .expect("profile"); + let profile = + compile_permission_profile(Some(PermissionProfile::default())).expect("profile"); assert_eq!( profile.macos_seatbelt_profile_extensions, diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 0ec03b139e..e2792638e8 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::collections::HashMap; use std::sync::Arc; use crate::AuthManager; @@ -9,11 +9,14 @@ use crate::client::ModelClient; use crate::config::StartedNetworkProxy; use crate::exec_policy::ExecPolicyManager; use crate::file_watcher::FileWatcher; +use crate::mcp::McpManager; use crate::mcp_connection_manager::McpConnectionManager; use crate::models_manager::manager::ModelsManager; +use crate::plugins::PluginsManager; use crate::skills::SkillsManager; use crate::state_db::StateDbHandle; use crate::tools::network_approval::NetworkApprovalService; +use crate::tools::runtimes::ExecveSessionApproval; use crate::tools::sandboxing::ApprovalStore; use crate::unified_exec::UnifiedExecProcessManager; use codex_hooks::Hooks; @@ -45,8 +48,10 @@ pub(crate) struct SessionServices { pub(crate) otel_manager: OtelManager, pub(crate) tool_approvals: Mutex, #[cfg_attr(not(unix), allow(dead_code))] - pub(crate) execve_session_approvals: RwLock>, + pub(crate) execve_session_approvals: RwLock>, pub(crate) skills_manager: Arc, + pub(crate) plugins_manager: Arc, + pub(crate) mcp_manager: Arc, pub(crate) file_watcher: Arc, pub(crate) agent_control: AgentControl, pub(crate) network_proxy: Option, diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 4523b93566..babfb044d8 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -1,10 +1,13 @@ //! Session-wide mutable state. +use codex_artifact_presentation::PresentationArtifactManager; +use codex_artifact_spreadsheet::SpreadsheetArtifactManager; use codex_protocol::models::ResponseItem; use std::collections::HashMap; use std::collections::HashSet; use tokio::task::JoinHandle; +use crate::codex::PreviousTurnSettings; use crate::codex::SessionConfiguration; use crate::context_manager::ContextManager; use crate::error::Result as CodexResult; @@ -15,6 +18,12 @@ use crate::tasks::RegularTask; use crate::truncate::TruncationPolicy; use codex_protocol::protocol::TurnContextItem; +#[derive(Default)] +pub(crate) struct SessionArtifacts { + pub(crate) presentation: PresentationArtifactManager, + pub(crate) spreadsheet: SpreadsheetArtifactManager, +} + /// Persistent, session-scoped state previously stored directly on `Session`. pub(crate) struct SessionState { pub(crate) session_configuration: SessionConfiguration, @@ -23,14 +32,15 @@ pub(crate) struct SessionState { pub(crate) server_reasoning_included: bool, pub(crate) dependency_env: HashMap, pub(crate) mcp_dependency_prompted: HashSet, - /// Model used by the latest regular user turn, used for model-switch handling - /// on subsequent regular turns (including full-context reinjection after - /// resume or `/compact`). - previous_model: Option, + /// Settings used by the latest regular user turn, used for turn-to-turn + /// model/realtime handling on subsequent regular turns (including full-context + /// reinjection after resume or `/compact`). + previous_turn_settings: Option, /// Startup regular task pre-created during session initialization. pub(crate) startup_regular_task: Option>>, pub(crate) active_mcp_tool_selection: Option>, pub(crate) active_connector_selection: HashSet, + pub(crate) artifacts: SessionArtifacts, } impl SessionState { @@ -44,10 +54,11 @@ impl SessionState { server_reasoning_included: false, dependency_env: HashMap::new(), mcp_dependency_prompted: HashSet::new(), - previous_model: None, + previous_turn_settings: None, startup_regular_task: None, active_mcp_tool_selection: None, active_connector_selection: HashSet::new(), + artifacts: SessionArtifacts::default(), } } @@ -60,11 +71,14 @@ impl SessionState { self.history.record_items(items, policy); } - pub(crate) fn previous_model(&self) -> Option { - self.previous_model.clone() + pub(crate) fn previous_turn_settings(&self) -> Option { + self.previous_turn_settings.clone() } - pub(crate) fn set_previous_model(&mut self, previous_model: Option) { - self.previous_model = previous_model; + pub(crate) fn set_previous_turn_settings( + &mut self, + previous_turn_settings: Option, + ) { + self.previous_turn_settings = previous_turn_settings; } pub(crate) fn clone_history(&self) -> ContextManager { diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index 3301740866..ccc50d066b 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -11,7 +11,6 @@ use tokio_util::task::AbortOnDropHandle; use codex_protocol::dynamic_tools::DynamicToolResponse; use codex_protocol::models::ResponseInputItem; use codex_protocol::request_user_input::RequestUserInputResponse; -use codex_protocol::skill_approval::SkillApprovalResponse; use tokio::sync::oneshot; use crate::codex::TurnContext; @@ -72,7 +71,6 @@ impl ActiveTurn { pub(crate) struct TurnState { pending_approvals: HashMap>, pending_user_input: HashMap>, - pending_skill_approvals: HashMap>, pending_dynamic_tools: HashMap>, pending_input: Vec, } @@ -96,7 +94,6 @@ impl TurnState { pub(crate) fn clear_pending(&mut self) { self.pending_approvals.clear(); self.pending_user_input.clear(); - self.pending_skill_approvals.clear(); self.pending_dynamic_tools.clear(); self.pending_input.clear(); } @@ -124,21 +121,6 @@ impl TurnState { self.pending_dynamic_tools.insert(key, tx) } - pub(crate) fn insert_pending_skill_approval( - &mut self, - key: String, - tx: oneshot::Sender, - ) -> Option> { - self.pending_skill_approvals.insert(key, tx) - } - - pub(crate) fn remove_pending_skill_approval( - &mut self, - key: &str, - ) -> Option> { - self.pending_skill_approvals.remove(key) - } - pub(crate) fn remove_pending_dynamic_tool( &mut self, key: &str, diff --git a/codex-rs/core/src/state_db.rs b/codex-rs/core/src/state_db.rs index f14b932fa6..43641402fe 100644 --- a/codex-rs/core/src/state_db.rs +++ b/codex-rs/core/src/state_db.rs @@ -157,7 +157,7 @@ fn cursor_to_anchor(cursor: Option<&Cursor>) -> Option { Some(codex_state::Anchor { ts, id }) } -fn normalize_cwd_for_state_db(cwd: &Path) -> PathBuf { +pub(crate) fn normalize_cwd_for_state_db(cwd: &Path) -> PathBuf { normalize_for_path_comparison(cwd).unwrap_or_else(|_| cwd.to_path_buf()) } @@ -337,6 +337,19 @@ pub async fn persist_dynamic_tools( } } +pub async fn mark_thread_memory_mode_polluted( + context: Option<&codex_state::StateRuntime>, + thread_id: ThreadId, + stage: &str, +) { + let Some(ctx) = context else { + return; + }; + if let Err(err) = ctx.mark_thread_memory_mode_polluted(thread_id).await { + warn!("state db mark_thread_memory_mode_polluted failed during {stage}: {err}"); + } +} + /// Reconcile rollout items into SQLite, falling back to scanning the rollout file. pub async fn reconcile_rollout( context: Option<&codex_state::StateRuntime>, @@ -345,6 +358,7 @@ pub async fn reconcile_rollout( builder: Option<&ThreadMetadataBuilder>, items: &[RolloutItem], archived_only: Option, + new_thread_memory_mode: Option<&str>, ) { let Some(ctx) = context else { return; @@ -357,6 +371,7 @@ pub async fn reconcile_rollout( builder, items, "reconcile_rollout", + new_thread_memory_mode, ) .await; return; @@ -373,6 +388,7 @@ pub async fn reconcile_rollout( } }; let mut metadata = outcome.metadata; + let memory_mode = outcome.memory_mode.unwrap_or_else(|| "enabled".to_string()); metadata.cwd = normalize_cwd_for_state_db(&metadata.cwd); match archived_only { Some(true) if metadata.archived_at.is_none() => { @@ -390,6 +406,16 @@ pub async fn reconcile_rollout( ); return; } + if let Err(err) = ctx + .set_thread_memory_mode(metadata.id, memory_mode.as_str()) + .await + { + warn!( + "state db reconcile_rollout memory_mode update failed {}: {err}", + rollout_path.display() + ); + return; + } if let Ok(meta_line) = crate::rollout::list::read_session_meta_line(rollout_path).await { persist_dynamic_tools( Some(ctx), @@ -467,6 +493,7 @@ pub async fn read_repair_rollout_path( None, &[], archived_only, + None, ) .await; } @@ -479,6 +506,7 @@ pub async fn apply_rollout_items( builder: Option<&ThreadMetadataBuilder>, items: &[RolloutItem], stage: &str, + new_thread_memory_mode: Option<&str>, ) { let Some(ctx) = context else { return; @@ -499,7 +527,10 @@ pub async fn apply_rollout_items( }; builder.rollout_path = rollout_path.to_path_buf(); builder.cwd = normalize_cwd_for_state_db(&builder.cwd); - if let Err(err) = ctx.apply_rollout_items(&builder, items, None).await { + if let Err(err) = ctx + .apply_rollout_items(&builder, items, None, new_thread_memory_mode) + .await + { warn!( "state db apply_rollout_items failed during {stage} for {}: {err}", rollout_path.display() diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index fe72db09f1..abb4aa86cd 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -58,9 +58,31 @@ pub(crate) async fn record_completed_response_item( ) { sess.record_conversation_items(turn_context, std::slice::from_ref(item)) .await; + maybe_mark_thread_memory_mode_polluted_from_web_search(sess, turn_context, item).await; record_stage1_output_usage_for_completed_item(turn_context, item).await; } +async fn maybe_mark_thread_memory_mode_polluted_from_web_search( + sess: &Session, + turn_context: &TurnContext, + item: &ResponseItem, +) { + if !turn_context + .config + .memories + .no_memories_if_mcp_or_web_search + || !matches!(item, ResponseItem::WebSearchCall { .. }) + { + return; + } + state_db::mark_thread_memory_mode_polluted( + sess.services.state_db.as_deref(), + sess.conversation_id, + "record_completed_response_item", + ) + .await; +} + async fn record_stage1_output_usage_for_completed_item( turn_context: &TurnContext, item: &ResponseItem, diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 861b18a52c..97719f1049 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -21,12 +21,12 @@ use tracing::warn; use crate::AuthManager; use crate::codex::Session; use crate::codex::TurnContext; +use crate::contextual_user_message::TURN_ABORTED_OPEN_TAG; use crate::models_manager::manager::ModelsManager; use crate::protocol::EventMsg; use crate::protocol::TurnAbortReason; use crate::protocol::TurnAbortedEvent; use crate::protocol::TurnCompleteEvent; -use crate::session_prefix::TURN_ABORTED_OPEN_TAG; use crate::state::ActiveTurn; use crate::state::RunningTask; use crate::state::TaskKind; diff --git a/codex-rs/core/src/tasks/regular.rs b/codex-rs/core/src/tasks/regular.rs index 725039d677..62493a46cd 100644 --- a/codex-rs/core/src/tasks/regular.rs +++ b/codex-rs/core/src/tasks/regular.rs @@ -44,6 +44,7 @@ impl RegularTask { &turn_context.otel_manager, turn_context.reasoning_effort, turn_context.reasoning_summary, + turn_context.config.service_tier, turn_metadata_header.as_deref(), ) .await?; diff --git a/codex-rs/core/src/terminal.rs b/codex-rs/core/src/terminal.rs index 8437962f6c..b91aef106b 100644 --- a/codex-rs/core/src/terminal.rs +++ b/codex-rs/core/src/terminal.rs @@ -249,6 +249,7 @@ pub fn terminal_info() -> TerminalInfo { /// type is split on whitespace to extract a program name plus optional version (for example, /// `ghostty 1.2.3`), while the client term name becomes the `TERM` capability string. /// - Otherwise, `TERM_PROGRAM` (plus `TERM_PROGRAM_VERSION`) drives the detected terminal name. +/// This means `TERM_PROGRAM` can mask later probes (for example `WT_SESSION`). /// - Next, terminal-specific variables (WEZTERM, iTerm2, Apple Terminal, kitty, etc.) are checked. /// - Finally, `TERM` is used as the capability fallback with `TerminalName::Unknown`. /// diff --git a/codex-rs/core/src/test_support.rs b/codex-rs/core/src/test_support.rs index 5e6d611adc..12ba7cda82 100644 --- a/codex-rs/core/src/test_support.rs +++ b/codex-rs/core/src/test_support.rs @@ -85,5 +85,7 @@ pub fn all_model_presets() -> &'static Vec { } pub fn builtin_collaboration_mode_presets() -> Vec { - collaboration_mode_presets::builtin_collaboration_mode_presets() + collaboration_mode_presets::builtin_collaboration_mode_presets( + collaboration_mode_presets::CollaborationModesConfig::default(), + ) } diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 55ca7da34c..2723ad955c 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -11,12 +11,16 @@ use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::file_watcher::FileWatcher; use crate::file_watcher::FileWatcherEvent; +use crate::mcp::McpManager; +use crate::models_manager::collaboration_mode_presets::CollaborationModesConfig; use crate::models_manager::manager::ModelsManager; +use crate::plugins::PluginsManager; use crate::protocol::Event; use crate::protocol::EventMsg; use crate::protocol::SessionConfiguredEvent; use crate::rollout::RolloutRecorder; use crate::rollout::truncation; +use crate::shell_snapshot::ShellSnapshot; use crate::skills::SkillsManager; use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationModeMask; @@ -131,6 +135,8 @@ pub(crate) struct ThreadManagerState { auth_manager: Arc, models_manager: Arc, skills_manager: Arc, + plugins_manager: Arc, + mcp_manager: Arc, file_watcher: Arc, session_source: SessionSource, // Captures submitted ops for testing purpose when test mode is enabled. @@ -143,9 +149,15 @@ impl ThreadManager { auth_manager: Arc, session_source: SessionSource, model_catalog: Option, + collaboration_modes_config: CollaborationModesConfig, ) -> Self { let (thread_created_tx, _) = broadcast::channel(THREAD_CREATED_CHANNEL_CAPACITY); - let skills_manager = Arc::new(SkillsManager::new(codex_home.clone())); + let plugins_manager = Arc::new(PluginsManager::new(codex_home.clone())); + let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager))); + let skills_manager = Arc::new(SkillsManager::new( + codex_home.clone(), + Arc::clone(&plugins_manager), + )); let file_watcher = build_file_watcher(codex_home.clone(), Arc::clone(&skills_manager)); Self { state: Arc::new(ThreadManagerState { @@ -155,8 +167,11 @@ impl ThreadManager { codex_home, auth_manager.clone(), model_catalog, + collaboration_modes_config, )), skills_manager, + plugins_manager, + mcp_manager, file_watcher, auth_manager, session_source, @@ -196,7 +211,12 @@ impl ThreadManager { set_thread_manager_test_mode_for_tests(true); let auth_manager = AuthManager::from_auth_for_testing(auth); let (thread_created_tx, _) = broadcast::channel(THREAD_CREATED_CHANNEL_CAPACITY); - let skills_manager = Arc::new(SkillsManager::new(codex_home.clone())); + let plugins_manager = Arc::new(PluginsManager::new(codex_home.clone())); + let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager))); + let skills_manager = Arc::new(SkillsManager::new( + codex_home.clone(), + Arc::clone(&plugins_manager), + )); let file_watcher = build_file_watcher(codex_home.clone(), Arc::clone(&skills_manager)); Self { state: Arc::new(ThreadManagerState { @@ -208,6 +228,8 @@ impl ThreadManager { provider, )), skills_manager, + plugins_manager, + mcp_manager, file_watcher, auth_manager, session_source: SessionSource::Exec, @@ -226,6 +248,14 @@ impl ThreadManager { self.state.skills_manager.clone() } + pub fn plugins_manager(&self) -> Arc { + self.state.plugins_manager.clone() + } + + pub fn mcp_manager(&self) -> Arc { + self.state.mcp_manager.clone() + } + pub fn subscribe_file_watcher(&self) -> broadcast::Receiver { self.state.file_watcher.subscribe() } @@ -249,7 +279,7 @@ impl ThreadManager { } pub async fn list_thread_ids(&self) -> Vec { - self.state.threads.read().await.keys().copied().collect() + self.state.list_thread_ids().await } pub async fn refresh_mcp_servers(&self, refresh_config: McpServerRefreshConfig) { @@ -409,6 +439,10 @@ impl ThreadManager { } impl ThreadManagerState { + pub(crate) async fn list_thread_ids(&self) -> Vec { + self.threads.read().await.keys().copied().collect() + } + /// Fetch a thread by ID or return ThreadNotFound. pub(crate) async fn get_thread(&self, thread_id: ThreadId) -> CodexResult> { let threads = self.threads.read().await; @@ -446,6 +480,7 @@ impl ThreadManagerState { self.session_source.clone(), false, None, + None, ) .await } @@ -457,6 +492,7 @@ impl ThreadManagerState { session_source: SessionSource, persist_extended_history: bool, metrics_service_name: Option, + inherited_shell_snapshot: Option>, ) -> CodexResult { self.spawn_thread_with_source( config, @@ -467,6 +503,7 @@ impl ThreadManagerState { Vec::new(), persist_extended_history, metrics_service_name, + inherited_shell_snapshot, ) .await } @@ -477,6 +514,7 @@ impl ThreadManagerState { rollout_path: PathBuf, agent_control: AgentControl, session_source: SessionSource, + inherited_shell_snapshot: Option>, ) -> CodexResult { let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; self.spawn_thread_with_source( @@ -488,6 +526,30 @@ impl ThreadManagerState { Vec::new(), false, None, + inherited_shell_snapshot, + ) + .await + } + + pub(crate) async fn fork_thread_with_source( + &self, + config: Config, + initial_history: InitialHistory, + agent_control: AgentControl, + session_source: SessionSource, + persist_extended_history: bool, + inherited_shell_snapshot: Option>, + ) -> CodexResult { + self.spawn_thread_with_source( + config, + initial_history, + Arc::clone(&self.auth_manager), + agent_control, + session_source, + Vec::new(), + persist_extended_history, + None, + inherited_shell_snapshot, ) .await } @@ -513,6 +575,7 @@ impl ThreadManagerState { dynamic_tools, persist_extended_history, metrics_service_name, + None, ) .await } @@ -528,8 +591,11 @@ impl ThreadManagerState { dynamic_tools: Vec, persist_extended_history: bool, metrics_service_name: Option, + inherited_shell_snapshot: Option>, ) -> CodexResult { - let watch_registration = self.file_watcher.register_config(&config); + let watch_registration = self + .file_watcher + .register_config(&config, self.skills_manager.as_ref()); let CodexSpawnOk { codex, thread_id, .. } = Codex::spawn( @@ -537,6 +603,8 @@ impl ThreadManagerState { auth_manager, Arc::clone(&self.models_manager), Arc::clone(&self.skills_manager), + Arc::clone(&self.plugins_manager), + Arc::clone(&self.mcp_manager), Arc::clone(&self.file_watcher), initial_history, session_source, @@ -544,6 +612,7 @@ impl ThreadManagerState { dynamic_tools, persist_extended_history, metrics_service_name, + inherited_shell_snapshot, ) .await?; self.finalize_thread_spawn(codex, thread_id, watch_registration) diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index 58925622a0..0700b4d013 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -95,15 +95,12 @@ impl ToolOutput { match self { ToolOutput::Function { body, success } => { // `custom_tool_call` is the Responses API item type for freeform - // tools (`ToolSpec::Freeform`, e.g. freeform `apply_patch`). - // Those payloads must round-trip as `custom_tool_call_output` - // with plain string output. + // tools (`ToolSpec::Freeform`, e.g. freeform `apply_patch` or + // `js_repl`). if matches!(payload, ToolPayload::Custom { .. }) { - // Freeform/custom tools (`custom_tool_call`) use the custom - // output wire shape and remain string-only. return ResponseInputItem::CustomToolCallOutput { call_id: call_id.to_string(), - output: body.to_text().unwrap_or_default(), + output: FunctionCallOutputPayload { body, success }, }; } @@ -183,7 +180,9 @@ mod tests { match response { ResponseInputItem::CustomToolCallOutput { call_id, output } => { assert_eq!(call_id, "call-42"); - assert_eq!(output, "patched"); + assert_eq!(output.text_content(), Some("patched")); + assert!(output.content_items().is_none()); + assert_eq!(output.success, Some(true)); } other => panic!("expected CustomToolCallOutput, got {other:?}"), } @@ -234,8 +233,21 @@ mod tests { match response { ResponseInputItem::CustomToolCallOutput { call_id, output } => { + let expected = vec![ + FunctionCallOutputContentItem::InputText { + text: "line 1".to_string(), + }, + FunctionCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,AAA".to_string(), + }, + FunctionCallOutputContentItem::InputText { + text: "line 2".to_string(), + }, + ]; assert_eq!(call_id, "call-99"); - assert_eq!(output, "line 1\nline 2"); + assert_eq!(output.content_items(), Some(expected.as_slice())); + assert_eq!(output.body.to_text().as_deref(), Some("line 1\nline 2")); + assert_eq!(output.success, Some(true)); } other => panic!("expected CustomToolCallOutput, got {other:?}"), } diff --git a/codex-rs/core/src/tools/handlers/dynamic.rs b/codex-rs/core/src/tools/handlers/dynamic.rs index 51dc8db56f..23c8474b9f 100644 --- a/codex-rs/core/src/tools/handlers/dynamic.rs +++ b/codex-rs/core/src/tools/handlers/dynamic.rs @@ -12,8 +12,10 @@ use codex_protocol::dynamic_tools::DynamicToolCallRequest; use codex_protocol::dynamic_tools::DynamicToolResponse; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputContentItem; +use codex_protocol::protocol::DynamicToolCallResponseEvent; use codex_protocol::protocol::EventMsg; use serde_json::Value; +use std::time::Instant; use tokio::sync::oneshot; use tracing::warn; @@ -81,7 +83,7 @@ async fn request_dynamic_tool( tool: String, arguments: Value, ) -> Option { - let _sub_id = turn_context.sub_id.clone(); + let turn_id = turn_context.sub_id.clone(); let (tx_response, rx_response) = oneshot::channel(); let event_id = call_id.clone(); let prev_entry = { @@ -98,12 +100,39 @@ async fn request_dynamic_tool( warn!("Overwriting existing pending dynamic tool call for call_id: {event_id}"); } + let started_at = Instant::now(); let event = EventMsg::DynamicToolCallRequest(DynamicToolCallRequest { - call_id, - turn_id: turn_context.sub_id.clone(), - tool, - arguments, + call_id: call_id.clone(), + turn_id: turn_id.clone(), + tool: tool.clone(), + arguments: arguments.clone(), }); session.send_event(turn_context, event).await; - rx_response.await.ok() + let response = rx_response.await.ok(); + + let response_event = match &response { + Some(response) => EventMsg::DynamicToolCallResponse(DynamicToolCallResponseEvent { + call_id, + turn_id, + tool, + arguments, + content_items: response.content_items.clone(), + success: response.success, + error: None, + duration: started_at.elapsed(), + }), + None => EventMsg::DynamicToolCallResponse(DynamicToolCallResponseEvent { + call_id, + turn_id, + tool, + arguments, + content_items: Vec::new(), + success: false, + error: Some("dynamic tool call was cancelled before receiving a response".to_string()), + duration: started_at.elapsed(), + }), + }; + session.send_event(turn_context, response_event).await; + + response } diff --git a/codex-rs/core/src/tools/handlers/js_repl.rs b/codex-rs/core/src/tools/handlers/js_repl.rs index 4488b4ea51..362d25b81e 100644 --- a/codex-rs/core/src/tools/handlers/js_repl.rs +++ b/codex-rs/core/src/tools/handlers/js_repl.rs @@ -155,9 +155,13 @@ impl ToolHandler for JsReplHandler { }; let content = result.output; - let items = vec![FunctionCallOutputContentItem::InputText { - text: content.clone(), - }]; + let mut items = Vec::with_capacity(result.content_items.len() + 1); + if !content.is_empty() { + items.push(FunctionCallOutputContentItem::InputText { + text: content.clone(), + }); + } + items.extend(result.content_items); emit_js_repl_exec_end( session.as_ref(), @@ -170,7 +174,11 @@ impl ToolHandler for JsReplHandler { .await; Ok(ToolOutput::Function { - body: FunctionCallOutputBody::ContentItems(items), + body: if items.is_empty() { + FunctionCallOutputBody::Text(content) + } else { + FunctionCallOutputBody::ContentItems(items) + }, success: Some(true), }) } diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index 23dc979f2c..908f3d18d0 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -8,17 +8,22 @@ mod mcp; mod mcp_resource; pub(crate) mod multi_agents; mod plan; +mod presentation_artifact; mod read_file; mod request_user_input; mod search_tool_bm25; mod shell; +mod spreadsheet_artifact; mod test_sync; pub(crate) mod unified_exec; mod view_image; +use codex_utils_absolute_path::AbsolutePathBufGuard; pub use plan::PLAN_TOOL; use serde::Deserialize; +use serde_json::Value; use std::path::Path; +use std::path::PathBuf; use crate::function_tool::FunctionCallError; use crate::sandboxing::SandboxPermissions; @@ -35,6 +40,7 @@ pub use mcp::McpHandler; pub use mcp_resource::McpResourceHandler; pub use multi_agents::MultiAgentHandler; pub use plan::PlanHandler; +pub use presentation_artifact::PresentationArtifactHandler; pub use read_file::ReadFileHandler; pub use request_user_input::RequestUserInputHandler; pub(crate) use request_user_input::request_user_input_tool_description; @@ -43,6 +49,7 @@ pub(crate) use search_tool_bm25::SEARCH_TOOL_BM25_TOOL_NAME; pub use search_tool_bm25::SearchToolBm25Handler; pub use shell::ShellCommandHandler; pub use shell::ShellHandler; +pub use spreadsheet_artifact::SpreadsheetArtifactHandler; pub use test_sync::TestSyncHandler; pub use unified_exec::UnifiedExecHandler; pub use view_image::ViewImageHandler; @@ -56,6 +63,33 @@ where }) } +fn parse_arguments_with_base_path( + arguments: &str, + base_path: &Path, +) -> Result +where + T: for<'de> Deserialize<'de>, +{ + let _guard = AbsolutePathBufGuard::new(base_path); + parse_arguments(arguments) +} + +fn resolve_workdir_base_path( + arguments: &str, + default_cwd: &Path, +) -> Result { + let arguments: Value = parse_arguments(arguments)?; + Ok(arguments + .get("workdir") + .and_then(Value::as_str) + .filter(|workdir| !workdir.is_empty()) + .map(PathBuf::from) + .map_or_else( + || default_cwd.to_path_buf(), + |workdir| crate::util::resolve_path(default_cwd, &workdir), + )) +} + /// Validates feature/policy constraints for `with_additional_permissions` and /// returns normalized absolute paths. Errors if paths are invalid. pub(super) fn normalize_and_validate_additional_permissions( @@ -63,7 +97,7 @@ pub(super) fn normalize_and_validate_additional_permissions( approval_policy: AskForApproval, sandbox_permissions: SandboxPermissions, additional_permissions: Option, - cwd: &Path, + _cwd: &Path, ) -> Result, String> { let uses_additional_permissions = matches!( sandbox_permissions, @@ -91,7 +125,7 @@ pub(super) fn normalize_and_validate_additional_permissions( .to_string(), ); }; - let normalized = normalize_additional_permissions(additional_permissions, cwd)?; + let normalized = normalize_additional_permissions(additional_permissions)?; if normalized.is_empty() { return Err( "`additional_permissions` must include at least one path in `file_system.read` or `file_system.write`" diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 6e62fd04fd..c179fcef7a 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -1,3 +1,10 @@ +//! Implements the collaboration tool surface for spawning and managing sub-agents. +//! +//! This handler translates model tool calls into `AgentControl` operations and keeps spawned +//! agents aligned with the live turn that created them. Sub-agents start from the turn's effective +//! config, inherit runtime-only state such as provider, approval policy, sandbox, and cwd, and +//! then optionally layer role-specific config on top. + use crate::agent::AgentStatus; use crate::agent::exceeds_thread_spawn_depth_limit; use crate::codex::Session; @@ -35,6 +42,7 @@ use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; +/// Function-tool handler for the multi-agent collaboration API. pub struct MultiAgentHandler; /// Minimum wait timeout to prevent tight polling loops from burning CPU. @@ -91,6 +99,7 @@ impl ToolHandler for MultiAgentHandler { mod spawn { use super::*; + use crate::agent::control::SpawnAgentOptions; use crate::agent::role::DEFAULT_ROLE_NAME; use crate::agent::role::apply_role_to_config; @@ -103,6 +112,8 @@ mod spawn { message: Option, items: Option>, agent_type: Option, + #[serde(default)] + fork_context: bool, } #[derive(Debug, Serialize)] @@ -155,7 +166,7 @@ mod spawn { let result = session .services .agent_control - .spawn_agent( + .spawn_agent_with_options( config, input_items, Some(thread_spawn_source( @@ -163,6 +174,9 @@ mod spawn { child_depth, role_name, )), + SpawnAgentOptions { + fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()), + }, ) .await .map_err(collab_spawn_error); @@ -888,6 +902,13 @@ fn input_preview(items: &[UserInput]) -> String { parts.join("\n") } +/// Builds the base config snapshot for a newly spawned sub-agent. +/// +/// The returned config starts from the parent's effective config and then refreshes the +/// runtime-owned fields carried on `turn`, including model selection, reasoning settings, +/// approval policy, sandbox, and cwd. Role-specific overrides are layered after this step; +/// skipping this helper and cloning stale config state directly can send the child agent out with +/// the wrong provider or runtime policy. pub(crate) fn build_agent_spawn_config( base_instructions: &BaseInstructions, turn: &TurnContext, @@ -914,7 +935,7 @@ fn build_agent_shared_config(turn: &TurnContext) -> Result Result ToolKind { + ToolKind::Function + } + + async fn is_mutating(&self, invocation: &ToolInvocation) -> bool { + let ToolPayload::Function { arguments } = &invocation.payload else { + return true; + }; + let Ok(request) = parse_arguments::(arguments) else { + return true; + }; + request.is_mutating().unwrap_or(true) + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + + if !session.enabled(Feature::Artifact) { + return Err(FunctionCallError::RespondToModel( + "presentation_artifact is disabled by feature flag".to_string(), + )); + } + + let arguments = match payload { + ToolPayload::Function { arguments } => arguments, + _ => { + return Err(FunctionCallError::RespondToModel( + "presentation_artifact handler received unsupported payload".to_string(), + )); + } + }; + + let request: PresentationArtifactToolRequest = parse_arguments(&arguments)?; + for access in request + .required_path_accesses(&turn.cwd) + .map_err(presentation_error)? + { + authorize_path_access(session.as_ref(), turn.as_ref(), &call_id, &access).await?; + } + + let response = session + .execute_presentation_artifact( + request + .into_execution_request() + .map_err(presentation_error)?, + &turn.cwd, + ) + .await + .map_err(presentation_error)?; + + Ok(ToolOutput::Function { + body: FunctionCallOutputBody::Text(to_string(&response).map_err(|error| { + FunctionCallError::RespondToModel(format!( + "failed to serialize presentation_artifact response: {error}" + )) + })?), + success: Some(true), + }) + } +} + +fn presentation_error(error: PresentationArtifactError) -> FunctionCallError { + FunctionCallError::RespondToModel(error.to_string()) +} + +async fn authorize_path_access( + session: &Session, + turn: &TurnContext, + call_id: &str, + access: &PathAccessRequirement, +) -> Result<(), FunctionCallError> { + let effective_path = match access.kind { + PathAccessKind::Read => effective_read_path(&access.path), + PathAccessKind::Write => effective_write_path(&access.path), + }; + let allowed = match access.kind { + PathAccessKind::Read => path_is_readable(turn, &effective_path), + PathAccessKind::Write => path_is_writable(turn, &effective_path), + }; + if allowed { + return Ok(()); + } + + let approval_policy = turn.approval_policy.value(); + if !matches!( + approval_policy, + AskForApproval::OnRequest | AskForApproval::UnlessTrusted + ) { + return Err(FunctionCallError::RespondToModel(format!( + "{} path `{}` is outside the current sandbox policy", + access_kind_label(access.kind), + access.path.display() + ))); + } + + let key = format!( + "presentation_artifact:{:?}:{}", + access.kind, + effective_path.display() + ); + let path = access.path.clone(); + let action = access.action.clone(); + let decision = with_cached_approval( + &session.services, + "presentation_artifact", + vec![key], + || { + let path = path.clone(); + let action = action.clone(); + async move { + session + .request_command_approval( + turn, + call_id.to_string(), + None, + vec![ + "presentation_artifact".to_string(), + action, + path.display().to_string(), + ], + turn.cwd.clone(), + Some(format!( + "Allow presentation_artifact to {} `{}`?", + access_kind_verb(access.kind), + path.display() + )), + None, + None, + None, + None, + ) + .await + } + }, + ) + .await; + + if matches!( + decision, + ReviewDecision::Approved + | ReviewDecision::ApprovedForSession + | ReviewDecision::ApprovedExecpolicyAmendment { .. } + ) { + return Ok(()); + } + + Err(FunctionCallError::RespondToModel(format!( + "{} path `{}` was not approved", + access_kind_label(access.kind), + access.path.display() + ))) +} + +fn path_is_readable(turn: &TurnContext, path: &Path) -> bool { + if turn.sandbox_policy.has_full_disk_read_access() { + return true; + } + + turn.sandbox_policy + .get_readable_roots_with_cwd(&turn.cwd) + .iter() + .any(|root| path.starts_with(root.as_path())) +} + +fn path_is_writable(turn: &TurnContext, path: &Path) -> bool { + if turn.sandbox_policy.has_full_disk_write_access() { + return true; + } + + turn.sandbox_policy + .get_writable_roots_with_cwd(&turn.cwd) + .iter() + .any(|root| root.is_path_writable(path)) +} + +fn effective_read_path(path: &Path) -> PathBuf { + normalize_for_path_comparison(path).unwrap_or_else(|_| normalize_without_fs(path)) +} + +fn effective_write_path(path: &Path) -> PathBuf { + let write_path = resolve_symlink_write_paths(path) + .map(|paths| paths.write_path) + .unwrap_or_else(|_| path.to_path_buf()); + normalize_for_path_comparison(&write_path).unwrap_or_else(|_| normalize_without_fs(&write_path)) +} + +fn normalize_without_fs(path: &Path) -> PathBuf { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + other => normalized.push(other.as_os_str()), + } + } + normalized +} + +fn access_kind_label(kind: PathAccessKind) -> &'static str { + match kind { + PathAccessKind::Read => "read", + PathAccessKind::Write => "write", + } +} + +fn access_kind_verb(kind: PathAccessKind) -> &'static str { + match kind { + PathAccessKind::Read => "read from", + PathAccessKind::Write => "write to", + } +} diff --git a/codex-rs/core/src/tools/handlers/request_user_input.rs b/codex-rs/core/src/tools/handlers/request_user_input.rs index 134294d428..f9b444186e 100644 --- a/codex-rs/core/src/tools/handlers/request_user_input.rs +++ b/codex-rs/core/src/tools/handlers/request_user_input.rs @@ -12,10 +12,15 @@ use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::TUI_VISIBLE_COLLABORATION_MODES; use codex_protocol::request_user_input::RequestUserInputArgs; -fn format_allowed_modes() -> String { +fn request_user_input_is_available(mode: ModeKind, default_mode_request_user_input: bool) -> bool { + mode.allows_request_user_input() + || (default_mode_request_user_input && mode == ModeKind::Default) +} + +fn format_allowed_modes(default_mode_request_user_input: bool) -> String { let mode_names: Vec<&str> = TUI_VISIBLE_COLLABORATION_MODES .into_iter() - .filter(|mode| mode.allows_request_user_input()) + .filter(|mode| request_user_input_is_available(*mode, default_mode_request_user_input)) .map(ModeKind::display_name) .collect(); @@ -27,8 +32,11 @@ fn format_allowed_modes() -> String { } } -pub(crate) fn request_user_input_unavailable_message(mode: ModeKind) -> Option { - if mode.allows_request_user_input() { +pub(crate) fn request_user_input_unavailable_message( + mode: ModeKind, + default_mode_request_user_input: bool, +) -> Option { + if request_user_input_is_available(mode, default_mode_request_user_input) { None } else { let mode_name = mode.display_name(); @@ -38,14 +46,16 @@ pub(crate) fn request_user_input_unavailable_message(mode: ModeKind) -> Option String { - let allowed_modes = format_allowed_modes(); +pub(crate) fn request_user_input_tool_description(default_mode_request_user_input: bool) -> String { + let allowed_modes = format_allowed_modes(default_mode_request_user_input); format!( "Request user input for one to three short questions and wait for the response. This tool is only available in {allowed_modes}." ) } -pub struct RequestUserInputHandler; +pub struct RequestUserInputHandler { + pub default_mode_request_user_input: bool, +} #[async_trait] impl ToolHandler for RequestUserInputHandler { @@ -72,7 +82,9 @@ impl ToolHandler for RequestUserInputHandler { }; let mode = session.collaboration_mode().await.mode; - if let Some(message) = request_user_input_unavailable_message(mode) { + if let Some(message) = + request_user_input_unavailable_message(mode, self.default_mode_request_user_input) + { return Err(FunctionCallError::RespondToModel(message)); } @@ -117,7 +129,7 @@ mod tests { use pretty_assertions::assert_eq; #[test] - fn request_user_input_mode_availability_is_plan_only() { + fn request_user_input_mode_availability_defaults_to_plan_only() { assert!(ModeKind::Plan.allows_request_user_input()); assert!(!ModeKind::Default.allows_request_user_input()); assert!(!ModeKind::Execute.allows_request_user_input()); @@ -125,27 +137,38 @@ mod tests { } #[test] - fn request_user_input_unavailable_messages_use_default_name_for_default_modes() { - assert_eq!(request_user_input_unavailable_message(ModeKind::Plan), None); + fn request_user_input_unavailable_messages_respect_default_mode_feature_flag() { assert_eq!( - request_user_input_unavailable_message(ModeKind::Default), + request_user_input_unavailable_message(ModeKind::Plan, false), + None + ); + assert_eq!( + request_user_input_unavailable_message(ModeKind::Default, false), Some("request_user_input is unavailable in Default mode".to_string()) ); assert_eq!( - request_user_input_unavailable_message(ModeKind::Execute), + request_user_input_unavailable_message(ModeKind::Default, true), + None + ); + assert_eq!( + request_user_input_unavailable_message(ModeKind::Execute, false), Some("request_user_input is unavailable in Execute mode".to_string()) ); assert_eq!( - request_user_input_unavailable_message(ModeKind::PairProgramming), + request_user_input_unavailable_message(ModeKind::PairProgramming, false), Some("request_user_input is unavailable in Pair Programming mode".to_string()) ); } #[test] - fn request_user_input_tool_description_mentions_plan_only() { + fn request_user_input_tool_description_mentions_available_modes() { assert_eq!( - request_user_input_tool_description(), + request_user_input_tool_description(false), "Request user input for one to three short questions and wait for the response. This tool is only available in Plan mode.".to_string() ); + assert_eq!( + request_user_input_tool_description(true), + "Request user input for one to three short questions and wait for the response. This tool is only available in Default or Plan mode.".to_string() + ); } } diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 95dbe05e54..efc596ea36 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -14,8 +14,6 @@ use crate::function_tool::FunctionCallError; use crate::is_safe_command::is_known_safe_command; use crate::protocol::ExecCommandSource; use crate::shell::Shell; -use crate::skills::SKILL_APPROVAL_DECLINED_MESSAGE; -use crate::skills::ensure_skill_approval_for_command; use crate::skills::maybe_emit_implicit_skill_invocation; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; @@ -24,7 +22,8 @@ use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; use crate::tools::handlers::apply_patch::intercept_apply_patch; use crate::tools::handlers::normalize_and_validate_additional_permissions; -use crate::tools::handlers::parse_arguments; +use crate::tools::handlers::parse_arguments_with_base_path; +use crate::tools::handlers::resolve_workdir_base_path; use crate::tools::orchestrator::ToolOrchestrator; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; @@ -68,8 +67,6 @@ impl ShellHandler { ) -> ExecParams { ExecParams { command: params.command.clone(), - original_command: shlex::try_join(params.command.iter().map(String::as_str)) - .unwrap_or_else(|_| params.command.join(" ")), cwd: turn_context.resolve_path(params.workdir.clone()), expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy, Some(thread_id)), @@ -120,7 +117,6 @@ impl ShellCommandHandler { Ok(ExecParams { command, - original_command: params.command.clone(), cwd: turn_context.resolve_path(params.workdir.clone()), expiration: params.timeout_ms.into(), env: create_env(&turn_context.shell_environment_policy, Some(thread_id)), @@ -181,7 +177,9 @@ impl ToolHandler for ShellHandler { match payload { ToolPayload::Function { arguments } => { - let params: ShellToolCallParams = parse_arguments(&arguments)?; + let cwd = resolve_workdir_base_path(&arguments, turn.cwd.as_path())?; + let params: ShellToolCallParams = + parse_arguments_with_base_path(&arguments, cwd.as_path())?; let prefix_rule = params.prefix_rule.clone(); let exec_params = Self::to_exec_params(¶ms, turn.as_ref(), session.conversation_id); @@ -271,7 +269,16 @@ impl ToolHandler for ShellCommandHandler { ))); }; - let params: ShellCommandToolCallParams = parse_arguments(&arguments)?; + let cwd = resolve_workdir_base_path(&arguments, turn.cwd.as_path())?; + let params: ShellCommandToolCallParams = + parse_arguments_with_base_path(&arguments, cwd.as_path())?; + maybe_emit_implicit_skill_invocation( + session.as_ref(), + turn.as_ref(), + ¶ms.command, + params.workdir.as_deref(), + ) + .await; let prefix_rule = params.prefix_rule.clone(); let exec_params = Self::to_exec_params( ¶ms, @@ -348,28 +355,6 @@ impl ShellHandler { "approval policy is {approval_policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {approval_policy:?}" ))); } - let original_command = exec_params.original_command.as_str(); - if !ensure_skill_approval_for_command( - session.as_ref(), - turn.as_ref(), - &call_id, - original_command, - exec_params.cwd.as_path(), - ) - .await - { - return Err(FunctionCallError::RespondToModel( - SKILL_APPROVAL_DECLINED_MESSAGE.to_string(), - )); - } - let workdir = exec_params.cwd.to_string_lossy().into_owned(); - maybe_emit_implicit_skill_invocation( - session.as_ref(), - turn.as_ref(), - original_command, - Some(workdir.as_str()), - ) - .await; // Intercept apply_patch if present. if let Some(output) = intercept_apply_patch( diff --git a/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs b/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs new file mode 100644 index 0000000000..be4eb7fc58 --- /dev/null +++ b/codex-rs/core/src/tools/handlers/spreadsheet_artifact.rs @@ -0,0 +1,235 @@ +use async_trait::async_trait; +use codex_artifact_spreadsheet::PathAccessKind; +use codex_artifact_spreadsheet::PathAccessRequirement; +use codex_artifact_spreadsheet::SpreadsheetArtifactError; +use codex_artifact_spreadsheet::SpreadsheetArtifactRequest; +use codex_protocol::models::FunctionCallOutputBody; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::ReviewDecision; +use serde_json::to_string; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::features::Feature; +use crate::function_tool::FunctionCallError; +use crate::path_utils::normalize_for_path_comparison; +use crate::path_utils::resolve_symlink_write_paths; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolOutput; +use crate::tools::context::ToolPayload; +use crate::tools::handlers::parse_arguments; +use crate::tools::registry::ToolHandler; +use crate::tools::registry::ToolKind; +use crate::tools::sandboxing::with_cached_approval; + +pub struct SpreadsheetArtifactHandler; + +#[async_trait] +impl ToolHandler for SpreadsheetArtifactHandler { + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + async fn is_mutating(&self, _invocation: &ToolInvocation) -> bool { + true + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + + if !session.enabled(Feature::Artifact) { + return Err(FunctionCallError::RespondToModel( + "spreadsheet_artifact is disabled by feature flag".to_string(), + )); + } + + let arguments = match payload { + ToolPayload::Function { arguments } => arguments, + _ => { + return Err(FunctionCallError::RespondToModel( + "spreadsheet_artifact handler received unsupported payload".to_string(), + )); + } + }; + + let request: SpreadsheetArtifactRequest = parse_arguments(&arguments)?; + for access in request + .required_path_accesses(&turn.cwd) + .map_err(spreadsheet_error)? + { + authorize_path_access(session.as_ref(), turn.as_ref(), &call_id, &access).await?; + } + + let response = session + .execute_spreadsheet_artifact(request, &turn.cwd) + .await + .map_err(spreadsheet_error)?; + + Ok(ToolOutput::Function { + body: FunctionCallOutputBody::Text(to_string(&response).map_err(|error| { + FunctionCallError::RespondToModel(format!( + "failed to serialize spreadsheet_artifact response: {error}" + )) + })?), + success: Some(true), + }) + } +} + +fn spreadsheet_error(error: SpreadsheetArtifactError) -> FunctionCallError { + FunctionCallError::RespondToModel(error.to_string()) +} + +async fn authorize_path_access( + session: &Session, + turn: &TurnContext, + call_id: &str, + access: &PathAccessRequirement, +) -> Result<(), FunctionCallError> { + let effective_path = match access.kind { + PathAccessKind::Read => effective_read_path(&access.path), + PathAccessKind::Write => effective_write_path(&access.path), + }; + let allowed = match access.kind { + PathAccessKind::Read => path_is_readable(turn, &effective_path), + PathAccessKind::Write => path_is_writable(turn, &effective_path), + }; + if allowed { + return Ok(()); + } + + let approval_policy = turn.approval_policy.value(); + if !matches!( + approval_policy, + AskForApproval::OnRequest | AskForApproval::UnlessTrusted + ) { + return Err(FunctionCallError::RespondToModel(format!( + "{} path `{}` is outside the current sandbox policy", + access_kind_label(access.kind), + access.path.display() + ))); + } + + let key = format!( + "spreadsheet_artifact:{:?}:{}", + access.kind, + effective_path.display() + ); + let path = access.path.clone(); + let action = access.action.clone(); + let decision = + with_cached_approval(&session.services, "spreadsheet_artifact", vec![key], || { + let path = path.clone(); + let action = action.clone(); + async move { + session + .request_command_approval( + turn, + call_id.to_string(), + None, + vec![ + "spreadsheet_artifact".to_string(), + action, + path.display().to_string(), + ], + turn.cwd.clone(), + Some(format!( + "Allow spreadsheet_artifact to {} `{}`?", + access_kind_verb(access.kind), + path.display() + )), + None, + None, + None, + None, + ) + .await + } + }) + .await; + + if matches!( + decision, + ReviewDecision::Approved + | ReviewDecision::ApprovedForSession + | ReviewDecision::ApprovedExecpolicyAmendment { .. } + ) { + return Ok(()); + } + + Err(FunctionCallError::RespondToModel(format!( + "{} path `{}` was not approved", + access_kind_label(access.kind), + access.path.display() + ))) +} + +fn path_is_readable(turn: &TurnContext, path: &Path) -> bool { + if turn.sandbox_policy.has_full_disk_read_access() { + return true; + } + + turn.sandbox_policy + .get_readable_roots_with_cwd(&turn.cwd) + .iter() + .any(|root| path.starts_with(root.as_path())) +} + +fn path_is_writable(turn: &TurnContext, path: &Path) -> bool { + if turn.sandbox_policy.has_full_disk_write_access() { + return true; + } + + turn.sandbox_policy + .get_writable_roots_with_cwd(&turn.cwd) + .iter() + .any(|root| root.is_path_writable(path)) +} + +fn effective_read_path(path: &Path) -> PathBuf { + normalize_for_path_comparison(path).unwrap_or_else(|_| normalize_without_fs(path)) +} + +fn effective_write_path(path: &Path) -> PathBuf { + let write_path = resolve_symlink_write_paths(path) + .map(|paths| paths.write_path) + .unwrap_or_else(|_| path.to_path_buf()); + normalize_for_path_comparison(&write_path).unwrap_or_else(|_| normalize_without_fs(&write_path)) +} + +fn normalize_without_fs(path: &Path) -> PathBuf { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + other => normalized.push(other.as_os_str()), + } + } + normalized +} + +fn access_kind_label(kind: PathAccessKind) -> &'static str { + match kind { + PathAccessKind::Read => "read", + PathAccessKind::Write => "write", + } +} + +fn access_kind_verb(kind: PathAccessKind) -> &'static str { + match kind { + PathAccessKind::Read => "read from", + PathAccessKind::Write => "write to", + } +} diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 57a109dd48..a04c5883c6 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -13,6 +13,8 @@ use crate::tools::context::ToolPayload; use crate::tools::handlers::apply_patch::intercept_apply_patch; use crate::tools::handlers::normalize_and_validate_additional_permissions; use crate::tools::handlers::parse_arguments; +use crate::tools::handlers::parse_arguments_with_base_path; +use crate::tools::handlers::resolve_workdir_base_path; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; use crate::unified_exec::ExecCommandRequest; @@ -136,7 +138,9 @@ impl ToolHandler for UnifiedExecHandler { let response = match tool_name.as_str() { "exec_command" => { - let args: ExecCommandArgs = parse_arguments(&arguments)?; + let cwd = resolve_workdir_base_path(&arguments, context.turn.cwd.as_path())?; + let args: ExecCommandArgs = + parse_arguments_with_base_path(&arguments, cwd.as_path())?; maybe_emit_implicit_skill_invocation( session.as_ref(), turn.as_ref(), @@ -183,7 +187,7 @@ impl ToolHandler for UnifiedExecHandler { let workdir = workdir.filter(|value| !value.is_empty()); let workdir = workdir.map(|dir| context.turn.resolve_path(Some(dir))); - let cwd = workdir.clone().unwrap_or_else(|| context.turn.cwd.clone()); + let cwd = workdir.clone().unwrap_or(cwd); let normalized_additional_permissions = match normalize_and_validate_additional_permissions( request_permission_enabled, @@ -336,8 +340,15 @@ fn format_response(response: &UnifiedExecResponse) -> String { mod tests { use super::*; use crate::shell::default_user_shell; + use crate::tools::handlers::parse_arguments_with_base_path; + use crate::tools::handlers::resolve_workdir_base_path; + use codex_protocol::models::FileSystemPermissions; + use codex_protocol::models::PermissionProfile; + use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; + use std::fs; use std::sync::Arc; + use tempfile::tempdir; #[test] fn test_get_command_uses_default_shell_when_unspecified() -> anyhow::Result<()> { @@ -420,4 +431,37 @@ mod tests { ); Ok(()) } + + #[test] + fn exec_command_args_resolve_relative_additional_permissions_against_workdir() + -> anyhow::Result<()> { + let cwd = tempdir()?; + let workdir = cwd.path().join("nested"); + fs::create_dir_all(&workdir)?; + let expected_write = workdir.join("relative-write.txt"); + let json = r#"{ + "cmd": "echo hello", + "workdir": "nested", + "additional_permissions": { + "file_system": { + "write": ["./relative-write.txt"] + } + } + }"#; + + let base_path = resolve_workdir_base_path(json, cwd.path())?; + let args: ExecCommandArgs = parse_arguments_with_base_path(json, base_path.as_path())?; + + assert_eq!( + args.additional_permissions, + Some(PermissionProfile { + file_system: Some(FileSystemPermissions { + read: None, + write: Some(vec![AbsolutePathBuf::try_from(expected_write)?]), + }), + ..Default::default() + }) + ); + Ok(()) + } } diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index 066cb8258c..a234fd0eb8 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -11,6 +11,7 @@ use std::time::Duration; use codex_protocol::ThreadId; use codex_protocol::models::ContentItem; use codex_protocol::models::FunctionCallOutputContentItem; +use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; use serde::Deserialize; use serde::Serialize; @@ -24,6 +25,8 @@ use tokio::sync::Mutex; use tokio::sync::Notify; use tokio::sync::OnceCell; use tokio_util::sync::CancellationToken; +use tracing::info; +use tracing::trace; use tracing::warn; use uuid::Uuid; @@ -39,6 +42,8 @@ use crate::sandboxing::SandboxPermissions; use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::sandboxing::SandboxablePreference; +use crate::truncate::TruncationPolicy; +use crate::truncate::truncate_text; pub(crate) const JS_REPL_PRAGMA_PREFIX: &str = "// codex-js-repl:"; const KERNEL_SOURCE: &str = include_str!("kernel.js"); @@ -51,6 +56,7 @@ const JS_REPL_STDERR_TAIL_SEPARATOR: &str = " | "; const JS_REPL_EXEC_ID_LOG_LIMIT: usize = 8; const JS_REPL_MODEL_DIAG_STDERR_MAX_BYTES: usize = 1_024; const JS_REPL_MODEL_DIAG_ERROR_MAX_BYTES: usize = 256; +const JS_REPL_TOOL_RESPONSE_TEXT_PREVIEW_MAX_BYTES: usize = 512; /// Per-task js_repl handle stored on the turn context. pub(crate) struct JsReplHandle { @@ -98,6 +104,7 @@ pub struct JsReplArgs { #[derive(Clone, Debug)] pub struct JsExecResult { pub output: String, + pub content_items: Vec, } struct KernelState { @@ -119,10 +126,37 @@ struct ExecContext { #[derive(Default)] struct ExecToolCalls { in_flight: usize, + content_items: Vec, notify: Arc, cancel: CancellationToken, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(clippy::enum_variant_names)] +enum JsReplToolCallPayloadKind { + MessageContent, + FunctionText, + FunctionContentItems, + CustomText, + CustomContentItems, + McpResult, + McpErrorResult, + Error, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +struct JsReplToolCallResponseSummary { + response_type: Option, + payload_kind: Option, + payload_text_preview: Option, + payload_text_length: Option, + payload_item_count: Option, + text_item_count: Option, + image_item_count: Option, + structured_content_present: Option, + result_is_error: Option, +} + enum KernelStreamEnd { Shutdown, StdoutEof, @@ -338,6 +372,21 @@ impl JsReplManager { Some(state.cancel.clone()) } + async fn record_exec_tool_call_content_items( + exec_tool_calls: &Arc>>, + exec_id: &str, + content_items: Vec, + ) { + if content_items.is_empty() { + return; + } + + let mut calls = exec_tool_calls.lock().await; + if let Some(state) = calls.get_mut(exec_id) { + state.content_items.extend(content_items); + } + } + async fn finish_exec_tool_call( exec_tool_calls: &Arc>>, exec_id: &str, @@ -404,6 +453,205 @@ impl JsReplManager { } } + fn log_tool_call_response( + req: &RunToolRequest, + ok: bool, + summary: &JsReplToolCallResponseSummary, + response: Option<&JsonValue>, + error: Option<&str>, + ) { + info!( + exec_id = %req.exec_id, + tool_call_id = %req.id, + tool_name = %req.tool_name, + ok, + summary = ?summary, + "js_repl nested tool call completed" + ); + if let Some(response) = response { + trace!( + exec_id = %req.exec_id, + tool_call_id = %req.id, + tool_name = %req.tool_name, + response_json = %response, + "js_repl nested tool call raw response" + ); + } + if let Some(error) = error { + trace!( + exec_id = %req.exec_id, + tool_call_id = %req.id, + tool_name = %req.tool_name, + error = %error, + "js_repl nested tool call raw error" + ); + } + } + + fn summarize_text_payload( + response_type: Option<&str>, + payload_kind: JsReplToolCallPayloadKind, + text: &str, + ) -> JsReplToolCallResponseSummary { + JsReplToolCallResponseSummary { + response_type: response_type.map(str::to_owned), + payload_kind: Some(payload_kind), + payload_text_preview: (!text.is_empty()).then(|| { + truncate_text( + text, + TruncationPolicy::Bytes(JS_REPL_TOOL_RESPONSE_TEXT_PREVIEW_MAX_BYTES), + ) + }), + payload_text_length: Some(text.len()), + ..Default::default() + } + } + + fn summarize_function_output_payload( + response_type: &str, + payload_kind: JsReplToolCallPayloadKind, + output: &FunctionCallOutputPayload, + ) -> JsReplToolCallResponseSummary { + let (payload_item_count, text_item_count, image_item_count) = + if let Some(items) = output.content_items() { + let text_item_count = items + .iter() + .filter(|item| matches!(item, FunctionCallOutputContentItem::InputText { .. })) + .count(); + let image_item_count = items.len().saturating_sub(text_item_count); + ( + Some(items.len()), + Some(text_item_count), + Some(image_item_count), + ) + } else { + (None, None, None) + }; + let payload_text = output.body.to_text(); + JsReplToolCallResponseSummary { + response_type: Some(response_type.to_string()), + payload_kind: Some(payload_kind), + payload_text_preview: payload_text.as_deref().and_then(|text| { + (!text.is_empty()).then(|| { + truncate_text( + text, + TruncationPolicy::Bytes(JS_REPL_TOOL_RESPONSE_TEXT_PREVIEW_MAX_BYTES), + ) + }) + }), + payload_text_length: payload_text.as_ref().map(String::len), + payload_item_count, + text_item_count, + image_item_count, + ..Default::default() + } + } + + fn summarize_message_payload(content: &[ContentItem]) -> JsReplToolCallResponseSummary { + let text_item_count = content + .iter() + .filter(|item| { + matches!( + item, + ContentItem::InputText { .. } | ContentItem::OutputText { .. } + ) + }) + .count(); + let image_item_count = content.len().saturating_sub(text_item_count); + let payload_text = content + .iter() + .filter_map(|item| match item { + ContentItem::InputText { text } | ContentItem::OutputText { text } + if !text.trim().is_empty() => + { + Some(text.as_str()) + } + ContentItem::InputText { .. } + | ContentItem::InputImage { .. } + | ContentItem::OutputText { .. } => None, + }) + .collect::>(); + let payload_text = if payload_text.is_empty() { + None + } else { + Some(payload_text.join("\n")) + }; + JsReplToolCallResponseSummary { + response_type: Some("message".to_string()), + payload_kind: Some(JsReplToolCallPayloadKind::MessageContent), + payload_text_preview: payload_text.as_deref().and_then(|text| { + (!text.is_empty()).then(|| { + truncate_text( + text, + TruncationPolicy::Bytes(JS_REPL_TOOL_RESPONSE_TEXT_PREVIEW_MAX_BYTES), + ) + }) + }), + payload_text_length: payload_text.as_ref().map(String::len), + payload_item_count: Some(content.len()), + text_item_count: Some(text_item_count), + image_item_count: Some(image_item_count), + ..Default::default() + } + } + + fn summarize_tool_call_response(response: &ResponseInputItem) -> JsReplToolCallResponseSummary { + match response { + ResponseInputItem::Message { content, .. } => Self::summarize_message_payload(content), + ResponseInputItem::FunctionCallOutput { output, .. } => { + let payload_kind = if output.content_items().is_some() { + JsReplToolCallPayloadKind::FunctionContentItems + } else { + JsReplToolCallPayloadKind::FunctionText + }; + Self::summarize_function_output_payload( + "function_call_output", + payload_kind, + output, + ) + } + ResponseInputItem::CustomToolCallOutput { output, .. } => { + let payload_kind = if output.content_items().is_some() { + JsReplToolCallPayloadKind::CustomContentItems + } else { + JsReplToolCallPayloadKind::CustomText + }; + Self::summarize_function_output_payload( + "custom_tool_call_output", + payload_kind, + output, + ) + } + ResponseInputItem::McpToolCallOutput { result, .. } => match result { + Ok(result) => { + let output = FunctionCallOutputPayload::from(result); + let mut summary = Self::summarize_function_output_payload( + "mcp_tool_call_output", + JsReplToolCallPayloadKind::McpResult, + &output, + ); + summary.payload_item_count = Some(result.content.len()); + summary.structured_content_present = Some(result.structured_content.is_some()); + summary.result_is_error = Some(result.is_error.unwrap_or(false)); + summary + } + Err(error) => { + let mut summary = Self::summarize_text_payload( + Some("mcp_tool_call_output"), + JsReplToolCallPayloadKind::McpErrorResult, + error, + ); + summary.result_is_error = Some(true); + summary + } + }, + } + } + + fn summarize_tool_call_error(error: &str) -> JsReplToolCallResponseSummary { + Self::summarize_text_payload(None, JsReplToolCallPayloadKind::Error, error) + } + pub async fn reset(&self) -> Result<(), FunctionCallError> { let _permit = self.exec_lock.clone().acquire_owned().await.map_err(|_| { FunctionCallError::RespondToModel("js_repl execution unavailable".to_string()) @@ -546,7 +794,13 @@ impl JsReplManager { }; match response { - ExecResultMessage::Ok { output } => Ok(JsExecResult { output }), + ExecResultMessage::Ok { content_items } => { + let (output, content_items) = split_exec_result_content_items(content_items); + Ok(JsExecResult { + output, + content_items, + }) + } ExecResultMessage::Err { message } => Err(FunctionCallError::RespondToModel(message)), } } @@ -556,10 +810,7 @@ impl JsReplManager { turn: Arc, thread_id: Option, ) -> Result { - let node_path = resolve_node(self.node_path.as_deref()).ok_or_else(|| { - "Node runtime not found; install Node or set CODEX_JS_REPL_NODE_PATH".to_string() - })?; - ensure_node_version(&node_path).await?; + let node_path = resolve_compatible_node(self.node_path.as_deref()).await?; let kernel_path = self .write_kernel_script() @@ -616,6 +867,8 @@ impl JsReplManager { enforce_managed_network: has_managed_network_requirements, network: None, sandbox_policy_cwd: &turn.cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, codex_linux_sandbox_exe: turn.codex_linux_sandbox_exe.as_ref(), use_linux_sandbox_bwrap: turn .features @@ -851,10 +1104,22 @@ impl JsReplManager { error, } => { JsReplManager::wait_for_exec_tool_calls_map(&exec_tool_calls, &id).await; + let content_items = { + let calls = exec_tool_calls.lock().await; + calls + .get(&id) + .map(|state| state.content_items.clone()) + .unwrap_or_default() + }; let mut pending = pending_execs.lock().await; if let Some(tx) = pending.remove(&id) { let payload = if ok { - ExecResultMessage::Ok { output } + ExecResultMessage::Ok { + content_items: build_exec_result_content_items( + output, + content_items, + ), + } } else { ExecResultMessage::Err { message: error @@ -911,7 +1176,11 @@ impl JsReplManager { response: None, error: Some("js_repl execution reset".to_string()), }, - result = JsReplManager::run_tool_request(ctx, req) => result, + result = JsReplManager::run_tool_request( + ctx, + req, + Arc::clone(&exec_tool_calls_for_task), + ) => result, } } None => RunToolResult { @@ -1005,13 +1274,20 @@ impl JsReplManager { } } - async fn run_tool_request(exec: ExecContext, req: RunToolRequest) -> RunToolResult { + async fn run_tool_request( + exec: ExecContext, + req: RunToolRequest, + exec_tool_calls: Arc>>, + ) -> RunToolResult { if is_js_repl_internal_tool(&req.tool_name) { + let error = "js_repl cannot invoke itself".to_string(); + let summary = Self::summarize_tool_call_error(&error); + Self::log_tool_call_response(&req, false, &summary, None, Some(&error)); return RunToolResult { id: req.id, ok: false, response: None, - error: Some("js_repl cannot invoke itself".to_string()), + error: Some(error), }; } @@ -1075,62 +1351,50 @@ impl JsReplManager { .await { Ok(response) => { - if let ResponseInputItem::FunctionCallOutput { output, .. } = &response - && let Some(items) = output.content_items() - { - let mut has_image = false; - let mut content = Vec::with_capacity(items.len()); - for item in items { - match item { - FunctionCallOutputContentItem::InputText { text } => { - content.push(ContentItem::InputText { text: text.clone() }); - } - FunctionCallOutputContentItem::InputImage { image_url } => { - has_image = true; - content.push(ContentItem::InputImage { - image_url: image_url.clone(), - }); - } + if let Some(items) = response_content_items(&response) { + Self::record_exec_tool_call_content_items( + &exec_tool_calls, + &req.exec_id, + items, + ) + .await; + } + + let summary = Self::summarize_tool_call_response(&response); + match serde_json::to_value(response) { + Ok(value) => { + Self::log_tool_call_response(&req, true, &summary, Some(&value), None); + RunToolResult { + id: req.id, + ok: true, + response: Some(value), + error: None, } } - - if has_image - && session - .inject_response_items(vec![ResponseInputItem::Message { - role: "user".to_string(), - content, - }]) - .await - .is_err() - { - warn!( - tool_name = %tool_name, - "js_repl tool call returned image content but there was no active turn to attach it to" - ); + Err(err) => { + let error = format!("failed to serialize tool output: {err}"); + let summary = Self::summarize_tool_call_error(&error); + Self::log_tool_call_response(&req, false, &summary, None, Some(&error)); + RunToolResult { + id: req.id, + ok: false, + response: None, + error: Some(error), + } } } - - match serde_json::to_value(response) { - Ok(value) => RunToolResult { - id: req.id, - ok: true, - response: Some(value), - error: None, - }, - Err(err) => RunToolResult { - id: req.id, - ok: false, - response: None, - error: Some(format!("failed to serialize tool output: {err}")), - }, + } + Err(err) => { + let error = err.to_string(); + let summary = Self::summarize_tool_call_error(&error); + Self::log_tool_call_response(&req, false, &summary, None, Some(&error)); + RunToolResult { + id: req.id, + ok: false, + response: None, + error: Some(error), } } - Err(err) => RunToolResult { - id: req.id, - ok: false, - response: None, - error: Some(err.to_string()), - }, } } @@ -1168,6 +1432,50 @@ impl JsReplManager { } } +fn response_content_items( + response: &ResponseInputItem, +) -> Option> { + match response { + ResponseInputItem::FunctionCallOutput { output, .. } + | ResponseInputItem::CustomToolCallOutput { output, .. } => output + .content_items() + .map(<[FunctionCallOutputContentItem]>::to_vec), + ResponseInputItem::McpToolCallOutput { result, .. } => match result { + Ok(result) => FunctionCallOutputPayload::from(result) + .content_items() + .map(<[FunctionCallOutputContentItem]>::to_vec), + Err(_) => None, + }, + ResponseInputItem::Message { .. } => None, + } +} + +fn build_exec_result_content_items( + output: String, + content_items: Vec, +) -> Vec { + let mut all_content_items = Vec::with_capacity(content_items.len() + 1); + all_content_items.push(FunctionCallOutputContentItem::InputText { text: output }); + all_content_items.extend(content_items); + all_content_items +} + +fn split_exec_result_content_items( + mut content_items: Vec, +) -> (String, Vec) { + match content_items.first() { + Some(FunctionCallOutputContentItem::InputText { .. }) => { + let FunctionCallOutputContentItem::InputText { text } = content_items.remove(0) else { + unreachable!("first content item should be input_text"); + }; + (text, content_items) + } + Some(FunctionCallOutputContentItem::InputImage { .. }) | None => { + (String::new(), content_items) + } + } +} + fn is_freeform_tool(specs: &[ToolSpec], name: &str) -> bool { specs .iter() @@ -1223,8 +1531,12 @@ struct RunToolResult { #[derive(Debug)] enum ExecResultMessage { - Ok { output: String }, - Err { message: String }, + Ok { + content_items: Vec, + }, + Err { + message: String, + }, } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -1321,6 +1633,14 @@ async fn ensure_node_version(node_path: &Path) -> Result<(), String> { Ok(()) } +pub(crate) async fn resolve_compatible_node(config_path: Option<&Path>) -> Result { + let node_path = resolve_node(config_path).ok_or_else(|| { + "Node runtime not found; install Node or set CODEX_JS_REPL_NODE_PATH".to_string() + })?; + ensure_node_version(&node_path).await?; + Ok(node_path) +} + pub(crate) fn resolve_node(config_path: Option<&Path>) -> Option { if let Some(path) = std::env::var_os("CODEX_JS_REPL_NODE_PATH") { let p = PathBuf::from(path); @@ -1354,7 +1674,8 @@ mod tests { use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem; use codex_protocol::dynamic_tools::DynamicToolResponse; use codex_protocol::dynamic_tools::DynamicToolSpec; - use codex_protocol::models::ContentItem; + use codex_protocol::models::FunctionCallOutputContentItem; + use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; use codex_protocol::openai_models::InputModality; use pretty_assertions::assert_eq; @@ -1572,6 +1893,84 @@ mod tests { ); } + #[test] + fn summarize_tool_call_response_for_multimodal_function_output() { + let response = ResponseInputItem::FunctionCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,abcd".to_string(), + }, + ]), + }; + + let actual = JsReplManager::summarize_tool_call_response(&response); + + assert_eq!( + actual, + JsReplToolCallResponseSummary { + response_type: Some("function_call_output".to_string()), + payload_kind: Some(JsReplToolCallPayloadKind::FunctionContentItems), + payload_text_preview: None, + payload_text_length: None, + payload_item_count: Some(1), + text_item_count: Some(0), + image_item_count: Some(1), + structured_content_present: None, + result_is_error: None, + } + ); + } + + #[test] + fn summarize_tool_call_response_for_multimodal_custom_output() { + let response = ResponseInputItem::CustomToolCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,abcd".to_string(), + }, + ]), + }; + + let actual = JsReplManager::summarize_tool_call_response(&response); + + assert_eq!( + actual, + JsReplToolCallResponseSummary { + response_type: Some("custom_tool_call_output".to_string()), + payload_kind: Some(JsReplToolCallPayloadKind::CustomContentItems), + payload_text_preview: None, + payload_text_length: None, + payload_item_count: Some(1), + text_item_count: Some(0), + image_item_count: Some(1), + structured_content_present: None, + result_is_error: None, + } + ); + } + + #[test] + fn summarize_tool_call_error_marks_error_payload() { + let actual = JsReplManager::summarize_tool_call_error("tool failed"); + + assert_eq!( + actual, + JsReplToolCallResponseSummary { + response_type: None, + payload_kind: Some(JsReplToolCallPayloadKind::Error), + payload_text_preview: Some("tool failed".to_string()), + payload_text_length: Some("tool failed".len()), + payload_item_count: None, + text_item_count: None, + image_item_count: None, + structured_content_present: None, + result_is_error: None, + } + ); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn reset_clears_inflight_exec_tool_calls_without_waiting() { let manager = JsReplManager::new(None, Vec::new()) @@ -2012,20 +2411,22 @@ console.log(out.output?.body?.text ?? ""); ) .await?; assert!(result.output.contains("function_call_output")); - - let pending_input = session.get_pending_input().await; - let [ResponseInputItem::Message { role, content }] = pending_input.as_slice() else { - panic!( - "view_image should inject exactly one pending input message, got {pending_input:?}" - ); - }; - assert_eq!(role, "user"); - let [ContentItem::InputImage { image_url }] = content.as_slice() else { - panic!( - "view_image should inject exactly one input_image content item, got {content:?}" - ); + assert_eq!( + result.content_items.as_slice(), + [FunctionCallOutputContentItem::InputImage { + image_url: + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" + .to_string(), + }] + .as_slice() + ); + let [FunctionCallOutputContentItem::InputImage { image_url }] = + result.content_items.as_slice() + else { + panic!("view_image should return exactly one input_image content item"); }; assert!(image_url.starts_with("data:image/png;base64,")); + assert!(session.get_pending_input().await.is_empty()); Ok(()) } @@ -2106,22 +2507,18 @@ console.log(out.type); response_watcher_result?; let result = result?; assert!(result.output.contains("function_call_output")); - - let pending_input = session.get_pending_input().await; assert_eq!( - pending_input, - vec![ResponseInputItem::Message { - role: "user".to_string(), - content: vec![ - ContentItem::InputText { - text: "inline image note".to_string(), - }, - ContentItem::InputImage { - image_url: image_url.to_string(), - }, - ], - }] + result.content_items, + vec![ + FunctionCallOutputContentItem::InputText { + text: "inline image note".to_string(), + }, + FunctionCallOutputContentItem::InputImage { + image_url: image_url.to_string(), + }, + ] ); + assert!(session.get_pending_input().await.is_empty()); Ok(()) } diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index ca31ec4d4c..aeef59833d 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -331,6 +331,7 @@ impl NetworkApprovalService { protocol, }; + let available_decisions = None; let approval_decision = session .request_command_approval( turn_context.as_ref(), @@ -342,6 +343,7 @@ impl NetworkApprovalService { Some(network_approval_context.clone()), None, None, + available_decisions, ) .await; diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index 04d505c584..5f2fc89e5f 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -117,7 +117,10 @@ impl ToolCallRuntime { match &call.payload { ToolPayload::Custom { .. } => ResponseInputItem::CustomToolCallOutput { call_id: call.call_id.clone(), - output: Self::abort_message(call, secs), + output: FunctionCallOutputPayload { + body: FunctionCallOutputBody::Text(Self::abort_message(call, secs)), + ..Default::default() + }, }, ToolPayload::Mcp { .. } => ResponseInputItem::McpToolCallOutput { call_id: call.call_id.clone(), diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 7a0be68df3..3c021cc582 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -379,6 +379,7 @@ async fn dispatch_after_tool_use_hook( .dispatch(HookPayload { session_id: session.conversation_id, cwd: turn.cwd.clone(), + client: turn.app_server_client_name.clone(), triggered_at: chrono::Utc::now(), hook_event: HookEvent::AfterToolUse { event: HookEventAfterToolUse { diff --git a/codex-rs/core/src/tools/router.rs b/codex-rs/core/src/tools/router.rs index 4897b4ea6f..a55fb5fd5a 100644 --- a/codex-rs/core/src/tools/router.rs +++ b/codex-rs/core/src/tools/router.rs @@ -197,7 +197,10 @@ impl ToolRouter { if payload_outputs_custom { ResponseInputItem::CustomToolCallOutput { call_id, - output: message, + output: codex_protocol::models::FunctionCallOutputPayload { + body: FunctionCallOutputBody::Text(message), + success: Some(false), + }, } } else { ResponseInputItem::FunctionCallOutput { diff --git a/codex-rs/core/src/tools/runtimes/mod.rs b/codex-rs/core/src/tools/runtimes/mod.rs index 937ab341d8..51002f3ce9 100644 --- a/codex-rs/core/src/tools/runtimes/mod.rs +++ b/codex-rs/core/src/tools/runtimes/mod.rs @@ -9,6 +9,7 @@ use crate::path_utils; use crate::sandboxing::CommandSpec; use crate::sandboxing::SandboxPermissions; use crate::shell::Shell; +use crate::skills::SkillMetadata; use crate::tools::sandboxing::ToolError; use codex_protocol::models::PermissionProfile; use std::collections::HashMap; @@ -18,6 +19,14 @@ pub mod apply_patch; pub mod shell; pub mod unified_exec; +#[derive(Debug, Clone)] +pub(crate) struct ExecveSessionApproval { + /// If this execve session approval is associated with a skill script, this + /// field contains metadata about the skill. + #[cfg_attr(not(unix), allow(dead_code))] + pub skill: Option, +} + /// Shared helper to construct a CommandSpec from a tokenized command line. /// Validates that at least a program is present. pub(crate) fn build_command_spec( diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index 80d3b22ebb..101d9309fd 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -150,6 +150,7 @@ impl Approvable for ShellRuntime { let call_id = ctx.call_id.to_string(); Box::pin(async move { with_cached_approval(&session.services, "shell", keys, move || async move { + let available_decisions = None; session .request_command_approval( turn, @@ -163,6 +164,7 @@ impl Approvable for ShellRuntime { .proposed_execpolicy_amendment() .cloned(), req.additional_permissions.clone(), + available_decisions, ) .await }) 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 7485825ab1..36f63be4fa 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -9,14 +9,20 @@ use crate::features::Feature; use crate::sandboxing::SandboxPermissions; use crate::shell::ShellType; use crate::skills::SkillMetadata; +use crate::skills::permissions::compile_permission_profile; +use crate::tools::runtimes::ExecveSessionApproval; use crate::tools::runtimes::build_command_spec; use crate::tools::sandboxing::SandboxAttempt; +use crate::tools::sandboxing::SandboxablePreference; use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; use codex_execpolicy::Decision; +use codex_execpolicy::Evaluation; +use codex_execpolicy::MatchOptions; use codex_execpolicy::Policy; use codex_execpolicy::RuleMatch; use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::models::MacOsSeatbeltProfileExtensions; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::NetworkPolicyRuleAction; @@ -25,11 +31,15 @@ use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::SandboxPolicy; use codex_shell_command::bash::parse_shell_lc_plain_commands; use codex_shell_command::bash::parse_shell_lc_single_command_prefix; -use codex_shell_escalation::EscalateAction; use codex_shell_escalation::EscalateServer; +use codex_shell_escalation::EscalationDecision; +use codex_shell_escalation::EscalationExecution; +use codex_shell_escalation::EscalationPermissions; use codex_shell_escalation::EscalationPolicy; use codex_shell_escalation::ExecParams; use codex_shell_escalation::ExecResult; +use codex_shell_escalation::Permissions as EscalatedPermissions; +use codex_shell_escalation::PreparedExec; use codex_shell_escalation::ShellCommandExecutor; use codex_shell_escalation::Stopwatch; use codex_utils_absolute_path::AbsolutePathBuf; @@ -72,14 +82,9 @@ pub(super) async fn try_run_zsh_fork( let sandbox_exec_request = attempt .env_for(spec, req.network.as_ref()) .map_err(|err| ToolError::Codex(err.into()))?; - // Keep env/network/sandbox metadata from `attempt.env_for()`, but build the - // script from the original shell argv. `attempt.env_for()` may wrap the - // command with `sandbox-exec` on macOS, and passing those wrapper flags - // (`-p`, `-D...`) through zsh breaks the zsh-fork path before subcommand - // approval runs. let crate::sandboxing::ExecRequest { - command: _sandbox_command, - cwd: _sandbox_cwd, + command, + cwd: sandbox_cwd, env: sandbox_env, network: sandbox_network, expiration: _sandbox_expiration, @@ -90,7 +95,7 @@ pub(super) async fn try_run_zsh_fork( justification, arg0, } = sandbox_exec_request; - let ParsedShellCommand { script, login } = extract_shell_script(command)?; + let ParsedShellCommand { script, login } = extract_shell_script(&command)?; let effective_timeout = Duration::from_millis( req.timeout_ms .unwrap_or(crate::exec::DEFAULT_EXEC_COMMAND_TIMEOUT_MS), @@ -99,6 +104,8 @@ pub(super) async fn try_run_zsh_fork( ctx.session.services.exec_policy.current().as_ref().clone(), )); let command_executor = CoreShellCommandExecutor { + command, + cwd: sandbox_cwd, sandbox_policy, sandbox, env: sandbox_env, @@ -107,6 +114,15 @@ pub(super) async fn try_run_zsh_fork( sandbox_permissions, justification, arg0, + sandbox_policy_cwd: ctx.turn.cwd.clone(), + macos_seatbelt_profile_extensions: ctx + .turn + .config + .permissions + .macos_seatbelt_profile_extensions + .clone(), + codex_linux_sandbox_exe: ctx.turn.codex_linux_sandbox_exe.clone(), + use_linux_sandbox_bwrap: ctx.turn.features.enabled(Feature::UseLinuxSandboxBwrap), }; let main_execve_wrapper_exe = ctx .session @@ -138,6 +154,7 @@ pub(super) async fn try_run_zsh_fork( approval_policy: ctx.turn.approval_policy.value(), sandbox_policy: attempt.policy.clone(), sandbox_permissions: req.sandbox_permissions, + prompt_permissions: req.additional_permissions.clone(), stopwatch: stopwatch.clone(), }; @@ -148,7 +165,7 @@ pub(super) async fn try_run_zsh_fork( ); let exec_result = escalate_server - .exec(exec_params, cancel_token, &command_executor) + .exec(exec_params, cancel_token, Arc::new(command_executor)) .await .map_err(|err| ToolError::Rejected(err.to_string()))?; @@ -163,11 +180,15 @@ struct CoreShellActionProvider { approval_policy: AskForApproval, sandbox_policy: SandboxPolicy, sandbox_permissions: SandboxPermissions, + prompt_permissions: Option, stopwatch: Stopwatch, } +#[allow(clippy::large_enum_variant)] enum DecisionSource { - SkillScript, + SkillScript { + skill: SkillMetadata, + }, PrefixRule, /// Often, this is `is_safe_command()`. UnmatchedCommandFallback, @@ -181,6 +202,46 @@ impl CoreShellActionProvider { }) } + fn shell_request_escalation_execution( + sandbox_permissions: SandboxPermissions, + sandbox_policy: &SandboxPolicy, + additional_permissions: Option<&PermissionProfile>, + macos_seatbelt_profile_extensions: Option<&MacOsSeatbeltProfileExtensions>, + ) -> EscalationExecution { + match sandbox_permissions { + SandboxPermissions::UseDefault => EscalationExecution::TurnDefault, + SandboxPermissions::RequireEscalated => EscalationExecution::Unsandboxed, + SandboxPermissions::WithAdditionalPermissions => additional_permissions + .map(|_| { + // Shell request additional permissions were already normalized and + // merged into the first-attempt sandbox policy. + EscalationExecution::Permissions(EscalationPermissions::Permissions( + EscalatedPermissions { + sandbox_policy: sandbox_policy.clone(), + macos_seatbelt_profile_extensions: macos_seatbelt_profile_extensions + .cloned(), + }, + )) + }) + .unwrap_or(EscalationExecution::TurnDefault), + } + } + + fn skill_escalation_execution(skill: &SkillMetadata) -> EscalationExecution { + compile_permission_profile(skill.permission_profile.clone()) + .map(|permissions| { + EscalationExecution::Permissions(EscalationPermissions::Permissions( + EscalatedPermissions { + sandbox_policy: permissions.sandbox_policy.get().clone(), + macos_seatbelt_profile_extensions: permissions + .macos_seatbelt_profile_extensions + .clone(), + }, + )) + }) + .unwrap_or(EscalationExecution::TurnDefault) + } + async fn prompt( &self, program: &AbsolutePathBuf, @@ -188,6 +249,7 @@ impl CoreShellActionProvider { workdir: &AbsolutePathBuf, stopwatch: &Stopwatch, additional_permissions: Option, + decision_source: &DecisionSource, ) -> anyhow::Result { let command = join_program_and_argv(program, argv); let workdir = workdir.to_path_buf(); @@ -197,6 +259,20 @@ impl CoreShellActionProvider { let approval_id = Some(Uuid::new_v4().to_string()); Ok(stopwatch .pause_for(async move { + let available_decisions = vec![ + Some(ReviewDecision::Approved), + // Currently, ApprovedForSession is only honored for skills, + // so only offer it for skill script approvals. + if matches!(decision_source, DecisionSource::SkillScript { .. }) { + Some(ReviewDecision::ApprovedForSession) + } else { + None + }, + Some(ReviewDecision::Abort), + ] + .into_iter() + .flatten() + .collect(); session .request_command_approval( &turn, @@ -208,6 +284,7 @@ impl CoreShellActionProvider { None, None, additional_permissions, + Some(available_decisions), ) .await }) @@ -248,22 +325,21 @@ impl CoreShellActionProvider { program: &AbsolutePathBuf, argv: &[String], workdir: &AbsolutePathBuf, - additional_permissions: Option, + prompt_permissions: Option, + escalation_execution: EscalationExecution, decision_source: DecisionSource, - ) -> anyhow::Result { + ) -> anyhow::Result { let action = match decision { - Decision::Forbidden => EscalateAction::Deny { - reason: Some("Execution forbidden by policy".to_string()), - }, + Decision::Forbidden => { + EscalationDecision::deny(Some("Execution forbidden by policy".to_string())) + } Decision::Prompt => { if matches!( self.approval_policy, AskForApproval::Never | AskForApproval::Reject(RejectConfig { rules: true, .. }) ) { - EscalateAction::Deny { - reason: Some("Execution forbidden by policy".to_string()), - } + EscalationDecision::deny(Some("Execution forbidden by policy".to_string())) } else { match self .prompt( @@ -271,35 +347,44 @@ impl CoreShellActionProvider { argv, workdir, &self.stopwatch, - additional_permissions, + prompt_permissions, + &decision_source, ) .await? { ReviewDecision::Approved | ReviewDecision::ApprovedExecpolicyAmendment { .. } => { if needs_escalation { - EscalateAction::Escalate + EscalationDecision::escalate(escalation_execution.clone()) } else { - EscalateAction::Run + EscalationDecision::run() } } ReviewDecision::ApprovedForSession => { // Currently, we only add session approvals for // skill scripts because we are storing only the // `program` whereas prefix rules may be restricted by a longer prefix. - if matches!(decision_source, DecisionSource::SkillScript) { + if let DecisionSource::SkillScript { skill } = decision_source { + tracing::debug!( + "Adding session approval for {program:?} due to user approval of skill script {skill:?}" + ); self.session .services .execve_session_approvals .write() .await - .insert(program.clone()); + .insert( + program.clone(), + ExecveSessionApproval { + skill: Some(skill.clone()), + }, + ); } if needs_escalation { - EscalateAction::Escalate + EscalationDecision::escalate(escalation_execution.clone()) } else { - EscalateAction::Run + EscalationDecision::run() } } ReviewDecision::NetworkPolicyAmendment { @@ -307,29 +392,29 @@ impl CoreShellActionProvider { } => match network_policy_amendment.action { NetworkPolicyRuleAction::Allow => { if needs_escalation { - EscalateAction::Escalate + EscalationDecision::escalate(escalation_execution.clone()) } else { - EscalateAction::Run + EscalationDecision::run() } } - NetworkPolicyRuleAction::Deny => EscalateAction::Deny { - reason: Some("User denied execution".to_string()), - }, - }, - ReviewDecision::Denied => EscalateAction::Deny { - reason: Some("User denied execution".to_string()), - }, - ReviewDecision::Abort => EscalateAction::Deny { - reason: Some("User cancelled execution".to_string()), + NetworkPolicyRuleAction::Deny => { + EscalationDecision::deny(Some("User denied execution".to_string())) + } }, + ReviewDecision::Denied => { + EscalationDecision::deny(Some("User denied execution".to_string())) + } + ReviewDecision::Abort => { + EscalationDecision::deny(Some("User cancelled execution".to_string())) + } } } } Decision::Allow => { if needs_escalation { - EscalateAction::Escalate + EscalationDecision::escalate(escalation_execution) } else { - EscalateAction::Run + EscalationDecision::run() } } }; @@ -340,6 +425,12 @@ impl CoreShellActionProvider { } } +// Shell-wrapper parsing is weaker than direct exec interception because it can +// only see the script text, not the final resolved executable path. Keep it +// disabled by default so path-sensitive rules rely on the later authoritative +// execve interception. +const ENABLE_INTERCEPTED_EXEC_POLICY_SHELL_WRAPPER_PARSING: bool = false; + #[async_trait::async_trait] impl EscalationPolicy for CoreShellActionProvider { async fn determine_action( @@ -347,11 +438,36 @@ impl EscalationPolicy for CoreShellActionProvider { program: &AbsolutePathBuf, argv: &[String], workdir: &AbsolutePathBuf, - ) -> anyhow::Result { + ) -> anyhow::Result { tracing::debug!( "Determining escalation action for command {program:?} with args {argv:?} in {workdir:?}" ); + // Check to see whether `program` has an existing entry in + // `execve_session_approvals`. If so, we can skip policy checks and user + // prompts and go straight to allowing execution. + let approval = { + self.session + .services + .execve_session_approvals + .read() + .await + .get(program) + .cloned() + }; + if let Some(approval) = approval { + tracing::debug!( + "Found session approval for {program:?}, allowing execution without further checks" + ); + let execution = approval + .skill + .as_ref() + .map(Self::skill_escalation_execution) + .unwrap_or(EscalationExecution::TurnDefault); + + return Ok(EscalationDecision::escalate(execution)); + } + // In the usual case, the execve wrapper reports the command being // executed in `program`, so a direct skill lookup is sufficient. if let Some(skill) = self.find_skill(program).await { @@ -359,58 +475,35 @@ impl EscalationPolicy for CoreShellActionProvider { // to skills, which means we ignore exec policy rules for those // scripts. tracing::debug!("Matched {program:?} to skill {skill:?}, prompting for approval"); - // TODO(mbolin): We should read the permissions associated with the - // skill and use those specific permissions in the - // EscalateAction::Run case, rather than always escalating when a - // skill matches. let needs_escalation = true; - let is_approved_for_session = self - .session - .services - .execve_session_approvals - .read() - .await - .contains(program); - let decision = if is_approved_for_session { - Decision::Allow - } else { - Decision::Prompt + let decision_source = DecisionSource::SkillScript { + skill: skill.clone(), }; return self .process_decision( - decision, + Decision::Prompt, needs_escalation, program, argv, workdir, skill.permission_profile.clone(), - DecisionSource::SkillScript, + Self::skill_escalation_execution(&skill), + decision_source, ) .await; } - let command = join_program_and_argv(program, argv); - let (commands, used_complex_parsing) = - if let Some(commands) = parse_shell_lc_plain_commands(&command) { - (commands, false) - } else if let Some(single_command) = parse_shell_lc_single_command_prefix(&command) { - (vec![single_command], true) - } else { - (vec![command.clone()], false) - }; - - let fallback = |cmd: &[String]| { - crate::exec_policy::render_decision_for_unmatched_command( - self.approval_policy, - &self.sandbox_policy, - cmd, - self.sandbox_permissions, - used_complex_parsing, - ) - }; let evaluation = { let policy = self.policy.read().await; - policy.check_multiple(commands.iter(), &fallback) + evaluate_intercepted_exec_policy( + &policy, + program, + argv, + self.approval_policy, + &self.sandbox_policy, + self.sandbox_permissions, + ENABLE_INTERCEPTED_EXEC_POLICY_SHELL_WRAPPER_PARSING, + ) }; // When true, means the Evaluation was due to *.rules, not the // fallback function. @@ -424,20 +517,117 @@ impl EscalationPolicy for CoreShellActionProvider { } else { DecisionSource::UnmatchedCommandFallback }; + let escalation_execution = match decision_source { + DecisionSource::PrefixRule => EscalationExecution::Unsandboxed, + DecisionSource::UnmatchedCommandFallback => Self::shell_request_escalation_execution( + self.sandbox_permissions, + &self.sandbox_policy, + self.prompt_permissions.as_ref(), + self.turn + .config + .permissions + .macos_seatbelt_profile_extensions + .as_ref(), + ), + DecisionSource::SkillScript { .. } => unreachable!("handled above"), + }; self.process_decision( evaluation.decision, needs_escalation, program, argv, workdir, - None, + self.prompt_permissions.clone(), + escalation_execution, decision_source, ) .await } } +fn evaluate_intercepted_exec_policy( + policy: &Policy, + program: &AbsolutePathBuf, + argv: &[String], + approval_policy: AskForApproval, + sandbox_policy: &SandboxPolicy, + sandbox_permissions: SandboxPermissions, + enable_intercepted_exec_policy_shell_wrapper_parsing: bool, +) -> Evaluation { + let CandidateCommands { + commands, + used_complex_parsing, + } = if enable_intercepted_exec_policy_shell_wrapper_parsing { + // In this codepath, the first argument in `commands` could be a bare + // name like `find` instead of an absolute path like `/usr/bin/find`. + // It could also be a shell built-in like `echo`. + commands_for_intercepted_exec_policy(program, argv) + } else { + // In this codepath, `commands` has a single entry where the program + // is always an absolute path. + CandidateCommands { + commands: vec![join_program_and_argv(program, argv)], + used_complex_parsing: false, + } + }; + + let fallback = |cmd: &[String]| { + crate::exec_policy::render_decision_for_unmatched_command( + approval_policy, + sandbox_policy, + cmd, + sandbox_permissions, + used_complex_parsing, + ) + }; + + policy.check_multiple_with_options( + commands.iter(), + &fallback, + &MatchOptions { + resolve_host_executables: true, + }, + ) +} + +struct CandidateCommands { + commands: Vec>, + used_complex_parsing: bool, +} + +fn commands_for_intercepted_exec_policy( + program: &AbsolutePathBuf, + argv: &[String], +) -> CandidateCommands { + if let [_, flag, script] = argv { + let shell_command = [ + program.to_string_lossy().to_string(), + flag.clone(), + script.clone(), + ]; + if let Some(commands) = parse_shell_lc_plain_commands(&shell_command) { + return CandidateCommands { + commands, + used_complex_parsing: false, + }; + } + if let Some(single_command) = parse_shell_lc_single_command_prefix(&shell_command) { + return CandidateCommands { + commands: vec![single_command], + used_complex_parsing: true, + }; + } + } + + CandidateCommands { + commands: vec![join_program_and_argv(program, argv)], + used_complex_parsing: false, + } +} + struct CoreShellCommandExecutor { + command: Vec, + cwd: PathBuf, sandbox_policy: SandboxPolicy, sandbox: SandboxType, env: HashMap, @@ -446,14 +636,18 @@ struct CoreShellCommandExecutor { sandbox_permissions: SandboxPermissions, justification: Option, arg0: Option, + sandbox_policy_cwd: PathBuf, + macos_seatbelt_profile_extensions: Option, + codex_linux_sandbox_exe: Option, + use_linux_sandbox_bwrap: bool, } #[async_trait::async_trait] impl ShellCommandExecutor for CoreShellCommandExecutor { async fn run( &self, - command: Vec, - cwd: PathBuf, + _command: Vec, + _cwd: PathBuf, env: HashMap, cancel_rx: CancellationToken, ) -> anyhow::Result { @@ -466,8 +660,8 @@ impl ShellCommandExecutor for CoreShellCommandExecutor { let result = crate::sandboxing::execute_env( crate::sandboxing::ExecRequest { - command, - cwd, + command: self.command.clone(), + cwd: self.cwd.clone(), env: exec_env, network: self.network.clone(), expiration: ExecExpiration::Cancellation(cancel_rx), @@ -491,6 +685,126 @@ impl ShellCommandExecutor for CoreShellCommandExecutor { timed_out: result.timed_out, }) } + + async fn prepare_escalated_exec( + &self, + program: &AbsolutePathBuf, + argv: &[String], + workdir: &AbsolutePathBuf, + env: HashMap, + execution: EscalationExecution, + ) -> anyhow::Result { + let command = join_program_and_argv(program, argv); + let Some(first_arg) = argv.first() else { + return Err(anyhow::anyhow!( + "intercepted exec request must contain argv[0]" + )); + }; + + let prepared = match execution { + EscalationExecution::Unsandboxed => PreparedExec { + command, + cwd: workdir.to_path_buf(), + env, + arg0: Some(first_arg.clone()), + }, + EscalationExecution::TurnDefault => self.prepare_sandboxed_exec( + command, + workdir, + env, + &self.sandbox_policy, + None, + self.macos_seatbelt_profile_extensions.as_ref(), + )?, + EscalationExecution::Permissions(EscalationPermissions::PermissionProfile( + permission_profile, + )) => self.prepare_sandboxed_exec( + command, + workdir, + env, + &self.sandbox_policy, + Some(permission_profile), + None, + )?, + EscalationExecution::Permissions(EscalationPermissions::Permissions(permissions)) => { + self.prepare_sandboxed_exec( + command, + workdir, + env, + &permissions.sandbox_policy, + None, + permissions.macos_seatbelt_profile_extensions.as_ref(), + )? + } + }; + + Ok(prepared) + } +} + +impl CoreShellCommandExecutor { + fn prepare_sandboxed_exec( + &self, + command: Vec, + workdir: &AbsolutePathBuf, + env: HashMap, + sandbox_policy: &SandboxPolicy, + additional_permissions: Option, + #[cfg(target_os = "macos")] macos_seatbelt_profile_extensions: Option< + &MacOsSeatbeltProfileExtensions, + >, + #[cfg(not(target_os = "macos"))] _macos_seatbelt_profile_extensions: Option< + &MacOsSeatbeltProfileExtensions, + >, + ) -> anyhow::Result { + let (program, args) = command + .split_first() + .ok_or_else(|| anyhow::anyhow!("prepared command must not be empty"))?; + let sandbox_manager = crate::sandboxing::SandboxManager::new(); + let sandbox = sandbox_manager.select_initial( + sandbox_policy, + SandboxablePreference::Auto, + self.windows_sandbox_level, + self.network.is_some(), + ); + let mut exec_request = + sandbox_manager.transform(crate::sandboxing::SandboxTransformRequest { + spec: crate::sandboxing::CommandSpec { + program: program.clone(), + args: args.to_vec(), + cwd: workdir.to_path_buf(), + env, + expiration: ExecExpiration::DefaultTimeout, + sandbox_permissions: if additional_permissions.is_some() { + SandboxPermissions::WithAdditionalPermissions + } else { + SandboxPermissions::UseDefault + }, + additional_permissions, + justification: self.justification.clone(), + }, + policy: sandbox_policy, + sandbox, + enforce_managed_network: self.network.is_some(), + network: self.network.as_ref(), + sandbox_policy_cwd: &self.sandbox_policy_cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions, + codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.as_ref(), + use_linux_sandbox_bwrap: self.use_linux_sandbox_bwrap, + windows_sandbox_level: self.windows_sandbox_level, + })?; + if let Some(network) = exec_request.network.as_ref() { + network.apply_to_env(&mut exec_request.env); + } + + Ok(PreparedExec { + command: exec_request.command, + cwd: exec_request.cwd, + env: exec_request.env, + arg0: exec_request.arg0, + }) + } } #[derive(Debug, Eq, PartialEq)] @@ -500,19 +814,20 @@ struct ParsedShellCommand { } fn extract_shell_script(command: &[String]) -> Result { - match command { - [_, flag, script, ..] if flag == "-c" => Ok(ParsedShellCommand { - script: script.clone(), - login: false, - }), - [_, flag, script, ..] if flag == "-lc" => Ok(ParsedShellCommand { - script: script.clone(), - login: true, - }), - _ => Err(ToolError::Rejected( - "unexpected shell command format for zsh-fork execution".to_string(), - )), + // Commands reaching zsh-fork can be wrapped by environment/sandbox helpers, so + // we search for the first `-c`/`-lc` triple anywhere in the argv rather + // than assuming it is the first positional form. + if let Some((script, login)) = command.windows(3).find_map(|parts| match parts { + [_, flag, script] if flag == "-c" => Some((script.to_owned(), false)), + [_, flag, script] if flag == "-lc" => Some((script.to_owned(), true)), + _ => None, + }) { + return Ok(ParsedShellCommand { script, login }); } + + Err(ToolError::Rejected( + "unexpected shell command format for zsh-fork execution".to_string(), + )) } fn map_exec_result( @@ -557,70 +872,5 @@ fn join_program_and_argv(program: &AbsolutePathBuf, argv: &[String]) -> Vec String { + let mut path = if cfg!(windows) { + PathBuf::from(r"C:\") + } else { + PathBuf::from("/") + }; + for segment in segments { + path.push(segment); + } + path.to_string_lossy().into_owned() +} + +fn starlark_string(value: &str) -> String { + value.replace('\\', "\\\\").replace('"', "\\\"") +} + +#[test] +fn extract_shell_script_preserves_login_flag() { + assert_eq!( + extract_shell_script(&["/bin/zsh".into(), "-lc".into(), "echo hi".into()]).unwrap(), + ParsedShellCommand { + script: "echo hi".to_string(), + login: true, + } + ); + assert_eq!( + extract_shell_script(&["/bin/zsh".into(), "-c".into(), "echo hi".into()]).unwrap(), + ParsedShellCommand { + script: "echo hi".to_string(), + login: false, + } + ); +} + +#[test] +fn extract_shell_script_supports_wrapped_command_prefixes() { + assert_eq!( + extract_shell_script(&[ + "/usr/bin/env".into(), + "CODEX_EXECVE_WRAPPER=1".into(), + "/bin/zsh".into(), + "-lc".into(), + "echo hello".into() + ]) + .unwrap(), + ParsedShellCommand { + script: "echo hello".to_string(), + login: true, + } + ); + + assert_eq!( + extract_shell_script(&[ + "sandbox-exec".into(), + "-p".into(), + "sandbox_policy".into(), + "/bin/zsh".into(), + "-c".into(), + "pwd".into(), + ]) + .unwrap(), + ParsedShellCommand { + script: "pwd".to_string(), + login: false, + } + ); +} + +#[test] +fn extract_shell_script_rejects_unsupported_shell_invocation() { + let err = extract_shell_script(&[ + "sandbox-exec".into(), + "-fc".into(), + "echo not supported".into(), + ]) + .unwrap_err(); + assert!(matches!(err, super::ToolError::Rejected(_))); + assert_eq!( + match err { + super::ToolError::Rejected(reason) => reason, + _ => "".to_string(), + }, + "unexpected shell command format for zsh-fork execution" + ); +} + +#[test] +fn join_program_and_argv_replaces_original_argv_zero() { + assert_eq!( + join_program_and_argv( + &AbsolutePathBuf::from_absolute_path("/tmp/tool").unwrap(), + &["./tool".into(), "--flag".into(), "value".into()], + ), + vec!["/tmp/tool", "--flag", "value"] + ); + assert_eq!( + join_program_and_argv( + &AbsolutePathBuf::from_absolute_path("/tmp/tool").unwrap(), + &["./tool".into()] + ), + vec!["/tmp/tool"] + ); +} + +#[test] +fn commands_for_intercepted_exec_policy_parses_plain_shell_wrappers() { + let program = AbsolutePathBuf::try_from(host_absolute_path(&["bin", "bash"])).unwrap(); + let candidate_commands = commands_for_intercepted_exec_policy( + &program, + &["not-bash".into(), "-lc".into(), "git status && pwd".into()], + ); + + assert_eq!( + candidate_commands.commands, + vec![ + vec!["git".to_string(), "status".to_string()], + vec!["pwd".to_string()], + ] + ); + assert!(!candidate_commands.used_complex_parsing); +} + +#[test] +fn map_exec_result_preserves_stdout_and_stderr() { + let out = map_exec_result( + SandboxType::None, + ExecResult { + exit_code: 0, + stdout: "out".to_string(), + stderr: "err".to_string(), + output: "outerr".to_string(), + duration: Duration::from_millis(1), + timed_out: false, + }, + ) + .unwrap(); + + assert_eq!(out.stdout.text, "out"); + assert_eq!(out.stderr.text, "err"); + assert_eq!(out.aggregated_output.text, "outerr"); +} + +#[test] +fn shell_request_escalation_execution_is_explicit() { + let requested_permissions = PermissionProfile { + file_system: Some(FileSystemPermissions { + read: None, + write: Some(vec![ + AbsolutePathBuf::from_absolute_path("/tmp/output").unwrap(), + ]), + }), + ..Default::default() + }; + let sandbox_policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![AbsolutePathBuf::from_absolute_path("/tmp/original/output").unwrap()], + read_only_access: ReadOnlyAccess::FullAccess, + network_access: false, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }; + let macos_seatbelt_profile_extensions = MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + ..Default::default() + }; + + assert_eq!( + CoreShellActionProvider::shell_request_escalation_execution( + crate::sandboxing::SandboxPermissions::UseDefault, + &sandbox_policy, + None, + Some(&macos_seatbelt_profile_extensions), + ), + EscalationExecution::TurnDefault, + ); + assert_eq!( + CoreShellActionProvider::shell_request_escalation_execution( + crate::sandboxing::SandboxPermissions::RequireEscalated, + &sandbox_policy, + None, + Some(&macos_seatbelt_profile_extensions), + ), + EscalationExecution::Unsandboxed, + ); + assert_eq!( + CoreShellActionProvider::shell_request_escalation_execution( + crate::sandboxing::SandboxPermissions::WithAdditionalPermissions, + &sandbox_policy, + Some(&requested_permissions), + Some(&macos_seatbelt_profile_extensions), + ), + EscalationExecution::Permissions(EscalationPermissions::Permissions( + EscalatedPermissions { + sandbox_policy, + macos_seatbelt_profile_extensions: Some(macos_seatbelt_profile_extensions), + }, + )), + ); +} + +#[test] +fn evaluate_intercepted_exec_policy_uses_wrapper_command_when_shell_wrapper_parsing_disabled() { + let policy_src = r#"prefix_rule(pattern = ["npm", "publish"], decision = "prompt")"#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src).unwrap(); + let policy = parser.build(); + let program = AbsolutePathBuf::try_from(host_absolute_path(&["bin", "zsh"])).unwrap(); + + let enable_intercepted_exec_policy_shell_wrapper_parsing = false; + let evaluation = evaluate_intercepted_exec_policy( + &policy, + &program, + &[ + "zsh".to_string(), + "-lc".to_string(), + "npm publish".to_string(), + ], + AskForApproval::OnRequest, + &SandboxPolicy::new_read_only_policy(), + SandboxPermissions::UseDefault, + enable_intercepted_exec_policy_shell_wrapper_parsing, + ); + + assert!( + matches!( + evaluation.matched_rules.as_slice(), + [RuleMatch::HeuristicsRuleMatch { command, decision: Decision::Allow }] + if command == &vec![ + program.to_string_lossy().to_string(), + "-lc".to_string(), + "npm publish".to_string(), + ] + ), + r#"This is allowed because when shell wrapper parsing is disabled, +the policy evaluation does not try to parse the shell command and instead +matches the whole command line with the resolved program path, which in this +case is `/bin/zsh` followed by some arguments. + +Because there is no policy rule for `/bin/zsh` or `zsh`, the decision is to +allow the command and let the sandbox be responsible for enforcing any +restrictions. + +That said, if /bin/zsh is the zsh-fork, then the execve wrapper should +ultimately intercept the `npm publish` command and apply the policy rules to it. +"# + ); +} + +#[test] +fn evaluate_intercepted_exec_policy_matches_inner_shell_commands_when_enabled() { + let policy_src = r#"prefix_rule(pattern = ["npm", "publish"], decision = "prompt")"#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src).unwrap(); + let policy = parser.build(); + let program = AbsolutePathBuf::try_from(host_absolute_path(&["bin", "bash"])).unwrap(); + + let enable_intercepted_exec_policy_shell_wrapper_parsing = true; + let evaluation = evaluate_intercepted_exec_policy( + &policy, + &program, + &[ + "bash".to_string(), + "-lc".to_string(), + "npm publish".to_string(), + ], + AskForApproval::OnRequest, + &SandboxPolicy::new_read_only_policy(), + SandboxPermissions::UseDefault, + enable_intercepted_exec_policy_shell_wrapper_parsing, + ); + + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: vec!["npm".to_string(), "publish".to_string()], + decision: Decision::Prompt, + resolved_program: None, + justification: None, + }], + } + ); +} + +#[test] +fn intercepted_exec_policy_uses_host_executable_mappings() { + let git_path = host_absolute_path(&["usr", "bin", "git"]); + let git_path_literal = starlark_string(&git_path); + let policy_src = format!( + r#" +prefix_rule(pattern = ["git", "status"], decision = "prompt") +host_executable(name = "git", paths = ["{git_path_literal}"]) +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src).unwrap(); + let policy = parser.build(); + let program = AbsolutePathBuf::try_from(git_path).unwrap(); + + let evaluation = evaluate_intercepted_exec_policy( + &policy, + &program, + &["git".to_string(), "status".to_string()], + AskForApproval::OnRequest, + &SandboxPolicy::new_read_only_policy(), + SandboxPermissions::UseDefault, + false, + ); + + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: vec!["git".to_string(), "status".to_string()], + decision: Decision::Prompt, + resolved_program: Some(program), + justification: None, + }], + } + ); + assert!(CoreShellActionProvider::decision_driven_by_policy( + &evaluation.matched_rules, + evaluation.decision + )); +} + +#[test] +fn intercepted_exec_policy_rejects_disallowed_host_executable_mapping() { + let allowed_git = host_absolute_path(&["usr", "bin", "git"]); + let other_git = host_absolute_path(&["opt", "homebrew", "bin", "git"]); + let allowed_git_literal = starlark_string(&allowed_git); + let policy_src = format!( + r#" +prefix_rule(pattern = ["git", "status"], decision = "prompt") +host_executable(name = "git", paths = ["{allowed_git_literal}"]) +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src).unwrap(); + let policy = parser.build(); + let program = AbsolutePathBuf::try_from(other_git.clone()).unwrap(); + + let evaluation = evaluate_intercepted_exec_policy( + &policy, + &program, + &["git".to_string(), "status".to_string()], + AskForApproval::OnRequest, + &SandboxPolicy::new_read_only_policy(), + SandboxPermissions::UseDefault, + false, + ); + + assert!(matches!( + evaluation.matched_rules.as_slice(), + [RuleMatch::HeuristicsRuleMatch { command, .. }] + if command == &vec![other_git, "status".to_string()] + )); + assert!(!CoreShellActionProvider::decision_driven_by_policy( + &evaluation.matched_rules, + evaluation.decision + )); +} + +#[cfg(target_os = "macos")] +#[tokio::test] +async fn prepare_escalated_exec_turn_default_preserves_macos_seatbelt_extensions() { + let cwd = AbsolutePathBuf::from_absolute_path(std::env::temp_dir()).unwrap(); + let executor = CoreShellCommandExecutor { + command: vec!["echo".to_string(), "ok".to_string()], + cwd: cwd.to_path_buf(), + env: HashMap::new(), + network: None, + sandbox: SandboxType::None, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + windows_sandbox_level: WindowsSandboxLevel::Disabled, + sandbox_permissions: SandboxPermissions::UseDefault, + justification: None, + arg0: None, + sandbox_policy_cwd: cwd.to_path_buf(), + macos_seatbelt_profile_extensions: Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + ..Default::default() + }), + codex_linux_sandbox_exe: None, + use_linux_sandbox_bwrap: false, + }; + + let prepared = executor + .prepare_escalated_exec( + &AbsolutePathBuf::from_absolute_path("/bin/echo").unwrap(), + &["echo".to_string(), "ok".to_string()], + &cwd, + HashMap::new(), + EscalationExecution::TurnDefault, + ) + .await + .unwrap(); + + assert_eq!( + prepared.command.first().map(String::as_str), + Some(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + ); + assert_eq!(prepared.command.get(1).map(String::as_str), Some("-p")); + assert!( + prepared + .command + .get(2) + .is_some_and(|policy| policy.contains("(allow user-preference-write)")), + "expected seatbelt policy to include macOS extension profile: {:?}", + prepared.command + ); +} + +#[cfg(target_os = "macos")] +#[tokio::test] +async fn prepare_escalated_exec_permissions_preserve_macos_seatbelt_extensions() { + let cwd = AbsolutePathBuf::from_absolute_path(std::env::temp_dir()).unwrap(); + let executor = CoreShellCommandExecutor { + command: vec!["echo".to_string(), "ok".to_string()], + cwd: cwd.to_path_buf(), + env: HashMap::new(), + network: None, + sandbox: SandboxType::None, + sandbox_policy: SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + sandbox_permissions: SandboxPermissions::UseDefault, + justification: None, + arg0: None, + sandbox_policy_cwd: cwd.to_path_buf(), + macos_seatbelt_profile_extensions: None, + codex_linux_sandbox_exe: None, + use_linux_sandbox_bwrap: false, + }; + + let permissions = Permissions { + approval_policy: Constrained::allow_any(AskForApproval::Never), + sandbox_policy: Constrained::allow_any(SandboxPolicy::new_read_only_policy()), + network: None, + allow_login_shell: true, + shell_environment_policy: ShellEnvironmentPolicy::default(), + windows_sandbox_mode: None, + macos_seatbelt_profile_extensions: Some(MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + ..Default::default() + }), + }; + + let prepared = executor + .prepare_escalated_exec( + &AbsolutePathBuf::from_absolute_path("/bin/echo").unwrap(), + &["echo".to_string(), "ok".to_string()], + &cwd, + HashMap::new(), + EscalationExecution::Permissions(EscalationPermissions::Permissions( + EscalatedPermissions { + sandbox_policy: permissions.sandbox_policy.get().clone(), + macos_seatbelt_profile_extensions: permissions + .macos_seatbelt_profile_extensions + .clone(), + }, + )), + ) + .await + .unwrap(); + + assert_eq!( + prepared.command.first().map(String::as_str), + Some(MACOS_PATH_TO_SEATBELT_EXECUTABLE) + ); + assert_eq!(prepared.command.get(1).map(String::as_str), Some("-p")); + assert!( + prepared + .command + .get(2) + .is_some_and(|policy| policy.contains("(allow user-preference-write)")), + "expected seatbelt policy to include macOS extension profile: {:?}", + prepared.command + ); +} diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 4b0c53d123..f4d823bf0e 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -111,6 +111,7 @@ impl Approvable for UnifiedExecRuntime<'_> { .or_else(|| req.justification.clone()); Box::pin(async move { with_cached_approval(&session.services, "unified_exec", keys, || async move { + let available_decisions = None; session .request_command_approval( turn, @@ -124,6 +125,7 @@ impl Approvable for UnifiedExecRuntime<'_> { .proposed_execpolicy_amendment() .cloned(), req.additional_permissions.clone(), + available_decisions, ) .await }) diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 25ea101592..28d87b5bf3 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -340,6 +340,8 @@ impl<'a> SandboxAttempt<'a> { enforce_managed_network: self.enforce_managed_network, network, sandbox_policy_cwd: self.sandbox_cwd, + #[cfg(target_os = "macos")] + macos_seatbelt_profile_extensions: None, codex_linux_sandbox_exe: self.codex_linux_sandbox_exe, use_linux_sandbox_bwrap: self.use_linux_sandbox_bwrap, windows_sandbox_level: self.windows_sandbox_level, diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 0f50cf8735..0e53670750 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -6,6 +6,7 @@ use crate::config::AgentRoleConfig; use crate::features::Feature; use crate::features::Features; use crate::mcp_connection_manager::ToolInfo; +use crate::models_manager::collaboration_mode_presets::CollaborationModesConfig; use crate::tools::handlers::PLAN_TOOL; use crate::tools::handlers::SEARCH_TOOL_BM25_DEFAULT_LIMIT; use crate::tools::handlers::SEARCH_TOOL_BM25_TOOL_NAME; @@ -54,7 +55,8 @@ pub(crate) struct ToolsConfig { pub js_repl_enabled: bool, pub js_repl_tools_only: bool, pub collab_tools: bool, - pub collaboration_modes_tools: bool, + pub artifact_tools: bool, + pub default_mode_request_user_input: bool, pub experimental_supported_tools: Vec, pub agent_jobs_tools: bool, pub agent_jobs_worker_tools: bool, @@ -80,8 +82,10 @@ impl ToolsConfig { let include_js_repl_tools_only = include_js_repl && features.enabled(Feature::JsReplToolsOnly); let include_collab_tools = features.enabled(Feature::Collab); - let include_collaboration_modes_tools = features.enabled(Feature::CollaborationModes); + let include_default_mode_request_user_input = + features.enabled(Feature::DefaultModeRequestUserInput); let include_search_tool = features.enabled(Feature::Apps); + let include_artifact_tools = features.enabled(Feature::Artifact); let include_agent_jobs = include_collab_tools && features.enabled(Feature::Sqlite); let request_permission_enabled = features.enabled(Feature::RequestPermissions); let shell_command_backend = @@ -137,7 +141,8 @@ impl ToolsConfig { js_repl_enabled: include_js_repl, js_repl_tools_only: include_js_repl_tools_only, collab_tools: include_collab_tools, - collaboration_modes_tools: include_collaboration_modes_tools, + artifact_tools: include_artifact_tools, + default_mode_request_user_input: include_default_mode_request_user_input, experimental_supported_tools: model_info.experimental_supported_tools.clone(), agent_jobs_tools: include_agent_jobs, agent_jobs_worker_tools, @@ -559,6 +564,97 @@ fn create_view_image_tool() -> ToolSpec { }) } +fn create_presentation_artifact_tool() -> ToolSpec { + let action_step_schema = JsonSchema::Object { + properties: BTreeMap::from([ + ( + "action".to_string(), + JsonSchema::String { + description: Some("Action name to run for this step.".to_string()), + }, + ), + ( + "args".to_string(), + JsonSchema::Object { + properties: BTreeMap::new(), + required: None, + additional_properties: Some(true.into()), + }, + ), + ]), + required: Some(vec!["action".to_string(), "args".to_string()]), + additional_properties: Some(false.into()), + }; + let properties = BTreeMap::from([ + ( + "artifact_id".to_string(), + JsonSchema::String { + description: Some( + "Artifact id returned by an earlier presentation_artifact call.".to_string(), + ), + }, + ), + ( + "actions".to_string(), + JsonSchema::Array { + items: Box::new(action_step_schema), + description: Some( + "Array of `(action, args)` steps to execute sequentially.".to_string(), + ), + }, + ), + ]); + + ToolSpec::Function(ResponsesApiTool { + name: "presentation_artifact".to_string(), + description: "Create or edit a presentation artifact for the current thread.".to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["actions".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_spreadsheet_artifact_tool() -> ToolSpec { + let properties = BTreeMap::from([ + ( + "artifact_id".to_string(), + JsonSchema::String { + description: Some( + "Artifact id returned by an earlier spreadsheet_artifact call.".to_string(), + ), + }, + ), + ( + "action".to_string(), + JsonSchema::String { + description: Some("Action name to run for this request.".to_string()), + }, + ), + ( + "args".to_string(), + JsonSchema::Object { + properties: BTreeMap::new(), + required: None, + additional_properties: Some(true.into()), + }, + ), + ]); + + ToolSpec::Function(ResponsesApiTool { + name: "spreadsheet_artifact".to_string(), + description: "Create or edit a spreadsheet artifact for the current thread.".to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["action".to_string(), "args".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + fn create_collab_input_items_schema() -> JsonSchema { let properties = BTreeMap::from([ ( @@ -631,6 +727,15 @@ fn create_spawn_agent_tool(config: &ToolsConfig) -> ToolSpec { )), }, ), + ( + "fork_context".to_string(), + JsonSchema::Boolean { + description: Some( + "When true, fork the current thread history into the new agent before sending the initial prompt. This must be used when you want the new agent to have exactly the same context as you." + .to_string(), + ), + }, + ), ]); ToolSpec::Function(ResponsesApiTool { @@ -872,7 +977,9 @@ fn create_wait_tool() -> ToolSpec { }) } -fn create_request_user_input_tool() -> ToolSpec { +fn create_request_user_input_tool( + collaboration_modes_config: CollaborationModesConfig, +) -> ToolSpec { let mut option_props = BTreeMap::new(); option_props.insert( "label".to_string(), @@ -943,7 +1050,9 @@ fn create_request_user_input_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "request_user_input".to_string(), - description: request_user_input_tool_description(), + description: request_user_input_tool_description( + collaboration_modes_config.default_mode_request_user_input, + ), strict: false, parameters: JsonSchema::Object { properties, @@ -1643,11 +1752,13 @@ pub(crate) fn build_specs( use crate::tools::handlers::McpResourceHandler; use crate::tools::handlers::MultiAgentHandler; use crate::tools::handlers::PlanHandler; + use crate::tools::handlers::PresentationArtifactHandler; use crate::tools::handlers::ReadFileHandler; use crate::tools::handlers::RequestUserInputHandler; use crate::tools::handlers::SearchToolBm25Handler; use crate::tools::handlers::ShellCommandHandler; use crate::tools::handlers::ShellHandler; + use crate::tools::handlers::SpreadsheetArtifactHandler; use crate::tools::handlers::TestSyncHandler; use crate::tools::handlers::UnifiedExecHandler; use crate::tools::handlers::ViewImageHandler; @@ -1664,10 +1775,14 @@ pub(crate) fn build_specs( let mcp_handler = Arc::new(McpHandler); let mcp_resource_handler = Arc::new(McpResourceHandler); let shell_command_handler = Arc::new(ShellCommandHandler::from(config.shell_command_backend)); - let request_user_input_handler = Arc::new(RequestUserInputHandler); + let request_user_input_handler = Arc::new(RequestUserInputHandler { + default_mode_request_user_input: config.default_mode_request_user_input, + }); let search_tool_handler = Arc::new(SearchToolBm25Handler); let js_repl_handler = Arc::new(JsReplHandler); let js_repl_reset_handler = Arc::new(JsReplResetHandler); + let presentation_artifact_handler = Arc::new(PresentationArtifactHandler); + let spreadsheet_artifact_handler = Arc::new(SpreadsheetArtifactHandler); let request_permission_enabled = config.request_permission_enabled; match &config.shell_type { @@ -1727,10 +1842,10 @@ pub(crate) fn build_specs( builder.register_handler("js_repl_reset", js_repl_reset_handler); } - if config.collaboration_modes_tools { - builder.push_spec(create_request_user_input_tool()); - builder.register_handler("request_user_input", request_user_input_handler); - } + builder.push_spec(create_request_user_input_tool(CollaborationModesConfig { + default_mode_request_user_input: config.default_mode_request_user_input, + })); + builder.register_handler("request_user_input", request_user_input_handler); if config.search_tool && let Some(app_tools) = app_tools @@ -1805,6 +1920,13 @@ pub(crate) fn build_specs( builder.push_spec_with_parallel_support(create_view_image_tool(), true); builder.register_handler("view_image", view_image_handler); + if config.artifact_tools { + builder.push_spec(create_presentation_artifact_tool()); + builder.push_spec(create_spreadsheet_artifact_tool()); + builder.register_handler("presentation_artifact", presentation_artifact_handler); + builder.register_handler("spreadsheet_artifact", spreadsheet_artifact_handler); + } + if config.collab_tools { let multi_agent_handler = Arc::new(MultiAgentHandler); builder.push_spec(create_spawn_agent_tool(config)); @@ -2024,7 +2146,6 @@ mod tests { let model_info = model_info_from_models_json("gpt-5-codex"); let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); - features.enable(Feature::CollaborationModes); let config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, @@ -2055,7 +2176,7 @@ mod tests { create_exec_command_tool(true, false), create_write_stdin_tool(), PLAN_TOOL.clone(), - create_request_user_input_tool(), + create_request_user_input_tool(CollaborationModesConfig::default()), create_apply_patch_freeform_tool(), ToolSpec::WebSearch { external_web_access: Some(true), @@ -2087,8 +2208,6 @@ mod tests { ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::Collab); - features.enable(Feature::CollaborationModes); - features.enable(Feature::Sqlite); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, @@ -2108,6 +2227,23 @@ mod tests { ); } + #[test] + fn test_build_specs_artifact_tool_enabled() { + let config = test_config(); + let model_info = + ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); + let mut features = Features::with_defaults(); + features.enable(Feature::Artifact); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + }); + let (tools, _) = build_specs(&tools_config, None, None, &[]).build(); + assert_contains_tool_names(&tools, &["presentation_artifact", "spreadsheet_artifact"]); + } + #[test] fn test_build_specs_agent_job_worker_tools_enabled() { let config = test_config(); @@ -2115,7 +2251,6 @@ mod tests { ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); let mut features = Features::with_defaults(); features.enable(Feature::Collab); - features.enable(Feature::CollaborationModes); features.enable(Feature::Sqlite); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, @@ -2141,12 +2276,11 @@ mod tests { } #[test] - fn request_user_input_requires_collaboration_modes_feature() { + fn request_user_input_description_reflects_default_mode_feature_flag() { let config = test_config(); let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); let mut features = Features::with_defaults(); - features.disable(Feature::CollaborationModes); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, @@ -2154,12 +2288,13 @@ mod tests { session_source: SessionSource::Cli, }); let (tools, _) = build_specs(&tools_config, None, None, &[]).build(); - assert!( - !tools.iter().any(|t| t.spec.name() == "request_user_input"), - "request_user_input should be disabled when collaboration_modes feature is off" + let request_user_input_tool = find_tool(&tools, "request_user_input"); + assert_eq!( + request_user_input_tool.spec, + create_request_user_input_tool(CollaborationModesConfig::default()) ); - features.enable(Feature::CollaborationModes); + features.enable(Feature::DefaultModeRequestUserInput); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, @@ -2167,7 +2302,13 @@ mod tests { session_source: SessionSource::Cli, }); let (tools, _) = build_specs(&tools_config, None, None, &[]).build(); - assert_contains_tool_names(&tools, &["request_user_input"]); + let request_user_input_tool = find_tool(&tools, "request_user_input"); + assert_eq!( + request_user_input_tool.spec, + create_request_user_input_tool(CollaborationModesConfig { + default_mode_request_user_input: true, + }) + ); } #[test] @@ -2335,8 +2476,7 @@ mod tests { let config = test_config(); let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, @@ -2359,8 +2499,7 @@ mod tests { let config = test_config(); let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_info: &model_info, features: &features, @@ -2381,8 +2520,7 @@ mod tests { #[test] fn test_build_specs_gpt5_codex_default() { - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); assert_default_model_tools( "gpt-5-codex", &features, @@ -2400,8 +2538,7 @@ mod tests { #[test] fn test_build_specs_gpt51_codex_default() { - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); assert_default_model_tools( "gpt-5.1-codex", &features, @@ -2421,7 +2558,6 @@ mod tests { fn test_build_specs_gpt5_codex_unified_exec_web_search() { let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); - features.enable(Feature::CollaborationModes); assert_model_tools( "gpt-5-codex", &features, @@ -2442,7 +2578,6 @@ mod tests { fn test_build_specs_gpt51_codex_unified_exec_web_search() { let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); - features.enable(Feature::CollaborationModes); assert_model_tools( "gpt-5.1-codex", &features, @@ -2461,8 +2596,7 @@ mod tests { #[test] fn test_gpt_5_1_codex_max_defaults() { - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); assert_default_model_tools( "gpt-5.1-codex-max", &features, @@ -2480,8 +2614,7 @@ mod tests { #[test] fn test_codex_5_1_mini_defaults() { - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); assert_default_model_tools( "gpt-5.1-codex-mini", &features, @@ -2499,8 +2632,7 @@ mod tests { #[test] fn test_gpt_5_defaults() { - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); assert_default_model_tools( "gpt-5", &features, @@ -2517,8 +2649,7 @@ mod tests { #[test] fn test_gpt_5_1_defaults() { - let mut features = Features::with_defaults(); - features.enable(Feature::CollaborationModes); + let features = Features::with_defaults(); assert_default_model_tools( "gpt-5.1", &features, @@ -2538,7 +2669,6 @@ mod tests { fn test_gpt_5_1_codex_max_unified_exec_web_search() { let mut features = Features::with_defaults(); features.enable(Feature::UnifiedExec); - features.enable(Feature::CollaborationModes); assert_model_tools( "gpt-5.1-codex-max", &features, diff --git a/codex-rs/core/src/user_shell_command.rs b/codex-rs/core/src/user_shell_command.rs index 80128df006..e7921c69f3 100644 --- a/codex-rs/core/src/user_shell_command.rs +++ b/codex-rs/core/src/user_shell_command.rs @@ -1,21 +1,12 @@ use std::time::Duration; -use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; use crate::codex::TurnContext; +use crate::contextual_user_message::USER_SHELL_COMMAND_FRAGMENT; use crate::exec::ExecToolCallOutput; use crate::tools::format_exec_output_str; -pub const USER_SHELL_COMMAND_OPEN: &str = ""; -pub const USER_SHELL_COMMAND_CLOSE: &str = ""; - -pub fn is_user_shell_command_text(text: &str) -> bool { - let trimmed = text.trim_start(); - let lowered = trimmed.to_ascii_lowercase(); - lowered.starts_with(USER_SHELL_COMMAND_OPEN) -} - fn format_duration_line(duration: Duration) -> String { let duration_seconds = duration.as_secs_f64(); format!("Duration: {duration_seconds:.4} seconds") @@ -48,7 +39,7 @@ pub fn format_user_shell_command_record( turn_context: &TurnContext, ) -> String { let body = format_user_shell_command_body(command, exec_output, turn_context); - format!("{USER_SHELL_COMMAND_OPEN}\n{body}\n{USER_SHELL_COMMAND_CLOSE}") + USER_SHELL_COMMAND_FRAGMENT.wrap(body) } pub fn user_shell_command_record_item( @@ -56,15 +47,11 @@ pub fn user_shell_command_record_item( exec_output: &ExecToolCallOutput, turn_context: &TurnContext, ) -> ResponseItem { - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: format_user_shell_command_record(command, exec_output, turn_context), - }], - end_turn: None, - phase: None, - } + USER_SHELL_COMMAND_FRAGMENT.into_message(format_user_shell_command_record( + command, + exec_output, + turn_context, + )) } #[cfg(test)] @@ -72,14 +59,16 @@ mod tests { use super::*; use crate::codex::make_session_and_context; use crate::exec::StreamOutput; + use codex_protocol::models::ContentItem; use pretty_assertions::assert_eq; #[test] fn detects_user_shell_command_text_variants() { - assert!(is_user_shell_command_text( - "\necho hi\n" - )); - assert!(!is_user_shell_command_text("echo hi")); + assert!( + USER_SHELL_COMMAND_FRAGMENT + .matches_text("\necho hi\n") + ); + assert!(!USER_SHELL_COMMAND_FRAGMENT.matches_text("echo hi")); } #[tokio::test] diff --git a/codex-rs/core/templates/collaboration_mode/default.md b/codex-rs/core/templates/collaboration_mode/default.md index 4efd963ba0..ff00857c6d 100644 --- a/codex-rs/core/templates/collaboration_mode/default.md +++ b/codex-rs/core/templates/collaboration_mode/default.md @@ -8,4 +8,4 @@ Your active mode changes only when new developer instructions with a different ` {{REQUEST_USER_INPUT_AVAILABILITY}} -If a decision is necessary and cannot be discovered from local context, ask the user directly. However, in Default mode you should strongly prefer executing the user's request rather than stopping to ask questions. +{{ASKING_QUESTIONS_GUIDANCE}} diff --git a/codex-rs/core/templates/collaboration_mode/plan.md b/codex-rs/core/templates/collaboration_mode/plan.md index 5c58310ae4..8a1a934f83 100644 --- a/codex-rs/core/templates/collaboration_mode/plan.md +++ b/codex-rs/core/templates/collaboration_mode/plan.md @@ -107,7 +107,7 @@ Example: plan content -plan content should be human and agent digestible. The final plan must be plan-only and include: +plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include: * A clear title * A brief summary section @@ -115,6 +115,12 @@ plan content should be human and agent digestible. The final plan must be plan-o * Test cases and scenarios * Explicit assumptions and defaults chosen where needed +When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes. + +Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes. + +Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand. + Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. Only produce at most one `` block per turn, and only when you are presenting a complete spec. diff --git a/codex-rs/core/templates/memories/consolidation.md b/codex-rs/core/templates/memories/consolidation.md index b880bdfd65..085895a69f 100644 --- a/codex-rs/core/templates/memories/consolidation.md +++ b/codex-rs/core/templates/memories/consolidation.md @@ -106,7 +106,7 @@ Under `{{ memory_root }}/`: context. - source of rollout-level metadata needed for MEMORY.md `### rollout_summary_files` annotations; - you should be able to find `cwd` and `updated_at` there. + you should be able to find `cwd`, `rollout_path`, and `updated_at` there. - `MEMORY.md` - merged memories; produce a lightly clustered version if applicable - `rollout_summaries/*.md` @@ -121,6 +121,27 @@ Mode selection: - INCREMENTAL UPDATE: existing artifacts already exist and `raw_memories.md` mostly contains new additions. +Incremental thread diff snapshot (computed before the current artifact sync rewrites local files): + +**Diff since last consolidation:** +{{ phase2_input_selection }} + +Incremental update and forgetting mechanism: +- Use the diff provided +- Do not open raw sessions / original rollout transcripts. +- For each added thread id, search it in `raw_memories.md`, read that raw-memory section, and + read the corresponding `rollout_summaries/*.md` file only when needed for stronger evidence, + task placement, or conflict resolution. +- For each removed thread id, search it in `MEMORY.md` and delete only the memory supported by + that thread. Use `thread_id=` in `### rollout_summary_files` when available; if not, + fall back to rollout summary filenames plus the corresponding `rollout_summaries/*.md` files. +- If a `MEMORY.md` block contains both removed and undeleted threads, do not delete the whole + block. Remove only the removed thread's references and thread-local learnings, preserve shared + or still-supported content, and split or rewrite the block only if needed to keep the undeleted + threads intact. +- After `MEMORY.md` cleanup is done, revisit `memory_summary.md` and remove or rewrite stale + summary/index content that was only supported by removed thread ids. + Outputs: Under `{{ memory_root }}/`: A) `MEMORY.md` @@ -171,7 +192,7 @@ Required task-oriented body shape (strict): ## Task 1: ### rollout_summary_files -- (cwd=, updated_at=, thread_id=, ) +- (cwd=, rollout_path=, updated_at=, thread_id=, ) ### keywords @@ -236,7 +257,8 @@ Schema rules (strict): - Every `## Task ` section must include `### rollout_summary_files`, `### keywords`, and `### learnings`. - `### rollout_summary_files` must be task-local (not a block-wide catch-all list). - - Each rollout annotation must include `cwd=` and `updated_at=`. + - Each rollout annotation must include `cwd=`, `rollout_path=`, and + `updated_at=`. If missing from a rollout summary, recover them from `raw_memories.md`. - Major learnings should be traceable to rollout summaries listed in the same task section. - Order rollout references by freshness and practical usefulness. @@ -497,27 +519,42 @@ WORKFLOW conflicting task families until MEMORY blocks are richer and more useful than raw memories 3) INCREMENTAL UPDATE behavior: - - Treat `raw_memories.md` as the primary source of NEW signal. - - Read existing memory files first for continuity. + - Read existing `MEMORY.md` and `memory_summary.md` first for continuity and to locate + existing references that may need surgical cleanup. + - Use the injected thread-diff snapshot as the first routing pass: + - added thread ids = ingestion queue + - removed thread ids = forgetting / stale-cleanup queue - Build an index of rollout references already present in existing `MEMORY.md` before scanning raw memories so you can route net-new evidence into the right blocks. - - Compute net-new candidates from the raw-memory inventory (threads / rollout summaries / - updated evidence not already represented in `MEMORY.md`). + - Work in this order: + 1. For newly added thread ids, search them in `raw_memories.md`, read those sections, and + open the corresponding `rollout_summaries/*.md` files when necessary. + 2. Route the new signal into existing `MEMORY.md` blocks or create new ones when needed. + 3. For removed thread ids, search `MEMORY.md` and surgically delete or rewrite only the + unsupported thread-local memory. + 4. If a block mixes removed and undeleted threads, preserve the undeleted-thread content; + split or rewrite the block if that is the cleanest way to delete only the removed part. + 5. After `MEMORY.md` is correct, revisit `memory_summary.md` and remove or rewrite stale + summary/index content that no longer has undeleted support. - Integrate new signal into existing artifacts by: - - scanning new raw memories in recency order and identifying which existing blocks they should update + - scanning the newly added raw-memory entries in recency order and identifying which existing blocks they should update - updating existing knowledge with better/newer evidence - updating stale or contradicting guidance + - pruning or downgrading memory whose only provenance comes from removed thread ids - expanding terse old blocks when new summaries/raw memories make the task family clearer - doing light clustering and merging if needed - refreshing `MEMORY.md` top-of-file ordering so recent high-utility task families stay easy to find - rebuilding the `memory_summary.md` recent active window (last 3 memory days) from current `updated_at` coverage - updating existing skills or adding new skills only when there is clear new reusable procedure - - update `memory_summary.md` last to reflect the final state of the memory folder + - updating `memory_summary.md` last to reflect the final state of the memory folder - Minimize churn in incremental mode: if an existing `MEMORY.md` block or `## What's in Memory` topic still reflects the current evidence and points to the same task family / retrieval target, keep its wording, label, and relative order mostly stable. Rewrite/reorder/rename/ split/merge only when fixing a real problem (staleness, ambiguity, schema drift, wrong boundaries) or when meaningful new evidence materially improves retrieval clarity/searchability. + - Spend most of your deep-dive budget on newly added thread ids and on mixed blocks touched by + removed thread ids. Do not re-read unchanged older threads unless you need them for + conflict resolution, clustering, or provenance repair. 4) Evidence deep-dive rule (both modes): - `raw_memories.md` is the routing layer, not always the final authority for detail. @@ -528,6 +565,9 @@ WORKFLOW - When a task family is important, ambiguous, or duplicated across multiple rollouts, open the relevant `rollout_summaries/*.md` files and extract richer procedural detail, validation signals, and user feedback before finalizing `MEMORY.md`. + - When deleting stale memory from a mixed block, use the relevant rollout summaries to decide + which details are uniquely supported by removed threads versus still supported by undeleted + threads. - Use `updated_at` and validation strength together to resolve stale/conflicting notes. 5) For both modes, update `MEMORY.md` after skill updates: @@ -541,6 +581,8 @@ WORKFLOW 7) Final pass: - remove duplication in memory_summary, skills/, and MEMORY.md - remove stale or low-signal blocks that are less likely to be useful in the future + - remove or rewrite blocks/task sections whose supporting rollout references point only to + removed thread ids or missing rollout summary files - run a global rollout-reference audit on final `MEMORY.md` and fix accidental duplicate entries / redundant repetition, while preserving intentional multi-task or multi-block reuse when it adds distinct task-local value @@ -559,16 +601,3 @@ WORKFLOW You should dive deep and make sure you didn't miss any important information that might be useful for future agents; do not be superficial. - -============================================================ -SEARCH / REVIEW COMMANDS (RG-FIRST) -============================================================ - -Use `rg` for fast retrieval while consolidating: - -- Search durable notes: - `rg -n -i "" "{{ memory_root }}/MEMORY.md"` -- Search across memory tree: - `rg -n -i "" "{{ memory_root }}" | head -n 100` -- Locate rollout summary files: - `rg --files "{{ memory_root }}/rollout_summaries" | head -n 400` diff --git a/codex-rs/core/templates/memories/read_path.md b/codex-rs/core/templates/memories/read_path.md index 59159b2ecc..b80cc6d13b 100644 --- a/codex-rs/core/templates/memories/read_path.md +++ b/codex-rs/core/templates/memories/read_path.md @@ -25,7 +25,10 @@ Memory layout (general -> specific): - scripts/ (optional helper scripts) - examples/ (optional example outputs) - templates/ (optional templates) -- {{ base_path }}/rollout_summaries/ (per-rollout recaps + evidence snippets) + - {{ base_path }}/rollout_summaries/ (per-rollout recaps + evidence snippets) + - The paths of these entries can be found in {{ base_path }}/MEMORY.md or {{ base_path }}/rollout_summaries/ as `rollout_path` + - These files are append-only `jsonl`: `session_meta.payload.id` identifies the session, `turn_context` marks turn boundaries, `event_msg` is the lightweight status stream, and `response_item` contains actual messages, tool calls, and tool outputs. + - For efficient lookup, prefer matching the filename suffix or `session_meta.payload.id`; avoid broad full-content scans unless needed. Quick memory pass (when applicable): @@ -34,7 +37,8 @@ Quick memory pass (when applicable): 3. Only if MEMORY.md directly points to rollout summaries/skills, open the 1-2 most relevant files under {{ base_path }}/rollout_summaries/ or {{ base_path }}/skills/. -4. If there are no relevant hits, stop memory lookup and continue normally. +4. If above are not clear and you need exact commands, error text, or precise evidence, search over `rollout_path` for more evidence. +5. If there are no relevant hits, stop memory lookup and continue normally. Quick-pass budget: @@ -44,13 +48,75 @@ Quick-pass budget: During execution: if you hit repeated errors, confusing behavior, or suspect relevant prior context, redo the quick memory pass. -When to update memory: +How to decide whether to verify memory: + +- Consider both risk of drift and verification effort. +- If a fact is likely to drift and is cheap to verify, verify it before + answering. +- If a fact is likely to drift but verification is expensive, slow, or + disruptive, it is acceptable to answer from memory in an interactive turn, + but you should say that it is memory-derived, note that it may be stale, and + consider offering to refresh it live. +- If a fact is lower-drift and cheap to verify, use judgment: verification is + more important when the fact is central to the answer or especially easy to + confirm. +- If a fact is lower-drift and expensive to verify, it is usually fine to + answer from memory directly. + +When answering from memory without current verification: + +- If you rely on memory for a fact that you did not verify in the current turn, + say so briefly in the final answer. +- If that fact is plausibly drift-prone or comes from an older note, older + snapshot, or prior run summary, say that it may be stale or outdated. +- If live verification was skipped and a refresh would be useful in the + interactive context, consider offering to verify or refresh it live. +- Do not present unverified memory-derived facts as confirmed-current. +- For interactive requests, prefer a short refresh offer over silently doing + expensive verification that the user did not ask for. +- When the unverified fact is about prior results, commands, timing, or an + older snapshot, a concrete refresh offer can be especially helpful. + +When to update memory (automatic, same turn; required): - Treat memory as guidance, not truth: if memory conflicts with current repo state, tool outputs, environment, or user feedback, current evidence wins. -- If you discover stale/misleading memory, update memory files accordingly. -- When user explicitly asks to remember/update memory, revise memory_summary.md - and/or MEMORY.md. +- Memory is writable. You are authorized to edit {{ base_path }}/MEMORY.md and + {{ base_path }}/memory_summary.md when stale guidance is detected. +- If any memory fact conflicts with current evidence (repo state, tool output, + or user correction), you MUST update memory in the same turn. Do not wait for + a separate user prompt. +- If you detect stale memory, updating MEMORY.md is part of task completion, + not optional cleanup. +- A final answer without the required MEMORY.md edit is incorrect. +- A memory entry can be partially stale: if the broad guidance is still useful + but a stored detail is outdated (for example line numbers, exact paths, exact + commands, or exact model/version strings), you should keep using current + evidence in your answer and update the stale detail in MEMORY.md. +- Correcting only the answer is not enough when you have identified a stale + stored detail in memory. +- If memory contains a broad point that is still right but any concrete stored + detail is wrong or outdated, the memory is stale and MEMORY.md should be + corrected in the same turn after you verify the replacement. +- Required behavior after detecting stale memory: + 1. Verify the correct replacement using local evidence. + 2. Continue the task using current evidence; do not rely on stale memory. + 3. Edit memory files later in the same turn, before your final response: + - Always update {{ base_path }}/MEMORY.md. + - Update {{ base_path }}/memory_summary.md only if the correction affects + reusable guidance and you have complete local file context for a + targeted edit. + 4. Read back the changed MEMORY.md lines to confirm the update. + 5. Finalize the task after the memory updates are written. +- Do not finish the turn until the stale memory is corrected or you have + determined the correction is ambiguous. +- If you verified a contradiction and did not edit MEMORY.md, the task is + incomplete. +- Only ask a clarifying question instead of editing when the replacement is + ambiguous (multiple plausible targets with low confidence and no single + verified replacement from local evidence). +- When user explicitly asks to remember something or update the memory, revise + the files accordingly. Memory citation requirements: diff --git a/codex-rs/core/templates/tools/presentation_artifact.md b/codex-rs/core/templates/tools/presentation_artifact.md new file mode 100644 index 0000000000..45a91bc43b --- /dev/null +++ b/codex-rs/core/templates/tools/presentation_artifact.md @@ -0,0 +1,200 @@ +Create and edit PowerPoint presentation artifacts inside the current thread. + +- This is a stateful built-in tool. `artifact_id` values are returned by earlier calls and persist only for the current thread. +- Resume and fork do not restore live artifact state. Export files if you need a durable handoff. +- Relative paths resolve from the current working directory. +- Position and size values are in slide points. +- Every tool call uses a top-level `actions` array of sequential steps. Each call operates on a single top-level `artifact_id` when one is needed. If a call starts with `create` or `import_pptx`, later steps in the same call automatically reuse the returned artifact id. + +Supported actions: +- `create` +- `import_pptx` +- `export_pptx` +- `export_preview` +- `get_summary` +- `list_slides` +- `list_layouts` +- `list_layout_placeholders` +- `list_slide_placeholders` +- `inspect` +- `resolve` +- `to_proto` +- `record_patch` +- `apply_patch` +- `undo` +- `redo` +- `create_layout` +- `add_layout_placeholder` +- `set_slide_layout` +- `update_placeholder_text` +- `set_theme` +- `add_style` +- `get_style` +- `describe_styles` +- `set_notes` +- `set_notes_rich_text` +- `append_notes` +- `clear_notes` +- `set_notes_visibility` +- `set_active_slide` +- `add_slide` +- `insert_slide` +- `duplicate_slide` +- `move_slide` +- `delete_slide` +- `set_slide_background` +- `add_text_shape` +- `add_shape` +- `add_connector` +- `add_image` +- `replace_image` +- `add_table` +- `update_table_style` +- `style_table_block` +- `update_table_cell` +- `merge_table_cells` +- `add_chart` +- `update_chart` +- `add_chart_series` +- `update_text` +- `set_rich_text` +- `format_text_range` +- `replace_text` +- `insert_text_after` +- `set_hyperlink` +- `set_comment_author` +- `add_comment_thread` +- `add_comment_reply` +- `toggle_comment_reaction` +- `resolve_comment_thread` +- `reopen_comment_thread` +- `update_shape_style` +- `bring_to_front` +- `send_to_back` +- `delete_element` +- `delete_artifact` + +Example create: +`{"actions":[{"action":"create","args":{"name":"Quarterly Update"}}]}` + +Example create with custom slide size: +`{"actions":[{"action":"create","args":{"name":"Quarterly Update","slide_size":{"width":960,"height":540}}}]}` + +Example edit: +`{"artifact_id":"presentation_x","actions":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Revenue up 24%","position":{"left":48,"top":72,"width":260,"height":80}}}]}` + +Example sequential batch: +`{"actions":[{"action":"create","args":{"name":"Quarterly Update"}},{"action":"add_slide","args":{}},{"action":"add_text_shape","args":{"slide_index":0,"text":"Revenue up 24%","position":{"left":48,"top":72,"width":260,"height":80}}}]}` + +Table creation also accepts optional `column_widths` and `row_heights` arrays in points when you need explicit table sizing instead of even splits. Tables also support `style_options`, `borders`, and `right_to_left`, with `update_table_style` and `style_table_block` available for incremental styling after creation. + +Example export: +`{"artifact_id":"presentation_x","actions":[{"action":"export_pptx","args":{"path":"artifacts/q2-update.pptx"}}]}` + +Example layout flow: +`{"artifact_id":"presentation_x","actions":[{"action":"create_layout","args":{"name":"Title Slide"}}]}` + +`{"artifact_id":"presentation_x","actions":[{"action":"add_layout_placeholder","args":{"layout_id":"layout_1","name":"title","placeholder_type":"title","text":"Click to add title","position":{"left":48,"top":48,"width":624,"height":72}}}]}` + +`{"artifact_id":"presentation_x","actions":[{"action":"set_slide_layout","args":{"slide_index":0,"layout_id":"layout_1"}}]}` + +`{"artifact_id":"presentation_x","actions":[{"action":"list_layout_placeholders","args":{"layout_id":"layout_1"}}]}` + +`{"artifact_id":"presentation_x","actions":[{"action":"list_slide_placeholders","args":{"slide_index":0}}]}` + +Layout references in `create_layout.parent_layout_id`, `add_layout_placeholder.layout_id`, `add_slide`, `insert_slide`, `set_slide_layout`, and `list_layout_placeholders` accept either a layout id or a layout name. Name matching prefers exact id, then exact name, then case-insensitive name. + +`insert_slide` accepts `index` or `after_slide_index`. If neither is provided, the new slide is inserted immediately after the active slide, or appended if no active slide is set yet. + +Example inspect: +`{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"deck,slide,textbox,shape,table,chart,image,notes,layoutList,textRange,comment","exclude":"notes","search":"roadmap","max_chars":12000}}]}` + +Example inspect target window: +`{"artifact_id":"presentation_x","actions":[{"action":"inspect","args":{"include":"textbox","target":{"id":"sh/element_3","before_lines":1,"after_lines":1}}}]}` + +Example resolve: +`{"artifact_id":"presentation_x","actions":[{"action":"resolve","args":{"id":"sh/element_3"}}]}` + +Example proto export: +`{"artifact_id":"presentation_x","actions":[{"action":"to_proto","args":{}}]}` + +`to_proto` returns a full JSON snapshot of the current in-memory presentation document, including slide/layout records, anchors, notes, theme state, and typed element payloads. + +Rich text is supported on notes, text boxes, shapes with text, and table cells. Use `set_rich_text` to replace a full rich-text payload, `set_notes_rich_text` for speaker notes, and `format_text_range` to annotate a substring by `query` or explicit codepoint range. `inspect`, `resolve`, and `to_proto` surface text-range anchors as `tr/`. + +Comment threads are supported through `set_comment_author`, `add_comment_thread`, `add_comment_reply`, `toggle_comment_reaction`, `resolve_comment_thread`, and `reopen_comment_thread`. Thread anchors resolve as `th/`, and comment records appear in both `inspect` and `to_proto`. + +Charts support richer series metadata plus `update_chart` and `add_chart_series`, including legend, axis, data-label, marker, fill, and per-point override state. + +Exported PPTX files embed Codex metadata so rich text, comment threads, and advanced table/chart state round-trip through `export_pptx` and `import_pptx` even when the base OOXML representation is lossy. + +Example patch recording: +`{"artifact_id":"presentation_x","actions":[{"action":"record_patch","args":{"operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}]}` + +Example patch application: +`{"artifact_id":"presentation_x","actions":[{"action":"apply_patch","args":{"patch":{"version":1,"artifactId":"presentation_x","operations":[{"action":"add_text_shape","args":{"slide_index":0,"text":"Headline","position":{"left":48,"top":48,"width":320,"height":72}}},{"action":"set_slide_background","args":{"slide_index":0,"fill":"#F7F1E8"}}]}}}]}` + +Patch payloads are single-artifact and currently support existing in-memory editing actions like slide/element/layout/theme/text updates. Lifecycle, import/export, and nested history actions are intentionally excluded. + +Example undo/redo: +`{"artifact_id":"presentation_x","actions":[{"action":"undo","args":{}}]}` + +`{"artifact_id":"presentation_x","actions":[{"action":"redo","args":{}}]}` + +Deck summaries, slide listings, `inspect`, and `resolve` now include active-slide metadata. Use `set_active_slide` to change it explicitly. + +Theme snapshots and `to_proto` both expose the deck theme hex color map via `hex_color_map` / `hexColorMap`. + +Named text styles are supported through `add_style`, `get_style`, and `describe_styles`. Built-in styles include `title`, `heading1`, `body`, `list`, and `numberedList`. + +Example style creation: +`{"artifact_id":"presentation_x","actions":[{"action":"add_style","args":{"name":"callout","font_size":18,"color":"#336699","italic":true,"underline":true}}]}` + +Example style lookup: +`{"artifact_id":"presentation_x","actions":[{"action":"get_style","args":{"name":"title"}}]}` + +Text styling payloads on `add_text_shape`, `add_shape.text_style`, `update_text.styling`, and `update_table_cell.styling` accept `style` and `underline` in addition to the existing whole-element fields. + +Text-bearing elements also support literal `replace_text` and `insert_text_after` helpers for in-place edits without resending the full string. + +Example rich text update: +`{"artifact_id":"presentation_x","actions":[{"action":"set_rich_text","args":{"element_id":"element_3","text":[[{"run":"Quarterly ","text_style":{"bold":true}},"update pipeline"]],"text_layout":{"wrap":"square","auto_fit":"shrinkText","vertical_alignment":"middle","insets":{"left":6,"right":6,"top":4,"bottom":4}}}}]}` + +Example substring formatting: +`{"artifact_id":"presentation_x","actions":[{"action":"format_text_range","args":{"element_id":"element_3","query":"update","styling":{"italic":true},"link":{"uri":"https://example.com/update","is_external":true}}}]}` + +Text boxes and shapes support whole-element hyperlinks via `set_hyperlink`. Supported `link_type` values are `url`, `slide`, `first_slide`, `last_slide`, `next_slide`, `previous_slide`, `end_show`, `email`, and `file`. Use `clear: true` to remove an existing hyperlink. + +Notes visibility is honored on export: `set_notes_visibility` controls whether speaker notes are emitted into exported PPTX output. + +Example comment thread: +`{"artifact_id":"presentation_x","actions":[{"action":"set_comment_author","args":{"display_name":"Jamie Fox","initials":"JF"}},{"action":"add_comment_thread","args":{"slide_index":0,"element_id":"element_3","query":"Quarterly","text":"Tighten this headline"}},{"action":"add_comment_reply","args":{"thread_id":"thread_1","text":"Applied to the draft."}}]}` + +Image placeholders can be prompt-only. `add_image` accepts `prompt` without `path`/`data_url`, and unresolved placeholders export as a visible placeholder box instead of failing. + +Layout placeholders with `placeholder_type: "picture"` or `"image"` materialize as placeholder image elements on slides, so they appear in `list_slide_placeholders`, `inspect`, and `resolve` as `image` records rather than generic shapes. + +Remote images are supported. `add_image` and `replace_image` accept `uri` in addition to local `path`, raw base64 `blob`, and `data_url`. + +Image edits can target inspect/resolve anchors like `im/element_3`, and `update_shape_style` now accepts image `fit`, `crop`, `rotation`, `flip_horizontal`, `flip_vertical`, and `lock_aspect_ratio` updates. + +`add_image` and `replace_image` also accept optional `rotation`, `flip_horizontal`, and `flip_vertical` fields for image transforms. + +`update_shape_style.position` accepts partial updates, so you can move or resize an element without resending the full rect. + +Shape strokes accept an optional `style` field such as `solid`, `dashed`, `dotted`, `dash-dot`, `dash-dot-dot`, `long-dash`, or `long-dash-dot`. This applies to ordinary shapes via `add_shape.stroke` and `update_shape_style.stroke`. + +`add_shape` also accepts optional `rotation`, `flip_horizontal`, and `flip_vertical` fields. Those same transform fields can also be provided inside the `position` object for `add_shape`, `add_image`, and `update_shape_style`. + +Connectors are supported via `add_connector`, with straight/elbow/curved types plus dash styles and arrow heads. + +Example chart update: +`{"artifact_id":"presentation_x","actions":[{"action":"update_chart","args":{"element_id":"element_7","style_index":12,"legend_position":"bottom","y_axis_title":"USD (millions)"}},{"action":"add_chart_series","args":{"element_id":"element_7","name":"Target","values":[11,13],"fill":"#70AD47","marker":{"symbol":"diamond","size":6}}}]}` + +Example preview: +`{"artifact_id":"presentation_x","actions":[{"action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.png"}}]}` + +`export_preview` also accepts `format`, `scale`, and `quality` for rendered previews. `format` currently supports `png`, `jpeg`, and `svg`. + +Example JPEG preview: +`{"artifact_id":"presentation_x","actions":[{"action":"export_preview","args":{"slide_index":0,"path":"artifacts/q2-update-slide1.jpg","format":"jpeg","scale":0.75,"quality":85}}]}` diff --git a/codex-rs/core/tests/common/context_snapshot.rs b/codex-rs/core/tests/common/context_snapshot.rs index f9362ee30c..5471fd8913 100644 --- a/codex-rs/core/tests/common/context_snapshot.rs +++ b/codex-rs/core/tests/common/context_snapshot.rs @@ -62,7 +62,7 @@ pub fn format_response_items_snapshot(items: &[Value], options: &ContextSnapshot match item_type { "message" => { let role = item.get("role").and_then(Value::as_str).unwrap_or("unknown"); - let text = item + let rendered_parts = item .get("content") .and_then(Value::as_array) .map(|content| { @@ -93,11 +93,27 @@ pub fn format_response_items_snapshot(items: &[Value], options: &ContextSnapshot } }) .collect::>() - .join(" | ") }) - .filter(|text| !text.is_empty()) - .unwrap_or_else(|| "".to_string()); - format!("{idx:02}:message/{role}:{text}") + .unwrap_or_default(); + let role = if rendered_parts.len() > 1 { + format!("{role}[{}]", rendered_parts.len()) + } else { + role.to_string() + }; + if rendered_parts.is_empty() { + return format!("{idx:02}:message/{role}:"); + } + if rendered_parts.len() == 1 { + return format!("{idx:02}:message/{role}:{}", rendered_parts[0]); + } + + let parts = rendered_parts + .iter() + .enumerate() + .map(|(part_idx, part)| format!(" [{:02}] {part}", part_idx + 1)) + .collect::>() + .join("\n"); + format!("{idx:02}:message/{role}:\n{parts}") } "function_call" => { let name = item.get("name").and_then(Value::as_str).unwrap_or("unknown"); @@ -198,11 +214,14 @@ pub fn format_labeled_items_snapshot( fn format_snapshot_text(text: &str, options: &ContextSnapshotOptions) -> String { match options.render_mode { ContextSnapshotRenderMode::RedactedText => { - canonicalize_snapshot_text(text).replace('\n', "\\n") + normalize_snapshot_line_endings(&canonicalize_snapshot_text(text)).replace('\n', "\\n") + } + ContextSnapshotRenderMode::FullText => { + normalize_snapshot_line_endings(text).replace('\n', "\\n") } - ContextSnapshotRenderMode::FullText => text.replace('\n', "\\n"), ContextSnapshotRenderMode::KindWithTextPrefix { max_chars } => { - let normalized = canonicalize_snapshot_text(text).replace('\n', "\\n"); + let normalized = normalize_snapshot_line_endings(&canonicalize_snapshot_text(text)) + .replace('\n', "\\n"); if normalized.chars().count() <= max_chars { normalized } else { @@ -214,6 +233,10 @@ fn format_snapshot_text(text: &str, options: &ContextSnapshotOptions) -> String } } +fn normalize_snapshot_line_endings(text: &str) -> String { + text.replace("\r\n", "\n").replace('\r', "\n") +} + fn canonicalize_snapshot_text(text: &str) -> String { if text.starts_with("") { return "".to_string(); @@ -222,15 +245,34 @@ fn canonicalize_snapshot_text(text: &str) -> String { return "".to_string(); } if text.starts_with("") { + let subagent_count = text + .split_once("") + .and_then(|(_, rest)| rest.split_once("")) + .map(|(subagents, _)| { + subagents + .lines() + .filter(|line| line.trim_start().starts_with("- ")) + .count() + }) + .unwrap_or(0); + let subagents_suffix = if subagent_count > 0 { + format!(":subagents={subagent_count}") + } else { + String::new() + }; if let (Some(cwd_start), Some(cwd_end)) = (text.find(""), text.find("")) { let cwd = &text[cwd_start + "".len()..cwd_end]; return if cwd.ends_with("PRETURN_CONTEXT_DIFF_CWD") { - "".to_string() + format!("") } else { - ">".to_string() + format!("{subagents_suffix}>") }; } - return "".to_string(); + return if subagent_count > 0 { + format!("") + } else { + "".to_string() + }; } if text.starts_with("You are performing a CONTEXT CHECKPOINT COMPACTION.") { return "".to_string(); @@ -258,7 +300,7 @@ mod tests { "role": "user", "content": [{ "type": "input_text", - "text": "# AGENTS.md instructions for /tmp/example" + "text": "# AGENTS.md instructions for /tmp/example\n\n\nbody\n" }] })]; @@ -269,10 +311,29 @@ mod tests { assert_eq!( rendered, - "00:message/user:# AGENTS.md instructions for /tmp/example" + r"00:message/user:# AGENTS.md instructions for /tmp/example\n\n\nbody\n" ); } + #[test] + fn full_text_mode_normalizes_crlf_line_endings() { + let items = vec![json!({ + "type": "message", + "role": "user", + "content": [{ + "type": "input_text", + "text": "line one\r\n\r\nline two" + }] + })]; + + let rendered = format_response_items_snapshot( + &items, + &ContextSnapshotOptions::default().render_mode(ContextSnapshotRenderMode::FullText), + ); + + assert_eq!(rendered, r"00:message/user:line one\n\nline two"); + } + #[test] fn redacted_text_mode_keeps_canonical_placeholders() { let items = vec![json!({ @@ -280,7 +341,7 @@ mod tests { "role": "user", "content": [{ "type": "input_text", - "text": "# AGENTS.md instructions for /tmp/example" + "text": "# AGENTS.md instructions for /tmp/example\n\n\nbody\n" }] })]; @@ -292,6 +353,51 @@ mod tests { assert_eq!(rendered, "00:message/user:"); } + #[test] + fn redacted_text_mode_normalizes_environment_context_with_subagents() { + let items = vec![json!({ + "type": "message", + "role": "user", + "content": [{ + "type": "input_text", + "text": "\n /tmp/example\n bash\n \n - agent-1: atlas\n - agent-2\n \n" + }] + })]; + + let rendered = format_response_items_snapshot( + &items, + &ContextSnapshotOptions::default().render_mode(ContextSnapshotRenderMode::RedactedText), + ); + + assert_eq!( + rendered, + "00:message/user::subagents=2>" + ); + } + + #[test] + fn kind_with_text_prefix_mode_normalizes_crlf_line_endings() { + let items = vec![json!({ + "type": "message", + "role": "developer", + "content": [{ + "type": "input_text", + "text": "\r\nRealtime conversation started.\r\n\r\nYou are..." + }] + })]; + + let rendered = format_response_items_snapshot( + &items, + &ContextSnapshotOptions::default() + .render_mode(ContextSnapshotRenderMode::KindWithTextPrefix { max_chars: 64 }), + ); + + assert_eq!( + rendered, + r"00:message/developer:\nRealtime conversation started.\n\nYou a..." + ); + } + #[test] fn image_only_message_is_rendered_as_non_text_span() { let items = vec![json!({ @@ -333,7 +439,7 @@ mod tests { assert_eq!( rendered, - "00:message/user: | | " + "00:message/user[3]:\n [01] \n [02] \n [03] " ); } } diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index a26cd5ae77..f324d93a1b 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -21,6 +21,7 @@ pub mod responses; pub mod streaming_sse; pub mod test_codex; pub mod test_codex_exec; +pub mod zsh_fork; #[ctor] fn enable_deterministic_unified_exec_process_ids_for_tests() { diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 4c7f26ddba..4f2e89636e 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -12,6 +12,7 @@ use futures::SinkExt; use futures::StreamExt; use serde_json::Value; use tokio::net::TcpListener; +use tokio::sync::Notify; use tokio::sync::oneshot; use tokio_tungstenite::accept_hdr_async_with_config; use tokio_tungstenite::tungstenite::Message; @@ -141,6 +142,32 @@ impl ResponsesRequest { .collect() } + /// Returns `input_text` spans grouped by `message` input for the provided role. + pub fn message_input_text_groups(&self, role: &str) -> Vec> { + self.inputs_of_type("message") + .into_iter() + .filter(|item| item.get("role").and_then(Value::as_str) == Some(role)) + .filter_map(|item| item.get("content").and_then(Value::as_array).cloned()) + .map(|content| { + content + .into_iter() + .filter(|span| span.get("type").and_then(Value::as_str) == Some("input_text")) + .filter_map(|span| span.get("text").and_then(Value::as_str).map(str::to_owned)) + .collect() + }) + .collect() + } + + pub fn has_message_with_input_texts( + &self, + role: &str, + predicate: impl Fn(&[String]) -> bool, + ) -> bool { + self.message_input_text_groups(role) + .iter() + .any(|texts| predicate(texts)) + } + /// Returns all `input_image` `image_url` spans from `message` inputs for the provided role. pub fn message_input_image_urls(&self, role: &str) -> Vec { self.inputs_of_type("message") @@ -237,7 +264,7 @@ impl ResponsesRequest { .cloned() .unwrap_or(Value::Null); match output { - Value::String(text) => Some((Some(text), None)), + Value::String(_) | Value::Array(_) => Some((output_value_to_text(&output), None)), Value::Object(obj) => Some(( obj.get("content") .and_then(Value::as_str) @@ -269,6 +296,87 @@ impl ResponsesRequest { } } +pub(crate) fn output_value_to_text(value: &Value) -> Option { + match value { + Value::String(text) => Some(text.clone()), + Value::Array(items) => match items.as_slice() { + [item] if item.get("type").and_then(Value::as_str) == Some("input_text") => { + item.get("text").and_then(Value::as_str).map(str::to_string) + } + [_] | [] | [_, _, ..] => None, + }, + Value::Object(_) | Value::Number(_) | Value::Bool(_) | Value::Null => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use wiremock::http::HeaderMap; + use wiremock::http::Method; + + fn request_with_input(input: Value) -> ResponsesRequest { + ResponsesRequest(wiremock::Request { + url: "http://localhost/v1/responses" + .parse() + .expect("valid request url"), + method: Method::POST, + headers: HeaderMap::new(), + body: serde_json::to_vec(&serde_json::json!({ "input": input })) + .expect("serialize request body"), + }) + } + + #[test] + fn call_output_content_and_success_returns_only_single_text_content_item() { + let single_text = request_with_input(serde_json::json!([ + { + "type": "function_call_output", + "call_id": "call-1", + "output": [{ "type": "input_text", "text": "hello" }] + }, + { + "type": "custom_tool_call_output", + "call_id": "call-2", + "output": [{ "type": "input_text", "text": "world" }] + } + ])); + assert_eq!( + single_text.function_call_output_content_and_success("call-1"), + Some((Some("hello".to_string()), None)) + ); + assert_eq!( + single_text.custom_tool_call_output_content_and_success("call-2"), + Some((Some("world".to_string()), None)) + ); + + let mixed_content = request_with_input(serde_json::json!([ + { + "type": "function_call_output", + "call_id": "call-3", + "output": [ + { "type": "input_text", "text": "hello" }, + { "type": "input_image", "image_url": "data:image/png;base64,abc" } + ] + }, + { + "type": "custom_tool_call_output", + "call_id": "call-4", + "output": [{ "type": "input_image", "image_url": "data:image/png;base64,abc" }] + } + ])); + assert_eq!( + mixed_content.function_call_output_content_and_success("call-3"), + Some((None, None)) + ); + assert_eq!( + mixed_content.custom_tool_call_output_content_and_success("call-4"), + Some((None, None)) + ); + } +} + #[derive(Debug, Clone)] pub struct WebSocketRequest { body: Value, @@ -282,10 +390,15 @@ impl WebSocketRequest { #[derive(Debug, Clone)] pub struct WebSocketHandshake { + uri: String, headers: Vec<(String, String)>, } impl WebSocketHandshake { + pub fn uri(&self) -> &str { + &self.uri + } + pub fn header(&self, name: &str) -> Option { self.headers .iter() @@ -309,6 +422,7 @@ pub struct WebSocketTestServer { uri: String, connections: Arc>>>, handshakes: Arc>>, + request_log_updated: Arc, shutdown: oneshot::Sender<()>, task: tokio::task::JoinHandle<()>, } @@ -330,6 +444,26 @@ impl WebSocketTestServer { connections.first().cloned().unwrap_or_default() } + pub async fn wait_for_request( + &self, + connection_index: usize, + request_index: usize, + ) -> WebSocketRequest { + loop { + if let Some(request) = self + .connections + .lock() + .unwrap() + .get(connection_index) + .and_then(|connection| connection.get(request_index)) + .cloned() + { + return request; + } + self.request_log_updated.notified().await; + } + } + pub fn handshakes(&self) -> Vec { self.handshakes.lock().unwrap().clone() } @@ -448,25 +582,6 @@ pub fn ev_completed(id: &str) -> Value { }) } -pub fn ev_done() -> Value { - serde_json::json!({ - "type": "response.done", - "response": { - "usage": {"input_tokens":0,"input_tokens_details":null,"output_tokens":0,"output_tokens_details":null,"total_tokens":0} - } - }) -} - -pub fn ev_done_with_id(id: &str) -> Value { - serde_json::json!({ - "type": "response.done", - "response": { - "id": id, - "usage": {"input_tokens":0,"input_tokens_details":null,"output_tokens":0,"output_tokens_details":null,"total_tokens":0} - } - }) -} - /// Convenience: SSE event for a created response with a specific id. pub fn ev_response_created(id: &str) -> Value { serde_json::json!({ @@ -1043,6 +1158,7 @@ pub async fn start_websocket_server(connections: Vec>>) -> WebSoc pub async fn start_websocket_server_with_headers( connections: Vec, ) -> WebSocketTestServer { + let start = std::time::Instant::now(); let listener = TcpListener::bind("127.0.0.1:0") .await .expect("bind websocket server"); @@ -1050,8 +1166,10 @@ pub async fn start_websocket_server_with_headers( let uri = format!("ws://{addr}"); let connections_log = Arc::new(Mutex::new(Vec::new())); let handshakes_log = Arc::new(Mutex::new(Vec::new())); + let request_log_updated = Arc::new(Notify::new()); let requests = Arc::clone(&connections_log); let handshakes = Arc::clone(&handshakes_log); + let request_log = Arc::clone(&request_log_updated); let connections = Arc::new(Mutex::new(VecDeque::from(connections))); let (shutdown_tx, mut shutdown_rx) = oneshot::channel(); @@ -1091,10 +1209,10 @@ pub async fn start_websocket_server_with_headers( .map(|value| (name.as_str().to_string(), value.to_string())) }) .collect(); - handshake_log - .lock() - .unwrap() - .push(WebSocketHandshake { headers }); + handshake_log.lock().unwrap().push(WebSocketHandshake { + uri: req.uri().to_string(), + headers, + }); let headers_mut = response.headers_mut(); for (name, value) in &response_headers { @@ -1133,9 +1251,51 @@ pub async fn start_websocket_server_with_headers( let mut log = requests.lock().unwrap(); if let Some(connection_log) = log.get_mut(connection_index) { connection_log.push(WebSocketRequest { body }); + let request_index = connection_log.len() - 1; + let request = &connection_log[request_index]; + let request_body = request.body_json(); + eprintln!( + "[ws test server +{}ms] connection={} received request={} type={:?} role={:?} text={:?} data={:?}", + start.elapsed().as_millis(), + connection_index, + request_index, + request_body.get("type").and_then(Value::as_str), + request_body + .get("item") + .and_then(|item| item.get("role")) + .and_then(Value::as_str), + request_body + .get("item") + .and_then(|item| item.get("content")) + .and_then(Value::as_array) + .and_then(|content| content.first()) + .and_then(|content| content.get("text")) + .and_then(Value::as_str), + request_body + .get("item") + .and_then(|item| item.get("content")) + .and_then(Value::as_array) + .and_then(|content| content.first()) + .and_then(|content| content.get("data")) + .and_then(Value::as_str), + ); } + request_log.notify_waiters(); } + eprintln!( + "[ws test server +{}ms] connection={} sending batch_size={} event_types={:?} audio_data={:?}", + start.elapsed().as_millis(), + connection_index, + request_events.len(), + request_events + .iter() + .map(|event| event.get("type").and_then(Value::as_str)) + .collect::>(), + request_events + .iter() + .find_map(|event| event.get("delta").and_then(Value::as_str)), + ); for event in &request_events { let Ok(payload) = serde_json::to_string(event) else { continue; @@ -1158,6 +1318,7 @@ pub async fn start_websocket_server_with_headers( uri, connections: connections_log, handshakes: handshakes_log, + request_log_updated, shutdown: shutdown_tx, task, } diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 173db5ca77..392d4d354f 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -11,7 +11,7 @@ use codex_core::ThreadManager; use codex_core::built_in_model_providers; use codex_core::config::Config; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::ServiceTier; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -24,6 +24,7 @@ use wiremock::MockServer; use crate::load_default_config_for_test; use crate::responses::WebSocketTestServer; +use crate::responses::output_value_to_text; use crate::responses::start_mock_server; use crate::streaming_sse::StreamingSseServer; use crate::wait_for_event; @@ -126,6 +127,7 @@ impl TestCodexBuilder { let base_url_clone = base_url.clone(); self.config_mutators.push(Box::new(move |config| { config.model_provider.base_url = Some(base_url_clone); + config.experimental_realtime_ws_model = Some("realtime-test-model".to_string()); config.features.enable(Feature::ResponsesWebsockets); })); self.build_with_home_and_base_url(base_url, home, None) @@ -281,11 +283,36 @@ impl TestCodex { .await } + pub async fn submit_turn_with_service_tier( + &self, + prompt: &str, + service_tier: Option, + ) -> Result<()> { + self.submit_turn_with_context( + prompt, + AskForApproval::Never, + SandboxPolicy::DangerFullAccess, + Some(service_tier), + ) + .await + } + pub async fn submit_turn_with_policies( &self, prompt: &str, approval_policy: AskForApproval, sandbox_policy: SandboxPolicy, + ) -> Result<()> { + self.submit_turn_with_context(prompt, approval_policy, sandbox_policy, None) + .await + } + + async fn submit_turn_with_context( + &self, + prompt: &str, + approval_policy: AskForApproval, + sandbox_policy: SandboxPolicy, + service_tier: Option>, ) -> Result<()> { let session_model = self.session_configured.model.clone(); self.codex @@ -300,7 +327,8 @@ impl TestCodex { sandbox_policy, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier, collaboration_mode: None, personality: None, }) @@ -395,11 +423,7 @@ impl TestCodexHarness { pub async fn custom_tool_call_output(&self, call_id: &str) -> String { let bodies = self.request_bodies().await; - custom_tool_call_output(&bodies, call_id) - .get("output") - .and_then(Value::as_str) - .expect("output string") - .to_string() + custom_tool_call_output_text(&bodies, call_id) } pub async fn apply_patch_output( @@ -434,6 +458,14 @@ fn custom_tool_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value panic!("custom_tool_call_output {call_id} not found"); } +fn custom_tool_call_output_text(bodies: &[Value], call_id: &str) -> String { + let output = custom_tool_call_output(bodies, call_id) + .get("output") + .unwrap_or_else(|| panic!("custom_tool_call_output {call_id} missing output")); + output_value_to_text(output) + .unwrap_or_else(|| panic!("custom_tool_call_output {call_id} missing text output")) +} + fn function_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value { for body in bodies { if let Some(items) = body.get("input").and_then(Value::as_array) { @@ -457,3 +489,36 @@ pub fn test_codex() -> TestCodexBuilder { home: None, } } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use serde_json::json; + + #[test] + fn custom_tool_call_output_text_returns_output_text() { + let bodies = vec![json!({ + "input": [{ + "type": "custom_tool_call_output", + "call_id": "call-1", + "output": "hello" + }] + })]; + + assert_eq!(custom_tool_call_output_text(&bodies, "call-1"), "hello"); + } + + #[test] + #[should_panic(expected = "custom_tool_call_output call-2 missing output")] + fn custom_tool_call_output_text_panics_when_output_is_missing() { + let bodies = vec![json!({ + "input": [{ + "type": "custom_tool_call_output", + "call_id": "call-2" + }] + })]; + + let _ = custom_tool_call_output_text(&bodies, "call-2"); + } +} diff --git a/codex-rs/core/tests/common/zsh_fork.rs b/codex-rs/core/tests/common/zsh_fork.rs new file mode 100644 index 0000000000..22ae69303e --- /dev/null +++ b/codex-rs/core/tests/common/zsh_fork.rs @@ -0,0 +1,118 @@ +use std::path::Path; +use std::path::PathBuf; + +use anyhow::Result; +use codex_core::config::Config; +use codex_core::config::Constrained; +use codex_core::features::Feature; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; + +use crate::test_codex::TestCodex; +use crate::test_codex::test_codex; + +#[derive(Clone)] +pub struct ZshForkRuntime { + zsh_path: PathBuf, + main_execve_wrapper_exe: PathBuf, +} + +impl ZshForkRuntime { + fn apply_to_config( + &self, + config: &mut Config, + approval_policy: AskForApproval, + sandbox_policy: SandboxPolicy, + ) { + config.features.enable(Feature::ShellTool); + config.features.enable(Feature::ShellZshFork); + config.zsh_path = Some(self.zsh_path.clone()); + config.main_execve_wrapper_exe = Some(self.main_execve_wrapper_exe.clone()); + config.permissions.allow_login_shell = false; + config.permissions.approval_policy = Constrained::allow_any(approval_policy); + config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy); + } +} + +pub fn restrictive_workspace_write_policy() -> SandboxPolicy { + SandboxPolicy::WorkspaceWrite { + writable_roots: Vec::new(), + read_only_access: Default::default(), + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + } +} + +pub fn zsh_fork_runtime(test_name: &str) -> Result> { + let Some(zsh_path) = find_test_zsh_path()? else { + return Ok(None); + }; + if !supports_exec_wrapper_intercept(&zsh_path) { + eprintln!( + "skipping {test_name}: zsh does not support EXEC_WRAPPER intercepts ({})", + zsh_path.display() + ); + return Ok(None); + } + let Ok(main_execve_wrapper_exe) = codex_utils_cargo_bin::cargo_bin("codex-execve-wrapper") + else { + eprintln!("skipping {test_name}: unable to resolve `codex-execve-wrapper` binary"); + return Ok(None); + }; + + Ok(Some(ZshForkRuntime { + zsh_path, + main_execve_wrapper_exe, + })) +} + +pub async fn build_zsh_fork_test( + server: &wiremock::MockServer, + runtime: ZshForkRuntime, + approval_policy: AskForApproval, + sandbox_policy: SandboxPolicy, + pre_build_hook: F, +) -> Result +where + F: FnOnce(&Path) + Send + 'static, +{ + let mut builder = test_codex() + .with_pre_build_hook(pre_build_hook) + .with_config(move |config| { + runtime.apply_to_config(config, approval_policy, sandbox_policy); + }); + builder.build(server).await +} + +fn find_test_zsh_path() -> Result> { + let repo_root = codex_utils_cargo_bin::repo_root()?; + let dotslash_zsh = repo_root.join("codex-rs/app-server/tests/suite/zsh"); + if !dotslash_zsh.is_file() { + eprintln!( + "skipping zsh-fork test: shared zsh DotSlash file not found at {}", + dotslash_zsh.display() + ); + return Ok(None); + } + + match crate::fetch_dotslash_file(&dotslash_zsh, None) { + Ok(path) => Ok(Some(path)), + Err(error) => { + eprintln!("skipping zsh-fork test: failed to fetch zsh via dotslash: {error:#}"); + Ok(None) + } + } +} + +fn supports_exec_wrapper_intercept(zsh_path: &Path) -> bool { + let status = std::process::Command::new(zsh_path) + .arg("-fc") + .arg("/usr/bin/true") + .env("EXEC_WRAPPER", "/usr/bin/false") + .status(); + match status { + Ok(status) => !status.success(), + Err(_) => false, + } +} diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs index 539e543230..b6e05cb145 100644 --- a/codex-rs/core/tests/responses_headers.rs +++ b/codex-rs/core/tests/responses_headers.rs @@ -6,7 +6,6 @@ use codex_core::ModelClient; use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponsesWebsocketVersion; use codex_core::WireApi; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; @@ -92,7 +91,7 @@ async fn responses_stream_includes_subagent_header_on_review() { provider.clone(), session_source, config.model_verbosity, - None::, + false, false, false, None, @@ -111,7 +110,15 @@ async fn responses_stream_includes_subagent_header_on_review() { }]; let mut stream = client_session - .stream(&prompt, &model_info, &otel_manager, effort, summary, None) + .stream( + &prompt, + &model_info, + &otel_manager, + effort, + summary.unwrap_or(model_info.default_reasoning_summary), + None, + None, + ) .await .expect("stream failed"); while let Some(event) = stream.next().await { @@ -197,7 +204,7 @@ async fn responses_stream_includes_subagent_header_on_other() { provider.clone(), session_source, config.model_verbosity, - None::, + false, false, false, None, @@ -216,7 +223,15 @@ async fn responses_stream_includes_subagent_header_on_other() { }]; let mut stream = client_session - .stream(&prompt, &model_info, &otel_manager, effort, summary, None) + .stream( + &prompt, + &model_info, + &otel_manager, + effort, + summary.unwrap_or(model_info.default_reasoning_summary), + None, + None, + ) .await .expect("stream failed"); while let Some(event) = stream.next().await { @@ -267,7 +282,7 @@ async fn responses_respects_model_info_overrides_from_config() { config.model_provider_id = provider.name.clone(); config.model_provider = provider.clone(); config.model_supports_reasoning_summaries = Some(true); - config.model_reasoning_summary = ReasoningSummary::Detailed; + config.model_reasoning_summary = Some(ReasoningSummary::Detailed); let effort = config.model_reasoning_effort; let summary = config.model_reasoning_summary; let model = config.model.clone().expect("model configured"); @@ -301,7 +316,7 @@ async fn responses_respects_model_info_overrides_from_config() { provider.clone(), session_source, config.model_verbosity, - None::, + false, false, false, None, @@ -320,7 +335,15 @@ async fn responses_respects_model_info_overrides_from_config() { }]; let mut stream = client_session - .stream(&prompt, &model_info, &otel_manager, effort, summary, None) + .stream( + &prompt, + &model_info, + &otel_manager, + effort, + summary.unwrap_or(model_info.default_reasoning_summary), + None, + None, + ) .await .expect("stream failed"); while let Some(event) = stream.next().await { diff --git a/codex-rs/core/tests/suite/agent_websocket.rs b/codex-rs/core/tests/suite/agent_websocket.rs index 26b07bbd52..0db3cf61ad 100644 --- a/codex-rs/core/tests/suite/agent_websocket.rs +++ b/codex-rs/core/tests/suite/agent_websocket.rs @@ -1,10 +1,9 @@ use anyhow::Result; use codex_core::features::Feature; +use codex_protocol::config_types::ServiceTier; use core_test_support::responses::WebSocketConnectionConfig; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_done; -use core_test_support::responses::ev_done_with_id; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_shell_command_call; use core_test_support::responses::start_websocket_server; @@ -26,7 +25,7 @@ async fn websocket_test_codex_shell_chain() -> Result<()> { vec![ ev_response_created("resp-1"), ev_shell_command_call(call_id, "echo websocket"), - ev_done(), + ev_completed("resp-1"), ], vec![ ev_response_created("resp-2"), @@ -58,36 +57,30 @@ async fn websocket_test_codex_shell_chain() -> Result<()> { .body_json(); assert_eq!(first_turn["type"].as_str(), Some("response.create")); - assert_eq!(second_turn["type"].as_str(), Some("response.append")); + assert_eq!(second_turn["type"].as_str(), Some("response.create")); - let append_items = second_turn + let input_items = second_turn .get("input") .and_then(Value::as_array) - .expect("response.append input array"); - assert!(!append_items.is_empty()); - - let output_item = append_items - .iter() - .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output")) - .expect("function_call_output in append"); - assert_eq!( - output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); + .expect("second response.create input array"); + assert!(!input_items.is_empty()); server.shutdown().await; Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn websocket_first_turn_uses_preconnect_and_create() -> Result<()> { +async fn websocket_first_turn_uses_startup_prewarm_and_create() -> Result<()> { skip_if_no_network!(Ok(())); - let server = start_websocket_server(vec![vec![vec![ - ev_response_created("resp-1"), - ev_assistant_message("msg-1", "hello"), - ev_completed("resp-1"), - ]]]) + let server = start_websocket_server(vec![vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "hello"), + ev_completed("resp-1"), + ], + ]]) .await; let mut builder = test_codex(); @@ -100,11 +93,14 @@ async fn websocket_first_turn_uses_preconnect_and_create() -> Result<()> { assert_eq!(server.handshakes().len(), 1); let connection = server.single_connection(); - assert_eq!(connection.len(), 1); - let turn = connection + assert_eq!(connection.len(), 2); + let warmup = connection .first() - .expect("missing turn request") + .expect("missing warmup request") .body_json(); + let turn = connection.get(1).expect("missing turn request").body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); assert!( turn["tools"] .as_array() @@ -118,15 +114,18 @@ async fn websocket_first_turn_uses_preconnect_and_create() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn websocket_first_turn_handles_handshake_delay_with_preconnect() -> Result<()> { +async fn websocket_first_turn_handles_handshake_delay_with_startup_prewarm() -> Result<()> { skip_if_no_network!(Ok(())); let server = start_websocket_server_with_headers(vec![WebSocketConnectionConfig { - requests: vec![vec![ - ev_response_created("resp-1"), - ev_assistant_message("msg-1", "hello"), - ev_completed("resp-1"), - ]], + requests: vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "hello"), + ev_completed("resp-1"), + ], + ], response_headers: Vec::new(), // Delay handshake so turn processing must tolerate websocket startup latency. accept_delay: Some(Duration::from_millis(150)), @@ -143,11 +142,14 @@ async fn websocket_first_turn_handles_handshake_delay_with_preconnect() -> Resul assert_eq!(server.handshakes().len(), 1); let connection = server.single_connection(); - assert_eq!(connection.len(), 1); - let turn = connection + assert_eq!(connection.len(), 2); + let warmup = connection .first() - .expect("missing turn request") + .expect("missing warmup request") .body_json(); + let turn = connection.get(1).expect("missing turn request").body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); assert!( turn["tools"] .as_array() @@ -166,7 +168,7 @@ async fn websocket_v2_test_codex_shell_chain() -> Result<()> { let call_id = "shell-command-call"; let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ ev_response_created("resp-1"), ev_shell_command_call(call_id, "echo websocket"), @@ -244,3 +246,171 @@ async fn websocket_v2_test_codex_shell_chain() -> Result<()> { server.shutdown().await; Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn websocket_v2_first_turn_uses_updated_fast_tier_after_startup_prewarm() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "fast"), + ev_completed("resp-1"), + ], + ]]) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::ResponsesWebsocketsV2); + }); + let test = builder.build_with_websocket_server(&server).await?; + + let warmup = server.wait_for_request(0, 0).await.body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); + assert_eq!(warmup.get("service_tier"), None); + + test.submit_turn_with_service_tier("hello", Some(ServiceTier::Fast)) + .await?; + + assert_eq!(server.handshakes().len(), 1); + let connection = server.single_connection(); + assert_eq!(connection.len(), 2); + let first_turn = connection + .get(1) + .expect("missing first turn request") + .body_json(); + + assert_eq!(first_turn["type"].as_str(), Some("response.create")); + assert_eq!(first_turn["service_tier"].as_str(), Some("priority")); + assert_eq!(first_turn.get("previous_response_id"), None); + assert!( + first_turn + .get("input") + .and_then(Value::as_array) + .is_some_and(|items| !items.is_empty()) + ); + + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn websocket_v2_first_turn_drops_fast_tier_after_startup_prewarm() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "standard"), + ev_completed("resp-1"), + ], + ]]) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::ResponsesWebsocketsV2); + config.service_tier = Some(ServiceTier::Fast); + }); + let test = builder.build_with_websocket_server(&server).await?; + + let warmup = server.wait_for_request(0, 0).await.body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); + assert_eq!(warmup["service_tier"].as_str(), Some("priority")); + + test.submit_turn_with_service_tier("hello", None).await?; + + assert_eq!(server.handshakes().len(), 1); + let connection = server.single_connection(); + assert_eq!(connection.len(), 2); + let first_turn = connection + .get(1) + .expect("missing first turn request") + .body_json(); + + assert_eq!(first_turn["type"].as_str(), Some("response.create")); + assert_eq!(first_turn.get("service_tier"), None); + assert_eq!(first_turn.get("previous_response_id"), None); + assert!( + first_turn + .get("input") + .and_then(Value::as_array) + .is_some_and(|items| !items.is_empty()) + ); + + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn websocket_v2_next_turn_uses_updated_service_tier() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_websocket_server(vec![vec![ + vec![ev_response_created("warm-1"), ev_completed("warm-1")], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "fast"), + ev_completed("resp-1"), + ], + vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-2", "standard"), + ev_completed("resp-2"), + ], + ]]) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::ResponsesWebsocketsV2); + }); + let test = builder.build_with_websocket_server(&server).await?; + + let warmup = server.wait_for_request(0, 0).await.body_json(); + assert_eq!(warmup["type"].as_str(), Some("response.create")); + assert_eq!(warmup["generate"].as_bool(), Some(false)); + assert_eq!(warmup.get("service_tier"), None); + + test.submit_turn_with_service_tier("first", Some(ServiceTier::Fast)) + .await?; + test.submit_turn_with_service_tier("second", None).await?; + + assert_eq!(server.handshakes().len(), 1); + let connection = server.single_connection(); + assert_eq!(connection.len(), 3); + + let first_turn = connection + .get(1) + .expect("missing first turn request") + .body_json(); + let second_turn = connection + .get(2) + .expect("missing second turn request") + .body_json(); + + assert_eq!(first_turn["type"].as_str(), Some("response.create")); + assert_eq!(first_turn["service_tier"].as_str(), Some("priority")); + assert_eq!(first_turn.get("previous_response_id"), None); + assert!( + first_turn + .get("input") + .and_then(Value::as_array) + .is_some_and(|items| !items.is_empty()) + ); + + assert_eq!(second_turn["type"].as_str(), Some("response.create")); + assert_eq!(second_turn.get("service_tier"), None); + assert_eq!(second_turn.get("previous_response_id"), None); + assert!( + second_turn + .get("input") + .and_then(Value::as_array) + .is_some_and(|items| !items.is_empty()) + ); + + server.shutdown().await; + Ok(()) +} diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 45494124e5..112b1c1bed 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -12,7 +12,6 @@ use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -312,7 +311,8 @@ async fn apply_patch_cli_move_without_content_change_has_no_turn_diff( sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -907,7 +907,8 @@ async fn apply_patch_shell_command_heredoc_with_cd_emits_turn_diff() -> Result<( sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -987,7 +988,8 @@ async fn apply_patch_shell_command_failure_propagates_error_and_skips_diff() -> sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1137,7 +1139,8 @@ async fn apply_patch_emits_turn_diff_event_with_unified_diff( sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1200,7 +1203,8 @@ async fn apply_patch_turn_diff_for_rename_with_content_change( sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1271,7 +1275,8 @@ async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1342,7 +1347,8 @@ async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 34934b3d4b..3f82139fe3 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -13,7 +13,6 @@ use codex_core::sandboxing::SandboxPermissions; use codex_protocol::approvals::NetworkApprovalProtocol; use codex_protocol::approvals::NetworkPolicyAmendment; use codex_protocol::approvals::NetworkPolicyRuleAction; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -36,6 +35,9 @@ use core_test_support::test_codex::TestCodex; 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::zsh_fork::build_zsh_fork_test; +use core_test_support::zsh_fork::restrictive_workspace_write_policy; +use core_test_support::zsh_fork::zsh_fork_runtime; use pretty_assertions::assert_eq; use regex_lite::Regex; use serde_json::Value; @@ -551,7 +553,8 @@ async fn submit_turn( sandbox_policy, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1979,6 +1982,81 @@ async fn approving_execpolicy_amendment_persists_policy_and_skips_future_prompts Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg(unix)] +async fn matched_prefix_rule_runs_unsandboxed_under_zsh_fork() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("zsh-fork prefix rule unsandboxed test")? else { + return Ok(()); + }; + + let approval_policy = AskForApproval::Never; + let sandbox_policy = restrictive_workspace_write_policy(); + let outside_dir = tempfile::tempdir_in(std::env::current_dir()?)?; + let outside_path = outside_dir + .path() + .join("zsh-fork-prefix-rule-unsandboxed.txt"); + let command = format!("touch {outside_path:?}"); + let rules = r#"prefix_rule(pattern=["touch"], decision="allow")"#.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, + sandbox_policy.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 call_id = "zsh-fork-prefix-rule-unsandboxed"; + let event = shell_event(call_id, &command, 1_000, SandboxPermissions::UseDefault)?; + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-zsh-fork-prefix-1"), + event, + ev_completed("resp-zsh-fork-prefix-1"), + ]), + ) + .await; + let results = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-zsh-fork-prefix-1", "done"), + ev_completed("resp-zsh-fork-prefix-2"), + ]), + ) + .await; + + submit_turn( + &test, + "run allowed touch under zsh fork", + approval_policy, + sandbox_policy, + ) + .await?; + + wait_for_completion_without_approval(&test).await; + + let result = parse_result(&results.single_request().function_call_output(call_id)); + assert_eq!(result.exit_code.unwrap_or(0), 0); + assert!( + outside_path.exists(), + "expected matched prefix_rule to rerun touch unsandboxed; output: {}", + result.stdout + ); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] #[cfg(unix)] async fn invalid_requested_prefix_rule_falls_back_for_compound_command() -> Result<()> { diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 5fc94a033e..d4a8ce9f3e 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -4,7 +4,6 @@ use codex_core::ModelProviderInfo; use codex_core::NewThread; use codex_core::Prompt; use codex_core::ResponseEvent; -use codex_core::ResponsesWebsocketVersion; use codex_core::ThreadManager; use codex_core::WireApi; use codex_core::auth::AuthCredentialsStoreMode; @@ -12,6 +11,7 @@ use codex_core::built_in_model_providers; use codex_core::default_client::originator; use codex_core::error::CodexErr; use codex_core::features::Feature; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_otel::OtelManager; use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; @@ -30,9 +30,14 @@ use codex_protocol::models::ReasoningItemContent; use codex_protocol::models::ReasoningItemReasoningSummary; use codex_protocol::models::ResponseItem; use codex_protocol::models::WebSearchAction; +use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SessionMeta; +use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; use codex_protocol::user_input::UserInput; use core_test_support::apps_test_server::AppsTestServer; @@ -73,40 +78,14 @@ fn assert_message_role(request_body: &serde_json::Value, role: &str) { assert_eq!(request_body["role"].as_str().unwrap(), role); } -#[expect(clippy::expect_used)] -fn assert_message_equals(request_body: &serde_json::Value, text: &str) { - let content = request_body["content"][0]["text"] - .as_str() - .expect("invalid message content"); - - assert_eq!( - content, text, - "expected message content '{content}' to equal '{text}'" - ); -} - -#[expect(clippy::expect_used)] -fn assert_message_starts_with(request_body: &serde_json::Value, text: &str) { - let content = request_body["content"][0]["text"] - .as_str() - .expect("invalid message content"); - - assert!( - content.starts_with(text), - "expected message content '{content}' to start with '{text}'" - ); -} - -#[expect(clippy::expect_used)] -fn assert_message_ends_with(request_body: &serde_json::Value, text: &str) { - let content = request_body["content"][0]["text"] - .as_str() - .expect("invalid message content"); - - assert!( - content.ends_with(text), - "expected message content '{content}' to end with '{text}'" - ); +#[expect(clippy::unwrap_used)] +fn message_input_texts(item: &serde_json::Value) -> Vec<&str> { + item["content"] + .as_array() + .unwrap() + .iter() + .filter_map(|entry| entry.get("text").and_then(|text| text.as_str())) + .collect() } /// Writes an `auth.json` into the provided `codex_home` with the specified parameters. @@ -304,19 +283,15 @@ async fn resume_includes_initial_messages_and_sends_prior_items() { let request = resp_mock.single_request(); let request_body = request.body_json(); let input = request_body["input"].as_array().expect("input array"); - let messages: Vec<(String, String)> = input - .iter() - .filter_map(|item| { - let role = item.get("role")?.as_str()?; - let text = item - .get("content")? - .as_array()? - .first()? - .get("text")? - .as_str()?; - Some((role.to_string(), text.to_string())) - }) - .collect(); + let mut messages: Vec<(String, String)> = Vec::new(); + for item in input { + let Some(role) = item.get("role").and_then(|role| role.as_str()) else { + continue; + }; + for text in message_input_texts(item) { + messages.push((role.to_string(), text.to_string())); + } + } let pos_prior_user = messages .iter() .position(|(role, text)| role == "user" && text == "resumed user message") @@ -353,8 +328,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() { .position(|(role, text)| { role == "user" && text.contains("be nice") - && (text.starts_with("# AGENTS.md instructions for ") - || text.starts_with("")) + && (text.starts_with("# AGENTS.md instructions for ")) }) .expect("user instructions"); let pos_environment = messages @@ -373,6 +347,144 @@ async fn resume_includes_initial_messages_and_sends_prior_items() { assert!(pos_environment < pos_new_user); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn resume_replays_legacy_js_repl_image_rollout_shapes() { + skip_if_no_network!(); + + // Early js_repl builds persisted image tool results as two separate rollout items: + // a string-valued custom_tool_call_output plus a standalone user input_image message. + // Current image tests cover today's shapes; this keeps resume compatibility for that + // legacy rollout representation. + let legacy_custom_tool_call = ResponseItem::CustomToolCall { + id: None, + status: None, + call_id: "legacy-js-call".to_string(), + name: "js_repl".to_string(), + input: "console.log('legacy image flow')".to_string(), + }; + let legacy_image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; + let rollout = vec![ + RolloutLine { + timestamp: "2024-01-01T00:00:00.000Z".to_string(), + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: SessionMeta { + id: ThreadId::default(), + timestamp: "2024-01-01T00:00:00Z".to_string(), + cwd: ".".into(), + originator: "test_originator".to_string(), + cli_version: "test_version".to_string(), + model_provider: Some("test-provider".to_string()), + ..Default::default() + }, + git: None, + }), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:01.000Z".to_string(), + item: RolloutItem::ResponseItem(legacy_custom_tool_call), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:02.000Z".to_string(), + item: RolloutItem::ResponseItem(ResponseItem::CustomToolCallOutput { + call_id: "legacy-js-call".to_string(), + output: FunctionCallOutputPayload::from_text("legacy js_repl stdout".to_string()), + }), + }, + RolloutLine { + timestamp: "2024-01-01T00:00:03.000Z".to_string(), + item: RolloutItem::ResponseItem(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { + image_url: legacy_image_url.to_string(), + }], + end_turn: None, + phase: None, + }), + }, + ]; + + let tmpdir = TempDir::new().unwrap(); + let session_path = tmpdir + .path() + .join("resume-legacy-js-repl-image-rollout.jsonl"); + let mut f = std::fs::File::create(&session_path).unwrap(); + for line in rollout { + writeln!(f, "{}", serde_json::to_string(&line).unwrap()).unwrap(); + } + + let server = MockServer::start().await; + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let codex_home = Arc::new(TempDir::new().unwrap()); + let mut builder = test_codex().with_model("gpt-5.1"); + let test = builder + .resume(&server, codex_home, session_path.clone()) + .await + .expect("resume conversation"); + test.submit_turn("after resume").await.unwrap(); + + let input = resp_mock.single_request().input(); + + let legacy_output_index = input + .iter() + .position(|item| { + item.get("type").and_then(|value| value.as_str()) == Some("custom_tool_call_output") + && item.get("call_id").and_then(|value| value.as_str()) == Some("legacy-js-call") + }) + .expect("legacy custom tool output should be replayed"); + assert_eq!( + input[legacy_output_index] + .get("output") + .and_then(|value| value.as_str()), + Some("legacy js_repl stdout") + ); + + let legacy_image_index = input + .iter() + .position(|item| { + item.get("type").and_then(|value| value.as_str()) == Some("message") + && item.get("role").and_then(|value| value.as_str()) == Some("user") + && item + .get("content") + .and_then(|value| value.as_array()) + .is_some_and(|content| { + content.iter().any(|entry| { + entry.get("type").and_then(|value| value.as_str()) + == Some("input_image") + && entry.get("image_url").and_then(|value| value.as_str()) + == Some(legacy_image_url) + }) + }) + }) + .expect("legacy injected image message should be replayed"); + + let new_user_index = input + .iter() + .position(|item| { + item.get("type").and_then(|value| value.as_str()) == Some("message") + && item.get("role").and_then(|value| value.as_str()) == Some("user") + && item + .get("content") + .and_then(|value| value.as_array()) + .is_some_and(|content| { + content.iter().any(|entry| { + entry.get("type").and_then(|value| value.as_str()) == Some("input_text") + && entry.get("text").and_then(|value| value.as_str()) + == Some("after resume") + }) + }) + }) + .expect("new user message should be present"); + + assert!(legacy_output_index < new_user_index); + assert!(legacy_image_index < new_user_index); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_conversation_id_and_model_headers_in_request() { skip_if_no_network!(); @@ -584,6 +696,11 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { auth_manager, SessionSource::Exec, config.model_catalog.clone(), + CollaborationModesConfig { + default_mode_request_user_input: config + .features + .enabled(Feature::DefaultModeRequestUserInput), + }, ); let NewThread { thread: codex, .. } = thread_manager .start_thread(config) @@ -658,16 +775,27 @@ async fn includes_user_instructions_message_in_request() { ); assert_message_role(&request_body["input"][1], "user"); - assert_message_starts_with(&request_body["input"][1], "# AGENTS.md instructions for "); - assert_message_ends_with(&request_body["input"][1], ""); - let ui_text = request_body["input"][1]["content"][0]["text"] - .as_str() + let user_context_texts = message_input_texts(&request_body["input"][1]); + assert!( + user_context_texts + .iter() + .any(|text| text.starts_with("# AGENTS.md instructions for ")), + "expected AGENTS text in contextual user message, got {user_context_texts:?}" + ); + let ui_text = user_context_texts + .iter() + .copied() + .find(|text| text.contains("")) .expect("invalid message content"); assert!(ui_text.contains("")); assert!(ui_text.contains("be nice")); - assert_message_role(&request_body["input"][2], "user"); - assert_message_starts_with(&request_body["input"][2], ""); - assert_message_ends_with(&request_body["input"][2], ""); + assert!( + user_context_texts + .iter() + .any(|text| text.starts_with("") + && text.ends_with("")), + "expected environment context in contextual user message, got {user_context_texts:?}" + ); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -721,10 +849,14 @@ async fn includes_apps_guidance_as_developer_message_when_enabled() { && item .get("content") .and_then(|value| value.as_array()) - .and_then(|value| value.first()) - .and_then(|value| value.get("text")) - .and_then(|value| value.as_str()) - .is_some_and(|text| text.contains(apps_snippet)) + .is_some_and(|content| { + content.iter().any(|entry| { + entry + .get("text") + .and_then(|value| value.as_str()) + .is_some_and(|text| text.contains(apps_snippet)) + }) + }) }); assert!( has_developer_apps_guidance, @@ -736,10 +868,14 @@ async fn includes_apps_guidance_as_developer_message_when_enabled() { && item .get("content") .and_then(|value| value.as_array()) - .and_then(|value| value.first()) - .and_then(|value| value.get("text")) - .and_then(|value| value.as_str()) - .is_some_and(|text| text.contains(apps_snippet)) + .is_some_and(|content| { + content.iter().any(|entry| { + entry + .get("text") + .and_then(|value| value.as_str()) + .is_some_and(|text| text.contains(apps_snippet)) + }) + }) }); assert!( !has_user_apps_guidance, @@ -986,7 +1122,12 @@ async fn user_turn_collaboration_mode_overrides_model_and_effort() -> anyhow::Re sandbox_policy: config.permissions.sandbox_policy.get().clone(), model: session_configured.model.clone(), effort: Some(ReasoningEffort::Low), - summary: config.model_reasoning_summary, + summary: Some( + config + .model_reasoning_summary + .unwrap_or(ReasoningSummary::Auto), + ), + service_tier: None, collaboration_mode: Some(collaboration_mode), final_output_json_schema: None, personality: None, @@ -1020,7 +1161,7 @@ async fn configured_reasoning_summary_is_sent() -> anyhow::Result<()> { .await; let TestCodex { codex, .. } = test_codex() .with_config(|config| { - config.model_reasoning_summary = ReasoningSummary::Concise; + config.model_reasoning_summary = Some(ReasoningSummary::Concise); }) .build(&server) .await?; @@ -1052,6 +1193,76 @@ async fn configured_reasoning_summary_is_sent() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn user_turn_explicit_reasoning_summary_overrides_model_catalog_default() -> anyhow::Result<()> +{ + skip_if_no_network!(Ok(())); + let server = MockServer::start().await; + + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let mut model_catalog: ModelsResponse = + serde_json::from_str(include_str!("../../models.json")).expect("valid models.json"); + let model = model_catalog + .models + .iter_mut() + .find(|model| model.slug == "gpt-5.1") + .expect("gpt-5.1 exists in bundled models.json"); + model.supports_reasoning_summaries = true; + model.default_reasoning_summary = ReasoningSummary::Detailed; + + let TestCodex { + codex, + config, + session_configured, + .. + } = test_codex() + .with_model("gpt-5.1") + .with_config(move |config| { + config.model_catalog = Some(model_catalog); + }) + .build(&server) + .await?; + + codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + cwd: config.cwd.clone(), + approval_policy: config.permissions.approval_policy.value(), + sandbox_policy: config.permissions.sandbox_policy.get().clone(), + model: session_configured.model, + effort: None, + summary: Some(ReasoningSummary::Concise), + service_tier: None, + collaboration_mode: None, + final_output_json_schema: None, + personality: None, + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request_body = resp_mock.single_request().body_json(); + + pretty_assertions::assert_eq!( + request_body + .get("reasoning") + .and_then(|reasoning| reasoning.get("summary")) + .and_then(|value| value.as_str()), + Some("concise") + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn reasoning_summary_is_omitted_when_disabled() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); @@ -1064,7 +1275,7 @@ async fn reasoning_summary_is_omitted_when_disabled() -> anyhow::Result<()> { .await; let TestCodex { codex, .. } = test_codex() .with_config(|config| { - config.model_reasoning_summary = ReasoningSummary::None; + config.model_reasoning_summary = Some(ReasoningSummary::None); }) .build(&server) .await?; @@ -1095,6 +1306,60 @@ async fn reasoning_summary_is_omitted_when_disabled() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn reasoning_summary_none_overrides_model_catalog_default() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + let server = MockServer::start().await; + + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let mut model_catalog: ModelsResponse = + serde_json::from_str(include_str!("../../models.json")).expect("valid models.json"); + let model = model_catalog + .models + .iter_mut() + .find(|model| model.slug == "gpt-5.1") + .expect("gpt-5.1 exists in bundled models.json"); + model.supports_reasoning_summaries = true; + model.default_reasoning_summary = ReasoningSummary::Detailed; + + let TestCodex { codex, .. } = test_codex() + .with_model("gpt-5.1") + .with_config(move |config| { + config.model_reasoning_summary = Some(ReasoningSummary::None); + config.model_catalog = Some(model_catalog); + }) + .build(&server) + .await?; + + codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await + .unwrap(); + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request_body = resp_mock.single_request().body_json(); + pretty_assertions::assert_eq!( + request_body + .get("reasoning") + .and_then(|reasoning| reasoning.get("summary")), + None + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_default_verbosity_in_request() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); @@ -1277,19 +1542,42 @@ async fn includes_developer_instructions_message_in_request() { "expected permissions message to mention sandbox_mode, got {permissions_text:?}" ); - assert_message_role(&request_body["input"][1], "developer"); - assert_message_equals(&request_body["input"][1], "be useful"); - assert_message_role(&request_body["input"][2], "user"); - assert_message_starts_with(&request_body["input"][2], "# AGENTS.md instructions for "); - assert_message_ends_with(&request_body["input"][2], ""); - let ui_text = request_body["input"][2]["content"][0]["text"] - .as_str() + let developer_messages: Vec<&serde_json::Value> = request_body["input"] + .as_array() + .expect("input array") + .iter() + .filter(|item| item.get("role").and_then(|role| role.as_str()) == Some("developer")) + .collect(); + assert!( + developer_messages + .iter() + .any(|item| message_input_texts(item).contains(&"be useful")), + "expected developer instructions in a developer message, got {:?}", + request_body["input"] + ); + + assert_message_role(&request_body["input"][1], "user"); + let user_context_texts = message_input_texts(&request_body["input"][1]); + assert!( + user_context_texts + .iter() + .any(|text| text.starts_with("# AGENTS.md instructions for ")), + "expected AGENTS text in contextual user message, got {user_context_texts:?}" + ); + let ui_text = user_context_texts + .iter() + .copied() + .find(|text| text.contains("")) .expect("invalid message content"); assert!(ui_text.contains("")); assert!(ui_text.contains("be nice")); - assert_message_role(&request_body["input"][3], "user"); - assert_message_starts_with(&request_body["input"][3], ""); - assert_message_ends_with(&request_body["input"][3], ""); + assert!( + user_context_texts + .iter() + .any(|text| text.starts_with("") + && text.ends_with("")), + "expected environment context in contextual user message, got {user_context_texts:?}" + ); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -1354,7 +1642,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { provider.clone(), SessionSource::Exec, config.model_verbosity, - None::, + false, false, false, None, @@ -1420,11 +1708,19 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() { }); prompt.input.push(ResponseItem::CustomToolCallOutput { call_id: "custom-tool-call-id".into(), - output: "ok".into(), + output: FunctionCallOutputPayload::from_text("ok".into()), }); let mut stream = client_session - .stream(&prompt, &model_info, &otel_manager, effort, summary, None) + .stream( + &prompt, + &model_info, + &otel_manager, + effort, + summary.unwrap_or(ReasoningSummary::Auto), + None, + None, + ) .await .expect("responses stream to start"); diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 3dec0c4408..b2098c039c 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -16,6 +16,7 @@ use codex_otel::metrics::MetricsConfig; use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::ServiceTier; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; @@ -30,8 +31,6 @@ use core_test_support::responses::WebSocketConnectionConfig; use core_test_support::responses::WebSocketTestServer; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_done; -use core_test_support::responses::ev_done_with_id; use core_test_support::responses::ev_response_created; use core_test_support::responses::start_websocket_server; use core_test_support::responses::start_websocket_server_with_headers; @@ -49,7 +48,6 @@ use tracing_test::traced_test; const MODEL: &str = "gpt-5.2-codex"; const OPENAI_BETA_HEADER: &str = "OpenAI-Beta"; -const OPENAI_BETA_RESPONSES_WEBSOCKETS: &str = "responses_websockets=2026-02-04"; const WS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; struct WebsocketTestHarness { @@ -88,7 +86,7 @@ async fn responses_websocket_streams_request() { let handshake = server.single_handshake(); assert_eq!( handshake.header(OPENAI_BETA_HEADER), - Some(OPENAI_BETA_RESPONSES_WEBSOCKETS.to_string()) + Some(WS_V2_BETA_HEADER_VALUE.to_string()) ); server.shutdown().await; @@ -124,7 +122,7 @@ async fn responses_websocket_request_prewarm_reuses_connection() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ev_response_created("resp-1"), ev_completed("resp-1")], ]]) .await; @@ -140,6 +138,7 @@ async fn responses_websocket_request_prewarm_reuses_connection() { harness.effort, harness.summary, None, + None, ) .await .expect("websocket prewarm failed"); @@ -220,6 +219,7 @@ async fn responses_websocket_preconnect_is_reused_even_with_header_changes() { harness.effort, harness.summary, None, + None, ) .await .expect("websocket stream failed"); @@ -241,7 +241,7 @@ async fn responses_websocket_request_prewarm_is_reused_even_with_header_changes( skip_if_no_network!(); let server = start_websocket_server(vec![vec![ - vec![ev_response_created("warm-1"), ev_done_with_id("warm-1")], + vec![ev_response_created("warm-1"), ev_completed("warm-1")], vec![ev_response_created("resp-1"), ev_completed("resp-1")], ]]) .await; @@ -257,6 +257,7 @@ async fn responses_websocket_request_prewarm_is_reused_even_with_header_changes( harness.effort, harness.summary, None, + None, ) .await .expect("websocket prewarm failed"); @@ -268,6 +269,7 @@ async fn responses_websocket_request_prewarm_is_reused_even_with_header_changes( harness.effort, harness.summary, None, + None, ) .await .expect("websocket stream failed"); @@ -300,7 +302,7 @@ async fn responses_websocket_request_prewarm_is_reused_even_with_header_changes( } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_prewarm_uses_model_preference_when_feature_disabled() { +async fn responses_websocket_prewarm_uses_v2_when_model_prefers_websockets_and_feature_disabled() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![vec![ @@ -320,24 +322,38 @@ async fn responses_websocket_prewarm_uses_model_preference_when_feature_disabled harness.effort, harness.summary, None, + None, ) .await .expect("websocket prewarm failed"); - // V1 prewarm only preconnects and should not issue a request. + // V2 prewarm issues a request on the websocket connection. assert_eq!(server.handshakes().len(), 1); - assert_eq!(server.single_connection().len(), 0); + assert_eq!(server.single_connection().len(), 1); + let handshake = server.single_handshake(); + let openai_beta_header = handshake + .header(OPENAI_BETA_HEADER) + .expect("missing OpenAI-Beta header"); + assert!( + openai_beta_header + .split(',') + .map(str::trim) + .any(|value| value == WS_V2_BETA_HEADER_VALUE) + ); stream_until_complete(&mut client_session, &harness, &prompt).await; assert_eq!(server.handshakes().len(), 1); let connection = server.single_connection(); assert_eq!(connection.len(), 1); - let turn = connection + let prewarm = connection .first() - .expect("missing turn request") + .expect("missing prewarm request") .body_json(); - assert_eq!(turn["type"].as_str(), Some("response.create")); - assert_eq!(turn["input"], serde_json::to_value(&prompt.input).unwrap()); + assert_eq!(prewarm["type"].as_str(), Some("response.create")); + assert_eq!( + prewarm["input"], + serde_json::to_value(&prompt.input).unwrap() + ); server.shutdown().await; } @@ -378,13 +394,6 @@ async fn responses_websocket_preconnect_runs_when_only_v2_feature_enabled() { .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -396,7 +405,7 @@ async fn responses_websocket_v2_requests_use_v2_when_model_prefers_websockets() vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -434,13 +443,6 @@ async fn responses_websocket_v2_requests_use_v2_when_model_prefers_websockets() .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -452,7 +454,7 @@ async fn responses_websocket_v2_incremental_requests_are_reused_across_turns() { vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -496,7 +498,7 @@ async fn responses_websocket_v2_wins_when_both_features_enabled() { vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -534,13 +536,6 @@ async fn responses_websocket_v2_wins_when_both_features_enabled() { .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -673,6 +668,7 @@ async fn responses_websocket_emits_reasoning_included_event() { harness.effort, harness.summary, None, + None, ) .await .expect("websocket stream failed"); @@ -744,6 +740,7 @@ async fn responses_websocket_emits_rate_limit_events() { harness.effort, harness.summary, None, + None, ) .await .expect("websocket stream failed"); @@ -807,7 +804,14 @@ async fn responses_websocket_usage_limit_error_emits_rate_limit_event() { } }); - let server = start_websocket_server(vec![vec![vec![usage_limit_error]]]).await; + let server = start_websocket_server(vec![vec![ + vec![ + ev_response_created("resp-prewarm"), + ev_completed("resp-prewarm"), + ], + vec![usage_limit_error], + ]]) + .await; let mut builder = test_codex().with_config(|config| { config.model_provider.request_max_retries = Some(0); config.model_provider.stream_max_retries = Some(0); @@ -885,7 +889,14 @@ async fn responses_websocket_invalid_request_error_with_status_is_forwarded() { } }); - let server = start_websocket_server(vec![vec![vec![invalid_request_error]]]).await; + let server = start_websocket_server(vec![vec![ + vec![ + ev_response_created("resp-prewarm"), + ev_completed("resp-prewarm"), + ], + vec![invalid_request_error], + ]]) + .await; let mut builder = test_codex().with_config(|config| { config.model_provider.request_max_retries = Some(0); config.model_provider.stream_max_retries = Some(0); @@ -924,14 +935,52 @@ async fn responses_websocket_invalid_request_error_with_status_is_forwarded() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_appends_on_prefix() { +async fn responses_websocket_connection_limit_error_reconnects_and_completes() { + skip_if_no_network!(); + + let websocket_connection_limit_error = json!({ + "type": "error", + "status": 400, + "error": { + "type": "invalid_request_error", + "code": "websocket_connection_limit_reached", + "message": "Responses websocket connection limit reached (60 minutes). Create a new websocket connection to continue." + } + }); + + let server = start_websocket_server(vec![ + vec![vec![websocket_connection_limit_error]], + vec![vec![ev_response_created("resp-1"), ev_completed("resp-1")]], + ]) + .await; + let mut builder = test_codex().with_config(|config| { + config.model_provider.request_max_retries = Some(0); + config.model_provider.stream_max_retries = Some(1); + }); + let test = builder + .build_with_websocket_server(&server) + .await + .expect("build websocket codex"); + + test.submit_turn("hello") + .await + .expect("submission should reconnect after websocket connection limit error"); + + let total_websocket_requests: usize = server.connections().iter().map(Vec::len).sum(); + assert_eq!(total_websocket_requests, 2); + + server.shutdown().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_websocket_uses_incremental_create_on_prefix() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done(), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -958,24 +1007,25 @@ async fn responses_websocket_appends_on_prefix() { assert_eq!(first["model"].as_str(), Some(MODEL)); assert_eq!(first["stream"], serde_json::Value::Bool(true)); assert_eq!(first["input"].as_array().map(Vec::len), Some(1)); - let expected_append = serde_json::json!({ - "type": "response.append", - "input": serde_json::to_value(&prompt_two.input[2..]).expect("serialize append items"), - }); - assert_eq!(second, expected_append); + assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); + assert_eq!( + second["input"], + serde_json::to_value(&prompt_two.input[2..]).expect("serialize incremental items") + ); server.shutdown().await; } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { +async fn responses_websocket_forwards_turn_metadata_on_initial_and_incremental_create() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done(), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -996,6 +1046,7 @@ async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { &mut client_session, &harness, &prompt_one, + None, Some(first_turn_metadata), ) .await; @@ -1003,6 +1054,7 @@ async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { &mut client_session, &harness, &prompt_two, + None, Some(enriched_turn_metadata), ) .await; @@ -1017,7 +1069,8 @@ async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { first["client_metadata"]["x-codex-turn-metadata"].as_str(), Some(first_turn_metadata) ); - assert_eq!(second["type"].as_str(), Some("response.append")); + assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); assert_eq!( second["client_metadata"]["x-codex-turn-metadata"].as_str(), Some(enriched_turn_metadata) @@ -1039,7 +1092,7 @@ async fn responses_websocket_forwards_turn_metadata_on_create_and_append() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn responses_websocket_creates_on_prefix_when_previous_completion_cannot_append() { +async fn responses_websocket_uses_previous_response_id_when_prefix_after_completed() { skip_if_no_network!(); let server = start_websocket_server(vec![vec![ @@ -1069,9 +1122,10 @@ async fn responses_websocket_creates_on_prefix_when_previous_completion_cannot_a let second = connection.get(1).expect("missing request").body_json(); assert_eq!(second["type"].as_str(), Some("response.create")); + assert_eq!(second["previous_response_id"].as_str(), Some("resp-1")); assert_eq!( second["input"], - serde_json::to_value(&prompt_two.input).expect("serialize full input") + serde_json::to_value(&prompt_two.input[2..]).expect("serialize incremental input") ); server.shutdown().await; @@ -1154,7 +1208,7 @@ async fn responses_websocket_v2_creates_with_previous_response_id_on_prefix() { vec![ ev_response_created("resp-1"), ev_assistant_message("msg-1", "assistant output"), - ev_done_with_id("resp-1"), + ev_completed("resp-1"), ], vec![ev_response_created("resp-2"), ev_completed("resp-2")], ]]) @@ -1266,6 +1320,7 @@ async fn responses_websocket_v2_after_error_uses_full_create_without_previous_re harness.effort, harness.summary, None, + None, ) .await .expect("websocket stream failed"); @@ -1340,13 +1395,6 @@ async fn responses_websocket_v2_sets_openai_beta_header() { .map(str::trim) .any(|value| value == WS_V2_BETA_HEADER_VALUE) ); - assert!( - !openai_beta_header - .split(',') - .map(str::trim) - .any(|value| value == OPENAI_BETA_RESPONSES_WEBSOCKETS) - ); - server.shutdown().await; } @@ -1497,13 +1545,24 @@ async fn stream_until_complete( harness: &WebsocketTestHarness, prompt: &Prompt, ) { - stream_until_complete_with_turn_metadata(client_session, harness, prompt, None).await; + stream_until_complete_with_service_tier(client_session, harness, prompt, None).await; +} + +async fn stream_until_complete_with_service_tier( + client_session: &mut ModelClientSession, + harness: &WebsocketTestHarness, + prompt: &Prompt, + service_tier: Option, +) { + stream_until_complete_with_turn_metadata(client_session, harness, prompt, service_tier, None) + .await; } async fn stream_until_complete_with_turn_metadata( client_session: &mut ModelClientSession, harness: &WebsocketTestHarness, prompt: &Prompt, + service_tier: Option, turn_metadata_header: Option<&str>, ) { let mut stream = client_session @@ -1513,6 +1572,7 @@ async fn stream_until_complete_with_turn_metadata( &harness.otel_manager, harness.effort, harness.summary, + service_tier, turn_metadata_header, ) .await diff --git a/codex-rs/core/tests/suite/collaboration_instructions.rs b/codex-rs/core/tests/suite/collaboration_instructions.rs index 68d695325d..781f226cb5 100644 --- a/codex-rs/core/tests/suite/collaboration_instructions.rs +++ b/codex-rs/core/tests/suite/collaboration_instructions.rs @@ -119,6 +119,7 @@ async fn user_input_includes_collaboration_instructions_after_override() -> Resu model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -169,7 +170,12 @@ async fn collaboration_instructions_added_on_user_turn() -> Result<()> { sandbox_policy: test.config.permissions.sandbox_policy.get().clone(), model: test.session_configured.model.clone(), effort: None, - summary: test.config.model_reasoning_summary, + summary: Some( + test.config + .model_reasoning_summary + .unwrap_or(codex_protocol::config_types::ReasoningSummary::Auto), + ), + service_tier: None, collaboration_mode: Some(collaboration_mode), final_output_json_schema: None, personality: None, @@ -209,6 +215,7 @@ async fn override_then_next_turn_uses_updated_collaboration_instructions() -> Re model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -259,6 +266,7 @@ async fn user_turn_overrides_collaboration_instructions_after_override() -> Resu model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(base_mode), personality: None, }) @@ -275,7 +283,12 @@ async fn user_turn_overrides_collaboration_instructions_after_override() -> Resu sandbox_policy: test.config.permissions.sandbox_policy.get().clone(), model: test.session_configured.model.clone(), effort: None, - summary: test.config.model_reasoning_summary, + summary: Some( + test.config + .model_reasoning_summary + .unwrap_or(codex_protocol::config_types::ReasoningSummary::Auto), + ), + service_tier: None, collaboration_mode: Some(turn_mode), final_output_json_schema: None, personality: None, @@ -322,6 +335,7 @@ async fn collaboration_mode_update_emits_new_instruction_message() -> Result<()> model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_instructions(Some(first_text))), personality: None, }) @@ -347,6 +361,7 @@ async fn collaboration_mode_update_emits_new_instruction_message() -> Result<()> model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_instructions(Some(second_text))), personality: None, }) @@ -401,6 +416,7 @@ async fn collaboration_mode_update_noop_does_not_append() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_instructions(Some(collab_text))), personality: None, }) @@ -426,6 +442,7 @@ async fn collaboration_mode_update_noop_does_not_append() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_instructions(Some(collab_text))), personality: None, }) @@ -479,6 +496,7 @@ async fn collaboration_mode_update_emits_new_instruction_message_when_mode_chang model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_mode_and_instructions( ModeKind::Default, Some(default_text), @@ -507,6 +525,7 @@ async fn collaboration_mode_update_emits_new_instruction_message_when_mode_chang model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_mode_and_instructions( ModeKind::Plan, Some(plan_text), @@ -564,6 +583,7 @@ async fn collaboration_mode_update_noop_does_not_append_when_mode_is_unchanged() model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_mode_and_instructions( ModeKind::Default, Some(collab_text), @@ -592,6 +612,7 @@ async fn collaboration_mode_update_noop_does_not_append_when_mode_is_unchanged() model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_mode_and_instructions( ModeKind::Default, Some(collab_text), @@ -655,6 +676,7 @@ async fn resume_replays_collaboration_instructions() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collab_mode_with_instructions(Some(collab_text))), personality: None, }) @@ -716,6 +738,7 @@ async fn empty_collaboration_instructions_are_ignored() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(CollaborationMode { mode: ModeKind::Default, settings: Settings { diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 9e9ce931e9..ac6ffc915d 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -5,7 +5,6 @@ use codex_core::built_in_model_providers; use codex_core::compact::SUMMARIZATION_PROMPT; use codex_core::compact::SUMMARY_PREFIX; use codex_core::config::Config; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::items::TurnItem; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelsResponse; @@ -363,7 +362,7 @@ async fn summarize_context_three_requests_and_instructions() { codex.submit(Op::Shutdown).await.unwrap(); wait_for_event(&codex, |ev| matches!(ev, EventMsg::ShutdownComplete)).await; - // Verify rollout contains regular sampling TurnContext entries and a Compacted entry. + // Verify rollout contains user-turn TurnContext entries and a Compacted entry. println!("rollout path: {}", rollout_path.display()); let text = std::fs::read_to_string(&rollout_path).unwrap_or_else(|e| { panic!( @@ -394,9 +393,9 @@ async fn summarize_context_three_requests_and_instructions() { } } - assert!( - regular_turn_context_count == 2, - "expected two regular sampling TurnContext entries in rollout" + assert_eq!( + regular_turn_context_count, 2, + "rollout should contain one TurnContext entry per real user turn" ); assert!( saw_compacted_summary, @@ -756,16 +755,40 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { let body = requests_payloads[0].body_json(); let input = body.get("input").and_then(|v| v.as_array()).unwrap(); + fn strip_agents_parts_from_user_message( + value: &serde_json::Value, + ) -> Option { + let content = value + .get("content") + .and_then(|content| content.as_array())?; + let filtered_content = content + .iter() + .filter(|item| { + !item + .get("text") + .and_then(|text| text.as_str()) + .is_some_and(|text| text.starts_with("# AGENTS.md instructions for ")) + }) + .cloned() + .collect::>(); + if filtered_content.is_empty() { + return None; + } + let mut normalized = value.clone(); + normalized["content"] = serde_json::Value::Array(filtered_content); + Some(normalized) + } + fn normalize_inputs(values: &[serde_json::Value]) -> Vec { values .iter() - .filter(|value| { + .filter_map(|value| { if value .get("type") .and_then(|ty| ty.as_str()) .is_some_and(|ty| ty == "function_call_output") { - return false; + return None; } let text = value @@ -781,11 +804,13 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { if role == Some("developer") && text.is_some_and(|text| text.contains("`sandbox_mode`")) { - return false; + return None; } - !text.is_some_and(|text| text.starts_with("# AGENTS.md instructions for ")) + if role == Some("user") { + return strip_agents_parts_from_user_message(value); + } + Some(value.clone()) }) - .cloned() .collect() } @@ -1633,7 +1658,8 @@ async fn auto_compact_runs_after_resume_when_token_usage_is_over_limit() { sandbox_policy: SandboxPolicy::DangerFullAccess, model: resumed.session_configured.model.clone(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1722,7 +1748,8 @@ async fn pre_sampling_compact_runs_on_switch_to_smaller_context_model() { sandbox_policy: SandboxPolicy::DangerFullAccess, model: previous_model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1745,7 +1772,8 @@ async fn pre_sampling_compact_runs_on_switch_to_smaller_context_model() { sandbox_policy: SandboxPolicy::DangerFullAccess, model: next_model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1854,7 +1882,8 @@ async fn pre_sampling_compact_runs_after_resume_and_switch_to_smaller_model() { sandbox_policy: SandboxPolicy::DangerFullAccess, model: previous_model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1901,7 +1930,8 @@ async fn pre_sampling_compact_runs_after_resume_and_switch_to_smaller_model() { sandbox_policy: SandboxPolicy::DangerFullAccess, model: next_model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2055,9 +2085,9 @@ async fn auto_compact_persists_rollout_entries() { } } - assert!( - turn_context_count >= 2, - "expected at least two turn context entries, got {turn_context_count}" + assert_eq!( + turn_context_count, 3, + "rollout should contain one TurnContext entry per real user turn" ); } @@ -2987,6 +3017,7 @@ async fn snapshot_request_shape_pre_turn_compaction_including_incoming_user_mess model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -3102,7 +3133,8 @@ async fn snapshot_request_shape_pre_turn_compaction_strips_incoming_model_switch sandbox_policy: SandboxPolicy::DangerFullAccess, model: previous_model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -3125,7 +3157,8 @@ async fn snapshot_request_shape_pre_turn_compaction_strips_incoming_model_switch sandbox_policy: SandboxPolicy::DangerFullAccess, model: next_model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -3184,7 +3217,7 @@ async fn snapshot_request_shape_pre_turn_compaction_context_window_exceeded() { ]); let mut responses = vec![first_turn]; responses.extend( - (0..6).map(|_| { + (0..5).map(|_| { sse_failed( "compact-failed", "context_length_exceeded", diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index 1d450f9b11..b336ce100e 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -9,10 +9,14 @@ use codex_core::compact::SUMMARY_PREFIX; use codex_protocol::items::TurnItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::ConversationStartParams; +use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ItemCompletedEvent; use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::Op; +use codex_protocol::protocol::RealtimeConversationRealtimeEvent; +use codex_protocol::protocol::RealtimeEvent; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::user_input::UserInput; @@ -22,12 +26,15 @@ use core_test_support::context_snapshot::ContextSnapshotRenderMode; use core_test_support::responses; use core_test_support::responses::mount_sse_once; use core_test_support::responses::sse; +use core_test_support::responses::start_websocket_server; use core_test_support::skip_if_no_network; +use core_test_support::test_codex::TestCodexBuilder; use core_test_support::test_codex::TestCodexHarness; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; +use serde_json::json; use wiremock::ResponseTemplate; fn approx_token_count(text: &str) -> i64 { @@ -68,6 +75,104 @@ fn format_labeled_requests_snapshot( ) } +fn compacted_summary_only_output(summary: &str) -> Vec { + vec![ResponseItem::Compaction { + encrypted_content: summary_with_prefix(summary), + }] +} + +fn remote_realtime_test_codex_builder( + realtime_server: &responses::WebSocketTestServer, +) -> TestCodexBuilder { + let realtime_base_url = realtime_server.uri().to_string(); + test_codex() + .with_auth(CodexAuth::from_api_key("dummy")) + .with_config(move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + }) +} + +async fn start_remote_realtime_server() -> responses::WebSocketTestServer { + start_websocket_server(vec![vec![ + vec![json!({ + "type": "session.updated", + "session": { "id": "sess_remote_compact", "instructions": "backend prompt" } + })], + // Keep the websocket open after startup so routed transcript items during the test do not + // exhaust the scripted responses and mark realtime inactive before the assertions run. + vec![], + vec![], + vec![], + vec![], + vec![], + vec![], + vec![], + vec![], + ]]) + .await +} + +async fn start_realtime_conversation(codex: &codex_core::CodexThread) -> Result<()> { + codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + wait_for_event_match(codex, |msg| match msg { + EventMsg::RealtimeConversationStarted(started) => Some(Ok(started.clone())), + EventMsg::Error(err) => Some(Err(err.clone())), + _ => None, + }) + .await + .unwrap_or_else(|err: ErrorEvent| panic!("conversation start failed: {err:?}")); + + wait_for_event_match(codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionUpdated { session_id, .. }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + + Ok(()) +} + +async fn close_realtime_conversation(codex: &codex_core::CodexThread) -> Result<()> { + codex.submit(Op::RealtimeConversationClose).await?; + wait_for_event_match(codex, |msg| match msg { + EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()), + _ => None, + }) + .await; + Ok(()) +} + +fn assert_request_contains_realtime_start(request: &responses::ResponsesRequest) { + let body = request.body_json().to_string(); + assert!( + body.contains(""), + "expected request to restate realtime instructions" + ); + assert!( + !body.contains("Reason: inactive"), + "expected request to use realtime start instructions" + ); +} + +fn assert_request_contains_realtime_end(request: &responses::ResponsesRequest) { + let body = request.body_json().to_string(); + assert!( + body.contains(""), + "expected request to restate realtime instructions" + ); + assert!( + body.contains("Reason: inactive"), + "expected request to use realtime end instructions" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn remote_compact_replaces_history_for_followups() -> Result<()> { skip_if_no_network!(Ok(())); @@ -77,6 +182,7 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { ) .await?; let codex = harness.test().codex.clone(); + let session_id = harness.test().session_configured.session_id.to_string(); let responses_mock = responses::mount_sse_sequence( harness.server(), @@ -137,6 +243,10 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> { compact_request.header("authorization").as_deref(), Some("Bearer Access Token") ); + assert_eq!( + compact_request.header("session_id").as_deref(), + Some(session_id.as_str()) + ); let compact_body = compact_request.body_json(); assert_eq!( compact_body.get("model").and_then(|v| v.as_str()), @@ -195,6 +305,7 @@ async fn remote_compact_runs_automatically() -> Result<()> { ) .await?; let codex = harness.test().codex.clone(); + let session_id = harness.test().session_configured.session_id.to_string(); mount_sse_once( harness.server(), @@ -237,6 +348,13 @@ async fn remote_compact_runs_automatically() -> Result<()> { wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await; assert!(message); assert_eq!(compact_mock.requests().len(), 1); + assert_eq!( + compact_mock + .single_request() + .header("session_id") + .as_deref(), + Some(session_id.as_str()) + ); let follow_up_request = responses_mock.single_request(); let follow_up_body = follow_up_request.body_json().to_string(); assert!(follow_up_body.contains("REMOTE_COMPACTED_SUMMARY")); @@ -1292,6 +1410,470 @@ async fn remote_compact_refreshes_stale_developer_instructions_without_resume() Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_request_shape_remote_pre_turn_compaction_restates_realtime_start() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = wiremock::MockServer::start().await; + let realtime_server = start_remote_realtime_server().await; + let mut builder = remote_realtime_test_codex_builder(&realtime_server).with_config(|config| { + config.model_auto_compact_token_limit = Some(200); + }); + let test = builder.build(&server).await?; + + let responses_mock = responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_assistant_message("m1", "REMOTE_FIRST_REPLY"), + responses::ev_completed_with_tokens("r1", 500), + ]), + responses::sse(vec![ + responses::ev_assistant_message("m2", "REMOTE_SECOND_REPLY"), + responses::ev_completed_with_tokens("r2", 80), + ]), + ], + ) + .await; + let compact_mock = responses::mount_compact_json_once( + &server, + serde_json::json!({ + "output": compacted_summary_only_output( + "REMOTE_PRETURN_REALTIME_STILL_ACTIVE_SUMMARY" + ) + }), + ) + .await; + + start_realtime_conversation(test.codex.as_ref()).await?; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_ONE".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_TWO".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + assert_eq!(compact_mock.requests().len(), 1); + let requests = responses_mock.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let compact_request = compact_mock.single_request(); + let post_compact_request = &requests[1]; + assert_request_contains_realtime_start(post_compact_request); + + insta::assert_snapshot!( + "remote_pre_turn_compaction_restates_realtime_start_shapes", + format_labeled_requests_snapshot( + "Remote pre-turn auto-compaction while realtime remains active: compaction clears the reference baseline, so the follow-up request restates realtime-start instructions.", + &[ + ("Remote Compaction Request", &compact_request), + ( + "Remote Post-Compaction History Layout", + post_compact_request + ), + ] + ) + ); + + close_realtime_conversation(test.codex.as_ref()).await?; + realtime_server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_request_shape_remote_pre_turn_compaction_restates_realtime_end() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = wiremock::MockServer::start().await; + let realtime_server = start_remote_realtime_server().await; + let mut builder = remote_realtime_test_codex_builder(&realtime_server).with_config(|config| { + config.model_auto_compact_token_limit = Some(200); + }); + let test = builder.build(&server).await?; + + let responses_mock = responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_assistant_message("m1", "REMOTE_FIRST_REPLY"), + responses::ev_completed_with_tokens("r1", 500), + ]), + responses::sse(vec![ + responses::ev_assistant_message("m2", "REMOTE_SECOND_REPLY"), + responses::ev_completed_with_tokens("r2", 80), + ]), + ], + ) + .await; + let compact_mock = responses::mount_compact_json_once( + &server, + serde_json::json!({ + "output": compacted_summary_only_output( + "REMOTE_PRETURN_REALTIME_CLOSED_SUMMARY" + ) + }), + ) + .await; + + start_realtime_conversation(test.codex.as_ref()).await?; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_ONE".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + close_realtime_conversation(test.codex.as_ref()).await?; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_TWO".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + assert_eq!(compact_mock.requests().len(), 1); + let requests = responses_mock.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let compact_request = compact_mock.single_request(); + let post_compact_request = &requests[1]; + assert_request_contains_realtime_end(post_compact_request); + + insta::assert_snapshot!( + "remote_pre_turn_compaction_restates_realtime_end_shapes", + format_labeled_requests_snapshot( + "Remote pre-turn auto-compaction after realtime was closed between turns: the follow-up request emits realtime-end instructions from previous-turn settings even though compaction cleared the reference baseline.", + &[ + ("Remote Compaction Request", &compact_request), + ( + "Remote Post-Compaction History Layout", + post_compact_request + ), + ] + ) + ); + + realtime_server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_request_shape_remote_manual_compact_restates_realtime_start() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = wiremock::MockServer::start().await; + let realtime_server = start_remote_realtime_server().await; + let mut builder = remote_realtime_test_codex_builder(&realtime_server); + let test = builder.build(&server).await?; + + let responses_mock = responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_assistant_message("m1", "REMOTE_FIRST_REPLY"), + responses::ev_completed_with_tokens("r1", 60), + ]), + responses::sse(vec![ + responses::ev_assistant_message("m2", "REMOTE_SECOND_REPLY"), + responses::ev_completed_with_tokens("r2", 80), + ]), + ], + ) + .await; + let compact_mock = responses::mount_compact_json_once( + &server, + serde_json::json!({ + "output": compacted_summary_only_output( + "REMOTE_MANUAL_REALTIME_STILL_ACTIVE_SUMMARY" + ) + }), + ) + .await; + + start_realtime_conversation(test.codex.as_ref()).await?; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_ONE".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + test.codex.submit(Op::Compact).await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_TWO".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + assert_eq!(compact_mock.requests().len(), 1); + let requests = responses_mock.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let compact_request = compact_mock.single_request(); + let post_compact_request = &requests[1]; + assert_request_contains_realtime_start(post_compact_request); + + insta::assert_snapshot!( + "remote_manual_compact_restates_realtime_start_shapes", + format_labeled_requests_snapshot( + "Remote manual /compact while realtime remains active: the next regular turn restates realtime-start instructions after compaction clears the baseline.", + &[ + ("Remote Compaction Request", &compact_request), + ( + "Remote Post-Compaction History Layout", + post_compact_request + ), + ] + ) + ); + + close_realtime_conversation(test.codex.as_ref()).await?; + realtime_server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_request_shape_remote_mid_turn_compaction_does_not_restate_realtime_end() +-> Result<()> { + skip_if_no_network!(Ok(())); + + let server = wiremock::MockServer::start().await; + let realtime_server = start_remote_realtime_server().await; + let mut builder = remote_realtime_test_codex_builder(&realtime_server).with_config(|config| { + config.model_auto_compact_token_limit = Some(200); + }); + let test = builder.build(&server).await?; + + let responses_mock = responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_assistant_message("setup", "REMOTE_SETUP_REPLY"), + responses::ev_completed_with_tokens("setup-response", 60), + ]), + responses::sse(vec![ + responses::ev_function_call("call-remote-mid-turn", DUMMY_FUNCTION_NAME, "{}"), + responses::ev_completed_with_tokens("r1", 500), + ]), + responses::sse(vec![ + responses::ev_assistant_message("m2", "REMOTE_MID_TURN_FINAL_REPLY"), + responses::ev_completed_with_tokens("r2", 80), + ]), + ], + ) + .await; + let compact_mock = responses::mount_compact_json_once( + &server, + serde_json::json!({ + "output": compacted_summary_only_output( + "REMOTE_MID_TURN_REALTIME_CLOSED_SUMMARY" + ) + }), + ) + .await; + + start_realtime_conversation(test.codex.as_ref()).await?; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "SETUP_USER".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + close_realtime_conversation(test.codex.as_ref()).await?; + + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_TWO".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + assert_eq!(compact_mock.requests().len(), 1); + let requests = responses_mock.requests(); + assert_eq!(requests.len(), 3, "expected three model requests"); + + let second_turn_request = &requests[1]; + let compact_request = compact_mock.single_request(); + let post_compact_request = &requests[2]; + assert_request_contains_realtime_end(second_turn_request); + assert!( + !post_compact_request + .body_json() + .to_string() + .contains(""), + "did not expect post-compaction history to restate realtime instructions once the current turn had already established an inactive baseline" + ); + + insta::assert_snapshot!( + "remote_mid_turn_compaction_does_not_restate_realtime_end_shapes", + format_labeled_requests_snapshot( + "Remote mid-turn continuation compaction after realtime was closed before the turn: the initial second-turn request emits realtime-end instructions, but the continuation request does not restate them after compaction because the current turn already established the inactive baseline.", + &[ + ("Second Turn Initial Request", second_turn_request), + ("Remote Compaction Request", &compact_request), + ( + "Remote Post-Compaction History Layout", + post_compact_request + ), + ] + ) + ); + + realtime_server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_request_shape_remote_compact_resume_restates_realtime_end() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = wiremock::MockServer::start().await; + let realtime_server = start_remote_realtime_server().await; + let mut builder = remote_realtime_test_codex_builder(&realtime_server); + let initial = builder.build(&server).await?; + let home = initial.home.clone(); + let rollout_path = initial + .session_configured + .rollout_path + .clone() + .expect("rollout path"); + + let responses_mock = responses::mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ + responses::ev_assistant_message("m1", "REMOTE_FIRST_REPLY"), + responses::ev_completed_with_tokens("r1", 60), + ]), + responses::sse(vec![ + responses::ev_assistant_message("m2", "REMOTE_AFTER_RESUME_REPLY"), + responses::ev_completed_with_tokens("r2", 80), + ]), + ], + ) + .await; + let compact_mock = responses::mount_compact_json_once( + &server, + serde_json::json!({ + "output": compacted_summary_only_output( + "REMOTE_RESUME_REALTIME_CLOSED_SUMMARY" + ) + }), + ) + .await; + + start_realtime_conversation(initial.codex.as_ref()).await?; + + initial + .codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_ONE".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&initial.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + close_realtime_conversation(initial.codex.as_ref()).await?; + + initial.codex.submit(Op::Compact).await?; + wait_for_event(&initial.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + initial.codex.submit(Op::Shutdown).await?; + wait_for_event(&initial.codex, |ev| { + matches!(ev, EventMsg::ShutdownComplete) + }) + .await; + + let mut resume_builder = + test_codex().with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()); + let resumed = resume_builder.resume(&server, home, rollout_path).await?; + + resumed + .codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "USER_TWO".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + wait_for_event(&resumed.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + assert_eq!(compact_mock.requests().len(), 1); + let requests = responses_mock.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let compact_request = compact_mock.single_request(); + let after_resume_request = &requests[1]; + assert_request_contains_realtime_end(after_resume_request); + + insta::assert_snapshot!( + "remote_compact_resume_restates_realtime_end_shapes", + format_labeled_requests_snapshot( + "After remote manual /compact and resume, the first resumed turn rebuilds history from the compaction item and restates realtime-end instructions from reconstructed previous-turn settings.", + &[ + ("Remote Compaction Request", &compact_request), + ("Remote Post-Resume History Layout", after_resume_request), + ] + ) + ); + + realtime_server.shutdown().await; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] // TODO(ccunningham): Update once remote pre-turn compaction includes incoming user input. async fn snapshot_request_shape_remote_pre_turn_compaction_including_incoming_user_message() @@ -1344,6 +1926,7 @@ async fn snapshot_request_shape_remote_pre_turn_compaction_including_incoming_us model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1453,6 +2036,7 @@ async fn snapshot_request_shape_remote_pre_turn_compaction_strips_incoming_model model: Some(next_model.to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index b6f78267b6..6546600681 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -33,7 +33,6 @@ async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/image_rollout.rs b/codex-rs/core/tests/suite/image_rollout.rs index 2349d9f5fa..07b51c7629 100644 --- a/codex-rs/core/tests/suite/image_rollout.rs +++ b/codex-rs/core/tests/suite/image_rollout.rs @@ -1,5 +1,4 @@ use anyhow::Context; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::AskForApproval; @@ -126,7 +125,8 @@ async fn copy_paste_local_image_persists_rollout_request_shape() -> anyhow::Resu sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -208,7 +208,8 @@ async fn drag_drop_image_persists_rollout_request_shape() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index 0d93278af1..af1a83f53b 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -377,7 +377,8 @@ async fn plan_mode_emits_plan_item_from_proposed_plan_block() -> anyhow::Result< sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -452,7 +453,8 @@ async fn plan_mode_strips_plan_from_agent_messages() -> anyhow::Result<()> { sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -559,7 +561,8 @@ async fn plan_mode_streaming_citations_are_stripped_across_added_deltas_and_done sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -744,7 +747,8 @@ async fn plan_mode_streaming_proposed_plan_tag_split_across_added_and_delta_is_p sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -856,7 +860,8 @@ async fn plan_mode_handles_missing_plan_close_tag() -> anyhow::Result<()> { sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) diff --git a/codex-rs/core/tests/suite/js_repl.rs b/codex-rs/core/tests/suite/js_repl.rs index ba2b52fd6d..31dbe6e60a 100644 --- a/codex-rs/core/tests/suite/js_repl.rs +++ b/codex-rs/core/tests/suite/js_repl.rs @@ -2,6 +2,7 @@ use anyhow::Result; use codex_core::features::Feature; +use codex_protocol::protocol::EventMsg; use core_test_support::responses; use core_test_support::responses::ResponseMock; use core_test_support::responses::ResponsesRequest; @@ -12,6 +13,12 @@ use core_test_support::responses::ev_response_created; use core_test_support::responses::sse; use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event_match; +use std::fs; +#[cfg(unix)] +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use tempfile::tempdir; use wiremock::MockServer; fn custom_tool_output_text_and_success( @@ -24,6 +31,45 @@ fn custom_tool_output_text_and_success( (output.unwrap_or_default(), success) } +fn tool_names(body: &serde_json::Value) -> Vec { + body["tools"] + .as_array() + .expect("tools array should be present") + .iter() + .map(|tool| { + tool.get("name") + .and_then(|value| value.as_str()) + .or_else(|| tool.get("type").and_then(|value| value.as_str())) + .expect("tool should have a name or type") + .to_string() + }) + .collect() +} + +fn write_too_old_node_script(dir: &Path) -> Result { + #[cfg(windows)] + { + let path = dir.join("old-node.cmd"); + fs::write(&path, "@echo off\r\necho v0.0.1\r\n")?; + Ok(path) + } + + #[cfg(unix)] + { + let path = dir.join("old-node.sh"); + fs::write(&path, "#!/bin/sh\necho v0.0.1\n")?; + let mut permissions = fs::metadata(&path)?.permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&path, permissions)?; + Ok(path) + } + + #[cfg(not(any(unix, windows)))] + { + anyhow::bail!("unsupported platform for js_repl test fixture"); + } +} + async fn run_js_repl_turn( server: &MockServer, prompt: &str, @@ -54,6 +100,64 @@ async fn run_js_repl_turn( Ok(second_mock) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn js_repl_is_not_advertised_when_startup_node_is_incompatible() -> Result<()> { + skip_if_no_network!(Ok(())); + if std::env::var_os("CODEX_JS_REPL_NODE_PATH").is_some() { + return Ok(()); + } + + let server = responses::start_mock_server().await; + let temp = tempdir()?; + let old_node = write_too_old_node_script(temp.path())?; + + let mut builder = test_codex().with_config(move |config| { + config.features.enable(Feature::JsRepl); + config.js_repl_node_path = Some(old_node); + }); + let test = builder.build(&server).await?; + let warning = wait_for_event_match(&test.codex, |event| match event { + EventMsg::Warning(ev) if ev.message.contains("Disabled `js_repl` for this session") => { + Some(ev.message.clone()) + } + _ => None, + }) + .await; + assert!( + warning.contains("Node runtime"), + "warning should explain the Node compatibility issue: {warning}" + ); + + let request_mock = responses::mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-1"), + ]), + ) + .await; + + test.submit_turn("hello").await?; + + let body = request_mock.single_request().body_json(); + let tools = tool_names(&body); + assert!( + !tools.iter().any(|tool| tool == "js_repl"), + "js_repl should be omitted when startup validation fails: {tools:?}" + ); + assert!( + !tools.iter().any(|tool| tool == "js_repl_reset"), + "js_repl_reset should be omitted when startup validation fails: {tools:?}" + ); + let instructions = body["instructions"].as_str().unwrap_or_default(); + assert!( + !instructions.contains("## JavaScript REPL (Node)"), + "startup instructions should not mention js_repl when it is disabled: {instructions}" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn js_repl_persists_top_level_bindings_and_supports_tla() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/tests/suite/json_result.rs b/codex-rs/core/tests/suite/json_result.rs index e32865e0c7..f7dfd02daf 100644 --- a/codex-rs/core/tests/suite/json_result.rs +++ b/codex-rs/core/tests/suite/json_result.rs @@ -1,6 +1,5 @@ #![cfg(not(target_os = "windows"))] -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -84,7 +83,8 @@ async fn codex_returns_json_result(model: String) -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/live_reload.rs b/codex-rs/core/tests/suite/live_reload.rs index 3ea0a3cbe9..2192bdffd9 100644 --- a/codex-rs/core/tests/suite/live_reload.rs +++ b/codex-rs/core/tests/suite/live_reload.rs @@ -7,7 +7,6 @@ use std::time::Duration; use anyhow::Result; use codex_core::config::ProjectConfig; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::TrustLevel; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -65,7 +64,8 @@ async fn submit_skill_turn(test: &TestCodex, skill_path: PathBuf, prompt: &str) sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/memories.rs b/codex-rs/core/tests/suite/memories.rs new file mode 100644 index 0000000000..80e2d6ff6d --- /dev/null +++ b/codex-rs/core/tests/suite/memories.rs @@ -0,0 +1,461 @@ +use anyhow::Result; +use chrono::Duration as ChronoDuration; +use chrono::Utc; +use codex_core::features::Feature; +use codex_protocol::ThreadId; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SessionSource; +use core_test_support::responses::ResponseMock; +use core_test_support::responses::ResponsesRequest; +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::ev_web_search_call_done; +use core_test_support::responses::mount_sse_once; +use core_test_support::responses::mount_sse_sequence; +use core_test_support::responses::sse; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::TestCodex; +use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event; +use pretty_assertions::assert_eq; +use std::path::Path; +use std::sync::Arc; +use tempfile::TempDir; +use tokio::time::Duration; +use tokio::time::Instant; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn memories_startup_phase2_tracks_added_and_removed_inputs_across_runs() -> Result<()> { + let server = start_mock_server().await; + let home = Arc::new(TempDir::new()?); + let db = init_state_db(&home).await?; + + let now = Utc::now(); + let thread_a = seed_stage1_output( + db.as_ref(), + home.path(), + now - ChronoDuration::hours(2), + "raw memory A", + "rollout summary A", + "rollout-a", + ) + .await?; + + let first_phase2 = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-phase2-1"), + ev_assistant_message("msg-phase2-1", "phase2 complete"), + ev_completed("resp-phase2-1"), + ]), + ) + .await; + + let first = build_test_codex(&server, home.clone()).await?; + let first_request = wait_for_single_request(&first_phase2).await; + let first_prompt = phase2_prompt_text(&first_request); + assert!( + first_prompt.contains("- selected inputs this run: 1"), + "expected selected count in first prompt: {first_prompt}" + ); + assert!( + first_prompt.contains("- newly added since the last successful Phase 2 run: 1"), + "expected added count in first prompt: {first_prompt}" + ); + assert!( + first_prompt.contains("- removed from the last successful Phase 2 run: 0"), + "expected removed count in first prompt: {first_prompt}" + ); + assert!( + first_prompt.contains(&format!("- [added] thread_id={thread_a},")), + "expected thread A to be marked added: {first_prompt}" + ); + assert!( + first_prompt.contains("Removed from the last successful Phase 2 selection:\n- none"), + "expected no removed items in first prompt: {first_prompt}" + ); + + wait_for_phase2_success(db.as_ref(), thread_a).await?; + let memory_root = home.path().join("memories"); + let raw_memories = tokio::fs::read_to_string(memory_root.join("raw_memories.md")).await?; + assert!(raw_memories.contains("raw memory A")); + assert!(!raw_memories.contains("raw memory B")); + let rollout_summaries = read_rollout_summary_bodies(&memory_root).await?; + assert_eq!(rollout_summaries.len(), 1); + assert!(rollout_summaries[0].contains("rollout summary A")); + assert!(rollout_summaries[0].contains("git_branch: branch-rollout-a")); + + shutdown_test_codex(&first).await?; + + let thread_b = seed_stage1_output( + db.as_ref(), + home.path(), + now - ChronoDuration::hours(1), + "raw memory B", + "rollout summary B", + "rollout-b", + ) + .await?; + + let second_phase2 = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-phase2-2"), + ev_assistant_message("msg-phase2-2", "phase2 complete"), + ev_completed("resp-phase2-2"), + ]), + ) + .await; + + let second = build_test_codex(&server, home.clone()).await?; + let second_request = wait_for_single_request(&second_phase2).await; + let second_prompt = phase2_prompt_text(&second_request); + assert!( + second_prompt.contains("- selected inputs this run: 1"), + "expected selected count in second prompt: {second_prompt}" + ); + assert!( + second_prompt.contains("- newly added since the last successful Phase 2 run: 1"), + "expected added count in second prompt: {second_prompt}" + ); + assert!( + second_prompt.contains("- removed from the last successful Phase 2 run: 1"), + "expected removed count in second prompt: {second_prompt}" + ); + assert!( + second_prompt.contains(&format!("- [added] thread_id={thread_b},")), + "expected thread B to be marked added: {second_prompt}" + ); + assert!( + second_prompt.contains(&format!("- thread_id={thread_a},")), + "expected thread A to be marked removed: {second_prompt}" + ); + + wait_for_phase2_success(db.as_ref(), thread_b).await?; + let raw_memories = tokio::fs::read_to_string(memory_root.join("raw_memories.md")).await?; + assert!(raw_memories.contains("raw memory B")); + assert!(raw_memories.contains("raw memory A")); + let rollout_summaries = read_rollout_summary_bodies(&memory_root).await?; + assert_eq!(rollout_summaries.len(), 2); + assert!( + rollout_summaries + .iter() + .any(|summary| summary.contains("rollout summary B")) + ); + assert!( + rollout_summaries + .iter() + .any(|summary| summary.contains("git_branch: branch-rollout-b")) + ); + assert!( + rollout_summaries + .iter() + .any(|summary| summary.contains("rollout summary A")) + ); + + shutdown_test_codex(&second).await?; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn web_search_pollution_moves_selected_thread_into_removed_phase2_inputs() -> Result<()> { + let server = start_mock_server().await; + let home = Arc::new(TempDir::new()?); + let db = init_state_db(&home).await?; + + let mut initial_builder = test_codex().with_home(home.clone()).with_config(|config| { + config.features.enable(Feature::Sqlite); + config.features.enable(Feature::MemoryTool); + config.memories.max_raw_memories_for_consolidation = 1; + config.memories.no_memories_if_mcp_or_web_search = true; + }); + let initial = initial_builder.build(&server).await?; + mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-initial-1"), + ev_assistant_message("msg-initial-1", "initial turn complete"), + ev_completed("resp-initial-1"), + ]), + ) + .await; + initial.submit_turn("hello before memories").await?; + let rollout_path = initial + .session_configured + .rollout_path + .clone() + .expect("rollout path"); + let thread_id = initial.session_configured.session_id; + let updated_at = { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Some(metadata) = db.get_thread(thread_id).await? { + break metadata.updated_at; + } + assert!( + Instant::now() < deadline, + "timed out waiting for thread metadata for {thread_id}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + }; + + seed_stage1_output_for_existing_thread( + db.as_ref(), + thread_id, + updated_at.timestamp(), + "raw memory seeded for web search pollution", + "rollout summary seeded for web search pollution", + Some("pollution-rollout"), + ) + .await?; + + shutdown_test_codex(&initial).await?; + + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-phase2-1"), + ev_assistant_message("msg-phase2-1", "phase2 complete"), + ev_completed("resp-phase2-1"), + ]), + sse(vec![ + ev_response_created("resp-web-1"), + ev_web_search_call_done("ws-1", "completed", "weather seattle"), + ev_completed("resp-web-1"), + ]), + ], + ) + .await; + + let mut resumed_builder = test_codex().with_home(home.clone()).with_config(|config| { + config.features.enable(Feature::Sqlite); + config.features.enable(Feature::MemoryTool); + config.memories.max_raw_memories_for_consolidation = 1; + config.memories.no_memories_if_mcp_or_web_search = true; + }); + let resumed = resumed_builder + .resume(&server, home.clone(), rollout_path.clone()) + .await?; + + let first_phase2_request = wait_for_request(&responses, 1).await.remove(0); + let first_phase2_prompt = phase2_prompt_text(&first_phase2_request); + assert!( + first_phase2_prompt.contains("- selected inputs this run: 1"), + "expected seeded thread to be selected before pollution: {first_phase2_prompt}" + ); + assert!( + first_phase2_prompt.contains("- newly added since the last successful Phase 2 run: 1"), + "expected seeded thread to be added before pollution: {first_phase2_prompt}" + ); + assert!( + first_phase2_prompt.contains(&format!("- [added] thread_id={thread_id},")), + "expected selected thread in first phase2 prompt: {first_phase2_prompt}" + ); + + wait_for_phase2_success(db.as_ref(), thread_id).await?; + + resumed + .submit_turn("search the web for weather seattle") + .await?; + assert_eq!( + { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let memory_mode = db.get_thread_memory_mode(thread_id).await?; + if memory_mode.as_deref() == Some("polluted") { + break memory_mode; + } + assert!( + Instant::now() < deadline, + "timed out waiting for polluted memory mode for {thread_id}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + .as_deref(), + Some("polluted") + ); + + let selection = { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let selection = db.get_phase2_input_selection(1, 30).await?; + if selection.selected.is_empty() + && selection.retained_thread_ids.is_empty() + && selection.removed.len() == 1 + && selection.removed[0].thread_id == thread_id + { + break selection; + } + assert!( + Instant::now() < deadline, + "timed out waiting for polluted thread to move into removed phase2 inputs: \ + {selection:?}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + }; + assert_eq!(responses.requests().len(), 2); + assert!(selection.selected.is_empty()); + assert_eq!(selection.retained_thread_ids, Vec::::new()); + assert_eq!(selection.removed.len(), 1); + assert_eq!(selection.removed[0].thread_id, thread_id); + + shutdown_test_codex(&resumed).await?; + Ok(()) +} + +async fn build_test_codex(server: &wiremock::MockServer, home: Arc) -> Result { + let mut builder = test_codex().with_home(home).with_config(|config| { + config.features.enable(Feature::Sqlite); + config.features.enable(Feature::MemoryTool); + config.memories.max_raw_memories_for_consolidation = 1; + }); + builder.build(server).await +} + +async fn init_state_db(home: &Arc) -> Result> { + let db = + codex_state::StateRuntime::init(home.path().to_path_buf(), "test-provider".into(), None) + .await?; + db.mark_backfill_complete(None).await?; + Ok(db) +} + +async fn seed_stage1_output( + db: &codex_state::StateRuntime, + codex_home: &Path, + updated_at: chrono::DateTime, + raw_memory: &str, + rollout_summary: &str, + rollout_slug: &str, +) -> Result { + let thread_id = ThreadId::new(); + let mut metadata_builder = codex_state::ThreadMetadataBuilder::new( + thread_id, + codex_home.join(format!("rollout-{thread_id}.jsonl")), + updated_at, + SessionSource::Cli, + ); + metadata_builder.cwd = codex_home.join(format!("workspace-{rollout_slug}")); + metadata_builder.model_provider = Some("test-provider".to_string()); + metadata_builder.git_branch = Some(format!("branch-{rollout_slug}")); + let metadata = metadata_builder.build("test-provider"); + db.upsert_thread(&metadata).await?; + + seed_stage1_output_for_existing_thread( + db, + thread_id, + updated_at.timestamp(), + raw_memory, + rollout_summary, + Some(rollout_slug), + ) + .await?; + + Ok(thread_id) +} + +async fn wait_for_single_request(mock: &ResponseMock) -> ResponsesRequest { + wait_for_request(mock, 1).await.remove(0) +} + +async fn wait_for_request(mock: &ResponseMock, expected_count: usize) -> Vec { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let requests = mock.requests(); + if requests.len() >= expected_count { + return requests; + } + assert!( + Instant::now() < deadline, + "timed out waiting for {expected_count} phase2 requests" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +#[allow(clippy::expect_used)] +fn phase2_prompt_text(request: &ResponsesRequest) -> String { + request + .message_input_texts("user") + .into_iter() + .find(|text| text.contains("Current selected Phase 1 inputs:")) + .expect("phase2 prompt text") +} + +async fn wait_for_phase2_success( + db: &codex_state::StateRuntime, + expected_thread_id: ThreadId, +) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let selection = db.get_phase2_input_selection(1, 30).await?; + if selection.selected.len() == 1 + && selection.selected[0].thread_id == expected_thread_id + && selection.retained_thread_ids == vec![expected_thread_id] + && selection.removed.is_empty() + { + return Ok(()); + } + + assert!( + Instant::now() < deadline, + "timed out waiting for phase2 success for {expected_thread_id}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +async fn seed_stage1_output_for_existing_thread( + db: &codex_state::StateRuntime, + thread_id: ThreadId, + updated_at: i64, + raw_memory: &str, + rollout_summary: &str, + rollout_slug: Option<&str>, +) -> Result<()> { + let owner = ThreadId::new(); + let claim = db + .try_claim_stage1_job(thread_id, owner, updated_at, 3_600, 64) + .await?; + let ownership_token = match claim { + codex_state::Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage-1 claim outcome: {other:?}"), + }; + + assert!( + db.mark_stage1_job_succeeded( + thread_id, + &ownership_token, + updated_at, + raw_memory, + rollout_summary, + rollout_slug, + ) + .await?, + "stage-1 success should enqueue global consolidation" + ); + + Ok(()) +} + +async fn read_rollout_summary_bodies(memory_root: &Path) -> Result> { + let mut dir = tokio::fs::read_dir(memory_root.join("rollout_summaries")).await?; + let mut summaries = Vec::new(); + while let Some(entry) = dir.next_entry().await? { + summaries.push(tokio::fs::read_to_string(entry.path()).await?); + } + summaries.sort(); + Ok(summaries) +} + +async fn shutdown_test_codex(test: &TestCodex) -> Result<()> { + test.codex.submit(Op::Shutdown {}).await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::ShutdownComplete)).await; + Ok(()) +} diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index 4cfe955b55..e9867caa76 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -83,6 +83,7 @@ mod json_result; mod list_dir; mod live_cli; mod live_reload; +mod memories; mod model_info_overrides; mod model_overrides; mod model_switching; @@ -94,6 +95,7 @@ mod pending_input; mod permissions_messages; mod personality; mod personality_migration; +mod plugins; mod prompt_caching; mod quota_exceeded; mod read_file; diff --git a/codex-rs/core/tests/suite/model_info_overrides.rs b/codex-rs/core/tests/suite/model_info_overrides.rs index 7a92e99f1e..ee4afc36bf 100644 --- a/codex-rs/core/tests/suite/model_info_overrides.rs +++ b/codex-rs/core/tests/suite/model_info_overrides.rs @@ -1,4 +1,5 @@ use codex_core::CodexAuth; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::models_manager::manager::ModelsManager; use codex_protocol::openai_models::TruncationPolicyConfig; use core_test_support::load_default_config_for_test; @@ -12,7 +13,12 @@ async fn offline_model_info_without_tool_output_override() { let auth_manager = codex_core::test_support::auth_manager_from_auth( CodexAuth::create_dummy_chatgpt_auth_for_testing(), ); - let manager = ModelsManager::new(config.codex_home.clone(), auth_manager, None); + let manager = ModelsManager::new( + config.codex_home.clone(), + auth_manager, + None, + CollaborationModesConfig::default(), + ); let model_info = manager.get_model_info("gpt-5.1", &config).await; @@ -30,7 +36,12 @@ async fn offline_model_info_with_tool_output_override() { let auth_manager = codex_core::test_support::auth_manager_from_auth( CodexAuth::create_dummy_chatgpt_auth_for_testing(), ); - let manager = ModelsManager::new(config.codex_home.clone(), auth_manager, None); + let manager = ModelsManager::new( + config.codex_home.clone(), + auth_manager, + None, + CollaborationModesConfig::default(), + ); let model_info = manager.get_model_info("gpt-5.1-codex", &config).await; diff --git a/codex-rs/core/tests/suite/model_overrides.rs b/codex-rs/core/tests/suite/model_overrides.rs index 1ba469f7f9..3760c9a38a 100644 --- a/codex-rs/core/tests/suite/model_overrides.rs +++ b/codex-rs/core/tests/suite/model_overrides.rs @@ -33,6 +33,7 @@ async fn override_turn_context_does_not_persist_when_config_exists() { model: Some("o3".to_string()), effort: Some(Some(ReasoningEffort::High)), summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -69,6 +70,7 @@ async fn override_turn_context_does_not_create_config_file() { model: Some("o3".to_string()), effort: Some(Some(ReasoningEffort::Medium)), summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index 6e06b0f224..385072f912 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -4,6 +4,7 @@ use codex_core::config::types::Personality; use codex_core::features::Feature; use codex_core::models_manager::manager::RefreshStrategy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::ServiceTier; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelInfo; @@ -58,7 +59,8 @@ async fn model_change_appends_model_instructions_developer_message() -> Result<( sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -74,6 +76,7 @@ async fn model_change_appends_model_instructions_developer_message() -> Result<( model: Some(next_model.to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -91,7 +94,8 @@ async fn model_change_appends_model_instructions_developer_message() -> Result<( sandbox_policy: SandboxPolicy::new_read_only_policy(), model: next_model.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -146,7 +150,8 @@ async fn model_and_personality_change_only_appends_model_instructions() -> Resul sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -162,6 +167,7 @@ async fn model_and_personality_change_only_appends_model_instructions() -> Resul model: Some(next_model.to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Pragmatic), }) @@ -179,7 +185,8 @@ async fn model_and_personality_change_only_appends_model_instructions() -> Resul sandbox_policy: SandboxPolicy::new_read_only_policy(), model: next_model.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -207,6 +214,36 @@ async fn model_and_personality_change_only_appends_model_instructions() -> Resul Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn service_tier_change_is_applied_on_next_http_turn() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let resp_mock = mount_sse_sequence( + &server, + vec![sse_completed("resp-1"), sse_completed("resp-2")], + ) + .await; + + let test = test_codex().build(&server).await?; + + test.submit_turn_with_service_tier("fast turn", Some(ServiceTier::Fast)) + .await?; + test.submit_turn_with_service_tier("standard turn", None) + .await?; + + let requests = resp_mock.requests(); + assert_eq!(requests.len(), 2, "expected two model requests"); + + let first_body = requests[0].body_json(); + let second_body = requests[1].body_json(); + + assert_eq!(first_body["service_tier"].as_str(), Some("priority")); + assert_eq!(second_body.get("service_tier"), None); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn model_change_from_image_to_text_strips_prior_image_content() -> Result<()> { skip_if_no_network!(Ok(())); @@ -234,8 +271,10 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result< base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -293,7 +332,8 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result< sandbox_policy: SandboxPolicy::new_read_only_policy(), model: image_model_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -312,7 +352,8 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result< sandbox_policy: SandboxPolicy::new_read_only_policy(), model: text_model_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -391,8 +432,10 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -469,7 +512,8 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< sandbox_policy: SandboxPolicy::new_read_only_policy(), model: large_model_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -507,6 +551,7 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< model: Some(smaller_model_slug.to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -524,7 +569,8 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< sandbox_policy: SandboxPolicy::new_read_only_policy(), model: smaller_model_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/model_visible_layout.rs b/codex-rs/core/tests/suite/model_visible_layout.rs index 3288eb5c05..a6a044f3f6 100644 --- a/codex-rs/core/tests/suite/model_visible_layout.rs +++ b/codex-rs/core/tests/suite/model_visible_layout.rs @@ -6,7 +6,6 @@ use std::sync::Arc; use anyhow::Result; use codex_core::config::types::Personality; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -26,6 +25,7 @@ use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; +use serde_json::json; const PRETURN_CONTEXT_DIFF_CWD: &str = "PRETURN_CONTEXT_DIFF_CWD"; @@ -53,6 +53,30 @@ fn agents_message_count(request: &ResponsesRequest) -> usize { .count() } +fn format_environment_context_subagents_snapshot(subagents: &[&str]) -> String { + let subagents_block = if subagents.is_empty() { + String::new() + } else { + let lines = subagents + .iter() + .map(|line| format!(" {line}")) + .collect::>() + .join("\n"); + format!("\n \n{lines}\n ") + }; + let items = vec![json!({ + "type": "message", + "role": "user", + "content": [{ + "type": "input_text", + "text": format!( + "\n /tmp/example\n bash{subagents_block}\n" + ), + }], + })]; + context_snapshot::format_response_items_snapshot(items.as_slice(), &context_snapshot_options()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn snapshot_model_visible_layout_turn_overrides() -> Result<()> { skip_if_no_network!(Ok(())); @@ -97,7 +121,8 @@ async fn snapshot_model_visible_layout_turn_overrides() -> Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -119,7 +144,8 @@ async fn snapshot_model_visible_layout_turn_overrides() -> Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Friendly), }) @@ -196,7 +222,8 @@ async fn snapshot_model_visible_layout_cwd_change_does_not_refresh_agents() -> R sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -218,7 +245,8 @@ async fn snapshot_model_visible_layout_cwd_change_does_not_refresh_agents() -> R sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -323,7 +351,8 @@ async fn snapshot_model_visible_layout_resume_with_personality_change() -> Resul sandbox_policy: SandboxPolicy::new_read_only_policy(), model: resumed.session_configured.model.clone(), effort: resumed.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Friendly), }) @@ -412,6 +441,7 @@ async fn snapshot_model_visible_layout_resume_override_matches_rollout_model() - model: Some("gpt-5.2".to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -445,3 +475,23 @@ async fn snapshot_model_visible_layout_resume_override_matches_rollout_model() - Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_model_visible_layout_environment_context_includes_one_subagent() -> Result<()> { + insta::assert_snapshot!( + "model_visible_layout_environment_context_includes_one_subagent", + format_environment_context_subagents_snapshot(&["- agent-1: Atlas"]) + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshot_model_visible_layout_environment_context_includes_two_subagents() -> Result<()> { + insta::assert_snapshot!( + "model_visible_layout_environment_context_includes_two_subagents", + format_environment_context_subagents_snapshot(&["- agent-1: Atlas", "- agent-2: Juniper"]) + ); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/models_cache_ttl.rs b/codex-rs/core/tests/suite/models_cache_ttl.rs index 3422e397b8..d2202b58cf 100644 --- a/codex-rs/core/tests/suite/models_cache_ttl.rs +++ b/codex-rs/core/tests/suite/models_cache_ttl.rs @@ -99,7 +99,8 @@ async fn renews_cache_ttl_on_matching_models_etag() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: test.session_configured.model.clone(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -336,8 +337,10 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo { base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, diff --git a/codex-rs/core/tests/suite/models_etag_responses.rs b/codex-rs/core/tests/suite/models_etag_responses.rs index 7c40bec987..a479ebb80c 100644 --- a/codex-rs/core/tests/suite/models_etag_responses.rs +++ b/codex-rs/core/tests/suite/models_etag_responses.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use anyhow::Result; use codex_core::CodexAuth; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -106,7 +105,8 @@ async fn refresh_models_on_models_etag_mismatch_and_avoid_duplicate_models_fetch sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/override_updates.rs b/codex-rs/core/tests/suite/override_updates.rs index 7ae78891f1..dbf19a2e42 100644 --- a/codex-rs/core/tests/suite/override_updates.rs +++ b/codex-rs/core/tests/suite/override_updates.rs @@ -121,6 +121,7 @@ async fn override_turn_context_without_user_turn_does_not_record_permissions_upd model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -161,6 +162,7 @@ async fn override_turn_context_without_user_turn_does_not_record_environment_upd model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -198,6 +200,7 @@ async fn override_turn_context_without_user_turn_does_not_record_collaboration_u model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index 36c93b3796..8dfe2b5e6b 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -120,6 +120,7 @@ async fn permissions_message_added_on_override_change() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -262,6 +263,7 @@ async fn resume_replays_permissions_messages() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -361,6 +363,7 @@ async fn resume_and_fork_append_permissions_messages() -> Result<()> { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index 0b4d485cfb..73f57ba0b0 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -97,7 +97,8 @@ async fn user_turn_personality_none_does_not_add_update_message() -> anyhow::Res sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -143,7 +144,8 @@ async fn config_personality_some_sets_instructions_template() -> anyhow::Result< sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -196,7 +198,8 @@ async fn config_personality_none_sends_no_personality() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -255,7 +258,8 @@ async fn default_personality_is_pragmatic_without_config_toml() -> anyhow::Resul sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -302,7 +306,8 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -319,6 +324,7 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Friendly), }) @@ -336,7 +342,8 @@ async fn user_turn_personality_some_adds_update_message() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -398,7 +405,8 @@ async fn user_turn_personality_same_value_does_not_add_update_message() -> anyho sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -415,6 +423,7 @@ async fn user_turn_personality_same_value_does_not_add_update_message() -> anyho model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Pragmatic), }) @@ -432,7 +441,8 @@ async fn user_turn_personality_same_value_does_not_add_update_message() -> anyho sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -504,7 +514,8 @@ async fn user_turn_personality_skips_if_feature_disabled() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -521,6 +532,7 @@ async fn user_turn_personality_skips_if_feature_disabled() -> anyhow::Result<()> model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Pragmatic), }) @@ -538,7 +550,8 @@ async fn user_turn_personality_skips_if_feature_disabled() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::new_read_only_policy(), model: test.session_configured.model.clone(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -599,8 +612,10 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow }), }), supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -646,7 +661,8 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow sandbox_policy: SandboxPolicy::new_read_only_policy(), model: remote_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Friendly), }) @@ -706,8 +722,10 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - }), }), supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -756,7 +774,8 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - sandbox_policy: SandboxPolicy::new_read_only_policy(), model: remote_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -773,6 +792,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: Some(Personality::Friendly), }) @@ -790,7 +810,8 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - sandbox_policy: SandboxPolicy::new_read_only_policy(), model: remote_slug.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/personality_migration.rs b/codex-rs/core/tests/suite/personality_migration.rs index dfff16ea03..adbd86cb23 100644 --- a/codex-rs/core/tests/suite/personality_migration.rs +++ b/codex-rs/core/tests/suite/personality_migration.rs @@ -71,6 +71,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R model_provider: None, base_instructions: None, dynamic_tools: None, + memory_mode: None, }, git: None, }; @@ -114,6 +115,7 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re model_provider: None, base_instructions: None, dynamic_tools: None, + memory_mode: None, }, git: None, }; diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs new file mode 100644 index 0000000000..ed2ba54a3a --- /dev/null +++ b/codex-rs/core/tests/suite/plugins.rs @@ -0,0 +1,182 @@ +#![cfg(not(target_os = "windows"))] +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + +use anyhow::Result; +use codex_core::CodexAuth; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_once; +use core_test_support::responses::sse; +use core_test_support::responses::start_mock_server; +use core_test_support::skip_if_no_network; +use core_test_support::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 dunce::canonicalize as normalize_path; +use tempfile::TempDir; +use wiremock::MockServer; + +fn write_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf { + let plugin_root = home.path().join("plugins/sample"); + let skill_dir = plugin_root.join("skills/sample-search"); + std::fs::create_dir_all(skill_dir.as_path()).expect("create plugin skill dir"); + std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); + std::fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ) + .expect("write plugin manifest"); + std::fs::write( + skill_dir.join("SKILL.md"), + "---\ndescription: inspect sample data\n---\n\n# body\n", + ) + .expect("write plugin skill"); + std::fs::write( + home.path().join("config.toml"), + format!( + "[features]\nplugins = true\n\n[plugins.sample]\nenabled = true\npath = \"{}\"\n", + plugin_root.display() + ), + ) + .expect("write config"); + skill_dir.join("SKILL.md") +} + +fn write_plugin_mcp_plugin(home: &TempDir, command: &str) { + let plugin_root = home.path().join("plugins/sample"); + std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); + std::fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ) + .expect("write plugin manifest"); + std::fs::write( + plugin_root.join(".mcp.json"), + format!( + r#"{{ + "mcpServers": {{ + "sample": {{ + "command": "{command}" + }} + }} +}}"# + ), + ) + .expect("write plugin mcp config"); + std::fs::write( + home.path().join("config.toml"), + format!( + "[features]\nplugins = true\n\n[plugins.sample]\nenabled = true\npath = \"{}\"\n", + plugin_root.display() + ), + ) + .expect("write config"); +} + +async fn build_plugin_test_codex( + server: &MockServer, + codex_home: Arc, +) -> Result> { + let mut builder = test_codex() + .with_home(codex_home) + .with_auth(CodexAuth::from_api_key("Test API Key")); + Ok(builder + .build(server) + .await + .expect("create new conversation") + .codex) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plugin_skills_append_to_instructions() -> Result<()> { + skip_if_no_network!(Ok(())); + let server = MockServer::start().await; + + let resp_mock = mount_sse_once( + &server, + sse(vec![ev_response_created("resp1"), ev_completed("resp1")]), + ) + .await; + + let codex_home = Arc::new(TempDir::new()?); + let skill_path = write_plugin_skill_plugin(codex_home.as_ref()); + let codex = build_plugin_test_codex(&server, Arc::clone(&codex_home)).await?; + + codex + .submit(Op::UserInput { + items: vec![codex_protocol::user_input::UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }) + .await?; + + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + + let request = resp_mock.single_request(); + let request_body = request.body_json(); + let instructions_text = request_body["input"][1]["content"][0]["text"] + .as_str() + .expect("instructions text"); + assert!( + instructions_text.contains("## Skills"), + "expected skills section present" + ); + assert!( + instructions_text.contains("sample:sample-search: inspect sample data"), + "expected namespaced plugin skill summary" + ); + let expected_path = normalize_path(skill_path)?; + let expected_path_str = expected_path.to_string_lossy().replace('\\', "/"); + assert!( + instructions_text.contains(&expected_path_str), + "expected path {expected_path_str} in instructions" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn plugin_mcp_tools_are_listed() -> Result<()> { + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let codex_home = Arc::new(TempDir::new()?); + let rmcp_test_server_bin = stdio_server_bin()?; + write_plugin_mcp_plugin(codex_home.as_ref(), &rmcp_test_server_bin); + let codex = build_plugin_test_codex(&server, codex_home).await?; + + let tools_ready_deadline = Instant::now() + Duration::from_secs(30); + loop { + codex.submit(Op::ListMcpTools).await?; + let list_event = wait_for_event_with_timeout( + &codex, + |ev| matches!(ev, EventMsg::McpListToolsResponse(_)), + Duration::from_secs(10), + ) + .await; + let EventMsg::McpListToolsResponse(tool_list) = list_event else { + unreachable!("event guard guarantees McpListToolsResponse"); + }; + if tool_list.tools.contains_key("mcp__sample__echo") + && tool_list.tools.contains_key("mcp__sample__image") + { + break; + } + + let available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect(); + if Instant::now() >= tools_ready_deadline { + panic!("timed out waiting for plugin MCP tools; discovered tools: {available_tools:?}"); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 38a8145d50..0275f3b4b2 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -30,21 +30,46 @@ use pretty_assertions::assert_eq; use tempfile::TempDir; fn text_user_input(text: String) -> serde_json::Value { + text_user_input_parts(vec![text]) +} + +fn text_user_input_parts(texts: Vec) -> serde_json::Value { serde_json::json!({ "type": "message", "role": "user", - "content": [ { "type": "input_text", "text": text } ] + "content": texts + .into_iter() + .map(|text| serde_json::json!({ "type": "input_text", "text": text })) + .collect::>() }) } -fn default_env_context_str(cwd: &str, shell: &Shell) -> String { +fn assert_default_env_context(text: &str, cwd: &str, shell: &Shell) { let shell_name = shell.name(); - format!( - r#" - {cwd} - {shell_name} -"# - ) + assert!( + text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG), + "expected environment context fragment: {text}" + ); + assert!( + text.contains(&format!("{cwd}")), + "expected cwd in environment context: {text}" + ); + assert!( + text.contains(&format!("{shell_name}")), + "expected shell in environment context: {text}" + ); + assert!( + text.contains("") && text.contains(""), + "expected current_date in environment context: {text}" + ); + assert!( + text.contains("") && text.contains(""), + "expected timezone in environment context: {text}" + ); + assert!( + text.ends_with(""), + "expected closing environment_context tag: {text}" + ); } fn assert_tool_names(body: &serde_json::Value, expected_names: &[&str]) { @@ -297,8 +322,8 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests let input1 = body1["input"].as_array().expect("input array"); assert_eq!( input1.len(), - 4, - "expected permissions + cached prefix + env + user msg" + 3, + "expected permissions + cached contextual user prefix + user msg" ); let ui_text = input1[1]["content"][0]["text"] @@ -311,13 +336,16 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests let shell = default_user_shell(); let cwd_str = config.cwd.to_string_lossy(); - let expected_env_text = default_env_context_str(&cwd_str, &shell); + let env_text = input1[1]["content"][1]["text"] + .as_str() + .expect("environment context text"); + assert_default_env_context(env_text, &cwd_str, &shell); assert_eq!( - input1[2], - text_user_input(expected_env_text), - "expected environment context after UI message" + input1[1]["content"][1]["type"].as_str(), + Some("input_text"), + "expected environment context bundled after UI message in cached contextual message" ); - assert_eq!(input1[3], text_user_input("hello 1".to_string())); + assert_eq!(input1[2], text_user_input("hello 1".to_string())); let body2 = req2.single_request().body_json(); let input2 = body2["input"].as_array().expect("input array"); @@ -385,6 +413,7 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an model: None, effort: Some(Some(ReasoningEffort::High)), summary: Some(ReasoningSummary::Detailed), + service_tier: None, collaboration_mode: None, personality: None, }) @@ -402,8 +431,10 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - let body1 = req1.single_request().body_json(); - let body2 = req2.single_request().body_json(); + let request1 = req1.single_request(); + let request2 = req2.single_request(); + let body1 = request1.body_json(); + let body2 = request2.body_json(); // prompt_cache_key should remain constant across overrides assert_eq!( body1["prompt_cache_key"], body2["prompt_cache_key"], @@ -464,6 +495,7 @@ async fn override_before_first_turn_emits_environment_context() -> anyhow::Resul model: Some("gpt-5.1-codex".to_string()), effort: Some(Some(ReasoningEffort::Low)), summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -500,17 +532,32 @@ async fn override_before_first_turn_emits_environment_context() -> anyhow::Resul let env_texts: Vec<&str> = input .iter() .filter_map(|msg| { - msg["content"] - .as_array() - .and_then(|content| content.first()) - .and_then(|item| item["text"].as_str()) + msg["content"].as_array().map(|content| { + content + .iter() + .filter_map(|item| item["text"].as_str()) + .collect::>() + }) }) + .flatten() .filter(|text| text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG)) .collect(); assert!( !env_texts.is_empty(), "expected environment context to be emitted: {env_texts:?}" ); + assert!( + env_texts + .iter() + .any(|text| text.contains("") && text.contains("")), + "expected current_date in environment context: {env_texts:?}" + ); + assert!( + env_texts + .iter() + .any(|text| text.contains("") && text.contains("")), + "expected timezone in environment context: {env_texts:?}" + ); let env_count = input .iter() @@ -559,11 +606,14 @@ async fn override_before_first_turn_emits_environment_context() -> anyhow::Resul let user_texts: Vec<&str> = input .iter() .filter_map(|msg| { - msg["content"] - .as_array() - .and_then(|content| content.first()) - .and_then(|item| item["text"].as_str()) + msg["content"].as_array().map(|content| { + content + .iter() + .filter_map(|item| item["text"].as_str()) + .collect::>() + }) }) + .flatten() .collect(); assert!( user_texts.contains(&"first message"), @@ -631,7 +681,8 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res sandbox_policy: new_policy.clone(), model: "o3".to_string(), effort: Some(ReasoningEffort::High), - summary: ReasoningSummary::Detailed, + summary: Some(ReasoningSummary::Detailed), + service_tier: None, collaboration_mode: None, final_output_json_schema: None, personality: None, @@ -639,8 +690,10 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - let body1 = req1.single_request().body_json(); - let body2 = req2.single_request().body_json(); + let request1 = req1.single_request(); + let request2 = req2.single_request(); + let body1 = request1.body_json(); + let body2 = request2.body_json(); // prompt_cache_key should remain constant across per-turn overrides assert_eq!( @@ -655,43 +708,34 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res "role": "user", "content": [ { "type": "input_text", "text": "hello 2" } ] }); - let shell = default_user_shell(); - - let expected_env_text_2 = format!( - r#" - {} - {} -"#, - new_cwd.path().display(), - shell.name() - ); - let expected_env_msg_2 = serde_json::json!({ - "type": "message", - "role": "user", - "content": [ { "type": "input_text", "text": expected_env_text_2 } ] - }); let expected_permissions_msg = body1["input"][0].clone(); let body1_input = body1["input"].as_array().expect("input array"); - let expected_model_switch_msg = body2["input"][body1_input.len()].clone(); + let expected_settings_update_msg = body2["input"][body1_input.len()].clone(); + assert_ne!( + expected_settings_update_msg, expected_permissions_msg, + "expected updated permissions message after per-turn override" + ); assert_eq!( - expected_model_switch_msg["role"].as_str(), + expected_settings_update_msg["role"].as_str(), Some("developer") ); assert!( - expected_model_switch_msg["content"][0]["text"] - .as_str() - .is_some_and(|text| text.contains("")), - "expected model switch message after model override: {expected_model_switch_msg:?}" - ); - let expected_permissions_msg_2 = body2["input"][body1_input.len() + 2].clone(); - assert_ne!( - expected_permissions_msg_2, expected_permissions_msg, - "expected updated permissions message after per-turn override" + request2.has_message_with_input_texts("developer", |texts| { + texts.iter().any(|text| text.contains("")) + }), + "expected model switch section after model override: {expected_settings_update_msg:?}" ); + 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"); + let shell = default_user_shell(); + let expected_cwd = new_cwd.path().display().to_string(); + assert_default_env_context(env_text, &expected_cwd, &shell); let mut expected_body2 = body1_input.to_vec(); - expected_body2.push(expected_model_switch_msg); + expected_body2.push(expected_settings_update_msg); expected_body2.push(expected_env_msg_2); - expected_body2.push(expected_permissions_msg_2); expected_body2.push(expected_user_message_2); assert_eq!(body2["input"], serde_json::Value::Array(expected_body2)); @@ -746,7 +790,8 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a sandbox_policy: default_sandbox_policy.clone(), model: default_model.clone(), effort: default_effort, - summary: default_summary, + summary: Some(default_summary.unwrap_or(ReasoningSummary::Auto)), + service_tier: None, collaboration_mode: None, final_output_json_schema: None, personality: None, @@ -765,7 +810,8 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a sandbox_policy: default_sandbox_policy.clone(), model: default_model.clone(), effort: default_effort, - summary: default_summary, + summary: Some(default_summary.unwrap_or(ReasoningSummary::Auto)), + service_tier: None, collaboration_mode: None, final_output_json_schema: None, personality: None, @@ -773,22 +819,34 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - let body1 = req1.single_request().body_json(); - let body2 = req2.single_request().body_json(); + let request1 = req1.single_request(); + let request2 = req2.single_request(); + let body1 = request1.body_json(); + let body2 = request2.body_json(); let expected_permissions_msg = body1["input"][0].clone(); let expected_ui_msg = body1["input"][1].clone(); let shell = default_user_shell(); let default_cwd_lossy = default_cwd.to_string_lossy(); + let expected_env_text_1 = expected_ui_msg["content"][1]["text"] + .as_str() + .expect("cached environment context text") + .to_string(); + assert_default_env_context(&expected_env_text_1, &default_cwd_lossy, &shell); - let expected_env_msg_1 = text_user_input(default_env_context_str(&default_cwd_lossy, &shell)); + let expected_contextual_user_msg_1 = text_user_input_parts(vec![ + expected_ui_msg["content"][0]["text"] + .as_str() + .expect("cached user instructions text") + .to_string(), + expected_env_text_1, + ]); let expected_user_message_1 = text_user_input("hello 1".to_string()); let expected_input_1 = serde_json::Value::Array(vec![ expected_permissions_msg.clone(), - expected_ui_msg.clone(), - expected_env_msg_1.clone(), + expected_contextual_user_msg_1.clone(), expected_user_message_1.clone(), ]); assert_eq!(body1["input"], expected_input_1); @@ -796,8 +854,7 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a 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_ui_msg, - expected_env_msg_1, + expected_contextual_user_msg_1, expected_user_message_1, expected_user_message_2, ]); @@ -854,7 +911,8 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu sandbox_policy: default_sandbox_policy.clone(), model: default_model, effort: default_effort, - summary: default_summary, + summary: Some(default_summary.unwrap_or(ReasoningSummary::Auto)), + service_tier: None, collaboration_mode: None, final_output_json_schema: None, personality: None, @@ -873,7 +931,8 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu sandbox_policy: SandboxPolicy::DangerFullAccess, model: "o3".to_string(), effort: Some(ReasoningEffort::High), - summary: ReasoningSummary::Detailed, + summary: Some(ReasoningSummary::Detailed), + service_tier: None, collaboration_mode: None, final_output_json_schema: None, personality: None, @@ -881,49 +940,57 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; - let body1 = req1.single_request().body_json(); - let body2 = req2.single_request().body_json(); + let request1 = req1.single_request(); + let request2 = req2.single_request(); + let body1 = request1.body_json(); + let body2 = request2.body_json(); let expected_permissions_msg = body1["input"][0].clone(); let expected_ui_msg = body1["input"][1].clone(); let shell = default_user_shell(); - let expected_env_text_1 = default_env_context_str(&default_cwd.to_string_lossy(), &shell); - let expected_env_msg_1 = text_user_input(expected_env_text_1); + let expected_env_text_1 = expected_ui_msg["content"][1]["text"] + .as_str() + .expect("cached environment context text") + .to_string(); + assert_default_env_context(&expected_env_text_1, &default_cwd.to_string_lossy(), &shell); + let expected_contextual_user_msg_1 = text_user_input_parts(vec![ + expected_ui_msg["content"][0]["text"] + .as_str() + .expect("cached user instructions text") + .to_string(), + expected_env_text_1, + ]); let expected_user_message_1 = text_user_input("hello 1".to_string()); let expected_input_1 = serde_json::Value::Array(vec![ expected_permissions_msg.clone(), - expected_ui_msg.clone(), - expected_env_msg_1.clone(), + expected_contextual_user_msg_1.clone(), expected_user_message_1.clone(), ]); assert_eq!(body1["input"], expected_input_1); let body1_input = body1["input"].as_array().expect("input array"); - let expected_model_switch_msg = body2["input"][body1_input.len()].clone(); + let expected_settings_update_msg = body2["input"][body1_input.len()].clone(); + assert_ne!( + expected_settings_update_msg, expected_permissions_msg, + "expected updated permissions message after policy change" + ); assert_eq!( - expected_model_switch_msg["role"].as_str(), + expected_settings_update_msg["role"].as_str(), Some("developer") ); assert!( - expected_model_switch_msg["content"][0]["text"] - .as_str() - .is_some_and(|text| text.contains("")), - "expected model switch message after model override: {expected_model_switch_msg:?}" - ); - let expected_permissions_msg_2 = body2["input"][body1_input.len() + 1].clone(); - assert_ne!( - expected_permissions_msg_2, expected_permissions_msg, - "expected updated permissions message after policy change" + request2.has_message_with_input_texts("developer", |texts| { + texts.iter().any(|text| text.contains("")) + }), + "expected model switch section after model override: {expected_settings_update_msg:?}" ); 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_ui_msg, - expected_env_msg_1, + expected_contextual_user_msg_1, expected_user_message_1, - expected_model_switch_msg, - expected_permissions_msg_2, + expected_settings_update_msg, expected_user_message_2, ]); assert_eq!(body2["input"], expected_input_2); diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index 98848e911c..32500299cb 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -1,4 +1,6 @@ use anyhow::Result; +use codex_core::CodexAuth; +use codex_core::auth::OPENAI_API_KEY_ENV_VAR; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::ConversationAudioParams; use codex_protocol::protocol::ConversationStartParams; @@ -22,6 +24,7 @@ use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; +use std::ffi::OsString; use std::time::Duration; use tokio::sync::oneshot; @@ -33,16 +36,16 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { vec![], vec![ vec![json!({ - "type": "session.created", - "session": { "id": "sess_1" } + "type": "session.updated", + "session": { "id": "sess_1", "instructions": "backend prompt" } })], vec![], vec![ json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24000, - "num_channels": 1 + "channels": 1 }), json!({ "type": "conversation.item.added", @@ -77,14 +80,14 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { .unwrap_or_else(|err: ErrorEvent| panic!("conversation start failed: {err:?}")); assert!(started.session_id.is_some()); - let session_created = wait_for_event_match(&test.codex, |msg| match msg { + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) => Some(session_id.clone()), _ => None, }) .await; - assert_eq!(session_created, "sess_1"); + assert_eq!(session_updated, "sess_1"); test.codex .submit(Op::RealtimeConversationAudio(ConversationAudioParams { @@ -117,17 +120,29 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { assert_eq!(connection.len(), 3); assert_eq!( connection[0].body_json()["type"].as_str(), - Some("session.create") + Some("session.update") ); assert_eq!( - connection[0].body_json()["session"]["conversation_id"] - .as_str() - .expect("session.create conversation_id"), + connection[0].body_json()["session"]["instructions"].as_str(), + Some("backend prompt") + ); + assert_eq!( + server.handshakes()[1] + .header("x-session-id") + .expect("session.update x-session-id header"), started .session_id .as_deref() .expect("started session id should be present") ); + assert_eq!( + server.handshakes()[1].header("authorization").as_deref(), + Some("Bearer dummy") + ); + assert_eq!( + server.handshakes()[1].uri(), + "/v1/realtime?intent=quicksilver&model=realtime-test-model" + ); let mut request_types = [ connection[1].body_json()["type"] .as_str() @@ -143,7 +158,7 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { request_types, [ "conversation.item.create".to_string(), - "response.input_audio.delta".to_string(), + "input_audio_buffer.append".to_string(), ] ); @@ -162,15 +177,74 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_start_uses_openai_env_key_fallback_with_chatgpt_auth() -> Result<()> { + skip_if_no_network!(Ok(())); + + let _env_guard = EnvGuard::set(OPENAI_API_KEY_ENV_VAR, "env-realtime-key"); + let server = start_websocket_server(vec![ + vec![], + vec![vec![json!({ + "type": "session.updated", + "session": { "id": "sess_env", "instructions": "backend prompt" } + })]], + ]) + .await; + + let mut builder = test_codex().with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()); + let test = builder.build_with_websocket_server(&server).await?; + assert!(server.wait_for_handshakes(1, Duration::from_secs(2)).await); + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let started = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationStarted(started) => Some(Ok(started.clone())), + EventMsg::Error(err) => Some(Err(err.clone())), + _ => None, + }) + .await + .unwrap_or_else(|err: ErrorEvent| panic!("conversation start failed: {err:?}")); + assert!(started.session_id.is_some()); + + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionUpdated { session_id, .. }, + }) => Some(session_id.clone()), + _ => None, + }) + .await; + assert_eq!(session_updated, "sess_env"); + + assert_eq!( + server.handshakes()[1].header("authorization").as_deref(), + Some("Bearer env-realtime-key") + ); + + test.codex.submit(Op::RealtimeConversationClose).await?; + let _closed = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()), + _ => None, + }) + .await; + + server.shutdown().await; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_transport_close_emits_closed_event() -> Result<()> { skip_if_no_network!(Ok(())); - let session_created = vec![json!({ - "type": "session.created", - "session": { "id": "sess_1" } + let session_updated = vec![json!({ + "type": "session.updated", + "session": { "id": "sess_1", "instructions": "backend prompt" } })]; - let server = start_websocket_server(vec![vec![], vec![session_created]]).await; + let server = start_websocket_server(vec![vec![], vec![session_updated]]).await; let mut builder = test_codex(); let test = builder.build_with_websocket_server(&server).await?; @@ -192,14 +266,14 @@ async fn conversation_transport_close_emits_closed_event() -> Result<()> { .unwrap_or_else(|err: ErrorEvent| panic!("conversation start failed: {err:?}")); assert!(started.session_id.is_some()); - let session_created = wait_for_event_match(&test.codex, |msg| match msg { + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) => Some(session_id.clone()), _ => None, }) .await; - assert_eq!(session_created, "sess_1"); + assert_eq!(session_updated, "sess_1"); let closed = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()), @@ -212,6 +286,34 @@ async fn conversation_transport_close_emits_closed_event() -> Result<()> { Ok(()) } +struct EnvGuard { + key: &'static str, + original: Option, +} + +impl EnvGuard { + fn set(key: &'static str, value: &str) -> Self { + let original = std::env::var_os(key); + // SAFETY: this guard restores the original value before the test exits. + unsafe { + std::env::set_var(key, value); + } + Self { key, original } + } +} + +impl Drop for EnvGuard { + fn drop(&mut self) { + // SAFETY: this guard restores the original value for the modified env var. + unsafe { + match &self.original { + Some(value) => std::env::set_var(self.key, value), + None => std::env::remove_var(self.key), + } + } + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_audio_before_start_emits_error() -> Result<()> { skip_if_no_network!(Ok(())); @@ -276,19 +378,19 @@ async fn conversation_second_start_replaces_runtime() -> Result<()> { let server = start_websocket_server(vec![ vec![], vec![vec![json!({ - "type": "session.created", - "session": { "id": "sess_old" } + "type": "session.updated", + "session": { "id": "sess_old", "instructions": "old" } })]], vec![ vec![json!({ - "type": "session.created", - "session": { "id": "sess_new" } + "type": "session.updated", + "session": { "id": "sess_new", "instructions": "new" } })], vec![json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24000, - "num_channels": 1 + "channels": 1 })], ], ]) @@ -305,7 +407,7 @@ async fn conversation_second_start_replaces_runtime() -> Result<()> { .await?; wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) if session_id == "sess_old" => Some(Ok(())), EventMsg::Error(err) => Some(Err(err.clone())), _ => None, @@ -321,7 +423,7 @@ async fn conversation_second_start_replaces_runtime() -> Result<()> { .await?; wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) if session_id == "sess_new" => Some(Ok(())), EventMsg::Error(err) => Some(Err(err.clone())), _ => None, @@ -351,30 +453,39 @@ async fn conversation_second_start_replaces_runtime() -> Result<()> { assert_eq!(connections.len(), 3); assert_eq!(connections[1].len(), 1); assert_eq!( - connections[1][0].body_json()["session"]["conversation_id"].as_str(), + connections[1][0].body_json()["session"]["instructions"].as_str(), + Some("old") + ); + assert_eq!( + server.handshakes()[1].header("x-session-id").as_deref(), Some("conv_old") ); assert_eq!(connections[2].len(), 2); assert_eq!( - connections[2][0].body_json()["session"]["conversation_id"].as_str(), + connections[2][0].body_json()["session"]["instructions"].as_str(), + Some("new") + ); + assert_eq!( + server.handshakes()[2].header("x-session-id").as_deref(), Some("conv_new") ); assert_eq!( connections[2][1].body_json()["type"].as_str(), - Some("response.input_audio.delta") + Some("input_audio_buffer.append") ); server.shutdown().await; Ok(()) } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn conversation_uses_experimental_realtime_ws_base_url_override() -> Result<()> { skip_if_no_network!(Ok(())); let startup_server = start_websocket_server(vec![vec![]]).await; let realtime_server = start_websocket_server(vec![vec![vec![json!({ - "type": "session.created", - "session": { "id": "sess_override" } + "type": "session.updated", + "session": { "id": "sess_override", "instructions": "backend prompt" } })]]]) .await; @@ -398,14 +509,14 @@ async fn conversation_uses_experimental_realtime_ws_base_url_override() -> Resul })) .await?; - let session_created = wait_for_event_match(&test.codex, |msg| match msg { + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) => Some(session_id.clone()), _ => None, }) .await; - assert_eq!(session_created, "sess_override"); + assert_eq!(session_updated, "sess_override"); let startup_connections = startup_server.connections(); assert_eq!(startup_connections.len(), 1); @@ -414,7 +525,7 @@ async fn conversation_uses_experimental_realtime_ws_base_url_override() -> Resul assert_eq!(realtime_connections.len(), 1); assert_eq!( realtime_connections[0][0].body_json()["type"].as_str(), - Some("session.create") + Some("session.update") ); startup_server.shutdown().await; @@ -429,8 +540,8 @@ async fn conversation_uses_experimental_realtime_ws_backend_prompt_override() -> let server = start_websocket_server(vec![ vec![], vec![vec![json!({ - "type": "session.created", - "session": { "id": "sess_override" } + "type": "session.updated", + "session": { "id": "sess_override", "instructions": "prompt from config" } })]], ]) .await; @@ -448,19 +559,19 @@ async fn conversation_uses_experimental_realtime_ws_backend_prompt_override() -> })) .await?; - let session_created = wait_for_event_match(&test.codex, |msg| match msg { + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) => Some(session_id.clone()), _ => None, }) .await; - assert_eq!(session_created, "sess_override"); + assert_eq!(session_updated, "sess_override"); let connections = server.connections(); assert_eq!(connections.len(), 2); assert_eq!( - connections[1][0].body_json()["session"]["backend_prompt"].as_str(), + connections[1][0].body_json()["session"]["instructions"].as_str(), Some("prompt from config") ); @@ -469,7 +580,7 @@ async fn conversation_uses_experimental_realtime_ws_backend_prompt_override() -> } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn conversation_mirrors_assistant_message_text_to_realtime_websocket() -> Result<()> { +async fn conversation_mirrors_assistant_message_text_to_realtime_handoff() -> Result<()> { skip_if_no_network!(Ok(())); let api_server = start_mock_server().await; @@ -484,10 +595,19 @@ async fn conversation_mirrors_assistant_message_text_to_realtime_websocket() -> .await; let realtime_server = start_websocket_server(vec![vec![ - vec![json!({ - "type": "session.created", - "session": { "id": "sess_1" } - })], + vec![ + json!({ + "type": "session.updated", + "session": { "id": "sess_1", "instructions": "backend prompt" } + }), + json!({ + "type": "conversation.handoff.requested", + "handoff_id": "handoff_1", + "item_id": "item_1", + "input_transcript": "delegate hello", + "messages": [{ "role": "user", "text": "delegate hello" }] + }), + ], vec![], ]]) .await; @@ -507,16 +627,27 @@ async fn conversation_mirrors_assistant_message_text_to_realtime_websocket() -> })) .await?; - let session_created = wait_for_event_match(&test.codex, |msg| match msg { + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) => Some(session_id.clone()), _ => None, }) .await; - assert_eq!(session_created, "sess_1"); + assert_eq!(session_updated, "sess_1"); - test.submit_turn("hello").await?; + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::HandoffRequested(handoff), + }) if handoff.handoff_id == "handoff_1" => Some(()), + _ => None, + }) + .await; + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; let deadline = tokio::time::Instant::now() + Duration::from_secs(2); while tokio::time::Instant::now() < deadline { @@ -532,14 +663,18 @@ async fn conversation_mirrors_assistant_message_text_to_realtime_websocket() -> assert_eq!(realtime_connections[0].len(), 2); assert_eq!( realtime_connections[0][0].body_json()["type"].as_str(), - Some("session.create") + Some("session.update") ); assert_eq!( realtime_connections[0][1].body_json()["type"].as_str(), - Some("conversation.item.create") + Some("conversation.handoff.append") ); assert_eq!( - realtime_connections[0][1].body_json()["item"]["content"][0]["text"].as_str(), + realtime_connections[0][1].body_json()["handoff_id"].as_str(), + Some("handoff_1") + ); + assert_eq!( + realtime_connections[0][1].body_json()["output_text"].as_str(), Some("assistant says hi") ); @@ -547,6 +682,145 @@ async fn conversation_mirrors_assistant_message_text_to_realtime_websocket() -> Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn conversation_handoff_persists_across_item_done_until_turn_complete() -> Result<()> { + skip_if_no_network!(Ok(())); + + let (gate_second_message_tx, gate_second_message_rx) = oneshot::channel(); + let first_chunks = vec![ + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_response_created("resp-1")), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_assistant_message( + "msg-1", + "assistant message 1", + )), + }, + StreamingSseChunk { + gate: Some(gate_second_message_rx), + body: sse_event(responses::ev_assistant_message( + "msg-2", + "assistant message 2", + )), + }, + StreamingSseChunk { + gate: None, + body: sse_event(responses::ev_completed("resp-1")), + }, + ]; + let (api_server, completions) = start_streaming_sse_server(vec![first_chunks]).await; + + let realtime_server = start_websocket_server(vec![vec![ + vec![ + json!({ + "type": "session.updated", + "session": { "id": "sess_item_done", "instructions": "backend prompt" } + }), + json!({ + "type": "conversation.handoff.requested", + "handoff_id": "handoff_item_done", + "item_id": "item_item_done", + "input_transcript": "delegate now", + "messages": [{ "role": "user", "text": "delegate now" }] + }), + ], + vec![json!({ + "type": "conversation.item.done", + "item": { "id": "item_item_done" } + })], + vec![], + ]]) + .await; + + let mut builder = test_codex().with_config({ + let realtime_base_url = realtime_server.uri().to_string(); + move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + } + }); + let test = builder.build_with_streaming_server(&api_server).await?; + + test.codex + .submit(Op::RealtimeConversationStart(ConversationStartParams { + prompt: "backend prompt".to_string(), + session_id: None, + })) + .await?; + + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::SessionUpdated { session_id, .. }, + }) if session_id == "sess_item_done" => Some(()), + _ => None, + }) + .await; + + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::HandoffRequested(handoff), + }) if handoff.handoff_id == "handoff_item_done" => Some(()), + _ => None, + }) + .await; + + let first_append = realtime_server.wait_for_request(0, 1).await; + assert_eq!( + first_append.body_json()["type"].as_str(), + Some("conversation.handoff.append") + ); + assert_eq!( + first_append.body_json()["handoff_id"].as_str(), + Some("handoff_item_done") + ); + assert_eq!( + first_append.body_json()["output_text"].as_str(), + Some("assistant message 1") + ); + + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::ConversationItemDone { item_id }, + }) if item_id == "item_item_done" => Some(()), + _ => None, + }) + .await; + + let _ = gate_second_message_tx.send(()); + + let second_append = realtime_server.wait_for_request(0, 2).await; + assert_eq!( + second_append.body_json()["type"].as_str(), + Some("conversation.handoff.append") + ); + assert_eq!( + second_append.body_json()["handoff_id"].as_str(), + Some("handoff_item_done") + ); + assert_eq!( + second_append.body_json()["output_text"].as_str(), + Some("assistant message 2") + ); + + let completion = completions + .into_iter() + .next() + .expect("missing delegated turn completion"); + completion + .await + .expect("delegated turn request did not complete"); + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + realtime_server.shutdown().await; + api_server.shutdown().await; + Ok(()) +} + fn sse_event(event: Value) -> String { responses::sse(vec![event]) } @@ -566,7 +840,7 @@ fn message_input_texts(body: &Value, role: &str) -> Vec { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_realtime_text_starts_turn_for_assistant_role() -> Result<()> { +async fn inbound_handoff_request_starts_turn() -> Result<()> { skip_if_no_network!(Ok(())); let api_server = start_mock_server().await; @@ -582,16 +856,15 @@ async fn inbound_realtime_text_starts_turn_for_assistant_role() -> Result<()> { let realtime_server = start_websocket_server(vec![vec![vec![ json!({ - "type": "session.created", - "session": { "id": "sess_inbound" } + "type": "session.updated", + "session": { "id": "sess_inbound", "instructions": "backend prompt" } }), json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "text from realtime"}] - } + "type": "conversation.handoff.requested", + "handoff_id": "handoff_inbound", + "item_id": "item_inbound", + "input_transcript": "text from realtime", + "messages": [{ "role": "user", "text": "text from realtime" }] }), ]]]) .await; @@ -611,14 +884,26 @@ async fn inbound_realtime_text_starts_turn_for_assistant_role() -> Result<()> { })) .await?; - let session_created = wait_for_event_match(&test.codex, |msg| match msg { + let session_updated = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) => Some(session_id.clone()), _ => None, }) .await; - assert_eq!(session_created, "sess_inbound"); + assert_eq!(session_updated, "sess_inbound"); + + let _ = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::HandoffRequested(handoff), + }) if handoff.handoff_id == "handoff_inbound" + && handoff.input_transcript == "text from realtime" => + { + Some(()) + } + _ => None, + }) + .await; wait_for_event(&test.codex, |event| { matches!(event, EventMsg::TurnComplete(_)) @@ -634,15 +919,15 @@ async fn inbound_realtime_text_starts_turn_for_assistant_role() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_realtime_text_ignores_user_role_and_still_forwards_audio() -> Result<()> { +async fn inbound_conversation_item_does_not_start_turn_and_still_forwards_audio() -> Result<()> { skip_if_no_network!(Ok(())); let api_server = start_mock_server().await; let realtime_server = start_websocket_server(vec![vec![vec![ json!({ - "type": "session.created", - "session": { "id": "sess_ignore_user_role" } + "type": "session.updated", + "session": { "id": "sess_ignore_item", "instructions": "backend prompt" } }), json!({ "type": "conversation.item.added", @@ -653,10 +938,10 @@ async fn inbound_realtime_text_ignores_user_role_and_still_forwards_audio() -> R } }), json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24000, - "num_channels": 1 + "channels": 1 }), ]]]) .await; @@ -678,8 +963,8 @@ async fn inbound_realtime_text_ignores_user_role_and_still_forwards_audio() -> R let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, - }) if session_id == "sess_ignore_user_role" => Some(()), + payload: RealtimeEvent::SessionUpdated { session_id, .. }, + }) if session_id == "sess_ignore_item" => Some(()), _ => None, }) .await; @@ -694,7 +979,7 @@ async fn inbound_realtime_text_ignores_user_role_and_still_forwards_audio() -> R }), ) .await - .expect("timed out waiting for realtime audio after user-role conversation item"); + .expect("timed out waiting for realtime audio after conversation item"); assert_eq!(audio_out.data, "AQID"); let unexpected_turn_started = tokio::time::timeout( @@ -715,6 +1000,7 @@ async fn inbound_realtime_text_ignores_user_role_and_still_forwards_audio() -> R async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_audio() -> Result<()> { skip_if_no_network!(Ok(())); + let start = std::time::Instant::now(); let (gate_completed_tx, gate_completed_rx) = oneshot::channel(); let first_chunks = vec![ @@ -739,16 +1025,15 @@ async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_au let realtime_server = start_websocket_server(vec![vec![ vec![ json!({ - "type": "session.created", - "session": { "id": "sess_echo_guard" } + "type": "session.updated", + "session": { "id": "sess_echo_guard", "instructions": "backend prompt" } }), json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "delegate now"}] - } + "type": "conversation.handoff.requested", + "handoff_id": "handoff_echo_guard", + "item_id": "item_echo_guard", + "input_transcript": "delegate now", + "messages": [{"role": "user", "text": "delegate now"}] }), ], vec![ @@ -761,10 +1046,10 @@ async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_au } }), json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24000, - "num_channels": 1 + "channels": 1 }), ], ]]) @@ -787,7 +1072,7 @@ async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_au let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) if session_id == "sess_echo_guard" => Some(()), _ => None, }) @@ -795,29 +1080,53 @@ async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_au let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::ConversationItemAdded(item), - }) => item - .get("content") - .and_then(Value::as_array) - .into_iter() - .flatten() - .any(|content| content.get("text").and_then(Value::as_str) == Some("delegate now")) - .then_some(()), + payload: RealtimeEvent::HandoffRequested(handoff), + }) if handoff.input_transcript == "delegate now" => Some(()), _ => None, }) .await; + eprintln!( + "[realtime test +{}ms] saw trigger text={:?}", + start.elapsed().as_millis(), + "delegate now" + ); - let audio_out = tokio::time::timeout( - Duration::from_millis(500), - wait_for_event_match(&test.codex, |msg| match msg { - EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::AudioOut(frame), - }) => Some(frame.clone()), - _ => None, - }), - ) - .await - .expect("timed out waiting for realtime audio after echoed user-role message"); + let mirrored_request = realtime_server.wait_for_request(0, 1).await; + let mirrored_request_body = mirrored_request.body_json(); + eprintln!( + "[realtime test +{}ms] saw mirrored request type={:?} handoff_id={:?} text={:?}", + start.elapsed().as_millis(), + mirrored_request_body["type"].as_str(), + mirrored_request_body["handoff_id"].as_str(), + mirrored_request_body["output_text"].as_str(), + ); + assert_eq!( + mirrored_request_body["type"].as_str(), + Some("conversation.handoff.append") + ); + assert_eq!( + mirrored_request_body["handoff_id"].as_str(), + Some("handoff_echo_guard") + ); + assert_eq!( + mirrored_request_body["output_text"].as_str(), + Some("assistant says hi") + ); + + let audio_out = wait_for_event_match(&test.codex, |msg| match msg { + EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { + payload: RealtimeEvent::AudioOut(frame), + }) => Some(frame.clone()), + _ => None, + }) + .await; + eprintln!( + "[realtime test +{}ms] saw audio out data={} sample_rate={} num_channels={}", + start.elapsed().as_millis(), + audio_out.data, + audio_out.sample_rate, + audio_out.num_channels + ); assert_eq!(audio_out.data, "AQID"); let completion = completions @@ -828,6 +1137,10 @@ async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_au completion .await .expect("delegated turn request did not complete"); + eprintln!( + "[realtime test +{}ms] delegated completion resolved", + start.elapsed().as_millis() + ); wait_for_event(&test.codex, |event| { matches!(event, EventMsg::TurnComplete(_)) }) @@ -842,7 +1155,7 @@ async fn delegated_turn_user_role_echo_does_not_redelegate_and_still_forwards_au } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_realtime_text_does_not_block_realtime_event_forwarding() -> Result<()> { +async fn inbound_handoff_request_does_not_block_realtime_event_forwarding() -> Result<()> { skip_if_no_network!(Ok(())); let (gate_completed_tx, gate_completed_rx) = oneshot::channel(); @@ -860,22 +1173,21 @@ async fn inbound_realtime_text_does_not_block_realtime_event_forwarding() -> Res let realtime_server = start_websocket_server(vec![vec![vec![ json!({ - "type": "session.created", - "session": { "id": "sess_non_blocking" } + "type": "session.updated", + "session": { "id": "sess_non_blocking", "instructions": "backend prompt" } }), json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "delegate now"}] - } + "type": "conversation.handoff.requested", + "handoff_id": "handoff_non_blocking", + "item_id": "item_non_blocking", + "input_transcript": "delegate now", + "messages": [{"role": "user", "text": "delegate now"}] }), json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24000, - "num_channels": 1 + "channels": 1 }), ]]]) .await; @@ -897,7 +1209,7 @@ async fn inbound_realtime_text_does_not_block_realtime_event_forwarding() -> Res let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) if session_id == "sess_non_blocking" => Some(()), _ => None, }) @@ -905,14 +1217,8 @@ async fn inbound_realtime_text_does_not_block_realtime_event_forwarding() -> Res let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::ConversationItemAdded(item), - }) => item - .get("content") - .and_then(Value::as_array) - .into_iter() - .flatten() - .any(|content| content.get("text").and_then(Value::as_str) == Some("delegate now")) - .then_some(()), + payload: RealtimeEvent::HandoffRequested(handoff), + }) if handoff.input_transcript == "delegate now" => Some(()), _ => None, }) .await; @@ -949,7 +1255,7 @@ async fn inbound_realtime_text_does_not_block_realtime_event_forwarding() -> Res } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_realtime_text_steers_active_turn() -> Result<()> { +async fn inbound_handoff_request_steers_active_turn() -> Result<()> { skip_if_no_network!(Ok(())); let (gate_completed_tx, gate_completed_rx) = oneshot::channel(); @@ -994,17 +1300,15 @@ async fn inbound_realtime_text_steers_active_turn() -> Result<()> { let realtime_server = start_websocket_server(vec![vec![ vec![json!({ - "type": "session.created", - "session": { "id": "sess_steer" } + "type": "session.updated", + "session": { "id": "sess_steer", "instructions": "backend prompt" } })], - vec![], vec![json!({ - "type": "conversation.item.added", - "item": { - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "steer via realtime"}] - } + "type": "conversation.handoff.requested", + "handoff_id": "handoff_steer", + "item_id": "item_steer", + "input_transcript": "steer via realtime", + "messages": [{ "role": "user", "text": "steer via realtime" }] })], ]]) .await; @@ -1025,7 +1329,7 @@ async fn inbound_realtime_text_steers_active_turn() -> Result<()> { .await?; let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, + payload: RealtimeEvent::SessionUpdated { session_id, .. }, }) if session_id == "sess_steer" => Some(()), _ => None, }) @@ -1059,16 +1363,8 @@ async fn inbound_realtime_text_steers_active_turn() -> Result<()> { let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::ConversationItemAdded(item), - }) => item - .get("content") - .and_then(Value::as_array) - .into_iter() - .flatten() - .any(|content| { - content.get("text").and_then(Value::as_str) == Some("steer via realtime") - }) - .then_some(()), + payload: RealtimeEvent::HandoffRequested(handoff), + }) if handoff.input_transcript == "steer via realtime" => Some(()), _ => None, }) .await; @@ -1108,7 +1404,7 @@ async fn inbound_realtime_text_steers_active_turn() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn inbound_spawn_transcript_starts_turn_and_does_not_block_realtime_audio() -> Result<()> { +async fn inbound_handoff_request_starts_turn_and_does_not_block_realtime_audio() -> Result<()> { skip_if_no_network!(Ok(())); let (gate_completed_tx, gate_completed_rx) = oneshot::channel(); @@ -1124,33 +1420,24 @@ async fn inbound_spawn_transcript_starts_turn_and_does_not_block_realtime_audio( ]; let (api_server, completions) = start_streaming_sse_server(vec![first_chunks]).await; - let delegated_text = "delegate from spawn transcript"; + let delegated_text = "delegate from handoff request"; let realtime_server = start_websocket_server(vec![vec![vec![ json!({ - "type": "session.created", - "session": { "id": "sess_spawn_transcript" } + "type": "session.updated", + "session": { "id": "sess_handoff_request", "instructions": "backend prompt" } }), json!({ - "type": "conversation.item.added", - "item": { - "type": "spawn_transcript", - "seq": 1, - "full_user_transcript": delegated_text, - "delta_user_transcript": delegated_text, - "backend_prompt_messages": [{ - "role": "user", - "channel": null, - "content": delegated_text, - "content_type": "text" - }], - "transcript_source": "backend_prompt_messages" - } + "type": "conversation.handoff.requested", + "handoff_id": "handoff_audio", + "item_id": "item_audio", + "input_transcript": delegated_text, + "messages": [{ "role": "user", "text": delegated_text }] }), json!({ - "type": "response.output_audio.delta", + "type": "conversation.output_audio.delta", "delta": "AQID", "sample_rate": 24000, - "num_channels": 1 + "channels": 1 }), ]]]) .await; @@ -1172,18 +1459,17 @@ async fn inbound_spawn_transcript_starts_turn_and_does_not_block_realtime_audio( let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::SessionCreated { session_id }, - }) if session_id == "sess_spawn_transcript" => Some(()), + payload: RealtimeEvent::SessionUpdated { session_id, .. }, + }) if session_id == "sess_handoff_request" => Some(()), _ => None, }) .await; let _ = wait_for_event_match(&test.codex, |msg| match msg { EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent { - payload: RealtimeEvent::ConversationItemAdded(item), - }) => (item.get("type").and_then(Value::as_str) == Some("spawn_transcript") - && item.get("delta_user_transcript").and_then(Value::as_str) == Some(delegated_text)) - .then_some(()), + payload: RealtimeEvent::HandoffRequested(handoff), + }) => (handoff.handoff_id == "handoff_audio" && handoff.input_transcript == delegated_text) + .then_some(()), _ => None, }) .await; @@ -1198,7 +1484,7 @@ async fn inbound_spawn_transcript_starts_turn_and_does_not_block_realtime_audio( }), ) .await - .expect("timed out waiting for realtime audio after spawn_transcript"); + .expect("timed out waiting for realtime audio after handoff request"); assert_eq!(audio_out.data, "AQID"); let completion = completions diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 74a5b6d90c..63f15f9c0d 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -139,6 +139,7 @@ async fn remote_models_long_model_slug_is_sent_with_high_reasoning() -> Result<( }, ]; remote_model.supports_reasoning_summaries = true; + remote_model.default_reasoning_summary = ReasoningSummary::Detailed; mount_models_once( &server, ModelsResponse { @@ -175,7 +176,8 @@ async fn remote_models_long_model_slug_is_sent_with_high_reasoning() -> Result<( sandbox_policy: config.permissions.sandbox_policy.get().clone(), model: requested_model.to_string(), effort: None, - summary: config.model_reasoning_summary, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -189,8 +191,13 @@ async fn remote_models_long_model_slug_is_sent_with_high_reasoning() -> Result<( .get("reasoning") .and_then(|reasoning| reasoning.get("effort")) .and_then(|value| value.as_str()); + let reasoning_summary = body + .get("reasoning") + .and_then(|reasoning| reasoning.get("summary")) + .and_then(|value| value.as_str()); assert_eq!(body["model"].as_str(), Some(requested_model)); assert_eq!(reasoning_effort, Some("high")); + assert_eq!(reasoning_summary, Some("detailed")); Ok(()) } @@ -227,7 +234,12 @@ async fn namespaced_model_slug_uses_catalog_metadata_without_fallback_warning() sandbox_policy: config.permissions.sandbox_policy.get().clone(), model: requested_model.to_string(), effort: None, - summary: config.model_reasoning_summary, + summary: Some( + config + .model_reasoning_summary + .unwrap_or(ReasoningSummary::Auto), + ), + service_tier: None, collaboration_mode: None, personality: None, }) @@ -284,8 +296,10 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -343,6 +357,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { model: Some(REMOTE_MODEL_SLUG.to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -379,7 +394,8 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: REMOTE_MODEL_SLUG.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: Some(ReasoningSummary::Auto), + service_tier: None, collaboration_mode: None, personality: None, }) @@ -520,8 +536,10 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { base_instructions: remote_base.to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -573,6 +591,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { model: Some(model.to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -590,7 +609,8 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: model.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: Some(ReasoningSummary::Auto), + service_tier: None, collaboration_mode: None, personality: None, }) @@ -830,8 +850,9 @@ async fn remote_models_request_times_out_after_5s() -> Result<()> { let elapsed = start.elapsed(); // get_model should return a default model even when refresh times out let default_model = model.expect("get_model should finish and return default model"); + let expected_default = bundled_default_model_slug(); assert!( - default_model == "gpt-5.2-codex", + default_model == expected_default, "get_model should return default model when refresh times out, got: {default_model}" ); let _ = server @@ -889,7 +910,7 @@ async fn remote_models_hide_picker_only_models() -> Result<()> { let selected = manager .get_default_model(&None, RefreshStrategy::OnlineIfUncached) .await; - assert_eq!(selected, "gpt-5.2-codex"); + assert_eq!(selected, bundled_default_model_slug()); let available = manager.list_models(RefreshStrategy::OnlineIfUncached).await; let hidden = available @@ -935,6 +956,15 @@ fn bundled_model_slug() -> String { .clone() } +fn bundled_default_model_slug() -> String { + codex_core::test_support::all_model_presets() + .iter() + .find(|preset| preset.is_default) + .expect("bundled models should include a default") + .model + .clone() +} + fn test_remote_model(slug: &str, visibility: ModelVisibility, priority: i32) -> ModelInfo { test_remote_model_with_policy( slug, @@ -970,8 +1000,10 @@ fn test_remote_model_with_policy( base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy, supports_parallel_tool_calls: false, diff --git a/codex-rs/core/tests/suite/request_permissions.rs b/codex-rs/core/tests/suite/request_permissions.rs index cda482079a..6f898e8c03 100644 --- a/codex-rs/core/tests/suite/request_permissions.rs +++ b/codex-rs/core/tests/suite/request_permissions.rs @@ -4,7 +4,6 @@ use anyhow::Result; use codex_core::config::Constrained; use codex_core::features::Feature; use codex_core::sandboxing::SandboxPermissions; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::FileSystemPermissions; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; @@ -14,6 +13,7 @@ use codex_protocol::protocol::Op; use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; +use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; @@ -32,6 +32,11 @@ use regex_lite::Regex; use serde_json::Value; use serde_json::json; use std::fs; +use std::path::Path; + +fn absolute_path(path: &Path) -> AbsolutePathBuf { + AbsolutePathBuf::try_from(path).expect("absolute path") +} struct CommandResult { exit_code: Option, @@ -92,6 +97,24 @@ fn shell_event_with_request_permissions( Ok(ev_function_call(call_id, "shell_command", &args_str)) } +#[cfg(target_os = "macos")] +fn shell_event_with_raw_request_permissions( + call_id: &str, + command: &str, + workdir: Option<&str>, + additional_permissions: Value, +) -> Result { + let args = json!({ + "command": command, + "workdir": workdir, + "timeout_ms": 1_000_u64, + "sandbox_permissions": SandboxPermissions::WithAdditionalPermissions, + "additional_permissions": additional_permissions, + }); + let args_str = serde_json::to_string(&args)?; + Ok(ev_function_call(call_id, "shell_command", &args_str)) +} + async fn submit_turn( test: &TestCodex, prompt: &str, @@ -111,7 +134,8 @@ async fn submit_turn( sandbox_policy, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -188,7 +212,7 @@ async fn with_additional_permissions_requires_approval_under_on_request() -> Res let requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![requested_write.clone()]), + write: Some(vec![absolute_path(&requested_write)]), }), ..Default::default() }; @@ -242,6 +266,98 @@ async fn with_additional_permissions_requires_approval_under_on_request() -> Res Ok(()) } +#[tokio::test(flavor = "current_thread")] +#[cfg(target_os = "macos")] +async fn relative_additional_permissions_resolve_against_tool_workdir() -> Result<()> { + skip_if_no_network!(Ok(())); + skip_if_sandbox!(Ok(())); + + let server = start_mock_server().await; + let approval_policy = AskForApproval::OnRequest; + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let sandbox_policy_for_config = sandbox_policy.clone(); + + let mut builder = test_codex().with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(approval_policy); + config.permissions.sandbox_policy = Constrained::allow_any(sandbox_policy_for_config); + config.features.enable(Feature::RequestPermissions); + }); + let test = builder.build(&server).await?; + + let nested_dir = test.workspace_path("nested"); + fs::create_dir_all(&nested_dir)?; + let requested_write = nested_dir.join("relative-write.txt"); + let _ = fs::remove_file(&requested_write); + + let call_id = "request_permissions_relative_workdir"; + let command = "touch relative-write.txt"; + let expected_permissions = PermissionProfile { + file_system: Some(FileSystemPermissions { + read: None, + write: Some(vec![absolute_path(&requested_write)]), + }), + ..Default::default() + }; + let event = shell_event_with_raw_request_permissions( + call_id, + command, + Some("nested"), + json!({ + "file_system": { + "write": ["./relative-write.txt"], + }, + }), + )?; + + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-relative-1"), + event, + ev_completed("resp-relative-1"), + ]), + ) + .await; + let results = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-relative-1", "done"), + ev_completed("resp-relative-2"), + ]), + ) + .await; + + submit_turn(&test, call_id, approval_policy, sandbox_policy.clone()).await?; + + let approval = expect_exec_approval(&test, command).await; + assert_eq!( + approval.additional_permissions, + Some(expected_permissions.clone()) + ); + 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!( + result.exit_code.is_none() || result.exit_code == Some(0), + "unexpected exit code/output: {:?} {}", + result.exit_code, + result.stdout + ); + assert!( + requested_write.exists(), + "touch command should create requested path" + ); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] #[cfg(target_os = "macos")] async fn read_only_with_additional_permissions_widens_to_unrequested_cwd_write() -> Result<()> { @@ -273,7 +389,7 @@ async fn read_only_with_additional_permissions_widens_to_unrequested_cwd_write() let requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![requested_write.clone()]), + write: Some(vec![absolute_path(&requested_write)]), }), ..Default::default() }; @@ -364,7 +480,7 @@ async fn read_only_with_additional_permissions_widens_to_unrequested_tmp_write() let requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![requested_write.clone()]), + write: Some(vec![absolute_path(&requested_write)]), }), ..Default::default() }; @@ -455,14 +571,16 @@ async fn workspace_write_with_additional_permissions_can_write_outside_cwd() -> let requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![outside_dir.path().to_path_buf()]), + write: Some(vec![absolute_path(outside_dir.path())]), }), ..Default::default() }; let normalized_requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![outside_dir.path().canonicalize()?]), + write: Some(vec![AbsolutePathBuf::try_from( + outside_dir.path().canonicalize()?, + )?]), }), ..Default::default() }; @@ -549,14 +667,16 @@ async fn with_additional_permissions_denied_approval_blocks_execution() -> Resul let requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![outside_dir.path().to_path_buf()]), + write: Some(vec![absolute_path(outside_dir.path())]), }), ..Default::default() }; let normalized_requested_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { read: Some(vec![]), - write: Some(vec![outside_dir.path().canonicalize()?]), + write: Some(vec![AbsolutePathBuf::try_from( + outside_dir.path().canonicalize()?, + )?]), }), ..Default::default() }; diff --git a/codex-rs/core/tests/suite/request_user_input.rs b/codex-rs/core/tests/suite/request_user_input.rs index ac6c1d2f3f..f767234c89 100644 --- a/codex-rs/core/tests/suite/request_user_input.rs +++ b/codex-rs/core/tests/suite/request_user_input.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use codex_core::features::Feature; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::Settings; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -86,8 +85,10 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul session_configured, .. } = builder - .with_config(|config| { - config.features.enable(Feature::CollaborationModes); + .with_config(move |config| { + if mode == ModeKind::Default { + config.features.enable(Feature::DefaultModeRequestUserInput); + } }) .build(&server) .await?; @@ -136,7 +137,8 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(CollaborationMode { mode, settings: Settings { @@ -198,18 +200,13 @@ where let server = start_mock_server().await; - let builder = test_codex(); + let mut builder = test_codex(); let TestCodex { codex, cwd, session_configured, .. - } = builder - .with_config(|config| { - config.features.enable(Feature::CollaborationModes); - }) - .build(&server) - .await?; + } = builder.build(&server).await?; let mode_slug = mode_name.to_lowercase().replace(' ', "-"); let call_id = format!("user-input-{mode_slug}-call"); @@ -257,7 +254,8 @@ where sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: Some(collaboration_mode), personality: None, }) @@ -290,7 +288,7 @@ async fn request_user_input_rejected_in_execute_mode_alias() -> anyhow::Result<( } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn request_user_input_rejected_in_default_mode() -> anyhow::Result<()> { +async fn request_user_input_rejected_in_default_mode_by_default() -> anyhow::Result<()> { assert_request_user_input_rejected("Default", |model| CollaborationMode { mode: ModeKind::Default, settings: Settings { @@ -302,6 +300,11 @@ async fn request_user_input_rejected_in_default_mode() -> anyhow::Result<()> { .await } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn request_user_input_round_trip_in_default_mode_with_feature() -> anyhow::Result<()> { + request_user_input_round_trip_for_mode(ModeKind::Default).await +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn request_user_input_rejected_in_pair_mode_alias() -> anyhow::Result<()> { assert_request_user_input_rejected("Pair Programming", |model| CollaborationMode { diff --git a/codex-rs/core/tests/suite/resume.rs b/codex-rs/core/tests/suite/resume.rs index 3d75879e49..98a570a1d9 100644 --- a/codex-rs/core/tests/suite/resume.rs +++ b/codex-rs/core/tests/suite/resume.rs @@ -340,6 +340,7 @@ async fn resume_model_switch_is_not_duplicated_after_pre_turn_override() -> Resu model: Some("gpt-5.1-codex-max".to_string()), effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index b0503d5929..ca40c0c191 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -4,6 +4,7 @@ use codex_core::CodexAuth; use codex_core::NewThread; use codex_protocol::ThreadId; use codex_protocol::config_types::ModeKind; +use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::ResumedHistory; @@ -27,14 +28,19 @@ fn resume_history( let turn_ctx = TurnContextItem { turn_id: Some(turn_id.clone()), cwd: config.cwd.clone(), + current_date: None, + timezone: None, approval_policy: config.permissions.approval_policy.value(), sandbox_policy: config.permissions.sandbox_policy.get().clone(), network: None, model: previous_model.to_string(), personality: None, collaboration_mode: None, + realtime_active: None, effort: config.model_reasoning_effort, - summary: config.model_reasoning_summary, + summary: config + .model_reasoning_summary + .unwrap_or(ReasoningSummary::Auto), user_instructions: None, developer_instructions: None, final_output_json_schema: None, diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index a123981444..3a18cf157b 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -605,7 +605,9 @@ async fn review_input_isolated_from_parent_history() { let env_text = input .iter() - .filter_map(|msg| msg["content"][0]["text"].as_str()) + .filter_map(|msg| msg.get("content").and_then(|content| content.as_array())) + .flat_map(|content| content.iter()) + .filter_map(|entry| entry.get("text").and_then(|text| text.as_str())) .find(|text| text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG)) .expect("env text"); assert!( @@ -615,7 +617,9 @@ async fn review_input_isolated_from_parent_history() { let review_text = input .iter() - .filter_map(|msg| msg["content"][0]["text"].as_str()) + .filter_map(|msg| msg.get("content").and_then(|content| content.as_array())) + .flat_map(|content| content.iter()) + .filter_map(|entry| entry.get("text").and_then(|text| text.as_str())) .find(|text| *text == review_prompt) .expect("review prompt text"); assert_eq!( @@ -826,6 +830,7 @@ async fn review_uses_overridden_cwd_for_base_branch_merge_base() { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index df389c5ef7..06c0042985 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -104,6 +104,7 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -128,7 +129,8 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -246,6 +248,7 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -295,7 +298,8 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -398,8 +402,10 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -462,6 +468,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -492,7 +499,8 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re sandbox_policy: SandboxPolicy::new_read_only_policy(), model: text_only_model_slug.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -580,6 +588,7 @@ async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -604,7 +613,8 @@ async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -739,6 +749,7 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -763,7 +774,8 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -958,6 +970,7 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -982,7 +995,8 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/safety_check_downgrade.rs b/codex-rs/core/tests/suite/safety_check_downgrade.rs index 247cfdaedc..eabbdc9d03 100644 --- a/codex-rs/core/tests/suite/safety_check_downgrade.rs +++ b/codex-rs/core/tests/suite/safety_check_downgrade.rs @@ -1,5 +1,4 @@ use anyhow::Result; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::AskForApproval; @@ -49,7 +48,8 @@ async fn openai_model_header_mismatch_emits_warning_event_and_warning_item() -> sandbox_policy: SandboxPolicy::DangerFullAccess, model: REQUESTED_MODEL.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -146,7 +146,8 @@ async fn response_model_field_mismatch_emits_warning_when_header_matches_request sandbox_policy: SandboxPolicy::DangerFullAccess, model: REQUESTED_MODEL.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -230,7 +231,8 @@ async fn openai_model_header_mismatch_only_emits_one_warning_per_turn() -> Resul sandbox_policy: SandboxPolicy::DangerFullAccess, model: REQUESTED_MODEL.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -278,7 +280,8 @@ async fn openai_model_header_casing_only_mismatch_does_not_warn() -> Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: REQUESTED_MODEL.to_string(), effort: test.config.model_reasoning_effort, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/search_tool.rs b/codex-rs/core/tests/suite/search_tool.rs index 1caab45b12..d852c9cfb3 100644 --- a/codex-rs/core/tests/suite/search_tool.rs +++ b/codex-rs/core/tests/suite/search_tool.rs @@ -133,6 +133,7 @@ fn rmcp_server_config(command: String) -> McpServerConfig { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, } } diff --git a/codex-rs/core/tests/suite/shell_snapshot.rs b/codex-rs/core/tests/suite/shell_snapshot.rs index 3be9d2b579..59c13fa50d 100644 --- a/codex-rs/core/tests/suite/shell_snapshot.rs +++ b/codex-rs/core/tests/suite/shell_snapshot.rs @@ -1,6 +1,5 @@ use anyhow::Result; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ExecCommandBeginEvent; @@ -162,7 +161,8 @@ async fn run_snapshot_command_with_options( sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -248,7 +248,8 @@ async fn run_shell_command_snapshot_with_options( sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -317,7 +318,8 @@ async fn run_tool_turn_on_harness( sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -535,7 +537,8 @@ async fn shell_command_snapshot_still_intercepts_apply_patch() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/skill_approval.rs b/codex-rs/core/tests/suite/skill_approval.rs index 147ecdd0c2..d81cbb5c66 100644 --- a/codex-rs/core/tests/suite/skill_approval.rs +++ b/codex-rs/core/tests/suite/skill_approval.rs @@ -1,55 +1,39 @@ -#![allow(clippy::expect_used, clippy::unwrap_used)] +#![allow(clippy::unwrap_used)] +#![cfg(unix)] use anyhow::Result; -use codex_core::features::Feature; -#[cfg(unix)] use codex_protocol::models::FileSystemPermissions; -#[cfg(unix)] use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecApprovalRequestEvent; use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::skill_approval::SkillApprovalResponse; -use core_test_support::responses::ev_assistant_message; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; -use core_test_support::responses::ev_response_created; +use codex_protocol::user_input::UserInput; +use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::responses::mount_function_call_agent_response; -use core_test_support::responses::mount_sse_sequence; -use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; -use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; +use core_test_support::zsh_fork::build_zsh_fork_test; +use core_test_support::zsh_fork::restrictive_workspace_write_policy; +use core_test_support::zsh_fork::zsh_fork_runtime; use pretty_assertions::assert_eq; use serde_json::json; use std::fs; use std::path::Path; use std::path::PathBuf; -fn write_skill_with_script(home: &Path, name: &str, script_body: &str) -> Result { - let skill_dir = home.join("skills").join(name); - let scripts_dir = skill_dir.join("scripts"); - fs::create_dir_all(&scripts_dir)?; - fs::write( - skill_dir.join("SKILL.md"), - format!( - r#"--- -name: {name} -description: {name} skill ---- -"# - ), - )?; - let script_path = scripts_dir.join("run.py"); - fs::write(&script_path, script_body)?; - Ok(script_path) +fn absolute_path(path: &Path) -> AbsolutePathBuf { + match AbsolutePathBuf::try_from(path) { + Ok(path) => path, + Err(err) => panic!("absolute path: {err}"), + } } -#[cfg(unix)] fn write_skill_metadata(home: &Path, name: &str, contents: &str) -> Result<()> { let metadata_dir = home.join("skills").join(name).join("agents"); fs::create_dir_all(&metadata_dir)?; @@ -64,40 +48,15 @@ fn shell_command_arguments(command: &str) -> Result { }))?) } -fn assistant_response(message: &str) -> String { - sse(vec![ - ev_response_created("resp-2"), - ev_assistant_message("msg-1", message), - ev_completed("resp-2"), - ]) -} - -fn command_for_script(script_path: &Path) -> Result { - let runner = if cfg!(windows) { "python" } else { "python3" }; - let script_path = script_path.to_string_lossy().into_owned(); - Ok(shlex::try_join([runner, script_path.as_str()])?) -} - -async fn submit_turn(test: &TestCodex, prompt: &str) -> Result<()> { - submit_turn_with_policies( - test, - prompt, - AskForApproval::Never, - SandboxPolicy::DangerFullAccess, - ) - .await -} - async fn submit_turn_with_policies( test: &TestCodex, prompt: &str, approval_policy: AskForApproval, sandbox_policy: SandboxPolicy, ) -> Result<()> { - let session_model = test.session_configured.model.clone(); test.codex .submit(Op::UserTurn { - items: vec![codex_protocol::user_input::UserInput::Text { + items: vec![UserInput::Text { text: prompt.to_string(), text_elements: Vec::new(), }], @@ -105,9 +64,10 @@ async fn submit_turn_with_policies( cwd: test.cwd_path().to_path_buf(), approval_policy, sandbox_policy, - model: session_model, + model: test.session_configured.model.clone(), effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -115,19 +75,25 @@ async fn submit_turn_with_policies( Ok(()) } -async fn wait_for_turn_complete_without_skill_approval(test: &TestCodex) { - wait_for_event_match(test.codex.as_ref(), |event| match event { - EventMsg::SkillRequestApproval(request) => { - panic!("unexpected skill approval request: {request:?}"); - } - EventMsg::TurnComplete(_) => Some(()), - _ => None, - }) - .await; +fn write_skill_with_shell_script(home: &Path, name: &str, script_name: &str) -> Result { + write_skill_with_shell_script_contents( + home, + name, + script_name, + r#"#!/bin/sh +echo 'zsh-fork-stdout' +echo 'zsh-fork-stderr' >&2 +"#, + ) } #[cfg(unix)] -fn write_skill_with_shell_script(home: &Path, name: &str, script_name: &str) -> Result { +fn write_skill_with_shell_script_contents( + home: &Path, + name: &str, + script_name: &str, + script_contents: &str, +) -> Result { use std::os::unix::fs::PermissionsExt; let skill_dir = home.join("skills").join(name); @@ -145,313 +111,65 @@ description: {name} skill )?; let script_path = scripts_dir.join(script_name); - fs::write( - &script_path, - r#"#!/bin/sh -echo 'zsh-fork-stdout' -echo 'zsh-fork-stderr' >&2 -"#, - )?; + fs::write(&script_path, script_contents)?; let mut permissions = fs::metadata(&script_path)?.permissions(); permissions.set_mode(0o755); fs::set_permissions(&script_path, permissions)?; Ok(script_path) } -#[cfg(unix)] -fn find_test_zsh_path() -> Result> { - use core_test_support::fetch_dotslash_file; - - let repo_root = codex_utils_cargo_bin::repo_root()?; - let dotslash_zsh = repo_root.join("codex-rs/app-server/tests/suite/zsh"); - if !dotslash_zsh.is_file() { - eprintln!( - "skipping zsh-fork skill test: shared zsh DotSlash file not found at {}", - dotslash_zsh.display() - ); - return Ok(None); - } - - match fetch_dotslash_file(&dotslash_zsh, None) { - Ok(path) => Ok(Some(path)), - Err(error) => { - eprintln!("skipping zsh-fork skill test: failed to fetch zsh via dotslash: {error:#}"); - Ok(None) - } - } +fn skill_script_command(test: &TestCodex, script_name: &str) -> Result<(String, String)> { + let script_path = fs::canonicalize( + test.codex_home_path() + .join("skills/mbolin-test-skill/scripts") + .join(script_name), + )?; + let script_path_str = script_path.to_string_lossy().into_owned(); + let command = shlex::try_join([script_path_str.as_str()])?; + Ok((script_path_str, command)) } -#[cfg(unix)] -fn supports_exec_wrapper_intercept(zsh_path: &Path) -> bool { - let status = std::process::Command::new(zsh_path) - .arg("-fc") - .arg("/usr/bin/true") - .env("EXEC_WRAPPER", "/usr/bin/false") - .status(); - match status { - Ok(status) => !status.success(), - Err(_) => false, - } -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn skill_approval_event_round_trip_for_shell_command_skill_script_exec() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = start_mock_server().await; - let tool_call_id = "shell-skill-call"; - let mut builder = test_codex() - .with_pre_build_hook(|home| { - write_skill_with_script(home, "demo", "print('shell skill approved')").unwrap(); - }) - .with_config(|config| { - config.features.enable(Feature::SkillApproval); - }); - let test = builder.build(&server).await?; - let script_path = test.codex_home_path().join("skills/demo/scripts/run.py"); - let command = command_for_script(&script_path)?; - let arguments = shell_command_arguments(&command)?; - let _mocks = - mount_function_call_agent_response(&server, tool_call_id, &arguments, "shell_command") - .await; - - submit_turn(&test, "run the shell skill").await?; - - let request = wait_for_event_match(test.codex.as_ref(), |event| match event { - EventMsg::SkillRequestApproval(request) => Some(request.clone()), +async fn wait_for_exec_approval_request(test: &TestCodex) -> Option { + wait_for_event_match(test.codex.as_ref(), |event| match event { + EventMsg::ExecApprovalRequest(request) => Some(Some(request.clone())), + EventMsg::TurnComplete(_) => Some(None), _ => None, }) - .await; - assert_eq!(request.item_id, tool_call_id); - assert_eq!(request.skill_name, "demo"); - - test.codex - .submit(Op::SkillApproval { - id: request.item_id, - response: SkillApprovalResponse { approved: true }, - }) - .await?; + .await +} +async fn wait_for_turn_complete(test: &TestCodex) { wait_for_event(test.codex.as_ref(), |event| { matches!(event, EventMsg::TurnComplete(_)) }) .await; - - Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn skill_approval_not_emitted_without_skill_script_exec() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = start_mock_server().await; - let tool_call_id = "non-skill-call"; - let mut builder = test_codex().with_config(|config| { - config.features.enable(Feature::SkillApproval); - }); - let test = builder.build(&server).await?; - let arguments = shell_command_arguments("echo no-skill")?; - let _mocks = - mount_function_call_agent_response(&server, tool_call_id, &arguments, "shell_command") - .await; - - submit_turn(&test, "run a plain command").await?; - wait_for_turn_complete_without_skill_approval(&test).await; - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn skill_approval_decline_blocks_execution() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = start_mock_server().await; - let tool_call_id = "decline-call"; - let marker_name = "declined-marker.txt"; - let mut builder = test_codex() - .with_pre_build_hook(move |home| { - let marker_path = home.join(marker_name); - let marker_path = marker_path.to_string_lossy(); - let script_body = format!( - r#"from pathlib import Path -Path({marker_path:?}).write_text('ran') -print('ran') -"# - ); - write_skill_with_script(home, "demo", &script_body).unwrap(); - }) - .with_config(|config| { - config.features.enable(Feature::SkillApproval); - }); - let test = builder.build(&server).await?; - let script_path = test.codex_home_path().join("skills/demo/scripts/run.py"); - let command = command_for_script(&script_path)?; - let arguments = shell_command_arguments(&command)?; - let mocks = - mount_function_call_agent_response(&server, tool_call_id, &arguments, "shell_command") - .await; - - submit_turn(&test, "run the skill").await?; - - let request = wait_for_event_match(test.codex.as_ref(), |event| match event { - EventMsg::SkillRequestApproval(request) => Some(request.clone()), - _ => None, - }) - .await; - assert_eq!(request.item_id, tool_call_id); - - test.codex - .submit(Op::SkillApproval { - id: request.item_id, - response: SkillApprovalResponse { approved: false }, - }) - .await?; - - wait_for_event(test.codex.as_ref(), |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - - let marker_path = test.codex_home_path().join(marker_name); - assert!( - !marker_path.exists(), - "declined skill approval should block script execution" - ); - - let call_output = mocks - .completion - .single_request() - .function_call_output(tool_call_id); - assert_eq!( - call_output["output"].as_str(), - Some("This script is part of the skill and the user declined the skill usage"), - ); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn skill_approval_cache_is_per_skill() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = start_mock_server().await; - let first_call_id = "skill-a-1"; - let second_call_id = "skill-a-2"; - let third_call_id = "skill-b-1"; - let mut builder = test_codex() - .with_pre_build_hook(|home| { - write_skill_with_script(home, "alpha", "print('alpha')").unwrap(); - write_skill_with_script(home, "beta", "print('beta')").unwrap(); - }) - .with_config(|config| { - config.features.enable(Feature::SkillApproval); - }); - let test = builder.build(&server).await?; - let alpha_command = - command_for_script(&test.codex_home_path().join("skills/alpha/scripts/run.py"))?; - let beta_command = - command_for_script(&test.codex_home_path().join("skills/beta/scripts/run.py"))?; - let first_alpha_arguments = shell_command_arguments(&alpha_command)?; - let second_alpha_arguments = shell_command_arguments(&alpha_command)?; - let beta_arguments = shell_command_arguments(&beta_command)?; - - mount_sse_sequence( - &server, - vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_function_call(first_call_id, "shell_command", &first_alpha_arguments), - ev_completed("resp-1"), - ]), - assistant_response("alpha-1"), - sse(vec![ - ev_response_created("resp-1"), - ev_function_call(second_call_id, "shell_command", &second_alpha_arguments), - ev_completed("resp-1"), - ]), - assistant_response("alpha-2"), - sse(vec![ - ev_response_created("resp-1"), - ev_function_call(third_call_id, "shell_command", &beta_arguments), - ev_completed("resp-1"), - ]), - assistant_response("beta-1"), - ], - ) - .await; - - submit_turn(&test, "run alpha").await?; - let first_request = wait_for_event_match(test.codex.as_ref(), |event| match event { - EventMsg::SkillRequestApproval(request) => Some(request.clone()), - _ => None, - }) - .await; - assert_eq!(first_request.item_id, first_call_id); - assert_eq!(first_request.skill_name, "alpha"); - test.codex - .submit(Op::SkillApproval { - id: first_request.item_id, - response: SkillApprovalResponse { approved: true }, - }) - .await?; - wait_for_event(test.codex.as_ref(), |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - - submit_turn(&test, "run alpha again").await?; - wait_for_turn_complete_without_skill_approval(&test).await; - - submit_turn(&test, "run beta").await?; - let third_request = wait_for_event_match(test.codex.as_ref(), |event| match event { - EventMsg::SkillRequestApproval(request) => Some(request.clone()), - _ => None, - }) - .await; - assert_eq!(third_request.item_id, third_call_id); - assert_eq!(third_request.skill_name, "beta"); - test.codex - .submit(Op::SkillApproval { - id: third_request.item_id, - response: SkillApprovalResponse { approved: true }, - }) - .await?; - wait_for_event(test.codex.as_ref(), |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - - Ok(()) +fn output_shows_sandbox_denial(output: &str) -> bool { + output.contains("Permission denied") + || output.contains("Operation not permitted") + || output.contains("Read-only file system") } +/// Focus on the approval payload: the skill should prompt before execution and +/// only advertise the permissions declared in its metadata. #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_zsh_fork_prompts_for_skill_script_execution() -> Result<()> { - use codex_config::Constrained; - use codex_protocol::protocol::ReviewDecision; - skip_if_no_network!(Ok(())); - let Some(zsh_path) = find_test_zsh_path()? else { - return Ok(()); - }; - if !supports_exec_wrapper_intercept(&zsh_path) { - eprintln!( - "skipping zsh-fork skill test: zsh does not support EXEC_WRAPPER intercepts ({})", - zsh_path.display() - ); - return Ok(()); - } - let Ok(main_execve_wrapper_exe) = codex_utils_cargo_bin::cargo_bin("codex-execve-wrapper") - else { - eprintln!("skipping zsh-fork skill test: unable to resolve `codex-execve-wrapper` binary"); + let Some(runtime) = zsh_fork_runtime("zsh-fork skill prompt test")? else { return Ok(()); }; let server = start_mock_server().await; let tool_call_id = "zsh-fork-skill-call"; - let mut builder = test_codex() - .with_pre_build_hook(|home| { + let test = build_zsh_fork_test( + &server, + runtime, + AskForApproval::OnRequest, + SandboxPolicy::new_workspace_write_policy(), + |home| { write_skill_with_shell_script(home, "mbolin-test-skill", "hello-mbolin.sh").unwrap(); write_skill_metadata( home, @@ -466,25 +184,11 @@ permissions: "#, ) .unwrap(); - }) - .with_config(move |config| { - config.features.enable(Feature::ShellTool); - config.features.enable(Feature::ShellZshFork); - config.zsh_path = Some(zsh_path.clone()); - config.main_execve_wrapper_exe = Some(main_execve_wrapper_exe); - config.permissions.allow_login_shell = false; - config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); - config.permissions.sandbox_policy = - Constrained::allow_any(SandboxPolicy::new_workspace_write_policy()); - }); - let test = builder.build(&server).await?; + }, + ) + .await?; - let script_path = fs::canonicalize( - test.codex_home_path() - .join("skills/mbolin-test-skill/scripts/hello-mbolin.sh"), - )?; - let script_path_str = script_path.to_string_lossy().into_owned(); - let command = shlex::try_join([script_path_str.as_str()])?; + let (script_path_str, command) = skill_script_command(&test, "hello-mbolin.sh")?; let arguments = shell_command_arguments(&command)?; let mocks = mount_function_call_agent_response(&server, tool_call_id, &arguments, "shell_command") @@ -498,12 +202,7 @@ permissions: ) .await?; - let maybe_approval = wait_for_event_match(test.codex.as_ref(), |event| match event { - EventMsg::ExecApprovalRequest(request) => Some(Some(request.clone())), - EventMsg::TurnComplete(_) => Some(None), - _ => None, - }) - .await; + let maybe_approval = wait_for_exec_approval_request(&test).await; let approval = match maybe_approval { Some(approval) => approval, None => { @@ -518,12 +217,26 @@ permissions: }; assert_eq!(approval.call_id, tool_call_id); assert_eq!(approval.command, vec![script_path_str.clone()]); + assert_eq!( + approval.available_decisions, + Some(vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::Abort, + ]) + ); assert_eq!( approval.additional_permissions, Some(PermissionProfile { file_system: Some(FileSystemPermissions { - read: Some(vec![PathBuf::from("./data")]), - write: Some(vec![PathBuf::from("./output")]), + read: Some(vec![absolute_path( + &test.codex_home_path().join("skills/mbolin-test-skill/data"), + )]), + write: Some(vec![absolute_path( + &test + .codex_home_path() + .join("skills/mbolin-test-skill/output"), + )]), }), ..Default::default() }) @@ -533,14 +246,11 @@ permissions: .submit(Op::ExecApproval { id: approval.effective_approval_id(), turn_id: None, - decision: ReviewDecision::Approved, + decision: ReviewDecision::Denied, }) .await?; - wait_for_event(test.codex.as_ref(), |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; + wait_for_turn_complete(&test).await; let call_output = mocks .completion @@ -548,12 +258,520 @@ permissions: .function_call_output(tool_call_id); let output = call_output["output"].as_str().unwrap_or_default(); assert!( - output.contains("zsh-fork-stdout"), - "expected stdout marker in function_call_output: {output:?}" - ); - assert!( - output.contains("zsh-fork-stderr"), - "expected stderr marker in function_call_output: {output:?}" + output.contains("Execution denied: User denied execution"), + "expected rejection marker in function_call_output: {output:?}" + ); + + Ok(()) +} + +/// Look for `additional_permissions == None`, then verify that both the first +/// run and the cached session-approval rerun stay inside the turn sandbox. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shell_zsh_fork_skill_without_permissions_inherits_turn_sandbox() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("zsh-fork inherited skill sandbox test")? else { + return Ok(()); + }; + + let outside_dir = tempfile::tempdir_in(std::env::current_dir()?)?; + let outside_path = outside_dir + .path() + .join("zsh-fork-skill-inherited-sandbox.txt"); + let outside_path_quoted = shlex::try_join([outside_path.to_string_lossy().as_ref()])?; + let script_contents = format!( + "#!/bin/sh\nprintf '%s' forbidden > {outside_path_quoted}\ncat {outside_path_quoted}\n" + ); + let outside_path_for_hook = outside_path.clone(); + let script_contents_for_hook = script_contents.clone(); + let workspace_write_policy = restrictive_workspace_write_policy(); + + let server = start_mock_server().await; + let test = build_zsh_fork_test( + &server, + runtime, + AskForApproval::OnRequest, + workspace_write_policy.clone(), + move |home| { + let _ = fs::remove_file(&outside_path_for_hook); + write_skill_with_shell_script_contents( + home, + "mbolin-test-skill", + "sandboxed.sh", + &script_contents_for_hook, + ) + .unwrap(); + }, + ) + .await?; + + let (script_path_str, command) = skill_script_command(&test, "sandboxed.sh")?; + + let first_call_id = "zsh-fork-skill-permissions-1"; + let first_arguments = shell_command_arguments(&command)?; + let first_mocks = mount_function_call_agent_response( + &server, + first_call_id, + &first_arguments, + "shell_command", + ) + .await; + + submit_turn_with_policies( + &test, + "use $mbolin-test-skill", + AskForApproval::OnRequest, + workspace_write_policy.clone(), + ) + .await?; + + let maybe_approval = wait_for_exec_approval_request(&test).await; + let approval = match maybe_approval { + Some(approval) => approval, + None => panic!("expected exec approval request before completion"), + }; + assert_eq!(approval.call_id, first_call_id); + assert_eq!(approval.command, vec![script_path_str.clone()]); + assert_eq!(approval.additional_permissions, None); + + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::ApprovedForSession, + }) + .await?; + + wait_for_turn_complete(&test).await; + + let first_output = first_mocks + .completion + .single_request() + .function_call_output(first_call_id)["output"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + output_shows_sandbox_denial(&first_output) || !first_output.contains("forbidden"), + "expected inherited turn sandbox denial on first run, got output: {first_output:?}" + ); + assert!( + !outside_path.exists(), + "first run should not write outside the turn sandbox" + ); + + let second_call_id = "zsh-fork-skill-permissions-2"; + let second_arguments = shell_command_arguments(&command)?; + let second_mocks = mount_function_call_agent_response( + &server, + second_call_id, + &second_arguments, + "shell_command", + ) + .await; + + submit_turn_with_policies( + &test, + "use $mbolin-test-skill", + AskForApproval::OnRequest, + workspace_write_policy, + ) + .await?; + + let cached_approval = wait_for_exec_approval_request(&test).await; + assert!( + cached_approval.is_none(), + "expected second run to reuse the cached session approval" + ); + + let second_output = second_mocks + .completion + .single_request() + .function_call_output(second_call_id)["output"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + output_shows_sandbox_denial(&second_output) || !second_output.contains("forbidden"), + "expected cached skill approval to retain inherited turn sandboxing, got output: {second_output:?}" + ); + assert!( + !outside_path.exists(), + "cached session approval should not widen a permissionless skill to full access" + ); + + Ok(()) +} + +/// Empty skill permissions should behave like no skill override and inherit the +/// turn sandbox instead of forcing an explicit read-only skill sandbox. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shell_zsh_fork_skill_with_empty_permissions_inherits_turn_sandbox() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("zsh-fork empty skill permissions test")? else { + return Ok(()); + }; + + let outside_dir = tempfile::tempdir_in(std::env::current_dir()?)?; + let outside_path = outside_dir + .path() + .join("zsh-fork-skill-empty-permissions.txt"); + let outside_path_quoted = shlex::try_join([outside_path.to_string_lossy().as_ref()])?; + let script_contents = format!( + "#!/bin/sh\nprintf '%s' allowed > {outside_path_quoted}\ncat {outside_path_quoted}\n" + ); + let outside_path_for_hook = outside_path.clone(); + let script_contents_for_hook = script_contents.clone(); + + let server = start_mock_server().await; + let test = build_zsh_fork_test( + &server, + runtime, + AskForApproval::OnRequest, + SandboxPolicy::DangerFullAccess, + move |home| { + let _ = fs::remove_file(&outside_path_for_hook); + write_skill_with_shell_script_contents( + home, + "mbolin-test-skill", + "sandboxed.sh", + &script_contents_for_hook, + ) + .unwrap(); + write_skill_metadata(home, "mbolin-test-skill", "permissions: {}\n").unwrap(); + }, + ) + .await?; + + let (script_path_str, command) = skill_script_command(&test, "sandboxed.sh")?; + + let first_call_id = "zsh-fork-skill-empty-permissions-1"; + let first_arguments = shell_command_arguments(&command)?; + let first_mocks = mount_function_call_agent_response( + &server, + first_call_id, + &first_arguments, + "shell_command", + ) + .await; + + submit_turn_with_policies( + &test, + "use $mbolin-test-skill", + AskForApproval::OnRequest, + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let approval = wait_for_exec_approval_request(&test) + .await + .expect("expected exec approval request before completion"); + assert_eq!(approval.call_id, first_call_id); + assert_eq!(approval.command, vec![script_path_str.clone()]); + assert_eq!(approval.additional_permissions, None); + + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::ApprovedForSession, + }) + .await?; + + wait_for_turn_complete(&test).await; + + let first_output = first_mocks + .completion + .single_request() + .function_call_output(first_call_id)["output"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + first_output.contains("allowed"), + "expected empty skill permissions to inherit full-access turn sandbox, got output: {first_output:?}" + ); + assert_eq!(fs::read_to_string(&outside_path)?, "allowed"); + + let second_call_id = "zsh-fork-skill-empty-permissions-2"; + let second_arguments = shell_command_arguments(&command)?; + let second_mocks = mount_function_call_agent_response( + &server, + second_call_id, + &second_arguments, + "shell_command", + ) + .await; + + let _ = fs::remove_file(&outside_path); + + submit_turn_with_policies( + &test, + "use $mbolin-test-skill", + AskForApproval::OnRequest, + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let cached_approval = wait_for_exec_approval_request(&test).await; + assert!( + cached_approval.is_none(), + "expected second run to reuse the cached session approval" + ); + + let second_output = second_mocks + .completion + .single_request() + .function_call_output(second_call_id)["output"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + second_output.contains("allowed"), + "expected cached empty-permissions skill approval to inherit the turn sandbox, got output: {second_output:?}" + ); + assert_eq!(fs::read_to_string(&outside_path)?, "allowed"); + + Ok(()) +} + +/// The validation to focus on is: writes to the skill-approved folder succeed, +/// and writes to an unrelated folder fail, both before and after cached approval. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shell_zsh_fork_skill_session_approval_enforces_skill_permissions() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("zsh-fork explicit skill sandbox test")? else { + return Ok(()); + }; + + let outside_dir = tempfile::tempdir_in(std::env::current_dir()?)?; + let allowed_dir = outside_dir.path().join("allowed-output"); + let blocked_dir = outside_dir.path().join("blocked-output"); + fs::create_dir_all(&allowed_dir)?; + fs::create_dir_all(&blocked_dir)?; + + let allowed_path = allowed_dir.join("allowed.txt"); + let blocked_path = blocked_dir.join("blocked.txt"); + let allowed_path_quoted = shlex::try_join([allowed_path.to_string_lossy().as_ref()])?; + let blocked_path_quoted = shlex::try_join([blocked_path.to_string_lossy().as_ref()])?; + let script_contents = format!( + "#!/bin/sh\nprintf '%s' allowed > {allowed_path_quoted}\ncat {allowed_path_quoted}\nprintf '%s' forbidden > {blocked_path_quoted}\nif [ -f {blocked_path_quoted} ]; then echo blocked-created; fi\n" + ); + let allowed_dir_for_hook = allowed_dir.clone(); + let allowed_path_for_hook = allowed_path.clone(); + let blocked_path_for_hook = blocked_path.clone(); + let script_contents_for_hook = script_contents.clone(); + + let permissions_yaml = format!( + "permissions:\n file_system:\n write:\n - \"{}\"\n", + allowed_dir.display() + ); + + let workspace_write_policy = restrictive_workspace_write_policy(); + let server = start_mock_server().await; + let test = build_zsh_fork_test( + &server, + runtime, + AskForApproval::OnRequest, + workspace_write_policy.clone(), + move |home| { + let _ = fs::remove_file(&allowed_path_for_hook); + let _ = fs::remove_file(&blocked_path_for_hook); + fs::create_dir_all(&allowed_dir_for_hook).unwrap(); + fs::create_dir_all(blocked_path_for_hook.parent().unwrap()).unwrap(); + write_skill_with_shell_script_contents( + home, + "mbolin-test-skill", + "sandboxed.sh", + &script_contents_for_hook, + ) + .unwrap(); + write_skill_metadata(home, "mbolin-test-skill", &permissions_yaml).unwrap(); + }, + ) + .await?; + + let (script_path_str, command) = skill_script_command(&test, "sandboxed.sh")?; + + let first_call_id = "zsh-fork-skill-permissions-1"; + let first_arguments = shell_command_arguments(&command)?; + let first_mocks = mount_function_call_agent_response( + &server, + first_call_id, + &first_arguments, + "shell_command", + ) + .await; + + submit_turn_with_policies( + &test, + "use $mbolin-test-skill", + AskForApproval::OnRequest, + workspace_write_policy.clone(), + ) + .await?; + + let maybe_approval = wait_for_exec_approval_request(&test).await; + let approval = match maybe_approval { + Some(approval) => approval, + None => panic!("expected exec approval request before completion"), + }; + assert_eq!(approval.call_id, first_call_id); + assert_eq!(approval.command, vec![script_path_str.clone()]); + assert_eq!( + approval.additional_permissions, + Some(PermissionProfile { + file_system: Some(FileSystemPermissions { + read: None, + write: Some(vec![absolute_path(&allowed_dir)]), + }), + ..Default::default() + }) + ); + + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::ApprovedForSession, + }) + .await?; + + wait_for_turn_complete(&test).await; + + let first_output = first_mocks + .completion + .single_request() + .function_call_output(first_call_id)["output"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + first_output.contains("allowed"), + "expected skill sandbox to permit writes to the approved folder, got output: {first_output:?}" + ); + assert_eq!(fs::read_to_string(&allowed_path)?, "allowed"); + assert!( + !blocked_path.exists(), + "first run should not write outside the explicit skill sandbox" + ); + assert!( + !first_output.contains("blocked-created"), + "blocked path should not have been created: {first_output:?}" + ); + + let second_call_id = "zsh-fork-skill-permissions-2"; + let second_arguments = shell_command_arguments(&command)?; + let second_mocks = mount_function_call_agent_response( + &server, + second_call_id, + &second_arguments, + "shell_command", + ) + .await; + + let _ = fs::remove_file(&allowed_path); + let _ = fs::remove_file(&blocked_path); + + submit_turn_with_policies( + &test, + "use $mbolin-test-skill", + AskForApproval::OnRequest, + workspace_write_policy, + ) + .await?; + + let cached_approval = wait_for_exec_approval_request(&test).await; + assert!( + cached_approval.is_none(), + "expected second run to reuse the cached session approval" + ); + + let second_output = second_mocks + .completion + .single_request() + .function_call_output(second_call_id)["output"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + second_output.contains("allowed"), + "expected cached skill approval to retain the explicit skill sandbox, got output: {second_output:?}" + ); + assert_eq!(fs::read_to_string(&allowed_path)?, "allowed"); + assert!( + !blocked_path.exists(), + "cached session approval should not widen skill execution beyond the explicit skill sandbox" + ); + assert!( + !second_output.contains("blocked-created"), + "blocked path should not have been created after cached approval: {second_output:?}" + ); + + Ok(()) +} + +/// This stays narrow on purpose: the important check is that `WorkspaceWrite` +/// continues to deny writes outside the workspace even under `zsh-fork`. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shell_zsh_fork_still_enforces_workspace_write_sandbox() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("zsh-fork workspace sandbox test")? else { + return Ok(()); + }; + + let server = start_mock_server().await; + let tool_call_id = "zsh-fork-workspace-write-deny"; + let outside_path = "/tmp/codex-zsh-fork-workspace-write-deny.txt"; + let workspace_write_policy = restrictive_workspace_write_policy(); + let _ = fs::remove_file(outside_path); + let test = build_zsh_fork_test( + &server, + runtime, + AskForApproval::Never, + workspace_write_policy.clone(), + move |_| { + let _ = fs::remove_file(outside_path); + }, + ) + .await?; + + let command = format!("touch {outside_path}"); + let arguments = shell_command_arguments(&command)?; + let mocks = + mount_function_call_agent_response(&server, tool_call_id, &arguments, "shell_command") + .await; + + submit_turn_with_policies( + &test, + "write outside workspace with zsh fork", + AskForApproval::Never, + workspace_write_policy, + ) + .await?; + + wait_for_turn_complete(&test).await; + + let call_output = mocks + .completion + .single_request() + .function_call_output(tool_call_id); + let output = call_output["output"].as_str().unwrap_or_default(); + assert!( + output_shows_sandbox_denial(output), + "expected sandbox denial, got output: {output:?}" + ); + assert!( + !Path::new(outside_path).exists(), + "command should not write outside workspace under WorkspaceWrite policy" ); Ok(()) diff --git a/codex-rs/core/tests/suite/skills.rs b/codex-rs/core/tests/suite/skills.rs index f681ca1b64..801e0dd6bb 100644 --- a/codex-rs/core/tests/suite/skills.rs +++ b/codex-rs/core/tests/suite/skills.rs @@ -77,7 +77,8 @@ async fn user_turn_includes_skill_instructions() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: codex_protocol::config_types::ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap index c88ff33122..e15d55aab2 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_with_history_shapes.snap @@ -6,16 +6,18 @@ Scenario: Manual /compact with prior user history compacts existing history and ## Local Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:first manual turn -04:message/assistant:FIRST_REPLY -05:message/user: +01:message/user[2]: + [01] + [02] > +02:message/user:first manual turn +03:message/assistant:FIRST_REPLY +04:message/user: ## Local Post-Compaction History Layout 00:message/user:first manual turn 01:message/user:\nFIRST_MANUAL_SUMMARY 02:message/developer: -03:message/user: -04:message/user:> -05:message/user:second manual turn +03:message/user[2]: + [01] + [02] > +04:message/user:second manual turn diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap index 0c8f87d04c..ca07006eae 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__manual_compact_without_prev_user_shapes.snap @@ -6,13 +6,15 @@ Scenario: Manual /compact with no prior user turn currently still issues a compa ## Local Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user: +01:message/user[2]: + [01] + [02] > +02:message/user: ## Local Post-Compaction History Layout 00:message/user:\nMANUAL_EMPTY_SUMMARY 01:message/developer: -02:message/user: -03:message/user:> -04:message/user:AFTER_MANUAL_EMPTY_COMPACT +02:message/user[2]: + [01] + [02] > +03:message/user:AFTER_MANUAL_EMPTY_COMPACT diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__mid_turn_compaction_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__mid_turn_compaction_shapes.snap index c13f78aff9..f59fdf4b96 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__mid_turn_compaction_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__mid_turn_compaction_shapes.snap @@ -1,22 +1,23 @@ --- source: core/tests/suite/compact.rs -assertion_line: 2646 expression: "format_labeled_requests_snapshot(\"True mid-turn continuation compaction after tool output: compact request includes tool artifacts, and the continuation request includes the summary in the same turn.\",\n&[(\"Local Compaction Request\", &auto_compact_mock.single_request()),\n(\"Local Post-Compaction History Layout\",\n&post_auto_compact_mock.single_request()),])" --- Scenario: True mid-turn continuation compaction after tool output: compact request includes tool artifacts, and the continuation request includes the summary in the same turn. ## Local Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:function call limit push -04:function_call/test_tool -05:function_call_output:unsupported call: test_tool -06:message/user: +01:message/user[2]: + [01] + [02] > +02:message/user:function call limit push +03:function_call/test_tool +04:function_call_output:unsupported call: test_tool +05:message/user: ## Local Post-Compaction History Layout 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:function call limit push -04:message/user:\nAUTO_SUMMARY +01:message/user[2]: + [01] + [02] > +02:message/user:function call limit push +03:message/user:\nAUTO_SUMMARY diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap index 552c117c98..7f61d7ed5e 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_sampling_model_switch_compaction_shapes.snap @@ -1,30 +1,35 @@ --- source: core/tests/suite/compact.rs +assertion_line: 1791 expression: "format_labeled_requests_snapshot(\"Pre-sampling compaction on model switch to a smaller context window: current behavior compacts using prior-turn history only (incoming user message excluded), and the follow-up request carries compacted history plus the new user message.\",\n&[(\"Initial Request (Previous Model)\", &requests[0]),\n(\"Pre-sampling Compaction Request\", &requests[1]),\n(\"Post-Compaction Follow-up Request (Next Model)\", &requests[2]),])" --- Scenario: Pre-sampling compaction on model switch to a smaller context window: current behavior compacts using prior-turn history only (incoming user message excluded), and the follow-up request carries compacted history plus the new user message. ## Initial Request (Previous Model) 00:message/developer: -01:message/user: -02:message/user:> -03:message/developer: -04:message/user:before switch +01:message/user[2]: + [01] + [02] > +02:message/developer: +03:message/user:before switch ## Pre-sampling Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/developer: -04:message/user:before switch -05:message/assistant:before switch -06:message/user: +01:message/user[2]: + [01] + [02] > +02:message/developer: +03:message/user:before switch +04:message/assistant:before switch +05:message/user: ## Post-Compaction Follow-up Request (Next Model) 00:message/user:before switch 01:message/user:\nPRE_SAMPLING_SUMMARY -02:message/developer:\nThe user was previously using a different model.... -03:message/developer: -04:message/user: -05:message/user:> -06:message/user:after switch +02:message/developer[2]: + [01] \nThe user was previously using a different model.... + [02] +03:message/user[2]: + [01] + [02] > +04:message/user:after switch diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_context_window_exceeded_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_context_window_exceeded_shapes.snap index da30b01bd7..0de8baeebe 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_context_window_exceeded_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_context_window_exceeded_shapes.snap @@ -6,8 +6,9 @@ Scenario: Pre-turn auto-compaction context-window failure: compaction request ex ## Local Compaction Request (Incoming User Excluded) 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:message/assistant:FIRST_REPLY -05:message/user: +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:message/assistant:FIRST_REPLY +04:message/user: diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap index ea4fea2f21..8712df5833 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_including_incoming_shapes.snap @@ -6,19 +6,25 @@ Scenario: Pre-turn auto-compaction with a context override emits the context dif ## Local Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:message/assistant:FIRST_REPLY -05:message/user:USER_TWO -06:message/assistant:SECOND_REPLY -07:message/user: +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:message/assistant:FIRST_REPLY +04:message/user:USER_TWO +05:message/assistant:SECOND_REPLY +06:message/user: ## Local Post-Compaction History Layout 00:message/user:USER_ONE 01:message/user:USER_TWO 02:message/user:\nPRE_TURN_SUMMARY 03:message/developer: -04:message/user: -05:message/user: -06:message/user: | | | USER_THREE +04:message/user[2]: + [01] + [02] +05:message/user[4]: + [01] + [02] + [03] + [04] USER_THREE diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap index 59d3785a43..46d76bb100 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact__pre_turn_compaction_strips_incoming_model_switch_shapes.snap @@ -1,31 +1,36 @@ --- source: core/tests/suite/compact.rs +assertion_line: 3188 expression: "format_labeled_requests_snapshot(\"Pre-turn compaction during model switch (without pre-sampling model-switch compaction): current behavior strips incoming from the compact request and restores it in the post-compaction follow-up request.\",\n&[(\"Initial Request (Previous Model)\", &requests[0]),\n(\"Local Compaction Request\", &requests[1]),\n(\"Local Post-Compaction History Layout\", &requests[2]),])" --- Scenario: Pre-turn compaction during model switch (without pre-sampling model-switch compaction): current behavior strips incoming from the compact request and restores it in the post-compaction follow-up request. ## Initial Request (Previous Model) 00:message/developer: -01:message/user: -02:message/user:> -03:message/developer: -04:message/user:BEFORE_SWITCH_USER +01:message/user[2]: + [01] + [02] > +02:message/developer: +03:message/user:BEFORE_SWITCH_USER ## Local Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/developer: -04:message/user:BEFORE_SWITCH_USER -05:message/assistant:BEFORE_SWITCH_REPLY -06:message/user: +01:message/user[2]: + [01] + [02] > +02:message/developer: +03:message/user:BEFORE_SWITCH_USER +04:message/assistant:BEFORE_SWITCH_REPLY +05:message/user: ## Local Post-Compaction History Layout 00:message/user:BEFORE_SWITCH_USER 01:message/user:\nPRETURN_SWITCH_SUMMARY -02:message/developer:\nThe user was previously using a different model.... -03:message/developer: -04:message/developer: The user has requested a new communication st... -05:message/user: -06:message/user:> -07:message/user:AFTER_SWITCH_USER +02:message/developer[3]: + [01] \nThe user was previously using a different model.... + [02] + [03] The user has requested a new communication st... +03:message/user[2]: + [01] + [02] > +04:message/user:AFTER_SWITCH_USER diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap new file mode 100644 index 0000000000..1b95615375 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_compact_resume_restates_realtime_end_shapes.snap @@ -0,0 +1,24 @@ +--- +source: core/tests/suite/compact_remote.rs +expression: "format_labeled_requests_snapshot(\"After remote manual /compact and resume, the first resumed turn rebuilds history from the compaction item and restates realtime-end instructions from reconstructed previous-turn settings.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Resume History Layout\", after_resume_request),])" +--- +Scenario: After remote manual /compact and resume, the first resumed turn rebuilds history from the compaction item and restates realtime-end instructions from reconstructed previous-turn settings. + +## Remote Compaction Request +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:message/developer:\nRealtime conversation started.\n\nYou a... +03:message/user:USER_ONE +04:message/assistant:REMOTE_FIRST_REPLY + +## Remote Post-Resume History Layout +00:compaction:encrypted=true +01:message/developer[2]: + [01] + [02] \nRealtime conversation ended.\n\nYou are... +02:message/user[2]: + [01] + [02] > +03:message/user:USER_TWO diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_restates_realtime_start_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_restates_realtime_start_shapes.snap new file mode 100644 index 0000000000..cb04630894 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_restates_realtime_start_shapes.snap @@ -0,0 +1,24 @@ +--- +source: core/tests/suite/compact_remote.rs +expression: "format_labeled_requests_snapshot(\"Remote manual /compact while realtime remains active: the next regular turn restates realtime-start instructions after compaction clears the baseline.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", post_compact_request),])" +--- +Scenario: Remote manual /compact while realtime remains active: the next regular turn restates realtime-start instructions after compaction clears the baseline. + +## Remote Compaction Request +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:message/developer:\nRealtime conversation started.\n\nYou a... +03:message/user:USER_ONE +04:message/assistant:REMOTE_FIRST_REPLY + +## Remote Post-Compaction History Layout +00:compaction:encrypted=true +01:message/developer[2]: + [01] + [02] \nRealtime conversation started.\n\nYou a... +02:message/user[2]: + [01] + [02] > +03:message/user:USER_TWO diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap index 701e676761..83bec30fb6 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_with_history_shapes.snap @@ -6,14 +6,16 @@ Scenario: Remote manual /compact where remote compact output is compaction-only: ## Remote Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:hello remote compact -04:message/assistant:FIRST_REMOTE_REPLY +01:message/user[2]: + [01] + [02] > +02:message/user:hello remote compact +03:message/assistant:FIRST_REMOTE_REPLY ## Remote Post-Compaction History Layout 00:compaction:encrypted=true 01:message/developer: -02:message/user: -03:message/user:> -04:message/user:after compact +02:message/user[2]: + [01] + [02] > +03:message/user:after compact diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_without_prev_user_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_without_prev_user_shapes.snap index ce62806d99..6ec8149c07 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_without_prev_user_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_without_prev_user_shapes.snap @@ -6,11 +6,13 @@ Scenario: Remote manual /compact with no prior user turn still issues a compact ## Remote Compaction Request 00:message/developer: -01:message/user: -02:message/user:> +01:message/user[2]: + [01] + [02] > ## Remote Post-Compaction History Layout 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap new file mode 100644 index 0000000000..eb7e583874 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_does_not_restate_realtime_end_shapes.snap @@ -0,0 +1,36 @@ +--- +source: core/tests/suite/compact_remote.rs +expression: "format_labeled_requests_snapshot(\"Remote mid-turn continuation compaction after realtime was closed before the turn: the initial second-turn request emits realtime-end instructions, but the continuation request does not restate them after compaction because the current turn already established the inactive baseline.\",\n&[(\"Second Turn Initial Request\", second_turn_request),\n(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", post_compact_request),])" +--- +Scenario: Remote mid-turn continuation compaction after realtime was closed before the turn: the initial second-turn request emits realtime-end instructions, but the continuation request does not restate them after compaction because the current turn already established the inactive baseline. + +## Second Turn Initial Request +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:message/developer:\nRealtime conversation started.\n\nYou a... +03:message/user:SETUP_USER +04:message/assistant:REMOTE_SETUP_REPLY +05:message/developer:\nRealtime conversation ended.\n\nYou are... +06:message/user:USER_TWO + +## Remote Compaction Request +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:message/developer:\nRealtime conversation started.\n\nYou a... +03:message/user:SETUP_USER +04:message/assistant:REMOTE_SETUP_REPLY +05:message/developer:\nRealtime conversation ended.\n\nYou are... +06:message/user:USER_TWO +07:function_call/test_tool +08:function_call_output:unsupported call: test_tool + +## Remote Post-Compaction History Layout +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:compaction:encrypted=true diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap index 7d5bcde902..ccc5a55811 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_multi_summary_reinjects_above_last_summary_shapes.snap @@ -1,6 +1,5 @@ --- source: core/tests/suite/compact_remote.rs -assertion_line: 1876 expression: "format_labeled_requests_snapshot(\"After a prior manual /compact produced an older remote compaction item, the next turn hits remote auto-compaction before the next sampling request. The compact request carries forward that earlier compaction item, and the next sampling request shows the latest compaction item with context reinjected before USER_TWO.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Second Turn Request (After Compaction)\", &second_turn_request),])" --- Scenario: After a prior manual /compact produced an older remote compaction item, the next turn hits remote auto-compaction before the next sampling request. The compact request carries forward that earlier compaction item, and the next sampling request shows the latest compaction item with context reinjected before USER_TWO. @@ -13,6 +12,7 @@ Scenario: After a prior manual /compact produced an older remote compaction item 00:message/user:USER_ONE 01:compaction:encrypted=true 02:message/developer: -03:message/user: -04:message/user:> -05:message/user:USER_TWO +03:message/user[2]: + [01] + [02] > +04:message/user:USER_TWO diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap index f5533b94a9..8e3e4235fa 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_shapes.snap @@ -6,15 +6,17 @@ Scenario: Remote mid-turn continuation compaction after tool output: compact req ## Remote Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:function_call/test_tool -05:function_call_output:unsupported call: test_tool +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:function_call/test_tool +04:function_call_output:unsupported call: test_tool ## Remote Post-Compaction History Layout 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:compaction:encrypted=true +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:compaction:encrypted=true diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap index 3f8c77e975..0f5886be13 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_mid_turn_compaction_summary_only_reinjects_context_shapes.snap @@ -1,19 +1,21 @@ --- source: core/tests/suite/compact_remote.rs -expression: "format_labeled_requests_snapshot(\"Remote mid-turn compaction where compact output has only a compaction item: continuation layout reinjects context before that compaction item.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &requests[1]),])" +expression: "format_labeled_requests_snapshot(\"Remote mid-turn compaction where compact output has only a compaction item: continuation layout reinjects context before that compaction item.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &post_compact_turn_request),])" --- Scenario: Remote mid-turn compaction where compact output has only a compaction item: continuation layout reinjects context before that compaction item. ## Remote Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:function_call/test_tool -05:function_call_output:unsupported call: test_tool +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:function_call/test_tool +04:function_call_output:unsupported call: test_tool ## Remote Post-Compaction History Layout 00:message/developer: -01:message/user: -02:message/user:> -03:compaction:encrypted=true +01:message/user[2]: + [01] + [02] > +02:compaction:encrypted=true diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_context_window_exceeded_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_context_window_exceeded_shapes.snap index e718bfda88..88e5c0bd23 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_context_window_exceeded_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_context_window_exceeded_shapes.snap @@ -6,7 +6,8 @@ Scenario: Remote pre-turn auto-compaction context-window failure: compaction req ## Remote Compaction Request (Incoming User Excluded) 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:message/assistant:REMOTE_FIRST_REPLY +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:message/assistant:REMOTE_FIRST_REPLY diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_failure_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_failure_shapes.snap index f8aa74e9a1..224f6dbba7 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_failure_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_failure_shapes.snap @@ -6,7 +6,8 @@ Scenario: Remote pre-turn auto-compaction parse failure: compaction request excl ## Remote Compaction Request (Incoming User Excluded) 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:turn that exceeds token threshold -04:message/assistant:initial turn complete +01:message/user[2]: + [01] + [02] > +02:message/user:turn that exceeds token threshold +03:message/assistant:initial turn complete diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap index 2236984a67..5a6f270d3d 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_including_incoming_shapes.snap @@ -6,18 +6,20 @@ Scenario: Remote pre-turn auto-compaction with a context override emits the cont ## Remote Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:USER_ONE -04:message/assistant:REMOTE_FIRST_REPLY -05:message/user:USER_TWO -06:message/assistant:REMOTE_SECOND_REPLY +01:message/user[2]: + [01] + [02] > +02:message/user:USER_ONE +03:message/assistant:REMOTE_FIRST_REPLY +04:message/user:USER_TWO +05:message/assistant:REMOTE_SECOND_REPLY ## Remote Post-Compaction History Layout 00:message/user:USER_ONE 01:message/user:USER_TWO 02:compaction:encrypted=true 03:message/developer: -04:message/user: -05:message/user: -06:message/user:USER_THREE +04:message/user[2]: + [01] + [02] +05:message/user:USER_THREE diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap new file mode 100644 index 0000000000..7f14509dd2 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_end_shapes.snap @@ -0,0 +1,24 @@ +--- +source: core/tests/suite/compact_remote.rs +expression: "format_labeled_requests_snapshot(\"Remote pre-turn auto-compaction after realtime was closed between turns: the follow-up request emits realtime-end instructions from previous-turn settings even though compaction cleared the reference baseline.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", post_compact_request),])" +--- +Scenario: Remote pre-turn auto-compaction after realtime was closed between turns: the follow-up request emits realtime-end instructions from previous-turn settings even though compaction cleared the reference baseline. + +## Remote Compaction Request +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:message/developer:\nRealtime conversation started.\n\nYou a... +03:message/user:USER_ONE +04:message/assistant:REMOTE_FIRST_REPLY + +## Remote Post-Compaction History Layout +00:compaction:encrypted=true +01:message/developer[2]: + [01] + [02] \nRealtime conversation ended.\n\nYou are... +02:message/user[2]: + [01] + [02] > +03:message/user:USER_TWO diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_start_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_start_shapes.snap new file mode 100644 index 0000000000..a72f581bbc --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_restates_realtime_start_shapes.snap @@ -0,0 +1,24 @@ +--- +source: core/tests/suite/compact_remote.rs +expression: "format_labeled_requests_snapshot(\"Remote pre-turn auto-compaction while realtime remains active: compaction clears the reference baseline, so the follow-up request restates realtime-start instructions.\",\n&[(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", post_compact_request),])" +--- +Scenario: Remote pre-turn auto-compaction while realtime remains active: compaction clears the reference baseline, so the follow-up request restates realtime-start instructions. + +## Remote Compaction Request +00:message/developer: +01:message/user[2]: + [01] + [02] > +02:message/developer:\nRealtime conversation started.\n\nYou a... +03:message/user:USER_ONE +04:message/assistant:REMOTE_FIRST_REPLY + +## Remote Post-Compaction History Layout +00:compaction:encrypted=true +01:message/developer[2]: + [01] + [02] \nRealtime conversation started.\n\nYou a... +02:message/user[2]: + [01] + [02] > +03:message/user:USER_TWO diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap index 15beec5f27..ebab84f4e0 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_pre_turn_compaction_strips_incoming_model_switch_shapes.snap @@ -1,28 +1,33 @@ --- source: core/tests/suite/compact_remote.rs +assertion_line: 1514 expression: "format_labeled_requests_snapshot(\"Remote pre-turn compaction during model switch currently excludes incoming user input, strips incoming from the compact request payload, and restores it in the post-compaction follow-up request.\",\n&[(\"Initial Request (Previous Model)\", &initial_turn_request),\n(\"Remote Compaction Request\", &compact_request),\n(\"Remote Post-Compaction History Layout\", &post_compact_turn_request),])" --- Scenario: Remote pre-turn compaction during model switch currently excludes incoming user input, strips incoming from the compact request payload, and restores it in the post-compaction follow-up request. ## Initial Request (Previous Model) 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:BEFORE_SWITCH_USER +01:message/user[2]: + [01] + [02] > +02:message/user:BEFORE_SWITCH_USER ## Remote Compaction Request 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:BEFORE_SWITCH_USER -04:message/assistant:BEFORE_SWITCH_REPLY +01:message/user[2]: + [01] + [02] > +02:message/user:BEFORE_SWITCH_USER +03:message/assistant:BEFORE_SWITCH_REPLY ## Remote Post-Compaction History Layout 00:message/user:BEFORE_SWITCH_USER 01:compaction:encrypted=true -02:message/developer:\nThe user was previously using a different model.... -03:message/developer: -04:message/developer: The user has requested a new communication st... -05:message/user: -06:message/user:> -07:message/user:AFTER_SWITCH_USER +02:message/developer[3]: + [01] \nThe user was previously using a different model.... + [02] + [03] The user has requested a new communication st... +03:message/user[2]: + [01] + [02] > +04:message/user:AFTER_SWITCH_USER diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_cwd_change_does_not_refresh_agents.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_cwd_change_does_not_refresh_agents.snap index 9b6291809a..65dffc556c 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_cwd_change_does_not_refresh_agents.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_cwd_change_does_not_refresh_agents.snap @@ -6,19 +6,21 @@ Scenario: Second turn changes cwd to a directory with different AGENTS.md; curre ## First Request (agents_one) 00:message/developer: -01:message/user: -02:message/user:> +01:message/user[2]: + [01] + [02] > +02:message/developer: 03:message/user:> -04:message/developer: -05:message/user:first turn in agents_one +04:message/user:first turn in agents_one ## Second Request (agents_two cwd) 00:message/developer: -01:message/user: -02:message/user:> +01:message/user[2]: + [01] + [02] > +02:message/developer: 03:message/user:> -04:message/developer: -05:message/user:first turn in agents_one -06:message/assistant:turn one complete -07:message/user:> -08:message/user:second turn in agents_two +04:message/user:first turn in agents_one +05:message/assistant:turn one complete +06:message/user:> +07:message/user:second turn in agents_two diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_environment_context_includes_one_subagent.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_environment_context_includes_one_subagent.snap new file mode 100644 index 0000000000..3436943cd2 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_environment_context_includes_one_subagent.snap @@ -0,0 +1,6 @@ +--- +source: core/tests/suite/model_visible_layout.rs +assertion_line: 476 +expression: "format_environment_context_subagents_snapshot(&[\"- agent-1: Atlas\"])" +--- +00:message/user::subagents=1> diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_environment_context_includes_two_subagents.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_environment_context_includes_two_subagents.snap new file mode 100644 index 0000000000..105c28515b --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_environment_context_includes_two_subagents.snap @@ -0,0 +1,6 @@ +--- +source: core/tests/suite/model_visible_layout.rs +assertion_line: 486 +expression: "format_environment_context_subagents_snapshot(&[\"- agent-1: Atlas\",\n\"- agent-2: Juniper\",])" +--- +00:message/user::subagents=2> diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap index 06269eff76..045e97706b 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_override_matches_rollout_model.snap @@ -1,21 +1,22 @@ --- source: core/tests/suite/model_visible_layout.rs -assertion_line: 435 expression: "format_labeled_requests_snapshot(\"First post-resume turn where pre-turn override sets model to rollout model; no model-switch update should appear.\",\n&[(\"Last Request Before Resume\", &initial_request),\n(\"First Request After Resume + Override\", &resumed_request),])" --- Scenario: First post-resume turn where pre-turn override sets model to rollout model; no model-switch update should appear. ## Last Request Before Resume 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:seed resume history +01:message/user[2]: + [01] + [02] > +02:message/user:seed resume history ## First Request After Resume + Override 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:seed resume history -04:message/assistant:recorded before resume -05:message/user: -06:message/user:first resumed turn after model override +01:message/user[2]: + [01] + [02] > +02:message/user:seed resume history +03:message/assistant:recorded before resume +04:message/user: +05:message/user:first resumed turn after model override diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap index 54417c6de2..3918fafa65 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_resume_with_personality_change.snap @@ -1,23 +1,25 @@ --- source: core/tests/suite/model_visible_layout.rs -assertion_line: 337 expression: "format_labeled_requests_snapshot(\"First post-resume turn where resumed config model differs from rollout and personality changes.\",\n&[(\"Last Request Before Resume\", &initial_request),\n(\"First Request After Resume\", &resumed_request),])" --- Scenario: First post-resume turn where resumed config model differs from rollout and personality changes. ## Last Request Before Resume 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:seed resume history +01:message/user[2]: + [01] + [02] > +02:message/user:seed resume history ## First Request After Resume 00:message/developer: -01:message/user: -02:message/user:> -03:message/user:seed resume history -04:message/assistant:recorded before resume -05:message/developer:\nThe user was previously using a different model. Please continue the conversatio... -06:message/user: -07:message/developer: -08:message/user:resume and change personality +01:message/user[2]: + [01] + [02] > +02:message/user:seed resume history +03:message/assistant:recorded before resume +04:message/developer[2]: + [01] \nThe user was previously using a different model. Please continue the conversatio... + [02] +05:message/user: +06:message/user:resume and change personality diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_turn_overrides.snap b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_turn_overrides.snap index 9ec0b2e7d0..2172d7399f 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_turn_overrides.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__model_visible_layout__model_visible_layout_turn_overrides.snap @@ -6,19 +6,22 @@ Scenario: Second turn changes cwd, approval policy, and personality while keepin ## First Request (Baseline) 00:message/developer: -01:message/user: -02:message/user:> -03:message/developer: -04:message/user:first turn +01:message/user[2]: + [01] + [02] > +02:message/developer: +03:message/user:first turn ## Second Request (Turn Overrides) 00:message/developer: -01:message/user: -02:message/user:> -03:message/developer: -04:message/user:first turn -05:message/assistant:turn one complete +01:message/user[2]: + [01] + [02] > +02:message/developer: +03:message/user:first turn +04:message/assistant:turn one complete +05:message/developer[2]: + [01] + [02] The user has requested a new communication style. Future messages should adhe... 06:message/user: -07:message/developer: -08:message/developer: The user has requested a new communication style. Future messages should adhe... -09:message/user:second turn with context updates +07:message/user:second turn with context updates diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index 113e837b30..177453d6dd 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -1,23 +1,36 @@ use anyhow::Result; +use codex_core::config::types::McpServerConfig; +use codex_core::config::types::McpServerTransportConfig; use codex_core::features::Feature; use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolSpec; +use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::UserMessageEvent; +use codex_protocol::user_input::UserInput; use core_test_support::responses; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; +use core_test_support::responses::ev_web_search_call_done; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::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_event; +use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; use serde_json::json; +use std::collections::HashMap; use std::fs; use tokio::time::Duration; use tracing_subscriber::prelude::*; @@ -128,6 +141,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { model_provider: None, base_instructions: None, dynamic_tools: Some(dynamic_tools_for_hook), + memory_mode: None, }, git: None, }; @@ -253,6 +267,149 @@ async fn user_messages_persist_in_state_db() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn web_search_marks_thread_memory_mode_polluted_when_configured() -> Result<()> { + let server = start_mock_server().await; + mount_sse_sequence( + &server, + vec![responses::sse(vec![ + ev_response_created("resp-1"), + ev_web_search_call_done("ws-1", "completed", "weather seattle"), + ev_completed("resp-1"), + ])], + ) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::Sqlite); + config.memories.no_memories_if_mcp_or_web_search = true; + }); + let test = builder.build(&server).await?; + let db = test.codex.state_db().expect("state db enabled"); + let thread_id = test.session_configured.session_id; + + test.submit_turn("search the web").await?; + + let mut memory_mode = None; + for _ in 0..100 { + memory_mode = db.get_thread_memory_mode(thread_id).await?; + if memory_mode.as_deref() == Some("polluted") { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + assert_eq!(memory_mode.as_deref(), Some("polluted")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_call_marks_thread_memory_mode_polluted_when_configured() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "call-123"; + let server_name = "rmcp"; + let tool_name = format!("mcp__{server_name}__echo"); + mount_sse_once( + &server, + responses::sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, &tool_name, "{\"message\":\"ping\"}"), + ev_completed("resp-1"), + ]), + ) + .await; + mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_assistant_message("msg-1", "rmcp echo tool completed."), + ev_completed("resp-2"), + ]), + ) + .await; + + let rmcp_test_server_bin = stdio_server_bin()?; + let mut builder = test_codex().with_config(move |config| { + config.features.enable(Feature::Sqlite); + config.memories.no_memories_if_mcp_or_web_search = true; + + let mut servers = config.mcp_servers.get().clone(); + servers.insert( + server_name.to_string(), + McpServerConfig { + transport: McpServerTransportConfig::Stdio { + command: rmcp_test_server_bin, + args: Vec::new(), + env: Some(HashMap::from([( + "MCP_TEST_VALUE".to_string(), + "propagated-env".to_string(), + )])), + env_vars: Vec::new(), + cwd: None, + }, + enabled: true, + required: false, + disabled_reason: None, + startup_timeout_sec: Some(Duration::from_secs(10)), + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth_resource: None, + }, + ); + config + .mcp_servers + .set(servers) + .expect("test mcp servers should accept any configuration"); + }); + let test = builder.build(&server).await?; + let db = test.codex.state_db().expect("state db enabled"); + let thread_id = test.session_configured.session_id; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "call the rmcp echo tool".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.cwd_path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + model: test.session_configured.model.clone(), + effort: None, + summary: None, + service_tier: None, + collaboration_mode: None, + personality: None, + }) + .await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::McpToolCallEnd(_)) + }) + .await; + wait_for_event_match(&test.codex, |event| match event { + EventMsg::Error(err) => Some(Err(anyhow::anyhow!(err.message.clone()))), + EventMsg::TurnComplete(_) => Some(Ok(())), + _ => None, + }) + .await?; + + let mut memory_mode = None; + for _ in 0..100 { + memory_mode = db.get_thread_memory_mode(thread_id).await?; + if memory_mode.as_deref() == Some("polluted") { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + + assert_eq!(memory_mode.as_deref(), Some("polluted")); + Ok(()) +} + #[tokio::test(flavor = "current_thread")] async fn tool_call_logs_include_thread_id() -> Result<()> { let server = start_mock_server().await; diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 422510f328..3dc463c4ab 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -20,6 +20,8 @@ use tokio::time::sleep; use wiremock::MockServer; const SPAWN_CALL_ID: &str = "spawn-call-1"; +const FORKED_SPAWN_AGENT_OUTPUT_MESSAGE: &str = "You are the newly spawned agent. The prior conversation history was forked from your parent agent. Treat the next user message as your new task, and use the forked history only as background context."; +const TURN_0_FORK_PROMPT: &str = "seed fork context"; const TURN_1_PROMPT: &str = "spawn a child and continue"; const TURN_2_NO_WAIT_PROMPT: &str = "follow up without wait"; const CHILD_PROMPT: &str = "child: do work"; @@ -194,3 +196,116 @@ async fn subagent_notification_is_included_without_wait() -> Result<()> { Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn spawned_child_receives_forked_parent_context() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let seed_turn = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, TURN_0_FORK_PROMPT), + sse(vec![ + ev_response_created("resp-seed-1"), + ev_assistant_message("msg-seed-1", "seeded"), + ev_completed("resp-seed-1"), + ]), + ) + .await; + + let spawn_args = serde_json::to_string(&json!({ + "message": CHILD_PROMPT, + "fork_context": true, + }))?; + let spawn_turn = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, TURN_1_PROMPT), + sse(vec![ + ev_response_created("resp-turn1-1"), + ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args), + ev_completed("resp-turn1-1"), + ]), + ) + .await; + + let _child_request_log = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, CHILD_PROMPT), + sse(vec![ + ev_response_created("resp-child-1"), + ev_assistant_message("msg-child-1", "child done"), + ev_completed("resp-child-1"), + ]), + ) + .await; + + let _turn1_followup = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, SPAWN_CALL_ID), + sse(vec![ + ev_response_created("resp-turn1-2"), + ev_assistant_message("msg-turn1-2", "parent done"), + ev_completed("resp-turn1-2"), + ]), + ) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::Collab); + }); + let test = builder.build(&server).await?; + + test.submit_turn(TURN_0_FORK_PROMPT).await?; + let _ = seed_turn.single_request(); + + test.submit_turn(TURN_1_PROMPT).await?; + let _ = spawn_turn.single_request(); + + let deadline = Instant::now() + Duration::from_secs(2); + let child_request = loop { + if let Some(request) = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .find(|request| { + body_contains(request, CHILD_PROMPT) + && body_contains(request, FORKED_SPAWN_AGENT_OUTPUT_MESSAGE) + }) + { + break request; + } + if Instant::now() >= deadline { + anyhow::bail!("timed out waiting for forked child request"); + } + sleep(Duration::from_millis(10)).await; + }; + assert!(body_contains(&child_request, TURN_0_FORK_PROMPT)); + assert!(body_contains(&child_request, "seeded")); + + let child_body = child_request + .body_json::() + .expect("forked child request body should be json"); + let function_call_output = child_body["input"] + .as_array() + .and_then(|items| { + items.iter().find(|item| { + item["type"].as_str() == Some("function_call_output") + && item["call_id"].as_str() == Some(SPAWN_CALL_ID) + }) + }) + .unwrap_or_else(|| panic!("expected forked child request to include spawn_agent output")); + let (content, success) = match &function_call_output["output"] { + serde_json::Value::String(text) => (Some(text.as_str()), None), + serde_json::Value::Object(output) => ( + output.get("content").and_then(serde_json::Value::as_str), + output.get("success").and_then(serde_json::Value::as_bool), + ), + _ => (None, None), + }; + assert_eq!(content, Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE)); + assert_ne!(success, Some(false)); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index 507c8eb068..ca666bce38 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -4,7 +4,6 @@ use std::fs; use assert_matches::assert_matches; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::plan_tool::StepStatus; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -89,7 +88,8 @@ async fn shell_tool_executes_command_and_streams_output() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -158,7 +158,8 @@ async fn update_plan_tool_emits_plan_update_event() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -237,7 +238,8 @@ async fn update_plan_tool_rejects_malformed_payload() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -328,7 +330,8 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -427,7 +430,8 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/tool_parallelism.rs b/codex-rs/core/tests/suite/tool_parallelism.rs index 357dcff0fd..a177a6ee37 100644 --- a/codex-rs/core/tests/suite/tool_parallelism.rs +++ b/codex-rs/core/tests/suite/tool_parallelism.rs @@ -5,7 +5,6 @@ use std::fs; use std::time::Duration; use std::time::Instant; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -46,7 +45,8 @@ async fn run_turn(test: &TestCodex, prompt: &str) -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -361,7 +361,8 @@ async fn shell_tools_start_before_response_completed_when_stream_delayed() -> an sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index 8ede6c621f..e7b25799ef 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -5,7 +5,6 @@ use anyhow::Context; use anyhow::Result; use codex_core::config::types::McpServerConfig; use codex_core::config::types::McpServerTransportConfig; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -371,6 +370,7 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -465,6 +465,7 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config @@ -488,7 +489,8 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -730,6 +732,7 @@ async fn mcp_tool_call_output_not_truncated_with_custom_limit() -> Result<()> { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }, ); config diff --git a/codex-rs/core/tests/suite/turn_state.rs b/codex-rs/core/tests/suite/turn_state.rs index 62bd974393..c068cfafb1 100644 --- a/codex-rs/core/tests/suite/turn_state.rs +++ b/codex-rs/core/tests/suite/turn_state.rs @@ -4,7 +4,6 @@ use anyhow::Result; use core_test_support::responses::WebSocketConnectionConfig; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_done; use core_test_support::responses::ev_reasoning_item; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_shell_command_call; @@ -100,7 +99,7 @@ async fn websocket_turn_state_persists_within_turn_and_resets_after() -> Result< ev_response_created("resp-1"), ev_reasoning_item("rsn-1", &["thinking"], &[]), ev_shell_command_call(call_id, "echo websocket"), - ev_done(), + ev_completed("resp-1"), ]], response_headers: vec![(TURN_STATE_HEADER.to_string(), "ts-1".to_string())], accept_delay: None, diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 705e415620..a3ef5711f8 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -6,7 +6,6 @@ use std::sync::OnceLock; use anyhow::Context; use anyhow::Result; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ExecCommandSource; @@ -209,7 +208,8 @@ async fn unified_exec_intercepts_apply_patch_exec_command() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -338,7 +338,8 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -416,7 +417,8 @@ async fn unified_exec_resolves_relative_workdir() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -497,7 +499,8 @@ async fn unified_exec_respects_workdir_override() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -590,7 +593,8 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -665,7 +669,8 @@ async fn unified_exec_emits_output_delta_for_exec_command() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -741,7 +746,8 @@ async fn unified_exec_full_lifecycle_with_background_end_event() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -871,7 +877,8 @@ async fn unified_exec_emits_terminal_interaction_for_write_stdin() -> Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1008,7 +1015,8 @@ async fn unified_exec_terminal_interaction_captures_delayed_output() -> Result<( sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1168,7 +1176,8 @@ async fn unified_exec_emits_one_begin_and_one_end_event() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1266,7 +1275,8 @@ async fn exec_command_reports_chunk_and_exit_metadata() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1384,7 +1394,8 @@ async fn unified_exec_defaults_to_pipe() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1474,7 +1485,8 @@ async fn unified_exec_can_enable_tty() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1555,7 +1567,8 @@ async fn unified_exec_respects_early_exit_notifications() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1686,7 +1699,8 @@ async fn write_stdin_returns_exit_metadata_and_clears_session() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1854,7 +1868,8 @@ async fn unified_exec_emits_end_event_when_session_dies_via_stdin() -> Result<() sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -1931,7 +1946,8 @@ async fn unified_exec_keeps_long_running_session_after_turn_end() -> Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2019,7 +2035,8 @@ async fn unified_exec_interrupt_terminates_long_running_session() -> Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2116,7 +2133,8 @@ async fn unified_exec_reuses_session_via_stdin() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2251,7 +2269,8 @@ PY sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2365,7 +2384,8 @@ async fn unified_exec_timeout_and_followup_poll() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2461,7 +2481,8 @@ PY sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2543,7 +2564,8 @@ async fn unified_exec_runs_under_sandbox() -> Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2647,7 +2669,8 @@ async fn unified_exec_python_prompt_under_seatbelt() -> Result<()> { sandbox_policy: SandboxPolicy::new_read_only_policy(), model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2742,7 +2765,8 @@ async fn unified_exec_runs_on_all_platforms() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -2877,7 +2901,8 @@ async fn unified_exec_prunes_exited_sessions_first() -> Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/user_notification.rs b/codex-rs/core/tests/suite/user_notification.rs index 5ef939776b..a2303c0ecf 100644 --- a/codex-rs/core/tests/suite/user_notification.rs +++ b/codex-rs/core/tests/suite/user_notification.rs @@ -23,10 +23,6 @@ use responses::start_mock_server; use std::time::Duration; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "flaky on ubuntu-24.04-arm - aarch64-unknown-linux-gnu"] -// The notify script gets far enough to create (and therefore surface) the file, -// but hasn’t flushed the JSON yet. Reading an empty file produces EOF while parsing -// a value at line 1 column 0. May be caused by a slow runner. async fn summarize_context_three_requests_and_instructions() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); @@ -43,7 +39,10 @@ async fn summarize_context_three_requests_and_instructions() -> anyhow::Result<( ¬ify_script, r#"#!/bin/bash set -e -echo -n "${@: -1}" > $(dirname "${0}")/notify.txt"#, +payload_path="$(dirname "${0}")/notify.txt" +tmp_path="${payload_path}.tmp" +echo -n "${@: -1}" > "${tmp_path}" +mv "${tmp_path}" "${payload_path}""#, )?; std::fs::set_permissions(¬ify_script, std::fs::Permissions::from_mode(0o755))?; diff --git a/codex-rs/core/tests/suite/user_shell_cmd.rs b/codex-rs/core/tests/suite/user_shell_cmd.rs index c38b86e443..6ce43a2d13 100644 --- a/codex-rs/core/tests/suite/user_shell_cmd.rs +++ b/codex-rs/core/tests/suite/user_shell_cmd.rs @@ -1,6 +1,5 @@ use anyhow::Context; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ExecCommandEndEvent; @@ -178,7 +177,8 @@ async fn user_shell_command_does_not_replace_active_turn() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: fixture.session_configured.model.clone(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 36ccf1a25e..5b8b9e0888 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -112,7 +112,8 @@ async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -214,7 +215,8 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -344,7 +346,8 @@ console.log(out.output?.body?.text ?? ""); sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -358,40 +361,26 @@ console.log(out.output?.body?.text ?? ""); .await; let req = mock.single_request(); - let (js_repl_output, js_repl_success) = req - .custom_tool_call_output_content_and_success(call_id) - .expect("custom tool output present"); - let js_repl_output = js_repl_output.expect("custom tool output text present"); - assert_ne!( - js_repl_success, - Some(false), - "js_repl call failed unexpectedly: {js_repl_output}" + let body = req.body_json(); + assert_eq!( + image_messages(&body).len(), + 0, + "js_repl view_image should not inject a pending input image message" ); - let body = req.body_json(); - let image_messages = image_messages(&body); - assert_eq!( - image_messages.len(), - 1, - "js_repl view_image should inject exactly one pending input image message" - ); - let image_message = image_messages - .into_iter() - .next() - .expect("pending input image message not included in request"); - let image_url = image_message - .get("content") + let custom_output = req.custom_tool_call_output(call_id); + let output_items = custom_output + .get("output") .and_then(Value::as_array) - .and_then(|content| { - content.iter().find_map(|span| { - if span.get("type").and_then(Value::as_str) == Some("input_image") { - span.get("image_url").and_then(Value::as_str) - } else { - None - } - }) + .expect("custom_tool_call_output should be a content item array"); + let image_url = output_items + .iter() + .find_map(|item| { + (item.get("type").and_then(Value::as_str) == Some("input_image")) + .then(|| item.get("image_url").and_then(Value::as_str)) + .flatten() }) - .expect("image_url present"); + .expect("image_url present in js_repl custom tool output"); assert!( image_url.starts_with("data:image/png;base64,"), "expected png data URL, got {image_url}" @@ -447,7 +436,8 @@ async fn view_image_tool_errors_when_path_is_directory() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -522,7 +512,8 @@ async fn view_image_tool_placeholder_for_non_image_files() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -614,7 +605,8 @@ async fn view_image_tool_errors_when_file_missing() -> anyhow::Result<()> { sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -675,8 +667,10 @@ async fn view_image_tool_returns_unsupported_message_for_text_only_model() -> an base_instructions: "base instructions".to_string(), model_messages: None, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, + availability_nux: None, apply_patch_tool_type: None, truncation_policy: TruncationPolicyConfig::bytes(10_000), supports_parallel_tool_calls: false, @@ -736,7 +730,8 @@ async fn view_image_tool_returns_unsupported_message_for_text_only_model() -> an sandbox_policy: SandboxPolicy::DangerFullAccess, model: model_slug.to_string(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) @@ -812,7 +807,8 @@ async fn replaces_invalid_local_image_after_bad_request() -> anyhow::Result<()> sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_model, effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/core/tests/suite/websocket_fallback.rs b/codex-rs/core/tests/suite/websocket_fallback.rs index 20c7b3b2f2..fadd427c16 100644 --- a/codex-rs/core/tests/suite/websocket_fallback.rs +++ b/codex-rs/core/tests/suite/websocket_fallback.rs @@ -1,6 +1,5 @@ use anyhow::Result; use codex_core::features::Feature; -use codex_protocol::config_types::ReasoningSummary; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -67,9 +66,9 @@ async fn websocket_fallback_switches_to_http_on_upgrade_required_connect() -> Re .filter(|req| req.method == Method::POST && req.url.path().ends_with("/responses")) .count(); - // Startup prewarm now only preconnects for v1 (one websocket GET with no request body). - // The first turn then attempts websocket once, sees 426, and falls back to HTTP. - assert_eq!(websocket_attempts, 2); + // The startup prewarm request sees 426 and immediately switches the session to HTTP fallback, + // so the first turn goes straight to HTTP with no additional websocket connect attempt. + assert_eq!(websocket_attempts, 1); assert_eq!(http_attempts, 1); assert_eq!(response_mock.requests().len(), 1); @@ -161,7 +160,8 @@ async fn websocket_fallback_hides_first_websocket_retry_stream_error() -> Result sandbox_policy: SandboxPolicy::DangerFullAccess, model: session_configured.model.clone(), effort: None, - summary: ReasoningSummary::Auto, + summary: None, + service_tier: None, collaboration_mode: None, personality: None, }) diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index 29bf6c5880..d2de502498 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -78,6 +78,7 @@ ignore = [ # TODO(fcoury): remove this exception when syntect drops yaml-rust and bincode, or updates to versions that have fixed the vulnerabilities. { id = "RUSTSEC-2024-0320", reason = "yaml-rust is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, { id = "RUSTSEC-2025-0141", reason = "bincode is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, + { id = "RUSTSEC-2025-0134", reason = "rustls-pemfile is unmaintained; pulled in via reqwest -> ppt-rs -> codex-artifact-presentation; no safe upgrade available yet" }, ] # If this is true, then cargo deny will use the git executable to fetch advisory database. # If this is false, then it uses a built-in git library. diff --git a/codex-rs/docs/codex_mcp_interface.md b/codex-rs/docs/codex_mcp_interface.md index 3a3abe9a9e..b4e3adfe53 100644 --- a/codex-rs/docs/codex_mcp_interface.md +++ b/codex-rs/docs/codex_mcp_interface.md @@ -1,38 +1,36 @@ # Codex MCP Server Interface [experimental] -This document describes Codex’s experimental MCP server interface: a JSON‑RPC API that runs over the Model Context Protocol (MCP) transport to control a local Codex engine. +This document describes Codex's experimental MCP server interface: a JSON-RPC API that runs over the Model Context Protocol (MCP) transport to control a local Codex engine. - Status: experimental and subject to change without notice - Server binary: `codex mcp-server` (or `codex-mcp-server`) -- Transport: standard MCP over stdio (JSON‑RPC 2.0, line‑delimited) +- Transport: standard MCP over stdio (JSON-RPC 2.0, line-delimited) ## Overview -Codex exposes a small set of MCP‑compatible methods to create and manage conversations, send user input, receive live events, and handle approval prompts. The types are defined in `protocol/src/mcp_protocol.rs` and re‑used by the MCP server implementation in `mcp-server/`. +Codex exposes MCP-compatible methods to manage threads, turns, accounts, config, and approvals. The types live in `app-server-protocol/src/protocol/{common,v1,v2}.rs` and are consumed by the app server implementation in `app-server/`. At a glance: -- Conversations - - `newConversation` → start a Codex session - - `sendUserMessage` / `sendUserTurn` → send user input into a conversation - - `interruptConversation` → stop the current turn - - `listConversations`, `resumeConversation`, `archiveConversation` -- Configuration and info - - `getUserSavedConfig`, `setDefaultModel`, `getUserAgent`, `userInfo` - - `model/list` → enumerate available models and reasoning options - - `collaborationMode/list` → enumerate collaboration mode presets (experimental) -- Auth +- Primary v2 RPCs + - `thread/start`, `thread/resume`, `thread/fork`, `thread/read`, `thread/list` + - `turn/start`, `turn/steer`, `turn/interrupt` - `account/read`, `account/login/start`, `account/login/cancel`, `account/logout`, `account/rateLimits/read` - - notifications: `account/login/completed`, `account/updated`, `account/rateLimits/updated` -- Utilities - - `gitDiffToRemote`, `execOneOffCommand` -- Approvals (server → client requests) + - `config/read`, `config/value/write`, `config/batchWrite` + - `model/list`, `app/list`, `collaborationMode/list` +- Remaining v1 compatibility RPCs + - `getConversationSummary` + - `getAuthStatus` + - `gitDiffToRemote` + - `fuzzyFileSearch`, `fuzzyFileSearch/sessionStart`, `fuzzyFileSearch/sessionUpdate`, `fuzzyFileSearch/sessionStop` +- Notifications + - v2 typed notifications such as `thread/started`, `turn/completed`, `account/login/completed` + - `codex/event/*` stream notifications for live agent events + - `fuzzyFileSearch/sessionUpdated`, `fuzzyFileSearch/sessionCompleted` +- Approvals (server -> client requests) - `applyPatchApproval`, `execCommandApproval` -- Notifications (server → client) - - `loginChatGptComplete`, `authStatusChange` - - `codex/event` stream with agent events -See code for full type definitions and exact shapes: `protocol/src/mcp_protocol.rs`. +See code for full type definitions and exact shapes: `app-server-protocol/src/protocol/{common,v1,v2}.rs`. ## Starting the server @@ -50,67 +48,45 @@ npx @modelcontextprotocol/inspector codex mcp-server Use the separate `codex mcp` subcommand to manage configured MCP server launchers in `config.toml`. -## Conversations +## Threads and turns -Start a new session with optional overrides: +Use the v2 thread and turn APIs for all new integrations. `thread/start` creates a thread, `turn/start` submits user input, `turn/interrupt` stops an in-flight turn, and `thread/list` / `thread/read` expose persisted history. -Request `newConversation` params (subset): +`getConversationSummary` remains as a compatibility helper for clients that still need a summary lookup by `conversationId` or `rolloutPath`. -- `model`: string model id (e.g. "o3", "gpt-5.1", "gpt-5.1-codex") -- `profile`: optional named profile -- `cwd`: optional working directory -- `approvalPolicy`: `untrusted` | `on-request` | `on-failure` (deprecated) | `never` -- `sandbox`: `read-only` | `workspace-write` | `external-sandbox` (honors `networkAccess` restricted/enabled) | `danger-full-access` -- `config`: map of additional config overrides -- `baseInstructions`: optional instruction override -- `compactPrompt`: optional replacement for the default compaction prompt -- `includePlanTool` / `includeApplyPatchTool`: booleans - -Response: `{ conversationId, model, reasoningEffort?, rolloutPath }` - -Send input to the active turn: - -- `sendUserMessage` → enqueue items to the conversation -- `sendUserTurn` → structured turn with explicit `cwd`, `approvalPolicy`, `sandboxPolicy`, `model`, optional `effort`, `summary`, optional `personality`, and optional `outputSchema` (JSON Schema for the final assistant message) - -Valid `personality` values are `friendly`, `pragmatic`, and `none`. When `none` is selected, the personality placeholder is replaced with an empty string. - -For v2 threads, `turn/start` also accepts `outputSchema` to constrain the final assistant message for that turn. - -Interrupt a running turn: `interruptConversation`. - -List/resume/archive: `listConversations`, `resumeConversation`, `archiveConversation`. - -For v2 threads, use `thread/list` with filters such as `archived: true`, `cwd: "/path"`, or -`searchTerm: "needle"` to -narrow results, and `thread/unarchive` to restore archived rollouts to the active sessions -directory (it returns the restored thread summary). +For complete request and response shapes, see the app-server README and the protocol definitions in `app-server-protocol/src/protocol/v2.rs`. ## Models Fetch the catalog of models available in the current Codex build with `model/list`. The request accepts optional pagination inputs: -- `pageSize` – number of models to return (defaults to a server-selected value) -- `cursor` – opaque string from the previous response’s `nextCursor` +- `limit` - number of models to return (defaults to a server-selected value) +- `cursor` - opaque string from the previous response's `nextCursor` Each response yields: -- `items` – ordered list of models. A model includes: +- `data` - ordered list of models. A model includes: - `id`, `model`, `displayName`, `description` - - `supportedReasoningEfforts` – array of objects with: - - `reasoningEffort` – one of `minimal|low|medium|high` - - `description` – human-friendly label for the effort - - `defaultReasoningEffort` – suggested effort for the UI - - `supportsPersonality` – whether the model supports personality-specific instructions - - `isDefault` – whether the model is recommended for most users - - `upgrade` – optional recommended upgrade model id -- `nextCursor` – pass into the next request to continue paging (optional) + - `supportedReasoningEfforts` - array of objects with: + - `reasoningEffort` - one of `none|minimal|low|medium|high|xhigh` + - `description` - human-friendly label for the effort + - `defaultReasoningEffort` - suggested effort for the UI + - `inputModalities` - accepted input types for the model + - `supportsPersonality` - whether the model supports personality-specific instructions + - `isDefault` - whether the model is recommended for most users + - `upgrade` - optional recommended upgrade model id + - `upgradeInfo` - optional upgrade metadata object with: + - `model` - recommended upgrade model id + - `upgradeCopy` - optional display copy for the upgrade recommendation + - `modelLink` - optional link for the upgrade recommendation + - `migrationMarkdown` - optional markdown shown when presenting the upgrade +- `nextCursor` - pass into the next request to continue paging (optional) ## Collaboration modes (experimental) Fetch the built-in collaboration mode presets with `collaborationMode/list`. This endpoint does not accept pagination and returns the full list in one response: -- `data` – ordered list of collaboration mode masks (partial settings to apply on top of the base mode) +- `data` - ordered list of collaboration mode masks (partial settings to apply on top of the base mode) - For tri-state fields like `reasoning_effort` and `developer_instructions`, omit the field to keep the current value, set it to `null` to clear it, or set a concrete value to update it. When sending `turn/start` with `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode". @@ -119,16 +95,14 @@ When sending `turn/start` with `collaborationMode`, `settings.developer_instruct While a conversation runs, the server sends notifications: -- `codex/event` with the serialized Codex event payload. The shape matches `core/src/protocol.rs`’s `Event` and `EventMsg` types. Some notifications include a `_meta.requestId` to correlate with the originating request. -- Auth notifications via method names `loginChatGptComplete` and `authStatusChange`. +- `codex/event` with the serialized Codex event payload. The shape matches `core/src/protocol.rs`'s `Event` and `EventMsg` types. Some notifications include a `_meta.requestId` to correlate with the originating request. +- `fuzzyFileSearch/sessionUpdated` and `fuzzyFileSearch/sessionCompleted` for the legacy fuzzy search flow. Clients should render events and, when present, surface approval requests (see next section). ## Tool responses -The `codex` and `codex-reply` tools return standard MCP `CallToolResult` payloads. For -compatibility with MCP clients that prefer `structuredContent`, Codex mirrors the -content blocks inside `structuredContent` alongside the `threadId`. +The `codex` and `codex-reply` tools return standard MCP `CallToolResult` payloads. For compatibility with MCP clients that prefer `structuredContent`, Codex mirrors the content blocks inside `structuredContent` alongside the `threadId`. Example: @@ -142,9 +116,9 @@ Example: } ``` -## Approvals (server → client) +## Approvals (server -> client) -When Codex needs approval to apply changes or run commands, the server issues JSON‑RPC requests to the client: +When Codex needs approval to apply changes or run commands, the server issues JSON-RPC requests to the client: - `applyPatchApproval { conversationId, callId, fileChanges, reason?, grantRoot? }` - `execCommandApproval { conversationId, callId, approvalId?, command, cwd, reason? }` @@ -153,28 +127,17 @@ The client must reply with `{ decision: "allow" | "deny" }` for each request. ## Auth helpers -For the complete request/response shapes and flow examples, see the [“Auth endpoints (v2)” section in the app‑server README](../app-server/README.md#auth-endpoints-v2). +For the complete request/response shapes and flow examples, see the [Auth endpoints (v2) section in the app-server README](../app-server/README.md#auth-endpoints-v2). -## Example: start and send a message +## Legacy compatibility methods -```json -{ "jsonrpc": "2.0", "id": 1, "method": "newConversation", "params": { "model": "gpt-5.1", "approvalPolicy": "on-request" } } -``` +The server still accepts a narrow v1 compatibility surface for existing app clients: -Server responds: - -```json -{ "jsonrpc": "2.0", "id": 1, "result": { "conversationId": "c7b0…", "model": "gpt-5.1", "rolloutPath": "/path/to/rollout.jsonl" } } -``` - -Then send input: - -```json -{ "jsonrpc": "2.0", "id": 2, "method": "sendUserMessage", "params": { "conversationId": "c7b0…", "items": [{ "type": "text", "text": "Hello Codex" }] } } -``` - -While processing, the server emits `codex/event` notifications containing agent output, approvals, and status updates. +- `getConversationSummary` +- `getAuthStatus` +- `gitDiffToRemote` +- `fuzzyFileSearch`, `fuzzyFileSearch/sessionStart`, `fuzzyFileSearch/sessionUpdate`, `fuzzyFileSearch/sessionStop` ## Compatibility and stability -This interface is experimental. Method names, fields, and event shapes may evolve. For the authoritative schema, consult `protocol/src/mcp_protocol.rs` and the corresponding server wiring in `mcp-server/`. +This interface is experimental. Method names, fields, and event shapes may evolve. For the authoritative schema, consult `app-server-protocol/src/protocol/{common,v1,v2}.rs` and the corresponding server wiring in `app-server/`. diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 6e679052e0..ff2699eedb 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -41,6 +41,7 @@ use owo_colors::Style; use serde::Deserialize; use shlex::try_join; use std::collections::HashMap; +use std::io::IsTerminal; use std::io::Write; use std::path::PathBuf; use std::time::Duration; @@ -854,7 +855,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { | EventMsg::RealtimeConversationRealtime(_) | EventMsg::RealtimeConversationClosed(_) | EventMsg::DynamicToolCallRequest(_) - | EventMsg::SkillRequestApproval(_) => {} + | EventMsg::DynamicToolCallResponse(_) => {} } CodexStatus::Running } @@ -869,12 +870,17 @@ impl EventProcessor for EventProcessorWithHumanOutput { ); } - // If the user has not piped the final message to a file, they will see - // it twice: once written to stderr as part of the normal event - // processing, and once here on stdout. We print the token summary above - // to help break up the output visually in that case. + // In interactive terminals we already emitted the final assistant + // message on stderr during event processing. Preserve stdout emission + // only for non-interactive use so pipes and scripts still receive the + // final message. #[allow(clippy::print_stdout)] - if let Some(message) = &self.final_message { + if should_print_final_message_to_stdout( + self.final_message.as_deref(), + std::io::stdout().is_terminal(), + std::io::stderr().is_terminal(), + ) && let Some(message) = &self.final_message + { if message.ends_with('\n') { print!("{message}"); } else { @@ -925,6 +931,7 @@ impl EventProcessorWithHumanOutput { | EventMsg::ThreadRolledBack(_) | EventMsg::RequestUserInput(_) | EventMsg::DynamicToolCallRequest(_) + | EventMsg::DynamicToolCallResponse(_) ) } @@ -1024,6 +1031,14 @@ impl EventProcessorWithHumanOutput { } } +fn should_print_final_message_to_stdout( + final_message: Option<&str>, + stdout_is_terminal: bool, + stderr_is_terminal: bool, +) -> bool { + final_message.is_some() && !(stdout_is_terminal && stderr_is_terminal) +} + struct AgentJobProgressStats { processed: usize, total: usize, @@ -1191,3 +1206,41 @@ fn format_mcp_invocation(invocation: &McpInvocation) -> String { format!("{fq_tool_name}({args_str})") } } + +#[cfg(test)] +mod tests { + use super::should_print_final_message_to_stdout; + use pretty_assertions::assert_eq; + + #[test] + fn suppresses_final_stdout_message_when_both_streams_are_terminals() { + assert_eq!( + should_print_final_message_to_stdout(Some("hello"), true, true), + false + ); + } + + #[test] + fn prints_final_stdout_message_when_stdout_is_not_terminal() { + assert_eq!( + should_print_final_message_to_stdout(Some("hello"), false, true), + true + ); + } + + #[test] + fn prints_final_stdout_message_when_stderr_is_not_terminal() { + assert_eq!( + should_print_final_message_to_stdout(Some("hello"), true, false), + true + ); + } + + #[test] + fn does_not_print_when_message_is_missing() { + assert_eq!( + should_print_final_message_to_stdout(None, false, false), + false + ); + } +} diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index cd577ca647..5f0ac4865e 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -32,6 +32,7 @@ use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::format_config_error_with_source; use codex_core::format_exec_policy_error_with_source; use codex_core::git_info::get_git_repo_root; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::models_manager::manager::RefreshStrategy; use codex_protocol::approvals::ElicitationAction; use codex_protocol::config_types::SandboxMode; @@ -73,6 +74,8 @@ use codex_core::default_client::set_default_originator; use codex_core::find_thread_path_by_id_str; use codex_core::find_thread_path_by_name_str; +const DEFAULT_ANALYTICS_ENABLED: bool = true; + enum InitialOperation { UserTurn { items: Vec, @@ -272,6 +275,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result sandbox_mode, cwd: resolved_cwd, model_provider: model_provider.clone(), + service_tier: None, codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(), js_repl_node_path: None, @@ -315,7 +319,12 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result } let otel = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - codex_core::otel_init::build_provider(&config, env!("CARGO_PKG_VERSION"), None, false) + codex_core::otel_init::build_provider( + &config, + env!("CARGO_PKG_VERSION"), + None, + DEFAULT_ANALYTICS_ENABLED, + ) })) { Ok(Ok(otel)) => otel, Ok(Err(e)) => { @@ -376,7 +385,6 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result let default_approval_policy = config.permissions.approval_policy.value(); let default_sandbox_policy = config.permissions.sandbox_policy.get(); let default_effort = config.model_reasoning_effort; - let default_summary = config.model_reasoning_summary; // When --yolo (dangerously_bypass_approvals_and_sandbox) is set, also skip the git repo check // since the user is explicitly running in an externally sandboxed environment. @@ -398,6 +406,11 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result auth_manager.clone(), SessionSource::Exec, config.model_catalog.clone(), + CollaborationModesConfig { + default_mode_request_user_input: config + .features + .enabled(codex_core::features::Feature::DefaultModeRequestUserInput), + }, )); let default_model = thread_manager .get_models_manager() @@ -554,7 +567,8 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result sandbox_policy: default_sandbox_policy.clone(), model: default_model, effort: default_effort, - summary: default_summary, + summary: None, + service_tier: None, final_output_json_schema: output_schema, collaboration_mode: None, personality: None, @@ -696,6 +710,7 @@ fn should_suppress_agent_job_event(msg: &EventMsg) -> bool { | EventMsg::ApplyPatchApprovalRequest(_) | EventMsg::RequestUserInput(_) | EventMsg::DynamicToolCallRequest(_) + | EventMsg::DynamicToolCallResponse(_) | EventMsg::ElicitationRequest(_) | EventMsg::Error(_) | EventMsg::Warning(_) @@ -921,6 +936,11 @@ mod tests { use super::*; use pretty_assertions::assert_eq; + #[test] + fn exec_defaults_analytics_to_enabled() { + assert_eq!(DEFAULT_ANALYTICS_ENABLED, true); + } + #[test] fn builds_uncommitted_review_request() { let request = build_review_request(ReviewArgs { diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 6595e82eab..a051b5bb00 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -93,6 +93,7 @@ fn session_configured_produces_thread_started_event() { thread_name: None, model: "codex-mini-latest".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), diff --git a/codex-rs/exec/tests/suite/resume.rs b/codex-rs/exec/tests/suite/resume.rs index 8cd8fffb40..a85183620e 100644 --- a/codex-rs/exec/tests/suite/resume.rs +++ b/codex-rs/exec/tests/suite/resume.rs @@ -321,6 +321,9 @@ fn exec_resume_last_respects_cwd_filter_and_all_flag() -> anyhow::Result<()> { let resumed_path_cwd = find_session_file_containing_marker(&sessions_dir, &marker_a2) .expect("no resumed session file containing marker_a2"); + // The `--all` resume above appends a new turn to `path_b` while running from `dir_a`, so the + // session's latest cwd now matches `dir_a`. A subsequent `resume --last` should therefore pick + // the newest matching session (`path_b`). assert_eq!( resumed_path_cwd, path_b, "resume --last should prefer sessions whose latest turn context matches the current cwd" diff --git a/codex-rs/execpolicy/Cargo.toml b/codex-rs/execpolicy/Cargo.toml index 890c23faa7..2105ce27d5 100644 --- a/codex-rs/execpolicy/Cargo.toml +++ b/codex-rs/execpolicy/Cargo.toml @@ -19,6 +19,7 @@ workspace = true [dependencies] anyhow = { workspace = true } clap = { workspace = true, features = ["derive"] } +codex-utils-absolute-path = { workspace = true } multimap = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } diff --git a/codex-rs/execpolicy/README.md b/codex-rs/execpolicy/README.md index 30fc57184b..5d1179362b 100644 --- a/codex-rs/execpolicy/README.md +++ b/codex-rs/execpolicy/README.md @@ -2,8 +2,8 @@ ## Overview -- Policy engine and CLI built around `prefix_rule(pattern=[...], decision?, justification?, match?, not_match?)`. -- This release covers the prefix-rule subset of the execpolicy language; a richer language will follow. +- Policy engine and CLI built around `prefix_rule(pattern=[...], decision?, justification?, match?, not_match?)` plus `host_executable(name=..., paths=[...])`. +- This release covers the prefix-rule subset of the execpolicy language plus host executable metadata; a richer language will follow. - Tokens are matched in order; any `pattern` element may be a list to denote alternatives. `decision` defaults to `allow`; valid values: `allow`, `prompt`, `forbidden`. - `justification` is an optional human-readable rationale for why a rule exists. It can be provided for any `decision` and may be surfaced in different contexts (for example, in approval prompts or rejection messages). When `decision = "forbidden"` is used, include a recommended alternative in the `justification`, when appropriate (e.g., ``"Use `jj` instead of `git`."``). - `match` / `not_match` supply example invocations that are validated at load time (think of them as unit tests); examples can be token arrays or strings (strings are tokenized with `shlex`). @@ -24,6 +24,26 @@ prefix_rule( ) ``` +- Host executable metadata can optionally constrain which absolute paths may + resolve through basename rules: + +```starlark +host_executable( + name = "git", + paths = [ + "/opt/homebrew/bin/git", + "/usr/bin/git", + ], +) +``` + +- Matching semantics: + - execpolicy always tries exact first-token matches first. + - With host-executable resolution disabled, `/usr/bin/git status` only matches a rule whose first token is `/usr/bin/git`. + - With host-executable resolution enabled, if no exact rule matches, execpolicy may fall back from `/usr/bin/git` to basename rules for `git`. + - If `host_executable(name="git", ...)` exists, basename fallback is only allowed for listed absolute paths. + - If no `host_executable()` entry exists for a basename, basename fallback is allowed. + ## CLI - From the Codex CLI, run `codex execpolicy check` subcommand with one or more policy files (for example `src/default.rules`) to check a command: @@ -32,6 +52,15 @@ prefix_rule( codex execpolicy check --rules path/to/policy.rules git status ``` +- To opt into basename fallback for absolute program paths, pass `--resolve-host-executables`: + +```bash +codex execpolicy check \ + --rules path/to/policy.rules \ + --resolve-host-executables \ + /usr/bin/git status +``` + - Pass multiple `--rules` flags to merge rules, evaluated in the order provided, and use `--pretty` for formatted JSON. - You can also run the standalone dev binary directly during development: @@ -52,6 +81,7 @@ cargo run -p codex-execpolicy -- check --rules path/to/policy.rules git status "prefixRuleMatch": { "matchedPrefix": ["", "..."], "decision": "allow|prompt|forbidden", + "resolvedProgram": "/absolute/path/to/program", "justification": "..." } } @@ -62,6 +92,7 @@ cargo run -p codex-execpolicy -- check --rules path/to/policy.rules git status - When no rules match, `matchedRules` is an empty array and `decision` is omitted. - `matchedRules` lists every rule whose prefix matched the command; `matchedPrefix` is the exact prefix that matched. +- `resolvedProgram` is omitted unless an absolute executable path matched via basename fallback. - The effective `decision` is the strictest severity across all matches (`forbidden` > `prompt` > `allow`). Note: `execpolicy` commands are still in preview. The API may have breaking changes in the future. diff --git a/codex-rs/execpolicy/src/error.rs b/codex-rs/execpolicy/src/error.rs index 25f9227210..0f2be753aa 100644 --- a/codex-rs/execpolicy/src/error.rs +++ b/codex-rs/execpolicy/src/error.rs @@ -38,16 +38,47 @@ pub enum Error { ExampleDidNotMatch { rules: Vec, examples: Vec, + location: Option, }, #[error("expected example to not match rule `{rule}`: {example}")] - ExampleDidMatch { rule: String, example: String }, + ExampleDidMatch { + rule: String, + example: String, + location: Option, + }, #[error("starlark error: {0}")] Starlark(StarlarkError), } impl Error { + pub fn with_location(self, location: ErrorLocation) -> Self { + match self { + Error::ExampleDidNotMatch { + rules, + examples, + location: None, + } => Error::ExampleDidNotMatch { + rules, + examples, + location: Some(location), + }, + Error::ExampleDidMatch { + rule, + example, + location: None, + } => Error::ExampleDidMatch { + rule, + example, + location: Some(location), + }, + other => other, + } + } + pub fn location(&self) -> Option { match self { + Error::ExampleDidNotMatch { location, .. } + | Error::ExampleDidMatch { location, .. } => location.clone(), Error::Starlark(err) => err.span().map(|span| { let resolved = span.resolve_span(); ErrorLocation { diff --git a/codex-rs/execpolicy/src/execpolicycheck.rs b/codex-rs/execpolicy/src/execpolicycheck.rs index f191f4b12e..1ff8937a5d 100644 --- a/codex-rs/execpolicy/src/execpolicycheck.rs +++ b/codex-rs/execpolicy/src/execpolicycheck.rs @@ -7,6 +7,7 @@ use clap::Parser; use serde::Serialize; use crate::Decision; +use crate::MatchOptions; use crate::Policy; use crate::PolicyParser; use crate::RuleMatch; @@ -22,6 +23,11 @@ pub struct ExecPolicyCheckCommand { #[arg(long)] pub pretty: bool, + /// Resolve absolute program paths against basename rules, gated by any + /// `host_executable()` definitions in the loaded policy files. + #[arg(long)] + pub resolve_host_executables: bool, + /// Command tokens to check against the policy. #[arg( value_name = "COMMAND", @@ -36,7 +42,13 @@ impl ExecPolicyCheckCommand { /// Load the policies for this command, evaluate the command, and render JSON output. pub fn run(&self) -> Result<()> { let policy = load_policies(&self.rules)?; - let matched_rules = policy.matches_for_command(&self.command, None); + let matched_rules = policy.matches_for_command_with_options( + &self.command, + None, + &MatchOptions { + resolve_host_executables: self.resolve_host_executables, + }, + ); let json = format_matches_json(&matched_rules, self.pretty)?; println!("{json}"); diff --git a/codex-rs/execpolicy/src/executable_name.rs b/codex-rs/execpolicy/src/executable_name.rs new file mode 100644 index 0000000000..bb3e8a536c --- /dev/null +++ b/codex-rs/execpolicy/src/executable_name.rs @@ -0,0 +1,29 @@ +use std::path::Path; + +#[cfg(windows)] +const WINDOWS_EXECUTABLE_SUFFIXES: [&str; 4] = [".exe", ".cmd", ".bat", ".com"]; + +pub(crate) fn executable_lookup_key(raw: &str) -> String { + #[cfg(windows)] + { + let raw = raw.to_ascii_lowercase(); + for suffix in WINDOWS_EXECUTABLE_SUFFIXES { + if raw.ends_with(suffix) { + let stripped_len = raw.len() - suffix.len(); + return raw[..stripped_len].to_string(); + } + } + raw + } + + #[cfg(not(windows))] + { + raw.to_string() + } +} + +pub(crate) fn executable_path_lookup_key(path: &Path) -> Option { + path.file_name() + .and_then(|name| name.to_str()) + .map(executable_lookup_key) +} diff --git a/codex-rs/execpolicy/src/lib.rs b/codex-rs/execpolicy/src/lib.rs index a9e9faa56d..8cb89c36e4 100644 --- a/codex-rs/execpolicy/src/lib.rs +++ b/codex-rs/execpolicy/src/lib.rs @@ -2,6 +2,7 @@ pub mod amend; pub mod decision; pub mod error; pub mod execpolicycheck; +mod executable_name; pub mod parser; pub mod policy; pub mod rule; @@ -18,6 +19,7 @@ pub use error::TextRange; pub use execpolicycheck::ExecPolicyCheckCommand; pub use parser::PolicyParser; pub use policy::Evaluation; +pub use policy::MatchOptions; pub use policy::Policy; pub use rule::NetworkRuleProtocol; pub use rule::Rule; diff --git a/codex-rs/execpolicy/src/parser.rs b/codex-rs/execpolicy/src/parser.rs index 8490c4848c..46764d0e07 100644 --- a/codex-rs/execpolicy/src/parser.rs +++ b/codex-rs/execpolicy/src/parser.rs @@ -1,6 +1,8 @@ +use codex_utils_absolute_path::AbsolutePathBuf; use multimap::MultiMap; use shlex; use starlark::any::ProvidesStaticType; +use starlark::codemap::FileSpan; use starlark::environment::GlobalsBuilder; use starlark::environment::Module; use starlark::eval::Evaluator; @@ -13,11 +15,18 @@ use starlark::values::list::UnpackList; use starlark::values::none::NoneType; use std::cell::RefCell; use std::cell::RefMut; +use std::collections::HashMap; +use std::path::Path; use std::sync::Arc; use crate::decision::Decision; use crate::error::Error; +use crate::error::ErrorLocation; use crate::error::Result; +use crate::error::TextPosition; +use crate::error::TextRange; +use crate::executable_name::executable_lookup_key; +use crate::executable_name::executable_path_lookup_key; use crate::rule::NetworkRule; use crate::rule::NetworkRuleProtocol; use crate::rule::PatternToken; @@ -47,6 +56,7 @@ impl PolicyParser { /// Parses a policy, tagging parser errors with `policy_identifier` so failures include the /// identifier alongside line numbers. pub fn parse(&mut self, policy_identifier: &str, policy_file_contents: &str) -> Result<()> { + let pending_validation_count = self.builder.borrow().pending_example_validations.len(); let mut dialect = Dialect::Extended.clone(); dialect.enable_f_strings = true; let ast = AstModule::parse( @@ -62,6 +72,9 @@ impl PolicyParser { eval.extra = Some(&self.builder); eval.eval_module(ast, &globals).map_err(Error::Starlark)?; } + self.builder + .borrow() + .validate_pending_examples_from(pending_validation_count)?; Ok(()) } @@ -74,6 +87,8 @@ impl PolicyParser { struct PolicyBuilder { rules_by_program: MultiMap, network_rules: Vec, + host_executables_by_name: HashMap>, + pending_example_validations: Vec, } impl PolicyBuilder { @@ -81,6 +96,8 @@ impl PolicyBuilder { Self { rules_by_program: MultiMap::new(), network_rules: Vec::new(), + host_executables_by_name: HashMap::new(), + pending_example_validations: Vec::new(), } } @@ -93,9 +110,62 @@ impl PolicyBuilder { self.network_rules.push(rule); } - fn build(self) -> crate::policy::Policy { - crate::policy::Policy::from_parts(self.rules_by_program, self.network_rules) + fn add_host_executable(&mut self, name: String, paths: Vec) { + self.host_executables_by_name.insert(name, paths.into()); } + + fn add_pending_example_validation( + &mut self, + rules: Vec, + matches: Vec>, + not_matches: Vec>, + location: Option, + ) { + self.pending_example_validations + .push(PendingExampleValidation { + rules, + matches, + not_matches, + location, + }); + } + + fn validate_pending_examples_from(&self, start: usize) -> Result<()> { + for validation in &self.pending_example_validations[start..] { + let mut rules_by_program = MultiMap::new(); + for rule in &validation.rules { + rules_by_program.insert(rule.program().to_string(), rule.clone()); + } + + let policy = crate::policy::Policy::from_parts( + rules_by_program, + Vec::new(), + self.host_executables_by_name.clone(), + ); + validate_not_match_examples(&policy, &validation.rules, &validation.not_matches) + .map_err(|error| attach_validation_location(error, validation.location.clone()))?; + validate_match_examples(&policy, &validation.rules, &validation.matches) + .map_err(|error| attach_validation_location(error, validation.location.clone()))?; + } + + Ok(()) + } + + fn build(self) -> crate::policy::Policy { + crate::policy::Policy::from_parts( + self.rules_by_program, + self.network_rules, + self.host_executables_by_name, + ) + } +} + +#[derive(Debug)] +struct PendingExampleValidation { + rules: Vec, + matches: Vec>, + not_matches: Vec>, + location: Option, } fn parse_pattern<'v>(pattern: UnpackList>) -> Result> { @@ -150,6 +220,36 @@ fn parse_examples<'v>(examples: UnpackList>) -> Result examples.items.into_iter().map(parse_example).collect() } +fn parse_literal_absolute_path(raw: &str) -> Result { + if !Path::new(raw).is_absolute() { + return Err(Error::InvalidRule(format!( + "host_executable paths must be absolute (got {raw})" + ))); + } + + AbsolutePathBuf::try_from(raw.to_string()) + .map_err(|error| Error::InvalidRule(format!("invalid absolute path `{raw}`: {error}"))) +} + +fn validate_host_executable_name(name: &str) -> Result<()> { + if name.is_empty() { + return Err(Error::InvalidRule( + "host_executable name cannot be empty".to_string(), + )); + } + + let path = Path::new(name); + if path.components().count() != 1 + || path.file_name().and_then(|value| value.to_str()) != Some(name) + { + return Err(Error::InvalidRule(format!( + "host_executable name must be a bare executable name (got {name})" + ))); + } + + Ok(()) +} + fn parse_network_rule_decision(raw: &str) -> Result { match raw { "deny" => Ok(Decision::Forbidden), @@ -157,6 +257,30 @@ fn parse_network_rule_decision(raw: &str) -> Result { } } +fn error_location_from_file_span(span: FileSpan) -> ErrorLocation { + let resolved = span.resolve_span(); + ErrorLocation { + path: span.filename().to_string(), + range: TextRange { + start: TextPosition { + line: resolved.begin.line + 1, + column: resolved.begin.column + 1, + }, + end: TextPosition { + line: resolved.end.line + 1, + column: resolved.end.column + 1, + }, + }, + } +} + +fn attach_validation_location(error: Error, location: Option) -> Error { + match location { + Some(location) => error.with_location(location), + None => error, + } +} + fn parse_example<'v>(value: Value<'v>) -> Result> { if let Some(raw) = value.unpack_str() { parse_string_example(raw) @@ -251,6 +375,9 @@ fn policy_builtins(builder: &mut GlobalsBuilder) { .map(parse_examples) .transpose()? .unwrap_or_default(); + let location = eval + .call_stack_top_location() + .map(error_location_from_file_span); let mut builder = policy_builder(eval); @@ -275,9 +402,7 @@ fn policy_builtins(builder: &mut GlobalsBuilder) { }) .collect(); - validate_not_match_examples(&rules, ¬_matches)?; - validate_match_examples(&rules, &matches)?; - + builder.add_pending_example_validation(rules.clone(), matches, not_matches, location); rules.into_iter().for_each(|rule| builder.add_rule(rule)); Ok(NoneType) } @@ -308,4 +433,41 @@ fn policy_builtins(builder: &mut GlobalsBuilder) { }); Ok(NoneType) } + + fn host_executable<'v>( + name: &'v str, + paths: UnpackList>, + eval: &mut Evaluator<'v, '_, '_>, + ) -> anyhow::Result { + validate_host_executable_name(name)?; + + let mut parsed_paths = Vec::new(); + for value in paths.items { + let raw = value.unpack_str().ok_or_else(|| { + Error::InvalidRule(format!( + "host_executable paths must be strings (got {})", + value.get_type() + )) + })?; + let path = parse_literal_absolute_path(raw)?; + let Some(path_name) = executable_path_lookup_key(path.as_path()) else { + return Err(Error::InvalidRule(format!( + "host_executable path `{raw}` must have basename `{name}`" + )) + .into()); + }; + if path_name != executable_lookup_key(name) { + return Err(Error::InvalidRule(format!( + "host_executable path `{raw}` must have basename `{name}`" + )) + .into()); + } + if !parsed_paths.iter().any(|existing| existing == &path) { + parsed_paths.push(path); + } + } + + policy_builder(eval).add_host_executable(executable_lookup_key(name), parsed_paths); + Ok(NoneType) + } } diff --git a/codex-rs/execpolicy/src/policy.rs b/codex-rs/execpolicy/src/policy.rs index faa74cc517..3102264e39 100644 --- a/codex-rs/execpolicy/src/policy.rs +++ b/codex-rs/execpolicy/src/policy.rs @@ -1,6 +1,7 @@ use crate::decision::Decision; use crate::error::Error; use crate::error::Result; +use crate::executable_name::executable_path_lookup_key; use crate::rule::NetworkRule; use crate::rule::NetworkRuleProtocol; use crate::rule::PatternToken; @@ -9,31 +10,41 @@ use crate::rule::PrefixRule; use crate::rule::RuleMatch; use crate::rule::RuleRef; use crate::rule::normalize_network_rule_host; +use codex_utils_absolute_path::AbsolutePathBuf; use multimap::MultiMap; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; use std::sync::Arc; type HeuristicsFallback<'a> = Option<&'a dyn Fn(&[String]) -> Decision>; +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct MatchOptions { + pub resolve_host_executables: bool, +} + #[derive(Clone, Debug)] pub struct Policy { rules_by_program: MultiMap, network_rules: Vec, + host_executables_by_name: HashMap>, } impl Policy { pub fn new(rules_by_program: MultiMap) -> Self { - Self::from_parts(rules_by_program, Vec::new()) + Self::from_parts(rules_by_program, Vec::new(), HashMap::new()) } pub fn from_parts( rules_by_program: MultiMap, network_rules: Vec, + host_executables_by_name: HashMap>, ) -> Self { Self { rules_by_program, network_rules, + host_executables_by_name, } } @@ -49,6 +60,10 @@ impl Policy { &self.network_rules } + pub fn host_executables(&self) -> &HashMap> { + &self.host_executables_by_name + } + pub fn get_allowed_prefixes(&self) -> Vec> { let mut prefixes = Vec::new(); @@ -119,6 +134,36 @@ impl Policy { Ok(()) } + pub fn set_host_executable_paths(&mut self, name: String, paths: Vec) { + self.host_executables_by_name.insert(name, paths.into()); + } + + pub fn merge_overlay(&self, overlay: &Policy) -> Policy { + let mut combined_rules = self.rules_by_program.clone(); + for (program, rules) in overlay.rules_by_program.iter_all() { + for rule in rules { + combined_rules.insert(program.clone(), rule.clone()); + } + } + + let mut combined_network_rules = self.network_rules.clone(); + combined_network_rules.extend(overlay.network_rules.iter().cloned()); + + let mut host_executables_by_name = self.host_executables_by_name.clone(); + host_executables_by_name.extend( + overlay + .host_executables_by_name + .iter() + .map(|(name, paths)| (name.clone(), paths.clone())), + ); + + Policy::from_parts( + combined_rules, + combined_network_rules, + host_executables_by_name, + ) + } + pub fn compiled_network_domains(&self) -> (Vec, Vec) { let mut allowed = Vec::new(); let mut denied = Vec::new(); @@ -144,7 +189,25 @@ impl Policy { where F: Fn(&[String]) -> Decision, { - let matched_rules = self.matches_for_command(cmd, Some(heuristics_fallback)); + let matched_rules = self.matches_for_command_with_options( + cmd, + Some(heuristics_fallback), + &MatchOptions::default(), + ); + Evaluation::from_matches(matched_rules) + } + + pub fn check_with_options( + &self, + cmd: &[String], + heuristics_fallback: &F, + options: &MatchOptions, + ) -> Evaluation + where + F: Fn(&[String]) -> Decision, + { + let matched_rules = + self.matches_for_command_with_options(cmd, Some(heuristics_fallback), options); Evaluation::from_matches(matched_rules) } @@ -154,6 +217,20 @@ impl Policy { commands: Commands, heuristics_fallback: &F, ) -> Evaluation + where + Commands: IntoIterator, + Commands::Item: AsRef<[String]>, + F: Fn(&[String]) -> Decision, + { + self.check_multiple_with_options(commands, heuristics_fallback, &MatchOptions::default()) + } + + pub fn check_multiple_with_options( + &self, + commands: Commands, + heuristics_fallback: &F, + options: &MatchOptions, + ) -> Evaluation where Commands: IntoIterator, Commands::Item: AsRef<[String]>, @@ -162,7 +239,11 @@ impl Policy { let matched_rules: Vec = commands .into_iter() .flat_map(|command| { - self.matches_for_command(command.as_ref(), Some(heuristics_fallback)) + self.matches_for_command_with_options( + command.as_ref(), + Some(heuristics_fallback), + options, + ) }) .collect(); @@ -181,14 +262,25 @@ impl Policy { cmd: &[String], heuristics_fallback: HeuristicsFallback<'_>, ) -> Vec { - let matched_rules: Vec = match cmd.first() { - Some(first) => self - .rules_by_program - .get_vec(first) - .map(|rules| rules.iter().filter_map(|rule| rule.matches(cmd)).collect()) - .unwrap_or_default(), - None => Vec::new(), - }; + self.matches_for_command_with_options(cmd, heuristics_fallback, &MatchOptions::default()) + } + + pub fn matches_for_command_with_options( + &self, + cmd: &[String], + heuristics_fallback: HeuristicsFallback<'_>, + options: &MatchOptions, + ) -> Vec { + let matched_rules = self + .match_exact_rules(cmd) + .filter(|matched_rules| !matched_rules.is_empty()) + .or_else(|| { + options + .resolve_host_executables + .then(|| self.match_host_executable_rules(cmd)) + .filter(|matched_rules| !matched_rules.is_empty()) + }) + .unwrap_or_default(); if matched_rules.is_empty() && let Some(heuristics_fallback) = heuristics_fallback @@ -201,6 +293,45 @@ impl Policy { matched_rules } } + + fn match_exact_rules(&self, cmd: &[String]) -> Option> { + let first = cmd.first()?; + Some( + self.rules_by_program + .get_vec(first) + .map(|rules| rules.iter().filter_map(|rule| rule.matches(cmd)).collect()) + .unwrap_or_default(), + ) + } + + fn match_host_executable_rules(&self, cmd: &[String]) -> Vec { + let Some(first) = cmd.first() else { + return Vec::new(); + }; + let Ok(program) = AbsolutePathBuf::try_from(first.clone()) else { + return Vec::new(); + }; + let Some(basename) = executable_path_lookup_key(program.as_path()) else { + return Vec::new(); + }; + let Some(rules) = self.rules_by_program.get_vec(&basename) else { + return Vec::new(); + }; + if let Some(paths) = self.host_executables_by_name.get(&basename) + && !paths.iter().any(|path| path == &program) + { + return Vec::new(); + } + + let basename_command = std::iter::once(basename) + .chain(cmd.iter().skip(1).cloned()) + .collect::>(); + rules + .iter() + .filter_map(|rule| rule.matches(&basename_command)) + .map(|rule_match| rule_match.with_resolved_program(&program)) + .collect() + } } fn upsert_domain(entries: &mut Vec, host: &str) { diff --git a/codex-rs/execpolicy/src/rule.rs b/codex-rs/execpolicy/src/rule.rs index 0d8bfc243a..15401ec878 100644 --- a/codex-rs/execpolicy/src/rule.rs +++ b/codex-rs/execpolicy/src/rule.rs @@ -1,6 +1,9 @@ use crate::decision::Decision; use crate::error::Error; use crate::error::Result; +use crate::policy::MatchOptions; +use crate::policy::Policy; +use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde::Serialize; use shlex::try_join; @@ -63,6 +66,8 @@ pub enum RuleMatch { #[serde(rename = "matchedPrefix")] matched_prefix: Vec, decision: Decision, + #[serde(rename = "resolvedProgram", skip_serializing_if = "Option::is_none")] + resolved_program: Option, /// Optional rationale for why this rule exists. /// /// This can be supplied for any decision and may be surfaced in different contexts @@ -83,6 +88,23 @@ impl RuleMatch { Self::HeuristicsRuleMatch { decision, .. } => *decision, } } + + pub fn with_resolved_program(self, resolved_program: &AbsolutePathBuf) -> Self { + match self { + Self::PrefixRuleMatch { + matched_prefix, + decision, + justification, + .. + } => Self::PrefixRuleMatch { + matched_prefix, + decision, + resolved_program: Some(resolved_program.clone()), + justification, + }, + other => other, + } + } } #[derive(Clone, Debug, Eq, PartialEq)] @@ -210,6 +232,7 @@ impl Rule for PrefixRule { .map(|matched_prefix| RuleMatch::PrefixRuleMatch { matched_prefix, decision: self.decision, + resolved_program: None, justification: self.justification.clone(), }) } @@ -220,11 +243,21 @@ impl Rule for PrefixRule { } /// Count how many rules match each provided example and error if any example is unmatched. -pub(crate) fn validate_match_examples(rules: &[RuleRef], matches: &[Vec]) -> Result<()> { +pub(crate) fn validate_match_examples( + policy: &Policy, + rules: &[RuleRef], + matches: &[Vec], +) -> Result<()> { let mut unmatched_examples = Vec::new(); + let options = MatchOptions { + resolve_host_executables: true, + }; for example in matches { - if rules.iter().any(|rule| rule.matches(example).is_some()) { + if !policy + .matches_for_command_with_options(example, None, &options) + .is_empty() + { continue; } @@ -240,21 +273,31 @@ pub(crate) fn validate_match_examples(rules: &[RuleRef], matches: &[Vec] Err(Error::ExampleDidNotMatch { rules: rules.iter().map(|rule| format!("{rule:?}")).collect(), examples: unmatched_examples, + location: None, }) } } /// Ensure that no rule matches any provided negative example. pub(crate) fn validate_not_match_examples( - rules: &[RuleRef], + policy: &Policy, + _rules: &[RuleRef], not_matches: &[Vec], ) -> Result<()> { + let options = MatchOptions { + resolve_host_executables: true, + }; + for example in not_matches { - if let Some(rule) = rules.iter().find(|rule| rule.matches(example).is_some()) { + if let Some(rule) = policy + .matches_for_command_with_options(example, None, &options) + .first() + { return Err(Error::ExampleDidMatch { rule: format!("{rule:?}"), example: try_join(example.iter().map(String::as_str)) .unwrap_or_else(|_| "unable to render example".to_string()), + location: None, }); } } diff --git a/codex-rs/execpolicy/tests/basic.rs b/codex-rs/execpolicy/tests/basic.rs index eec7cec651..bef845da67 100644 --- a/codex-rs/execpolicy/tests/basic.rs +++ b/codex-rs/execpolicy/tests/basic.rs @@ -1,5 +1,6 @@ use std::any::Any; use std::fs; +use std::path::PathBuf; use std::sync::Arc; use anyhow::Context; @@ -7,6 +8,7 @@ use anyhow::Result; use codex_execpolicy::Decision; use codex_execpolicy::Error; use codex_execpolicy::Evaluation; +use codex_execpolicy::MatchOptions; use codex_execpolicy::NetworkRuleProtocol; use codex_execpolicy::Policy; use codex_execpolicy::PolicyParser; @@ -16,6 +18,7 @@ use codex_execpolicy::blocking_append_allow_prefix_rule; use codex_execpolicy::rule::PatternToken; use codex_execpolicy::rule::PrefixPattern; use codex_execpolicy::rule::PrefixRule; +use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use tempfile::tempdir; @@ -31,6 +34,35 @@ fn prompt_all(_: &[String]) -> Decision { Decision::Prompt } +fn absolute_path(path: &str) -> AbsolutePathBuf { + AbsolutePathBuf::try_from(path.to_string()) + .unwrap_or_else(|error| panic!("expected absolute path `{path}`: {error}")) +} + +fn host_absolute_path(segments: &[&str]) -> String { + let mut path = if cfg!(windows) { + PathBuf::from(r"C:\") + } else { + PathBuf::from("/") + }; + for segment in segments { + path.push(segment); + } + path.to_string_lossy().into_owned() +} + +fn host_executable_name(name: &str) -> String { + if cfg!(windows) { + format!("{name}.exe") + } else { + name.to_string() + } +} + +fn starlark_string(value: &str) -> String { + value.replace('\\', "\\\\").replace('"', "\\\"") +} + #[derive(Clone, Debug, Eq, PartialEq)] enum RuleSnapshot { Prefix(PrefixRule), @@ -125,6 +157,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "status"]), decision: Decision::Allow, + resolved_program: None, justification: None, }], }, @@ -156,6 +189,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["rm"]), decision: Decision::Forbidden, + resolved_program: None, justification: Some("destructive command".to_string()), }], }, @@ -184,6 +218,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["ls"]), decision: Decision::Allow, + resolved_program: None, justification: Some("safe and commonly used".to_string()), }], }, @@ -236,6 +271,7 @@ fn add_prefix_rule_extends_policy() -> Result<()> { matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["ls", "-l"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }], }, @@ -305,6 +341,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }], }, @@ -319,11 +356,13 @@ prefix_rule( RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "commit"]), decision: Decision::Forbidden, + resolved_program: None, justification: None, }, ], @@ -381,6 +420,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["bash", "-c"]), decision: Decision::Allow, + resolved_program: None, justification: None, }], }, @@ -394,6 +434,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["sh", "-l"]), decision: Decision::Allow, + resolved_program: None, justification: None, }], }, @@ -440,6 +481,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["npm", "i", "--legacy-peer-deps"]), decision: Decision::Allow, + resolved_program: None, justification: None, }], }, @@ -456,6 +498,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["npm", "install", "--no-save"]), decision: Decision::Allow, + resolved_program: None, justification: None, }], }, @@ -486,6 +529,7 @@ prefix_rule( matched_rules: vec![RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "status"]), decision: Decision::Allow, + resolved_program: None, justification: None, }], }, @@ -533,11 +577,13 @@ prefix_rule( RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "commit"]), decision: Decision::Forbidden, + resolved_program: None, justification: None, }, ], @@ -576,16 +622,19 @@ prefix_rule( RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git"]), decision: Decision::Prompt, + resolved_program: None, justification: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "commit"]), decision: Decision::Forbidden, + resolved_program: None, justification: None, }, ], @@ -612,3 +661,303 @@ fn heuristics_match_is_returned_when_no_policy_matches() { evaluation ); } + +#[test] +fn parses_host_executable_paths() -> Result<()> { + let homebrew_git = host_absolute_path(&["opt", "homebrew", "bin", "git"]); + let usr_git = host_absolute_path(&["usr", "bin", "git"]); + let homebrew_git_literal = starlark_string(&homebrew_git); + let usr_git_literal = starlark_string(&usr_git); + let policy_src = format!( + r#" +host_executable( + name = "git", + paths = [ + "{homebrew_git_literal}", + "{usr_git_literal}", + "{usr_git_literal}", + ], +) +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src)?; + let policy = parser.build(); + + assert_eq!( + policy + .host_executables() + .get("git") + .expect("missing git host executable") + .as_ref(), + [absolute_path(&homebrew_git), absolute_path(&usr_git)] + ); + Ok(()) +} + +#[test] +fn host_executable_rejects_non_absolute_path() { + let policy_src = r#" +host_executable(name = "git", paths = ["git"]) +"#; + let mut parser = PolicyParser::new(); + let err = parser + .parse("test.rules", policy_src) + .expect_err("expected parse error"); + assert!( + err.to_string() + .contains("host_executable paths must be absolute") + ); +} + +#[test] +fn host_executable_rejects_name_with_path_separator() { + let git_path = host_absolute_path(&["usr", "bin", "git"]); + let git_path_literal = starlark_string(&git_path); + let policy_src = + format!(r#"host_executable(name = "{git_path_literal}", paths = ["{git_path_literal}"])"#); + let mut parser = PolicyParser::new(); + let err = parser + .parse("test.rules", &policy_src) + .expect_err("expected parse error"); + assert!( + err.to_string() + .contains("host_executable name must be a bare executable name") + ); +} + +#[test] +fn host_executable_rejects_path_with_wrong_basename() { + let rg_path = host_absolute_path(&["usr", "bin", "rg"]); + let rg_path_literal = starlark_string(&rg_path); + let policy_src = format!(r#"host_executable(name = "git", paths = ["{rg_path_literal}"])"#); + let mut parser = PolicyParser::new(); + let err = parser + .parse("test.rules", &policy_src) + .expect_err("expected parse error"); + assert!(err.to_string().contains("must have basename `git`")); +} + +#[test] +fn host_executable_last_definition_wins() -> Result<()> { + let usr_git = host_absolute_path(&["usr", "bin", "git"]); + let homebrew_git = host_absolute_path(&["opt", "homebrew", "bin", "git"]); + let usr_git_literal = starlark_string(&usr_git); + let homebrew_git_literal = starlark_string(&homebrew_git); + let mut parser = PolicyParser::new(); + parser.parse( + "shared.rules", + &format!(r#"host_executable(name = "git", paths = ["{usr_git_literal}"])"#), + )?; + parser.parse( + "user.rules", + &format!(r#"host_executable(name = "git", paths = ["{homebrew_git_literal}"])"#), + )?; + let policy = parser.build(); + + assert_eq!( + policy + .host_executables() + .get("git") + .expect("missing git host executable") + .as_ref(), + [absolute_path(&homebrew_git)] + ); + Ok(()) +} + +#[test] +fn host_executable_resolution_uses_basename_rule_when_allowed() -> Result<()> { + let git_name = host_executable_name("git"); + let git_path = host_absolute_path(&["usr", "bin", &git_name]); + let git_path_literal = starlark_string(&git_path); + let policy_src = format!( + r#" +prefix_rule(pattern = ["git", "status"], decision = "prompt") +host_executable(name = "git", paths = ["{git_path_literal}"]) +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src)?; + let policy = parser.build(); + + let evaluation = policy.check_with_options( + &[git_path.clone(), "status".to_string()], + &allow_all, + &MatchOptions { + resolve_host_executables: true, + }, + ); + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["git", "status"]), + decision: Decision::Prompt, + resolved_program: Some(absolute_path(&git_path)), + justification: None, + }], + } + ); + Ok(()) +} + +#[test] +fn prefix_rule_examples_honor_host_executable_resolution() -> Result<()> { + let allowed_git_name = host_executable_name("git"); + let allowed_git = host_absolute_path(&["usr", "bin", &allowed_git_name]); + let other_git = host_absolute_path(&["opt", "homebrew", "bin", &allowed_git_name]); + let allowed_git_literal = starlark_string(&allowed_git); + let other_git_literal = starlark_string(&other_git); + let policy_src = format!( + r#" +prefix_rule( + pattern = ["git", "status"], + match = [["{allowed_git_literal}", "status"]], + not_match = [["{other_git_literal}", "status"]], +) +host_executable(name = "git", paths = ["{allowed_git_literal}"]) +"# + ); + + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src)?; + + Ok(()) +} + +#[test] +fn host_executable_resolution_respects_explicit_empty_allowlist() -> Result<()> { + let policy_src = r#" +prefix_rule(pattern = ["git"], decision = "prompt") +host_executable(name = "git", paths = []) +"#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src)?; + let policy = parser.build(); + let git_path = host_absolute_path(&["usr", "bin", "git"]); + + let evaluation = policy.check_with_options( + &[git_path.clone(), "status".to_string()], + &allow_all, + &MatchOptions { + resolve_host_executables: true, + }, + ); + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Allow, + matched_rules: vec![RuleMatch::HeuristicsRuleMatch { + command: vec![git_path, "status".to_string()], + decision: Decision::Allow, + }], + } + ); + Ok(()) +} + +#[test] +fn host_executable_resolution_ignores_path_not_in_allowlist() -> Result<()> { + let allowed_git = host_absolute_path(&["usr", "bin", "git"]); + let other_git = host_absolute_path(&["opt", "homebrew", "bin", "git"]); + let allowed_git_literal = starlark_string(&allowed_git); + let policy_src = format!( + r#" +prefix_rule(pattern = ["git"], decision = "prompt") +host_executable(name = "git", paths = ["{allowed_git_literal}"]) +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src)?; + let policy = parser.build(); + + let evaluation = policy.check_with_options( + &[other_git.clone(), "status".to_string()], + &allow_all, + &MatchOptions { + resolve_host_executables: true, + }, + ); + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Allow, + matched_rules: vec![RuleMatch::HeuristicsRuleMatch { + command: vec![other_git, "status".to_string()], + decision: Decision::Allow, + }], + } + ); + Ok(()) +} + +#[test] +fn host_executable_resolution_falls_back_without_mapping() -> Result<()> { + let policy_src = r#" +prefix_rule(pattern = ["git"], decision = "prompt") +"#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src)?; + let policy = parser.build(); + let git_path = host_absolute_path(&["usr", "bin", "git"]); + + let evaluation = policy.check_with_options( + &[git_path.clone(), "status".to_string()], + &allow_all, + &MatchOptions { + resolve_host_executables: true, + }, + ); + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["git"]), + decision: Decision::Prompt, + resolved_program: Some(absolute_path(&git_path)), + justification: None, + }], + } + ); + Ok(()) +} + +#[test] +fn host_executable_resolution_does_not_override_exact_match() -> Result<()> { + let git_path = host_absolute_path(&["usr", "bin", "git"]); + let git_path_literal = starlark_string(&git_path); + let policy_src = format!( + r#" +prefix_rule(pattern = ["{git_path_literal}"], decision = "allow") +prefix_rule(pattern = ["git"], decision = "prompt") +host_executable(name = "git", paths = ["{git_path_literal}"]) +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src)?; + let policy = parser.build(); + + let evaluation = policy.check_with_options( + &[git_path.clone(), "status".to_string()], + &allow_all, + &MatchOptions { + resolve_host_executables: true, + }, + ); + assert_eq!( + evaluation, + Evaluation { + decision: Decision::Allow, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: vec![git_path], + decision: Decision::Allow, + resolved_program: None, + justification: None, + }], + } + ); + Ok(()) +} diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index a4fe6cc185..ee8e98c39e 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -226,6 +226,7 @@ impl CodexLogSnapshot { include_logs: bool, extra_log_files: &[PathBuf], session_source: Option, + logs_override: Option>, ) -> Result<()> { use std::collections::BTreeMap; use std::fs; @@ -310,7 +311,7 @@ impl CodexLogSnapshot { if include_logs { envelope.add_item(EnvelopeItem::Attachment(Attachment { - buffer: self.bytes.clone(), + buffer: logs_override.unwrap_or_else(|| self.bytes.clone()), filename: String::from("codex-logs.log"), content_type: Some("text/plain".to_string()), ty: None, diff --git a/codex-rs/file-search/src/lib.rs b/codex-rs/file-search/src/lib.rs index 151fafe98f..ba376c38f1 100644 --- a/codex-rs/file-search/src/lib.rs +++ b/codex-rs/file-search/src/lib.rs @@ -92,6 +92,13 @@ pub struct FileSearchOptions { pub exclude: Vec, pub threads: NonZero, pub compute_indices: bool, + /// Toggle ignore-file processing in the walker. + /// + /// When enabled, `.gitignore` files are scoped by + /// `WalkBuilder::require_git(true)`, so they are honored only when the + /// traversed path is inside a git repository. When disabled, the walker + /// turns off `.gitignore`, git-global/exclude rules, `.ignore`, and + /// parent-directory ignore scanning. pub respect_gitignore: bool, } @@ -379,6 +386,18 @@ fn get_file_path<'a>(path: &'a Path, search_directories: &[PathBuf]) -> Option<( rel_path.to_str().map(|p| (root_idx, p)) } +/// Walks the search directories and feeds discovered file paths into `nucleo` +/// via the injector. +/// +/// The walker uses `require_git(true)` to match git's own ignore semantics: +/// git never reads `.gitignore` files from directories above the repository +/// root. Without this flag, the `ignore` crate reads `.gitignore` files from +/// *all* ancestor directories—a deliberate divergence from git intended for +/// non-git use cases—allowing a broad parent ignore (e.g. `~/.gitignore` +/// containing `*`) to silently suppress every file in the walk. +/// +/// When `respect_gitignore` is `false`, all git-related ignore processing is +/// disabled regardless of this flag. fn walker_worker( inner: Arc, override_matcher: Option, @@ -399,8 +418,9 @@ fn walker_worker( .hidden(false) // Follow symlinks to search their contents. .follow_links(true) - // Don't require git to be present to apply to apply git-related ignore rules. - .require_git(false); + // Keep ignore behavior aligned with git repositories: only apply + // gitignore rules when a git context exists. + .require_git(true); if !inner.respect_gitignore { walk_builder .git_ignore(false) @@ -966,4 +986,151 @@ mod tests { assert_eq!(results.matches, Vec::new()); assert_eq!(results.total_match_count, 0); } + + /// Regression test for #3493: a parent directory's `.gitignore` with `*` + /// must not suppress files discovered inside a child "repo" directory. + /// + /// The fixture intentionally omits `git init` so that no `.git` directory + /// exists. With `require_git(true)`, the walker skips all gitignore + /// processing, making the parent's broad ignore harmless. + #[test] + fn parent_gitignore_outside_repo_does_not_hide_repo_files() { + let temp = tempfile::tempdir().unwrap(); + let parent = temp.path().join("home"); + let repo = parent.join("repo"); + fs::create_dir_all(repo.join(".vscode")).unwrap(); + + fs::write(parent.join(".gitignore"), "*\n!.gitignore\n").unwrap(); + fs::write( + repo.join(".gitignore"), + ".vscode/*\n!.vscode/\n!.vscode/settings.json\n!package.json\n", + ) + .unwrap(); + fs::write(repo.join("package.json"), "{ \"name\": \"demo\" }\n").unwrap(); + fs::write(repo.join(".vscode/settings.json"), "{ \"editor\": true }\n").unwrap(); + + let respect_results = run( + "package", + vec![repo.clone()], + FileSearchOptions { + limit: NonZero::new(20).unwrap(), + exclude: Vec::new(), + threads: NonZero::new(2).unwrap(), + compute_indices: false, + respect_gitignore: true, + }, + None, + ) + .expect("run ok"); + assert!( + respect_results + .matches + .iter() + .any(|m| m.path.as_path() == Path::new("package.json")) + ); + + let nested_file_results = run( + "settings", + vec![repo], + FileSearchOptions { + limit: NonZero::new(20).unwrap(), + exclude: Vec::new(), + threads: NonZero::new(2).unwrap(), + compute_indices: false, + respect_gitignore: true, + }, + None, + ) + .expect("run ok"); + assert!( + nested_file_results + .matches + .iter() + .any(|m| m.path.as_path() == Path::new(".vscode/settings.json")) + ); + } + + #[test] + fn git_repo_still_respects_local_gitignore_when_enabled() { + let temp = tempfile::tempdir().unwrap(); + let parent = temp.path().join("home"); + let repo = parent.join("repo"); + fs::create_dir_all(repo.join(".vscode")).unwrap(); + + fs::write(parent.join(".gitignore"), "*\n!.gitignore\n").unwrap(); + fs::write( + repo.join(".gitignore"), + ".vscode/*\n!.vscode/\n!.vscode/settings.json\n!package.json\n", + ) + .unwrap(); + fs::write(repo.join("package.json"), "{ \"name\": \"demo\" }\n").unwrap(); + fs::write(repo.join(".vscode/settings.json"), "{ \"editor\": true }\n").unwrap(); + fs::write( + repo.join(".vscode/extensions.json"), + "{ \"extensions\": [] }\n", + ) + .unwrap(); + + fs::create_dir_all(repo.join(".git")).unwrap(); + + let package_results = run( + "package", + vec![repo.clone()], + FileSearchOptions { + limit: NonZero::new(20).unwrap(), + exclude: Vec::new(), + threads: NonZero::new(2).unwrap(), + compute_indices: false, + respect_gitignore: true, + }, + None, + ) + .expect("run ok"); + assert!( + package_results + .matches + .iter() + .any(|m| m.path.as_path() == Path::new("package.json")) + ); + + let ignored_results = run( + "extensions.json", + vec![repo.clone()], + FileSearchOptions { + limit: NonZero::new(20).unwrap(), + exclude: Vec::new(), + threads: NonZero::new(2).unwrap(), + compute_indices: false, + respect_gitignore: true, + }, + None, + ) + .expect("run ok"); + assert!( + !ignored_results + .matches + .iter() + .any(|m| m.path.as_path() == Path::new(".vscode/extensions.json")) + ); + + let whitelisted_results = run( + "settings.json", + vec![repo], + FileSearchOptions { + limit: NonZero::new(20).unwrap(), + exclude: Vec::new(), + threads: NonZero::new(2).unwrap(), + compute_indices: false, + respect_gitignore: true, + }, + None, + ) + .expect("run ok"); + assert!( + whitelisted_results + .matches + .iter() + .any(|m| m.path.as_path() == Path::new(".vscode/settings.json")) + ); + } } diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index 6568f5374f..1648fa0462 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -104,6 +104,7 @@ mod tests { HookPayload { session_id: ThreadId::new(), cwd: PathBuf::from(CWD), + client: None, triggered_at: Utc .with_ymd_and_hms(2025, 1, 1, 0, 0, 0) .single() @@ -172,6 +173,7 @@ mod tests { HookPayload { session_id: ThreadId::new(), cwd: PathBuf::from(CWD), + client: None, triggered_at: Utc .with_ymd_and_hms(2025, 1, 1, 0, 0, 0) .single() diff --git a/codex-rs/hooks/src/types.rs b/codex-rs/hooks/src/types.rs index 5131580128..b7ef3c2141 100644 --- a/codex-rs/hooks/src/types.rs +++ b/codex-rs/hooks/src/types.rs @@ -65,6 +65,8 @@ impl Hook { pub struct HookPayload { pub session_id: ThreadId, pub cwd: PathBuf, + #[serde(skip_serializing_if = "Option::is_none")] + pub client: Option, #[serde(serialize_with = "serialize_triggered_at")] pub triggered_at: DateTime, pub hook_event: HookEvent, @@ -181,6 +183,7 @@ mod tests { let payload = HookPayload { session_id, cwd: PathBuf::from("tmp"), + client: None, triggered_at: Utc .with_ymd_and_hms(2025, 1, 1, 0, 0, 0) .single() @@ -218,6 +221,7 @@ mod tests { let payload = HookPayload { session_id, cwd: PathBuf::from("tmp"), + client: None, triggered_at: Utc .with_ymd_and_hms(2025, 1, 1, 0, 0, 0) .single() diff --git a/codex-rs/hooks/src/user_notification.rs b/codex-rs/hooks/src/user_notification.rs index 50472225e4..caeca59b50 100644 --- a/codex-rs/hooks/src/user_notification.rs +++ b/codex-rs/hooks/src/user_notification.rs @@ -1,4 +1,3 @@ -use std::path::Path; use std::process::Stdio; use std::sync::Arc; @@ -19,6 +18,8 @@ enum UserNotification { thread_id: String, turn_id: String, cwd: String, + #[serde(skip_serializing_if = "Option::is_none")] + client: Option, /// Messages that the user sent to the agent to initiate the turn. input_messages: Vec, @@ -28,13 +29,14 @@ enum UserNotification { }, } -pub fn legacy_notify_json(hook_event: &HookEvent, cwd: &Path) -> Result { - match hook_event { +pub fn legacy_notify_json(payload: &HookPayload) -> Result { + match &payload.hook_event { HookEvent::AfterAgent { event } => { serde_json::to_string(&UserNotification::AgentTurnComplete { thread_id: event.thread_id.to_string(), turn_id: event.turn_id.clone(), - cwd: cwd.display().to_string(), + cwd: payload.cwd.display().to_string(), + client: payload.client.clone(), input_messages: event.input_messages.clone(), last_assistant_message: event.last_assistant_message.clone(), }) @@ -56,7 +58,7 @@ pub fn notify_hook(argv: Vec) -> Hook { Some(command) => command, None => return HookResult::Success, }; - if let Ok(notify_payload) = legacy_notify_json(&payload.hook_event, &payload.cwd) { + if let Ok(notify_payload) = legacy_notify_json(payload) { command.arg(notify_payload); } @@ -91,6 +93,7 @@ mod tests { "thread-id": "b5f6c1c2-1111-2222-3333-444455556666", "turn-id": "12345", "cwd": "/Users/example/project", + "client": "codex-tui", "input-messages": ["Rename `foo` to `bar` and update the callsites."], "last-assistant-message": "Rename complete and verified `cargo build` succeeds.", }) @@ -102,6 +105,7 @@ mod tests { thread_id: "b5f6c1c2-1111-2222-3333-444455556666".to_string(), turn_id: "12345".to_string(), cwd: "/Users/example/project".to_string(), + client: Some("codex-tui".to_string()), input_messages: vec!["Rename `foo` to `bar` and update the callsites.".to_string()], last_assistant_message: Some( "Rename complete and verified `cargo build` succeeds.".to_string(), @@ -115,19 +119,27 @@ mod tests { #[test] fn legacy_notify_json_matches_historical_wire_shape() -> Result<()> { - let hook_event = HookEvent::AfterAgent { - event: crate::HookEventAfterAgent { - thread_id: ThreadId::from_string("b5f6c1c2-1111-2222-3333-444455556666") - .expect("valid thread id"), - turn_id: "12345".to_string(), - input_messages: vec!["Rename `foo` to `bar` and update the callsites.".to_string()], - last_assistant_message: Some( - "Rename complete and verified `cargo build` succeeds.".to_string(), - ), + let payload = HookPayload { + session_id: ThreadId::new(), + cwd: std::path::Path::new("/Users/example/project").to_path_buf(), + client: Some("codex-tui".to_string()), + triggered_at: chrono::Utc::now(), + hook_event: HookEvent::AfterAgent { + event: crate::HookEventAfterAgent { + thread_id: ThreadId::from_string("b5f6c1c2-1111-2222-3333-444455556666") + .expect("valid thread id"), + turn_id: "12345".to_string(), + input_messages: vec![ + "Rename `foo` to `bar` and update the callsites.".to_string(), + ], + last_assistant_message: Some( + "Rename complete and verified `cargo build` succeeds.".to_string(), + ), + }, }, }; - let serialized = legacy_notify_json(&hook_event, Path::new("/Users/example/project"))?; + let serialized = legacy_notify_json(&payload)?; let actual: Value = serde_json::from_str(&serialized)?; assert_eq!(actual, expected_notification_json()); diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index d1fefc1747..67a8b8e604 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -18,6 +18,22 @@ use codex_core::error::Result; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::WritableRoot; +/// Linux "platform defaults" that keep common system binaries and dynamic +/// libraries readable when `ReadOnlyAccess::Restricted` requests them. +/// +/// These are intentionally system-level paths only (plus Nix store roots) so +/// `include_platform_defaults` does not silently widen access to user data. +const LINUX_PLATFORM_DEFAULT_READ_ROOTS: &[&str] = &[ + "/bin", + "/sbin", + "/usr", + "/etc", + "/lib", + "/lib64", + "/nix/store", + "/run/current-system/sw", +]; + /// Options that control how bubblewrap is invoked. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct BwrapOptions { @@ -134,7 +150,8 @@ fn create_bwrap_flags( /// Build the bubblewrap filesystem mounts for a given sandbox policy. /// /// The mount order is important: -/// 1. `--ro-bind / /` makes the entire filesystem read-only. +/// 1. Full-read policies use `--ro-bind / /`; restricted-read policies start +/// from `--tmpfs /` and layer scoped `--ro-bind` mounts. /// 2. `--dev /dev` mounts a minimal writable `/dev` with standard device nodes /// (including `/dev/urandom`) even under a read-only root. /// 3. `--bind ` re-enables writes for allowed roots, including @@ -142,28 +159,69 @@ fn create_bwrap_flags( /// 4. `--ro-bind ` re-applies read-only protections under /// those writable roots so protected subpaths win. fn create_filesystem_args(sandbox_policy: &SandboxPolicy, cwd: &Path) -> Result> { - if !sandbox_policy.has_full_disk_read_access() { - return Err(CodexErr::UnsupportedOperation( - "Restricted read-only access is not yet supported by the Linux bubblewrap backend." - .to_string(), - )); - } - let writable_roots = sandbox_policy.get_writable_roots_with_cwd(cwd); ensure_mount_targets_exist(&writable_roots)?; - // Read-only root, then mount a minimal device tree. - // In bubblewrap (`bubblewrap.c`, `SETUP_MOUNT_DEV`), `--dev /dev` creates - // the standard minimal nodes: null, zero, full, random, urandom, and tty. - // `/dev` must be mounted before writable roots so explicit `/dev/*` - // writable binds remain visible. - let mut args = vec![ - "--ro-bind".to_string(), - "/".to_string(), - "/".to_string(), - "--dev".to_string(), - "/dev".to_string(), - ]; + let mut args = if sandbox_policy.has_full_disk_read_access() { + // Read-only root, then mount a minimal device tree. + // In bubblewrap (`bubblewrap.c`, `SETUP_MOUNT_DEV`), `--dev /dev` + // creates the standard minimal nodes: null, zero, full, random, + // urandom, and tty. `/dev` must be mounted before writable roots so + // explicit `/dev/*` writable binds remain visible. + vec![ + "--ro-bind".to_string(), + "/".to_string(), + "/".to_string(), + "--dev".to_string(), + "/dev".to_string(), + ] + } else { + // Start from an empty filesystem and add only the approved readable + // roots plus a minimal `/dev`. + let mut args = vec![ + "--tmpfs".to_string(), + "/".to_string(), + "--dev".to_string(), + "/dev".to_string(), + ]; + + let mut readable_roots: BTreeSet = sandbox_policy + .get_readable_roots_with_cwd(cwd) + .into_iter() + .map(PathBuf::from) + .collect(); + if sandbox_policy.include_platform_defaults() { + readable_roots.extend( + LINUX_PLATFORM_DEFAULT_READ_ROOTS + .iter() + .map(|path| PathBuf::from(*path)) + .filter(|path| path.exists()), + ); + } + + // A restricted policy can still explicitly request `/`, which is + // semantically equivalent to broad read access. + if readable_roots.iter().any(|root| root == Path::new("/")) { + args = vec![ + "--ro-bind".to_string(), + "/".to_string(), + "/".to_string(), + "--dev".to_string(), + "/dev".to_string(), + ]; + } else { + for root in readable_roots { + if !root.exists() { + continue; + } + args.push("--ro-bind".to_string()); + args.push(path_to_string(&root)); + args.push(path_to_string(&root)); + } + } + + args + }; for writable_root in &writable_roots { let root = writable_root.root.as_path(); @@ -322,9 +380,11 @@ fn find_first_non_existent_component(target_path: &Path) -> Option { #[cfg(test)] mod tests { use super::*; + use codex_protocol::protocol::ReadOnlyAccess; use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; + use tempfile::TempDir; #[test] fn full_disk_write_full_network_returns_unwrapped_command() { @@ -403,4 +463,60 @@ mod tests { ] ); } + + #[test] + fn restricted_read_only_uses_scoped_read_roots_instead_of_erroring() { + let temp_dir = TempDir::new().expect("temp dir"); + let readable_root = temp_dir.path().join("readable"); + std::fs::create_dir(&readable_root).expect("create readable root"); + + let policy = SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: false, + readable_roots: vec![ + AbsolutePathBuf::try_from(readable_root.as_path()) + .expect("absolute readable root"), + ], + }, + }; + + let args = create_filesystem_args(&policy, temp_dir.path()).expect("filesystem args"); + + assert_eq!(args[0..4], ["--tmpfs", "/", "--dev", "/dev"]); + + let readable_root_str = path_to_string(&readable_root); + assert!(args.windows(3).any(|window| { + window + == [ + "--ro-bind", + readable_root_str.as_str(), + readable_root_str.as_str(), + ] + })); + } + + #[test] + fn restricted_read_only_with_platform_defaults_includes_usr_when_present() { + let temp_dir = TempDir::new().expect("temp dir"); + let policy = SandboxPolicy::ReadOnly { + access: ReadOnlyAccess::Restricted { + include_platform_defaults: true, + readable_roots: Vec::new(), + }, + }; + + // `ReadOnlyAccess::Restricted` always includes `cwd` as a readable + // root. Using `"/"` here would intentionally collapse to broad read + // access, so use a non-root cwd to exercise the restricted path. + let args = create_filesystem_args(&policy, temp_dir.path()).expect("filesystem args"); + + assert!(args.starts_with(&["--tmpfs".to_string(), "/".to_string()])); + + if Path::new("/usr").exists() { + assert!( + args.windows(3) + .any(|window| window == ["--ro-bind", "/usr", "/usr"]) + ); + } + } } diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index b9c0d6c8b6..362fcaf35f 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -73,7 +73,6 @@ async fn run_cmd_result_with_writable_roots( let sandbox_cwd = cwd.clone(); let params = ExecParams { command: cmd.iter().copied().map(str::to_owned).collect(), - original_command: cmd.iter().copied().map(str::to_owned).collect(), cwd, expiration: timeout_ms.into(), env: create_env_from_core_vars(), @@ -316,7 +315,6 @@ async fn assert_network_blocked(cmd: &[&str]) { let sandbox_cwd = cwd.clone(); let params = ExecParams { command: cmd.iter().copied().map(str::to_owned).collect(), - original_command: cmd.iter().copied().map(str::to_owned).collect(), cwd, // Give the tool a generous 2-second timeout so even slow DNS timeouts // do not stall the suite. diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index eff8d8e13e..e624fe2b1b 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -227,6 +227,7 @@ async fn run_codex_tool_session_inner( parsed_cmd, network_approval_context: _, additional_permissions: _, + available_decisions: _, } = ev; handle_exec_approval_request( command, @@ -363,7 +364,7 @@ async fn run_codex_tool_session_inner( | EventMsg::ExitedReviewMode(_) | EventMsg::RequestUserInput(_) | EventMsg::DynamicToolCallRequest(_) - | EventMsg::SkillRequestApproval(_) + | EventMsg::DynamicToolCallResponse(_) | EventMsg::ContextCompacted(_) | EventMsg::ModelReroute(_) | EventMsg::ThreadRolledBack(_) diff --git a/codex-rs/mcp-server/src/lib.rs b/codex-rs/mcp-server/src/lib.rs index 554daf9a8c..6e4be0a91c 100644 --- a/codex-rs/mcp-server/src/lib.rs +++ b/codex-rs/mcp-server/src/lib.rs @@ -21,6 +21,7 @@ use tracing::debug; use tracing::error; use tracing::info; use tracing_subscriber::EnvFilter; +use tracing_subscriber::prelude::*; mod codex_tool_config; mod codex_tool_runner; @@ -45,6 +46,8 @@ pub use crate::patch_approval::PatchApprovalResponse; /// is a balance between throughput and memory usage – 128 messages should be /// plenty for an interactive CLI. const CHANNEL_CAPACITY: usize = 128; +const DEFAULT_ANALYTICS_ENABLED: bool = true; +const OTEL_SERVICE_NAME: &str = "codex_mcp_server"; type IncomingMessage = JsonRpcMessage; @@ -52,12 +55,44 @@ pub async fn run_main( arg0_paths: Arg0DispatchPaths, cli_config_overrides: CliConfigOverrides, ) -> IoResult<()> { - // Install a simple subscriber so `tracing` output is visible. Users can - // control the log level with `RUST_LOG`. - tracing_subscriber::fmt() + // Parse CLI overrides once and derive the base Config eagerly so later + // components do not need to work with raw TOML values. + let cli_kv_overrides = cli_config_overrides.parse_overrides().map_err(|e| { + std::io::Error::new( + ErrorKind::InvalidInput, + format!("error parsing -c overrides: {e}"), + ) + })?; + let config = Config::load_with_cli_overrides(cli_kv_overrides) + .await + .map_err(|e| { + std::io::Error::new(ErrorKind::InvalidData, format!("error loading config: {e}")) + })?; + + let otel = codex_core::otel_init::build_provider( + &config, + env!("CARGO_PKG_VERSION"), + Some(OTEL_SERVICE_NAME), + DEFAULT_ANALYTICS_ENABLED, + ) + .map_err(|e| { + std::io::Error::new( + ErrorKind::InvalidData, + format!("error loading otel config: {e}"), + ) + })?; + + let fmt_layer = tracing_subscriber::fmt::layer() .with_writer(std::io::stderr) - .with_env_filter(EnvFilter::from_default_env()) - .init(); + .with_filter(EnvFilter::from_default_env()); + let otel_logger_layer = otel.as_ref().and_then(|provider| provider.logger_layer()); + let otel_tracing_layer = otel.as_ref().and_then(|provider| provider.tracing_layer()); + + let _ = tracing_subscriber::registry() + .with(fmt_layer) + .with(otel_logger_layer) + .with(otel_tracing_layer) + .try_init(); // Set up channels. let (incoming_tx, mut incoming_rx) = mpsc::channel::(CHANNEL_CAPACITY); @@ -86,20 +121,6 @@ pub async fn run_main( } }); - // Parse CLI overrides once and derive the base Config eagerly so later - // components do not need to work with raw TOML values. - let cli_kv_overrides = cli_config_overrides.parse_overrides().map_err(|e| { - std::io::Error::new( - ErrorKind::InvalidInput, - format!("error parsing -c overrides: {e}"), - ) - })?; - let config = Config::load_with_cli_overrides(cli_kv_overrides) - .await - .map_err(|e| { - std::io::Error::new(ErrorKind::InvalidData, format!("error loading config: {e}")) - })?; - // Task: process incoming messages. let processor_handle = tokio::spawn({ let outgoing_message_sender = OutgoingMessageSender::new(outgoing_tx); @@ -152,3 +173,55 @@ pub async fn run_main( Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use codex_core::config::ConfigBuilder; + use codex_core::config::types::OtelExporterKind; + use pretty_assertions::assert_eq; + use std::collections::HashMap; + use tempfile::TempDir; + + #[test] + fn mcp_server_defaults_analytics_to_enabled() { + assert_eq!(DEFAULT_ANALYTICS_ENABLED, true); + } + + #[tokio::test] + async fn mcp_server_builds_otel_provider_with_logs_traces_and_metrics() -> anyhow::Result<()> { + let codex_home = TempDir::new()?; + let mut config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .build() + .await?; + let exporter = OtelExporterKind::OtlpGrpc { + endpoint: "http://localhost:4317".to_string(), + headers: HashMap::new(), + tls: None, + }; + config.otel.exporter = exporter.clone(); + config.otel.trace_exporter = exporter.clone(); + config.otel.metrics_exporter = exporter; + config.analytics_enabled = None; + + let provider = codex_core::otel_init::build_provider( + &config, + "0.0.0-test", + Some(OTEL_SERVICE_NAME), + DEFAULT_ANALYTICS_ENABLED, + ) + .map_err(|err| anyhow::anyhow!(err.to_string()))? + .expect("otel provider"); + + assert!(provider.logger.is_some(), "expected log exporter"); + assert!( + provider.tracer_provider.is_some(), + "expected trace exporter" + ); + assert!(provider.metrics().is_some(), "expected metrics exporter"); + provider.shutdown(); + + Ok(()) + } +} diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index d6cf0d23e1..6b634e1947 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -6,6 +6,7 @@ use codex_core::ThreadManager; use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::Submission; @@ -62,6 +63,11 @@ impl MessageProcessor { auth_manager, SessionSource::Mcp, config.model_catalog.clone(), + CollaborationModesConfig { + default_mode_request_user_input: config + .features + .enabled(codex_core::features::Feature::DefaultModeRequestUserInput), + }, )); Self { outgoing, diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index 7dcfa0c233..684cd1a705 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -300,6 +300,7 @@ mod tests { thread_name: None, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -342,6 +343,7 @@ mod tests { thread_name: None, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -408,6 +410,7 @@ mod tests { thread_name: None, model: "gpt-4o".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), diff --git a/codex-rs/node-version.txt b/codex-rs/node-version.txt index 32f8c50de0..85e502778f 100644 --- a/codex-rs/node-version.txt +++ b/codex-rs/node-version.txt @@ -1 +1 @@ -24.13.1 +22.22.0 diff --git a/codex-rs/otel/src/lib.rs b/codex-rs/otel/src/lib.rs index 5aaee5f5a9..217099524c 100644 --- a/codex-rs/otel/src/lib.rs +++ b/codex-rs/otel/src/lib.rs @@ -1,6 +1,7 @@ pub mod config; pub mod metrics; pub mod otel_provider; +pub mod trace_context; pub mod traces; mod otlp; @@ -23,6 +24,11 @@ use tracing::debug; pub use crate::metrics::runtime_metrics::RuntimeMetricTotals; pub use crate::metrics::runtime_metrics::RuntimeMetricsSummary; +pub use crate::otel_provider::traceparent_context_from_env; +pub use crate::trace_context::context_from_w3c_trace_context; +pub use crate::trace_context::current_span_w3c_trace_context; +pub use crate::trace_context::set_parent_from_context; +pub use crate::trace_context::set_parent_from_w3c_trace_context; #[derive(Debug, Clone, Serialize, Display)] #[serde(rename_all = "snake_case")] diff --git a/codex-rs/otel/src/otel_provider.rs b/codex-rs/otel/src/otel_provider.rs index 6f2dc5a09d..c9233f5d6a 100644 --- a/codex-rs/otel/src/otel_provider.rs +++ b/codex-rs/otel/src/otel_provider.rs @@ -3,13 +3,12 @@ use crate::config::OtelHttpProtocol; use crate::config::OtelSettings; use crate::metrics::MetricsClient; use crate::metrics::MetricsConfig; +use crate::trace_context::context_from_trace_headers; use gethostname::gethostname; use opentelemetry::Context; use opentelemetry::KeyValue; use opentelemetry::context::ContextGuard; use opentelemetry::global; -use opentelemetry::propagation::TextMapPropagator; -use opentelemetry::trace::TraceContextExt; use opentelemetry::trace::TracerProvider as _; use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; use opentelemetry_otlp::LogExporter; @@ -30,7 +29,6 @@ use opentelemetry_sdk::trace::SdkTracerProvider; use opentelemetry_sdk::trace::Tracer; use opentelemetry_semantic_conventions as semconv; use std::cell::RefCell; -use std::collections::HashMap; use std::env; use std::error::Error; use std::sync::OnceLock; @@ -172,7 +170,7 @@ impl Drop for OtelProvider { } } -pub(crate) fn traceparent_context_from_env() -> Option { +pub fn traceparent_context_from_env() -> Option { TRACEPARENT_CONTEXT .get_or_init(load_traceparent_context) .clone() @@ -194,7 +192,7 @@ fn load_traceparent_context() -> Option { let traceparent = env::var(TRACEPARENT_ENV_VAR).ok()?; let tracestate = env::var(TRACESTATE_ENV_VAR).ok(); - match extract_traceparent_context(traceparent, tracestate) { + match context_from_trace_headers(Some(&traceparent), tracestate.as_deref()) { Some(context) => { debug!("TRACEPARENT detected; continuing trace from parent context"); Some(context) @@ -206,22 +204,6 @@ fn load_traceparent_context() -> Option { } } -fn extract_traceparent_context(traceparent: String, tracestate: Option) -> Option { - let mut headers = HashMap::new(); - headers.insert("traceparent".to_string(), traceparent); - if let Some(tracestate) = tracestate { - headers.insert("tracestate".to_string(), tracestate); - } - - let context = TraceContextPropagator::new().extract(&headers); - let span = context.span(); - let span_context = span.span_context(); - if !span_context.is_valid() { - return None; - } - Some(context) -} - fn make_resource(settings: &OtelSettings) -> Resource { Resource::builder() .with_service_name(settings.service_name.clone()) @@ -407,8 +389,9 @@ mod tests { fn parses_valid_traceparent() { let trace_id = "00000000000000000000000000000001"; let span_id = "0000000000000002"; - let context = extract_traceparent_context(format!("00-{trace_id}-{span_id}-01"), None) - .expect("trace context"); + let context = + context_from_trace_headers(Some(&format!("00-{trace_id}-{span_id}-01")), None) + .expect("trace context"); let span = context.span(); let span_context = span.span_context(); assert_eq!( @@ -421,7 +404,7 @@ mod tests { #[test] fn invalid_traceparent_returns_none() { - assert!(extract_traceparent_context("not-a-traceparent".to_string(), None).is_none()); + assert!(context_from_trace_headers(Some("not-a-traceparent"), None).is_none()); } #[test] diff --git a/codex-rs/otel/src/trace_context.rs b/codex-rs/otel/src/trace_context.rs new file mode 100644 index 0000000000..3ef38062d3 --- /dev/null +++ b/codex-rs/otel/src/trace_context.rs @@ -0,0 +1,106 @@ +use std::collections::HashMap; + +use codex_protocol::protocol::W3cTraceContext; +use opentelemetry::Context; +use opentelemetry::propagation::TextMapPropagator; +use opentelemetry::trace::TraceContextExt; +use opentelemetry_sdk::propagation::TraceContextPropagator; +use tracing::Span; +use tracing_opentelemetry::OpenTelemetrySpanExt; + +pub fn current_span_w3c_trace_context() -> Option { + let context = Span::current().context(); + if !context.span().span_context().is_valid() { + return None; + } + + let mut headers = HashMap::new(); + TraceContextPropagator::new().inject_context(&context, &mut headers); + + Some(W3cTraceContext { + traceparent: headers.remove("traceparent"), + tracestate: headers.remove("tracestate"), + }) +} + +pub fn context_from_w3c_trace_context(trace: &W3cTraceContext) -> Option { + context_from_trace_headers(trace.traceparent.as_deref(), trace.tracestate.as_deref()) +} + +pub fn set_parent_from_w3c_trace_context(span: &Span, trace: &W3cTraceContext) -> bool { + if let Some(context) = context_from_w3c_trace_context(trace) { + set_parent_from_context(span, context); + true + } else { + false + } +} + +pub fn set_parent_from_context(span: &Span, context: Context) { + let _ = span.set_parent(context); +} + +pub(crate) fn context_from_trace_headers( + traceparent: Option<&str>, + tracestate: Option<&str>, +) -> Option { + let traceparent = traceparent?; + let mut headers = HashMap::new(); + headers.insert("traceparent".to_string(), traceparent.to_string()); + if let Some(tracestate) = tracestate { + headers.insert("tracestate".to_string(), tracestate.to_string()); + } + + let context = TraceContextPropagator::new().extract(&headers); + if !context.span().span_context().is_valid() { + return None; + } + Some(context) +} + +#[cfg(test)] +mod tests { + use super::context_from_trace_headers; + use super::context_from_w3c_trace_context; + use codex_protocol::protocol::W3cTraceContext; + use opentelemetry::trace::SpanId; + use opentelemetry::trace::TraceContextExt; + use opentelemetry::trace::TraceId; + use pretty_assertions::assert_eq; + + #[test] + fn parses_valid_w3c_trace_context() { + let trace_id = "00000000000000000000000000000001"; + let span_id = "0000000000000002"; + let context = context_from_w3c_trace_context(&W3cTraceContext { + traceparent: Some(format!("00-{trace_id}-{span_id}-01")), + tracestate: None, + }) + .expect("trace context"); + + let span = context.span(); + let span_context = span.span_context(); + assert_eq!( + span_context.trace_id(), + TraceId::from_hex(trace_id).unwrap() + ); + assert_eq!(span_context.span_id(), SpanId::from_hex(span_id).unwrap()); + assert!(span_context.is_remote()); + } + + #[test] + fn invalid_traceparent_returns_none() { + assert!(context_from_trace_headers(Some("not-a-traceparent"), None).is_none()); + } + + #[test] + fn missing_traceparent_returns_none() { + assert!( + context_from_w3c_trace_context(&W3cTraceContext { + traceparent: None, + tracestate: Some("vendor=value".to_string()), + }) + .is_none() + ); + } +} diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index f742dc6328..12bd65ec59 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -2,14 +2,30 @@ use std::collections::HashMap; use std::path::PathBuf; use crate::mcp::RequestId; +use crate::models::MacOsSeatbeltProfileExtensions; use crate::models::PermissionProfile; use crate::parse_command::ParsedCommand; use crate::protocol::FileChange; +use crate::protocol::ReviewDecision; +use crate::protocol::SandboxPolicy; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use ts_rs::TS; +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Permissions { + pub sandbox_policy: SandboxPolicy, + pub macos_seatbelt_profile_extensions: Option, +} + +#[allow(clippy::large_enum_variant)] +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EscalationPermissions { + PermissionProfile(PermissionProfile), + Permissions(Permissions), +} + /// Proposed execpolicy change to allow commands starting with this prefix. /// /// The `command` tokens form the prefix that would be added as an execpolicy @@ -107,6 +123,13 @@ pub struct ExecApprovalRequestEvent { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub additional_permissions: Option, + /// Ordered list of decisions the client may present for this prompt. + /// + /// When absent, clients should derive the legacy default set from the + /// other fields on this request. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub available_decisions: Option>, pub parsed_cmd: Vec, } @@ -116,6 +139,55 @@ impl ExecApprovalRequestEvent { .clone() .unwrap_or_else(|| self.call_id.clone()) } + + pub fn effective_available_decisions(&self) -> Vec { + // available_decisions is a new field that may not be populated by older + // senders, so we fall back to the legacy logic if it's not present. + match &self.available_decisions { + Some(decisions) => decisions.clone(), + None => Self::default_available_decisions( + self.network_approval_context.as_ref(), + self.proposed_execpolicy_amendment.as_ref(), + self.proposed_network_policy_amendments.as_deref(), + self.additional_permissions.as_ref(), + ), + } + } + + pub fn default_available_decisions( + network_approval_context: Option<&NetworkApprovalContext>, + proposed_execpolicy_amendment: Option<&ExecPolicyAmendment>, + proposed_network_policy_amendments: Option<&[NetworkPolicyAmendment]>, + additional_permissions: Option<&PermissionProfile>, + ) -> Vec { + if network_approval_context.is_some() { + let mut decisions = vec![ReviewDecision::Approved, ReviewDecision::ApprovedForSession]; + if let Some(amendment) = proposed_network_policy_amendments.and_then(|amendments| { + amendments + .iter() + .find(|amendment| amendment.action == NetworkPolicyRuleAction::Allow) + }) { + decisions.push(ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: amendment.clone(), + }); + } + decisions.push(ReviewDecision::Abort); + return decisions; + } + + if additional_permissions.is_some() { + return vec![ReviewDecision::Approved, ReviewDecision::Abort]; + } + + let mut decisions = vec![ReviewDecision::Approved]; + if let Some(prefix) = proposed_execpolicy_amendment { + decisions.push(ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: prefix.clone(), + }); + } + decisions.push(ReviewDecision::Abort); + decisions + } } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index 7586212adb..984dcf39f1 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -113,6 +113,13 @@ pub enum WebSearchMode { Live, } +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum ServiceTier { + Fast, +} + #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs index c942a717d7..5841b1187e 100644 --- a/codex-rs/protocol/src/lib.rs +++ b/codex-rs/protocol/src/lib.rs @@ -15,5 +15,4 @@ pub mod parse_command; pub mod plan_tool; pub mod protocol; pub mod request_user_input; -pub mod skill_approval; pub mod user_input; diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index ff5030c75e..8461209823 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; use std::path::Path; -use std::path::PathBuf; use codex_utils_image::load_and_resize_to_fit; use serde::Deserialize; @@ -15,11 +14,14 @@ use crate::protocol::AskForApproval; use crate::protocol::COLLABORATION_MODE_CLOSE_TAG; use crate::protocol::COLLABORATION_MODE_OPEN_TAG; use crate::protocol::NetworkAccess; +use crate::protocol::REALTIME_CONVERSATION_CLOSE_TAG; +use crate::protocol::REALTIME_CONVERSATION_OPEN_TAG; use crate::protocol::SandboxPolicy; use crate::protocol::WritableRoot; use crate::user_input::UserInput; use codex_execpolicy::Policy; use codex_git::GhostCommit; +use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_image::error::ImageProcessingError; use schemars::JsonSchema; @@ -54,8 +56,8 @@ impl SandboxPermissions { #[derive(Debug, Clone, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS)] pub struct FileSystemPermissions { - pub read: Option>, - pub write: Option>, + pub read: Option>, + pub write: Option>, } impl FileSystemPermissions { @@ -95,6 +97,32 @@ pub enum MacOsAutomationValue { BundleIds(Vec), } +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum MacOsPreferencesPermission { + // IMPORTANT: ReadOnly needs to be the default because it's the + // security-sensitive default and keeps cf prefs working. + #[default] + ReadOnly, + ReadWrite, + None, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum MacOsAutomationPermission { + #[default] + None, + All, + BundleIds(Vec), +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct MacOsSeatbeltProfileExtensions { + pub macos_preferences: MacOsPreferencesPermission, + pub macos_automation: MacOsAutomationPermission, + pub macos_accessibility: bool, + pub macos_calendar: bool, +} + #[derive(Debug, Clone, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TS)] pub struct PermissionProfile { pub network: Option, @@ -135,7 +163,7 @@ pub enum ResponseInputItem { }, CustomToolCallOutput { call_id: String, - output: String, + output: FunctionCallOutputPayload, }, } @@ -235,9 +263,12 @@ pub enum ResponseItem { name: String, input: String, }, + // `custom_tool_call_output.output` uses the same wire encoding as + // `function_call_output.output` so freeform tools can return either plain + // text or structured content items. CustomToolCallOutput { call_id: String, - output: String, + output: FunctionCallOutputPayload, }, // Emitted by the Responses API when the agent triggers a web search. // Example payload (from SSE `response.output_item.done`): @@ -311,6 +342,9 @@ const SANDBOX_MODE_WORKSPACE_WRITE: &str = include_str!("prompts/permissions/sandbox_mode/workspace_write.md"); const SANDBOX_MODE_READ_ONLY: &str = include_str!("prompts/permissions/sandbox_mode/read_only.md"); +const REALTIME_START_INSTRUCTIONS: &str = include_str!("prompts/realtime/realtime_start.md"); +const REALTIME_END_INSTRUCTIONS: &str = include_str!("prompts/realtime/realtime_end.md"); + impl DeveloperInstructions { pub fn new>(text: T) -> Self { Self { text: text.into() } @@ -380,6 +414,20 @@ impl DeveloperInstructions { )) } + pub fn realtime_start_message() -> Self { + DeveloperInstructions::new(format!( + "{REALTIME_CONVERSATION_OPEN_TAG}\n{}\n{REALTIME_CONVERSATION_CLOSE_TAG}", + REALTIME_START_INSTRUCTIONS.trim() + )) + } + + pub fn realtime_end_message(reason: &str) -> Self { + DeveloperInstructions::new(format!( + "{REALTIME_CONVERSATION_OPEN_TAG}\n{}\n\nReason: {reason}\n{REALTIME_CONVERSATION_CLOSE_TAG}", + REALTIME_END_INSTRUCTIONS.trim() + )) + } + pub fn personality_spec_message(spec: String) -> Self { let message = format!( " The user has requested a new communication style. Future messages should adhere to the following personality: \n{spec} " @@ -1512,6 +1560,26 @@ mod tests { Ok(()) } + #[test] + fn serializes_custom_tool_image_outputs_as_array() -> Result<()> { + let item = ResponseInputItem::CustomToolCallOutput { + call_id: "call1".into(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: "data:image/png;base64,BASE64".into(), + }, + ]), + }; + + let json = serde_json::to_string(&item)?; + let v: serde_json::Value = serde_json::from_str(&json)?; + + let output = v.get("output").expect("output field"); + assert!(output.is_array(), "expected array output"); + + Ok(()) + } + #[test] fn preserves_existing_image_data_urls() -> Result<()> { let call_tool_result = CallToolResult { diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index 8d01e10d0b..b63f137442 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -15,6 +15,7 @@ use tracing::warn; use ts_rs::TS; use crate::config_types::Personality; +use crate::config_types::ReasoningSummary; use crate::config_types::Verbosity; const PERSONALITY_PLACEHOLDER: &str = "{{ personality }}"; @@ -98,6 +99,11 @@ pub struct ModelUpgrade { pub migration_markdown: Option, } +#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)] +pub struct ModelAvailabilityNux { + pub message: String, +} + /// Metadata describing a Codex-supported model. #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)] pub struct ModelPreset { @@ -122,6 +128,8 @@ pub struct ModelPreset { pub upgrade: Option, /// Whether this preset should appear in the picker UI. pub show_in_picker: bool, + /// Availability NUX shown when this preset becomes accessible to the user. + pub availability_nux: Option, /// whether this model is supported in the api pub supported_in_api: bool, /// Input modalities accepted when composing user turns for this preset. @@ -224,11 +232,14 @@ pub struct ModelInfo { pub visibility: ModelVisibility, pub supported_in_api: bool, pub priority: i32, + pub availability_nux: Option, pub upgrade: Option, pub base_instructions: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub model_messages: Option, pub supports_reasoning_summaries: bool, + #[serde(default)] + pub default_reasoning_summary: ReasoningSummary, pub support_verbosity: bool, pub default_verbosity: Option, pub apply_patch_tool_type: Option, @@ -407,6 +418,7 @@ impl From for ModelPreset { migration_markdown: Some(upgrade.migration_markdown.clone()), }), show_in_picker: info.visibility == ModelVisibility::List, + availability_nux: info.availability_nux, supported_in_api: info.supported_in_api, input_modalities: info.input_modalities, } @@ -492,10 +504,12 @@ mod tests { visibility: ModelVisibility::List, supported_in_api: true, priority: 1, + availability_nux: None, upgrade: None, base_instructions: "base".to_string(), model_messages: spec, supports_reasoning_summaries: false, + default_reasoning_summary: ReasoningSummary::Auto, support_verbosity: false, default_verbosity: None, apply_patch_tool_type: None, @@ -664,4 +678,57 @@ mod tests { ); assert_eq!(personality_variables.get_personality_message(None), None); } + + #[test] + fn model_info_defaults_availability_nux_to_none_when_omitted() { + let model: ModelInfo = serde_json::from_value(serde_json::json!({ + "slug": "test-model", + "display_name": "Test Model", + "description": null, + "supported_reasoning_levels": [], + "shell_type": "shell_command", + "visibility": "list", + "supported_in_api": true, + "priority": 1, + "upgrade": null, + "base_instructions": "base", + "model_messages": null, + "supports_reasoning_summaries": false, + "default_reasoning_summary": "auto", + "support_verbosity": false, + "default_verbosity": null, + "apply_patch_tool_type": null, + "truncation_policy": { + "mode": "bytes", + "limit": 10000 + }, + "supports_parallel_tool_calls": false, + "context_window": null, + "auto_compact_token_limit": null, + "effective_context_window_percent": 95, + "experimental_supported_tools": [], + "input_modalities": ["text", "image"], + "prefer_websockets": false + })) + .expect("deserialize model info"); + + assert_eq!(model.availability_nux, None); + } + + #[test] + fn model_preset_preserves_availability_nux() { + let preset = ModelPreset::from(ModelInfo { + availability_nux: Some(ModelAvailabilityNux { + message: "Try Spark.".to_string(), + }), + ..test_model(None) + }); + + assert_eq!( + preset.availability_nux, + Some(ModelAvailabilityNux { + message: "Try Spark.".to_string(), + }) + ); + } } diff --git a/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md b/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md index 96d962d12d..3928a91b7e 100644 --- a/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md +++ b/codex-rs/protocol/src/prompts/permissions/approval_policy/on_request_rule.md @@ -27,7 +27,7 @@ IMPORTANT: To request approval to execute a command that will require escalated - Include a short question asking the user if they want to allow the action in `justification` parameter. e.g. "Do you want to download and install dependencies for this project?" - Optionally suggest a `prefix_rule` - this will be shown to the user with an option to persist the rule approval for future sessions. -If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with "require_escalated". ALWAYS proceed to use the `justification` parameter - do not message the user before requesting approval for the command. +If you run a command that is important to solving the user's query, but it fails because of sandboxing or with a likely sandbox-related network error (for example DNS/host resolution, registry/index access, or dependency download failure), rerun the command with "require_escalated". ALWAYS proceed to use the `justification` parameter - do not message the user before requesting approval for the command. ## When to request escalation @@ -35,7 +35,7 @@ While commands are running inside the sandbox, here are some scenarios that will - You need to run a command that writes to a directory that requires it (e.g. running tests that write to /var) - You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files. -- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with `require_escalated`. ALWAYS proceed to use the `sandbox_permissions` and `justification` parameters. do not message the user before requesting approval for the command. +- If you run a command that is important to solving the user's query, but it fails because of sandboxing or with a likely sandbox-related network error (for example DNS/host resolution, registry/index access, or dependency download failure), rerun the command with `require_escalated`. ALWAYS proceed to use the `sandbox_permissions` and `justification` parameters. do not message the user before requesting approval for the command. - You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for. - Be judicious with escalating, but if completing the user's request requires it, you should do so - don't try and circumvent approvals by using other tools. @@ -54,4 +54,3 @@ Good examples of prefixes: - ["gh", "pr", "check"] - ["pytest"] - ["cargo", "test"] - diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_end.md b/codex-rs/protocol/src/prompts/realtime/realtime_end.md new file mode 100644 index 0000000000..07ccae5286 --- /dev/null +++ b/codex-rs/protocol/src/prompts/realtime/realtime_end.md @@ -0,0 +1,5 @@ +Realtime conversation ended. + +You are still operating behind an intermediary rather than speaking to the user directly. Use the conversation transcript and current context to decide whether backend help is actually needed, and avoid verbose responses that only add latency. + +Subsequent user input may return to typed text rather than transcript-style text. Do not assume recognition errors or missing punctuation once realtime has ended. Resume normal chat behavior. diff --git a/codex-rs/protocol/src/prompts/realtime/realtime_start.md b/codex-rs/protocol/src/prompts/realtime/realtime_start.md new file mode 100644 index 0000000000..c7d363eff7 --- /dev/null +++ b/codex-rs/protocol/src/prompts/realtime/realtime_start.md @@ -0,0 +1,10 @@ +Realtime conversation started. + +You are operating as a backend executor behind an intermediary. The user does not talk to you directly. Any response you produce will be consumed by the intermediary and may be summarized before the user sees it. + +When invoked, you receive the latest conversation transcript and any relevant mode or metadata. The intermediary may invoke you even when backend help is not actually needed. Use the transcript to decide whether you should do work. If backend help is unnecessary, avoid verbose responses that add user-visible latency. + +When user text is routed from realtime, treat it as a transcript. It may be unpunctuated or contain recognition errors. + +- Ask brief clarification questions when needed. +- Keep responses concise and action-oriented. diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index a8770cc90a..3f1c392719 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -18,8 +18,10 @@ use crate::config_types::CollaborationMode; use crate::config_types::ModeKind; use crate::config_types::Personality; use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; +use crate::config_types::ServiceTier; use crate::config_types::WindowsSandboxLevel; use crate::custom_prompts::CustomPrompt; +use crate::dynamic_tools::DynamicToolCallOutputContentItem; use crate::dynamic_tools::DynamicToolCallRequest; use crate::dynamic_tools::DynamicToolResponse; use crate::dynamic_tools::DynamicToolSpec; @@ -40,7 +42,6 @@ use crate::openai_models::ReasoningEffort as ReasoningEffortConfig; use crate::parse_command::ParsedCommand; use crate::plan_tool::UpdatePlanArgs; use crate::request_user_input::RequestUserInputResponse; -use crate::skill_approval::SkillApprovalResponse; use crate::user_input::UserInput; use codex_utils_absolute_path::AbsolutePathBuf; use schemars::JsonSchema; @@ -61,7 +62,6 @@ pub use crate::approvals::NetworkApprovalProtocol; pub use crate::approvals::NetworkPolicyAmendment; pub use crate::approvals::NetworkPolicyRuleAction; pub use crate::request_user_input::RequestUserInputEvent; -pub use crate::skill_approval::SkillRequestApprovalEvent; /// Open/close tags for special user-input blocks. Used across crates to avoid /// duplicated hardcoded strings. @@ -71,6 +71,8 @@ pub const ENVIRONMENT_CONTEXT_OPEN_TAG: &str = ""; pub const ENVIRONMENT_CONTEXT_CLOSE_TAG: &str = ""; pub const COLLABORATION_MODE_OPEN_TAG: &str = ""; pub const COLLABORATION_MODE_CLOSE_TAG: &str = ""; +pub const REALTIME_CONVERSATION_OPEN_TAG: &str = ""; +pub const REALTIME_CONVERSATION_CLOSE_TAG: &str = ""; pub const USER_MESSAGE_BEGIN: &str = "## My request for Codex:"; /// Submission Queue Entry - requests from user @@ -82,6 +84,16 @@ pub struct Submission { pub op: Op, } +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct W3cTraceContext { + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub traceparent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub tracestate: Option, +} + /// Config payload for refreshing MCP servers. #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema)] pub struct McpServerRefreshConfig { @@ -105,12 +117,32 @@ pub struct RealtimeAudioFrame { pub samples_per_channel: Option, } +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct RealtimeHandoffMessage { + pub role: String, + pub text: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct RealtimeHandoffRequested { + pub handoff_id: String, + pub item_id: String, + pub input_transcript: String, + pub messages: Vec, +} + #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] pub enum RealtimeEvent { - SessionCreated { session_id: String }, - SessionUpdated { backend_prompt: Option }, + SessionUpdated { + session_id: String, + instructions: Option, + }, AudioOut(RealtimeAudioFrame), ConversationItemAdded(Value), + ConversationItemDone { + item_id: String, + }, + HandoffRequested(RealtimeHandoffRequested), Error(String), } @@ -186,7 +218,20 @@ pub enum Op { effort: Option, /// Will only be honored if the model is configured to use reasoning. - summary: ReasoningSummaryConfig, + /// + /// When omitted, the session keeps the current setting (which allows core to + /// fall back to the selected model's default on new sessions). + #[serde(default, skip_serializing_if = "Option::is_none")] + summary: Option, + + /// Optional service tier override for this turn. + /// + /// Use `Some(Some(_))` to set a specific tier for this turn, `Some(None)` to + /// explicitly clear the tier for this turn, or `None` to keep the existing + /// session preference. + #[serde(default, skip_serializing_if = "Option::is_none")] + service_tier: Option>, + // The JSON schema to use for the final assistant message final_output_json_schema: Option, @@ -239,6 +284,13 @@ pub enum Op { #[serde(skip_serializing_if = "Option::is_none")] summary: Option, + /// Updated service tier preference for future turns. + /// + /// Use `Some(Some(_))` to set a specific tier, `Some(None)` to clear the + /// preference, or `None` to leave the existing value unchanged. + #[serde(skip_serializing_if = "Option::is_none")] + service_tier: Option>, + /// EXPERIMENTAL - set a pre-set collaboration mode. /// Takes precedence over model, effort, and developer instructions if set. #[serde(skip_serializing_if = "Option::is_none")] @@ -295,14 +347,6 @@ pub enum Op { response: DynamicToolResponse, }, - /// Resolve a skill approval request. - SkillApproval { - /// Item id for the in-flight request. - id: String, - /// User decision. - response: SkillApprovalResponse, - }, - /// Append an entry to the persistent cross-session message history. /// /// Note the entry is not guaranteed to be logged if the user has @@ -1053,7 +1097,7 @@ pub enum EventMsg { DynamicToolCallRequest(DynamicToolCallRequest), - SkillRequestApproval(SkillRequestApprovalEvent), + DynamicToolCallResponse(DynamicToolCallResponseEvent), ElicitationRequest(ElicitationRequestEvent), @@ -1781,6 +1825,27 @@ pub struct McpToolCallEndEvent { pub result: Result, } +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq)] +pub struct DynamicToolCallResponseEvent { + /// Identifier for the corresponding DynamicToolCallRequest. + pub call_id: String, + /// Turn ID that this dynamic tool call belongs to. + pub turn_id: String, + /// Dynamic tool name. + pub tool: String, + /// Dynamic tool call arguments. + pub arguments: serde_json::Value, + /// Dynamic tool response content items. + pub content_items: Vec, + /// Whether the tool call succeeded. + pub success: bool, + /// Optional error text when the tool call failed before producing a response. + pub error: Option, + /// The duration of the dynamic tool call. + #[ts(type = "string")] + pub duration: Duration, +} + impl McpToolCallEndEvent { pub fn is_success(&self) -> bool { match &self.result { @@ -1976,7 +2041,7 @@ impl SessionSource { agent_nickname.clone() } SessionSource::SubAgent(SubAgentSource::MemoryConsolidation) => { - Some("morpheus".to_string()) + Some("Morpheus".to_string()) } _ => None, } @@ -2042,6 +2107,8 @@ pub struct SessionMeta { pub base_instructions: Option, #[serde(skip_serializing_if = "Option::is_none")] pub dynamic_tools: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_mode: Option, } impl Default for SessionMeta { @@ -2059,6 +2126,7 @@ impl Default for SessionMeta { model_provider: None, base_instructions: None, dynamic_tools: None, + memory_mode: None, } } } @@ -2108,15 +2176,19 @@ pub struct TurnContextNetworkItem { pub denied_domains: Vec, } -/// Persist only when the same turn also persists the corresponding -/// model-visible context updates (diffs or full reinjection), so -/// resume/fork does not use a `reference_context_item` whose context -/// was never actually visible to the model. +/// Persist once per real user turn after computing that turn's model-visible +/// context updates, and again after mid-turn compaction when replacement +/// history re-establishes full context, so resume/fork replay can recover the +/// latest durable baseline. #[derive(Serialize, Deserialize, Clone, Debug, JsonSchema, TS)] pub struct TurnContextItem { #[serde(default, skip_serializing_if = "Option::is_none")] pub turn_id: Option, pub cwd: PathBuf, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub current_date: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timezone: Option, pub approval_policy: AskForApproval, pub sandbox_policy: SandboxPolicy, #[serde(skip_serializing_if = "Option::is_none")] @@ -2126,6 +2198,8 @@ pub struct TurnContextItem { pub personality: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub collaboration_mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub realtime_active: Option, #[serde(skip_serializing_if = "Option::is_none")] pub effort: Option, pub summary: ReasoningSummaryConfig, @@ -2709,6 +2783,9 @@ pub struct SessionConfiguredEvent { pub model_provider_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub service_tier: Option, + /// When to escalate for approval for execution pub approval_policy: AskForApproval, @@ -2765,8 +2842,8 @@ pub enum ReviewDecision { proposed_execpolicy_amendment: ExecPolicyAmendment, }, - /// User has approved this command and wants to automatically approve any - /// future identical instances (`command` and `cwd` match exactly) for the + /// User has approved this request and wants future prompts in the same + /// session-scoped approval cache to be automatically approved for the /// remainder of the session. ApprovedForSession, @@ -3345,6 +3422,8 @@ mod tests { let item = TurnContextItem { turn_id: None, cwd: PathBuf::from("/tmp"), + current_date: None, + timezone: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::DangerFullAccess, network: Some(TurnContextNetworkItem { @@ -3354,6 +3433,7 @@ mod tests { model: "gpt-5".to_string(), personality: None, collaboration_mode: None, + realtime_active: None, effort: None, summary: ReasoningSummaryConfig::Auto, user_instructions: None, @@ -3387,6 +3467,7 @@ mod tests { thread_name: None, model: "codex-mini-latest".to_string(), model_provider_id: "openai".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), diff --git a/codex-rs/protocol/src/skill_approval.rs b/codex-rs/protocol/src/skill_approval.rs deleted file mode 100644 index 152e248186..0000000000 --- a/codex-rs/protocol/src/skill_approval.rs +++ /dev/null @@ -1,15 +0,0 @@ -use schemars::JsonSchema; -use serde::Deserialize; -use serde::Serialize; -use ts_rs::TS; - -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] -pub struct SkillRequestApprovalEvent { - pub item_id: String, - pub skill_name: String, -} - -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] -pub struct SkillApprovalResponse { - pub approved: bool, -} diff --git a/codex-rs/protocol/src/user_input.rs b/codex-rs/protocol/src/user_input.rs index d40511f342..c1c22dcaf9 100644 --- a/codex-rs/protocol/src/user_input.rs +++ b/codex-rs/protocol/src/user_input.rs @@ -3,6 +3,9 @@ use serde::Deserialize; use serde::Serialize; use ts_rs::TS; +/// Conservative cap so one user message cannot monopolize a large context window. +pub const MAX_USER_INPUT_TEXT_CHARS: usize = 1 << 20; + /// User input #[non_exhaustive] #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, TS, JsonSchema)] diff --git a/codex-rs/rmcp-client/src/perform_oauth_login.rs b/codex-rs/rmcp-client/src/perform_oauth_login.rs index 62a9c3b019..c71799c629 100644 --- a/codex-rs/rmcp-client/src/perform_oauth_login.rs +++ b/codex-rs/rmcp-client/src/perform_oauth_login.rs @@ -47,6 +47,7 @@ pub async fn perform_oauth_login( http_headers: Option>, env_http_headers: Option>, scopes: &[String], + oauth_resource: Option<&str>, callback_port: Option, callback_url: Option<&str>, ) -> Result<()> { @@ -60,6 +61,7 @@ pub async fn perform_oauth_login( store_mode, headers, scopes, + oauth_resource, true, callback_port, callback_url, @@ -78,6 +80,7 @@ pub async fn perform_oauth_login_return_url( http_headers: Option>, env_http_headers: Option>, scopes: &[String], + oauth_resource: Option<&str>, timeout_secs: Option, callback_port: Option, callback_url: Option<&str>, @@ -92,6 +95,7 @@ pub async fn perform_oauth_login_return_url( store_mode, headers, scopes, + oauth_resource, false, callback_port, callback_url, @@ -303,6 +307,7 @@ impl OauthLoginFlow { store_mode: OAuthCredentialsStoreMode, headers: OauthHeaders, scopes: &[String], + oauth_resource: Option<&str>, launch_browser: bool, callback_port: Option, callback_url: Option<&str>, @@ -340,7 +345,11 @@ impl OauthLoginFlow { oauth_state .start_authorization(&scope_refs, &redirect_uri, Some("Codex")) .await?; - let auth_url = oauth_state.get_authorization_url().await?; + let auth_url = append_query_param( + &oauth_state.get_authorization_url().await?, + "resource", + oauth_resource, + ); let timeout_secs = timeout_secs.unwrap_or(DEFAULT_OAUTH_TIMEOUT_SECS).max(1); let timeout = Duration::from_secs(timeout_secs as u64); @@ -431,9 +440,29 @@ impl OauthLoginFlow { } } +fn append_query_param(url: &str, key: &str, value: Option<&str>) -> String { + let Some(value) = value else { + return url.to_string(); + }; + let value = value.trim(); + if value.is_empty() { + return url.to_string(); + } + if let Ok(mut parsed) = Url::parse(url) { + parsed.query_pairs_mut().append_pair(key, value); + return parsed.to_string(); + } + let encoded = urlencoding::encode(value); + let separator = if url.contains('?') { "&" } else { "?" }; + format!("{url}{separator}{key}={encoded}") +} + #[cfg(test)] mod tests { + use pretty_assertions::assert_eq; + use super::CallbackOutcome; + use super::append_query_param; use super::callback_path_from_redirect_uri; use super::parse_oauth_callback; @@ -461,4 +490,36 @@ mod tests { .expect("redirect URI should parse"); assert_eq!(path, "/oauth/callback"); } + + #[test] + fn append_query_param_adds_resource_to_absolute_url() { + let url = append_query_param( + "https://example.com/authorize?scope=read", + "resource", + Some("https://api.example.com"), + ); + + assert_eq!( + url, + "https://example.com/authorize?scope=read&resource=https%3A%2F%2Fapi.example.com" + ); + } + + #[test] + fn append_query_param_ignores_empty_values() { + let url = append_query_param( + "https://example.com/authorize?scope=read", + "resource", + Some(" "), + ); + + assert_eq!(url, "https://example.com/authorize?scope=read"); + } + + #[test] + fn append_query_param_handles_unparseable_url() { + let url = append_query_param("not a url", "resource", Some("api/resource")); + + assert_eq!(url, "not a url?resource=api%2Fresource"); + } } diff --git a/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs b/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs index 33b12bea60..9e4bfe16a8 100644 --- a/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs +++ b/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs @@ -1,4 +1,5 @@ use crate::bash::parse_shell_lc_plain_commands; +use std::path::Path; #[cfg(windows)] #[path = "windows_dangerous_commands.rs"] mod windows_dangerous_commands; @@ -52,6 +53,32 @@ fn is_git_global_option_with_inline_value(arg: &str) -> bool { ) || ((arg.starts_with("-C") || arg.starts_with("-c")) && arg.len() > 2) } +pub(crate) fn executable_name_lookup_key(raw: &str) -> Option { + #[cfg(windows)] + { + Path::new(raw) + .file_name() + .and_then(|name| name.to_str()) + .map(|name| { + let name = name.to_ascii_lowercase(); + for suffix in [".exe", ".cmd", ".bat", ".com"] { + if let Some(stripped) = name.strip_suffix(suffix) { + return stripped.to_string(); + } + } + name + }) + } + + #[cfg(not(windows))] + { + Path::new(raw) + .file_name() + .and_then(|name| name.to_str()) + .map(std::borrow::ToOwned::to_owned) + } +} + /// Find the first matching git subcommand, skipping known global options that /// may appear before it (e.g., `-C`, `-c`, `--git-dir`). /// @@ -61,7 +88,7 @@ pub(crate) fn find_git_subcommand<'a>( subcommands: &[&str], ) -> Option<(usize, &'a str)> { let cmd0 = command.first().map(String::as_str)?; - if !cmd0.ends_with("git") { + if executable_name_lookup_key(cmd0).as_deref() != Some("git") { return None; } 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 e52079c74b..b7349f220a 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 @@ -1,4 +1,5 @@ use crate::bash::parse_shell_lc_plain_commands; +use crate::command_safety::is_dangerous_command::executable_name_lookup_key; // Find the first matching git subcommand, skipping known global options that // may appear before it (e.g., `-C`, `-c`, `--git-dir`). // Implemented in `is_dangerous_command` and shared here. @@ -47,10 +48,7 @@ fn is_safe_to_call_with_exec(command: &[String]) -> bool { return false; }; - match std::path::Path::new(&cmd0) - .file_name() - .and_then(|osstr| osstr.to_str()) - { + match executable_name_lookup_key(cmd0).as_deref() { Some(cmd) if cfg!(target_os = "linux") && matches!(cmd, "numfmt" | "tac") => true, #[rustfmt::skip] @@ -495,6 +493,18 @@ mod tests { ]))); } + #[test] + fn windows_git_full_path_is_safe() { + if !cfg!(windows) { + return; + } + + assert!(is_known_safe_command(&vec_str(&[ + r"C:\Program Files\Git\cmd\git.exe", + "status", + ]))); + } + #[test] fn bash_lc_safe_examples() { assert!(is_known_safe_command(&vec_str(&["bash", "-lc", "ls"]))); diff --git a/codex-rs/shell-command/src/parse_command.rs b/codex-rs/shell-command/src/parse_command.rs index 71018a53d1..1c8ac99485 100644 --- a/codex-rs/shell-command/src/parse_command.rs +++ b/codex-rs/shell-command/src/parse_command.rs @@ -37,7 +37,26 @@ pub fn parse_command(command: &[String]) -> Vec { } deduped.push(cmd); } - deduped + if deduped + .iter() + .any(|cmd| matches!(cmd, ParsedCommand::Unknown { .. })) + { + vec![single_unknown_for_command(command)] + } else { + deduped + } +} + +fn single_unknown_for_command(command: &[String]) -> ParsedCommand { + if let Some((_, shell_command)) = extract_shell_command(command) { + ParsedCommand::Unknown { + cmd: shell_command.to_string(), + } + } else { + ParsedCommand::Unknown { + cmd: shlex_join(command), + } + } } #[cfg(test)] @@ -119,7 +138,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Unknown { - cmd: "git status".to_string(), + cmd: inner.to_string(), }], ); } @@ -141,24 +160,9 @@ mod tests { "rg --version && node -v && pnpm -v && rg --files | wc -l && rg --files | head -n 40"; assert_parsed( &vec_str(&["bash", "-lc", inner]), - vec![ - // Expect commands in left-to-right execution order - ParsedCommand::Search { - cmd: "rg --version".to_string(), - query: None, - path: None, - }, - ParsedCommand::Unknown { - cmd: "node -v".to_string(), - }, - ParsedCommand::Unknown { - cmd: "pnpm -v".to_string(), - }, - ParsedCommand::ListFiles { - cmd: "rg --files".to_string(), - path: None, - }, - ], + vec![ParsedCommand::Unknown { + cmd: inner.to_string(), + }], ); } @@ -218,16 +222,33 @@ mod tests { let inner = r#"rg -l QkBindingController presentation/src/main/java | xargs perl -pi -e 's/QkBindingController/QkController/g'"#; assert_parsed( &vec_str(&["bash", "-lc", inner]), - vec![ - ParsedCommand::Search { - cmd: "rg -l QkBindingController presentation/src/main/java".to_string(), - query: Some("QkBindingController".to_string()), - path: Some("java".to_string()), - }, - ParsedCommand::Unknown { - cmd: "xargs perl -pi -e s/QkBindingController/QkController/g".to_string(), - }, - ], + vec![ParsedCommand::Unknown { + cmd: inner.to_string(), + }], + ); + } + + #[test] + fn collapses_plain_pipeline_when_any_stage_is_unknown() { + let command = shlex_split_safe( + "rg -l QkBindingController presentation/src/main/java | xargs perl -pi -e 's/QkBindingController/QkController/g'", + ); + assert_parsed( + &command, + vec![ParsedCommand::Unknown { + cmd: shlex_join(&command), + }], + ); + } + + #[test] + fn collapses_pipeline_with_helper_when_later_stage_is_unknown() { + let command = shlex_split_safe("rg --files | nl -ba | foo"); + assert_parsed( + &command, + vec![ParsedCommand::Unknown { + cmd: shlex_join(&command), + }], ); } @@ -395,7 +416,7 @@ mod tests { assert_parsed( &shlex_split_safe("bash -lc 'cd foo && bar'"), vec![ParsedCommand::Unknown { - cmd: "bar".to_string(), + cmd: "cd foo && bar".to_string(), }], ); } @@ -922,85 +943,6 @@ mod tests { ); } - #[test] - fn trim_on_semicolon() { - assert_parsed( - &shlex_split_safe("rg foo ; echo done"), - vec![ - ParsedCommand::Search { - cmd: "rg foo".to_string(), - query: Some("foo".to_string()), - path: None, - }, - ParsedCommand::Unknown { - cmd: "echo done".to_string(), - }, - ], - ); - } - - #[test] - fn split_on_or_connector() { - // Ensure we split commands on the logical OR operator as well. - assert_parsed( - &shlex_split_safe("rg foo || echo done"), - vec![ - ParsedCommand::Search { - cmd: "rg foo".to_string(), - query: Some("foo".to_string()), - path: None, - }, - ParsedCommand::Unknown { - cmd: "echo done".to_string(), - }, - ], - ); - } - - #[test] - fn parses_mixed_sequence_with_pipes_semicolons_and_or() { - // Provided long command sequence combining sequencing, pipelines, and ORs. - let inner = "pwd; ls -la; rg --files -g '!target' | wc -l; rg -n '^\\[workspace\\]' -n Cargo.toml || true; rg -n '^\\[package\\]' -n */Cargo.toml || true; cargo --version; rustc --version; cargo clippy --workspace --all-targets --all-features -q"; - let args = vec_str(&["bash", "-lc", inner]); - - let expected = vec![ - ParsedCommand::Unknown { - cmd: "pwd".to_string(), - }, - ParsedCommand::ListFiles { - cmd: shlex_join(&shlex_split_safe("ls -la")), - path: None, - }, - ParsedCommand::ListFiles { - cmd: shlex_join(&shlex_split_safe("rg --files -g '!target'")), - path: None, - }, - ParsedCommand::Search { - cmd: shlex_join(&shlex_split_safe("rg -n '^\\[workspace\\]' -n Cargo.toml")), - query: Some("^\\[workspace\\]".to_string()), - path: Some("Cargo.toml".to_string()), - }, - ParsedCommand::Search { - cmd: shlex_join(&shlex_split_safe("rg -n '^\\[package\\]' -n */Cargo.toml")), - query: Some("^\\[package\\]".to_string()), - path: Some("Cargo.toml".to_string()), - }, - ParsedCommand::Unknown { - cmd: shlex_join(&shlex_split_safe("cargo --version")), - }, - ParsedCommand::Unknown { - cmd: shlex_join(&shlex_split_safe("rustc --version")), - }, - ParsedCommand::Unknown { - cmd: shlex_join(&shlex_split_safe( - "cargo clippy --workspace --all-targets --all-features -q", - )), - }, - ]; - - assert_parsed(&args, expected); - } - #[test] fn strips_true_in_sequence() { // `true` should be dropped from parsed sequences @@ -1926,6 +1868,7 @@ fn parse_shell_lc_commands(original: &[String]) -> Option> { }; commands.push(parsed); } + if commands.len() > 1 { commands.retain(|pc| !matches!(pc, ParsedCommand::Unknown { cmd } if cmd == "true")); // Apply the same simplifications used for non-bash parsing, e.g., drop leading `cd`. diff --git a/codex-rs/shell-escalation/Cargo.toml b/codex-rs/shell-escalation/Cargo.toml index 85075cfb51..fbc5bcd8c7 100644 --- a/codex-rs/shell-escalation/Cargo.toml +++ b/codex-rs/shell-escalation/Cargo.toml @@ -12,6 +12,7 @@ path = "src/bin/main_execve_wrapper.rs" anyhow = { workspace = true } async-trait = { workspace = true } clap = { workspace = true, features = ["derive"] } +codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } libc = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/codex-rs/shell-escalation/README.md b/codex-rs/shell-escalation/README.md index 38c79d8349..cea59601f8 100644 --- a/codex-rs/shell-escalation/README.md +++ b/codex-rs/shell-escalation/README.md @@ -20,7 +20,7 @@ decision to the shell-escalation protocol over a shared file descriptor (specifi We carry a small patch to `execute_cmd.c` (see `patches/bash-exec-wrapper.patch`) that adds support for `EXEC_WRAPPER`. The original commit message is “add support for BASH_EXEC_WRAPPER” and the patch applies cleanly to `a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b` from https://github.com/bminor/bash. To rebuild manually: ```bash -git clone https://github.com/bminor/bash +git clone https://git.savannah.gnu.org/git/bash git checkout a8a1c2fac029404d3f42cd39f5a20f24b6e4fe4b git apply /path/to/patches/bash-exec-wrapper.patch ./configure --without-bash-malloc diff --git a/codex-rs/shell-escalation/src/lib.rs b/codex-rs/shell-escalation/src/lib.rs index 48bc116581..1cc42a46db 100644 --- a/codex-rs/shell-escalation/src/lib.rs +++ b/codex-rs/shell-escalation/src/lib.rs @@ -6,12 +6,22 @@ pub use unix::EscalateAction; #[cfg(unix)] pub use unix::EscalateServer; #[cfg(unix)] +pub use unix::EscalationDecision; +#[cfg(unix)] +pub use unix::EscalationExecution; +#[cfg(unix)] +pub use unix::EscalationPermissions; +#[cfg(unix)] pub use unix::EscalationPolicy; #[cfg(unix)] pub use unix::ExecParams; #[cfg(unix)] pub use unix::ExecResult; #[cfg(unix)] +pub use unix::Permissions; +#[cfg(unix)] +pub use unix::PreparedExec; +#[cfg(unix)] pub use unix::ShellCommandExecutor; #[cfg(unix)] pub use unix::Stopwatch; diff --git a/codex-rs/shell-escalation/src/unix/escalate_protocol.rs b/codex-rs/shell-escalation/src/unix/escalate_protocol.rs index 6002fdc57b..ea38c7b2a6 100644 --- a/codex-rs/shell-escalation/src/unix/escalate_protocol.rs +++ b/codex-rs/shell-escalation/src/unix/escalate_protocol.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use std::os::fd::RawFd; use std::path::PathBuf; +use codex_protocol::approvals::EscalationPermissions; use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde::Serialize; @@ -35,6 +36,38 @@ pub struct EscalateResponse { pub action: EscalateAction, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EscalationDecision { + Run, + Escalate(EscalationExecution), + Deny { reason: Option }, +} + +#[allow(clippy::large_enum_variant)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EscalationExecution { + /// Rerun the intercepted command outside any sandbox wrapper. + Unsandboxed, + /// Rerun using the turn's current sandbox configuration. + TurnDefault, + /// Rerun using an explicit sandbox configuration attached to the request. + Permissions(EscalationPermissions), +} + +impl EscalationDecision { + pub fn run() -> Self { + Self::Run + } + + pub fn escalate(execution: EscalationExecution) -> Self { + Self::Escalate(execution) + } + + pub fn deny(reason: Option) -> Self { + Self::Deny { reason } + } +} + #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub enum EscalateAction { /// The command should be run directly by the client. diff --git a/codex-rs/shell-escalation/src/unix/escalate_server.rs b/codex-rs/shell-escalation/src/unix/escalate_server.rs index 2951f584a6..bb45c3ed71 100644 --- a/codex-rs/shell-escalation/src/unix/escalate_server.rs +++ b/codex-rs/shell-escalation/src/unix/escalate_server.rs @@ -15,6 +15,8 @@ use crate::unix::escalate_protocol::EXEC_WRAPPER_ENV_VAR; use crate::unix::escalate_protocol::EscalateAction; use crate::unix::escalate_protocol::EscalateRequest; use crate::unix::escalate_protocol::EscalateResponse; +use crate::unix::escalate_protocol::EscalationDecision; +use crate::unix::escalate_protocol::EscalationExecution; use crate::unix::escalate_protocol::LEGACY_BASH_EXEC_WRAPPER_ENV_VAR; use crate::unix::escalate_protocol::SuperExecMessage; use crate::unix::escalate_protocol::SuperExecResult; @@ -37,6 +39,16 @@ pub trait ShellCommandExecutor: Send + Sync { env: HashMap, cancel_rx: CancellationToken, ) -> anyhow::Result; + + /// Prepares an escalated subcommand for execution on the server side. + async fn prepare_escalated_exec( + &self, + program: &AbsolutePathBuf, + argv: &[String], + workdir: &AbsolutePathBuf, + env: HashMap, + execution: EscalationExecution, + ) -> anyhow::Result; } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -62,6 +74,14 @@ pub struct ExecResult { pub timed_out: bool, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PreparedExec { + pub command: Vec, + pub cwd: PathBuf, + pub env: HashMap, + pub arg0: Option, +} + pub struct EscalateServer { bash_path: PathBuf, execve_wrapper: PathBuf, @@ -69,9 +89,9 @@ pub struct EscalateServer { } impl EscalateServer { - pub fn new

(bash_path: PathBuf, execve_wrapper: PathBuf, policy: P) -> Self + pub fn new(bash_path: PathBuf, execve_wrapper: PathBuf, policy: Policy) -> Self where - P: EscalationPolicy + Send + Sync + 'static, + Policy: EscalationPolicy + Send + Sync + 'static, { Self { bash_path, @@ -84,13 +104,17 @@ impl EscalateServer { &self, params: ExecParams, cancel_rx: CancellationToken, - command_executor: &dyn ShellCommandExecutor, + command_executor: Arc, ) -> anyhow::Result { let (escalate_server, escalate_client) = AsyncDatagramSocket::pair()?; let client_socket = escalate_client.into_inner(); // Only the client endpoint should cross exec into the wrapper process. client_socket.set_cloexec(false)?; - let escalate_task = tokio::spawn(escalate_task(escalate_server, self.policy.clone())); + let escalate_task = tokio::spawn(escalate_task( + escalate_server, + Arc::clone(&self.policy), + Arc::clone(&command_executor), + )); let mut env = std::env::vars().collect::>(); env.insert( ESCALATE_SOCKET_ENV_VAR.to_string(), @@ -126,6 +150,7 @@ impl EscalateServer { async fn escalate_task( socket: AsyncDatagramSocket, policy: Arc, + command_executor: Arc, ) -> anyhow::Result<()> { loop { let (_, mut fds) = socket.receive_with_fds().await?; @@ -134,9 +159,12 @@ async fn escalate_task( continue; } let stream_socket = AsyncSocket::from_fd(fds.remove(0))?; - let policy = policy.clone(); + let policy = Arc::clone(&policy); + let command_executor = Arc::clone(&command_executor); tokio::spawn(async move { - if let Err(err) = handle_escalate_session_with_policy(stream_socket, policy).await { + if let Err(err) = + handle_escalate_session_with_policy(stream_socket, policy, command_executor).await + { tracing::error!("escalate session failed: {err:?}"); } }); @@ -146,6 +174,7 @@ async fn escalate_task( async fn handle_escalate_session_with_policy( socket: AsyncSocket, policy: Arc, + command_executor: Arc, ) -> anyhow::Result<()> { let EscalateRequest { file, @@ -154,22 +183,22 @@ async fn handle_escalate_session_with_policy( env, } = socket.receive::().await?; let program = AbsolutePathBuf::resolve_path_against_base(file, workdir.as_path())?; - let action = policy + let decision = policy .determine_action(&program, &argv, &workdir) .await .context("failed to determine escalation action")?; - tracing::debug!("decided {action:?} for {program:?} {argv:?} {workdir:?}"); + tracing::debug!("decided {decision:?} for {program:?} {argv:?} {workdir:?}"); - match action { - EscalateAction::Run => { + match decision { + EscalationDecision::Run => { socket .send(EscalateResponse { action: EscalateAction::Run, }) .await?; } - EscalateAction::Escalate => { + EscalationDecision::Escalate(execution) => { socket .send(EscalateResponse { action: EscalateAction::Escalate, @@ -197,12 +226,23 @@ async fn handle_escalate_session_with_policy( )); } - let mut command = Command::new(program.as_path()); + let PreparedExec { + command, + cwd, + env, + arg0, + } = command_executor + .prepare_escalated_exec(&program, &argv, &workdir, env, execution) + .await?; + let (program, args) = command + .split_first() + .ok_or_else(|| anyhow::anyhow!("prepared escalated command must not be empty"))?; + let mut command = Command::new(program); command - .args(&argv[1..]) - .arg0(argv[0].clone()) + .args(args) + .arg0(arg0.unwrap_or_else(|| program.clone())) .envs(&env) - .current_dir(&workdir) + .current_dir(&cwd) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); @@ -222,7 +262,7 @@ async fn handle_escalate_session_with_policy( }) .await?; } - EscalateAction::Deny { reason } => { + EscalationDecision::Deny { reason } => { socket .send(EscalateResponse { action: EscalateAction::Deny { reason }, @@ -236,13 +276,15 @@ async fn handle_escalate_session_with_policy( #[cfg(test)] mod tests { use super::*; + use codex_protocol::approvals::EscalationPermissions; + use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::collections::HashMap; use std::path::PathBuf; struct DeterministicEscalationPolicy { - action: EscalateAction, + decision: EscalationDecision, } #[async_trait::async_trait] @@ -252,8 +294,8 @@ mod tests { _file: &AbsolutePathBuf, _argv: &[String], _workdir: &AbsolutePathBuf, - ) -> anyhow::Result { - Ok(self.action.clone()) + ) -> anyhow::Result { + Ok(self.decision.clone()) } } @@ -269,10 +311,82 @@ mod tests { file: &AbsolutePathBuf, _argv: &[String], workdir: &AbsolutePathBuf, - ) -> anyhow::Result { + ) -> anyhow::Result { assert_eq!(file, &self.expected_file); assert_eq!(workdir, &self.expected_workdir); - Ok(EscalateAction::Run) + Ok(EscalationDecision::run()) + } + } + + struct ForwardingShellCommandExecutor; + + #[async_trait::async_trait] + impl ShellCommandExecutor for ForwardingShellCommandExecutor { + async fn run( + &self, + _command: Vec, + _cwd: PathBuf, + _env: HashMap, + _cancel_rx: CancellationToken, + ) -> anyhow::Result { + unreachable!("run() is not used by handle_escalate_session_with_policy() tests") + } + + async fn prepare_escalated_exec( + &self, + program: &AbsolutePathBuf, + argv: &[String], + workdir: &AbsolutePathBuf, + env: HashMap, + _execution: EscalationExecution, + ) -> anyhow::Result { + Ok(PreparedExec { + command: std::iter::once(program.to_string_lossy().to_string()) + .chain(argv.iter().skip(1).cloned()) + .collect(), + cwd: workdir.to_path_buf(), + env, + arg0: argv.first().cloned(), + }) + } + } + + struct PermissionAssertingShellCommandExecutor { + expected_permissions: EscalationPermissions, + } + + #[async_trait::async_trait] + impl ShellCommandExecutor for PermissionAssertingShellCommandExecutor { + async fn run( + &self, + _command: Vec, + _cwd: PathBuf, + _env: HashMap, + _cancel_rx: CancellationToken, + ) -> anyhow::Result { + unreachable!("run() is not used by handle_escalate_session_with_policy() tests") + } + + async fn prepare_escalated_exec( + &self, + program: &AbsolutePathBuf, + argv: &[String], + workdir: &AbsolutePathBuf, + env: HashMap, + execution: EscalationExecution, + ) -> anyhow::Result { + assert_eq!( + execution, + EscalationExecution::Permissions(self.expected_permissions.clone()) + ); + Ok(PreparedExec { + command: std::iter::once(program.to_string_lossy().to_string()) + .chain(argv.iter().skip(1).cloned()) + .collect(), + cwd: workdir.to_path_buf(), + env, + arg0: argv.first().cloned(), + }) } } @@ -282,8 +396,9 @@ mod tests { let server_task = tokio::spawn(handle_escalate_session_with_policy( server, Arc::new(DeterministicEscalationPolicy { - action: EscalateAction::Run, + decision: EscalationDecision::run(), }), + Arc::new(ForwardingShellCommandExecutor), )); let mut env = HashMap::new(); @@ -326,6 +441,7 @@ mod tests { expected_file, expected_workdir: workdir.clone(), }), + Arc::new(ForwardingShellCommandExecutor), )); client @@ -353,8 +469,9 @@ mod tests { let server_task = tokio::spawn(handle_escalate_session_with_policy( server, Arc::new(DeterministicEscalationPolicy { - action: EscalateAction::Escalate, + decision: EscalationDecision::escalate(EscalationExecution::Unsandboxed), }), + Arc::new(ForwardingShellCommandExecutor), )); client @@ -387,4 +504,52 @@ mod tests { server_task.await? } + + #[tokio::test] + async fn handle_escalate_session_passes_permissions_to_executor() -> anyhow::Result<()> { + let (server, client) = AsyncSocket::pair()?; + let server_task = tokio::spawn(handle_escalate_session_with_policy( + server, + Arc::new(DeterministicEscalationPolicy { + decision: EscalationDecision::escalate(EscalationExecution::Permissions( + EscalationPermissions::PermissionProfile(PermissionProfile { + network: Some(true), + ..Default::default() + }), + )), + }), + Arc::new(PermissionAssertingShellCommandExecutor { + expected_permissions: EscalationPermissions::PermissionProfile(PermissionProfile { + network: Some(true), + ..Default::default() + }), + }), + )); + + client + .send(EscalateRequest { + file: PathBuf::from("/bin/sh"), + argv: vec!["sh".to_string(), "-c".to_string(), "exit 0".to_string()], + workdir: AbsolutePathBuf::current_dir()?, + env: HashMap::new(), + }) + .await?; + + let response = client.receive::().await?; + assert_eq!( + EscalateResponse { + action: EscalateAction::Escalate, + }, + response + ); + + client + .send_with_fds(SuperExecMessage { fds: Vec::new() }, &[]) + .await?; + + let result = client.receive::().await?; + assert_eq!(0, result.exit_code); + + server_task.await? + } } diff --git a/codex-rs/shell-escalation/src/unix/escalation_policy.rs b/codex-rs/shell-escalation/src/unix/escalation_policy.rs index 28e04e6f59..c3da252dd9 100644 --- a/codex-rs/shell-escalation/src/unix/escalation_policy.rs +++ b/codex-rs/shell-escalation/src/unix/escalation_policy.rs @@ -1,6 +1,6 @@ use codex_utils_absolute_path::AbsolutePathBuf; -use crate::unix::escalate_protocol::EscalateAction; +use crate::unix::escalate_protocol::EscalationDecision; /// Decides what action to take in response to an execve request from a client. #[async_trait::async_trait] @@ -10,5 +10,5 @@ pub trait EscalationPolicy: Send + Sync { file: &AbsolutePathBuf, argv: &[String], workdir: &AbsolutePathBuf, - ) -> anyhow::Result; + ) -> anyhow::Result; } diff --git a/codex-rs/shell-escalation/src/unix/mod.rs b/codex-rs/shell-escalation/src/unix/mod.rs index 37e29e8775..6de12297a4 100644 --- a/codex-rs/shell-escalation/src/unix/mod.rs +++ b/codex-rs/shell-escalation/src/unix/mod.rs @@ -63,10 +63,15 @@ pub mod stopwatch; pub use self::escalate_client::run_shell_escalation_execve_wrapper; pub use self::escalate_protocol::EscalateAction; +pub use self::escalate_protocol::EscalationDecision; +pub use self::escalate_protocol::EscalationExecution; pub use self::escalate_server::EscalateServer; pub use self::escalate_server::ExecParams; pub use self::escalate_server::ExecResult; +pub use self::escalate_server::PreparedExec; pub use self::escalate_server::ShellCommandExecutor; pub use self::escalation_policy::EscalationPolicy; pub use self::execve_wrapper::main_execve_wrapper; pub use self::stopwatch::Stopwatch; +pub use codex_protocol::approvals::EscalationPermissions; +pub use codex_protocol::approvals::Permissions; diff --git a/codex-rs/state/migrations/0018_phase2_selection_snapshot.sql b/codex-rs/state/migrations/0018_phase2_selection_snapshot.sql new file mode 100644 index 0000000000..f175980fc7 --- /dev/null +++ b/codex-rs/state/migrations/0018_phase2_selection_snapshot.sql @@ -0,0 +1,3 @@ +ALTER TABLE stage1_outputs +ADD COLUMN selected_for_phase2_source_updated_at INTEGER; +ALTER TABLE threads ADD COLUMN memory_mode TEXT NOT NULL DEFAULT 'enabled'; diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 0ba3df6790..54ef7ea662 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -56,7 +56,9 @@ fn apply_session_meta_from_item(metadata: &mut ThreadMetadata, meta_line: &Sessi } fn apply_turn_context(metadata: &mut ThreadMetadata, turn_ctx: &TurnContextItem) { - metadata.cwd = turn_ctx.cwd.clone(); + if metadata.cwd.as_os_str().is_empty() { + metadata.cwd = turn_ctx.cwd.clone(); + } metadata.sandbox_policy = enum_to_string(&turn_ctx.sandbox_policy); metadata.approval_mode = enum_to_string(&turn_ctx.approval_policy); } @@ -125,10 +127,17 @@ mod tests { use chrono::DateTime; use chrono::Utc; use codex_protocol::ThreadId; + use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; + use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; + use codex_protocol::protocol::SandboxPolicy; + use codex_protocol::protocol::SessionMeta; + use codex_protocol::protocol::SessionMetaLine; + use codex_protocol::protocol::SessionSource; + use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::USER_MESSAGE_BEGIN; use codex_protocol::protocol::UserMessageEvent; @@ -209,6 +218,100 @@ mod tests { assert_eq!(metadata.title, ""); } + #[test] + fn turn_context_does_not_override_session_cwd() { + let mut metadata = metadata_for_test(); + metadata.cwd = PathBuf::new(); + let thread_id = metadata.id; + + apply_rollout_item( + &mut metadata, + &RolloutItem::SessionMeta(SessionMetaLine { + meta: SessionMeta { + id: thread_id, + forked_from_id: Some( + ThreadId::from_string(&Uuid::now_v7().to_string()).expect("thread id"), + ), + timestamp: "2026-02-26T00:00:00.000Z".to_string(), + cwd: PathBuf::from("/child/worktree"), + originator: "codex_cli_rs".to_string(), + cli_version: "0.0.0".to_string(), + source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, + model_provider: Some("openai".to_string()), + base_instructions: None, + dynamic_tools: None, + memory_mode: None, + }, + git: None, + }), + "test-provider", + ); + apply_rollout_item( + &mut metadata, + &RolloutItem::TurnContext(TurnContextItem { + turn_id: Some("turn-1".to_string()), + cwd: PathBuf::from("/parent/workspace"), + current_date: None, + timezone: None, + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + network: None, + model: "gpt-5".to_string(), + personality: None, + collaboration_mode: None, + realtime_active: None, + effort: None, + summary: ReasoningSummary::Auto, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: None, + }), + "test-provider", + ); + + assert_eq!(metadata.cwd, PathBuf::from("/child/worktree")); + assert_eq!( + metadata.sandbox_policy, + super::enum_to_string(&SandboxPolicy::DangerFullAccess) + ); + assert_eq!(metadata.approval_mode, "never"); + } + + #[test] + fn turn_context_sets_cwd_when_session_cwd_missing() { + let mut metadata = metadata_for_test(); + metadata.cwd = PathBuf::new(); + + apply_rollout_item( + &mut metadata, + &RolloutItem::TurnContext(TurnContextItem { + turn_id: Some("turn-1".to_string()), + cwd: PathBuf::from("/fallback/workspace"), + current_date: None, + timezone: None, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + network: None, + model: "gpt-5".to_string(), + personality: None, + collaboration_mode: None, + realtime_active: None, + effort: None, + summary: ReasoningSummary::Auto, + user_instructions: None, + developer_instructions: None, + final_output_json_schema: None, + truncation_policy: None, + }), + "test-provider", + ); + + assert_eq!(metadata.cwd, PathBuf::from("/fallback/workspace")); + } + fn metadata_for_test() -> ThreadMetadata { let id = ThreadId::from_string(&Uuid::from_u128(42).to_string()).expect("thread id"); let created_at = DateTime::::from_timestamp(1_735_689_600, 0).expect("timestamp"); diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs index 59607f3d9b..a6d1deeb84 100644 --- a/codex-rs/state/src/lib.rs +++ b/codex-rs/state/src/lib.rs @@ -14,6 +14,7 @@ mod runtime; pub use model::LogEntry; pub use model::LogQuery; pub use model::LogRow; +pub use model::Phase2InputSelection; pub use model::Phase2JobClaimOutcome; /// Preferred entrypoint: owns configuration and metrics. pub use runtime::StateRuntime; @@ -38,6 +39,7 @@ pub use model::SortKey; pub use model::Stage1JobClaim; pub use model::Stage1JobClaimOutcome; pub use model::Stage1Output; +pub use model::Stage1OutputRef; pub use model::Stage1StartupClaimParams; pub use model::ThreadMetadata; pub use model::ThreadMetadataBuilder; diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index 64deeef2ad..e646828bda 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -26,6 +26,7 @@ use std::time::SystemTime; use std::time::UNIX_EPOCH; use tokio::sync::mpsc; +use tokio::sync::oneshot; use tracing::Event; use tracing::field::Field; use tracing::field::Visit; @@ -45,7 +46,7 @@ const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(250); const LOG_RETENTION_DAYS: i64 = 90; pub struct LogDbLayer { - sender: mpsc::Sender, + sender: mpsc::Sender, process_uuid: String, } @@ -61,6 +62,24 @@ pub fn start(state_db: std::sync::Arc) -> LogDbLayer { } } +impl Clone for LogDbLayer { + fn clone(&self) -> Self { + Self { + sender: self.sender.clone(), + process_uuid: self.process_uuid.clone(), + } + } +} + +impl LogDbLayer { + pub async fn flush(&self) { + let (tx, rx) = oneshot::channel(); + if self.sender.send(LogDbCommand::Flush(tx)).await.is_ok() { + let _ = rx.await; + } + } +} + impl Layer for LogDbLayer where S: tracing::Subscriber + for<'a> LookupSpan<'a>, @@ -131,10 +150,15 @@ where line: metadata.line().map(|line| line as i64), }; - let _ = self.sender.try_send(entry); + let _ = self.sender.try_send(LogDbCommand::Entry(entry)); } } +enum LogDbCommand { + Entry(LogEntry), + Flush(oneshot::Sender<()>), +} + #[derive(Clone, Debug, Default)] struct SpanLogContext { thread_id: Option, @@ -215,20 +239,24 @@ fn current_process_log_uuid() -> &'static str { async fn run_inserter( state_db: std::sync::Arc, - mut receiver: mpsc::Receiver, + mut receiver: mpsc::Receiver, ) { let mut buffer = Vec::with_capacity(LOG_BATCH_SIZE); let mut ticker = tokio::time::interval(LOG_FLUSH_INTERVAL); loop { tokio::select! { - maybe_entry = receiver.recv() => { - match maybe_entry { - Some(entry) => { + maybe_command = receiver.recv() => { + match maybe_command { + Some(LogDbCommand::Entry(entry)) => { buffer.push(entry); if buffer.len() >= LOG_BATCH_SIZE { flush(&state_db, &mut buffer).await; } } + Some(LogDbCommand::Flush(reply)) => { + flush(&state_db, &mut buffer).await; + let _ = reply.send(()); + } None => { flush(&state_db, &mut buffer).await; break; @@ -304,3 +332,150 @@ impl Visit for MessageVisitor { self.record_field(field, format!("{value:?}")); } } + +#[cfg(test)] +mod tests { + use std::io; + use std::sync::Arc; + use std::sync::Mutex; + use std::time::Duration; + + use tokio::time::Instant; + use tracing_subscriber::filter::Targets; + use tracing_subscriber::fmt::writer::MakeWriter; + use tracing_subscriber::layer::SubscriberExt; + use tracing_subscriber::util::SubscriberInitExt; + + use super::*; + + #[derive(Clone, Default)] + struct SharedWriter { + bytes: Arc>>, + } + + impl SharedWriter { + fn snapshot(&self) -> String { + String::from_utf8(self.bytes.lock().expect("writer mutex poisoned").clone()) + .expect("valid utf-8") + } + } + + struct SharedWriterGuard { + bytes: Arc>>, + } + + impl<'a> MakeWriter<'a> for SharedWriter { + type Writer = SharedWriterGuard; + + fn make_writer(&'a self) -> Self::Writer { + SharedWriterGuard { + bytes: Arc::clone(&self.bytes), + } + } + } + + impl io::Write for SharedWriterGuard { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.bytes + .lock() + .expect("writer mutex poisoned") + .extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + #[tokio::test] + async fn sqlite_feedback_logs_match_feedback_formatter_shape() { + let codex_home = + std::env::temp_dir().join(format!("codex-state-log-db-{}", Uuid::new_v4())); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let writer = SharedWriter::default(); + + let subscriber = tracing_subscriber::registry() + .with( + tracing_subscriber::fmt::layer() + .with_writer(writer.clone()) + .without_time() + .with_ansi(false) + .with_target(false) + .with_filter(Targets::new().with_default(tracing::Level::TRACE)), + ) + .with( + start(runtime.clone()) + .with_filter(Targets::new().with_default(tracing::Level::TRACE)), + ); + let guard = subscriber.set_default(); + + tracing::trace!("threadless-before"); + tracing::info_span!("feedback-thread", thread_id = "thread-1").in_scope(|| { + tracing::info!("thread-scoped"); + }); + tracing::debug!("threadless-after"); + + drop(guard); + + // TODO(ccunningham): Store enough span metadata in SQLite to reproduce span + // prefixes like `feedback-thread{thread_id="thread-1"}:` in feedback exports. + let feedback_logs = writer + .snapshot() + .replace("feedback-thread{thread_id=\"thread-1\"}: ", ""); + let deadline = Instant::now() + Duration::from_secs(2); + loop { + let sqlite_logs = String::from_utf8( + runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"), + ) + .expect("valid utf-8"); + if sqlite_logs == feedback_logs { + break; + } + assert!( + Instant::now() < deadline, + "sqlite feedback logs did not match feedback formatter output before timeout\nsqlite:\n{sqlite_logs}\nfeedback:\n{feedback_logs}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn flush_persists_logs_for_query() { + let codex_home = + std::env::temp_dir().join(format!("codex-state-log-db-{}", Uuid::new_v4())); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let layer = start(runtime.clone()); + + let guard = tracing_subscriber::registry() + .with( + layer + .clone() + .with_filter(Targets::new().with_default(tracing::Level::TRACE)), + ) + .set_default(); + + tracing::info!("buffered-log"); + + layer.flush().await; + drop(guard); + + let after_flush = runtime + .query_logs(&crate::LogQuery::default()) + .await + .expect("query logs after flush"); + assert_eq!(after_flush.len(), 1); + assert_eq!(after_flush[0].message.as_deref(), Some("buffered-log")); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } +} diff --git a/codex-rs/state/src/model/memories.rs b/codex-rs/state/src/model/memories.rs index 813c999395..0e663bf904 100644 --- a/codex-rs/state/src/model/memories.rs +++ b/codex-rs/state/src/model/memories.rs @@ -12,22 +12,41 @@ use super::ThreadMetadata; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stage1Output { pub thread_id: ThreadId, + pub rollout_path: PathBuf, pub source_updated_at: DateTime, pub raw_memory: String, pub rollout_summary: String, pub rollout_slug: Option, pub cwd: PathBuf, + pub git_branch: Option, pub generated_at: DateTime, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stage1OutputRef { + pub thread_id: ThreadId, + pub source_updated_at: DateTime, + pub rollout_slug: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Phase2InputSelection { + pub selected: Vec, + pub previous_selected: Vec, + pub retained_thread_ids: Vec, + pub removed: Vec, +} + #[derive(Debug)] pub(crate) struct Stage1OutputRow { thread_id: String, + rollout_path: String, source_updated_at: i64, raw_memory: String, rollout_summary: String, rollout_slug: Option, cwd: String, + git_branch: Option, generated_at: i64, } @@ -35,11 +54,13 @@ impl Stage1OutputRow { pub(crate) fn try_from_row(row: &SqliteRow) -> Result { Ok(Self { thread_id: row.try_get("thread_id")?, + rollout_path: row.try_get("rollout_path")?, source_updated_at: row.try_get("source_updated_at")?, raw_memory: row.try_get("raw_memory")?, rollout_summary: row.try_get("rollout_summary")?, rollout_slug: row.try_get("rollout_slug")?, cwd: row.try_get("cwd")?, + git_branch: row.try_get("git_branch")?, generated_at: row.try_get("generated_at")?, }) } @@ -51,11 +72,13 @@ impl TryFrom for Stage1Output { fn try_from(row: Stage1OutputRow) -> std::result::Result { Ok(Self { thread_id: ThreadId::try_from(row.thread_id)?, + rollout_path: PathBuf::from(row.rollout_path), source_updated_at: epoch_seconds_to_datetime(row.source_updated_at)?, raw_memory: row.raw_memory, rollout_summary: row.rollout_summary, rollout_slug: row.rollout_slug, cwd: PathBuf::from(row.cwd), + git_branch: row.git_branch, generated_at: epoch_seconds_to_datetime(row.generated_at)?, }) } @@ -66,6 +89,18 @@ fn epoch_seconds_to_datetime(secs: i64) -> Result> { .ok_or_else(|| anyhow::anyhow!("invalid unix timestamp: {secs}")) } +pub(crate) fn stage1_output_ref_from_parts( + thread_id: String, + source_updated_at: i64, + rollout_slug: Option, +) -> Result { + Ok(Stage1OutputRef { + thread_id: ThreadId::try_from(thread_id)?, + source_updated_at: epoch_seconds_to_datetime(source_updated_at)?, + rollout_slug, + }) +} + /// Result of trying to claim a stage-1 memory extraction job. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Stage1JobClaimOutcome { diff --git a/codex-rs/state/src/model/mod.rs b/codex-rs/state/src/model/mod.rs index 816c036f8b..efaf3f787e 100644 --- a/codex-rs/state/src/model/mod.rs +++ b/codex-rs/state/src/model/mod.rs @@ -16,10 +16,12 @@ pub use backfill_state::BackfillStatus; pub use log::LogEntry; pub use log::LogQuery; pub use log::LogRow; +pub use memories::Phase2InputSelection; pub use memories::Phase2JobClaimOutcome; pub use memories::Stage1JobClaim; pub use memories::Stage1JobClaimOutcome; pub use memories::Stage1Output; +pub use memories::Stage1OutputRef; pub use memories::Stage1StartupClaimParams; pub use thread_metadata::Anchor; pub use thread_metadata::BackfillStats; @@ -32,6 +34,7 @@ pub use thread_metadata::ThreadsPage; pub(crate) use agent_job::AgentJobItemRow; pub(crate) use agent_job::AgentJobRow; pub(crate) use memories::Stage1OutputRow; +pub(crate) use memories::stage1_output_ref_from_parts; pub(crate) use thread_metadata::ThreadRow; pub(crate) use thread_metadata::anchor_from_item; pub(crate) use thread_metadata::datetime_to_epoch_seconds; diff --git a/codex-rs/state/src/model/thread_metadata.rs b/codex-rs/state/src/model/thread_metadata.rs index 9533b8fede..9616268012 100644 --- a/codex-rs/state/src/model/thread_metadata.rs +++ b/codex-rs/state/src/model/thread_metadata.rs @@ -45,6 +45,8 @@ pub struct ThreadsPage { pub struct ExtractionOutcome { /// The extracted thread metadata. pub metadata: ThreadMetadata, + /// The explicit thread memory mode from rollout metadata, if present. + pub memory_mode: Option, /// The number of rollout lines that failed to parse. pub parse_errors: usize, } diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index f0c6230508..42d235fc76 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -18,7 +18,6 @@ use crate::ThreadMetadataBuilder; use crate::ThreadsPage; use crate::apply_rollout_item; use crate::migrations::MIGRATOR; -use crate::model::AgentJobItemRow; use crate::model::AgentJobRow; use crate::model::ThreadRow; use crate::model::anchor_from_item; @@ -48,10 +47,14 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use tracing::warn; -use uuid::Uuid; +mod agent_jobs; +mod backfill; +mod logs; mod memories; -// Memory-specific CRUD and phase job lifecycle methods live in `runtime/memories.rs`. +#[cfg(test)] +mod test_support; +mod threads; // "Partition" is the retention bucket we cap at 10 MiB: // - one bucket per non-null thread_id @@ -107,1461 +110,6 @@ impl StateRuntime { pub fn codex_home(&self) -> &Path { self.codex_home.as_path() } - - /// Get persisted rollout metadata backfill state. - pub async fn get_backfill_state(&self) -> anyhow::Result { - self.ensure_backfill_state_row().await?; - let row = sqlx::query( - r#" -SELECT status, last_watermark, last_success_at -FROM backfill_state -WHERE id = 1 - "#, - ) - .fetch_one(self.pool.as_ref()) - .await?; - crate::BackfillState::try_from_row(&row) - } - - /// Attempt to claim ownership of rollout metadata backfill. - /// - /// Returns `true` when this runtime claimed the backfill worker slot. - /// Returns `false` if backfill is already complete or currently owned by a - /// non-expired worker. - pub async fn try_claim_backfill(&self, lease_seconds: i64) -> anyhow::Result { - self.ensure_backfill_state_row().await?; - let now = Utc::now().timestamp(); - let lease_cutoff = now.saturating_sub(lease_seconds.max(0)); - let result = sqlx::query( - r#" -UPDATE backfill_state -SET status = ?, updated_at = ? -WHERE id = 1 - AND status != ? - AND (status != ? OR updated_at <= ?) - "#, - ) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(now) - .bind(crate::BackfillStatus::Complete.as_str()) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(lease_cutoff) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() == 1) - } - - /// Mark rollout metadata backfill as running. - pub async fn mark_backfill_running(&self) -> anyhow::Result<()> { - self.ensure_backfill_state_row().await?; - sqlx::query( - r#" -UPDATE backfill_state -SET status = ?, updated_at = ? -WHERE id = 1 - "#, - ) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(Utc::now().timestamp()) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } - - /// Persist rollout metadata backfill progress. - pub async fn checkpoint_backfill(&self, watermark: &str) -> anyhow::Result<()> { - self.ensure_backfill_state_row().await?; - sqlx::query( - r#" -UPDATE backfill_state -SET status = ?, last_watermark = ?, updated_at = ? -WHERE id = 1 - "#, - ) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(watermark) - .bind(Utc::now().timestamp()) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } - - /// Mark rollout metadata backfill as complete. - pub async fn mark_backfill_complete(&self, last_watermark: Option<&str>) -> anyhow::Result<()> { - self.ensure_backfill_state_row().await?; - let now = Utc::now().timestamp(); - sqlx::query( - r#" -UPDATE backfill_state -SET - status = ?, - last_watermark = COALESCE(?, last_watermark), - last_success_at = ?, - updated_at = ? -WHERE id = 1 - "#, - ) - .bind(crate::BackfillStatus::Complete.as_str()) - .bind(last_watermark) - .bind(now) - .bind(now) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } - - /// Load thread metadata by id using the underlying database. - pub async fn get_thread(&self, id: ThreadId) -> anyhow::Result> { - let row = sqlx::query( - r#" -SELECT - id, - rollout_path, - created_at, - updated_at, - source, - agent_nickname, - agent_role, - model_provider, - cwd, - cli_version, - title, - sandbox_policy, - approval_mode, - tokens_used, - first_user_message, - archived_at, - git_sha, - git_branch, - git_origin_url -FROM threads -WHERE id = ? - "#, - ) - .bind(id.to_string()) - .fetch_optional(self.pool.as_ref()) - .await?; - row.map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) - .transpose() - } - - /// 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 name, description, input_schema -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 { - name: row.try_get("name")?, - description: row.try_get("description")?, - input_schema, - }); - } - Ok(Some(tools)) - } - - /// Find a rollout path by thread id using the underlying database. - pub async fn find_rollout_path_by_id( - &self, - id: ThreadId, - archived_only: Option, - ) -> anyhow::Result> { - let mut builder = - QueryBuilder::::new("SELECT rollout_path FROM threads WHERE id = "); - builder.push_bind(id.to_string()); - match archived_only { - Some(true) => { - builder.push(" AND archived = 1"); - } - Some(false) => { - builder.push(" AND archived = 0"); - } - None => {} - } - let row = builder.build().fetch_optional(self.pool.as_ref()).await?; - Ok(row - .and_then(|r| r.try_get::("rollout_path").ok()) - .map(PathBuf::from)) - } - - /// List threads using the underlying database. - #[allow(clippy::too_many_arguments)] - pub async fn list_threads( - &self, - page_size: usize, - anchor: Option<&crate::Anchor>, - sort_key: crate::SortKey, - allowed_sources: &[String], - model_providers: Option<&[String]>, - archived_only: bool, - search_term: Option<&str>, - ) -> anyhow::Result { - let limit = page_size.saturating_add(1); - - let mut builder = QueryBuilder::::new( - r#" -SELECT - id, - rollout_path, - created_at, - updated_at, - source, - agent_nickname, - agent_role, - model_provider, - cwd, - cli_version, - title, - sandbox_policy, - approval_mode, - tokens_used, - first_user_message, - archived_at, - git_sha, - git_branch, - git_origin_url -FROM threads - "#, - ); - push_thread_filters( - &mut builder, - archived_only, - allowed_sources, - model_providers, - anchor, - sort_key, - search_term, - ); - push_thread_order_and_limit(&mut builder, sort_key, limit); - - let rows = builder.build().fetch_all(self.pool.as_ref()).await?; - let mut items = rows - .into_iter() - .map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) - .collect::, _>>()?; - let num_scanned_rows = items.len(); - let next_anchor = if items.len() > page_size { - items.pop(); - items - .last() - .and_then(|item| anchor_from_item(item, sort_key)) - } else { - None - }; - Ok(ThreadsPage { - items, - next_anchor, - num_scanned_rows, - }) - } - - /// Insert one log entry into the logs table. - pub async fn insert_log(&self, entry: &LogEntry) -> anyhow::Result<()> { - self.insert_logs(std::slice::from_ref(entry)).await - } - - /// Insert a batch of log entries into the logs table. - pub async fn insert_logs(&self, entries: &[LogEntry]) -> anyhow::Result<()> { - if entries.is_empty() { - return Ok(()); - } - - let mut tx = self.pool.begin().await?; - let mut builder = QueryBuilder::::new( - "INSERT INTO logs (ts, ts_nanos, level, target, message, thread_id, process_uuid, module_path, file, line, estimated_bytes) ", - ); - builder.push_values(entries, |mut row, entry| { - let estimated_bytes = entry.message.as_ref().map_or(0, String::len) as i64 - + entry.level.len() as i64 - + entry.target.len() as i64 - + entry.module_path.as_ref().map_or(0, String::len) as i64 - + entry.file.as_ref().map_or(0, String::len) as i64; - row.push_bind(entry.ts) - .push_bind(entry.ts_nanos) - .push_bind(&entry.level) - .push_bind(&entry.target) - .push_bind(&entry.message) - .push_bind(&entry.thread_id) - .push_bind(&entry.process_uuid) - .push_bind(&entry.module_path) - .push_bind(&entry.file) - .push_bind(entry.line) - .push_bind(estimated_bytes); - }); - builder.build().execute(&mut *tx).await?; - self.prune_logs_after_insert(entries, &mut tx).await?; - tx.commit().await?; - Ok(()) - } - - /// Enforce per-partition log size caps after a successful batch insert. - /// - /// We maintain two independent budgets: - /// - Thread logs: rows with `thread_id IS NOT NULL`, capped per `thread_id`. - /// - Threadless process logs: rows with `thread_id IS NULL` ("threadless"), - /// capped per `process_uuid` (including `process_uuid IS NULL` as its own - /// threadless partition). - /// - /// "Threadless" means the log row is not associated with any conversation - /// thread, so retention is keyed by process identity instead. - /// - /// This runs inside the same transaction as the insert so callers never - /// observe "inserted but not yet pruned" rows. - async fn prune_logs_after_insert( - &self, - entries: &[LogEntry], - tx: &mut SqliteConnection, - ) -> anyhow::Result<()> { - let thread_ids: BTreeSet<&str> = entries - .iter() - .filter_map(|entry| entry.thread_id.as_deref()) - .collect(); - if !thread_ids.is_empty() { - // Cheap precheck: only run the heavier window-function prune for - // threads that are currently above the cap. - let mut over_limit_threads_query = - QueryBuilder::::new("SELECT thread_id FROM logs WHERE thread_id IN ("); - { - let mut separated = over_limit_threads_query.separated(", "); - for thread_id in &thread_ids { - separated.push_bind(*thread_id); - } - } - over_limit_threads_query.push(") GROUP BY thread_id HAVING SUM("); - over_limit_threads_query.push("estimated_bytes"); - over_limit_threads_query.push(") > "); - over_limit_threads_query.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); - let over_limit_thread_ids: Vec = over_limit_threads_query - .build() - .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| row.try_get("thread_id")) - .collect::>()?; - if !over_limit_thread_ids.is_empty() { - // Enforce a strict per-thread cap by deleting every row whose - // newest-first cumulative bytes exceed the partition budget. - let mut prune_threads = QueryBuilder::::new( - r#" -DELETE FROM logs -WHERE id IN ( - SELECT id - FROM ( - SELECT - id, - SUM( -"#, - ); - prune_threads.push("estimated_bytes"); - prune_threads.push( - r#" - ) OVER ( - PARTITION BY thread_id - ORDER BY ts DESC, ts_nanos DESC, id DESC - ) AS cumulative_bytes - FROM logs - WHERE thread_id IN ( -"#, - ); - { - let mut separated = prune_threads.separated(", "); - for thread_id in &over_limit_thread_ids { - separated.push_bind(thread_id); - } - } - prune_threads.push( - r#" - ) - ) - WHERE cumulative_bytes > -"#, - ); - prune_threads.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); - prune_threads.push("\n)"); - prune_threads.build().execute(&mut *tx).await?; - } - } - - let threadless_process_uuids: BTreeSet<&str> = entries - .iter() - .filter(|entry| entry.thread_id.is_none()) - .filter_map(|entry| entry.process_uuid.as_deref()) - .collect(); - let has_threadless_null_process_uuid = entries - .iter() - .any(|entry| entry.thread_id.is_none() && entry.process_uuid.is_none()); - if !threadless_process_uuids.is_empty() { - // Threadless logs are budgeted separately per process UUID. - let mut over_limit_processes_query = QueryBuilder::::new( - "SELECT process_uuid FROM logs WHERE thread_id IS NULL AND process_uuid IN (", - ); - { - let mut separated = over_limit_processes_query.separated(", "); - for process_uuid in &threadless_process_uuids { - separated.push_bind(*process_uuid); - } - } - over_limit_processes_query.push(") GROUP BY process_uuid HAVING SUM("); - over_limit_processes_query.push("estimated_bytes"); - over_limit_processes_query.push(") > "); - over_limit_processes_query.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); - let over_limit_process_uuids: Vec = over_limit_processes_query - .build() - .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| row.try_get("process_uuid")) - .collect::>()?; - if !over_limit_process_uuids.is_empty() { - // Same strict cap policy as thread pruning, but only for - // threadless rows in the affected process UUIDs. - let mut prune_threadless_process_logs = QueryBuilder::::new( - r#" -DELETE FROM logs -WHERE id IN ( - SELECT id - FROM ( - SELECT - id, - SUM( -"#, - ); - prune_threadless_process_logs.push("estimated_bytes"); - prune_threadless_process_logs.push( - r#" - ) OVER ( - PARTITION BY process_uuid - ORDER BY ts DESC, ts_nanos DESC, id DESC - ) AS cumulative_bytes - FROM logs - WHERE thread_id IS NULL - AND process_uuid IN ( -"#, - ); - { - let mut separated = prune_threadless_process_logs.separated(", "); - for process_uuid in &over_limit_process_uuids { - separated.push_bind(process_uuid); - } - } - prune_threadless_process_logs.push( - r#" - ) - ) - WHERE cumulative_bytes > -"#, - ); - prune_threadless_process_logs.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); - prune_threadless_process_logs.push("\n)"); - prune_threadless_process_logs - .build() - .execute(&mut *tx) - .await?; - } - } - if has_threadless_null_process_uuid { - // Rows without a process UUID still need a cap; treat NULL as its - // own threadless partition. - let mut null_process_usage_query = QueryBuilder::::new("SELECT SUM("); - null_process_usage_query.push("estimated_bytes"); - null_process_usage_query.push( - ") AS total_bytes FROM logs WHERE thread_id IS NULL AND process_uuid IS NULL", - ); - let total_null_process_bytes: Option = null_process_usage_query - .build() - .fetch_one(&mut *tx) - .await? - .try_get("total_bytes")?; - - if total_null_process_bytes.unwrap_or(0) > LOG_PARTITION_SIZE_LIMIT_BYTES { - let mut prune_threadless_null_process_logs = QueryBuilder::::new( - r#" -DELETE FROM logs -WHERE id IN ( - SELECT id - FROM ( - SELECT - id, - SUM( -"#, - ); - prune_threadless_null_process_logs.push("estimated_bytes"); - prune_threadless_null_process_logs.push( - r#" - ) OVER ( - PARTITION BY process_uuid - ORDER BY ts DESC, ts_nanos DESC, id DESC - ) AS cumulative_bytes - FROM logs - WHERE thread_id IS NULL - AND process_uuid IS NULL - ) - WHERE cumulative_bytes > -"#, - ); - prune_threadless_null_process_logs.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); - prune_threadless_null_process_logs.push("\n)"); - prune_threadless_null_process_logs - .build() - .execute(&mut *tx) - .await?; - } - } - Ok(()) - } - - pub(crate) async fn delete_logs_before(&self, cutoff_ts: i64) -> anyhow::Result { - let result = sqlx::query("DELETE FROM logs WHERE ts < ?") - .bind(cutoff_ts) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected()) - } - - /// Query logs with optional filters. - pub async fn query_logs(&self, query: &LogQuery) -> anyhow::Result> { - let mut builder = QueryBuilder::::new( - "SELECT id, ts, ts_nanos, level, target, message, thread_id, process_uuid, file, line FROM logs WHERE 1 = 1", - ); - push_log_filters(&mut builder, query); - if query.descending { - builder.push(" ORDER BY id DESC"); - } else { - builder.push(" ORDER BY id ASC"); - } - if let Some(limit) = query.limit { - builder.push(" LIMIT ").push_bind(limit as i64); - } - - let rows = builder - .build_query_as::() - .fetch_all(self.pool.as_ref()) - .await?; - Ok(rows) - } - - /// Return the max log id matching optional filters. - pub async fn max_log_id(&self, query: &LogQuery) -> anyhow::Result { - let mut builder = - QueryBuilder::::new("SELECT MAX(id) AS max_id FROM logs WHERE 1 = 1"); - push_log_filters(&mut builder, query); - let row = builder.build().fetch_one(self.pool.as_ref()).await?; - let max_id: Option = row.try_get("max_id")?; - Ok(max_id.unwrap_or(0)) - } - - /// List thread ids using the underlying database (no rollout scanning). - pub async fn list_thread_ids( - &self, - limit: usize, - anchor: Option<&crate::Anchor>, - sort_key: crate::SortKey, - allowed_sources: &[String], - model_providers: Option<&[String]>, - archived_only: bool, - ) -> anyhow::Result> { - let mut builder = QueryBuilder::::new("SELECT id FROM threads"); - push_thread_filters( - &mut builder, - archived_only, - allowed_sources, - model_providers, - anchor, - sort_key, - None, - ); - push_thread_order_and_limit(&mut builder, sort_key, limit); - - let rows = builder.build().fetch_all(self.pool.as_ref()).await?; - rows.into_iter() - .map(|row| { - let id: String = row.try_get("id")?; - Ok(ThreadId::try_from(id)?) - }) - .collect() - } - - /// Insert or replace thread metadata directly. - pub async fn upsert_thread(&self, metadata: &crate::ThreadMetadata) -> anyhow::Result<()> { - sqlx::query( - r#" -INSERT INTO threads ( - id, - rollout_path, - created_at, - updated_at, - source, - agent_nickname, - agent_role, - model_provider, - cwd, - cli_version, - title, - sandbox_policy, - approval_mode, - tokens_used, - first_user_message, - archived, - archived_at, - git_sha, - git_branch, - git_origin_url -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) -ON CONFLICT(id) DO UPDATE SET - rollout_path = excluded.rollout_path, - created_at = excluded.created_at, - updated_at = excluded.updated_at, - source = excluded.source, - agent_nickname = excluded.agent_nickname, - agent_role = excluded.agent_role, - model_provider = excluded.model_provider, - cwd = excluded.cwd, - cli_version = excluded.cli_version, - title = excluded.title, - sandbox_policy = excluded.sandbox_policy, - approval_mode = excluded.approval_mode, - tokens_used = excluded.tokens_used, - first_user_message = excluded.first_user_message, - archived = excluded.archived, - archived_at = excluded.archived_at, - git_sha = excluded.git_sha, - git_branch = excluded.git_branch, - git_origin_url = excluded.git_origin_url - "#, - ) - .bind(metadata.id.to_string()) - .bind(metadata.rollout_path.display().to_string()) - .bind(datetime_to_epoch_seconds(metadata.created_at)) - .bind(datetime_to_epoch_seconds(metadata.updated_at)) - .bind(metadata.source.as_str()) - .bind(metadata.agent_nickname.as_deref()) - .bind(metadata.agent_role.as_deref()) - .bind(metadata.model_provider.as_str()) - .bind(metadata.cwd.display().to_string()) - .bind(metadata.cli_version.as_str()) - .bind(metadata.title.as_str()) - .bind(metadata.sandbox_policy.as_str()) - .bind(metadata.approval_mode.as_str()) - .bind(metadata.tokens_used) - .bind(metadata.first_user_message.as_deref().unwrap_or_default()) - .bind(metadata.archived_at.is_some()) - .bind(metadata.archived_at.map(datetime_to_epoch_seconds)) - .bind(metadata.git_sha.as_deref()) - .bind(metadata.git_branch.as_deref()) - .bind(metadata.git_origin_url.as_deref()) - .execute(self.pool.as_ref()) - .await?; - 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, - name, - description, - input_schema -) VALUES (?, ?, ?, ?, ?) -ON CONFLICT(thread_id, position) DO NOTHING - "#, - ) - .bind(thread_id.as_str()) - .bind(position) - .bind(tool.name.as_str()) - .bind(tool.description.as_str()) - .bind(input_schema) - .execute(&mut *tx) - .await?; - } - tx.commit().await?; - Ok(()) - } - - /// Apply rollout items incrementally using the underlying database. - pub async fn apply_rollout_items( - &self, - builder: &ThreadMetadataBuilder, - items: &[RolloutItem], - otel: Option<&OtelManager>, - ) -> anyhow::Result<()> { - if items.is_empty() { - return Ok(()); - } - let mut metadata = self - .get_thread(builder.id) - .await? - .unwrap_or_else(|| builder.build(&self.default_provider)); - metadata.rollout_path = builder.rollout_path.clone(); - for item in items { - apply_rollout_item(&mut metadata, item, &self.default_provider); - } - if let Some(updated_at) = file_modified_time_utc(builder.rollout_path.as_path()).await { - 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. - if let Err(err) = self.upsert_thread(&metadata).await { - if let Some(otel) = otel { - otel.counter(DB_ERROR_METRIC, 1, &[("stage", "apply_rollout_items")]); - } - 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 - { - if let Some(otel) = otel { - otel.counter(DB_ERROR_METRIC, 1, &[("stage", "persist_dynamic_tools")]); - } - return Err(err); - } - Ok(()) - } - - /// Mark a thread as archived using the underlying database. - pub async fn mark_archived( - &self, - thread_id: ThreadId, - rollout_path: &Path, - archived_at: DateTime, - ) -> anyhow::Result<()> { - let Some(mut metadata) = self.get_thread(thread_id).await? else { - return Ok(()); - }; - metadata.archived_at = Some(archived_at); - metadata.rollout_path = rollout_path.to_path_buf(); - if let Some(updated_at) = file_modified_time_utc(rollout_path).await { - metadata.updated_at = updated_at; - } - if metadata.id != thread_id { - warn!( - "thread id mismatch during archive: expected {thread_id}, got {}", - metadata.id - ); - } - self.upsert_thread(&metadata).await - } - - /// Mark a thread as unarchived using the underlying database. - pub async fn mark_unarchived( - &self, - thread_id: ThreadId, - rollout_path: &Path, - ) -> anyhow::Result<()> { - let Some(mut metadata) = self.get_thread(thread_id).await? else { - return Ok(()); - }; - metadata.archived_at = None; - metadata.rollout_path = rollout_path.to_path_buf(); - if let Some(updated_at) = file_modified_time_utc(rollout_path).await { - metadata.updated_at = updated_at; - } - if metadata.id != thread_id { - warn!( - "thread id mismatch during unarchive: expected {thread_id}, got {}", - metadata.id - ); - } - self.upsert_thread(&metadata).await - } - - /// Delete a thread metadata row by id. - pub async fn delete_thread(&self, thread_id: ThreadId) -> anyhow::Result { - let result = sqlx::query("DELETE FROM threads WHERE id = ?") - .bind(thread_id.to_string()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected()) - } - - pub async fn create_agent_job( - &self, - params: &AgentJobCreateParams, - items: &[AgentJobItemCreateParams], - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let input_headers_json = serde_json::to_string(¶ms.input_headers)?; - let output_schema_json = params - .output_schema_json - .as_ref() - .map(serde_json::to_string) - .transpose()?; - let max_runtime_seconds = params - .max_runtime_seconds - .map(i64::try_from) - .transpose() - .map_err(|_| anyhow::anyhow!("invalid max_runtime_seconds value"))?; - let mut tx = self.pool.begin().await?; - sqlx::query( - r#" -INSERT INTO agent_jobs ( - id, - name, - status, - instruction, - auto_export, - max_runtime_seconds, - output_schema_json, - input_headers_json, - input_csv_path, - output_csv_path, - created_at, - updated_at, - started_at, - completed_at, - last_error -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL) - "#, - ) - .bind(params.id.as_str()) - .bind(params.name.as_str()) - .bind(AgentJobStatus::Pending.as_str()) - .bind(params.instruction.as_str()) - .bind(i64::from(params.auto_export)) - .bind(max_runtime_seconds) - .bind(output_schema_json) - .bind(input_headers_json) - .bind(params.input_csv_path.as_str()) - .bind(params.output_csv_path.as_str()) - .bind(now) - .bind(now) - .execute(&mut *tx) - .await?; - - for item in items { - let row_json = serde_json::to_string(&item.row_json)?; - sqlx::query( - r#" -INSERT INTO agent_job_items ( - job_id, - item_id, - row_index, - source_id, - row_json, - status, - assigned_thread_id, - attempt_count, - result_json, - last_error, - created_at, - updated_at, - completed_at, - reported_at -) VALUES (?, ?, ?, ?, ?, ?, NULL, 0, NULL, NULL, ?, ?, NULL, NULL) - "#, - ) - .bind(params.id.as_str()) - .bind(item.item_id.as_str()) - .bind(item.row_index) - .bind(item.source_id.as_deref()) - .bind(row_json) - .bind(AgentJobItemStatus::Pending.as_str()) - .bind(now) - .bind(now) - .execute(&mut *tx) - .await?; - } - - tx.commit().await?; - - let job_id = params.id.as_str(); - self.get_agent_job(job_id) - .await? - .ok_or_else(|| anyhow::anyhow!("failed to load created agent job {job_id}")) - } - - pub async fn get_agent_job(&self, job_id: &str) -> anyhow::Result> { - let row = sqlx::query_as::<_, AgentJobRow>( - r#" -SELECT - id, - name, - status, - instruction, - auto_export, - max_runtime_seconds, - output_schema_json, - input_headers_json, - input_csv_path, - output_csv_path, - created_at, - updated_at, - started_at, - completed_at, - last_error -FROM agent_jobs -WHERE id = ? - "#, - ) - .bind(job_id) - .fetch_optional(self.pool.as_ref()) - .await?; - row.map(AgentJob::try_from).transpose() - } - - pub async fn list_agent_job_items( - &self, - job_id: &str, - status: Option, - limit: Option, - ) -> anyhow::Result> { - let mut builder = QueryBuilder::::new( - r#" -SELECT - job_id, - item_id, - row_index, - source_id, - row_json, - status, - assigned_thread_id, - attempt_count, - result_json, - last_error, - created_at, - updated_at, - completed_at, - reported_at -FROM agent_job_items -WHERE job_id = - "#, - ); - builder.push_bind(job_id); - if let Some(status) = status { - builder.push(" AND status = "); - builder.push_bind(status.as_str()); - } - builder.push(" ORDER BY row_index ASC"); - if let Some(limit) = limit { - builder.push(" LIMIT "); - builder.push_bind(limit as i64); - } - let rows = builder - .build_query_as::() - .fetch_all(self.pool.as_ref()) - .await?; - rows.into_iter().map(AgentJobItem::try_from).collect() - } - - pub async fn get_agent_job_item( - &self, - job_id: &str, - item_id: &str, - ) -> anyhow::Result> { - let row = sqlx::query_as::<_, AgentJobItemRow>( - r#" -SELECT - job_id, - item_id, - row_index, - source_id, - row_json, - status, - assigned_thread_id, - attempt_count, - result_json, - last_error, - created_at, - updated_at, - completed_at, - reported_at -FROM agent_job_items -WHERE job_id = ? AND item_id = ? - "#, - ) - .bind(job_id) - .bind(item_id) - .fetch_optional(self.pool.as_ref()) - .await?; - row.map(AgentJobItem::try_from).transpose() - } - - pub async fn mark_agent_job_running(&self, job_id: &str) -> anyhow::Result<()> { - let now = Utc::now().timestamp(); - sqlx::query( - r#" -UPDATE agent_jobs -SET - status = ?, - updated_at = ?, - started_at = COALESCE(started_at, ?), - completed_at = NULL, - last_error = NULL -WHERE id = ? - "#, - ) - .bind(AgentJobStatus::Running.as_str()) - .bind(now) - .bind(now) - .bind(job_id) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } - - pub async fn mark_agent_job_completed(&self, job_id: &str) -> anyhow::Result<()> { - let now = Utc::now().timestamp(); - sqlx::query( - r#" -UPDATE agent_jobs -SET status = ?, updated_at = ?, completed_at = ?, last_error = NULL -WHERE id = ? - "#, - ) - .bind(AgentJobStatus::Completed.as_str()) - .bind(now) - .bind(now) - .bind(job_id) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } - - pub async fn mark_agent_job_failed( - &self, - job_id: &str, - error_message: &str, - ) -> anyhow::Result<()> { - let now = Utc::now().timestamp(); - sqlx::query( - r#" -UPDATE agent_jobs -SET status = ?, updated_at = ?, completed_at = ?, last_error = ? -WHERE id = ? - "#, - ) - .bind(AgentJobStatus::Failed.as_str()) - .bind(now) - .bind(now) - .bind(error_message) - .bind(job_id) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } - - pub async fn mark_agent_job_cancelled( - &self, - job_id: &str, - reason: &str, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_jobs -SET status = ?, updated_at = ?, completed_at = ?, last_error = ? -WHERE id = ? AND status IN (?, ?) - "#, - ) - .bind(AgentJobStatus::Cancelled.as_str()) - .bind(now) - .bind(now) - .bind(reason) - .bind(job_id) - .bind(AgentJobStatus::Pending.as_str()) - .bind(AgentJobStatus::Running.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn is_agent_job_cancelled(&self, job_id: &str) -> anyhow::Result { - let row = sqlx::query( - r#" -SELECT status -FROM agent_jobs -WHERE id = ? - "#, - ) - .bind(job_id) - .fetch_optional(self.pool.as_ref()) - .await?; - let Some(row) = row else { - return Ok(false); - }; - let status: String = row.try_get("status")?; - Ok(AgentJobStatus::parse(status.as_str())? == AgentJobStatus::Cancelled) - } - - pub async fn mark_agent_job_item_running( - &self, - job_id: &str, - item_id: &str, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET - status = ?, - assigned_thread_id = NULL, - attempt_count = attempt_count + 1, - updated_at = ?, - last_error = NULL -WHERE job_id = ? AND item_id = ? AND status = ? - "#, - ) - .bind(AgentJobItemStatus::Running.as_str()) - .bind(now) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Pending.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn mark_agent_job_item_running_with_thread( - &self, - job_id: &str, - item_id: &str, - thread_id: &str, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET - status = ?, - assigned_thread_id = ?, - attempt_count = attempt_count + 1, - updated_at = ?, - last_error = NULL -WHERE job_id = ? AND item_id = ? AND status = ? - "#, - ) - .bind(AgentJobItemStatus::Running.as_str()) - .bind(thread_id) - .bind(now) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Pending.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn mark_agent_job_item_pending( - &self, - job_id: &str, - item_id: &str, - error_message: Option<&str>, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET - status = ?, - assigned_thread_id = NULL, - updated_at = ?, - last_error = ? -WHERE job_id = ? AND item_id = ? AND status = ? - "#, - ) - .bind(AgentJobItemStatus::Pending.as_str()) - .bind(now) - .bind(error_message) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Running.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn set_agent_job_item_thread( - &self, - job_id: &str, - item_id: &str, - thread_id: &str, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET assigned_thread_id = ?, updated_at = ? -WHERE job_id = ? AND item_id = ? AND status = ? - "#, - ) - .bind(thread_id) - .bind(now) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Running.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn report_agent_job_item_result( - &self, - job_id: &str, - item_id: &str, - reporting_thread_id: &str, - result_json: &Value, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let serialized = serde_json::to_string(result_json)?; - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET - result_json = ?, - reported_at = ?, - updated_at = ?, - last_error = NULL -WHERE - job_id = ? - AND item_id = ? - AND status = ? - AND assigned_thread_id = ? - "#, - ) - .bind(serialized) - .bind(now) - .bind(now) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Running.as_str()) - .bind(reporting_thread_id) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn mark_agent_job_item_completed( - &self, - job_id: &str, - item_id: &str, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET - status = ?, - completed_at = ?, - updated_at = ?, - assigned_thread_id = NULL -WHERE - job_id = ? - AND item_id = ? - AND status = ? - AND result_json IS NOT NULL - "#, - ) - .bind(AgentJobItemStatus::Completed.as_str()) - .bind(now) - .bind(now) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Running.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn mark_agent_job_item_failed( - &self, - job_id: &str, - item_id: &str, - error_message: &str, - ) -> anyhow::Result { - let now = Utc::now().timestamp(); - let result = sqlx::query( - r#" -UPDATE agent_job_items -SET - status = ?, - completed_at = ?, - updated_at = ?, - last_error = ?, - assigned_thread_id = NULL -WHERE - job_id = ? - AND item_id = ? - AND status = ? - "#, - ) - .bind(AgentJobItemStatus::Failed.as_str()) - .bind(now) - .bind(now) - .bind(error_message) - .bind(job_id) - .bind(item_id) - .bind(AgentJobItemStatus::Running.as_str()) - .execute(self.pool.as_ref()) - .await?; - Ok(result.rows_affected() > 0) - } - - pub async fn get_agent_job_progress(&self, job_id: &str) -> anyhow::Result { - let row = sqlx::query( - r#" -SELECT - COUNT(*) AS total_items, - SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS pending_items, - SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS running_items, - SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS completed_items, - SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS failed_items -FROM agent_job_items -WHERE job_id = ? - "#, - ) - .bind(AgentJobItemStatus::Pending.as_str()) - .bind(AgentJobItemStatus::Running.as_str()) - .bind(AgentJobItemStatus::Completed.as_str()) - .bind(AgentJobItemStatus::Failed.as_str()) - .bind(job_id) - .fetch_one(self.pool.as_ref()) - .await?; - - let total_items: i64 = row.try_get("total_items")?; - let pending_items: Option = row.try_get("pending_items")?; - let running_items: Option = row.try_get("running_items")?; - let completed_items: Option = row.try_get("completed_items")?; - let failed_items: Option = row.try_get("failed_items")?; - Ok(AgentJobProgress { - total_items: usize::try_from(total_items).unwrap_or_default(), - pending_items: usize::try_from(pending_items.unwrap_or_default()).unwrap_or_default(), - running_items: usize::try_from(running_items.unwrap_or_default()).unwrap_or_default(), - completed_items: usize::try_from(completed_items.unwrap_or_default()) - .unwrap_or_default(), - failed_items: usize::try_from(failed_items.unwrap_or_default()).unwrap_or_default(), - }) - } - - async fn ensure_backfill_state_row(&self) -> anyhow::Result<()> { - sqlx::query( - r#" -INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at) -VALUES (?, ?, NULL, NULL, ?) -ON CONFLICT(id) DO NOTHING - "#, - ) - .bind(1_i64) - .bind(crate::BackfillStatus::Pending.as_str()) - .bind(Utc::now().timestamp()) - .execute(self.pool.as_ref()) - .await?; - Ok(()) - } -} - -fn push_log_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, query: &'a LogQuery) { - if let Some(level_upper) = query.level_upper.as_ref() { - builder - .push(" AND UPPER(level) = ") - .push_bind(level_upper.as_str()); - } - if let Some(from_ts) = query.from_ts { - builder.push(" AND ts >= ").push_bind(from_ts); - } - if let Some(to_ts) = query.to_ts { - builder.push(" AND ts <= ").push_bind(to_ts); - } - push_like_filters(builder, "module_path", &query.module_like); - push_like_filters(builder, "file", &query.file_like); - let has_thread_filter = !query.thread_ids.is_empty() || query.include_threadless; - if has_thread_filter { - builder.push(" AND ("); - let mut needs_or = false; - for thread_id in &query.thread_ids { - if needs_or { - builder.push(" OR "); - } - builder.push("thread_id = ").push_bind(thread_id.as_str()); - needs_or = true; - } - if query.include_threadless { - if needs_or { - builder.push(" OR "); - } - builder.push("thread_id IS NULL"); - } - builder.push(")"); - } - if let Some(after_id) = query.after_id { - builder.push(" AND id > ").push_bind(after_id); - } - if let Some(search) = query.search.as_ref() { - builder.push(" AND INSTR(message, "); - builder.push_bind(search.as_str()); - builder.push(") > 0"); - } -} - -fn push_like_filters<'a>( - builder: &mut QueryBuilder<'a, Sqlite>, - column: &str, - filters: &'a [String], -) { - if filters.is_empty() { - return; - } - builder.push(" AND ("); - for (idx, filter) in filters.iter().enumerate() { - if idx > 0 { - builder.push(" OR "); - } - builder - .push(column) - .push(" LIKE '%' || ") - .push_bind(filter.as_str()) - .push(" || '%'"); - } - builder.push(")"); -} - -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, - }) } async fn open_sqlite(path: &Path) -> anyhow::Result { @@ -1650,2254 +198,3 @@ fn should_remove_state_file(file_name: &str, current_name: &str) -> bool { }; !version_suffix.is_empty() && version_suffix.chars().all(|ch| ch.is_ascii_digit()) } - -fn push_thread_filters<'a>( - builder: &mut QueryBuilder<'a, Sqlite>, - archived_only: bool, - allowed_sources: &'a [String], - model_providers: Option<&'a [String]>, - anchor: Option<&crate::Anchor>, - sort_key: SortKey, - search_term: Option<&'a str>, -) { - builder.push(" WHERE 1 = 1"); - if archived_only { - builder.push(" AND archived = 1"); - } else { - builder.push(" AND archived = 0"); - } - builder.push(" AND first_user_message <> ''"); - if !allowed_sources.is_empty() { - builder.push(" AND source IN ("); - let mut separated = builder.separated(", "); - for source in allowed_sources { - separated.push_bind(source); - } - separated.push_unseparated(")"); - } - if let Some(model_providers) = model_providers - && !model_providers.is_empty() - { - builder.push(" AND model_provider IN ("); - let mut separated = builder.separated(", "); - for provider in model_providers { - separated.push_bind(provider); - } - separated.push_unseparated(")"); - } - if let Some(search_term) = search_term { - builder.push(" AND instr(title, "); - builder.push_bind(search_term); - builder.push(") > 0"); - } - if let Some(anchor) = anchor { - let anchor_ts = datetime_to_epoch_seconds(anchor.ts); - let column = match sort_key { - SortKey::CreatedAt => "created_at", - SortKey::UpdatedAt => "updated_at", - }; - builder.push(" AND ("); - builder.push(column); - builder.push(" < "); - builder.push_bind(anchor_ts); - builder.push(" OR ("); - builder.push(column); - builder.push(" = "); - builder.push_bind(anchor_ts); - builder.push(" AND id < "); - builder.push_bind(anchor.id.to_string()); - builder.push("))"); - } -} - -fn push_thread_order_and_limit( - builder: &mut QueryBuilder<'_, Sqlite>, - sort_key: SortKey, - limit: usize, -) { - let order_column = match sort_key { - SortKey::CreatedAt => "created_at", - SortKey::UpdatedAt => "updated_at", - }; - builder.push(" ORDER BY "); - builder.push(order_column); - builder.push(" DESC, id DESC"); - builder.push(" LIMIT "); - builder.push_bind(limit as i64); -} - -#[cfg(test)] -mod tests { - use super::StateRuntime; - use super::ThreadMetadata; - use super::state_db_filename; - use crate::LogEntry; - use crate::LogQuery; - use crate::STATE_DB_FILENAME; - use crate::STATE_DB_VERSION; - use crate::model::Phase2JobClaimOutcome; - use crate::model::Stage1JobClaimOutcome; - use crate::model::Stage1StartupClaimParams; - use chrono::DateTime; - use chrono::Duration; - use chrono::Utc; - use codex_protocol::ThreadId; - use codex_protocol::protocol::AskForApproval; - use codex_protocol::protocol::SandboxPolicy; - use pretty_assertions::assert_eq; - use sqlx::Row; - use std::path::Path; - use std::path::PathBuf; - use std::sync::Arc; - use std::time::SystemTime; - use std::time::UNIX_EPOCH; - use uuid::Uuid; - - fn unique_temp_dir() -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |duration| duration.as_nanos()); - std::env::temp_dir().join(format!( - "codex-state-runtime-test-{nanos}-{}", - Uuid::new_v4() - )) - } - - #[tokio::test] - async fn init_removes_legacy_state_db_files() { - let codex_home = unique_temp_dir(); - tokio::fs::create_dir_all(&codex_home) - .await - .expect("create codex_home"); - - let current_name = state_db_filename(); - let previous_version = STATE_DB_VERSION.saturating_sub(1); - let unversioned_name = format!("{STATE_DB_FILENAME}.sqlite"); - for suffix in ["", "-wal", "-shm", "-journal"] { - let path = codex_home.join(format!("{unversioned_name}{suffix}")); - tokio::fs::write(path, b"legacy") - .await - .expect("write legacy"); - let old_version_path = codex_home.join(format!( - "{STATE_DB_FILENAME}_{previous_version}.sqlite{suffix}" - )); - tokio::fs::write(old_version_path, b"old_version") - .await - .expect("write old version"); - } - let unrelated_path = codex_home.join("state.sqlite_backup"); - tokio::fs::write(&unrelated_path, b"keep") - .await - .expect("write unrelated"); - let numeric_path = codex_home.join("123"); - tokio::fs::write(&numeric_path, b"keep") - .await - .expect("write numeric"); - - let _runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - for suffix in ["", "-wal", "-shm", "-journal"] { - let legacy_path = codex_home.join(format!("{unversioned_name}{suffix}")); - assert_eq!( - tokio::fs::try_exists(&legacy_path) - .await - .expect("check legacy path"), - false - ); - let old_version_path = codex_home.join(format!( - "{STATE_DB_FILENAME}_{previous_version}.sqlite{suffix}" - )); - assert_eq!( - tokio::fs::try_exists(&old_version_path) - .await - .expect("check old version path"), - false - ); - } - assert_eq!( - tokio::fs::try_exists(codex_home.join(current_name)) - .await - .expect("check new db path"), - true - ); - assert_eq!( - tokio::fs::try_exists(&unrelated_path) - .await - .expect("check unrelated path"), - true - ); - assert_eq!( - tokio::fs::try_exists(&numeric_path) - .await - .expect("check numeric path"), - true - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn backfill_state_persists_progress_and_completion() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let initial = runtime - .get_backfill_state() - .await - .expect("get initial backfill state"); - assert_eq!(initial.status, crate::BackfillStatus::Pending); - assert_eq!(initial.last_watermark, None); - assert_eq!(initial.last_success_at, None); - - runtime - .mark_backfill_running() - .await - .expect("mark backfill running"); - runtime - .checkpoint_backfill("sessions/2026/01/27/rollout-a.jsonl") - .await - .expect("checkpoint backfill"); - - let running = runtime - .get_backfill_state() - .await - .expect("get running backfill state"); - assert_eq!(running.status, crate::BackfillStatus::Running); - assert_eq!( - running.last_watermark, - Some("sessions/2026/01/27/rollout-a.jsonl".to_string()) - ); - assert_eq!(running.last_success_at, None); - - runtime - .mark_backfill_complete(Some("sessions/2026/01/28/rollout-b.jsonl")) - .await - .expect("mark backfill complete"); - let completed = runtime - .get_backfill_state() - .await - .expect("get completed backfill state"); - assert_eq!(completed.status, crate::BackfillStatus::Complete); - assert_eq!( - completed.last_watermark, - Some("sessions/2026/01/28/rollout-b.jsonl".to_string()) - ); - assert!(completed.last_success_at.is_some()); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn backfill_claim_is_singleton_until_stale_and_blocked_when_complete() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let claimed = runtime - .try_claim_backfill(3600) - .await - .expect("initial backfill claim"); - assert_eq!(claimed, true); - - let duplicate_claim = runtime - .try_claim_backfill(3600) - .await - .expect("duplicate backfill claim"); - assert_eq!(duplicate_claim, false); - - let stale_updated_at = Utc::now().timestamp().saturating_sub(10_000); - sqlx::query( - r#" -UPDATE backfill_state -SET status = ?, updated_at = ? -WHERE id = 1 - "#, - ) - .bind(crate::BackfillStatus::Running.as_str()) - .bind(stale_updated_at) - .execute(runtime.pool.as_ref()) - .await - .expect("force stale backfill lease"); - - let stale_claim = runtime - .try_claim_backfill(10) - .await - .expect("stale backfill claim"); - assert_eq!(stale_claim, true); - - runtime - .mark_backfill_complete(None) - .await - .expect("mark complete"); - let claim_after_complete = runtime - .try_claim_backfill(3600) - .await - .expect("claim after complete"); - assert_eq!(claim_after_complete, false); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn stage1_claim_skips_when_up_to_date() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let metadata = test_thread_metadata(&codex_home, thread_id, codex_home.join("a")); - runtime - .upsert_thread(&metadata) - .await - .expect("upsert thread"); - - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - - let claim = runtime - .try_claim_stage1_job(thread_id, owner_a, 100, 3600, 64) - .await - .expect("claim stage1 job"); - let ownership_token = match claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected claim outcome: {other:?}"), - }; - - assert!( - runtime - .mark_stage1_job_succeeded( - thread_id, - ownership_token.as_str(), - 100, - "raw", - "sum", - None, - ) - .await - .expect("mark stage1 succeeded"), - "stage1 success should finalize for current token" - ); - - let up_to_date = runtime - .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) - .await - .expect("claim stage1 up-to-date"); - assert_eq!(up_to_date, Stage1JobClaimOutcome::SkippedUpToDate); - - let needs_rerun = runtime - .try_claim_stage1_job(thread_id, owner_b, 101, 3600, 64) - .await - .expect("claim stage1 newer source"); - assert!( - matches!(needs_rerun, Stage1JobClaimOutcome::Claimed { .. }), - "newer source_updated_at should be claimable" - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn stage1_running_stale_can_be_stolen_but_fresh_running_is_skipped() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let cwd = codex_home.join("workspace"); - runtime - .upsert_thread(&test_thread_metadata(&codex_home, thread_id, cwd)) - .await - .expect("upsert thread"); - - let claim_a = runtime - .try_claim_stage1_job(thread_id, owner_a, 100, 3600, 64) - .await - .expect("claim a"); - assert!(matches!(claim_a, Stage1JobClaimOutcome::Claimed { .. })); - - let claim_b_fresh = runtime - .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) - .await - .expect("claim b fresh"); - assert_eq!(claim_b_fresh, Stage1JobClaimOutcome::SkippedRunning); - - sqlx::query("UPDATE jobs SET lease_until = 0 WHERE kind = 'memory_stage1' AND job_key = ?") - .bind(thread_id.to_string()) - .execute(runtime.pool.as_ref()) - .await - .expect("force stale lease"); - - let claim_b_stale = runtime - .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) - .await - .expect("claim b stale"); - assert!(matches!( - claim_b_stale, - Stage1JobClaimOutcome::Claimed { .. } - )); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn stage1_concurrent_claim_for_same_thread_is_conflict_safe() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id, - codex_home.join("workspace"), - )) - .await - .expect("upsert thread"); - - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let thread_id_a = thread_id; - let thread_id_b = thread_id; - let runtime_a = Arc::clone(&runtime); - let runtime_b = Arc::clone(&runtime); - let claim_with_retry = |runtime: Arc, - thread_id: ThreadId, - owner: ThreadId| async move { - for attempt in 0..5 { - match runtime - .try_claim_stage1_job(thread_id, owner, 100, 3_600, 64) - .await - { - Ok(outcome) => return outcome, - Err(err) if err.to_string().contains("database is locked") && attempt < 4 => { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - Err(err) => panic!("claim stage1 should not fail: {err}"), - } - } - panic!("claim stage1 should have returned within retry budget") - }; - - let (claim_a, claim_b) = tokio::join!( - claim_with_retry(runtime_a, thread_id_a, owner_a), - claim_with_retry(runtime_b, thread_id_b, owner_b), - ); - - let claim_outcomes = vec![claim_a, claim_b]; - let claimed_count = claim_outcomes - .iter() - .filter(|outcome| matches!(outcome, Stage1JobClaimOutcome::Claimed { .. })) - .count(); - assert_eq!(claimed_count, 1); - assert!( - claim_outcomes.iter().all(|outcome| { - matches!( - outcome, - Stage1JobClaimOutcome::Claimed { .. } | Stage1JobClaimOutcome::SkippedRunning - ) - }), - "unexpected claim outcomes: {claim_outcomes:?}" - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn stage1_concurrent_claims_respect_running_cap() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_a, - codex_home.join("workspace-a"), - )) - .await - .expect("upsert thread a"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_b, - codex_home.join("workspace-b"), - )) - .await - .expect("upsert thread b"); - - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let runtime_a = Arc::clone(&runtime); - let runtime_b = Arc::clone(&runtime); - - let (claim_a, claim_b) = tokio::join!( - async move { - runtime_a - .try_claim_stage1_job(thread_a, owner_a, 100, 3_600, 1) - .await - .expect("claim stage1 thread a") - }, - async move { - runtime_b - .try_claim_stage1_job(thread_b, owner_b, 101, 3_600, 1) - .await - .expect("claim stage1 thread b") - }, - ); - - let claim_outcomes = vec![claim_a, claim_b]; - let claimed_count = claim_outcomes - .iter() - .filter(|outcome| matches!(outcome, Stage1JobClaimOutcome::Claimed { .. })) - .count(); - assert_eq!(claimed_count, 1); - assert!( - claim_outcomes - .iter() - .any(|outcome| { matches!(outcome, Stage1JobClaimOutcome::SkippedRunning) }), - "one concurrent claim should be throttled by running cap: {claim_outcomes:?}" - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn claim_stage1_jobs_filters_by_age_idle_and_current_thread() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let now = Utc::now(); - let fresh_at = now - Duration::hours(1); - let just_under_idle_at = now - Duration::hours(12) + Duration::minutes(1); - let eligible_idle_at = now - Duration::hours(12) - Duration::minutes(1); - let old_at = now - Duration::days(31); - - let current_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); - let fresh_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("fresh thread id"); - let just_under_idle_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("just under idle thread id"); - let eligible_idle_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("eligible idle thread id"); - let old_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("old thread id"); - - let mut current = - test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); - current.created_at = now; - current.updated_at = now; - runtime - .upsert_thread(¤t) - .await - .expect("upsert current"); - - let mut fresh = - test_thread_metadata(&codex_home, fresh_thread_id, codex_home.join("fresh")); - fresh.created_at = fresh_at; - fresh.updated_at = fresh_at; - runtime.upsert_thread(&fresh).await.expect("upsert fresh"); - - let mut just_under_idle = test_thread_metadata( - &codex_home, - just_under_idle_thread_id, - codex_home.join("just-under-idle"), - ); - just_under_idle.created_at = just_under_idle_at; - just_under_idle.updated_at = just_under_idle_at; - runtime - .upsert_thread(&just_under_idle) - .await - .expect("upsert just-under-idle"); - - let mut eligible_idle = test_thread_metadata( - &codex_home, - eligible_idle_thread_id, - codex_home.join("eligible-idle"), - ); - eligible_idle.created_at = eligible_idle_at; - eligible_idle.updated_at = eligible_idle_at; - runtime - .upsert_thread(&eligible_idle) - .await - .expect("upsert eligible-idle"); - - let mut old = test_thread_metadata(&codex_home, old_thread_id, codex_home.join("old")); - old.created_at = old_at; - old.updated_at = old_at; - runtime.upsert_thread(&old).await.expect("upsert old"); - - let allowed_sources = vec!["cli".to_string()]; - let claims = runtime - .claim_stage1_jobs_for_startup( - current_thread_id, - Stage1StartupClaimParams { - scan_limit: 1, - max_claimed: 5, - max_age_days: 30, - min_rollout_idle_hours: 12, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: 3600, - }, - ) - .await - .expect("claim stage1 jobs"); - - assert_eq!(claims.len(), 1); - assert_eq!(claims[0].thread.id, eligible_idle_thread_id); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn claim_stage1_jobs_prefilters_threads_with_up_to_date_memory() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let now = Utc::now(); - let eligible_newer_at = now - Duration::hours(13); - let eligible_older_at = now - Duration::hours(14); - - let current_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); - let up_to_date_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("up-to-date thread id"); - let stale_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("stale thread id"); - let worker_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("worker id"); - - let mut current = - test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); - current.created_at = now; - current.updated_at = now; - runtime - .upsert_thread(¤t) - .await - .expect("upsert current thread"); - - let mut up_to_date = test_thread_metadata( - &codex_home, - up_to_date_thread_id, - codex_home.join("up-to-date"), - ); - up_to_date.created_at = eligible_newer_at; - up_to_date.updated_at = eligible_newer_at; - runtime - .upsert_thread(&up_to_date) - .await - .expect("upsert up-to-date thread"); - - let up_to_date_claim = runtime - .try_claim_stage1_job( - up_to_date_thread_id, - worker_id, - up_to_date.updated_at.timestamp(), - 3600, - 64, - ) - .await - .expect("claim up-to-date thread for seed"); - let up_to_date_token = match up_to_date_claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected seed claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded( - up_to_date_thread_id, - up_to_date_token.as_str(), - up_to_date.updated_at.timestamp(), - "raw", - "summary", - None, - ) - .await - .expect("mark up-to-date thread succeeded"), - "seed stage1 success should complete for up-to-date thread" - ); - - let mut stale = - test_thread_metadata(&codex_home, stale_thread_id, codex_home.join("stale")); - stale.created_at = eligible_older_at; - stale.updated_at = eligible_older_at; - runtime - .upsert_thread(&stale) - .await - .expect("upsert stale thread"); - - let allowed_sources = vec!["cli".to_string()]; - let claims = runtime - .claim_stage1_jobs_for_startup( - current_thread_id, - Stage1StartupClaimParams { - scan_limit: 1, - max_claimed: 1, - max_age_days: 30, - min_rollout_idle_hours: 12, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: 3600, - }, - ) - .await - .expect("claim stage1 startup jobs"); - assert_eq!(claims.len(), 1); - assert_eq!(claims[0].thread.id, stale_thread_id); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn claim_stage1_jobs_enforces_global_running_cap() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let current_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - current_thread_id, - codex_home.join("current"), - )) - .await - .expect("upsert current"); - - let now = Utc::now(); - let started_at = now.timestamp(); - let lease_until = started_at + 3600; - let eligible_at = now - Duration::hours(13); - let existing_running = 10usize; - let total_candidates = 80usize; - - for idx in 0..total_candidates { - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let mut metadata = test_thread_metadata( - &codex_home, - thread_id, - codex_home.join(format!("thread-{idx}")), - ); - metadata.created_at = eligible_at - Duration::seconds(idx as i64); - metadata.updated_at = eligible_at - Duration::seconds(idx as i64); - runtime - .upsert_thread(&metadata) - .await - .expect("upsert thread"); - - if idx < existing_running { - sqlx::query( - r#" -INSERT INTO jobs ( - kind, - job_key, - status, - worker_id, - ownership_token, - started_at, - finished_at, - lease_until, - retry_at, - retry_remaining, - last_error, - input_watermark, - last_success_watermark -) VALUES (?, ?, 'running', ?, ?, ?, NULL, ?, NULL, ?, NULL, ?, NULL) - "#, - ) - .bind("memory_stage1") - .bind(thread_id.to_string()) - .bind(current_thread_id.to_string()) - .bind(Uuid::new_v4().to_string()) - .bind(started_at) - .bind(lease_until) - .bind(3) - .bind(metadata.updated_at.timestamp()) - .execute(runtime.pool.as_ref()) - .await - .expect("seed running stage1 job"); - } - } - - let allowed_sources = vec!["cli".to_string()]; - let claims = runtime - .claim_stage1_jobs_for_startup( - current_thread_id, - Stage1StartupClaimParams { - scan_limit: 200, - max_claimed: 64, - max_age_days: 30, - min_rollout_idle_hours: 12, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: 3600, - }, - ) - .await - .expect("claim stage1 jobs"); - assert_eq!(claims.len(), 54); - - let running_count = sqlx::query( - r#" -SELECT COUNT(*) AS count -FROM jobs -WHERE kind = 'memory_stage1' - AND status = 'running' - AND lease_until IS NOT NULL - AND lease_until > ? - "#, - ) - .bind(Utc::now().timestamp()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("count running stage1 jobs") - .try_get::("count") - .expect("running count value"); - assert_eq!(running_count, 64); - - let more_claims = runtime - .claim_stage1_jobs_for_startup( - current_thread_id, - Stage1StartupClaimParams { - scan_limit: 200, - max_claimed: 64, - max_age_days: 30, - min_rollout_idle_hours: 12, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: 3600, - }, - ) - .await - .expect("claim stage1 jobs with cap reached"); - assert_eq!(more_claims.len(), 0); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn claim_stage1_jobs_processes_two_full_batches_across_startup_passes() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let current_thread_id = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); - let mut current = - test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); - current.created_at = Utc::now(); - current.updated_at = Utc::now(); - runtime - .upsert_thread(¤t) - .await - .expect("upsert current"); - - let eligible_at = Utc::now() - Duration::hours(13); - for idx in 0..200 { - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let mut metadata = test_thread_metadata( - &codex_home, - thread_id, - codex_home.join(format!("thread-{idx}")), - ); - metadata.created_at = eligible_at - Duration::seconds(idx as i64); - metadata.updated_at = eligible_at - Duration::seconds(idx as i64); - runtime - .upsert_thread(&metadata) - .await - .expect("upsert eligible thread"); - } - - let allowed_sources = vec!["cli".to_string()]; - let first_claims = runtime - .claim_stage1_jobs_for_startup( - current_thread_id, - Stage1StartupClaimParams { - scan_limit: 5_000, - max_claimed: 64, - max_age_days: 30, - min_rollout_idle_hours: 12, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: 3_600, - }, - ) - .await - .expect("first stage1 startup claim"); - assert_eq!(first_claims.len(), 64); - - for claim in first_claims { - assert!( - runtime - .mark_stage1_job_succeeded( - claim.thread.id, - claim.ownership_token.as_str(), - claim.thread.updated_at.timestamp(), - "raw", - "summary", - None, - ) - .await - .expect("mark first-batch stage1 success"), - "first batch stage1 completion should succeed" - ); - } - - let second_claims = runtime - .claim_stage1_jobs_for_startup( - current_thread_id, - Stage1StartupClaimParams { - scan_limit: 5_000, - max_claimed: 64, - max_age_days: 30, - min_rollout_idle_hours: 12, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: 3_600, - }, - ) - .await - .expect("second stage1 startup claim"); - assert_eq!(second_claims.len(), 64); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn stage1_output_cascades_on_thread_delete() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let cwd = codex_home.join("workspace"); - runtime - .upsert_thread(&test_thread_metadata(&codex_home, thread_id, cwd)) - .await - .expect("upsert thread"); - - let claim = runtime - .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) - .await - .expect("claim stage1"); - let ownership_token = match claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded( - thread_id, - ownership_token.as_str(), - 100, - "raw", - "sum", - None, - ) - .await - .expect("mark stage1 succeeded"), - "mark stage1 succeeded should write stage1_outputs" - ); - - let count_before = - sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") - .bind(thread_id.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("count before delete") - .try_get::("count") - .expect("count value"); - assert_eq!(count_before, 1); - - sqlx::query("DELETE FROM threads WHERE id = ?") - .bind(thread_id.to_string()) - .execute(runtime.pool.as_ref()) - .await - .expect("delete thread"); - - let count_after = - sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") - .bind(thread_id.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("count after delete") - .try_get::("count") - .expect("count value"); - assert_eq!(count_after, 0); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn mark_stage1_job_succeeded_no_output_skips_phase2_when_output_was_already_absent() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id, - codex_home.join("workspace"), - )) - .await - .expect("upsert thread"); - - let claim = runtime - .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) - .await - .expect("claim stage1"); - let ownership_token = match claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded_no_output(thread_id, ownership_token.as_str()) - .await - .expect("mark stage1 succeeded without output"), - "stage1 no-output success should complete the job" - ); - - let output_row_count = - sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") - .bind(thread_id.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("load stage1 output count") - .try_get::("count") - .expect("stage1 output count"); - assert_eq!( - output_row_count, 0, - "stage1 no-output success should not persist empty stage1 outputs" - ); - - let up_to_date = runtime - .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) - .await - .expect("claim stage1 up-to-date"); - assert_eq!(up_to_date, Stage1JobClaimOutcome::SkippedUpToDate); - - let global_job_row_count = sqlx::query("SELECT COUNT(*) AS count FROM jobs WHERE kind = ?") - .bind("memory_consolidate_global") - .fetch_one(runtime.pool.as_ref()) - .await - .expect("load phase2 job row count") - .try_get::("count") - .expect("phase2 job row count"); - assert_eq!( - global_job_row_count, 0, - "no-output without an existing stage1 output should not enqueue phase2" - ); - - let claim_phase2 = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim phase2"); - assert_eq!( - claim_phase2, - Phase2JobClaimOutcome::SkippedNotDirty, - "phase2 should remain clean when no-output deleted nothing" - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn mark_stage1_job_succeeded_no_output_enqueues_phase2_when_deleting_output() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id, - codex_home.join("workspace"), - )) - .await - .expect("upsert thread"); - - let first_claim = runtime - .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) - .await - .expect("claim initial stage1"); - let first_token = match first_claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected initial stage1 claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded(thread_id, first_token.as_str(), 100, "raw", "sum", None) - .await - .expect("mark initial stage1 succeeded"), - "initial stage1 success should create stage1 output" - ); - - let phase2_claim = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim phase2 after initial output"); - let (phase2_token, phase2_input_watermark) = match phase2_claim { - Phase2JobClaimOutcome::Claimed { - ownership_token, - input_watermark, - } => (ownership_token, input_watermark), - other => panic!("unexpected phase2 claim after initial output: {other:?}"), - }; - assert_eq!(phase2_input_watermark, 100); - assert!( - runtime - .mark_global_phase2_job_succeeded(phase2_token.as_str(), phase2_input_watermark) - .await - .expect("mark initial phase2 succeeded"), - "initial phase2 success should clear global dirty state" - ); - - let no_output_claim = runtime - .try_claim_stage1_job(thread_id, owner_b, 101, 3600, 64) - .await - .expect("claim stage1 for no-output delete"); - let no_output_token = match no_output_claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected no-output stage1 claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded_no_output(thread_id, no_output_token.as_str()) - .await - .expect("mark stage1 no-output after existing output"), - "no-output should succeed when deleting an existing stage1 output" - ); - - let output_row_count = - sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") - .bind(thread_id.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("load stage1 output count after delete") - .try_get::("count") - .expect("stage1 output count"); - assert_eq!(output_row_count, 0); - - let claim_phase2 = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim phase2 after no-output deletion"); - let (phase2_token, phase2_input_watermark) = match claim_phase2 { - Phase2JobClaimOutcome::Claimed { - ownership_token, - input_watermark, - } => (ownership_token, input_watermark), - other => panic!("unexpected phase2 claim after no-output deletion: {other:?}"), - }; - assert_eq!(phase2_input_watermark, 101); - assert!( - runtime - .mark_global_phase2_job_succeeded(phase2_token.as_str(), phase2_input_watermark) - .await - .expect("mark phase2 succeeded after no-output delete") - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn stage1_retry_exhaustion_does_not_block_newer_watermark() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id, - codex_home.join("workspace"), - )) - .await - .expect("upsert thread"); - - for attempt in 0..3 { - let claim = runtime - .try_claim_stage1_job(thread_id, owner, 100, 3_600, 64) - .await - .expect("claim stage1 for retry exhaustion"); - let ownership_token = match claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!( - "attempt {} should claim stage1 before retries are exhausted: {other:?}", - attempt + 1 - ), - }; - assert!( - runtime - .mark_stage1_job_failed(thread_id, ownership_token.as_str(), "boom", 0) - .await - .expect("mark stage1 failed"), - "attempt {} should decrement retry budget", - attempt + 1 - ); - } - - let exhausted_claim = runtime - .try_claim_stage1_job(thread_id, owner, 100, 3_600, 64) - .await - .expect("claim stage1 after retry exhaustion"); - assert_eq!( - exhausted_claim, - Stage1JobClaimOutcome::SkippedRetryExhausted - ); - - let newer_source_claim = runtime - .try_claim_stage1_job(thread_id, owner, 101, 3_600, 64) - .await - .expect("claim stage1 with newer source watermark"); - assert!( - matches!(newer_source_claim, Stage1JobClaimOutcome::Claimed { .. }), - "newer source watermark should reset retry budget and be claimable" - ); - - let job_row = sqlx::query( - "SELECT retry_remaining, input_watermark FROM jobs WHERE kind = ? AND job_key = ?", - ) - .bind("memory_stage1") - .bind(thread_id.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("load stage1 job row after newer-source claim"); - assert_eq!( - job_row - .try_get::("retry_remaining") - .expect("retry_remaining"), - 3 - ); - assert_eq!( - job_row - .try_get::("input_watermark") - .expect("input_watermark"), - 101 - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn phase2_global_consolidation_reruns_when_watermark_advances() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - - runtime - .enqueue_global_consolidation(100) - .await - .expect("enqueue global consolidation"); - - let claim = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim phase2"); - let (ownership_token, input_watermark) = match claim { - Phase2JobClaimOutcome::Claimed { - ownership_token, - input_watermark, - } => (ownership_token, input_watermark), - other => panic!("unexpected phase2 claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_global_phase2_job_succeeded(ownership_token.as_str(), input_watermark) - .await - .expect("mark phase2 succeeded"), - "phase2 success should finalize for current token" - ); - - let claim_up_to_date = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim phase2 up-to-date"); - assert_eq!(claim_up_to_date, Phase2JobClaimOutcome::SkippedNotDirty); - - runtime - .enqueue_global_consolidation(101) - .await - .expect("enqueue global consolidation again"); - - let claim_rerun = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim phase2 rerun"); - assert!( - matches!(claim_rerun, Phase2JobClaimOutcome::Claimed { .. }), - "advanced watermark should be claimable" - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn list_stage1_outputs_for_global_returns_latest_outputs() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let thread_id_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id_a, - codex_home.join("workspace-a"), - )) - .await - .expect("upsert thread a"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id_b, - codex_home.join("workspace-b"), - )) - .await - .expect("upsert thread b"); - - let claim = runtime - .try_claim_stage1_job(thread_id_a, owner, 100, 3600, 64) - .await - .expect("claim stage1 a"); - let ownership_token = match claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected stage1 claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded( - thread_id_a, - ownership_token.as_str(), - 100, - "raw memory a", - "summary a", - None, - ) - .await - .expect("mark stage1 succeeded a"), - "stage1 success should persist output a" - ); - - let claim = runtime - .try_claim_stage1_job(thread_id_b, owner, 101, 3600, 64) - .await - .expect("claim stage1 b"); - let ownership_token = match claim { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected stage1 claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded( - thread_id_b, - ownership_token.as_str(), - 101, - "raw memory b", - "summary b", - Some("rollout-b"), - ) - .await - .expect("mark stage1 succeeded b"), - "stage1 success should persist output b" - ); - - let outputs = runtime - .list_stage1_outputs_for_global(10) - .await - .expect("list stage1 outputs for global"); - assert_eq!(outputs.len(), 2); - assert_eq!(outputs[0].thread_id, thread_id_b); - assert_eq!(outputs[0].rollout_summary, "summary b"); - assert_eq!(outputs[0].rollout_slug.as_deref(), Some("rollout-b")); - assert_eq!(outputs[0].cwd, codex_home.join("workspace-b")); - assert_eq!(outputs[1].thread_id, thread_id_a); - assert_eq!(outputs[1].rollout_summary, "summary a"); - assert_eq!(outputs[1].rollout_slug, None); - assert_eq!(outputs[1].cwd, codex_home.join("workspace-a")); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn list_stage1_outputs_for_global_skips_empty_payloads() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_id_non_empty = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - let thread_id_empty = - ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id_non_empty, - codex_home.join("workspace-non-empty"), - )) - .await - .expect("upsert non-empty thread"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_id_empty, - codex_home.join("workspace-empty"), - )) - .await - .expect("upsert empty thread"); - - sqlx::query( - r#" -INSERT INTO stage1_outputs (thread_id, source_updated_at, raw_memory, rollout_summary, generated_at) -VALUES (?, ?, ?, ?, ?) - "#, - ) - .bind(thread_id_non_empty.to_string()) - .bind(100_i64) - .bind("raw memory") - .bind("summary") - .bind(100_i64) - .execute(runtime.pool.as_ref()) - .await - .expect("insert non-empty stage1 output"); - sqlx::query( - r#" -INSERT INTO stage1_outputs (thread_id, source_updated_at, raw_memory, rollout_summary, generated_at) -VALUES (?, ?, ?, ?, ?) - "#, - ) - .bind(thread_id_empty.to_string()) - .bind(101_i64) - .bind("") - .bind("") - .bind(101_i64) - .execute(runtime.pool.as_ref()) - .await - .expect("insert empty stage1 output"); - - let outputs = runtime - .list_stage1_outputs_for_global(1) - .await - .expect("list stage1 outputs for global"); - assert_eq!(outputs.len(), 1); - assert_eq!(outputs[0].thread_id, thread_id_non_empty); - assert_eq!(outputs[0].rollout_summary, "summary"); - assert_eq!(outputs[0].cwd, codex_home.join("workspace-non-empty")); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn record_stage1_output_usage_updates_usage_metadata() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id a"); - let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id b"); - let missing = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("missing id"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_a, - codex_home.join("workspace-a"), - )) - .await - .expect("upsert thread a"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_b, - codex_home.join("workspace-b"), - )) - .await - .expect("upsert thread b"); - - let claim_a = runtime - .try_claim_stage1_job(thread_a, owner, 100, 3600, 64) - .await - .expect("claim stage1 a"); - let token_a = match claim_a { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected stage1 claim outcome for a: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded(thread_a, token_a.as_str(), 100, "raw a", "sum a", None) - .await - .expect("mark stage1 succeeded a") - ); - - let claim_b = runtime - .try_claim_stage1_job(thread_b, owner, 101, 3600, 64) - .await - .expect("claim stage1 b"); - let token_b = match claim_b { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected stage1 claim outcome for b: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded(thread_b, token_b.as_str(), 101, "raw b", "sum b", None) - .await - .expect("mark stage1 succeeded b") - ); - - let updated_rows = runtime - .record_stage1_output_usage(&[thread_a, thread_a, thread_b, missing]) - .await - .expect("record stage1 output usage"); - assert_eq!(updated_rows, 3); - - let row_a = - sqlx::query("SELECT usage_count, last_usage FROM stage1_outputs WHERE thread_id = ?") - .bind(thread_a.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("load stage1 usage row a"); - let row_b = - sqlx::query("SELECT usage_count, last_usage FROM stage1_outputs WHERE thread_id = ?") - .bind(thread_b.to_string()) - .fetch_one(runtime.pool.as_ref()) - .await - .expect("load stage1 usage row b"); - - assert_eq!( - row_a - .try_get::("usage_count") - .expect("usage_count a"), - 2 - ); - assert_eq!( - row_b - .try_get::("usage_count") - .expect("usage_count b"), - 1 - ); - - let last_usage_a = row_a.try_get::("last_usage").expect("last_usage a"); - let last_usage_b = row_b.try_get::("last_usage").expect("last_usage b"); - assert_eq!(last_usage_a, last_usage_b); - assert!(last_usage_a > 0); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn mark_stage1_job_succeeded_enqueues_global_consolidation() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id a"); - let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id b"); - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); - - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_a, - codex_home.join("workspace-a"), - )) - .await - .expect("upsert thread a"); - runtime - .upsert_thread(&test_thread_metadata( - &codex_home, - thread_b, - codex_home.join("workspace-b"), - )) - .await - .expect("upsert thread b"); - - let claim_a = runtime - .try_claim_stage1_job(thread_a, owner, 100, 3600, 64) - .await - .expect("claim stage1 a"); - let token_a = match claim_a { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected stage1 claim outcome for thread a: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded( - thread_a, - token_a.as_str(), - 100, - "raw-a", - "summary-a", - None, - ) - .await - .expect("mark stage1 succeeded a"), - "stage1 success should persist output for thread a" - ); - - let claim_b = runtime - .try_claim_stage1_job(thread_b, owner, 101, 3600, 64) - .await - .expect("claim stage1 b"); - let token_b = match claim_b { - Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, - other => panic!("unexpected stage1 claim outcome for thread b: {other:?}"), - }; - assert!( - runtime - .mark_stage1_job_succeeded( - thread_b, - token_b.as_str(), - 101, - "raw-b", - "summary-b", - None, - ) - .await - .expect("mark stage1 succeeded b"), - "stage1 success should persist output for thread b" - ); - - let claim = runtime - .try_claim_global_phase2_job(owner, 3600) - .await - .expect("claim global consolidation"); - let input_watermark = match claim { - Phase2JobClaimOutcome::Claimed { - input_watermark, .. - } => input_watermark, - other => panic!("unexpected global consolidation claim outcome: {other:?}"), - }; - assert_eq!(input_watermark, 101); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn phase2_global_lock_allows_only_one_fresh_runner() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - runtime - .enqueue_global_consolidation(200) - .await - .expect("enqueue global consolidation"); - - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner a"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner b"); - - let running_claim = runtime - .try_claim_global_phase2_job(owner_a, 3600) - .await - .expect("claim global lock"); - assert!( - matches!(running_claim, Phase2JobClaimOutcome::Claimed { .. }), - "first owner should claim global lock" - ); - - let second_claim = runtime - .try_claim_global_phase2_job(owner_b, 3600) - .await - .expect("claim global lock from second owner"); - assert_eq!(second_claim, Phase2JobClaimOutcome::SkippedRunning); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn phase2_global_lock_stale_lease_allows_takeover() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - runtime - .enqueue_global_consolidation(300) - .await - .expect("enqueue global consolidation"); - - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner a"); - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner b"); - - let initial_claim = runtime - .try_claim_global_phase2_job(owner_a, 3600) - .await - .expect("claim initial global lock"); - let token_a = match initial_claim { - Phase2JobClaimOutcome::Claimed { - ownership_token, .. - } => ownership_token, - other => panic!("unexpected initial claim outcome: {other:?}"), - }; - - sqlx::query("UPDATE jobs SET lease_until = ? WHERE kind = ? AND job_key = ?") - .bind(Utc::now().timestamp() - 1) - .bind("memory_consolidate_global") - .bind("global") - .execute(runtime.pool.as_ref()) - .await - .expect("expire global consolidation lease"); - - let takeover_claim = runtime - .try_claim_global_phase2_job(owner_b, 3600) - .await - .expect("claim stale global lock"); - let (token_b, input_watermark) = match takeover_claim { - Phase2JobClaimOutcome::Claimed { - ownership_token, - input_watermark, - } => (ownership_token, input_watermark), - other => panic!("unexpected takeover claim outcome: {other:?}"), - }; - assert_ne!(token_a, token_b); - assert_eq!(input_watermark, 300); - - assert_eq!( - runtime - .mark_global_phase2_job_succeeded(token_a.as_str(), 300) - .await - .expect("mark stale owner success result"), - false, - "stale owner should lose finalization ownership after takeover" - ); - assert!( - runtime - .mark_global_phase2_job_succeeded(token_b.as_str(), 300) - .await - .expect("mark takeover owner success"), - "takeover owner should finalize consolidation" - ); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn phase2_backfilled_inputs_below_last_success_still_become_dirty() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - runtime - .enqueue_global_consolidation(500) - .await - .expect("enqueue initial consolidation"); - let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner a"); - let claim_a = runtime - .try_claim_global_phase2_job(owner_a, 3_600) - .await - .expect("claim initial consolidation"); - let token_a = match claim_a { - Phase2JobClaimOutcome::Claimed { - ownership_token, - input_watermark, - } => { - assert_eq!(input_watermark, 500); - ownership_token - } - other => panic!("unexpected initial phase2 claim outcome: {other:?}"), - }; - assert!( - runtime - .mark_global_phase2_job_succeeded(token_a.as_str(), 500) - .await - .expect("mark initial phase2 success"), - "initial phase2 success should finalize" - ); - - runtime - .enqueue_global_consolidation(400) - .await - .expect("enqueue backfilled consolidation"); - - let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner b"); - let claim_b = runtime - .try_claim_global_phase2_job(owner_b, 3_600) - .await - .expect("claim backfilled consolidation"); - match claim_b { - Phase2JobClaimOutcome::Claimed { - input_watermark, .. - } => { - assert!( - input_watermark > 500, - "backfilled enqueue should advance dirty watermark beyond last success" - ); - } - other => panic!("unexpected backfilled phase2 claim outcome: {other:?}"), - } - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn phase2_failure_fallback_updates_unowned_running_job() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - runtime - .enqueue_global_consolidation(400) - .await - .expect("enqueue global consolidation"); - - let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner"); - let claim = runtime - .try_claim_global_phase2_job(owner, 3_600) - .await - .expect("claim global consolidation"); - let ownership_token = match claim { - Phase2JobClaimOutcome::Claimed { - ownership_token, .. - } => ownership_token, - other => panic!("unexpected claim outcome: {other:?}"), - }; - - sqlx::query("UPDATE jobs SET ownership_token = NULL WHERE kind = ? AND job_key = ?") - .bind("memory_consolidate_global") - .bind("global") - .execute(runtime.pool.as_ref()) - .await - .expect("clear ownership token"); - - assert_eq!( - runtime - .mark_global_phase2_job_failed(ownership_token.as_str(), "lost", 3_600) - .await - .expect("mark phase2 failed with strict ownership"), - false, - "strict failure update should not match unowned running job" - ); - assert!( - runtime - .mark_global_phase2_job_failed_if_unowned(ownership_token.as_str(), "lost", 3_600) - .await - .expect("fallback failure update should match unowned running job"), - "fallback failure update should transition the unowned running job" - ); - - let claim = runtime - .try_claim_global_phase2_job(ThreadId::new(), 3_600) - .await - .expect("claim after fallback failure"); - assert_eq!(claim, Phase2JobClaimOutcome::SkippedNotDirty); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn query_logs_with_search_matches_substring() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - runtime - .insert_logs(&[ - LogEntry { - ts: 1_700_000_001, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some("alpha".to_string()), - thread_id: Some("thread-1".to_string()), - process_uuid: None, - file: Some("main.rs".to_string()), - line: Some(42), - module_path: None, - }, - LogEntry { - ts: 1_700_000_002, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some("alphabet".to_string()), - thread_id: Some("thread-1".to_string()), - process_uuid: None, - file: Some("main.rs".to_string()), - line: Some(43), - module_path: None, - }, - ]) - .await - .expect("insert test logs"); - - let rows = runtime - .query_logs(&LogQuery { - search: Some("alphab".to_string()), - ..Default::default() - }) - .await - .expect("query matching logs"); - - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].message.as_deref(), Some("alphabet")); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn insert_logs_prunes_old_rows_when_thread_exceeds_size_limit() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let six_mebibytes = "a".repeat(6 * 1024 * 1024); - runtime - .insert_logs(&[ - LogEntry { - ts: 1, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes.clone()), - thread_id: Some("thread-1".to_string()), - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(1), - module_path: Some("mod".to_string()), - }, - LogEntry { - ts: 2, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes.clone()), - thread_id: Some("thread-1".to_string()), - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(2), - module_path: Some("mod".to_string()), - }, - ]) - .await - .expect("insert test logs"); - - let rows = runtime - .query_logs(&LogQuery { - thread_ids: vec!["thread-1".to_string()], - ..Default::default() - }) - .await - .expect("query thread logs"); - - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].ts, 2); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn insert_logs_prunes_single_thread_row_when_it_exceeds_size_limit() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let eleven_mebibytes = "d".repeat(11 * 1024 * 1024); - runtime - .insert_logs(&[LogEntry { - ts: 1, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(eleven_mebibytes), - thread_id: Some("thread-oversized".to_string()), - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(1), - module_path: Some("mod".to_string()), - }]) - .await - .expect("insert test log"); - - let rows = runtime - .query_logs(&LogQuery { - thread_ids: vec!["thread-oversized".to_string()], - ..Default::default() - }) - .await - .expect("query thread logs"); - - assert!(rows.is_empty()); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn insert_logs_prunes_threadless_rows_per_process_uuid_only() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let six_mebibytes = "b".repeat(6 * 1024 * 1024); - runtime - .insert_logs(&[ - LogEntry { - ts: 1, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes.clone()), - thread_id: None, - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(1), - module_path: Some("mod".to_string()), - }, - LogEntry { - ts: 2, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes.clone()), - thread_id: None, - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(2), - module_path: Some("mod".to_string()), - }, - LogEntry { - ts: 3, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes), - thread_id: Some("thread-1".to_string()), - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(3), - module_path: Some("mod".to_string()), - }, - ]) - .await - .expect("insert test logs"); - - let rows = runtime - .query_logs(&LogQuery { - thread_ids: vec!["thread-1".to_string()], - include_threadless: true, - ..Default::default() - }) - .await - .expect("query thread and threadless logs"); - - let mut timestamps: Vec = rows.into_iter().map(|row| row.ts).collect(); - timestamps.sort_unstable(); - assert_eq!(timestamps, vec![2, 3]); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn insert_logs_prunes_single_threadless_process_row_when_it_exceeds_size_limit() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let eleven_mebibytes = "e".repeat(11 * 1024 * 1024); - runtime - .insert_logs(&[LogEntry { - ts: 1, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(eleven_mebibytes), - thread_id: None, - process_uuid: Some("proc-oversized".to_string()), - file: Some("main.rs".to_string()), - line: Some(1), - module_path: Some("mod".to_string()), - }]) - .await - .expect("insert test log"); - - let rows = runtime - .query_logs(&LogQuery { - include_threadless: true, - ..Default::default() - }) - .await - .expect("query threadless logs"); - - assert!(rows.is_empty()); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn insert_logs_prunes_threadless_rows_with_null_process_uuid() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let six_mebibytes = "c".repeat(6 * 1024 * 1024); - runtime - .insert_logs(&[ - LogEntry { - ts: 1, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes.clone()), - thread_id: None, - process_uuid: None, - file: Some("main.rs".to_string()), - line: Some(1), - module_path: Some("mod".to_string()), - }, - LogEntry { - ts: 2, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(six_mebibytes), - thread_id: None, - process_uuid: None, - file: Some("main.rs".to_string()), - line: Some(2), - module_path: Some("mod".to_string()), - }, - LogEntry { - ts: 3, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some("small".to_string()), - thread_id: None, - process_uuid: Some("proc-1".to_string()), - file: Some("main.rs".to_string()), - line: Some(3), - module_path: Some("mod".to_string()), - }, - ]) - .await - .expect("insert test logs"); - - let rows = runtime - .query_logs(&LogQuery { - include_threadless: true, - ..Default::default() - }) - .await - .expect("query threadless logs"); - - let mut timestamps: Vec = rows.into_iter().map(|row| row.ts).collect(); - timestamps.sort_unstable(); - assert_eq!(timestamps, vec![2, 3]); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - #[tokio::test] - async fn insert_logs_prunes_single_threadless_null_process_row_when_it_exceeds_limit() { - let codex_home = unique_temp_dir(); - let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) - .await - .expect("initialize runtime"); - - let eleven_mebibytes = "f".repeat(11 * 1024 * 1024); - runtime - .insert_logs(&[LogEntry { - ts: 1, - ts_nanos: 0, - level: "INFO".to_string(), - target: "cli".to_string(), - message: Some(eleven_mebibytes), - thread_id: None, - process_uuid: None, - file: Some("main.rs".to_string()), - line: Some(1), - module_path: Some("mod".to_string()), - }]) - .await - .expect("insert test log"); - - let rows = runtime - .query_logs(&LogQuery { - include_threadless: true, - ..Default::default() - }) - .await - .expect("query threadless logs"); - - assert!(rows.is_empty()); - - let _ = tokio::fs::remove_dir_all(codex_home).await; - } - - fn test_thread_metadata( - codex_home: &Path, - thread_id: ThreadId, - cwd: PathBuf, - ) -> ThreadMetadata { - let now = DateTime::::from_timestamp(1_700_000_000, 0).expect("timestamp"); - ThreadMetadata { - id: thread_id, - rollout_path: codex_home.join(format!("rollout-{thread_id}.jsonl")), - created_at: now, - updated_at: now, - source: "cli".to_string(), - agent_nickname: None, - agent_role: None, - model_provider: "test-provider".to_string(), - cwd, - cli_version: "0.0.0".to_string(), - title: String::new(), - sandbox_policy: crate::extract::enum_to_string(&SandboxPolicy::new_read_only_policy()), - approval_mode: crate::extract::enum_to_string(&AskForApproval::OnRequest), - tokens_used: 0, - first_user_message: Some("hello".to_string()), - archived_at: None, - git_sha: None, - git_branch: None, - git_origin_url: None, - } - } -} diff --git a/codex-rs/state/src/runtime/agent_jobs.rs b/codex-rs/state/src/runtime/agent_jobs.rs new file mode 100644 index 0000000000..c685605945 --- /dev/null +++ b/codex-rs/state/src/runtime/agent_jobs.rs @@ -0,0 +1,562 @@ +use super::*; +use crate::model::AgentJobItemRow; + +impl StateRuntime { + pub async fn create_agent_job( + &self, + params: &AgentJobCreateParams, + items: &[AgentJobItemCreateParams], + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let input_headers_json = serde_json::to_string(¶ms.input_headers)?; + let output_schema_json = params + .output_schema_json + .as_ref() + .map(serde_json::to_string) + .transpose()?; + let max_runtime_seconds = params + .max_runtime_seconds + .map(i64::try_from) + .transpose() + .map_err(|_| anyhow::anyhow!("invalid max_runtime_seconds value"))?; + let mut tx = self.pool.begin().await?; + sqlx::query( + r#" +INSERT INTO agent_jobs ( + id, + name, + status, + instruction, + auto_export, + max_runtime_seconds, + output_schema_json, + input_headers_json, + input_csv_path, + output_csv_path, + created_at, + updated_at, + started_at, + completed_at, + last_error +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL) + "#, + ) + .bind(params.id.as_str()) + .bind(params.name.as_str()) + .bind(AgentJobStatus::Pending.as_str()) + .bind(params.instruction.as_str()) + .bind(i64::from(params.auto_export)) + .bind(max_runtime_seconds) + .bind(output_schema_json) + .bind(input_headers_json) + .bind(params.input_csv_path.as_str()) + .bind(params.output_csv_path.as_str()) + .bind(now) + .bind(now) + .execute(&mut *tx) + .await?; + + for item in items { + let row_json = serde_json::to_string(&item.row_json)?; + sqlx::query( + r#" +INSERT INTO agent_job_items ( + job_id, + item_id, + row_index, + source_id, + row_json, + status, + assigned_thread_id, + attempt_count, + result_json, + last_error, + created_at, + updated_at, + completed_at, + reported_at +) VALUES (?, ?, ?, ?, ?, ?, NULL, 0, NULL, NULL, ?, ?, NULL, NULL) + "#, + ) + .bind(params.id.as_str()) + .bind(item.item_id.as_str()) + .bind(item.row_index) + .bind(item.source_id.as_deref()) + .bind(row_json) + .bind(AgentJobItemStatus::Pending.as_str()) + .bind(now) + .bind(now) + .execute(&mut *tx) + .await?; + } + + tx.commit().await?; + + let job_id = params.id.as_str(); + self.get_agent_job(job_id) + .await? + .ok_or_else(|| anyhow::anyhow!("failed to load created agent job {job_id}")) + } + + pub async fn get_agent_job(&self, job_id: &str) -> anyhow::Result> { + let row = sqlx::query_as::<_, AgentJobRow>( + r#" +SELECT + id, + name, + status, + instruction, + auto_export, + max_runtime_seconds, + output_schema_json, + input_headers_json, + input_csv_path, + output_csv_path, + created_at, + updated_at, + started_at, + completed_at, + last_error +FROM agent_jobs +WHERE id = ? + "#, + ) + .bind(job_id) + .fetch_optional(self.pool.as_ref()) + .await?; + row.map(AgentJob::try_from).transpose() + } + + pub async fn list_agent_job_items( + &self, + job_id: &str, + status: Option, + limit: Option, + ) -> anyhow::Result> { + let mut builder = QueryBuilder::::new( + r#" +SELECT + job_id, + item_id, + row_index, + source_id, + row_json, + status, + assigned_thread_id, + attempt_count, + result_json, + last_error, + created_at, + updated_at, + completed_at, + reported_at +FROM agent_job_items +WHERE job_id = + "#, + ); + builder.push_bind(job_id); + if let Some(status) = status { + builder.push(" AND status = "); + builder.push_bind(status.as_str()); + } + builder.push(" ORDER BY row_index ASC"); + if let Some(limit) = limit { + builder.push(" LIMIT "); + builder.push_bind(limit as i64); + } + let rows: Vec = builder + .build_query_as::() + .fetch_all(self.pool.as_ref()) + .await?; + rows.into_iter().map(AgentJobItem::try_from).collect() + } + + pub async fn get_agent_job_item( + &self, + job_id: &str, + item_id: &str, + ) -> anyhow::Result> { + let row: Option = sqlx::query_as::<_, AgentJobItemRow>( + r#" +SELECT + job_id, + item_id, + row_index, + source_id, + row_json, + status, + assigned_thread_id, + attempt_count, + result_json, + last_error, + created_at, + updated_at, + completed_at, + reported_at +FROM agent_job_items +WHERE job_id = ? AND item_id = ? + "#, + ) + .bind(job_id) + .bind(item_id) + .fetch_optional(self.pool.as_ref()) + .await?; + row.map(AgentJobItem::try_from).transpose() + } + + pub async fn mark_agent_job_running(&self, job_id: &str) -> anyhow::Result<()> { + let now = Utc::now().timestamp(); + sqlx::query( + r#" +UPDATE agent_jobs +SET + status = ?, + updated_at = ?, + started_at = COALESCE(started_at, ?), + completed_at = NULL, + last_error = NULL +WHERE id = ? + "#, + ) + .bind(AgentJobStatus::Running.as_str()) + .bind(now) + .bind(now) + .bind(job_id) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + pub async fn mark_agent_job_completed(&self, job_id: &str) -> anyhow::Result<()> { + let now = Utc::now().timestamp(); + sqlx::query( + r#" +UPDATE agent_jobs +SET status = ?, updated_at = ?, completed_at = ?, last_error = NULL +WHERE id = ? + "#, + ) + .bind(AgentJobStatus::Completed.as_str()) + .bind(now) + .bind(now) + .bind(job_id) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + pub async fn mark_agent_job_failed( + &self, + job_id: &str, + error_message: &str, + ) -> anyhow::Result<()> { + let now = Utc::now().timestamp(); + sqlx::query( + r#" +UPDATE agent_jobs +SET status = ?, updated_at = ?, completed_at = ?, last_error = ? +WHERE id = ? + "#, + ) + .bind(AgentJobStatus::Failed.as_str()) + .bind(now) + .bind(now) + .bind(error_message) + .bind(job_id) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + pub async fn mark_agent_job_cancelled( + &self, + job_id: &str, + reason: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_jobs +SET status = ?, updated_at = ?, completed_at = ?, last_error = ? +WHERE id = ? AND status IN (?, ?) + "#, + ) + .bind(AgentJobStatus::Cancelled.as_str()) + .bind(now) + .bind(now) + .bind(reason) + .bind(job_id) + .bind(AgentJobStatus::Pending.as_str()) + .bind(AgentJobStatus::Running.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn is_agent_job_cancelled(&self, job_id: &str) -> anyhow::Result { + let row = sqlx::query( + r#" +SELECT status +FROM agent_jobs +WHERE id = ? + "#, + ) + .bind(job_id) + .fetch_optional(self.pool.as_ref()) + .await?; + let Some(row) = row else { + return Ok(false); + }; + let status: String = row.try_get("status")?; + Ok(AgentJobStatus::parse(status.as_str())? == AgentJobStatus::Cancelled) + } + + pub async fn mark_agent_job_item_running( + &self, + job_id: &str, + item_id: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET + status = ?, + assigned_thread_id = NULL, + attempt_count = attempt_count + 1, + updated_at = ?, + last_error = NULL +WHERE job_id = ? AND item_id = ? AND status = ? + "#, + ) + .bind(AgentJobItemStatus::Running.as_str()) + .bind(now) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Pending.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn mark_agent_job_item_running_with_thread( + &self, + job_id: &str, + item_id: &str, + thread_id: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET + status = ?, + assigned_thread_id = ?, + attempt_count = attempt_count + 1, + updated_at = ?, + last_error = NULL +WHERE job_id = ? AND item_id = ? AND status = ? + "#, + ) + .bind(AgentJobItemStatus::Running.as_str()) + .bind(thread_id) + .bind(now) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Pending.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn mark_agent_job_item_pending( + &self, + job_id: &str, + item_id: &str, + error_message: Option<&str>, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET + status = ?, + assigned_thread_id = NULL, + updated_at = ?, + last_error = ? +WHERE job_id = ? AND item_id = ? AND status = ? + "#, + ) + .bind(AgentJobItemStatus::Pending.as_str()) + .bind(now) + .bind(error_message) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Running.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn set_agent_job_item_thread( + &self, + job_id: &str, + item_id: &str, + thread_id: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET assigned_thread_id = ?, updated_at = ? +WHERE job_id = ? AND item_id = ? AND status = ? + "#, + ) + .bind(thread_id) + .bind(now) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Running.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn report_agent_job_item_result( + &self, + job_id: &str, + item_id: &str, + reporting_thread_id: &str, + result_json: &Value, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let serialized = serde_json::to_string(result_json)?; + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET + result_json = ?, + reported_at = ?, + updated_at = ?, + last_error = NULL +WHERE + job_id = ? + AND item_id = ? + AND status = ? + AND assigned_thread_id = ? + "#, + ) + .bind(serialized) + .bind(now) + .bind(now) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Running.as_str()) + .bind(reporting_thread_id) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn mark_agent_job_item_completed( + &self, + job_id: &str, + item_id: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET + status = ?, + completed_at = ?, + updated_at = ?, + assigned_thread_id = NULL +WHERE + job_id = ? + AND item_id = ? + AND status = ? + AND result_json IS NOT NULL + "#, + ) + .bind(AgentJobItemStatus::Completed.as_str()) + .bind(now) + .bind(now) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Running.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn mark_agent_job_item_failed( + &self, + job_id: &str, + item_id: &str, + error_message: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let result = sqlx::query( + r#" +UPDATE agent_job_items +SET + status = ?, + completed_at = ?, + updated_at = ?, + last_error = ?, + assigned_thread_id = NULL +WHERE + job_id = ? + AND item_id = ? + AND status = ? + "#, + ) + .bind(AgentJobItemStatus::Failed.as_str()) + .bind(now) + .bind(now) + .bind(error_message) + .bind(job_id) + .bind(item_id) + .bind(AgentJobItemStatus::Running.as_str()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + pub async fn get_agent_job_progress(&self, job_id: &str) -> anyhow::Result { + let row = sqlx::query( + r#" +SELECT + COUNT(*) AS total_items, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS pending_items, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS running_items, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS completed_items, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS failed_items +FROM agent_job_items +WHERE job_id = ? + "#, + ) + .bind(AgentJobItemStatus::Pending.as_str()) + .bind(AgentJobItemStatus::Running.as_str()) + .bind(AgentJobItemStatus::Completed.as_str()) + .bind(AgentJobItemStatus::Failed.as_str()) + .bind(job_id) + .fetch_one(self.pool.as_ref()) + .await?; + + let total_items: i64 = row.try_get("total_items")?; + let pending_items: Option = row.try_get("pending_items")?; + let running_items: Option = row.try_get("running_items")?; + let completed_items: Option = row.try_get("completed_items")?; + let failed_items: Option = row.try_get("failed_items")?; + Ok(AgentJobProgress { + total_items: usize::try_from(total_items).unwrap_or_default(), + pending_items: usize::try_from(pending_items.unwrap_or_default()).unwrap_or_default(), + running_items: usize::try_from(running_items.unwrap_or_default()).unwrap_or_default(), + completed_items: usize::try_from(completed_items.unwrap_or_default()) + .unwrap_or_default(), + failed_items: usize::try_from(failed_items.unwrap_or_default()).unwrap_or_default(), + }) + } +} diff --git a/codex-rs/state/src/runtime/backfill.rs b/codex-rs/state/src/runtime/backfill.rs new file mode 100644 index 0000000000..93e1569872 --- /dev/null +++ b/codex-rs/state/src/runtime/backfill.rs @@ -0,0 +1,311 @@ +use super::*; + +impl StateRuntime { + pub async fn get_backfill_state(&self) -> anyhow::Result { + self.ensure_backfill_state_row().await?; + let row = sqlx::query( + r#" +SELECT status, last_watermark, last_success_at +FROM backfill_state +WHERE id = 1 + "#, + ) + .fetch_one(self.pool.as_ref()) + .await?; + crate::BackfillState::try_from_row(&row) + } + + /// Attempt to claim ownership of rollout metadata backfill. + /// + /// Returns `true` when this runtime claimed the backfill worker slot. + /// Returns `false` if backfill is already complete or currently owned by a + /// non-expired worker. + pub async fn try_claim_backfill(&self, lease_seconds: i64) -> anyhow::Result { + self.ensure_backfill_state_row().await?; + let now = Utc::now().timestamp(); + let lease_cutoff = now.saturating_sub(lease_seconds.max(0)); + let result = sqlx::query( + r#" +UPDATE backfill_state +SET status = ?, updated_at = ? +WHERE id = 1 + AND status != ? + AND (status != ? OR updated_at <= ?) + "#, + ) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(now) + .bind(crate::BackfillStatus::Complete.as_str()) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(lease_cutoff) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() == 1) + } + + /// Mark rollout metadata backfill as running. + pub async fn mark_backfill_running(&self) -> anyhow::Result<()> { + self.ensure_backfill_state_row().await?; + sqlx::query( + r#" +UPDATE backfill_state +SET status = ?, updated_at = ? +WHERE id = 1 + "#, + ) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(Utc::now().timestamp()) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + /// Persist rollout metadata backfill progress. + pub async fn checkpoint_backfill(&self, watermark: &str) -> anyhow::Result<()> { + self.ensure_backfill_state_row().await?; + sqlx::query( + r#" +UPDATE backfill_state +SET status = ?, last_watermark = ?, updated_at = ? +WHERE id = 1 + "#, + ) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(watermark) + .bind(Utc::now().timestamp()) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + /// Mark rollout metadata backfill as complete. + pub async fn mark_backfill_complete(&self, last_watermark: Option<&str>) -> anyhow::Result<()> { + self.ensure_backfill_state_row().await?; + let now = Utc::now().timestamp(); + sqlx::query( + r#" +UPDATE backfill_state +SET + status = ?, + last_watermark = COALESCE(?, last_watermark), + last_success_at = ?, + updated_at = ? +WHERE id = 1 + "#, + ) + .bind(crate::BackfillStatus::Complete.as_str()) + .bind(last_watermark) + .bind(now) + .bind(now) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } + + async fn ensure_backfill_state_row(&self) -> anyhow::Result<()> { + sqlx::query( + r#" +INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at) +VALUES (?, ?, NULL, NULL, ?) +ON CONFLICT(id) DO NOTHING + "#, + ) + .bind(1_i64) + .bind(crate::BackfillStatus::Pending.as_str()) + .bind(Utc::now().timestamp()) + .execute(self.pool.as_ref()) + .await?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::StateRuntime; + use super::state_db_filename; + use super::test_support::unique_temp_dir; + use crate::STATE_DB_FILENAME; + use crate::STATE_DB_VERSION; + use chrono::Utc; + use pretty_assertions::assert_eq; + + #[tokio::test] + async fn init_removes_legacy_state_db_files() { + let codex_home = unique_temp_dir(); + tokio::fs::create_dir_all(&codex_home) + .await + .expect("create codex_home"); + + let current_name = state_db_filename(); + let previous_version = STATE_DB_VERSION.saturating_sub(1); + let unversioned_name = format!("{STATE_DB_FILENAME}.sqlite"); + for suffix in ["", "-wal", "-shm", "-journal"] { + let path = codex_home.join(format!("{unversioned_name}{suffix}")); + tokio::fs::write(path, b"legacy") + .await + .expect("write legacy"); + let old_version_path = codex_home.join(format!( + "{STATE_DB_FILENAME}_{previous_version}.sqlite{suffix}" + )); + tokio::fs::write(old_version_path, b"old_version") + .await + .expect("write old version"); + } + let unrelated_path = codex_home.join("state.sqlite_backup"); + tokio::fs::write(&unrelated_path, b"keep") + .await + .expect("write unrelated"); + let numeric_path = codex_home.join("123"); + tokio::fs::write(&numeric_path, b"keep") + .await + .expect("write numeric"); + + let _runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + for suffix in ["", "-wal", "-shm", "-journal"] { + let legacy_path = codex_home.join(format!("{unversioned_name}{suffix}")); + assert_eq!( + tokio::fs::try_exists(&legacy_path) + .await + .expect("check legacy path"), + false + ); + let old_version_path = codex_home.join(format!( + "{STATE_DB_FILENAME}_{previous_version}.sqlite{suffix}" + )); + assert_eq!( + tokio::fs::try_exists(&old_version_path) + .await + .expect("check old version path"), + false + ); + } + assert_eq!( + tokio::fs::try_exists(codex_home.join(current_name)) + .await + .expect("check new db path"), + true + ); + assert_eq!( + tokio::fs::try_exists(&unrelated_path) + .await + .expect("check unrelated path"), + true + ); + assert_eq!( + tokio::fs::try_exists(&numeric_path) + .await + .expect("check numeric path"), + true + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn backfill_state_persists_progress_and_completion() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let initial = runtime + .get_backfill_state() + .await + .expect("get initial backfill state"); + assert_eq!(initial.status, crate::BackfillStatus::Pending); + assert_eq!(initial.last_watermark, None); + assert_eq!(initial.last_success_at, None); + + runtime + .mark_backfill_running() + .await + .expect("mark backfill running"); + runtime + .checkpoint_backfill("sessions/2026/01/27/rollout-a.jsonl") + .await + .expect("checkpoint backfill"); + + let running = runtime + .get_backfill_state() + .await + .expect("get running backfill state"); + assert_eq!(running.status, crate::BackfillStatus::Running); + assert_eq!( + running.last_watermark, + Some("sessions/2026/01/27/rollout-a.jsonl".to_string()) + ); + assert_eq!(running.last_success_at, None); + + runtime + .mark_backfill_complete(Some("sessions/2026/01/28/rollout-b.jsonl")) + .await + .expect("mark backfill complete"); + let completed = runtime + .get_backfill_state() + .await + .expect("get completed backfill state"); + assert_eq!(completed.status, crate::BackfillStatus::Complete); + assert_eq!( + completed.last_watermark, + Some("sessions/2026/01/28/rollout-b.jsonl".to_string()) + ); + assert!(completed.last_success_at.is_some()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn backfill_claim_is_singleton_until_stale_and_blocked_when_complete() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let claimed = runtime + .try_claim_backfill(3600) + .await + .expect("initial backfill claim"); + assert_eq!(claimed, true); + + let duplicate_claim = runtime + .try_claim_backfill(3600) + .await + .expect("duplicate backfill claim"); + assert_eq!(duplicate_claim, false); + + let stale_updated_at = Utc::now().timestamp().saturating_sub(10_000); + sqlx::query( + r#" +UPDATE backfill_state +SET status = ?, updated_at = ? +WHERE id = 1 + "#, + ) + .bind(crate::BackfillStatus::Running.as_str()) + .bind(stale_updated_at) + .execute(runtime.pool.as_ref()) + .await + .expect("force stale backfill lease"); + + let stale_claim = runtime + .try_claim_backfill(10) + .await + .expect("stale backfill claim"); + assert_eq!(stale_claim, true); + + runtime + .mark_backfill_complete(None) + .await + .expect("mark complete"); + let claim_after_complete = runtime + .try_claim_backfill(3600) + .await + .expect("claim after complete"); + assert_eq!(claim_after_complete, false); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } +} diff --git a/codex-rs/state/src/runtime/logs.rs b/codex-rs/state/src/runtime/logs.rs new file mode 100644 index 0000000000..2ee8940afd --- /dev/null +++ b/codex-rs/state/src/runtime/logs.rs @@ -0,0 +1,1106 @@ +use super::*; + +impl StateRuntime { + pub async fn insert_log(&self, entry: &LogEntry) -> anyhow::Result<()> { + self.insert_logs(std::slice::from_ref(entry)).await + } + + /// Insert a batch of log entries into the logs table. + pub async fn insert_logs(&self, entries: &[LogEntry]) -> anyhow::Result<()> { + if entries.is_empty() { + return Ok(()); + } + + let mut tx = self.pool.begin().await?; + let mut builder = QueryBuilder::::new( + "INSERT INTO logs (ts, ts_nanos, level, target, message, thread_id, process_uuid, module_path, file, line, estimated_bytes) ", + ); + builder.push_values(entries, |mut row, entry| { + let estimated_bytes = entry.message.as_ref().map_or(0, String::len) as i64 + + entry.level.len() as i64 + + entry.target.len() as i64 + + entry.module_path.as_ref().map_or(0, String::len) as i64 + + entry.file.as_ref().map_or(0, String::len) as i64; + row.push_bind(entry.ts) + .push_bind(entry.ts_nanos) + .push_bind(&entry.level) + .push_bind(&entry.target) + .push_bind(&entry.message) + .push_bind(&entry.thread_id) + .push_bind(&entry.process_uuid) + .push_bind(&entry.module_path) + .push_bind(&entry.file) + .push_bind(entry.line) + .push_bind(estimated_bytes); + }); + builder.build().execute(&mut *tx).await?; + self.prune_logs_after_insert(entries, &mut tx).await?; + tx.commit().await?; + Ok(()) + } + + /// Enforce per-partition log size caps after a successful batch insert. + /// + /// We maintain two independent budgets: + /// - Thread logs: rows with `thread_id IS NOT NULL`, capped per `thread_id`. + /// - Threadless process logs: rows with `thread_id IS NULL` ("threadless"), + /// capped per `process_uuid` (including `process_uuid IS NULL` as its own + /// threadless partition). + /// + /// "Threadless" means the log row is not associated with any conversation + /// thread, so retention is keyed by process identity instead. + /// + /// This runs inside the same transaction as the insert so callers never + /// observe "inserted but not yet pruned" rows. + async fn prune_logs_after_insert( + &self, + entries: &[LogEntry], + tx: &mut SqliteConnection, + ) -> anyhow::Result<()> { + let thread_ids: BTreeSet<&str> = entries + .iter() + .filter_map(|entry| entry.thread_id.as_deref()) + .collect(); + if !thread_ids.is_empty() { + // Cheap precheck: only run the heavier window-function prune for + // threads that are currently above the cap. + let mut over_limit_threads_query = + QueryBuilder::::new("SELECT thread_id FROM logs WHERE thread_id IN ("); + { + let mut separated = over_limit_threads_query.separated(", "); + for thread_id in &thread_ids { + separated.push_bind(*thread_id); + } + } + over_limit_threads_query.push(") GROUP BY thread_id HAVING SUM("); + over_limit_threads_query.push("estimated_bytes"); + over_limit_threads_query.push(") > "); + over_limit_threads_query.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); + let over_limit_thread_ids: Vec = over_limit_threads_query + .build() + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.try_get("thread_id")) + .collect::>()?; + if !over_limit_thread_ids.is_empty() { + // Enforce a strict per-thread cap by deleting every row whose + // newest-first cumulative bytes exceed the partition budget. + let mut prune_threads = QueryBuilder::::new( + r#" +DELETE FROM logs +WHERE id IN ( + SELECT id + FROM ( + SELECT + id, + SUM( +"#, + ); + prune_threads.push("estimated_bytes"); + prune_threads.push( + r#" + ) OVER ( + PARTITION BY thread_id + ORDER BY ts DESC, ts_nanos DESC, id DESC + ) AS cumulative_bytes + FROM logs + WHERE thread_id IN ( +"#, + ); + { + let mut separated = prune_threads.separated(", "); + for thread_id in &over_limit_thread_ids { + separated.push_bind(thread_id); + } + } + prune_threads.push( + r#" + ) + ) + WHERE cumulative_bytes > +"#, + ); + prune_threads.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); + prune_threads.push("\n)"); + prune_threads.build().execute(&mut *tx).await?; + } + } + + let threadless_process_uuids: BTreeSet<&str> = entries + .iter() + .filter(|entry| entry.thread_id.is_none()) + .filter_map(|entry| entry.process_uuid.as_deref()) + .collect(); + let has_threadless_null_process_uuid = entries + .iter() + .any(|entry| entry.thread_id.is_none() && entry.process_uuid.is_none()); + if !threadless_process_uuids.is_empty() { + // Threadless logs are budgeted separately per process UUID. + let mut over_limit_processes_query = QueryBuilder::::new( + "SELECT process_uuid FROM logs WHERE thread_id IS NULL AND process_uuid IN (", + ); + { + let mut separated = over_limit_processes_query.separated(", "); + for process_uuid in &threadless_process_uuids { + separated.push_bind(*process_uuid); + } + } + over_limit_processes_query.push(") GROUP BY process_uuid HAVING SUM("); + over_limit_processes_query.push("estimated_bytes"); + over_limit_processes_query.push(") > "); + over_limit_processes_query.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); + let over_limit_process_uuids: Vec = over_limit_processes_query + .build() + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| row.try_get("process_uuid")) + .collect::>()?; + if !over_limit_process_uuids.is_empty() { + // Same strict cap policy as thread pruning, but only for + // threadless rows in the affected process UUIDs. + let mut prune_threadless_process_logs = QueryBuilder::::new( + r#" +DELETE FROM logs +WHERE id IN ( + SELECT id + FROM ( + SELECT + id, + SUM( +"#, + ); + prune_threadless_process_logs.push("estimated_bytes"); + prune_threadless_process_logs.push( + r#" + ) OVER ( + PARTITION BY process_uuid + ORDER BY ts DESC, ts_nanos DESC, id DESC + ) AS cumulative_bytes + FROM logs + WHERE thread_id IS NULL + AND process_uuid IN ( +"#, + ); + { + let mut separated = prune_threadless_process_logs.separated(", "); + for process_uuid in &over_limit_process_uuids { + separated.push_bind(process_uuid); + } + } + prune_threadless_process_logs.push( + r#" + ) + ) + WHERE cumulative_bytes > +"#, + ); + prune_threadless_process_logs.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); + prune_threadless_process_logs.push("\n)"); + prune_threadless_process_logs + .build() + .execute(&mut *tx) + .await?; + } + } + if has_threadless_null_process_uuid { + // Rows without a process UUID still need a cap; treat NULL as its + // own threadless partition. + let mut null_process_usage_query = QueryBuilder::::new("SELECT SUM("); + null_process_usage_query.push("estimated_bytes"); + null_process_usage_query.push( + ") AS total_bytes FROM logs WHERE thread_id IS NULL AND process_uuid IS NULL", + ); + let total_null_process_bytes: Option = null_process_usage_query + .build() + .fetch_one(&mut *tx) + .await? + .try_get("total_bytes")?; + + if total_null_process_bytes.unwrap_or(0) > LOG_PARTITION_SIZE_LIMIT_BYTES { + let mut prune_threadless_null_process_logs = QueryBuilder::::new( + r#" +DELETE FROM logs +WHERE id IN ( + SELECT id + FROM ( + SELECT + id, + SUM( +"#, + ); + prune_threadless_null_process_logs.push("estimated_bytes"); + prune_threadless_null_process_logs.push( + r#" + ) OVER ( + PARTITION BY process_uuid + ORDER BY ts DESC, ts_nanos DESC, id DESC + ) AS cumulative_bytes + FROM logs + WHERE thread_id IS NULL + AND process_uuid IS NULL + ) + WHERE cumulative_bytes > +"#, + ); + prune_threadless_null_process_logs.push_bind(LOG_PARTITION_SIZE_LIMIT_BYTES); + prune_threadless_null_process_logs.push("\n)"); + prune_threadless_null_process_logs + .build() + .execute(&mut *tx) + .await?; + } + } + Ok(()) + } + + pub(crate) async fn delete_logs_before(&self, cutoff_ts: i64) -> anyhow::Result { + let result = sqlx::query("DELETE FROM logs WHERE ts < ?") + .bind(cutoff_ts) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected()) + } + + /// Query logs with optional filters. + pub async fn query_logs(&self, query: &LogQuery) -> anyhow::Result> { + let mut builder = QueryBuilder::::new( + "SELECT id, ts, ts_nanos, level, target, message, thread_id, process_uuid, file, line FROM logs WHERE 1 = 1", + ); + push_log_filters(&mut builder, query); + if query.descending { + builder.push(" ORDER BY id DESC"); + } else { + builder.push(" ORDER BY id ASC"); + } + if let Some(limit) = query.limit { + builder.push(" LIMIT ").push_bind(limit as i64); + } + + let rows = builder + .build_query_as::() + .fetch_all(self.pool.as_ref()) + .await?; + Ok(rows) + } + + /// Query per-thread feedback logs, capped to the per-thread SQLite retention budget. + pub async fn query_feedback_logs(&self, thread_id: &str) -> anyhow::Result> { + let max_bytes = LOG_PARTITION_SIZE_LIMIT_BYTES; + let lines = sqlx::query_scalar::<_, String>( + r#" +WITH latest_process AS ( + SELECT process_uuid + FROM logs + WHERE thread_id = ? AND process_uuid IS NOT NULL + ORDER BY ts DESC, ts_nanos DESC, id DESC + LIMIT 1 +), +feedback_logs AS ( + SELECT + printf('%5s %s', level, message) || CASE + WHEN substr(message, -1, 1) = char(10) THEN '' + ELSE char(10) + END AS line, + length(CAST( + printf('%5s %s', level, message) || CASE + WHEN substr(message, -1, 1) = char(10) THEN '' + ELSE char(10) + END AS BLOB + )) AS line_bytes, + ts, + ts_nanos, + id + FROM logs + WHERE message IS NOT NULL AND ( + thread_id = ? + OR ( + thread_id IS NULL + AND process_uuid IN (SELECT process_uuid FROM latest_process) + ) + ) +) +SELECT line +FROM ( + SELECT + line, + ts, + ts_nanos, + id, + SUM(line_bytes) OVER ( + ORDER BY ts DESC, ts_nanos DESC, id DESC + ) AS cumulative_bytes + FROM feedback_logs +) +WHERE cumulative_bytes <= ? +ORDER BY ts ASC, ts_nanos ASC, id ASC +"#, + ) + .bind(thread_id) + .bind(thread_id) + .bind(max_bytes) + .fetch_all(self.pool.as_ref()) + .await?; + + Ok(lines.concat().into_bytes()) + } + + /// Return the max log id matching optional filters. + pub async fn max_log_id(&self, query: &LogQuery) -> anyhow::Result { + let mut builder = + QueryBuilder::::new("SELECT MAX(id) AS max_id FROM logs WHERE 1 = 1"); + push_log_filters(&mut builder, query); + let row = builder.build().fetch_one(self.pool.as_ref()).await?; + let max_id: Option = row.try_get("max_id")?; + Ok(max_id.unwrap_or(0)) + } +} + +fn push_log_filters<'a>(builder: &mut QueryBuilder<'a, Sqlite>, query: &'a LogQuery) { + if let Some(level_upper) = query.level_upper.as_ref() { + builder + .push(" AND UPPER(level) = ") + .push_bind(level_upper.as_str()); + } + if let Some(from_ts) = query.from_ts { + builder.push(" AND ts >= ").push_bind(from_ts); + } + if let Some(to_ts) = query.to_ts { + builder.push(" AND ts <= ").push_bind(to_ts); + } + push_like_filters(builder, "module_path", &query.module_like); + push_like_filters(builder, "file", &query.file_like); + let has_thread_filter = !query.thread_ids.is_empty() || query.include_threadless; + if has_thread_filter { + builder.push(" AND ("); + let mut needs_or = false; + for thread_id in &query.thread_ids { + if needs_or { + builder.push(" OR "); + } + builder.push("thread_id = ").push_bind(thread_id.as_str()); + needs_or = true; + } + if query.include_threadless { + if needs_or { + builder.push(" OR "); + } + builder.push("thread_id IS NULL"); + } + builder.push(")"); + } + if let Some(after_id) = query.after_id { + builder.push(" AND id > ").push_bind(after_id); + } + if let Some(search) = query.search.as_ref() { + builder.push(" AND INSTR(message, "); + builder.push_bind(search.as_str()); + builder.push(") > 0"); + } +} + +fn push_like_filters<'a>( + builder: &mut QueryBuilder<'a, Sqlite>, + column: &str, + filters: &'a [String], +) { + if filters.is_empty() { + return; + } + builder.push(" AND ("); + for (idx, filter) in filters.iter().enumerate() { + if idx > 0 { + builder.push(" OR "); + } + builder + .push(column) + .push(" LIKE '%' || ") + .push_bind(filter.as_str()) + .push(" || '%'"); + } + builder.push(")"); +} + +#[cfg(test)] +mod tests { + use super::StateRuntime; + use super::test_support::unique_temp_dir; + use crate::LogEntry; + use crate::LogQuery; + use pretty_assertions::assert_eq; + #[tokio::test] + async fn query_logs_with_search_matches_substring() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1_700_000_001, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("alpha".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: None, + file: Some("main.rs".to_string()), + line: Some(42), + module_path: None, + }, + LogEntry { + ts: 1_700_000_002, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("alphabet".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: None, + file: Some("main.rs".to_string()), + line: Some(43), + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let rows = runtime + .query_logs(&LogQuery { + search: Some("alphab".to_string()), + ..Default::default() + }) + .await + .expect("query matching logs"); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].message.as_deref(), Some("alphabet")); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn insert_logs_prunes_old_rows_when_thread_exceeds_size_limit() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let six_mebibytes = "a".repeat(6 * 1024 * 1024); + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes.clone()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(1), + module_path: Some("mod".to_string()), + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes.clone()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(2), + module_path: Some("mod".to_string()), + }, + ]) + .await + .expect("insert test logs"); + + let rows = runtime + .query_logs(&LogQuery { + thread_ids: vec!["thread-1".to_string()], + ..Default::default() + }) + .await + .expect("query thread logs"); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].ts, 2); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn insert_logs_prunes_single_thread_row_when_it_exceeds_size_limit() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let eleven_mebibytes = "d".repeat(11 * 1024 * 1024); + runtime + .insert_logs(&[LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(eleven_mebibytes), + thread_id: Some("thread-oversized".to_string()), + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(1), + module_path: Some("mod".to_string()), + }]) + .await + .expect("insert test log"); + + let rows = runtime + .query_logs(&LogQuery { + thread_ids: vec!["thread-oversized".to_string()], + ..Default::default() + }) + .await + .expect("query thread logs"); + + assert!(rows.is_empty()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn insert_logs_prunes_threadless_rows_per_process_uuid_only() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let six_mebibytes = "b".repeat(6 * 1024 * 1024); + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes.clone()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(1), + module_path: Some("mod".to_string()), + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes.clone()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(2), + module_path: Some("mod".to_string()), + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(3), + module_path: Some("mod".to_string()), + }, + ]) + .await + .expect("insert test logs"); + + let rows = runtime + .query_logs(&LogQuery { + thread_ids: vec!["thread-1".to_string()], + include_threadless: true, + ..Default::default() + }) + .await + .expect("query thread and threadless logs"); + + let mut timestamps: Vec = rows.into_iter().map(|row| row.ts).collect(); + timestamps.sort_unstable(); + assert_eq!(timestamps, vec![2, 3]); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn insert_logs_prunes_single_threadless_process_row_when_it_exceeds_size_limit() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let eleven_mebibytes = "e".repeat(11 * 1024 * 1024); + runtime + .insert_logs(&[LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(eleven_mebibytes), + thread_id: None, + process_uuid: Some("proc-oversized".to_string()), + file: Some("main.rs".to_string()), + line: Some(1), + module_path: Some("mod".to_string()), + }]) + .await + .expect("insert test log"); + + let rows = runtime + .query_logs(&LogQuery { + include_threadless: true, + ..Default::default() + }) + .await + .expect("query threadless logs"); + + assert!(rows.is_empty()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn insert_logs_prunes_threadless_rows_with_null_process_uuid() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let six_mebibytes = "c".repeat(6 * 1024 * 1024); + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes.clone()), + thread_id: None, + process_uuid: None, + file: Some("main.rs".to_string()), + line: Some(1), + module_path: Some("mod".to_string()), + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(six_mebibytes), + thread_id: None, + process_uuid: None, + file: Some("main.rs".to_string()), + line: Some(2), + module_path: Some("mod".to_string()), + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("small".to_string()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: Some("main.rs".to_string()), + line: Some(3), + module_path: Some("mod".to_string()), + }, + ]) + .await + .expect("insert test logs"); + + let rows = runtime + .query_logs(&LogQuery { + include_threadless: true, + ..Default::default() + }) + .await + .expect("query threadless logs"); + + let mut timestamps: Vec = rows.into_iter().map(|row| row.ts).collect(); + timestamps.sort_unstable(); + assert_eq!(timestamps, vec![2, 3]); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn insert_logs_prunes_single_threadless_null_process_row_when_it_exceeds_limit() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let eleven_mebibytes = "f".repeat(11 * 1024 * 1024); + runtime + .insert_logs(&[LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(eleven_mebibytes), + thread_id: None, + process_uuid: None, + file: Some("main.rs".to_string()), + line: Some(1), + module_path: Some("mod".to_string()), + }]) + .await + .expect("insert test log"); + + let rows = runtime + .query_logs(&LogQuery { + include_threadless: true, + ..Default::default() + }) + .await + .expect("query threadless logs"); + + assert!(rows.is_empty()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_returns_newest_lines_within_limit_in_order() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("alpha".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("bravo".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("charlie".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + + assert_eq!( + String::from_utf8(bytes).expect("valid utf-8"), + " INFO alpha\n INFO bravo\n INFO charlie\n" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_excludes_oversized_newest_row() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let eleven_mebibytes = "z".repeat(11 * 1024 * 1024); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("small".to_string()), + thread_id: Some("thread-oversized".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(eleven_mebibytes), + thread_id: Some("thread-oversized".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-oversized") + .await + .expect("query feedback logs"); + + assert_eq!(bytes, Vec::::new()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_includes_threadless_rows_from_same_process() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("threadless-before".to_string()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("thread-scoped".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("threadless-after".to_string()), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 4, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("other-process-threadless".to_string()), + thread_id: None, + process_uuid: Some("proc-2".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + + assert_eq!( + String::from_utf8(bytes).expect("valid utf-8"), + " INFO threadless-before\n INFO thread-scoped\n INFO threadless-after\n" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_excludes_threadless_rows_from_prior_processes() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("old-process-threadless".to_string()), + thread_id: None, + process_uuid: Some("proc-old".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("old-process-thread".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-old".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("new-process-thread".to_string()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-new".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 4, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some("new-process-threadless".to_string()), + thread_id: None, + process_uuid: Some("proc-new".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + + assert_eq!( + String::from_utf8(bytes).expect("valid utf-8"), + " INFO old-process-thread\n INFO new-process-thread\n INFO new-process-threadless\n" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn query_feedback_logs_keeps_newest_suffix_across_thread_and_threadless_logs() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + let thread_marker = "thread-scoped-oldest"; + let threadless_older_marker = "threadless-older"; + let threadless_newer_marker = "threadless-newer"; + let five_mebibytes = format!("{threadless_older_marker} {}", "a".repeat(5 * 1024 * 1024)); + let four_and_half_mebibytes = format!( + "{threadless_newer_marker} {}", + "b".repeat((9 * 1024 * 1024) / 2) + ); + let one_mebibyte = format!("{thread_marker} {}", "c".repeat(1024 * 1024)); + + runtime + .insert_logs(&[ + LogEntry { + ts: 1, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(one_mebibyte.clone()), + thread_id: Some("thread-1".to_string()), + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 2, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(five_mebibytes), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + LogEntry { + ts: 3, + ts_nanos: 0, + level: "INFO".to_string(), + target: "cli".to_string(), + message: Some(four_and_half_mebibytes), + thread_id: None, + process_uuid: Some("proc-1".to_string()), + file: None, + line: None, + module_path: None, + }, + ]) + .await + .expect("insert test logs"); + + let bytes = runtime + .query_feedback_logs("thread-1") + .await + .expect("query feedback logs"); + let logs = String::from_utf8(bytes).expect("valid utf-8"); + + assert!(!logs.contains(thread_marker)); + assert!(logs.contains(threadless_older_marker)); + assert!(logs.contains(threadless_newer_marker)); + assert_eq!(logs.matches('\n').count(), 2); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } +} diff --git a/codex-rs/state/src/runtime/memories.rs b/codex-rs/state/src/runtime/memories.rs index 6d5ffc888a..75d81e2327 100644 --- a/codex-rs/state/src/runtime/memories.rs +++ b/codex-rs/state/src/runtime/memories.rs @@ -1,4 +1,7 @@ +use super::threads::push_thread_filters; +use super::threads::push_thread_order_and_limit; use super::*; +use crate::model::Phase2InputSelection; use crate::model::Phase2JobClaimOutcome; use crate::model::Stage1JobClaim; use crate::model::Stage1JobClaimOutcome; @@ -6,10 +9,13 @@ use crate::model::Stage1Output; use crate::model::Stage1OutputRow; use crate::model::Stage1StartupClaimParams; use crate::model::ThreadRow; +use crate::model::stage1_output_ref_from_parts; use chrono::Duration; use sqlx::Executor; use sqlx::QueryBuilder; use sqlx::Sqlite; +use std::collections::HashSet; +use uuid::Uuid; const JOB_KIND_MEMORY_STAGE1: &str = "memory_stage1"; const JOB_KIND_MEMORY_CONSOLIDATE_GLOBAL: &str = "memory_consolidate_global"; @@ -24,6 +30,19 @@ impl StateRuntime { /// stage-1 (`memory_stage1`) and phase-2 (`memory_consolidate_global`) /// memory pipelines. pub async fn clear_memory_data(&self) -> anyhow::Result<()> { + self.clear_memory_data_inner(false).await + } + + /// Resets persisted memory state for a clean-slate local start. + /// + /// In addition to clearing persisted stage-1 outputs and memory pipeline + /// jobs, this disables memory generation for all existing threads so + /// historical rollouts are not immediately picked up again. + pub async fn reset_memory_data_for_fresh_start(&self) -> anyhow::Result<()> { + self.clear_memory_data_inner(true).await + } + + async fn clear_memory_data_inner(&self, disable_existing_threads: bool) -> anyhow::Result<()> { let mut tx = self.pool.begin().await?; sqlx::query( @@ -45,6 +64,18 @@ WHERE kind = ? OR kind = ? .execute(&mut *tx) .await?; + if disable_existing_threads { + sqlx::query( + r#" +UPDATE threads +SET memory_mode = 'disabled' +WHERE memory_mode = 'enabled' + "#, + ) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; Ok(()) } @@ -91,6 +122,7 @@ WHERE thread_id = ? /// Query behavior: /// - starts from `threads` filtered to active threads and allowed sources /// (`push_thread_filters`) + /// - excludes threads with `memory_mode != 'enabled'` /// - excludes the current thread id /// - keeps only threads in the age window: /// `updated_at >= now - max_age_days` and `updated_at <= now - min_rollout_idle_hours` @@ -168,6 +200,7 @@ LEFT JOIN jobs SortKey::UpdatedAt, None, ); + builder.push(" AND threads.memory_mode = 'enabled'"); builder .push(" AND id != ") .push_bind(current_thread_id.as_str()); @@ -218,7 +251,7 @@ LEFT JOIN jobs /// /// Query behavior: /// - filters out rows where both `raw_memory` and `rollout_summary` are blank - /// - joins `threads` to include thread `cwd` + /// - joins `threads` to include thread `cwd`, `rollout_path`, and `git_branch` /// - orders by `source_updated_at DESC, thread_id DESC` /// - applies `LIMIT n` pub async fn list_stage1_outputs_for_global( @@ -233,16 +266,19 @@ LEFT JOIN jobs r#" SELECT so.thread_id, + COALESCE(t.rollout_path, '') AS rollout_path, so.source_updated_at, so.raw_memory, so.rollout_summary, so.rollout_slug, - so.generated_at - , COALESCE(t.cwd, '') AS cwd + so.generated_at, + COALESCE(t.cwd, '') AS cwd, + t.git_branch AS git_branch FROM stage1_outputs AS so LEFT JOIN threads AS t ON t.id = so.thread_id -WHERE length(trim(so.raw_memory)) > 0 OR length(trim(so.rollout_summary)) > 0 +WHERE t.memory_mode = 'enabled' + AND (length(trim(so.raw_memory)) > 0 OR length(trim(so.rollout_summary)) > 0) ORDER BY so.source_updated_at DESC, so.thread_id DESC LIMIT ? "#, @@ -256,6 +292,184 @@ LIMIT ? .collect::, _>>() } + /// Returns the current phase-2 input set along with its diff against the + /// last successful phase-2 selection. + /// + /// Query behavior: + /// - current selection keeps only non-empty stage-1 outputs whose + /// `last_usage` is within `max_unused_days`, or whose + /// `source_updated_at` is within that window when the memory has never + /// been used + /// - eligible rows are ordered by `usage_count DESC`, + /// `COALESCE(last_usage, source_updated_at) DESC`, `source_updated_at DESC`, + /// `thread_id DESC` + /// - previously selected rows are identified by `selected_for_phase2 = 1` + /// - `previous_selected` contains the current persisted rows that belonged + /// to the last successful phase-2 baseline, even if those threads are no + /// longer memory-eligible + /// - `retained_thread_ids` records which current rows still match the exact + /// snapshot selected in the last successful phase-2 run + /// - removed rows are previously selected rows that are still present in + /// `stage1_outputs` but are no longer in the current selection, including + /// threads that are no longer memory-eligible + pub async fn get_phase2_input_selection( + &self, + n: usize, + max_unused_days: i64, + ) -> anyhow::Result { + if n == 0 { + return Ok(Phase2InputSelection::default()); + } + let cutoff = (Utc::now() - Duration::days(max_unused_days.max(0))).timestamp(); + + let current_rows = sqlx::query( + r#" +SELECT + so.thread_id, + COALESCE(t.rollout_path, '') AS rollout_path, + so.source_updated_at, + so.raw_memory, + so.rollout_summary, + so.rollout_slug, + so.generated_at, + COALESCE(t.cwd, '') AS cwd, + t.git_branch AS git_branch, + so.selected_for_phase2, + so.selected_for_phase2_source_updated_at +FROM stage1_outputs AS so +LEFT JOIN threads AS t + ON t.id = so.thread_id +WHERE t.memory_mode = 'enabled' + AND (length(trim(so.raw_memory)) > 0 OR length(trim(so.rollout_summary)) > 0) + AND ( + (so.last_usage IS NOT NULL AND so.last_usage >= ?) + OR (so.last_usage IS NULL AND so.source_updated_at >= ?) + ) +ORDER BY + COALESCE(so.usage_count, 0) DESC, + COALESCE(so.last_usage, so.source_updated_at) DESC, + so.source_updated_at DESC, + so.thread_id DESC +LIMIT ? + "#, + ) + .bind(cutoff) + .bind(cutoff) + .bind(n as i64) + .fetch_all(self.pool.as_ref()) + .await?; + + let mut current_thread_ids = HashSet::with_capacity(current_rows.len()); + let mut selected = Vec::with_capacity(current_rows.len()); + let mut retained_thread_ids = Vec::new(); + for row in current_rows { + let thread_id = row.try_get::("thread_id")?; + current_thread_ids.insert(thread_id.clone()); + let source_updated_at = row.try_get::("source_updated_at")?; + if row.try_get::("selected_for_phase2")? != 0 + && row.try_get::, _>("selected_for_phase2_source_updated_at")? + == Some(source_updated_at) + { + retained_thread_ids.push(ThreadId::try_from(thread_id.clone())?); + } + selected.push(Stage1Output::try_from(Stage1OutputRow::try_from_row( + &row, + )?)?); + } + + let previous_rows = sqlx::query( + r#" +SELECT + so.thread_id, + COALESCE(t.rollout_path, '') AS rollout_path, + so.source_updated_at, + so.raw_memory, + so.rollout_summary, + so.rollout_slug, + so.generated_at, + COALESCE(t.cwd, '') AS cwd, + t.git_branch AS git_branch +FROM stage1_outputs AS so +LEFT JOIN threads AS t + ON t.id = so.thread_id +WHERE so.selected_for_phase2 = 1 +ORDER BY so.source_updated_at DESC, so.thread_id DESC + "#, + ) + .fetch_all(self.pool.as_ref()) + .await?; + + let previous_selected = previous_rows + .iter() + .map(Stage1OutputRow::try_from_row) + .map(|row| row.and_then(Stage1Output::try_from)) + .collect::, _>>()?; + let mut removed = Vec::new(); + for row in previous_rows { + let thread_id = row.try_get::("thread_id")?; + if current_thread_ids.contains(thread_id.as_str()) { + continue; + } + removed.push(stage1_output_ref_from_parts( + thread_id, + row.try_get("source_updated_at")?, + row.try_get("rollout_slug")?, + )?); + } + + Ok(Phase2InputSelection { + selected, + previous_selected, + retained_thread_ids, + removed, + }) + } + + /// Marks a thread as polluted and enqueues phase-2 forgetting when the + /// thread participated in the last successful phase-2 baseline. + pub async fn mark_thread_memory_mode_polluted( + &self, + thread_id: ThreadId, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); + let thread_id = thread_id.to_string(); + let mut tx = self.pool.begin().await?; + let rows_affected = sqlx::query( + r#" +UPDATE threads +SET memory_mode = 'polluted' +WHERE id = ? AND memory_mode != 'polluted' + "#, + ) + .bind(thread_id.as_str()) + .execute(&mut *tx) + .await? + .rows_affected(); + + if rows_affected == 0 { + tx.commit().await?; + return Ok(false); + } + + let selected_for_phase2 = sqlx::query_scalar::<_, i64>( + r#" +SELECT selected_for_phase2 +FROM stage1_outputs +WHERE thread_id = ? + "#, + ) + .bind(thread_id.as_str()) + .fetch_optional(&mut *tx) + .await? + .unwrap_or(0); + if selected_for_phase2 != 0 { + enqueue_global_consolidation_with_executor(&mut *tx, now).await?; + } + + tx.commit().await?; + Ok(true) + } + /// Attempts to claim a stage-1 job for a thread at `source_updated_at`. /// /// Claim semantics: @@ -453,6 +667,9 @@ WHERE kind = ? AND job_key = ? /// - sets `status='done'` and `last_success_watermark = input_watermark` /// - upserts `stage1_outputs` for the thread, replacing existing output only /// when `source_updated_at` is newer or equal + /// - preserves any existing `selected_for_phase2` baseline until the next + /// successful phase-2 run rewrites the baseline selection, including the + /// snapshot timestamp chosen during that run /// - persists optional `rollout_slug` for rollout summary artifact naming /// - enqueues/advances the global phase-2 job watermark using /// `source_updated_at` @@ -805,12 +1022,18 @@ WHERE kind = ? AND job_key = ? /// - sets `status='done'`, clears lease/errors /// - advances `last_success_watermark` to /// `max(existing_last_success_watermark, completed_watermark)` + /// - rewrites `selected_for_phase2` so only the exact selected stage-1 + /// snapshots remain marked as part of the latest successful phase-2 + /// selection, and persists each selected snapshot's + /// `source_updated_at` for future retained-vs-added diffing pub async fn mark_global_phase2_job_succeeded( &self, ownership_token: &str, completed_watermark: i64, + selected_outputs: &[Stage1Output], ) -> anyhow::Result { let now = Utc::now().timestamp(); + let mut tx = self.pool.begin().await?; let rows_affected = sqlx::query( r#" UPDATE jobs @@ -829,11 +1052,46 @@ WHERE kind = ? AND job_key = ? .bind(JOB_KIND_MEMORY_CONSOLIDATE_GLOBAL) .bind(MEMORY_CONSOLIDATION_JOB_KEY) .bind(ownership_token) - .execute(self.pool.as_ref()) + .execute(&mut *tx) .await? .rows_affected(); - Ok(rows_affected > 0) + if rows_affected == 0 { + tx.commit().await?; + return Ok(false); + } + + sqlx::query( + r#" +UPDATE stage1_outputs +SET + selected_for_phase2 = 0, + selected_for_phase2_source_updated_at = NULL +WHERE selected_for_phase2 != 0 OR selected_for_phase2_source_updated_at IS NOT NULL + "#, + ) + .execute(&mut *tx) + .await?; + + for output in selected_outputs { + sqlx::query( + r#" +UPDATE stage1_outputs +SET + selected_for_phase2 = 1, + selected_for_phase2_source_updated_at = ? +WHERE thread_id = ? AND source_updated_at = ? + "#, + ) + .bind(output.source_updated_at.timestamp()) + .bind(output.thread_id.to_string()) + .bind(output.source_updated_at.timestamp()) + .execute(&mut *tx) + .await?; + } + + tx.commit().await?; + Ok(true) } /// Marks the owned running global phase-2 job as failed and schedules retry. @@ -971,3 +1229,2953 @@ ON CONFLICT(kind, job_key) DO UPDATE SET Ok(()) } + +#[cfg(test)] +mod tests { + use super::JOB_KIND_MEMORY_CONSOLIDATE_GLOBAL; + use super::JOB_KIND_MEMORY_STAGE1; + use super::StateRuntime; + use super::test_support::test_thread_metadata; + use super::test_support::unique_temp_dir; + use crate::model::Phase2JobClaimOutcome; + use crate::model::Stage1JobClaimOutcome; + use crate::model::Stage1StartupClaimParams; + use chrono::Duration; + use chrono::Utc; + use codex_protocol::ThreadId; + use pretty_assertions::assert_eq; + use sqlx::Row; + use std::sync::Arc; + use uuid::Uuid; + + #[tokio::test] + async fn stage1_claim_skips_when_up_to_date() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let metadata = test_thread_metadata(&codex_home, thread_id, codex_home.join("a")); + runtime + .upsert_thread(&metadata) + .await + .expect("upsert thread"); + + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + let claim = runtime + .try_claim_stage1_job(thread_id, owner_a, 100, 3600, 64) + .await + .expect("claim stage1 job"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected claim outcome: {other:?}"), + }; + + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + 100, + "raw", + "sum", + None, + ) + .await + .expect("mark stage1 succeeded"), + "stage1 success should finalize for current token" + ); + + let up_to_date = runtime + .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) + .await + .expect("claim stage1 up-to-date"); + assert_eq!(up_to_date, Stage1JobClaimOutcome::SkippedUpToDate); + + let needs_rerun = runtime + .try_claim_stage1_job(thread_id, owner_b, 101, 3600, 64) + .await + .expect("claim stage1 newer source"); + assert!( + matches!(needs_rerun, Stage1JobClaimOutcome::Claimed { .. }), + "newer source_updated_at should be claimable" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn stage1_running_stale_can_be_stolen_but_fresh_running_is_skipped() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let cwd = codex_home.join("workspace"); + runtime + .upsert_thread(&test_thread_metadata(&codex_home, thread_id, cwd)) + .await + .expect("upsert thread"); + + let claim_a = runtime + .try_claim_stage1_job(thread_id, owner_a, 100, 3600, 64) + .await + .expect("claim a"); + assert!(matches!(claim_a, Stage1JobClaimOutcome::Claimed { .. })); + + let claim_b_fresh = runtime + .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) + .await + .expect("claim b fresh"); + assert_eq!(claim_b_fresh, Stage1JobClaimOutcome::SkippedRunning); + + sqlx::query("UPDATE jobs SET lease_until = 0 WHERE kind = 'memory_stage1' AND job_key = ?") + .bind(thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("force stale lease"); + + let claim_b_stale = runtime + .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) + .await + .expect("claim b stale"); + assert!(matches!( + claim_b_stale, + Stage1JobClaimOutcome::Claimed { .. } + )); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn stage1_concurrent_claim_for_same_thread_is_conflict_safe() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let thread_id_a = thread_id; + let thread_id_b = thread_id; + let runtime_a = Arc::clone(&runtime); + let runtime_b = Arc::clone(&runtime); + let claim_with_retry = |runtime: Arc, + thread_id: ThreadId, + owner: ThreadId| async move { + for attempt in 0..5 { + match runtime + .try_claim_stage1_job(thread_id, owner, 100, 3_600, 64) + .await + { + Ok(outcome) => return outcome, + Err(err) if err.to_string().contains("database is locked") && attempt < 4 => { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + Err(err) => panic!("claim stage1 should not fail: {err}"), + } + } + panic!("claim stage1 should have returned within retry budget") + }; + + let (claim_a, claim_b) = tokio::join!( + claim_with_retry(runtime_a, thread_id_a, owner_a), + claim_with_retry(runtime_b, thread_id_b, owner_b), + ); + + let claim_outcomes = vec![claim_a, claim_b]; + let claimed_count = claim_outcomes + .iter() + .filter(|outcome| matches!(outcome, Stage1JobClaimOutcome::Claimed { .. })) + .count(); + assert_eq!(claimed_count, 1); + assert!( + claim_outcomes.iter().all(|outcome| { + matches!( + outcome, + Stage1JobClaimOutcome::Claimed { .. } | Stage1JobClaimOutcome::SkippedRunning + ) + }), + "unexpected claim outcomes: {claim_outcomes:?}" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn stage1_concurrent_claims_respect_running_cap() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_a, + codex_home.join("workspace-a"), + )) + .await + .expect("upsert thread a"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_b, + codex_home.join("workspace-b"), + )) + .await + .expect("upsert thread b"); + + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let runtime_a = Arc::clone(&runtime); + let runtime_b = Arc::clone(&runtime); + + let (claim_a, claim_b) = tokio::join!( + async move { + runtime_a + .try_claim_stage1_job(thread_a, owner_a, 100, 3_600, 1) + .await + .expect("claim stage1 thread a") + }, + async move { + runtime_b + .try_claim_stage1_job(thread_b, owner_b, 101, 3_600, 1) + .await + .expect("claim stage1 thread b") + }, + ); + + let claim_outcomes = vec![claim_a, claim_b]; + let claimed_count = claim_outcomes + .iter() + .filter(|outcome| matches!(outcome, Stage1JobClaimOutcome::Claimed { .. })) + .count(); + assert_eq!(claimed_count, 1); + assert!( + claim_outcomes + .iter() + .any(|outcome| { matches!(outcome, Stage1JobClaimOutcome::SkippedRunning) }), + "one concurrent claim should be throttled by running cap: {claim_outcomes:?}" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn claim_stage1_jobs_filters_by_age_idle_and_current_thread() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let now = Utc::now(); + let fresh_at = now - Duration::hours(1); + let just_under_idle_at = now - Duration::hours(12) + Duration::minutes(1); + let eligible_idle_at = now - Duration::hours(12) - Duration::minutes(1); + let old_at = now - Duration::days(31); + + let current_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); + let fresh_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("fresh thread id"); + let just_under_idle_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("just under idle thread id"); + let eligible_idle_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("eligible idle thread id"); + let old_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("old thread id"); + + let mut current = + test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); + current.created_at = now; + current.updated_at = now; + runtime + .upsert_thread(¤t) + .await + .expect("upsert current"); + + let mut fresh = + test_thread_metadata(&codex_home, fresh_thread_id, codex_home.join("fresh")); + fresh.created_at = fresh_at; + fresh.updated_at = fresh_at; + runtime.upsert_thread(&fresh).await.expect("upsert fresh"); + + let mut just_under_idle = test_thread_metadata( + &codex_home, + just_under_idle_thread_id, + codex_home.join("just-under-idle"), + ); + just_under_idle.created_at = just_under_idle_at; + just_under_idle.updated_at = just_under_idle_at; + runtime + .upsert_thread(&just_under_idle) + .await + .expect("upsert just-under-idle"); + + let mut eligible_idle = test_thread_metadata( + &codex_home, + eligible_idle_thread_id, + codex_home.join("eligible-idle"), + ); + eligible_idle.created_at = eligible_idle_at; + eligible_idle.updated_at = eligible_idle_at; + runtime + .upsert_thread(&eligible_idle) + .await + .expect("upsert eligible-idle"); + + let mut old = test_thread_metadata(&codex_home, old_thread_id, codex_home.join("old")); + old.created_at = old_at; + old.updated_at = old_at; + runtime.upsert_thread(&old).await.expect("upsert old"); + + let allowed_sources = vec!["cli".to_string()]; + let claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 1, + max_claimed: 5, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3600, + }, + ) + .await + .expect("claim stage1 jobs"); + + assert_eq!(claims.len(), 1); + assert_eq!(claims[0].thread.id, eligible_idle_thread_id); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn claim_stage1_jobs_prefilters_threads_with_up_to_date_memory() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let now = Utc::now(); + let eligible_newer_at = now - Duration::hours(13); + let eligible_older_at = now - Duration::hours(14); + + let current_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); + let up_to_date_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("up-to-date thread id"); + let stale_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("stale thread id"); + let worker_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("worker id"); + + let mut current = + test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); + current.created_at = now; + current.updated_at = now; + runtime + .upsert_thread(¤t) + .await + .expect("upsert current thread"); + + let mut up_to_date = test_thread_metadata( + &codex_home, + up_to_date_thread_id, + codex_home.join("up-to-date"), + ); + up_to_date.created_at = eligible_newer_at; + up_to_date.updated_at = eligible_newer_at; + runtime + .upsert_thread(&up_to_date) + .await + .expect("upsert up-to-date thread"); + + let up_to_date_claim = runtime + .try_claim_stage1_job( + up_to_date_thread_id, + worker_id, + up_to_date.updated_at.timestamp(), + 3600, + 64, + ) + .await + .expect("claim up-to-date thread for seed"); + let up_to_date_token = match up_to_date_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected seed claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + up_to_date_thread_id, + up_to_date_token.as_str(), + up_to_date.updated_at.timestamp(), + "raw", + "summary", + None, + ) + .await + .expect("mark up-to-date thread succeeded"), + "seed stage1 success should complete for up-to-date thread" + ); + + let mut stale = + test_thread_metadata(&codex_home, stale_thread_id, codex_home.join("stale")); + stale.created_at = eligible_older_at; + stale.updated_at = eligible_older_at; + runtime + .upsert_thread(&stale) + .await + .expect("upsert stale thread"); + + let allowed_sources = vec!["cli".to_string()]; + let claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 1, + max_claimed: 1, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3600, + }, + ) + .await + .expect("claim stage1 startup jobs"); + assert_eq!(claims.len(), 1); + assert_eq!(claims[0].thread.id, stale_thread_id); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn claim_stage1_jobs_skips_threads_with_disabled_memory_mode() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let now = Utc::now(); + let eligible_at = now - Duration::hours(13); + + let current_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); + let disabled_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("disabled thread id"); + let enabled_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("enabled thread id"); + + let mut current = + test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); + current.created_at = now; + current.updated_at = now; + runtime + .upsert_thread(¤t) + .await + .expect("upsert current thread"); + + let mut disabled = + test_thread_metadata(&codex_home, disabled_thread_id, codex_home.join("disabled")); + disabled.created_at = eligible_at; + disabled.updated_at = eligible_at; + runtime + .upsert_thread(&disabled) + .await + .expect("upsert disabled thread"); + sqlx::query("UPDATE threads SET memory_mode = 'disabled' WHERE id = ?") + .bind(disabled_thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("disable thread memory mode"); + + let mut enabled = + test_thread_metadata(&codex_home, enabled_thread_id, codex_home.join("enabled")); + enabled.created_at = eligible_at; + enabled.updated_at = eligible_at; + runtime + .upsert_thread(&enabled) + .await + .expect("upsert enabled thread"); + + let allowed_sources = vec!["cli".to_string()]; + let claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 10, + max_claimed: 10, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3600, + }, + ) + .await + .expect("claim stage1 startup jobs"); + + assert_eq!(claims.len(), 1); + assert_eq!(claims[0].thread.id, enabled_thread_id); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn reset_memory_data_for_fresh_start_clears_rows_and_disables_threads() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let now = Utc::now() - Duration::hours(13); + let worker_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("worker id"); + let enabled_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("enabled thread id"); + let disabled_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("disabled thread id"); + + let mut enabled = + test_thread_metadata(&codex_home, enabled_thread_id, codex_home.join("enabled")); + enabled.created_at = now; + enabled.updated_at = now; + runtime + .upsert_thread(&enabled) + .await + .expect("upsert enabled thread"); + + let claim = runtime + .try_claim_stage1_job( + enabled_thread_id, + worker_id, + enabled.updated_at.timestamp(), + 3600, + 64, + ) + .await + .expect("claim enabled thread"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + enabled_thread_id, + ownership_token.as_str(), + enabled.updated_at.timestamp(), + "raw", + "summary", + None, + ) + .await + .expect("mark enabled thread succeeded"), + "stage1 success should be recorded" + ); + runtime + .enqueue_global_consolidation(enabled.updated_at.timestamp()) + .await + .expect("enqueue global consolidation"); + + let mut disabled = + test_thread_metadata(&codex_home, disabled_thread_id, codex_home.join("disabled")); + disabled.created_at = now; + disabled.updated_at = now; + runtime + .upsert_thread(&disabled) + .await + .expect("upsert disabled thread"); + sqlx::query("UPDATE threads SET memory_mode = 'disabled' WHERE id = ?") + .bind(disabled_thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("disable existing thread"); + + runtime + .reset_memory_data_for_fresh_start() + .await + .expect("reset memory data"); + + let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs") + .fetch_one(runtime.pool.as_ref()) + .await + .expect("count stage1 outputs"); + assert_eq!(stage1_outputs_count, 0); + + let memory_jobs_count: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM jobs WHERE kind = ? OR kind = ?") + .bind(JOB_KIND_MEMORY_STAGE1) + .bind(JOB_KIND_MEMORY_CONSOLIDATE_GLOBAL) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("count memory jobs"); + assert_eq!(memory_jobs_count, 0); + + let enabled_memory_mode: String = + sqlx::query_scalar("SELECT memory_mode FROM threads WHERE id = ?") + .bind(enabled_thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("read enabled thread memory mode"); + assert_eq!(enabled_memory_mode, "disabled"); + + let disabled_memory_mode: String = + sqlx::query_scalar("SELECT memory_mode FROM threads WHERE id = ?") + .bind(disabled_thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("read disabled thread memory mode"); + assert_eq!(disabled_memory_mode, "disabled"); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn claim_stage1_jobs_enforces_global_running_cap() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let current_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + current_thread_id, + codex_home.join("current"), + )) + .await + .expect("upsert current"); + + let now = Utc::now(); + let started_at = now.timestamp(); + let lease_until = started_at + 3600; + let eligible_at = now - Duration::hours(13); + let existing_running = 10usize; + let total_candidates = 80usize; + + for idx in 0..total_candidates { + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let mut metadata = test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(format!("thread-{idx}")), + ); + metadata.created_at = eligible_at - Duration::seconds(idx as i64); + metadata.updated_at = eligible_at - Duration::seconds(idx as i64); + runtime + .upsert_thread(&metadata) + .await + .expect("upsert thread"); + + if idx < existing_running { + sqlx::query( + r#" +INSERT INTO jobs ( + kind, + job_key, + status, + worker_id, + ownership_token, + started_at, + finished_at, + lease_until, + retry_at, + retry_remaining, + last_error, + input_watermark, + last_success_watermark +) VALUES (?, ?, 'running', ?, ?, ?, NULL, ?, NULL, ?, NULL, ?, NULL) + "#, + ) + .bind("memory_stage1") + .bind(thread_id.to_string()) + .bind(current_thread_id.to_string()) + .bind(Uuid::new_v4().to_string()) + .bind(started_at) + .bind(lease_until) + .bind(3) + .bind(metadata.updated_at.timestamp()) + .execute(runtime.pool.as_ref()) + .await + .expect("seed running stage1 job"); + } + } + + let allowed_sources = vec!["cli".to_string()]; + let claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 200, + max_claimed: 64, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3600, + }, + ) + .await + .expect("claim stage1 jobs"); + assert_eq!(claims.len(), 54); + + let running_count = sqlx::query( + r#" +SELECT COUNT(*) AS count +FROM jobs +WHERE kind = 'memory_stage1' + AND status = 'running' + AND lease_until IS NOT NULL + AND lease_until > ? + "#, + ) + .bind(Utc::now().timestamp()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("count running stage1 jobs") + .try_get::("count") + .expect("running count value"); + assert_eq!(running_count, 64); + + let more_claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 200, + max_claimed: 64, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3600, + }, + ) + .await + .expect("claim stage1 jobs with cap reached"); + assert_eq!(more_claims.len(), 0); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn claim_stage1_jobs_processes_two_full_batches_across_startup_passes() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let current_thread_id = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("current thread id"); + let mut current = + test_thread_metadata(&codex_home, current_thread_id, codex_home.join("current")); + current.created_at = Utc::now(); + current.updated_at = Utc::now(); + runtime + .upsert_thread(¤t) + .await + .expect("upsert current"); + + let eligible_at = Utc::now() - Duration::hours(13); + for idx in 0..200 { + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let mut metadata = test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(format!("thread-{idx}")), + ); + metadata.created_at = eligible_at - Duration::seconds(idx as i64); + metadata.updated_at = eligible_at - Duration::seconds(idx as i64); + runtime + .upsert_thread(&metadata) + .await + .expect("upsert eligible thread"); + } + + let allowed_sources = vec!["cli".to_string()]; + let first_claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 5_000, + max_claimed: 64, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3_600, + }, + ) + .await + .expect("first stage1 startup claim"); + assert_eq!(first_claims.len(), 64); + + for claim in first_claims { + assert!( + runtime + .mark_stage1_job_succeeded( + claim.thread.id, + claim.ownership_token.as_str(), + claim.thread.updated_at.timestamp(), + "raw", + "summary", + None, + ) + .await + .expect("mark first-batch stage1 success"), + "first batch stage1 completion should succeed" + ); + } + + let second_claims = runtime + .claim_stage1_jobs_for_startup( + current_thread_id, + Stage1StartupClaimParams { + scan_limit: 5_000, + max_claimed: 64, + max_age_days: 30, + min_rollout_idle_hours: 12, + allowed_sources: allowed_sources.as_slice(), + lease_seconds: 3_600, + }, + ) + .await + .expect("second stage1 startup claim"); + assert_eq!(second_claims.len(), 64); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn stage1_output_cascades_on_thread_delete() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let cwd = codex_home.join("workspace"); + runtime + .upsert_thread(&test_thread_metadata(&codex_home, thread_id, cwd)) + .await + .expect("upsert thread"); + + let claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + 100, + "raw", + "sum", + None, + ) + .await + .expect("mark stage1 succeeded"), + "mark stage1 succeeded should write stage1_outputs" + ); + + let count_before = + sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("count before delete") + .try_get::("count") + .expect("count value"); + assert_eq!(count_before, 1); + + sqlx::query("DELETE FROM threads WHERE id = ?") + .bind(thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("delete thread"); + + let count_after = + sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("count after delete") + .try_get::("count") + .expect("count value"); + assert_eq!(count_after, 0); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_stage1_job_succeeded_no_output_skips_phase2_when_output_was_already_absent() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded_no_output(thread_id, ownership_token.as_str()) + .await + .expect("mark stage1 succeeded without output"), + "stage1 no-output success should complete the job" + ); + + let output_row_count = + sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load stage1 output count") + .try_get::("count") + .expect("stage1 output count"); + assert_eq!( + output_row_count, 0, + "stage1 no-output success should not persist empty stage1 outputs" + ); + + let up_to_date = runtime + .try_claim_stage1_job(thread_id, owner_b, 100, 3600, 64) + .await + .expect("claim stage1 up-to-date"); + assert_eq!(up_to_date, Stage1JobClaimOutcome::SkippedUpToDate); + + let global_job_row_count = sqlx::query("SELECT COUNT(*) AS count FROM jobs WHERE kind = ?") + .bind("memory_consolidate_global") + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load phase2 job row count") + .try_get::("count") + .expect("phase2 job row count"); + assert_eq!( + global_job_row_count, 0, + "no-output without an existing stage1 output should not enqueue phase2" + ); + + let claim_phase2 = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + assert_eq!( + claim_phase2, + Phase2JobClaimOutcome::SkippedNotDirty, + "phase2 should remain clean when no-output deleted nothing" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_stage1_job_succeeded_no_output_enqueues_phase2_when_deleting_output() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let first_claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim initial stage1"); + let first_token = match first_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected initial stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded(thread_id, first_token.as_str(), 100, "raw", "sum", None) + .await + .expect("mark initial stage1 succeeded"), + "initial stage1 success should create stage1 output" + ); + + let phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 after initial output"); + let (phase2_token, phase2_input_watermark) = match phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim after initial output: {other:?}"), + }; + assert_eq!(phase2_input_watermark, 100); + assert!( + runtime + .mark_global_phase2_job_succeeded( + phase2_token.as_str(), + phase2_input_watermark, + &[], + ) + .await + .expect("mark initial phase2 succeeded"), + "initial phase2 success should clear global dirty state" + ); + + let no_output_claim = runtime + .try_claim_stage1_job(thread_id, owner_b, 101, 3600, 64) + .await + .expect("claim stage1 for no-output delete"); + let no_output_token = match no_output_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected no-output stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded_no_output(thread_id, no_output_token.as_str()) + .await + .expect("mark stage1 no-output after existing output"), + "no-output should succeed when deleting an existing stage1 output" + ); + + let output_row_count = + sqlx::query("SELECT COUNT(*) AS count FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load stage1 output count after delete") + .try_get::("count") + .expect("stage1 output count"); + assert_eq!(output_row_count, 0); + + let claim_phase2 = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 after no-output deletion"); + let (phase2_token, phase2_input_watermark) = match claim_phase2 { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim after no-output deletion: {other:?}"), + }; + assert_eq!(phase2_input_watermark, 101); + assert!( + runtime + .mark_global_phase2_job_succeeded( + phase2_token.as_str(), + phase2_input_watermark, + &[], + ) + .await + .expect("mark phase2 succeeded after no-output delete") + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn stage1_retry_exhaustion_does_not_block_newer_watermark() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + for attempt in 0..3 { + let claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3_600, 64) + .await + .expect("claim stage1 for retry exhaustion"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!( + "attempt {} should claim stage1 before retries are exhausted: {other:?}", + attempt + 1 + ), + }; + assert!( + runtime + .mark_stage1_job_failed(thread_id, ownership_token.as_str(), "boom", 0) + .await + .expect("mark stage1 failed"), + "attempt {} should decrement retry budget", + attempt + 1 + ); + } + + let exhausted_claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3_600, 64) + .await + .expect("claim stage1 after retry exhaustion"); + assert_eq!( + exhausted_claim, + Stage1JobClaimOutcome::SkippedRetryExhausted + ); + + let newer_source_claim = runtime + .try_claim_stage1_job(thread_id, owner, 101, 3_600, 64) + .await + .expect("claim stage1 with newer source watermark"); + assert!( + matches!(newer_source_claim, Stage1JobClaimOutcome::Claimed { .. }), + "newer source watermark should reset retry budget and be claimable" + ); + + let job_row = sqlx::query( + "SELECT retry_remaining, input_watermark FROM jobs WHERE kind = ? AND job_key = ?", + ) + .bind("memory_stage1") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load stage1 job row after newer-source claim"); + assert_eq!( + job_row + .try_get::("retry_remaining") + .expect("retry_remaining"), + 3 + ); + assert_eq!( + job_row + .try_get::("input_watermark") + .expect("input_watermark"), + 101 + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn phase2_global_consolidation_reruns_when_watermark_advances() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + runtime + .enqueue_global_consolidation(100) + .await + .expect("enqueue global consolidation"); + + let claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (ownership_token, input_watermark) = match claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_global_phase2_job_succeeded(ownership_token.as_str(), input_watermark, &[],) + .await + .expect("mark phase2 succeeded"), + "phase2 success should finalize for current token" + ); + + let claim_up_to_date = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 up-to-date"); + assert_eq!(claim_up_to_date, Phase2JobClaimOutcome::SkippedNotDirty); + + runtime + .enqueue_global_consolidation(101) + .await + .expect("enqueue global consolidation again"); + + let claim_rerun = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 rerun"); + assert!( + matches!(claim_rerun, Phase2JobClaimOutcome::Claimed { .. }), + "advanced watermark should be claimable" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn list_stage1_outputs_for_global_returns_latest_outputs() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_id_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id_a, + codex_home.join("workspace-a"), + )) + .await + .expect("upsert thread a"); + let mut metadata_b = + test_thread_metadata(&codex_home, thread_id_b, codex_home.join("workspace-b")); + metadata_b.git_branch = Some("feature/stage1-b".to_string()); + runtime + .upsert_thread(&metadata_b) + .await + .expect("upsert thread b"); + + let claim = runtime + .try_claim_stage1_job(thread_id_a, owner, 100, 3600, 64) + .await + .expect("claim stage1 a"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id_a, + ownership_token.as_str(), + 100, + "raw memory a", + "summary a", + None, + ) + .await + .expect("mark stage1 succeeded a"), + "stage1 success should persist output a" + ); + + let claim = runtime + .try_claim_stage1_job(thread_id_b, owner, 101, 3600, 64) + .await + .expect("claim stage1 b"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id_b, + ownership_token.as_str(), + 101, + "raw memory b", + "summary b", + Some("rollout-b"), + ) + .await + .expect("mark stage1 succeeded b"), + "stage1 success should persist output b" + ); + + let outputs = runtime + .list_stage1_outputs_for_global(10) + .await + .expect("list stage1 outputs for global"); + assert_eq!(outputs.len(), 2); + assert_eq!(outputs[0].thread_id, thread_id_b); + assert_eq!(outputs[0].rollout_summary, "summary b"); + assert_eq!(outputs[0].rollout_slug.as_deref(), Some("rollout-b")); + assert_eq!(outputs[0].cwd, codex_home.join("workspace-b")); + assert_eq!(outputs[0].git_branch.as_deref(), Some("feature/stage1-b")); + assert_eq!(outputs[1].thread_id, thread_id_a); + assert_eq!(outputs[1].rollout_summary, "summary a"); + assert_eq!(outputs[1].rollout_slug, None); + assert_eq!(outputs[1].cwd, codex_home.join("workspace-a")); + assert_eq!(outputs[1].git_branch, None); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn list_stage1_outputs_for_global_skips_empty_payloads() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id_non_empty = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_id_empty = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id_non_empty, + codex_home.join("workspace-non-empty"), + )) + .await + .expect("upsert non-empty thread"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id_empty, + codex_home.join("workspace-empty"), + )) + .await + .expect("upsert empty thread"); + + sqlx::query( + r#" +INSERT INTO stage1_outputs (thread_id, source_updated_at, raw_memory, rollout_summary, generated_at) +VALUES (?, ?, ?, ?, ?) + "#, + ) + .bind(thread_id_non_empty.to_string()) + .bind(100_i64) + .bind("raw memory") + .bind("summary") + .bind(100_i64) + .execute(runtime.pool.as_ref()) + .await + .expect("insert non-empty stage1 output"); + sqlx::query( + r#" +INSERT INTO stage1_outputs (thread_id, source_updated_at, raw_memory, rollout_summary, generated_at) +VALUES (?, ?, ?, ?, ?) + "#, + ) + .bind(thread_id_empty.to_string()) + .bind(101_i64) + .bind("") + .bind("") + .bind(101_i64) + .execute(runtime.pool.as_ref()) + .await + .expect("insert empty stage1 output"); + + let outputs = runtime + .list_stage1_outputs_for_global(1) + .await + .expect("list stage1 outputs for global"); + assert_eq!(outputs.len(), 1); + assert_eq!(outputs[0].thread_id, thread_id_non_empty); + assert_eq!(outputs[0].rollout_summary, "summary"); + assert_eq!(outputs[0].cwd, codex_home.join("workspace-non-empty")); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn list_stage1_outputs_for_global_skips_polluted_threads() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id_enabled = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_id_polluted = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + for (thread_id, workspace) in [ + (thread_id_enabled, "workspace-enabled"), + (thread_id_polluted, "workspace-polluted"), + ] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(workspace), + )) + .await + .expect("upsert thread"); + + let claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + 100, + "raw memory", + "summary", + None, + ) + .await + .expect("mark stage1 succeeded"), + "stage1 success should persist output" + ); + } + + runtime + .set_thread_memory_mode(thread_id_polluted, "polluted") + .await + .expect("mark thread polluted"); + + let outputs = runtime + .list_stage1_outputs_for_global(10) + .await + .expect("list stage1 outputs for global"); + assert_eq!(outputs.len(), 1); + assert_eq!(outputs[0].thread_id, thread_id_enabled); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_reports_added_retained_and_removed_rows() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_id_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_id_c = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + for (thread_id, workspace) in [ + (thread_id_a, "workspace-a"), + (thread_id_b, "workspace-b"), + (thread_id_c, "workspace-c"), + ] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(workspace), + )) + .await + .expect("upsert thread"); + } + + for (thread_id, updated_at, slug) in [ + (thread_id_a, 100, Some("rollout-a")), + (thread_id_b, 101, Some("rollout-b")), + (thread_id_c, 102, Some("rollout-c")), + ] { + let claim = runtime + .try_claim_stage1_job(thread_id, owner, updated_at, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + updated_at, + &format!("raw-{updated_at}"), + &format!("summary-{updated_at}"), + slug, + ) + .await + .expect("mark stage1 succeeded"), + "stage1 success should persist output" + ); + } + + let claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (ownership_token, input_watermark) = match claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + assert_eq!(input_watermark, 102); + let selected_outputs = runtime + .list_stage1_outputs_for_global(10) + .await + .expect("list stage1 outputs for global") + .into_iter() + .filter(|output| output.thread_id == thread_id_c || output.thread_id == thread_id_a) + .collect::>(); + assert!( + runtime + .mark_global_phase2_job_succeeded( + ownership_token.as_str(), + input_watermark, + &selected_outputs, + ) + .await + .expect("mark phase2 success with selection"), + "phase2 success should persist selected rows" + ); + + let selection = runtime + .get_phase2_input_selection(2, 36_500) + .await + .expect("load phase2 input selection"); + + assert_eq!(selection.selected.len(), 2); + assert_eq!(selection.previous_selected.len(), 2); + assert_eq!(selection.selected[0].thread_id, thread_id_c); + assert_eq!( + selection.selected[0].rollout_path, + codex_home.join(format!("rollout-{thread_id_c}.jsonl")) + ); + assert_eq!(selection.selected[1].thread_id, thread_id_b); + assert_eq!(selection.retained_thread_ids, vec![thread_id_c]); + + assert_eq!(selection.removed.len(), 1); + assert_eq!(selection.removed[0].thread_id, thread_id_a); + assert_eq!( + selection.removed[0].rollout_slug.as_deref(), + Some("rollout-a") + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_marks_polluted_previous_selection_as_removed() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id_enabled = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let thread_id_polluted = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + for (thread_id, updated_at) in [(thread_id_enabled, 100), (thread_id_polluted, 101)] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(thread_id.to_string()), + )) + .await + .expect("upsert thread"); + + let claim = runtime + .try_claim_stage1_job(thread_id, owner, updated_at, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + updated_at, + &format!("raw-{updated_at}"), + &format!("summary-{updated_at}"), + None, + ) + .await + .expect("mark stage1 succeeded"), + "stage1 success should persist output" + ); + } + + let claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (ownership_token, input_watermark) = match claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + let selected_outputs = runtime + .list_stage1_outputs_for_global(10) + .await + .expect("list stage1 outputs for global"); + assert!( + runtime + .mark_global_phase2_job_succeeded( + ownership_token.as_str(), + input_watermark, + &selected_outputs, + ) + .await + .expect("mark phase2 success"), + "phase2 success should persist selected rows" + ); + + runtime + .set_thread_memory_mode(thread_id_polluted, "polluted") + .await + .expect("mark thread polluted"); + + let selection = runtime + .get_phase2_input_selection(2, 36_500) + .await + .expect("load phase2 input selection"); + + assert_eq!(selection.selected.len(), 1); + assert_eq!(selection.selected[0].thread_id, thread_id_enabled); + assert_eq!(selection.previous_selected.len(), 2); + assert!( + selection + .previous_selected + .iter() + .any(|item| item.thread_id == thread_id_enabled) + ); + assert!( + selection + .previous_selected + .iter() + .any(|item| item.thread_id == thread_id_polluted) + ); + assert_eq!(selection.retained_thread_ids, vec![thread_id_enabled]); + assert_eq!(selection.removed.len(), 1); + assert_eq!(selection.removed[0].thread_id, thread_id_polluted); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_thread_memory_mode_polluted_enqueues_phase2_for_selected_threads() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + 100, + "raw", + "summary", + None, + ) + .await + .expect("mark stage1 succeeded"), + "stage1 success should persist output" + ); + + let phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (phase2_token, input_watermark) = match phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + let selected_outputs = runtime + .list_stage1_outputs_for_global(10) + .await + .expect("list stage1 outputs"); + assert!( + runtime + .mark_global_phase2_job_succeeded( + phase2_token.as_str(), + input_watermark, + &selected_outputs, + ) + .await + .expect("mark phase2 success"), + "phase2 success should persist selected rows" + ); + + assert!( + runtime + .mark_thread_memory_mode_polluted(thread_id) + .await + .expect("mark thread polluted"), + "thread should transition to polluted" + ); + + let next_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2 after pollution"); + assert!(matches!(next_claim, Phase2JobClaimOutcome::Claimed { .. })); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_treats_regenerated_selected_rows_as_added() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let first_claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim initial stage1"); + let first_token = match first_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + first_token.as_str(), + 100, + "raw-100", + "summary-100", + Some("rollout-100"), + ) + .await + .expect("mark initial stage1 success"), + "initial stage1 success should persist output" + ); + + let phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (phase2_token, input_watermark) = match phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + let selected_outputs = runtime + .list_stage1_outputs_for_global(1) + .await + .expect("list selected outputs"); + assert!( + runtime + .mark_global_phase2_job_succeeded( + phase2_token.as_str(), + input_watermark, + &selected_outputs, + ) + .await + .expect("mark phase2 success"), + "phase2 success should persist selected rows" + ); + + let refreshed_claim = runtime + .try_claim_stage1_job(thread_id, owner, 101, 3600, 64) + .await + .expect("claim refreshed stage1"); + let refreshed_token = match refreshed_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + refreshed_token.as_str(), + 101, + "raw-101", + "summary-101", + Some("rollout-101"), + ) + .await + .expect("mark refreshed stage1 success"), + "refreshed stage1 success should persist output" + ); + + let selection = runtime + .get_phase2_input_selection(1, 36_500) + .await + .expect("load phase2 input selection"); + assert_eq!(selection.selected.len(), 1); + assert_eq!(selection.previous_selected.len(), 1); + assert_eq!(selection.selected[0].thread_id, thread_id); + assert_eq!(selection.selected[0].source_updated_at.timestamp(), 101); + assert!(selection.retained_thread_ids.is_empty()); + assert!(selection.removed.is_empty()); + + let (selected_for_phase2, selected_for_phase2_source_updated_at) = + sqlx::query_as::<_, (i64, Option)>( + "SELECT selected_for_phase2, selected_for_phase2_source_updated_at FROM stage1_outputs WHERE thread_id = ?", + ) + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load selected_for_phase2"); + assert_eq!(selected_for_phase2, 1); + assert_eq!(selected_for_phase2_source_updated_at, Some(100)); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_reports_regenerated_previous_selection_as_removed() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread a"); + let thread_id_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread b"); + let thread_id_c = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread c"); + let thread_id_d = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread d"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + for (thread_id, workspace) in [ + (thread_id_a, "workspace-a"), + (thread_id_b, "workspace-b"), + (thread_id_c, "workspace-c"), + (thread_id_d, "workspace-d"), + ] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(workspace), + )) + .await + .expect("upsert thread"); + } + + for (thread_id, updated_at, slug) in [ + (thread_id_a, 100, Some("rollout-a-100")), + (thread_id_b, 101, Some("rollout-b-101")), + (thread_id_c, 99, Some("rollout-c-99")), + (thread_id_d, 98, Some("rollout-d-98")), + ] { + let claim = runtime + .try_claim_stage1_job(thread_id, owner, updated_at, 3600, 64) + .await + .expect("claim initial stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + updated_at, + &format!("raw-{updated_at}"), + &format!("summary-{updated_at}"), + slug, + ) + .await + .expect("mark stage1 succeeded"), + "stage1 success should persist output" + ); + } + + let phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (phase2_token, input_watermark) = match phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + let selected_outputs = runtime + .list_stage1_outputs_for_global(2) + .await + .expect("list selected outputs"); + assert_eq!( + selected_outputs + .iter() + .map(|output| output.thread_id) + .collect::>(), + vec![thread_id_b, thread_id_a] + ); + assert!( + runtime + .mark_global_phase2_job_succeeded( + phase2_token.as_str(), + input_watermark, + &selected_outputs, + ) + .await + .expect("mark phase2 success"), + "phase2 success should persist selected rows" + ); + + for (thread_id, updated_at, slug) in [ + (thread_id_a, 102, Some("rollout-a-102")), + (thread_id_c, 103, Some("rollout-c-103")), + (thread_id_d, 104, Some("rollout-d-104")), + ] { + let claim = runtime + .try_claim_stage1_job(thread_id, owner, updated_at, 3600, 64) + .await + .expect("claim refreshed stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + updated_at, + &format!("raw-{updated_at}"), + &format!("summary-{updated_at}"), + slug, + ) + .await + .expect("mark refreshed stage1 success"), + "refreshed stage1 success should persist output" + ); + } + + let selection = runtime + .get_phase2_input_selection(2, 36_500) + .await + .expect("load phase2 input selection"); + assert_eq!( + selection + .selected + .iter() + .map(|output| output.thread_id) + .collect::>(), + vec![thread_id_d, thread_id_c] + ); + assert_eq!( + selection + .previous_selected + .iter() + .map(|output| output.thread_id) + .collect::>(), + vec![thread_id_a, thread_id_b] + ); + assert!(selection.retained_thread_ids.is_empty()); + assert_eq!( + selection + .removed + .iter() + .map(|output| (output.thread_id, output.source_updated_at.timestamp())) + .collect::>(), + vec![(thread_id_a, 102), (thread_id_b, 101)] + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_global_phase2_job_succeeded_updates_selected_snapshot_timestamp() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let initial_claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim initial stage1"); + let initial_token = match initial_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + initial_token.as_str(), + 100, + "raw-100", + "summary-100", + Some("rollout-100"), + ) + .await + .expect("mark initial stage1 success"), + "initial stage1 success should persist output" + ); + + let first_phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim first phase2"); + let (first_phase2_token, first_input_watermark) = match first_phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected first phase2 claim outcome: {other:?}"), + }; + let first_selected_outputs = runtime + .list_stage1_outputs_for_global(1) + .await + .expect("list first selected outputs"); + assert!( + runtime + .mark_global_phase2_job_succeeded( + first_phase2_token.as_str(), + first_input_watermark, + &first_selected_outputs, + ) + .await + .expect("mark first phase2 success"), + "first phase2 success should persist selected rows" + ); + + let refreshed_claim = runtime + .try_claim_stage1_job(thread_id, owner, 101, 3600, 64) + .await + .expect("claim refreshed stage1"); + let refreshed_token = match refreshed_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected refreshed stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + refreshed_token.as_str(), + 101, + "raw-101", + "summary-101", + Some("rollout-101"), + ) + .await + .expect("mark refreshed stage1 success"), + "refreshed stage1 success should persist output" + ); + + let second_phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim second phase2"); + let (second_phase2_token, second_input_watermark) = match second_phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected second phase2 claim outcome: {other:?}"), + }; + let second_selected_outputs = runtime + .list_stage1_outputs_for_global(1) + .await + .expect("list second selected outputs"); + assert_eq!( + second_selected_outputs[0].source_updated_at.timestamp(), + 101 + ); + assert!( + runtime + .mark_global_phase2_job_succeeded( + second_phase2_token.as_str(), + second_input_watermark, + &second_selected_outputs, + ) + .await + .expect("mark second phase2 success"), + "second phase2 success should persist selected rows" + ); + + let selection = runtime + .get_phase2_input_selection(1, 36_500) + .await + .expect("load phase2 input selection after refresh"); + assert_eq!(selection.retained_thread_ids, vec![thread_id]); + + let (selected_for_phase2, selected_for_phase2_source_updated_at) = + sqlx::query_as::<_, (i64, Option)>( + "SELECT selected_for_phase2, selected_for_phase2_source_updated_at FROM stage1_outputs WHERE thread_id = ?", + ) + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load selected snapshot after phase2"); + assert_eq!(selected_for_phase2, 1); + assert_eq!(selected_for_phase2_source_updated_at, Some(101)); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_global_phase2_job_succeeded_only_marks_exact_selected_snapshots() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_id = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join("workspace"), + )) + .await + .expect("upsert thread"); + + let initial_claim = runtime + .try_claim_stage1_job(thread_id, owner, 100, 3600, 64) + .await + .expect("claim initial stage1"); + let initial_token = match initial_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + initial_token.as_str(), + 100, + "raw-100", + "summary-100", + Some("rollout-100"), + ) + .await + .expect("mark initial stage1 success"), + "initial stage1 success should persist output" + ); + + let phase2_claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim phase2"); + let (phase2_token, input_watermark) = match phase2_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected phase2 claim outcome: {other:?}"), + }; + let selected_outputs = runtime + .list_stage1_outputs_for_global(1) + .await + .expect("list selected outputs"); + assert_eq!(selected_outputs[0].source_updated_at.timestamp(), 100); + + let refreshed_claim = runtime + .try_claim_stage1_job(thread_id, owner, 101, 3600, 64) + .await + .expect("claim refreshed stage1"); + let refreshed_token = match refreshed_claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + refreshed_token.as_str(), + 101, + "raw-101", + "summary-101", + Some("rollout-101"), + ) + .await + .expect("mark refreshed stage1 success"), + "refreshed stage1 success should persist output" + ); + + assert!( + runtime + .mark_global_phase2_job_succeeded( + phase2_token.as_str(), + input_watermark, + &selected_outputs, + ) + .await + .expect("mark phase2 success"), + "phase2 success should still complete" + ); + + let (selected_for_phase2, selected_for_phase2_source_updated_at) = + sqlx::query_as::<_, (i64, Option)>( + "SELECT selected_for_phase2, selected_for_phase2_source_updated_at FROM stage1_outputs WHERE thread_id = ?", + ) + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load selected_for_phase2"); + assert_eq!(selected_for_phase2, 0); + assert_eq!(selected_for_phase2_source_updated_at, None); + + let selection = runtime + .get_phase2_input_selection(1, 36_500) + .await + .expect("load phase2 input selection"); + assert_eq!(selection.selected.len(), 1); + assert_eq!(selection.selected[0].source_updated_at.timestamp(), 101); + assert!(selection.retained_thread_ids.is_empty()); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn record_stage1_output_usage_updates_usage_metadata() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id a"); + let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id b"); + let missing = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("missing id"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_a, + codex_home.join("workspace-a"), + )) + .await + .expect("upsert thread a"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_b, + codex_home.join("workspace-b"), + )) + .await + .expect("upsert thread b"); + + let claim_a = runtime + .try_claim_stage1_job(thread_a, owner, 100, 3600, 64) + .await + .expect("claim stage1 a"); + let token_a = match claim_a { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome for a: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded(thread_a, token_a.as_str(), 100, "raw a", "sum a", None) + .await + .expect("mark stage1 succeeded a") + ); + + let claim_b = runtime + .try_claim_stage1_job(thread_b, owner, 101, 3600, 64) + .await + .expect("claim stage1 b"); + let token_b = match claim_b { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome for b: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded(thread_b, token_b.as_str(), 101, "raw b", "sum b", None) + .await + .expect("mark stage1 succeeded b") + ); + + let updated_rows = runtime + .record_stage1_output_usage(&[thread_a, thread_a, thread_b, missing]) + .await + .expect("record stage1 output usage"); + assert_eq!(updated_rows, 3); + + let row_a = + sqlx::query("SELECT usage_count, last_usage FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_a.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load stage1 usage row a"); + let row_b = + sqlx::query("SELECT usage_count, last_usage FROM stage1_outputs WHERE thread_id = ?") + .bind(thread_b.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("load stage1 usage row b"); + + assert_eq!( + row_a + .try_get::("usage_count") + .expect("usage_count a"), + 2 + ); + assert_eq!( + row_b + .try_get::("usage_count") + .expect("usage_count b"), + 1 + ); + + let last_usage_a = row_a.try_get::("last_usage").expect("last_usage a"); + let last_usage_b = row_b.try_get::("last_usage").expect("last_usage b"); + assert_eq!(last_usage_a, last_usage_b); + assert!(last_usage_a > 0); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_prioritizes_usage_count_then_recent_usage() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let now = Utc::now(); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id a"); + let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id b"); + let thread_c = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id c"); + + for (thread_id, workspace) in [ + (thread_a, "workspace-a"), + (thread_b, "workspace-b"), + (thread_c, "workspace-c"), + ] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(workspace), + )) + .await + .expect("upsert thread"); + } + + for (thread_id, generated_at, summary) in [ + (thread_a, now - Duration::days(3), "summary-a"), + (thread_b, now - Duration::days(2), "summary-b"), + (thread_c, now - Duration::days(1), "summary-c"), + ] { + let source_updated_at = generated_at.timestamp(); + let claim = runtime + .try_claim_stage1_job(thread_id, owner, source_updated_at, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + source_updated_at, + &format!("raw-{summary}"), + summary, + None, + ) + .await + .expect("mark stage1 success"), + "stage1 success should persist output" + ); + } + + for (thread_id, usage_count, last_usage) in [ + (thread_a, 5_i64, now - Duration::days(10)), + (thread_b, 5_i64, now - Duration::days(1)), + (thread_c, 1_i64, now - Duration::hours(1)), + ] { + sqlx::query( + "UPDATE stage1_outputs SET usage_count = ?, last_usage = ? WHERE thread_id = ?", + ) + .bind(usage_count) + .bind(last_usage.timestamp()) + .bind(thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("update usage metadata"); + } + + let selection = runtime + .get_phase2_input_selection(3, 30) + .await + .expect("load phase2 input selection"); + + assert_eq!( + selection + .selected + .iter() + .map(|output| output.thread_id) + .collect::>(), + vec![thread_b, thread_a, thread_c] + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_excludes_stale_used_memories_but_keeps_fresh_never_used() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let now = Utc::now(); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id a"); + let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id b"); + let thread_c = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id c"); + + for (thread_id, workspace) in [ + (thread_a, "workspace-a"), + (thread_b, "workspace-b"), + (thread_c, "workspace-c"), + ] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(workspace), + )) + .await + .expect("upsert thread"); + } + + for (thread_id, generated_at, summary) in [ + (thread_a, now - Duration::days(40), "summary-a"), + (thread_b, now - Duration::days(2), "summary-b"), + (thread_c, now - Duration::days(50), "summary-c"), + ] { + let source_updated_at = generated_at.timestamp(); + let claim = runtime + .try_claim_stage1_job(thread_id, owner, source_updated_at, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + source_updated_at, + &format!("raw-{summary}"), + summary, + None, + ) + .await + .expect("mark stage1 success"), + "stage1 success should persist output" + ); + } + + for (thread_id, usage_count, last_usage) in [ + (thread_a, Some(9_i64), Some(now - Duration::days(31))), + (thread_b, None, None), + (thread_c, Some(1_i64), Some(now - Duration::days(1))), + ] { + sqlx::query( + "UPDATE stage1_outputs SET usage_count = ?, last_usage = ? WHERE thread_id = ?", + ) + .bind(usage_count) + .bind(last_usage.map(|value| value.timestamp())) + .bind(thread_id.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("update usage metadata"); + } + + let selection = runtime + .get_phase2_input_selection(3, 30) + .await + .expect("load phase2 input selection"); + + assert_eq!( + selection + .selected + .iter() + .map(|output| output.thread_id) + .collect::>(), + vec![thread_c, thread_b] + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn get_phase2_input_selection_prefers_recent_thread_updates_over_recent_generation() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + let older_thread = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("older thread id"); + let newer_thread = + ThreadId::from_string(&Uuid::new_v4().to_string()).expect("newer thread id"); + + for (thread_id, workspace) in [ + (older_thread, "workspace-older"), + (newer_thread, "workspace-newer"), + ] { + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_id, + codex_home.join(workspace), + )) + .await + .expect("upsert thread"); + } + + for (thread_id, source_updated_at, summary) in [ + (older_thread, 100_i64, "summary-older"), + (newer_thread, 200_i64, "summary-newer"), + ] { + let claim = runtime + .try_claim_stage1_job(thread_id, owner, source_updated_at, 3600, 64) + .await + .expect("claim stage1"); + let ownership_token = match claim { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_id, + ownership_token.as_str(), + source_updated_at, + &format!("raw-{summary}"), + summary, + None, + ) + .await + .expect("mark stage1 success"), + "stage1 success should persist output" + ); + } + + sqlx::query("UPDATE stage1_outputs SET generated_at = ? WHERE thread_id = ?") + .bind(300_i64) + .bind(older_thread.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("update older generated_at"); + sqlx::query("UPDATE stage1_outputs SET generated_at = ? WHERE thread_id = ?") + .bind(150_i64) + .bind(newer_thread.to_string()) + .execute(runtime.pool.as_ref()) + .await + .expect("update newer generated_at"); + + let selection = runtime + .get_phase2_input_selection(1, 36_500) + .await + .expect("load phase2 input selection"); + + assert_eq!(selection.selected.len(), 1); + assert_eq!(selection.selected[0].thread_id, newer_thread); + assert_eq!(selection.selected[0].source_updated_at.timestamp(), 200); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn mark_stage1_job_succeeded_enqueues_global_consolidation() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + let thread_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id a"); + let thread_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("thread id b"); + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner id"); + + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_a, + codex_home.join("workspace-a"), + )) + .await + .expect("upsert thread a"); + runtime + .upsert_thread(&test_thread_metadata( + &codex_home, + thread_b, + codex_home.join("workspace-b"), + )) + .await + .expect("upsert thread b"); + + let claim_a = runtime + .try_claim_stage1_job(thread_a, owner, 100, 3600, 64) + .await + .expect("claim stage1 a"); + let token_a = match claim_a { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome for thread a: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_a, + token_a.as_str(), + 100, + "raw-a", + "summary-a", + None, + ) + .await + .expect("mark stage1 succeeded a"), + "stage1 success should persist output for thread a" + ); + + let claim_b = runtime + .try_claim_stage1_job(thread_b, owner, 101, 3600, 64) + .await + .expect("claim stage1 b"); + let token_b = match claim_b { + Stage1JobClaimOutcome::Claimed { ownership_token } => ownership_token, + other => panic!("unexpected stage1 claim outcome for thread b: {other:?}"), + }; + assert!( + runtime + .mark_stage1_job_succeeded( + thread_b, + token_b.as_str(), + 101, + "raw-b", + "summary-b", + None, + ) + .await + .expect("mark stage1 succeeded b"), + "stage1 success should persist output for thread b" + ); + + let claim = runtime + .try_claim_global_phase2_job(owner, 3600) + .await + .expect("claim global consolidation"); + let input_watermark = match claim { + Phase2JobClaimOutcome::Claimed { + input_watermark, .. + } => input_watermark, + other => panic!("unexpected global consolidation claim outcome: {other:?}"), + }; + assert_eq!(input_watermark, 101); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn phase2_global_lock_allows_only_one_fresh_runner() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .enqueue_global_consolidation(200) + .await + .expect("enqueue global consolidation"); + + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner a"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner b"); + + let running_claim = runtime + .try_claim_global_phase2_job(owner_a, 3600) + .await + .expect("claim global lock"); + assert!( + matches!(running_claim, Phase2JobClaimOutcome::Claimed { .. }), + "first owner should claim global lock" + ); + + let second_claim = runtime + .try_claim_global_phase2_job(owner_b, 3600) + .await + .expect("claim global lock from second owner"); + assert_eq!(second_claim, Phase2JobClaimOutcome::SkippedRunning); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn phase2_global_lock_stale_lease_allows_takeover() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .enqueue_global_consolidation(300) + .await + .expect("enqueue global consolidation"); + + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner a"); + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner b"); + + let initial_claim = runtime + .try_claim_global_phase2_job(owner_a, 3600) + .await + .expect("claim initial global lock"); + let token_a = match initial_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, .. + } => ownership_token, + other => panic!("unexpected initial claim outcome: {other:?}"), + }; + + sqlx::query("UPDATE jobs SET lease_until = ? WHERE kind = ? AND job_key = ?") + .bind(Utc::now().timestamp() - 1) + .bind("memory_consolidate_global") + .bind("global") + .execute(runtime.pool.as_ref()) + .await + .expect("expire global consolidation lease"); + + let takeover_claim = runtime + .try_claim_global_phase2_job(owner_b, 3600) + .await + .expect("claim stale global lock"); + let (token_b, input_watermark) = match takeover_claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => (ownership_token, input_watermark), + other => panic!("unexpected takeover claim outcome: {other:?}"), + }; + assert_ne!(token_a, token_b); + assert_eq!(input_watermark, 300); + + assert_eq!( + runtime + .mark_global_phase2_job_succeeded(token_a.as_str(), 300, &[]) + .await + .expect("mark stale owner success result"), + false, + "stale owner should lose finalization ownership after takeover" + ); + assert!( + runtime + .mark_global_phase2_job_succeeded(token_b.as_str(), 300, &[]) + .await + .expect("mark takeover owner success"), + "takeover owner should finalize consolidation" + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn phase2_backfilled_inputs_below_last_success_still_become_dirty() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .enqueue_global_consolidation(500) + .await + .expect("enqueue initial consolidation"); + let owner_a = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner a"); + let claim_a = runtime + .try_claim_global_phase2_job(owner_a, 3_600) + .await + .expect("claim initial consolidation"); + let token_a = match claim_a { + Phase2JobClaimOutcome::Claimed { + ownership_token, + input_watermark, + } => { + assert_eq!(input_watermark, 500); + ownership_token + } + other => panic!("unexpected initial phase2 claim outcome: {other:?}"), + }; + assert!( + runtime + .mark_global_phase2_job_succeeded(token_a.as_str(), 500, &[]) + .await + .expect("mark initial phase2 success"), + "initial phase2 success should finalize" + ); + + runtime + .enqueue_global_consolidation(400) + .await + .expect("enqueue backfilled consolidation"); + + let owner_b = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner b"); + let claim_b = runtime + .try_claim_global_phase2_job(owner_b, 3_600) + .await + .expect("claim backfilled consolidation"); + match claim_b { + Phase2JobClaimOutcome::Claimed { + input_watermark, .. + } => { + assert!( + input_watermark > 500, + "backfilled enqueue should advance dirty watermark beyond last success" + ); + } + other => panic!("unexpected backfilled phase2 claim outcome: {other:?}"), + } + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } + + #[tokio::test] + async fn phase2_failure_fallback_updates_unowned_running_job() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("initialize runtime"); + + runtime + .enqueue_global_consolidation(400) + .await + .expect("enqueue global consolidation"); + + let owner = ThreadId::from_string(&Uuid::new_v4().to_string()).expect("owner"); + let claim = runtime + .try_claim_global_phase2_job(owner, 3_600) + .await + .expect("claim global consolidation"); + let ownership_token = match claim { + Phase2JobClaimOutcome::Claimed { + ownership_token, .. + } => ownership_token, + other => panic!("unexpected claim outcome: {other:?}"), + }; + + sqlx::query("UPDATE jobs SET ownership_token = NULL WHERE kind = ? AND job_key = ?") + .bind("memory_consolidate_global") + .bind("global") + .execute(runtime.pool.as_ref()) + .await + .expect("clear ownership token"); + + assert_eq!( + runtime + .mark_global_phase2_job_failed(ownership_token.as_str(), "lost", 3_600) + .await + .expect("mark phase2 failed with strict ownership"), + false, + "strict failure update should not match unowned running job" + ); + assert!( + runtime + .mark_global_phase2_job_failed_if_unowned(ownership_token.as_str(), "lost", 3_600) + .await + .expect("fallback failure update should match unowned running job"), + "fallback failure update should transition the unowned running job" + ); + + let claim = runtime + .try_claim_global_phase2_job(ThreadId::new(), 3_600) + .await + .expect("claim after fallback failure"); + assert_eq!(claim, Phase2JobClaimOutcome::SkippedNotDirty); + + let _ = tokio::fs::remove_dir_all(codex_home).await; + } +} diff --git a/codex-rs/state/src/runtime/test_support.rs b/codex-rs/state/src/runtime/test_support.rs new file mode 100644 index 0000000000..d749fe2bfb --- /dev/null +++ b/codex-rs/state/src/runtime/test_support.rs @@ -0,0 +1,64 @@ +#[cfg(test)] +use chrono::DateTime; +#[cfg(test)] +use chrono::Utc; +#[cfg(test)] +use codex_protocol::ThreadId; +#[cfg(test)] +use codex_protocol::protocol::AskForApproval; +#[cfg(test)] +use codex_protocol::protocol::SandboxPolicy; +#[cfg(test)] +use std::path::Path; +#[cfg(test)] +use std::path::PathBuf; +#[cfg(test)] +use std::time::SystemTime; +#[cfg(test)] +use std::time::UNIX_EPOCH; +#[cfg(test)] +use uuid::Uuid; + +#[cfg(test)] +use crate::ThreadMetadata; + +#[cfg(test)] +pub(super) fn unique_temp_dir() -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()); + std::env::temp_dir().join(format!( + "codex-state-runtime-test-{nanos}-{}", + Uuid::new_v4() + )) +} + +#[cfg(test)] +pub(super) fn test_thread_metadata( + codex_home: &Path, + thread_id: ThreadId, + cwd: PathBuf, +) -> ThreadMetadata { + let now = DateTime::::from_timestamp(1_700_000_000, 0).expect("timestamp"); + ThreadMetadata { + id: thread_id, + rollout_path: codex_home.join(format!("rollout-{thread_id}.jsonl")), + created_at: now, + updated_at: now, + source: "cli".to_string(), + agent_nickname: None, + agent_role: None, + model_provider: "test-provider".to_string(), + cwd, + cli_version: "0.0.0".to_string(), + title: String::new(), + sandbox_policy: crate::extract::enum_to_string(&SandboxPolicy::new_read_only_policy()), + approval_mode: crate::extract::enum_to_string(&AskForApproval::OnRequest), + tokens_used: 0, + first_user_message: Some("hello".to_string()), + archived_at: None, + git_sha: None, + git_branch: None, + git_origin_url: None, + } +} diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs new file mode 100644 index 0000000000..f9e939a4a1 --- /dev/null +++ b/codex-rs/state/src/runtime/threads.rs @@ -0,0 +1,657 @@ +use super::*; + +impl StateRuntime { + pub async fn get_thread(&self, id: ThreadId) -> anyhow::Result> { + let row = sqlx::query( + r#" +SELECT + id, + rollout_path, + created_at, + updated_at, + source, + agent_nickname, + agent_role, + model_provider, + cwd, + cli_version, + title, + sandbox_policy, + approval_mode, + tokens_used, + first_user_message, + archived_at, + git_sha, + git_branch, + git_origin_url +FROM threads +WHERE id = ? + "#, + ) + .bind(id.to_string()) + .fetch_optional(self.pool.as_ref()) + .await?; + row.map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) + .transpose() + } + + pub async fn get_thread_memory_mode(&self, id: ThreadId) -> anyhow::Result> { + let row = sqlx::query("SELECT memory_mode FROM threads WHERE id = ?") + .bind(id.to_string()) + .fetch_optional(self.pool.as_ref()) + .await?; + Ok(row.and_then(|row| row.try_get("memory_mode").ok())) + } + + /// 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 name, description, input_schema +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 { + name: row.try_get("name")?, + description: row.try_get("description")?, + input_schema, + }); + } + Ok(Some(tools)) + } + + /// Find a rollout path by thread id using the underlying database. + pub async fn find_rollout_path_by_id( + &self, + id: ThreadId, + archived_only: Option, + ) -> anyhow::Result> { + let mut builder = + QueryBuilder::::new("SELECT rollout_path FROM threads WHERE id = "); + builder.push_bind(id.to_string()); + match archived_only { + Some(true) => { + builder.push(" AND archived = 1"); + } + Some(false) => { + builder.push(" AND archived = 0"); + } + None => {} + } + let row = builder.build().fetch_optional(self.pool.as_ref()).await?; + Ok(row + .and_then(|r| r.try_get::("rollout_path").ok()) + .map(PathBuf::from)) + } + + /// List threads using the underlying database. + #[allow(clippy::too_many_arguments)] + pub async fn list_threads( + &self, + page_size: usize, + anchor: Option<&crate::Anchor>, + sort_key: crate::SortKey, + allowed_sources: &[String], + model_providers: Option<&[String]>, + archived_only: bool, + search_term: Option<&str>, + ) -> anyhow::Result { + let limit = page_size.saturating_add(1); + + let mut builder = QueryBuilder::::new( + r#" +SELECT + id, + rollout_path, + created_at, + updated_at, + source, + agent_nickname, + agent_role, + model_provider, + cwd, + cli_version, + title, + sandbox_policy, + approval_mode, + tokens_used, + first_user_message, + archived_at, + git_sha, + git_branch, + git_origin_url +FROM threads + "#, + ); + push_thread_filters( + &mut builder, + archived_only, + allowed_sources, + model_providers, + anchor, + sort_key, + search_term, + ); + push_thread_order_and_limit(&mut builder, sort_key, limit); + + let rows = builder.build().fetch_all(self.pool.as_ref()).await?; + let mut items = rows + .into_iter() + .map(|row| ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)) + .collect::, _>>()?; + let num_scanned_rows = items.len(); + let next_anchor = if items.len() > page_size { + items.pop(); + items + .last() + .and_then(|item| anchor_from_item(item, sort_key)) + } else { + None + }; + Ok(ThreadsPage { + items, + next_anchor, + num_scanned_rows, + }) + } + + /// List thread ids using the underlying database (no rollout scanning). + pub async fn list_thread_ids( + &self, + limit: usize, + anchor: Option<&crate::Anchor>, + sort_key: crate::SortKey, + allowed_sources: &[String], + model_providers: Option<&[String]>, + archived_only: bool, + ) -> anyhow::Result> { + let mut builder = QueryBuilder::::new("SELECT id FROM threads"); + push_thread_filters( + &mut builder, + archived_only, + allowed_sources, + model_providers, + anchor, + sort_key, + None, + ); + push_thread_order_and_limit(&mut builder, sort_key, limit); + + let rows = builder.build().fetch_all(self.pool.as_ref()).await?; + rows.into_iter() + .map(|row| { + let id: String = row.try_get("id")?; + Ok(ThreadId::try_from(id)?) + }) + .collect() + } + + /// Insert or replace thread metadata directly. + pub async fn upsert_thread(&self, metadata: &crate::ThreadMetadata) -> anyhow::Result<()> { + self.upsert_thread_with_creation_memory_mode(metadata, None) + .await + } + + pub async fn set_thread_memory_mode( + &self, + thread_id: ThreadId, + memory_mode: &str, + ) -> anyhow::Result { + let result = sqlx::query("UPDATE threads SET memory_mode = ? WHERE id = ?") + .bind(memory_mode) + .bind(thread_id.to_string()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected() > 0) + } + + async fn upsert_thread_with_creation_memory_mode( + &self, + metadata: &crate::ThreadMetadata, + creation_memory_mode: Option<&str>, + ) -> anyhow::Result<()> { + sqlx::query( + r#" +INSERT INTO threads ( + id, + rollout_path, + created_at, + updated_at, + source, + agent_nickname, + agent_role, + model_provider, + cwd, + cli_version, + title, + sandbox_policy, + approval_mode, + tokens_used, + first_user_message, + archived, + archived_at, + git_sha, + git_branch, + git_origin_url, + memory_mode +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +ON CONFLICT(id) DO UPDATE SET + rollout_path = excluded.rollout_path, + created_at = excluded.created_at, + updated_at = excluded.updated_at, + source = excluded.source, + agent_nickname = excluded.agent_nickname, + agent_role = excluded.agent_role, + model_provider = excluded.model_provider, + cwd = excluded.cwd, + cli_version = excluded.cli_version, + title = excluded.title, + sandbox_policy = excluded.sandbox_policy, + approval_mode = excluded.approval_mode, + tokens_used = excluded.tokens_used, + first_user_message = excluded.first_user_message, + archived = excluded.archived, + archived_at = excluded.archived_at, + git_sha = excluded.git_sha, + git_branch = excluded.git_branch, + git_origin_url = excluded.git_origin_url + "#, + ) + .bind(metadata.id.to_string()) + .bind(metadata.rollout_path.display().to_string()) + .bind(datetime_to_epoch_seconds(metadata.created_at)) + .bind(datetime_to_epoch_seconds(metadata.updated_at)) + .bind(metadata.source.as_str()) + .bind(metadata.agent_nickname.as_deref()) + .bind(metadata.agent_role.as_deref()) + .bind(metadata.model_provider.as_str()) + .bind(metadata.cwd.display().to_string()) + .bind(metadata.cli_version.as_str()) + .bind(metadata.title.as_str()) + .bind(metadata.sandbox_policy.as_str()) + .bind(metadata.approval_mode.as_str()) + .bind(metadata.tokens_used) + .bind(metadata.first_user_message.as_deref().unwrap_or_default()) + .bind(metadata.archived_at.is_some()) + .bind(metadata.archived_at.map(datetime_to_epoch_seconds)) + .bind(metadata.git_sha.as_deref()) + .bind(metadata.git_branch.as_deref()) + .bind(metadata.git_origin_url.as_deref()) + .bind(creation_memory_mode.unwrap_or("enabled")) + .execute(self.pool.as_ref()) + .await?; + 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, + name, + description, + input_schema +) VALUES (?, ?, ?, ?, ?) +ON CONFLICT(thread_id, position) DO NOTHING + "#, + ) + .bind(thread_id.as_str()) + .bind(position) + .bind(tool.name.as_str()) + .bind(tool.description.as_str()) + .bind(input_schema) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(()) + } + + /// Apply rollout items incrementally using the underlying database. + pub async fn apply_rollout_items( + &self, + builder: &ThreadMetadataBuilder, + items: &[RolloutItem], + otel: Option<&OtelManager>, + new_thread_memory_mode: Option<&str>, + ) -> anyhow::Result<()> { + if items.is_empty() { + return Ok(()); + } + let existing_metadata = self.get_thread(builder.id).await?; + let mut metadata = existing_metadata + .clone() + .unwrap_or_else(|| builder.build(&self.default_provider)); + metadata.rollout_path = builder.rollout_path.clone(); + for item in items { + apply_rollout_item(&mut metadata, item, &self.default_provider); + } + if let Some(updated_at) = file_modified_time_utc(builder.rollout_path.as_path()).await { + 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 + } else { + self.upsert_thread(&metadata).await + }; + if let Err(err) = upsert_result { + if let Some(otel) = otel { + otel.counter(DB_ERROR_METRIC, 1, &[("stage", "apply_rollout_items")]); + } + return Err(err); + } + if let Some(memory_mode) = extract_memory_mode(items) + && let Err(err) = self + .set_thread_memory_mode(builder.id, memory_mode.as_str()) + .await + { + if let Some(otel) = otel { + otel.counter(DB_ERROR_METRIC, 1, &[("stage", "set_thread_memory_mode")]); + } + 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 + { + if let Some(otel) = otel { + otel.counter(DB_ERROR_METRIC, 1, &[("stage", "persist_dynamic_tools")]); + } + return Err(err); + } + Ok(()) + } + + /// Mark a thread as archived using the underlying database. + pub async fn mark_archived( + &self, + thread_id: ThreadId, + rollout_path: &Path, + archived_at: DateTime, + ) -> anyhow::Result<()> { + let Some(mut metadata) = self.get_thread(thread_id).await? else { + return Ok(()); + }; + metadata.archived_at = Some(archived_at); + metadata.rollout_path = rollout_path.to_path_buf(); + if let Some(updated_at) = file_modified_time_utc(rollout_path).await { + metadata.updated_at = updated_at; + } + if metadata.id != thread_id { + warn!( + "thread id mismatch during archive: expected {thread_id}, got {}", + metadata.id + ); + } + self.upsert_thread(&metadata).await + } + + /// Mark a thread as unarchived using the underlying database. + pub async fn mark_unarchived( + &self, + thread_id: ThreadId, + rollout_path: &Path, + ) -> anyhow::Result<()> { + let Some(mut metadata) = self.get_thread(thread_id).await? else { + return Ok(()); + }; + metadata.archived_at = None; + metadata.rollout_path = rollout_path.to_path_buf(); + if let Some(updated_at) = file_modified_time_utc(rollout_path).await { + metadata.updated_at = updated_at; + } + if metadata.id != thread_id { + warn!( + "thread id mismatch during unarchive: expected {thread_id}, got {}", + metadata.id + ); + } + self.upsert_thread(&metadata).await + } + + /// Delete a thread metadata row by id. + pub async fn delete_thread(&self, thread_id: ThreadId) -> anyhow::Result { + let result = sqlx::query("DELETE FROM threads WHERE id = ?") + .bind(thread_id.to_string()) + .execute(self.pool.as_ref()) + .await?; + Ok(result.rows_affected()) + } +} + +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(), + RolloutItem::ResponseItem(_) + | RolloutItem::Compacted(_) + | RolloutItem::TurnContext(_) + | RolloutItem::EventMsg(_) => None, + }) +} + +pub(super) fn push_thread_filters<'a>( + builder: &mut QueryBuilder<'a, Sqlite>, + archived_only: bool, + allowed_sources: &'a [String], + model_providers: Option<&'a [String]>, + anchor: Option<&crate::Anchor>, + sort_key: SortKey, + search_term: Option<&'a str>, +) { + builder.push(" WHERE 1 = 1"); + if archived_only { + builder.push(" AND archived = 1"); + } else { + builder.push(" AND archived = 0"); + } + builder.push(" AND first_user_message <> ''"); + if !allowed_sources.is_empty() { + builder.push(" AND source IN ("); + let mut separated = builder.separated(", "); + for source in allowed_sources { + separated.push_bind(source); + } + separated.push_unseparated(")"); + } + if let Some(model_providers) = model_providers + && !model_providers.is_empty() + { + builder.push(" AND model_provider IN ("); + let mut separated = builder.separated(", "); + for provider in model_providers { + separated.push_bind(provider); + } + separated.push_unseparated(")"); + } + if let Some(search_term) = search_term { + builder.push(" AND instr(title, "); + builder.push_bind(search_term); + builder.push(") > 0"); + } + if let Some(anchor) = anchor { + let anchor_ts = datetime_to_epoch_seconds(anchor.ts); + let column = match sort_key { + SortKey::CreatedAt => "created_at", + SortKey::UpdatedAt => "updated_at", + }; + builder.push(" AND ("); + builder.push(column); + builder.push(" < "); + builder.push_bind(anchor_ts); + builder.push(" OR ("); + builder.push(column); + builder.push(" = "); + builder.push_bind(anchor_ts); + builder.push(" AND id < "); + builder.push_bind(anchor.id.to_string()); + builder.push("))"); + } +} + +pub(super) fn push_thread_order_and_limit( + builder: &mut QueryBuilder<'_, Sqlite>, + sort_key: SortKey, + limit: usize, +) { + let order_column = match sort_key { + SortKey::CreatedAt => "created_at", + SortKey::UpdatedAt => "updated_at", + }; + builder.push(" ORDER BY "); + builder.push(order_column); + builder.push(" DESC, id DESC"); + builder.push(" LIMIT "); + builder.push_bind(limit as i64); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::test_support::test_thread_metadata; + use crate::runtime::test_support::unique_temp_dir; + use codex_protocol::protocol::SessionMeta; + use codex_protocol::protocol::SessionMetaLine; + use codex_protocol::protocol::SessionSource; + use pretty_assertions::assert_eq; + use std::path::PathBuf; + + #[tokio::test] + async fn upsert_thread_keeps_creation_memory_mode_for_existing_rows() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("state db should initialize"); + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("valid thread id"); + let mut metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + + runtime + .upsert_thread_with_creation_memory_mode(&metadata, Some("disabled")) + .await + .expect("initial insert should succeed"); + + let memory_mode: String = + sqlx::query_scalar("SELECT memory_mode FROM threads WHERE id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("memory mode should be readable"); + assert_eq!(memory_mode, "disabled"); + + metadata.title = "updated title".to_string(); + runtime + .upsert_thread(&metadata) + .await + .expect("upsert should succeed"); + + let memory_mode: String = + sqlx::query_scalar("SELECT memory_mode FROM threads WHERE id = ?") + .bind(thread_id.to_string()) + .fetch_one(runtime.pool.as_ref()) + .await + .expect("memory mode should remain readable"); + assert_eq!(memory_mode, "disabled"); + } + + #[tokio::test] + async fn apply_rollout_items_restores_memory_mode_from_session_meta() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string(), None) + .await + .expect("state db should initialize"); + let thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000456").expect("valid thread id"); + let metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone()); + + runtime + .upsert_thread(&metadata) + .await + .expect("initial upsert should succeed"); + + let builder = ThreadMetadataBuilder::new( + thread_id, + metadata.rollout_path.clone(), + metadata.created_at, + SessionSource::Cli, + ); + let items = vec![RolloutItem::SessionMeta(SessionMetaLine { + meta: SessionMeta { + id: thread_id, + forked_from_id: None, + timestamp: metadata.created_at.to_rfc3339(), + cwd: PathBuf::new(), + originator: String::new(), + cli_version: String::new(), + source: SessionSource::Cli, + agent_nickname: None, + agent_role: None, + model_provider: None, + base_instructions: None, + dynamic_tools: None, + memory_mode: Some("polluted".to_string()), + }, + git: None, + })]; + + runtime + .apply_rollout_items(&builder, &items, None, None) + .await + .expect("apply_rollout_items should succeed"); + + let memory_mode = runtime + .get_thread_memory_mode(thread_id) + .await + .expect("memory mode should load"); + assert_eq!(memory_mode.as_deref(), Some("polluted")); + } +} diff --git a/codex-rs/tui/BUILD.bazel b/codex-rs/tui/BUILD.bazel index 1400b7cf4e..58fbc31fb5 100644 --- a/codex-rs/tui/BUILD.bazel +++ b/codex-rs/tui/BUILD.bazel @@ -12,7 +12,7 @@ codex_rust_crate( ], allow_empty = True, ), - test_data_extra = glob(["src/**/snapshots/**"]), + test_data_extra = glob(["src/**/snapshots/**"]) + ["//codex-rs/core:model_availability_nux_fixtures"], integration_compile_data_extra = ["src/test_backend.rs"], extra_binaries = [ "//codex-rs/cli:codex", diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 1a87314e98..594acb33d4 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -50,6 +50,7 @@ codex-utils-fuzzy-match = { workspace = true } codex-utils-oss = { workspace = true } codex-utils-sandbox-summary = { workspace = true } codex-utils-sleep-inhibitor = { workspace = true } +codex-utils-string = { workspace = true } color-eyre = { workspace = true } crossterm = { workspace = true, features = ["bracketed-paste", "event-stream"] } derive_more = { workspace = true, features = ["is_variant"] } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 7987688331..4a6d93dfb7 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1,6 +1,7 @@ use crate::app_backtrack::BacktrackState; use crate::app_event::AppEvent; use crate::app_event::ExitMode; +use crate::app_event::RealtimeAudioDeviceKind; #[cfg(target_os = "windows")] use crate::app_event::WindowsSandboxEnableMode; use crate::app_event_sender::AppEventSender; @@ -46,9 +47,11 @@ use codex_core::config::ConfigOverrides; use codex_core::config::ConstraintError; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; +use codex_core::config::types::ModelAvailabilityNuxConfig; use codex_core::config_loader::ConfigLayerStackOrdering; use codex_core::config_loader::RequirementSource; use codex_core::features::Feature; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::models_manager::manager::RefreshStrategy; use codex_core::models_manager::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG; use codex_core::models_manager::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; @@ -61,6 +64,7 @@ use codex_protocol::config_types::Personality; #[cfg(target_os = "windows")] use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::items::TurnItem; +use codex_protocol::openai_models::ModelAvailabilityNux; use codex_protocol::openai_models::ModelPreset; use codex_protocol::openai_models::ModelUpgrade; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; @@ -104,6 +108,7 @@ use tokio::sync::mpsc; use tokio::sync::mpsc::error::TryRecvError; use tokio::sync::mpsc::error::TrySendError; use tokio::sync::mpsc::unbounded_channel; +use tokio::task::JoinHandle; use toml::Value as TomlValue; mod pending_interactive_replay; @@ -461,12 +466,77 @@ fn target_preset_for_upgrade<'a>( .find(|preset| preset.model == target_model && preset.show_in_picker) } +const MODEL_AVAILABILITY_NUX_MAX_SHOW_COUNT: u32 = 4; + +#[derive(Debug, Clone, PartialEq, Eq)] +struct StartupTooltipOverride { + model_slug: String, + message: String, +} + +fn select_model_availability_nux( + available_models: &[ModelPreset], + nux_config: &ModelAvailabilityNuxConfig, +) -> Option { + available_models.iter().find_map(|preset| { + let ModelAvailabilityNux { message } = preset.availability_nux.as_ref()?; + let shown_count = nux_config + .shown_count + .get(&preset.model) + .copied() + .unwrap_or_default(); + (shown_count < MODEL_AVAILABILITY_NUX_MAX_SHOW_COUNT).then(|| StartupTooltipOverride { + model_slug: preset.model.clone(), + message: message.clone(), + }) + }) +} + +async fn prepare_startup_tooltip_override( + config: &mut Config, + available_models: &[ModelPreset], + is_first_run: bool, +) -> Option { + if is_first_run || !config.show_tooltips { + return None; + } + + let tooltip_override = + select_model_availability_nux(available_models, &config.model_availability_nux)?; + + let shown_count = config + .model_availability_nux + .shown_count + .get(&tooltip_override.model_slug) + .copied() + .unwrap_or_default(); + let next_count = shown_count.saturating_add(1); + let mut updated_shown_count = config.model_availability_nux.shown_count.clone(); + updated_shown_count.insert(tooltip_override.model_slug.clone(), next_count); + + if let Err(err) = ConfigEditsBuilder::new(&config.codex_home) + .set_model_availability_nux_count(&updated_shown_count) + .apply() + .await + { + tracing::error!( + error = %err, + model = %tooltip_override.model_slug, + "failed to persist model availability nux count" + ); + return Some(tooltip_override.message); + } + + config.model_availability_nux.shown_count = updated_shown_count; + Some(tooltip_override.message) +} + async fn handle_model_migration_prompt_if_needed( tui: &mut tui::Tui, config: &mut Config, model: &str, app_event_tx: &AppEventSender, - available_models: Vec, + available_models: &[ModelPreset], ) -> Option { let upgrade = available_models .iter() @@ -491,13 +561,13 @@ async fn handle_model_migration_prompt_if_needed( model, &target_model, &config.notices.model_migrations, - &available_models, + available_models, ) { return None; } let current_preset = available_models.iter().find(|preset| preset.model == model); - let target_preset = target_preset_for_upgrade(&available_models, &target_model); + let target_preset = target_preset_for_upgrade(available_models, &target_model); let target_preset = target_preset?; let target_display_name = target_preset.display_name.clone(); let heading_label = if target_display_name == model { @@ -627,6 +697,7 @@ pub(crate) struct App { windows_sandbox: WindowsSandboxState, thread_event_channels: HashMap, + thread_event_listener_tasks: HashMap>, agent_picker_threads: HashMap, active_thread_id: Option, active_thread_rx: Option>, @@ -678,6 +749,7 @@ impl App { is_first_run: false, feedback_audience: self.feedback_audience, model: Some(self.chat_widget.current_model().to_string()), + startup_tooltip_override: None, status_line_invalid_items_warned: self.status_line_invalid_items_warned.clone(), otel_manager: self.otel_manager.clone(), } @@ -815,6 +887,23 @@ impl App { self.suppress_shutdown_complete = true; self.chat_widget.submit_op(Op::Shutdown); self.server.remove_thread(&thread_id).await; + self.abort_thread_event_listener(thread_id); + } + } + + fn abort_thread_event_listener(&mut self, thread_id: ThreadId) { + if let Some(handle) = self.thread_event_listener_tasks.remove(&thread_id) { + handle.abort(); + } + } + + fn abort_all_thread_event_listeners(&mut self) { + for handle in self + .thread_event_listener_tasks + .drain() + .map(|(_, handle)| handle) + { + handle.abort(); } } @@ -880,6 +969,14 @@ impl App { self.refresh_pending_thread_approvals().await; } + async fn note_thread_outbound_op(&mut self, thread_id: ThreadId, op: &Op) { + let Some(channel) = self.thread_event_channels.get(&thread_id) else { + return; + }; + let mut store = channel.store.lock().await; + store.note_outbound_op(op); + } + async fn note_active_thread_outbound_op(&mut self, op: &Op) { if !ThreadEventStore::op_can_change_pending_replay_state(op) { return; @@ -887,11 +984,113 @@ impl App { let Some(thread_id) = self.active_thread_id else { return; }; - let Some(channel) = self.thread_event_channels.get(&thread_id) else { - return; + self.note_thread_outbound_op(thread_id, op).await; + } + + fn thread_label(&self, thread_id: ThreadId) -> String { + let is_primary = self.primary_thread_id == Some(thread_id); + let fallback_label = if is_primary { + "Main [default]".to_string() + } else { + let thread_id = thread_id.to_string(); + let short_id: String = thread_id.chars().take(8).collect(); + format!("Agent ({short_id})") }; - let mut store = channel.store.lock().await; - store.note_outbound_op(op); + if let Some(entry) = self.agent_picker_threads.get(&thread_id) { + let label = format_agent_picker_item_name( + entry.agent_nickname.as_deref(), + entry.agent_role.as_deref(), + is_primary, + ); + if label == "Agent" { + let thread_id = thread_id.to_string(); + let short_id: String = thread_id.chars().take(8).collect(); + format!("{label} ({short_id})") + } else { + label + } + } else { + fallback_label + } + } + + async fn thread_cwd(&self, thread_id: ThreadId) -> Option { + let channel = self.thread_event_channels.get(&thread_id)?; + let store = channel.store.lock().await; + match store.session_configured.as_ref().map(|event| &event.msg) { + Some(EventMsg::SessionConfigured(session)) => Some(session.cwd.clone()), + _ => None, + } + } + + async fn approval_request_for_thread_event( + &self, + thread_id: ThreadId, + event: &Event, + ) -> Option { + let thread_label = Some(self.thread_label(thread_id)); + match &event.msg { + EventMsg::ExecApprovalRequest(ev) => Some(ApprovalRequest::Exec { + thread_id, + thread_label, + id: ev.effective_approval_id(), + command: ev.command.clone(), + reason: ev.reason.clone(), + available_decisions: ev.effective_available_decisions(), + network_approval_context: ev.network_approval_context.clone(), + additional_permissions: ev.additional_permissions.clone(), + }), + EventMsg::ApplyPatchApprovalRequest(ev) => Some(ApprovalRequest::ApplyPatch { + thread_id, + thread_label, + id: ev.call_id.clone(), + reason: ev.reason.clone(), + cwd: self + .thread_cwd(thread_id) + .await + .unwrap_or_else(|| self.config.cwd.clone()), + changes: ev.changes.clone(), + }), + EventMsg::ElicitationRequest(ev) => Some(ApprovalRequest::McpElicitation { + thread_id, + thread_label, + server_name: ev.server_name.clone(), + request_id: ev.id.clone(), + message: ev.message.clone(), + }), + _ => None, + } + } + + async fn submit_op_to_thread(&mut self, thread_id: ThreadId, op: Op) { + let replay_state_op = + ThreadEventStore::op_can_change_pending_replay_state(&op).then(|| op.clone()); + let submitted = if self.active_thread_id == Some(thread_id) { + self.chat_widget.submit_op(op) + } else { + crate::session_log::log_outbound_op(&op); + match self.server.get_thread(thread_id).await { + Ok(thread) => match thread.submit(op).await { + Ok(_) => true, + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to submit op to thread {thread_id}: {err}" + )); + false + } + }, + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to find thread {thread_id} for approval response: {err}" + )); + false + } + } + }; + if submitted && let Some(op) = replay_state_op.as_ref() { + self.note_thread_outbound_op(thread_id, op).await; + self.refresh_pending_thread_approvals().await; + } } async fn refresh_pending_thread_approvals(&mut self) { @@ -917,32 +1116,7 @@ impl App { let threads = pending_thread_ids .into_iter() - .map(|thread_id| { - let is_primary = self.primary_thread_id == Some(thread_id); - let fallback_label = if is_primary { - "Main [default]".to_string() - } else { - let thread_id = thread_id.to_string(); - let short_id: String = thread_id.chars().take(8).collect(); - format!("Agent ({short_id})") - }; - if let Some(entry) = self.agent_picker_threads.get(&thread_id) { - let label = format_agent_picker_item_name( - entry.agent_nickname.as_deref(), - entry.agent_role.as_deref(), - is_primary, - ); - if label == "Agent" { - let thread_id = thread_id.to_string(); - let short_id: String = thread_id.chars().take(8).collect(); - format!("{label} ({short_id})") - } else { - label - } - } else { - fallback_label - } - }) + .map(|thread_id| self.thread_label(thread_id)) .collect(); self.chat_widget.set_pending_thread_approvals(threads); @@ -951,6 +1125,12 @@ impl App { async fn enqueue_thread_event(&mut self, thread_id: ThreadId, event: Event) -> Result<()> { let refresh_pending_thread_approvals = ThreadEventStore::event_can_change_pending_thread_approvals(&event); + let inactive_approval_request = if self.active_thread_id != Some(thread_id) { + self.approval_request_for_thread_event(thread_id, &event) + .await + } else { + None + }; let (sender, store) = { let channel = self.ensure_thread_channel(thread_id); (channel.sender.clone(), Arc::clone(&channel.store)) @@ -979,6 +1159,8 @@ impl App { tracing::warn!("thread {thread_id} event channel closed"); } } + } else if let Some(request) = inactive_approval_request { + self.chat_widget.push_approval_request(request); } if refresh_pending_thread_approvals { self.refresh_pending_thread_approvals().await; @@ -986,6 +1168,19 @@ impl App { Ok(()) } + async fn handle_routed_thread_event( + &mut self, + thread_id: ThreadId, + event: Event, + ) -> Result<()> { + if !self.thread_event_channels.contains_key(&thread_id) { + tracing::debug!("dropping stale event for untracked thread {thread_id}"); + return Ok(()); + } + + self.enqueue_thread_event(thread_id, event).await + } + async fn enqueue_primary_event(&mut self, event: Event) -> Result<()> { if let Some(thread_id) = self.primary_thread_id { return self.enqueue_thread_event(thread_id, event).await; @@ -997,12 +1192,12 @@ impl App { self.primary_session_configured = Some(session.clone()); self.ensure_thread_channel(thread_id); self.activate_thread_channel(thread_id).await; + self.enqueue_thread_event(thread_id, event).await?; let pending = std::mem::take(&mut self.pending_primary_events); for pending_event in pending { self.enqueue_thread_event(thread_id, pending_event).await?; } - self.enqueue_thread_event(thread_id, event).await?; } else { self.pending_primary_events.push_back(event); } @@ -1028,6 +1223,15 @@ impl App { } } + let has_non_primary_agent_thread = self + .agent_picker_threads + .keys() + .any(|thread_id| Some(*thread_id) != self.primary_thread_id); + if !self.config.features.enabled(Feature::Collab) && !has_non_primary_agent_thread { + self.chat_widget.open_multi_agent_enable_prompt(); + return; + } + if self.agent_picker_threads.is_empty() { self.chat_widget .add_info_message("No agents available yet.".to_string(), None); @@ -1073,8 +1277,8 @@ impl App { .collect(); self.chat_widget.show_selection_view(SelectionViewParams { - title: Some("Agents".to_string()), - subtitle: Some("Select a thread to focus".to_string()), + title: Some("Multi-agents".to_string()), + subtitle: Some("Select an agent to watch".to_string()), footer_hint: Some(standard_popup_hint_line()), items, initial_selected_idx, @@ -1179,6 +1383,7 @@ impl App { } fn reset_thread_event_state(&mut self) { + self.abort_all_thread_event_listeners(); self.thread_event_channels.clear(); self.agent_picker_threads.clear(); self.active_thread_id = None; @@ -1192,6 +1397,7 @@ impl App { // Start a fresh in-memory session while preserving resumability via persisted rollout // history. let model = self.chat_widget.current_model().to_string(); + let config = self.fresh_session_config(); let summary = session_summary( self.chat_widget.token_usage(), self.chat_widget.thread_id(), @@ -1202,7 +1408,7 @@ impl App { tracing::warn!(error = %err, "failed to close all threads"); } let init = crate::chatwidget::ChatWidgetInit { - config: self.config.clone(), + config, frame_requester: tui.frame_requester(), app_event_tx: self.app_event_tx.clone(), // New sessions start without prefilled message content. @@ -1214,6 +1420,7 @@ impl App { is_first_run: false, feedback_audience: self.feedback_audience, model: Some(model), + startup_tooltip_override: None, status_line_invalid_items_warned: self.status_line_invalid_items_warned.clone(), otel_manager: self.otel_manager.clone(), }; @@ -1230,6 +1437,12 @@ impl App { tui.frame_requester().schedule_frame(); } + fn fresh_session_config(&self) -> Config { + let mut config = self.config.clone(); + config.service_tier = self.chat_widget.current_service_tier(); + config + } + async fn drain_active_thread_events(&mut self, tui: &mut tui::Tui) -> Result<()> { let Some(mut rx) = self.active_thread_rx.take() else { return Ok(()); @@ -1341,6 +1554,11 @@ impl App { auth_manager.clone(), SessionSource::Cli, config.model_catalog.clone(), + CollaborationModesConfig { + default_mode_request_user_input: config + .features + .enabled(codex_core::features::Feature::DefaultModeRequestUserInput), + }, )); let mut model = thread_manager .get_models_manager() @@ -1355,7 +1573,7 @@ impl App { &mut config, model.as_str(), &app_event_tx, - available_models, + &available_models, ) .await; if let Some(exit_info) = exit_info { @@ -1364,7 +1582,6 @@ impl App { if let Some(updated_model) = config.model.clone() { model = updated_model; } - let auth = auth_manager.auth().await; let auth_ref = auth.as_ref(); // Determine who should see internal Slack routing. We treat @@ -1408,6 +1625,9 @@ impl App { Self::should_wait_for_initial_session(&session_selection); let mut chat_widget = match session_selection { SessionSelection::StartFresh | SessionSelection::Exit => { + let startup_tooltip_override = + prepare_startup_tooltip_override(&mut config, &available_models, is_first_run) + .await; let init = crate::chatwidget::ChatWidgetInit { config: config.clone(), frame_requester: tui.frame_requester(), @@ -1425,17 +1645,22 @@ impl App { is_first_run, feedback_audience, model: Some(model.clone()), + startup_tooltip_override, status_line_invalid_items_warned: status_line_invalid_items_warned.clone(), otel_manager: otel_manager.clone(), }; ChatWidget::new(init, thread_manager.clone()) } - SessionSelection::Resume(path) => { + SessionSelection::Resume(target_session) => { let resumed = thread_manager - .resume_thread_from_rollout(config.clone(), path.clone(), auth_manager.clone()) + .resume_thread_from_rollout( + config.clone(), + target_session.path.clone(), + auth_manager.clone(), + ) .await .wrap_err_with(|| { - let path_display = path.display(); + let path_display = target_session.path.display(); format!("Failed to resume session from {path_display}") })?; let init = crate::chatwidget::ChatWidgetInit { @@ -1455,18 +1680,24 @@ impl App { is_first_run, feedback_audience, model: config.model.clone(), + startup_tooltip_override: None, status_line_invalid_items_warned: status_line_invalid_items_warned.clone(), otel_manager: otel_manager.clone(), }; ChatWidget::new_from_existing(init, resumed.thread, resumed.session_configured) } - SessionSelection::Fork(path) => { + SessionSelection::Fork(target_session) => { otel_manager.counter("codex.thread.fork", 1, &[("source", "cli_subcommand")]); let forked = thread_manager - .fork_thread(usize::MAX, config.clone(), path.clone(), false) + .fork_thread( + usize::MAX, + config.clone(), + target_session.path.clone(), + false, + ) .await .wrap_err_with(|| { - let path_display = path.display(); + let path_display = target_session.path.display(); format!("Failed to fork session from {path_display}") })?; let init = crate::chatwidget::ChatWidgetInit { @@ -1486,6 +1717,7 @@ impl App { is_first_run, feedback_audience, model: config.model.clone(), + startup_tooltip_override: None, status_line_invalid_items_warned: status_line_invalid_items_warned.clone(), otel_manager: otel_manager.clone(), }; @@ -1529,6 +1761,7 @@ impl App { pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), thread_event_channels: HashMap::new(), + thread_event_listener_tasks: HashMap::new(), agent_picker_threads: HashMap::new(), active_thread_id: None, active_thread_rx: None, @@ -1729,12 +1962,14 @@ impl App { } AppEvent::OpenResumePicker => { match crate::resume_picker::run_resume_picker(tui, &self.config, false).await? { - SessionSelection::Resume(path) => { + SessionSelection::Resume(target_session) => { let current_cwd = self.config.cwd.clone(); let resume_cwd = match crate::resolve_cwd_for_resume_or_fork( tui, + &self.config, ¤t_cwd, - &path, + target_session.thread_id, + &target_session.path, CwdPromptAction::Resume, true, ) @@ -1770,7 +2005,7 @@ impl App { .server .resume_thread_from_rollout( resume_config.clone(), - path.clone(), + target_session.path.clone(), self.auth_manager.clone(), ) .await @@ -1804,7 +2039,7 @@ impl App { } } Err(err) => { - let path_display = path.display(); + let path_display = target_session.path.display(); self.chat_widget.add_error_message(format!( "Failed to resume session from {path_display}: {err}" )); @@ -1941,19 +2176,12 @@ impl App { AppEvent::CodexEvent(event) => { self.enqueue_primary_event(event).await?; } - AppEvent::Exit(mode) => match mode { - ExitMode::ShutdownFirst => { - // Mark the thread we are explicitly shutting down for exit so - // its shutdown completion does not trigger agent failover. - self.pending_shutdown_exit_thread_id = - self.active_thread_id.or(self.chat_widget.thread_id()); - self.chat_widget.submit_op(Op::Shutdown); - } - ExitMode::Immediate => { - self.pending_shutdown_exit_thread_id = None; - return Ok(AppRunControl::Exit(ExitReason::UserRequested)); - } - }, + AppEvent::ThreadEvent { thread_id, event } => { + self.handle_routed_thread_event(thread_id, event).await?; + } + AppEvent::Exit(mode) => { + return Ok(self.handle_exit_mode(mode)); + } AppEvent::FatalExitRequest(message) => { return Ok(AppRunControl::Exit(ExitReason::Fatal(message))); } @@ -1966,6 +2194,9 @@ impl App { self.refresh_pending_thread_approvals().await; } } + AppEvent::SubmitThreadOp { thread_id, op } => { + self.submit_op_to_thread(thread_id, op).await; + } AppEvent::DiffResult(text) => { // Clear the in-progress state in the bottom pane self.chat_widget.on_diff_complete(); @@ -2035,6 +2266,9 @@ impl App { AppEvent::UpdatePersonality(personality) => { self.on_update_personality(personality); } + AppEvent::OpenRealtimeAudioDeviceSelection { kind } => { + self.chat_widget.open_realtime_audio_device_selection(kind); + } AppEvent::OpenReasoningPopup { model } => { self.chat_widget.open_reasoning_popup(model); } @@ -2327,6 +2561,7 @@ impl App { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }, @@ -2349,6 +2584,7 @@ impl App { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, }, @@ -2460,6 +2696,89 @@ impl App { } } } + AppEvent::PersistServiceTierSelection { service_tier } => { + self.refresh_status_line(); + let profile = self.active_profile.as_deref(); + match ConfigEditsBuilder::new(&self.config.codex_home) + .with_profile(profile) + .set_service_tier(service_tier) + .apply() + .await + { + Ok(()) => { + let status = if service_tier.is_some() { "on" } else { "off" }; + let mut message = format!("Fast mode set to {status}"); + if let Some(profile) = profile { + message.push_str(" for "); + message.push_str(profile); + message.push_str(" profile"); + } + self.chat_widget.add_info_message(message, None); + } + Err(err) => { + tracing::error!(error = %err, "failed to persist fast mode selection"); + if let Some(profile) = profile { + self.chat_widget.add_error_message(format!( + "Failed to save Fast mode for profile `{profile}`: {err}" + )); + } else { + self.chat_widget.add_error_message(format!( + "Failed to save default Fast mode: {err}" + )); + } + } + } + } + AppEvent::PersistRealtimeAudioDeviceSelection { kind, name } => { + let builder = match kind { + RealtimeAudioDeviceKind::Microphone => { + ConfigEditsBuilder::new(&self.config.codex_home) + .set_realtime_microphone(name.as_deref()) + } + RealtimeAudioDeviceKind::Speaker => { + ConfigEditsBuilder::new(&self.config.codex_home) + .set_realtime_speaker(name.as_deref()) + } + }; + + match builder.apply().await { + Ok(()) => { + match kind { + RealtimeAudioDeviceKind::Microphone => { + self.config.realtime_audio.microphone = name.clone(); + } + RealtimeAudioDeviceKind::Speaker => { + self.config.realtime_audio.speaker = name.clone(); + } + } + self.chat_widget + .set_realtime_audio_device(kind, name.clone()); + + if self.chat_widget.realtime_conversation_is_live() { + self.chat_widget.open_realtime_audio_restart_prompt(kind); + } else { + let selection = name.unwrap_or_else(|| "System default".to_string()); + self.chat_widget.add_info_message( + format!("Realtime {} set to {selection}", kind.noun()), + None, + ); + } + } + Err(err) => { + tracing::error!( + error = %err, + "failed to persist realtime audio selection" + ); + self.chat_widget.add_error_message(format!( + "Failed to save realtime {}: {err}", + kind.noun() + )); + } + } + } + AppEvent::RestartRealtimeAudioDevice { kind } => { + self.chat_widget.restart_realtime_audio_device(kind); + } AppEvent::UpdateAskForApprovalPolicy(policy) => { if let Err(err) = self.config.permissions.approval_policy.set(policy) { tracing::warn!(%err, "failed to set approval policy on app config"); @@ -2580,6 +2899,7 @@ impl App { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, })); @@ -2718,9 +3038,6 @@ impl App { AppEvent::OpenAgentPicker => { self.open_agent_picker().await; } - AppEvent::RefreshPendingThreadApprovals => { - self.refresh_pending_thread_approvals().await; - } AppEvent::SelectAgentThread(thread_id) => { self.select_agent_thread(tui, thread_id).await?; } @@ -2938,6 +3255,27 @@ impl App { Ok(AppRunControl::Continue) } + fn handle_exit_mode(&mut self, mode: ExitMode) -> AppRunControl { + match mode { + ExitMode::ShutdownFirst => { + // Mark the thread we are explicitly shutting down for exit so + // its shutdown completion does not trigger agent failover. + self.pending_shutdown_exit_thread_id = + self.active_thread_id.or(self.chat_widget.thread_id()); + if self.chat_widget.submit_op(Op::Shutdown) { + AppRunControl::Continue + } else { + self.pending_shutdown_exit_thread_id = None; + AppRunControl::Exit(ExitReason::UserRequested) + } + } + ExitMode::Immediate => { + self.pending_shutdown_exit_thread_id = None; + AppRunControl::Exit(ExitReason::UserRequested) + } + } + } + fn handle_codex_event_now(&mut self, event: Event) { let needs_refresh = matches!( event.msg, @@ -3045,6 +3383,7 @@ impl App { thread_name: None, model: config_snapshot.model, model_provider_id: config_snapshot.model_provider_id, + service_tier: config_snapshot.service_tier, approval_policy: config_snapshot.approval_policy, sandbox_policy: config_snapshot.sandbox_policy, cwd: config_snapshot.cwd, @@ -3058,11 +3397,9 @@ impl App { }; let channel = ThreadEventChannel::new_with_session_configured(THREAD_EVENT_CHANNEL_CAPACITY, event); - let sender = channel.sender.clone(); - let store = Arc::clone(&channel.store); let app_event_tx = self.app_event_tx.clone(); self.thread_event_channels.insert(thread_id, channel); - tokio::spawn(async move { + let listener_handle = tokio::spawn(async move { loop { let event = match thread.next_event().await { Ok(event) => event, @@ -3071,22 +3408,11 @@ impl App { break; } }; - let refresh_pending_thread_approvals = - ThreadEventStore::event_can_change_pending_thread_approvals(&event); - let should_send = { - let mut guard = store.lock().await; - guard.push_event(event.clone()); - guard.active - }; - if refresh_pending_thread_approvals { - app_event_tx.send(AppEvent::RefreshPendingThreadApprovals); - } - if should_send && let Err(err) = sender.send(event).await { - tracing::debug!("external thread {thread_id} channel closed: {err}"); - break; - } + app_event_tx.send(AppEvent::ThreadEvent { thread_id, event }); } }); + self.thread_event_listener_tasks + .insert(thread_id, listener_handle); Ok(()) } @@ -3358,11 +3684,14 @@ mod tests { use crate::history_cell::HistoryCell; use crate::history_cell::UserHistoryCell; use crate::history_cell::new_session_info; + use assert_matches::assert_matches; use codex_core::CodexAuth; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; + use codex_core::config::types::ModelAvailabilityNuxConfig; use codex_otel::OtelManager; use codex_protocol::ThreadId; + use codex_protocol::openai_models::ModelAvailabilityNux; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -3413,15 +3742,21 @@ mod tests { true ); assert_eq!( - App::should_wait_for_initial_session(&SessionSelection::Resume(PathBuf::from( - "/tmp/restore" - ))), + App::should_wait_for_initial_session(&SessionSelection::Resume( + crate::resume_picker::SessionTarget { + path: PathBuf::from("/tmp/restore"), + thread_id: ThreadId::new(), + } + )), false ); assert_eq!( - App::should_wait_for_initial_session(&SessionSelection::Fork(PathBuf::from( - "/tmp/fork" - ))), + App::should_wait_for_initial_session(&SessionSelection::Fork( + crate::resume_picker::SessionTarget { + path: PathBuf::from("/tmp/fork"), + thread_id: ThreadId::new(), + } + )), false ); } @@ -3479,14 +3814,20 @@ mod tests { #[test] fn startup_waiting_gate_not_applied_for_resume_or_fork_session_selection() { let wait_for_resume = App::should_wait_for_initial_session(&SessionSelection::Resume( - PathBuf::from("/tmp/restore"), + crate::resume_picker::SessionTarget { + path: PathBuf::from("/tmp/restore"), + thread_id: ThreadId::new(), + }, )); assert_eq!( App::should_handle_active_thread_events(wait_for_resume, true), true ); let wait_for_fork = App::should_wait_for_initial_session(&SessionSelection::Fork( - PathBuf::from("/tmp/fork"), + crate::resume_picker::SessionTarget { + path: PathBuf::from("/tmp/fork"), + thread_id: ThreadId::new(), + }, )); assert_eq!( App::should_handle_active_thread_events(wait_for_fork, true), @@ -3494,6 +3835,153 @@ mod tests { ); } + #[tokio::test] + async fn enqueue_primary_event_delivers_session_configured_before_buffered_approval() + -> Result<()> { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let approval_event = Event { + id: "approval-event".to_string(), + msg: EventMsg::ExecApprovalRequest( + codex_protocol::protocol::ExecApprovalRequestEvent { + call_id: "call-1".to_string(), + approval_id: None, + turn_id: "turn-1".to_string(), + command: vec!["echo".to_string(), "hello".to_string()], + cwd: PathBuf::from("/tmp/project"), + reason: Some("needs approval".to_string()), + network_approval_context: None, + proposed_execpolicy_amendment: None, + proposed_network_policy_amendments: None, + additional_permissions: None, + available_decisions: None, + parsed_cmd: Vec::new(), + }, + ), + }; + let session_configured_event = Event { + id: "session-configured".to_string(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-test".to_string(), + model_provider_id: "test-provider".to_string(), + service_tier: None, + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + }), + }; + + app.enqueue_primary_event(approval_event.clone()).await?; + app.enqueue_primary_event(session_configured_event.clone()) + .await?; + + let rx = app + .active_thread_rx + .as_mut() + .expect("primary thread receiver should be active"); + let first_event = time::timeout(Duration::from_millis(50), rx.recv()) + .await + .expect("timed out waiting for session configured event") + .expect("channel closed unexpectedly"); + let second_event = time::timeout(Duration::from_millis(50), rx.recv()) + .await + .expect("timed out waiting for buffered approval event") + .expect("channel closed unexpectedly"); + + assert!(matches!(first_event.msg, EventMsg::SessionConfigured(_))); + assert!(matches!(second_event.msg, EventMsg::ExecApprovalRequest(_))); + + app.handle_codex_event_now(first_event); + app.handle_codex_event_now(second_event); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + + while let Ok(app_event) = app_event_rx.try_recv() { + if let AppEvent::SubmitThreadOp { + thread_id: op_thread_id, + .. + } = app_event + { + assert_eq!(op_thread_id, thread_id); + return Ok(()); + } + } + + panic!("expected approval action to submit a thread-scoped op"); + } + + #[tokio::test] + async fn routed_thread_event_does_not_recreate_channel_after_reset() -> Result<()> { + let mut app = make_test_app().await; + let thread_id = ThreadId::new(); + app.thread_event_channels.insert( + thread_id, + ThreadEventChannel::new(THREAD_EVENT_CHANNEL_CAPACITY), + ); + + app.reset_thread_event_state(); + app.handle_routed_thread_event( + thread_id, + Event { + id: "stale-event".to_string(), + msg: EventMsg::ShutdownComplete, + }, + ) + .await?; + + assert!( + !app.thread_event_channels.contains_key(&thread_id), + "stale routed events should not recreate cleared thread channels" + ); + assert_eq!(app.active_thread_id, None); + assert_eq!(app.primary_thread_id, None); + Ok(()) + } + + #[tokio::test] + async fn reset_thread_event_state_aborts_listener_tasks() { + struct NotifyOnDrop(Option>); + + impl Drop for NotifyOnDrop { + fn drop(&mut self) { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + } + } + } + + let mut app = make_test_app().await; + let thread_id = ThreadId::new(); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel(); + let handle = tokio::spawn(async move { + let _notify_on_drop = NotifyOnDrop(Some(dropped_tx)); + let _ = started_tx.send(()); + std::future::pending::<()>().await; + }); + app.thread_event_listener_tasks.insert(thread_id, handle); + started_rx + .await + .expect("listener task should report it started"); + + app.reset_thread_event_state(); + + assert_eq!(app.thread_event_listener_tasks.is_empty(), true); + time::timeout(Duration::from_millis(50), dropped_rx) + .await + .expect("timed out waiting for listener task abort") + .expect("listener task drop notification should succeed"); + } + #[tokio::test] async fn enqueue_thread_event_does_not_block_when_channel_full() -> Result<()> { let mut app = make_test_app().await; @@ -3585,6 +4073,51 @@ mod tests { Ok(()) } + #[tokio::test] + async fn open_agent_picker_prompts_to_enable_multi_agent_when_disabled() -> Result<()> { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + + app.open_agent_picker().await; + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_matches!( + app_event_rx.try_recv(), + Ok(AppEvent::UpdateFeatureFlags { updates }) if updates == vec![(Feature::Collab, true)] + ); + let cell = match app_event_rx.try_recv() { + Ok(AppEvent::InsertHistoryCell(cell)) => cell, + other => panic!("expected InsertHistoryCell event, got {other:?}"), + }; + let rendered = cell + .display_lines(120) + .into_iter() + .map(|line| line.to_string()) + .collect::>() + .join("\n"); + assert!(rendered.contains("Multi-agent will be enabled in the next session.")); + Ok(()) + } + + #[tokio::test] + async fn open_agent_picker_allows_existing_agent_threads_when_feature_is_disabled() -> Result<()> + { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + app.thread_event_channels + .insert(thread_id, ThreadEventChannel::new(1)); + + app.open_agent_picker().await; + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_matches!( + app_event_rx.try_recv(), + Ok(AppEvent::SelectAgentThread(selected_thread_id)) if selected_thread_id == thread_id + ); + Ok(()) + } + #[tokio::test] async fn refresh_pending_thread_approvals_only_lists_inactive_threads() { let mut app = make_test_app().await; @@ -3615,6 +4148,7 @@ mod tests { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: Vec::new(), }, ), @@ -3642,6 +4176,86 @@ mod tests { assert!(app.chat_widget.pending_thread_approvals().is_empty()); } + #[tokio::test] + async fn inactive_thread_approval_bubbles_into_active_view() -> Result<()> { + let mut app = make_test_app().await; + let main_thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000011").expect("valid thread"); + let agent_thread_id = + ThreadId::from_string("00000000-0000-0000-0000-000000000022").expect("valid thread"); + + app.primary_thread_id = Some(main_thread_id); + app.active_thread_id = Some(main_thread_id); + app.thread_event_channels + .insert(main_thread_id, ThreadEventChannel::new(1)); + app.thread_event_channels.insert( + agent_thread_id, + ThreadEventChannel::new_with_session_configured( + 1, + Event { + id: String::new(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id: agent_thread_id, + forked_from_id: None, + thread_name: None, + model: "gpt-5".to_string(), + model_provider_id: "test-provider".to_string(), + service_tier: None, + approval_policy: AskForApproval::OnRequest, + sandbox_policy: SandboxPolicy::new_workspace_write_policy(), + cwd: PathBuf::from("/tmp/agent"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::from("/tmp/agent-rollout.jsonl")), + }), + }, + ), + ); + app.agent_picker_threads.insert( + agent_thread_id, + AgentPickerThreadEntry { + agent_nickname: Some("Robie".to_string()), + agent_role: Some("explorer".to_string()), + is_closed: false, + }, + ); + + app.enqueue_thread_event( + agent_thread_id, + Event { + id: "ev-approval".to_string(), + msg: EventMsg::ExecApprovalRequest( + codex_protocol::protocol::ExecApprovalRequestEvent { + call_id: "call-approval".to_string(), + approval_id: None, + turn_id: "turn-approval".to_string(), + command: vec!["echo".to_string(), "hi".to_string()], + cwd: PathBuf::from("/tmp/agent"), + reason: Some("need approval".to_string()), + network_approval_context: None, + proposed_execpolicy_amendment: None, + proposed_network_policy_amendments: None, + additional_permissions: None, + available_decisions: None, + parsed_cmd: Vec::new(), + }, + ), + }, + ) + .await?; + + assert_eq!(app.chat_widget.has_active_view(), true); + assert_eq!( + app.chat_widget.pending_thread_approvals(), + &["Robie [explorer]".to_string()] + ); + + Ok(()) + } + #[test] fn agent_picker_item_name_snapshot() { let thread_id = @@ -3807,6 +4421,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), @@ -3823,6 +4438,7 @@ mod tests { event, is_first, None, + None, )) as Arc }; @@ -3921,6 +4537,7 @@ mod tests { pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), thread_event_channels: HashMap::new(), + thread_event_listener_tasks: HashMap::new(), agent_picker_threads: HashMap::new(), active_thread_id: None, active_thread_rx: None, @@ -3980,6 +4597,7 @@ mod tests { pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), thread_event_channels: HashMap::new(), + thread_event_listener_tasks: HashMap::new(), agent_picker_threads: HashMap::new(), active_thread_id: None, active_thread_rx: None, @@ -4025,6 +4643,15 @@ mod tests { codex_core::test_support::all_model_presets().clone() } + fn model_availability_nux_config(shown_count: &[(&str, u32)]) -> ModelAvailabilityNuxConfig { + ModelAvailabilityNuxConfig { + shown_count: shown_count + .iter() + .map(|(model, count)| ((*model).to_string(), *count)) + .collect(), + } + } + fn model_migration_copy_to_plain_text( copy: &crate::model_migration::ModelMigrationCopy, ) -> String { @@ -4081,6 +4708,120 @@ mod tests { )); } + #[test] + fn select_model_availability_nux_picks_only_eligible_model() { + let mut presets = all_model_presets(); + presets.iter_mut().for_each(|preset| { + preset.availability_nux = None; + }); + let target = presets + .iter_mut() + .find(|preset| preset.model == "gpt-5") + .expect("target preset present"); + target.availability_nux = Some(ModelAvailabilityNux { + message: "gpt-5 is available".to_string(), + }); + + let selected = select_model_availability_nux(&presets, &model_availability_nux_config(&[])); + + assert_eq!( + selected, + Some(StartupTooltipOverride { + model_slug: "gpt-5".to_string(), + message: "gpt-5 is available".to_string(), + }) + ); + } + + #[test] + fn select_model_availability_nux_skips_missing_and_exhausted_models() { + let mut presets = all_model_presets(); + presets.iter_mut().for_each(|preset| { + preset.availability_nux = None; + }); + let gpt_5 = presets + .iter_mut() + .find(|preset| preset.model == "gpt-5") + .expect("gpt-5 preset present"); + gpt_5.availability_nux = Some(ModelAvailabilityNux { + message: "gpt-5 is available".to_string(), + }); + let gpt_5_2 = presets + .iter_mut() + .find(|preset| preset.model == "gpt-5.2") + .expect("gpt-5.2 preset present"); + gpt_5_2.availability_nux = Some(ModelAvailabilityNux { + message: "gpt-5.2 is available".to_string(), + }); + + let selected = select_model_availability_nux( + &presets, + &model_availability_nux_config(&[("gpt-5", MODEL_AVAILABILITY_NUX_MAX_SHOW_COUNT)]), + ); + + assert_eq!( + selected, + Some(StartupTooltipOverride { + model_slug: "gpt-5.2".to_string(), + message: "gpt-5.2 is available".to_string(), + }) + ); + } + + #[test] + fn select_model_availability_nux_uses_existing_model_order_as_priority() { + let mut presets = all_model_presets(); + presets.iter_mut().for_each(|preset| { + preset.availability_nux = None; + }); + let first = presets + .iter_mut() + .find(|preset| preset.model == "gpt-5") + .expect("gpt-5 preset present"); + first.availability_nux = Some(ModelAvailabilityNux { + message: "first".to_string(), + }); + let second = presets + .iter_mut() + .find(|preset| preset.model == "gpt-5.2") + .expect("gpt-5.2 preset present"); + second.availability_nux = Some(ModelAvailabilityNux { + message: "second".to_string(), + }); + + let selected = select_model_availability_nux(&presets, &model_availability_nux_config(&[])); + + assert_eq!( + selected, + Some(StartupTooltipOverride { + model_slug: "gpt-5.2".to_string(), + message: "second".to_string(), + }) + ); + } + + #[test] + fn select_model_availability_nux_returns_none_when_all_models_are_exhausted() { + let mut presets = all_model_presets(); + presets.iter_mut().for_each(|preset| { + preset.availability_nux = None; + }); + let target = presets + .iter_mut() + .find(|preset| preset.model == "gpt-5") + .expect("target preset present"); + target.availability_nux = Some(ModelAvailabilityNux { + message: "gpt-5 is available".to_string(), + }); + + let selected = select_model_availability_nux( + &presets, + &model_availability_nux_config(&[("gpt-5", MODEL_AVAILABILITY_NUX_MAX_SHOW_COUNT)]), + ); + + assert_eq!(selected, None); + } + #[tokio::test] async fn model_migration_prompt_respects_hide_flag_and_self_target() { let mut seen = BTreeMap::new(); @@ -4274,6 +5015,20 @@ mod tests { ); } + #[tokio::test] + async fn fresh_session_config_uses_current_service_tier() { + let mut app = make_test_app().await; + app.chat_widget + .set_service_tier(Some(codex_protocol::config_types::ServiceTier::Fast)); + + let config = app.fresh_session_config(); + + assert_eq!( + config.service_tier, + Some(codex_protocol::config_types::ServiceTier::Fast) + ); + } + #[tokio::test] async fn backtrack_selection_with_duplicate_history_targets_unique_turn() { let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await; @@ -4304,6 +5059,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4320,6 +5076,7 @@ mod tests { event, is_first, None, + None, )) as Arc }; @@ -4360,6 +5117,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4451,6 +5209,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4515,6 +5274,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4594,6 +5354,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4720,6 +5481,7 @@ mod tests { thread_name: None, model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4748,6 +5510,34 @@ mod tests { } } + #[tokio::test] + async fn shutdown_first_exit_returns_immediate_exit_when_shutdown_submit_fails() { + let mut app = make_test_app().await; + let thread_id = ThreadId::new(); + app.active_thread_id = Some(thread_id); + + let control = app.handle_exit_mode(ExitMode::ShutdownFirst); + + assert_eq!(app.pending_shutdown_exit_thread_id, None); + assert!(matches!( + control, + AppRunControl::Exit(ExitReason::UserRequested) + )); + } + + #[tokio::test] + async fn shutdown_first_exit_waits_for_shutdown_when_submit_succeeds() { + let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + app.active_thread_id = Some(thread_id); + + let control = app.handle_exit_mode(ExitMode::ShutdownFirst); + + assert_eq!(app.pending_shutdown_exit_thread_id, Some(thread_id)); + assert!(matches!(control, AppRunControl::Continue)); + assert_eq!(op_rx.try_recv(), Ok(Op::Shutdown)); + } + #[tokio::test] async fn clear_only_ui_reset_preserves_chat_session_state() { let mut app = make_test_app().await; @@ -4760,6 +5550,7 @@ mod tests { thread_name: Some("keep me".to_string()), model: "gpt-test".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/tmp/project"), diff --git a/codex-rs/tui/src/app/pending_interactive_replay.rs b/codex-rs/tui/src/app/pending_interactive_replay.rs index 3d30914781..d82d014827 100644 --- a/codex-rs/tui/src/app/pending_interactive_replay.rs +++ b/codex-rs/tui/src/app/pending_interactive_replay.rs @@ -402,6 +402,7 @@ mod tests { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: Vec::new(), }, ), @@ -544,6 +545,7 @@ mod tests { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: Vec::new(), }, ), @@ -622,6 +624,7 @@ mod tests { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: Vec::new(), }, ), diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 0767696e28..9f9a8d6de1 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -25,10 +25,33 @@ use crate::history_cell::HistoryCell; use codex_core::features::Feature; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::ServiceTier; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::SandboxPolicy; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RealtimeAudioDeviceKind { + Microphone, + Speaker, +} + +impl RealtimeAudioDeviceKind { + pub(crate) fn title(self) -> &'static str { + match self { + Self::Microphone => "Microphone", + Self::Speaker => "Speaker", + } + } + + pub(crate) fn noun(self) -> &'static str { + match self { + Self::Microphone => "microphone", + Self::Speaker => "speaker", + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(not(target_os = "windows"), allow(dead_code))] pub(crate) enum WindowsSandboxEnableMode { @@ -51,8 +74,17 @@ pub(crate) enum AppEvent { /// Switch the active thread to the selected agent. SelectAgentThread(ThreadId), - /// Recompute the list of inactive threads that still need approval. - RefreshPendingThreadApprovals, + /// Submit an op to the specified thread, regardless of current focus. + SubmitThreadOp { + thread_id: ThreadId, + op: codex_protocol::protocol::Op, + }, + + /// Forward an event from a non-primary thread into the app-level thread router. + ThreadEvent { + thread_id: ThreadId, + event: Event, + }, /// Start a new session. NewSession, @@ -166,6 +198,31 @@ pub(crate) enum AppEvent { personality: Personality, }, + /// Persist the selected service tier to the appropriate config. + PersistServiceTierSelection { + service_tier: Option, + }, + + /// Open the device picker for a realtime microphone or speaker. + OpenRealtimeAudioDeviceSelection { + kind: RealtimeAudioDeviceKind, + }, + + /// Persist the selected realtime microphone or speaker to top-level config. + #[cfg_attr( + any(target_os = "linux", not(feature = "voice-input")), + allow(dead_code) + )] + PersistRealtimeAudioDeviceSelection { + kind: RealtimeAudioDeviceKind, + name: Option, + }, + + /// Restart the selected realtime microphone or speaker locally. + RestartRealtimeAudioDevice { + kind: RealtimeAudioDeviceKind, + }, + /// Open the reasoning selection popup after picking a model. OpenReasoningPopup { model: ModelPreset, diff --git a/codex-rs/tui/src/audio_device.rs b/codex-rs/tui/src/audio_device.rs new file mode 100644 index 0000000000..6c3b22ccdd --- /dev/null +++ b/codex-rs/tui/src/audio_device.rs @@ -0,0 +1,176 @@ +use codex_core::config::Config; +use cpal::traits::DeviceTrait; +use cpal::traits::HostTrait; +use tracing::warn; + +use crate::app_event::RealtimeAudioDeviceKind; + +const PREFERRED_INPUT_SAMPLE_RATE: u32 = 24_000; +const PREFERRED_INPUT_CHANNELS: u16 = 1; + +pub(crate) fn list_realtime_audio_device_names( + kind: RealtimeAudioDeviceKind, +) -> Result, String> { + let host = cpal::default_host(); + let mut device_names = Vec::new(); + for device in devices(&host, kind)? { + let Ok(name) = device.name() else { + continue; + }; + if !device_names.contains(&name) { + device_names.push(name); + } + } + Ok(device_names) +} + +pub(crate) fn select_configured_input_device_and_config( + config: &Config, +) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> { + select_device_and_config(RealtimeAudioDeviceKind::Microphone, config) +} + +pub(crate) fn select_configured_output_device_and_config( + config: &Config, +) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> { + select_device_and_config(RealtimeAudioDeviceKind::Speaker, config) +} + +pub(crate) fn preferred_input_config( + device: &cpal::Device, +) -> Result { + let supported_configs = device + .supported_input_configs() + .map_err(|err| format!("failed to enumerate input audio configs: {err}"))?; + + supported_configs + .filter_map(|range| { + let sample_format_rank = match range.sample_format() { + cpal::SampleFormat::I16 => 0u8, + cpal::SampleFormat::U16 => 1u8, + cpal::SampleFormat::F32 => 2u8, + _ => return None, + }; + let sample_rate = preferred_input_sample_rate(&range); + let sample_rate_penalty = sample_rate.0.abs_diff(PREFERRED_INPUT_SAMPLE_RATE); + let channel_penalty = range.channels().abs_diff(PREFERRED_INPUT_CHANNELS); + Some(( + (sample_rate_penalty, channel_penalty, sample_format_rank), + range.with_sample_rate(sample_rate), + )) + }) + .min_by_key(|(score, _)| *score) + .map(|(_, config)| config) + .or_else(|| device.default_input_config().ok()) + .ok_or_else(|| "failed to get default input config".to_string()) +} + +fn select_device_and_config( + kind: RealtimeAudioDeviceKind, + config: &Config, +) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> { + let host = cpal::default_host(); + let configured_name = configured_name(kind, config); + let selected = configured_name + .and_then(|name| find_device_by_name(&host, kind, name)) + .or_else(|| { + let default_device = default_device(&host, kind); + if let Some(name) = configured_name && default_device.is_some() { + warn!( + "configured {} audio device `{name}` was unavailable; falling back to system default", + kind.noun() + ); + } + default_device + }) + .ok_or_else(|| missing_device_error(kind, configured_name))?; + + let stream_config = match kind { + RealtimeAudioDeviceKind::Microphone => preferred_input_config(&selected)?, + RealtimeAudioDeviceKind::Speaker => default_config(&selected, kind)?, + }; + Ok((selected, stream_config)) +} + +fn configured_name(kind: RealtimeAudioDeviceKind, config: &Config) -> Option<&str> { + match kind { + RealtimeAudioDeviceKind::Microphone => config.realtime_audio.microphone.as_deref(), + RealtimeAudioDeviceKind::Speaker => config.realtime_audio.speaker.as_deref(), + } +} + +fn find_device_by_name( + host: &cpal::Host, + kind: RealtimeAudioDeviceKind, + name: &str, +) -> Option { + let devices = devices(host, kind).ok()?; + devices + .into_iter() + .find(|device| device.name().ok().as_deref() == Some(name)) +} + +fn devices(host: &cpal::Host, kind: RealtimeAudioDeviceKind) -> Result, String> { + match kind { + RealtimeAudioDeviceKind::Microphone => host + .input_devices() + .map(|devices| devices.collect()) + .map_err(|err| format!("failed to enumerate input audio devices: {err}")), + RealtimeAudioDeviceKind::Speaker => host + .output_devices() + .map(|devices| devices.collect()) + .map_err(|err| format!("failed to enumerate output audio devices: {err}")), + } +} + +fn default_device(host: &cpal::Host, kind: RealtimeAudioDeviceKind) -> Option { + match kind { + RealtimeAudioDeviceKind::Microphone => host.default_input_device(), + RealtimeAudioDeviceKind::Speaker => host.default_output_device(), + } +} + +fn default_config( + device: &cpal::Device, + kind: RealtimeAudioDeviceKind, +) -> Result { + match kind { + RealtimeAudioDeviceKind::Microphone => device + .default_input_config() + .map_err(|err| format!("failed to get default input config: {err}")), + RealtimeAudioDeviceKind::Speaker => device + .default_output_config() + .map_err(|err| format!("failed to get default output config: {err}")), + } +} + +fn preferred_input_sample_rate(range: &cpal::SupportedStreamConfigRange) -> cpal::SampleRate { + let min = range.min_sample_rate().0; + let max = range.max_sample_rate().0; + if (min..=max).contains(&PREFERRED_INPUT_SAMPLE_RATE) { + cpal::SampleRate(PREFERRED_INPUT_SAMPLE_RATE) + } else if PREFERRED_INPUT_SAMPLE_RATE < min { + cpal::SampleRate(min) + } else { + cpal::SampleRate(max) + } +} + +fn missing_device_error(kind: RealtimeAudioDeviceKind, configured_name: Option<&str>) -> String { + match (kind, configured_name) { + (RealtimeAudioDeviceKind::Microphone, Some(name)) => { + format!( + "configured microphone `{name}` was unavailable and no default input audio device was found" + ) + } + (RealtimeAudioDeviceKind::Speaker, Some(name)) => { + format!( + "configured speaker `{name}` was unavailable and no default output audio device was found" + ) + } + (RealtimeAudioDeviceKind::Microphone, None) => { + "no input audio device available".to_string() + } + (RealtimeAudioDeviceKind::Speaker, None) => "no output audio device available".to_string(), + } +} diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index fd58baef46..a9ef2cd38a 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -17,13 +17,12 @@ use crate::render::highlight::highlight_bash_to_lines; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; use codex_core::features::Features; +use codex_protocol::ThreadId; use codex_protocol::mcp::RequestId; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::ElicitationAction; -use codex_protocol::protocol::ExecPolicyAmendment; use codex_protocol::protocol::FileChange; use codex_protocol::protocol::NetworkApprovalContext; -use codex_protocol::protocol::NetworkPolicyAmendment; use codex_protocol::protocol::NetworkPolicyRuleAction; use codex_protocol::protocol::Op; use codex_protocol::protocol::ReviewDecision; @@ -43,31 +42,53 @@ use ratatui::widgets::Wrap; #[derive(Clone, Debug)] pub(crate) enum ApprovalRequest { Exec { + thread_id: ThreadId, + thread_label: Option, id: String, command: Vec, reason: Option, + available_decisions: Vec, network_approval_context: Option, - proposed_execpolicy_amendment: Option, - proposed_network_policy_amendments: Option>, additional_permissions: Option, }, ApplyPatch { + thread_id: ThreadId, + thread_label: Option, id: String, reason: Option, cwd: PathBuf, changes: HashMap, }, McpElicitation { + thread_id: ThreadId, + thread_label: Option, server_name: String, request_id: RequestId, message: String, }, } +impl ApprovalRequest { + fn thread_id(&self) -> ThreadId { + match self { + ApprovalRequest::Exec { thread_id, .. } + | ApprovalRequest::ApplyPatch { thread_id, .. } + | ApprovalRequest::McpElicitation { thread_id, .. } => *thread_id, + } + } + + fn thread_label(&self) -> Option<&str> { + match self { + ApprovalRequest::Exec { thread_label, .. } + | ApprovalRequest::ApplyPatch { thread_label, .. } + | ApprovalRequest::McpElicitation { thread_label, .. } => thread_label.as_deref(), + } + } +} + /// Modal overlay asking the user to approve or deny one or more requests. pub(crate) struct ApprovalOverlay { current_request: Option, - current_variant: Option, queue: Vec, app_event_tx: AppEventSender, list: ListSelectionView, @@ -81,7 +102,6 @@ impl ApprovalOverlay { pub fn new(request: ApprovalRequest, app_event_tx: AppEventSender, features: Features) -> Self { let mut view = Self { current_request: None, - current_variant: None, queue: Vec::new(), app_event_tx: app_event_tx.clone(), list: ListSelectionView::new(Default::default(), app_event_tx), @@ -99,31 +119,28 @@ impl ApprovalOverlay { } fn set_current(&mut self, request: ApprovalRequest) { - self.current_request = Some(request.clone()); - let ApprovalRequestState { variant, header } = ApprovalRequestState::from(request); - self.current_variant = Some(variant.clone()); self.current_complete = false; - let (options, params) = Self::build_options(variant, header, &self.features); + let header = build_header(&request); + let (options, params) = Self::build_options(&request, header, &self.features); + self.current_request = Some(request); self.options = options; self.list = ListSelectionView::new(params, self.app_event_tx.clone()); } fn build_options( - variant: ApprovalVariant, + request: &ApprovalRequest, header: Box, _features: &Features, ) -> (Vec, SelectionViewParams) { - let (options, title) = match &variant { - ApprovalVariant::Exec { + let (options, title) = match request { + ApprovalRequest::Exec { + available_decisions, network_approval_context, - proposed_execpolicy_amendment, - proposed_network_policy_amendments, additional_permissions, .. } => ( exec_options( - proposed_execpolicy_amendment.clone(), - proposed_network_policy_amendments.clone(), + available_decisions, network_approval_context.as_ref(), additional_permissions.as_ref(), ), @@ -137,11 +154,11 @@ impl ApprovalOverlay { }, ), ), - ApprovalVariant::ApplyPatch { .. } => ( + ApprovalRequest::ApplyPatch { .. } => ( patch_options(), "Would you like to make the following edits?".to_string(), ), - ApprovalVariant::McpElicitation { server_name, .. } => ( + ApprovalRequest::McpElicitation { server_name, .. } => ( elicitation_options(), format!("{server_name} needs your approval."), ), @@ -166,13 +183,7 @@ impl ApprovalOverlay { .collect(); let params = SelectionViewParams { - footer_hint: Some(Line::from(vec![ - "Press ".into(), - key_hint::plain(KeyCode::Enter).into(), - " to confirm or ".into(), - key_hint::plain(KeyCode::Esc).into(), - " to cancel".into(), - ])), + footer_hint: Some(approval_footer_hint(request)), items, header, ..Default::default() @@ -188,18 +199,19 @@ impl ApprovalOverlay { let Some(option) = self.options.get(actual_idx) else { return; }; - if let Some(variant) = self.current_variant.as_ref() { - match (variant, &option.decision) { - (ApprovalVariant::Exec { id, command, .. }, ApprovalDecision::Review(decision)) => { + if let Some(request) = self.current_request.as_ref() { + match (request, &option.decision) { + (ApprovalRequest::Exec { id, command, .. }, ApprovalDecision::Review(decision)) => { self.handle_exec_decision(id, command, decision.clone()); } - (ApprovalVariant::ApplyPatch { id, .. }, ApprovalDecision::Review(decision)) => { + (ApprovalRequest::ApplyPatch { id, .. }, ApprovalDecision::Review(decision)) => { self.handle_patch_decision(id, decision.clone()); } ( - ApprovalVariant::McpElicitation { + ApprovalRequest::McpElicitation { server_name, request_id, + .. }, ApprovalDecision::McpElicitation(decision), ) => { @@ -214,20 +226,39 @@ impl ApprovalOverlay { } fn handle_exec_decision(&self, id: &str, command: &[String], decision: ReviewDecision) { - let cell = history_cell::new_approval_decision_cell(command.to_vec(), decision.clone()); - self.app_event_tx.send(AppEvent::InsertHistoryCell(cell)); - self.app_event_tx.send(AppEvent::CodexOp(Op::ExecApproval { - id: id.to_string(), - turn_id: None, - decision, - })); + let Some(request) = self.current_request.as_ref() else { + return; + }; + if request.thread_label().is_none() { + let cell = history_cell::new_approval_decision_cell(command.to_vec(), decision.clone()); + self.app_event_tx.send(AppEvent::InsertHistoryCell(cell)); + } + let thread_id = request.thread_id(); + self.app_event_tx.send(AppEvent::SubmitThreadOp { + thread_id, + op: Op::ExecApproval { + id: id.to_string(), + turn_id: None, + decision, + }, + }); } fn handle_patch_decision(&self, id: &str, decision: ReviewDecision) { - self.app_event_tx.send(AppEvent::CodexOp(Op::PatchApproval { - id: id.to_string(), - decision, - })); + let Some(thread_id) = self + .current_request + .as_ref() + .map(ApprovalRequest::thread_id) + else { + return; + }; + self.app_event_tx.send(AppEvent::SubmitThreadOp { + thread_id, + op: Op::PatchApproval { + id: id.to_string(), + decision, + }, + }); } fn handle_elicitation_decision( @@ -236,12 +267,21 @@ impl ApprovalOverlay { request_id: &RequestId, decision: ElicitationAction, ) { - self.app_event_tx - .send(AppEvent::CodexOp(Op::ResolveElicitation { + let Some(thread_id) = self + .current_request + .as_ref() + .map(ApprovalRequest::thread_id) + else { + return; + }; + self.app_event_tx.send(AppEvent::SubmitThreadOp { + thread_id, + op: Op::ResolveElicitation { server_name: server_name.to_string(), request_id: request_id.clone(), decision, - })); + }, + }); } fn advance_queue(&mut self) { @@ -268,6 +308,23 @@ impl ApprovalOverlay { false } } + KeyEvent { + kind: KeyEventKind::Press, + code: KeyCode::Char('o'), + .. + } => { + if let Some(request) = self.current_request.as_ref() { + if request.thread_label().is_some() { + self.app_event_tx + .send(AppEvent::SelectAgentThread(request.thread_id())); + true + } else { + false + } + } else { + false + } + } e => { if let Some(idx) = self .options @@ -300,18 +357,19 @@ impl BottomPaneView for ApprovalOverlay { return CancellationEvent::Handled; } if !self.current_complete - && let Some(variant) = self.current_variant.as_ref() + && let Some(request) = self.current_request.as_ref() { - match &variant { - ApprovalVariant::Exec { id, command, .. } => { + match request { + ApprovalRequest::Exec { id, command, .. } => { self.handle_exec_decision(id, command, ReviewDecision::Abort); } - ApprovalVariant::ApplyPatch { id, .. } => { + ApprovalRequest::ApplyPatch { id, .. } => { self.handle_patch_decision(id, ReviewDecision::Abort); } - ApprovalVariant::McpElicitation { + ApprovalRequest::McpElicitation { server_name, request_id, + .. } => { self.handle_elicitation_decision( server_name, @@ -353,122 +411,120 @@ impl Renderable for ApprovalOverlay { } } -struct ApprovalRequestState { - variant: ApprovalVariant, - header: Box, +fn approval_footer_hint(request: &ApprovalRequest) -> Line<'static> { + let mut spans = vec![ + "Press ".into(), + key_hint::plain(KeyCode::Enter).into(), + " to confirm or ".into(), + key_hint::plain(KeyCode::Esc).into(), + " to cancel".into(), + ]; + if request.thread_label().is_some() { + spans.extend([ + " or ".into(), + key_hint::plain(KeyCode::Char('o')).into(), + " to open thread".into(), + ]); + } + Line::from(spans) } -impl From for ApprovalRequestState { - fn from(value: ApprovalRequest) -> Self { - match value { - ApprovalRequest::Exec { - id, - command, - reason, - network_approval_context, - proposed_execpolicy_amendment, - proposed_network_policy_amendments, - additional_permissions, - } => { - let mut header: Vec> = Vec::new(); - if let Some(reason) = reason { - header.push(Line::from(vec!["Reason: ".into(), reason.italic()])); - header.push(Line::from("")); - } - if let Some(ref additional_permissions) = additional_permissions - && let Some(rule_line) = - format_additional_permissions_rule(additional_permissions) - { - header.push(Line::from(vec![ - "Permission rule: ".into(), - rule_line.cyan(), - ])); - header.push(Line::from("")); - } - let full_cmd = strip_bash_lc_and_escape(&command); - let mut full_cmd_lines = highlight_bash_to_lines(&full_cmd); - if let Some(first) = full_cmd_lines.first_mut() { - first.spans.insert(0, Span::from("$ ")); - } - if network_approval_context.is_none() { - header.extend(full_cmd_lines); - } - Self { - variant: ApprovalVariant::Exec { - id, - command, - network_approval_context, - proposed_execpolicy_amendment, - proposed_network_policy_amendments, - additional_permissions, - }, - header: Box::new(Paragraph::new(header).wrap(Wrap { trim: false })), - } +fn build_header(request: &ApprovalRequest) -> Box { + match request { + ApprovalRequest::Exec { + thread_label, + reason, + command, + network_approval_context, + additional_permissions, + .. + } => { + let mut header: Vec> = Vec::new(); + if let Some(thread_label) = thread_label { + header.push(Line::from(vec![ + "Thread: ".into(), + thread_label.clone().bold(), + ])); + header.push(Line::from("")); } - ApprovalRequest::ApplyPatch { - id, - reason, - cwd, - changes, - } => { - let mut header: Vec> = Vec::new(); - if let Some(reason) = reason - && !reason.is_empty() - { - header.push(Box::new( - Paragraph::new(Line::from_iter(["Reason: ".into(), reason.italic()])) - .wrap(Wrap { trim: false }), - )); - header.push(Box::new(Line::from(""))); - } - header.push(DiffSummary::new(changes, cwd).into()); - Self { - variant: ApprovalVariant::ApplyPatch { id }, - header: Box::new(ColumnRenderable::with(header)), - } + if let Some(reason) = reason { + header.push(Line::from(vec!["Reason: ".into(), reason.clone().italic()])); + header.push(Line::from("")); } - ApprovalRequest::McpElicitation { - server_name, - request_id, - message, - } => { - let header = Paragraph::new(vec![ - Line::from(vec!["Server: ".into(), server_name.clone().bold()]), - Line::from(""), - Line::from(message), - ]) - .wrap(Wrap { trim: false }); - Self { - variant: ApprovalVariant::McpElicitation { - server_name, - request_id, - }, - header: Box::new(header), - } + if let Some(additional_permissions) = additional_permissions + && let Some(rule_line) = format_additional_permissions_rule(additional_permissions) + { + header.push(Line::from(vec![ + "Permission rule: ".into(), + rule_line.cyan(), + ])); + header.push(Line::from("")); } + let full_cmd = strip_bash_lc_and_escape(command); + let mut full_cmd_lines = highlight_bash_to_lines(&full_cmd); + if let Some(first) = full_cmd_lines.first_mut() { + first.spans.insert(0, Span::from("$ ")); + } + if network_approval_context.is_none() { + header.extend(full_cmd_lines); + } + Box::new(Paragraph::new(header).wrap(Wrap { trim: false })) + } + ApprovalRequest::ApplyPatch { + thread_label, + reason, + cwd, + changes, + .. + } => { + let mut header: Vec> = Vec::new(); + if let Some(thread_label) = thread_label { + header.push(Box::new(Line::from(vec![ + "Thread: ".into(), + thread_label.clone().bold(), + ]))); + header.push(Box::new(Line::from(""))); + } + if let Some(reason) = reason + && !reason.is_empty() + { + header.push(Box::new( + Paragraph::new(Line::from_iter([ + "Reason: ".into(), + reason.clone().italic(), + ])) + .wrap(Wrap { trim: false }), + )); + header.push(Box::new(Line::from(""))); + } + header.push(DiffSummary::new(changes.clone(), cwd.clone()).into()); + Box::new(ColumnRenderable::with(header)) + } + ApprovalRequest::McpElicitation { + thread_label, + server_name, + message, + .. + } => { + let mut lines = Vec::new(); + if let Some(thread_label) = thread_label { + lines.push(Line::from(vec![ + "Thread: ".into(), + thread_label.clone().bold(), + ])); + lines.push(Line::from("")); + } + lines.extend([ + Line::from(vec!["Server: ".into(), server_name.clone().bold()]), + Line::from(""), + Line::from(message.clone()), + ]); + let header = Paragraph::new(lines).wrap(Wrap { trim: false }); + Box::new(header) } } } -#[derive(Clone)] -enum ApprovalVariant { - Exec { - id: String, - command: Vec, - network_approval_context: Option, - proposed_execpolicy_amendment: Option, - proposed_network_policy_amendments: Option>, - additional_permissions: Option, - }, - ApplyPatch { - id: String, - }, - McpElicitation { - server_name: String, - request_id: RequestId, - }, -} - #[derive(Clone)] enum ApprovalDecision { Review(ReviewDecision), @@ -492,100 +548,93 @@ impl ApprovalOption { } fn exec_options( - proposed_execpolicy_amendment: Option, - proposed_network_policy_amendments: Option>, + available_decisions: &[ReviewDecision], network_approval_context: Option<&NetworkApprovalContext>, additional_permissions: Option<&PermissionProfile>, ) -> Vec { - if network_approval_context.is_some() { - let mut options = vec![ - ApprovalOption { - label: "Yes, just this once".to_string(), + available_decisions + .iter() + .filter_map(|decision| match decision { + ReviewDecision::Approved => Some(ApprovalOption { + label: if network_approval_context.is_some() { + "Yes, just this once".to_string() + } else { + "Yes, proceed".to_string() + }, decision: ApprovalDecision::Review(ReviewDecision::Approved), display_shortcut: None, additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))], - }, - ApprovalOption { - label: "Yes, and allow this host for this conversation".to_string(), + }), + ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment, + } => { + let rendered_prefix = + strip_bash_lc_and_escape(proposed_execpolicy_amendment.command()); + if rendered_prefix.contains('\n') || rendered_prefix.contains('\r') { + return None; + } + + Some(ApprovalOption { + label: format!( + "Yes, and don't ask again for commands that start with `{rendered_prefix}`" + ), + decision: ApprovalDecision::Review( + ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: proposed_execpolicy_amendment.clone(), + }, + ), + display_shortcut: None, + additional_shortcuts: vec![key_hint::plain(KeyCode::Char('p'))], + }) + } + ReviewDecision::ApprovedForSession => Some(ApprovalOption { + label: if network_approval_context.is_some() { + "Yes, and allow this host for this conversation".to_string() + } else if additional_permissions.is_some() { + "Yes, and allow these permissions for this session".to_string() + } else { + "Yes, and don't ask again for this command in this session".to_string() + }, decision: ApprovalDecision::Review(ReviewDecision::ApprovedForSession), display_shortcut: None, additional_shortcuts: vec![key_hint::plain(KeyCode::Char('a'))], - }, - ]; - for amendment in proposed_network_policy_amendments.unwrap_or_default() { - let (label, shortcut) = match amendment.action { - NetworkPolicyRuleAction::Allow => ( - "Yes, and allow this host in the future".to_string(), - KeyCode::Char('p'), - ), - NetworkPolicyRuleAction::Deny => continue, - }; - options.push(ApprovalOption { - label, - decision: ApprovalDecision::Review(ReviewDecision::NetworkPolicyAmendment { - network_policy_amendment: amendment, - }), + }), + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment, + } => { + let (label, shortcut) = match network_policy_amendment.action { + NetworkPolicyRuleAction::Allow => ( + "Yes, and allow this host in the future".to_string(), + KeyCode::Char('p'), + ), + NetworkPolicyRuleAction::Deny => ( + "No, and block this host in the future".to_string(), + KeyCode::Char('d'), + ), + }; + Some(ApprovalOption { + label, + decision: ApprovalDecision::Review(ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: network_policy_amendment.clone(), + }), + display_shortcut: None, + additional_shortcuts: vec![key_hint::plain(shortcut)], + }) + } + ReviewDecision::Denied => Some(ApprovalOption { + label: "No, continue without running it".to_string(), + decision: ApprovalDecision::Review(ReviewDecision::Denied), display_shortcut: None, - additional_shortcuts: vec![key_hint::plain(shortcut)], - }); - } - options.push(ApprovalOption { - label: "No, and tell Codex what to do differently".to_string(), - decision: ApprovalDecision::Review(ReviewDecision::Abort), - display_shortcut: Some(key_hint::plain(KeyCode::Esc)), - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))], - }); - return options; - } - - if additional_permissions.is_some() { - return vec![ - ApprovalOption { - label: "Yes, proceed".to_string(), - decision: ApprovalDecision::Review(ReviewDecision::Approved), - display_shortcut: None, - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))], - }, - ApprovalOption { + additional_shortcuts: vec![key_hint::plain(KeyCode::Char('d'))], + }), + ReviewDecision::Abort => Some(ApprovalOption { label: "No, and tell Codex what to do differently".to_string(), decision: ApprovalDecision::Review(ReviewDecision::Abort), display_shortcut: Some(key_hint::plain(KeyCode::Esc)), additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))], - }, - ]; - } - - vec![ApprovalOption { - label: "Yes, proceed".to_string(), - decision: ApprovalDecision::Review(ReviewDecision::Approved), - display_shortcut: None, - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))], - }] - .into_iter() - .chain(proposed_execpolicy_amendment.and_then(|prefix| { - let rendered_prefix = strip_bash_lc_and_escape(prefix.command()); - if rendered_prefix.contains('\n') || rendered_prefix.contains('\r') { - return None; - } - - Some(ApprovalOption { - label: format!( - "Yes, and don't ask again for commands that start with `{rendered_prefix}`" - ), - decision: ApprovalDecision::Review(ReviewDecision::ApprovedExecpolicyAmendment { - proposed_execpolicy_amendment: prefix, }), - display_shortcut: None, - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('p'))], }) - })) - .chain([ApprovalOption { - label: "No, and tell Codex what to do differently".to_string(), - decision: ApprovalDecision::Review(ReviewDecision::Abort), - display_shortcut: Some(key_hint::plain(KeyCode::Esc)), - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))], - }]) - .collect() + .collect() } fn format_additional_permissions_rule( @@ -669,11 +718,18 @@ mod tests { use super::*; use crate::app_event::AppEvent; use codex_protocol::models::FileSystemPermissions; + use codex_protocol::protocol::ExecPolicyAmendment; use codex_protocol::protocol::NetworkApprovalProtocol; + use codex_protocol::protocol::NetworkPolicyAmendment; + use codex_utils_absolute_path::AbsolutePathBuf; use insta::assert_snapshot; use pretty_assertions::assert_eq; use tokio::sync::mpsc::unbounded_channel; + fn absolute_path(path: &str) -> AbsolutePathBuf { + AbsolutePathBuf::from_absolute_path(path).expect("absolute path") + } + fn render_overlay_lines(view: &ApprovalOverlay, width: u16) -> String { let height = view.desired_height(width); let mut buf = Buffer::empty(Rect::new(0, 0, width, height)); @@ -690,14 +746,26 @@ mod tests { .join("\n") } + fn normalize_snapshot_paths(rendered: String) -> String { + [ + (absolute_path("/tmp/readme.txt"), "/tmp/readme.txt"), + (absolute_path("/tmp/out.txt"), "/tmp/out.txt"), + ] + .into_iter() + .fold(rendered, |rendered, (path, normalized)| { + rendered.replace(&path.display().to_string(), normalized) + }) + } + fn make_exec_request() -> ApprovalRequest { ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".to_string(), command: vec!["echo".to_string(), "hi".to_string()], reason: Some("reason".to_string()), + available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: None, additional_permissions: None, } } @@ -720,10 +788,10 @@ mod tests { let mut view = ApprovalOverlay::new(make_exec_request(), tx, Features::with_defaults()); assert!(!view.is_complete()); view.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - // We expect at least one CodexOp message in the queue. + // We expect at least one thread-scoped approval op message in the queue. let mut saw_op = false; while let Ok(ev) = rx.try_recv() { - if matches!(ev, AppEvent::CodexOp(_)) { + if matches!(ev, AppEvent::SubmitThreadOp { .. }) { saw_op = true; break; } @@ -731,20 +799,81 @@ mod tests { assert!(saw_op, "expected approval decision to emit an op"); } + #[test] + fn o_opens_source_thread_for_cross_thread_approval() { + let (tx, mut rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx); + let thread_id = ThreadId::new(); + let mut view = ApprovalOverlay::new( + ApprovalRequest::Exec { + thread_id, + thread_label: Some("Robie [explorer]".to_string()), + id: "test".to_string(), + command: vec!["echo".to_string(), "hi".to_string()], + reason: None, + available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], + network_approval_context: None, + additional_permissions: None, + }, + tx, + Features::with_defaults(), + ); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE)); + + let event = rx.try_recv().expect("expected select-agent-thread event"); + assert_eq!( + matches!(event, AppEvent::SelectAgentThread(id) if id == thread_id), + true + ); + } + + #[test] + fn cross_thread_footer_hint_mentions_o_shortcut() { + let (tx, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx); + let view = ApprovalOverlay::new( + ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: Some("Robie [explorer]".to_string()), + id: "test".to_string(), + command: vec!["echo".to_string(), "hi".to_string()], + reason: None, + available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], + network_approval_context: None, + additional_permissions: None, + }, + tx, + Features::with_defaults(), + ); + + assert_snapshot!( + "approval_overlay_cross_thread_prompt", + render_overlay_lines(&view, 80) + ); + } + #[test] fn exec_prefix_option_emits_execpolicy_amendment() { let (tx, mut rx) = unbounded_channel::(); let tx = AppEventSender::new(tx); let mut view = ApprovalOverlay::new( ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".to_string(), command: vec!["echo".to_string()], reason: None, + available_decisions: vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedExecpolicyAmendment { + proposed_execpolicy_amendment: ExecPolicyAmendment::new(vec![ + "echo".to_string(), + ]), + }, + ReviewDecision::Abort, + ], network_approval_context: None, - proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ - "echo".to_string(), - ])), - proposed_network_policy_amendments: None, additional_permissions: None, }, tx, @@ -753,7 +882,11 @@ mod tests { view.handle_key_event(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE)); let mut saw_op = false; while let Ok(ev) = rx.try_recv() { - if let AppEvent::CodexOp(Op::ExecApproval { decision, .. }) = ev { + if let AppEvent::SubmitThreadOp { + op: Op::ExecApproval { decision, .. }, + .. + } = ev + { assert_eq!( decision, ReviewDecision::ApprovedExecpolicyAmendment { @@ -778,24 +911,26 @@ mod tests { let tx = AppEventSender::new(tx); let mut view = ApprovalOverlay::new( ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".to_string(), command: vec!["curl".to_string(), "https://example.com".to_string()], reason: None, + available_decisions: vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: NetworkPolicyAmendment { + host: "example.com".to_string(), + action: NetworkPolicyRuleAction::Allow, + }, + }, + ReviewDecision::Abort, + ], network_approval_context: Some(NetworkApprovalContext { host: "example.com".to_string(), protocol: NetworkApprovalProtocol::Https, }), - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: Some(vec![ - NetworkPolicyAmendment { - host: "example.com".to_string(), - action: NetworkPolicyRuleAction::Allow, - }, - NetworkPolicyAmendment { - host: "example.com".to_string(), - action: NetworkPolicyRuleAction::Deny, - }, - ]), additional_permissions: None, }, tx, @@ -815,12 +950,13 @@ mod tests { let tx = AppEventSender::new(tx); let command = vec!["echo".into(), "hello".into(), "world".into()]; let exec_request = ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".into(), command, reason: None, + available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: None, additional_permissions: None, }; @@ -850,17 +986,17 @@ mod tests { protocol: NetworkApprovalProtocol::Https, }; let options = exec_options( - Some(ExecPolicyAmendment::new(vec!["curl".to_string()])), - Some(vec![ - NetworkPolicyAmendment { - host: "example.com".to_string(), - action: NetworkPolicyRuleAction::Allow, + &[ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: NetworkPolicyAmendment { + host: "example.com".to_string(), + action: NetworkPolicyRuleAction::Allow, + }, }, - NetworkPolicyAmendment { - host: "example.com".to_string(), - action: NetworkPolicyRuleAction::Deny, - }, - ]), + ReviewDecision::Abort, + ], Some(&network_context), None, ); @@ -877,16 +1013,43 @@ mod tests { ); } + #[test] + fn generic_exec_options_can_offer_allow_for_session() { + let options = exec_options( + &[ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::Abort, + ], + None, + None, + ); + + let labels: Vec = options.into_iter().map(|option| option.label).collect(); + assert_eq!( + labels, + vec![ + "Yes, proceed".to_string(), + "Yes, and don't ask again for this command in this session".to_string(), + "No, and tell Codex what to do differently".to_string(), + ] + ); + } + #[test] fn additional_permissions_exec_options_hide_execpolicy_amendment() { let additional_permissions = PermissionProfile { file_system: Some(FileSystemPermissions { - read: Some(vec![PathBuf::from("/tmp/readme.txt")]), - write: Some(vec![PathBuf::from("/tmp/out.txt")]), + read: Some(vec![absolute_path("/tmp/readme.txt")]), + write: Some(vec![absolute_path("/tmp/out.txt")]), }), ..Default::default() }; - let options = exec_options(None, None, None, Some(&additional_permissions)); + let options = exec_options( + &[ReviewDecision::Approved, ReviewDecision::Abort], + None, + Some(&additional_permissions), + ); let labels: Vec = options.into_iter().map(|option| option.label).collect(); assert_eq!( @@ -903,16 +1066,17 @@ mod tests { let (tx, _rx) = unbounded_channel::(); let tx = AppEventSender::new(tx); let exec_request = ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".into(), command: vec!["cat".into(), "/tmp/readme.txt".into()], reason: None, + available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: None, additional_permissions: Some(PermissionProfile { file_system: Some(FileSystemPermissions { - read: Some(vec![PathBuf::from("/tmp/readme.txt")]), - write: Some(vec![PathBuf::from("/tmp/out.txt")]), + read: Some(vec![absolute_path("/tmp/readme.txt")]), + write: Some(vec![absolute_path("/tmp/out.txt")]), }), ..Default::default() }), @@ -943,16 +1107,17 @@ mod tests { let (tx, _rx) = unbounded_channel::(); let tx = AppEventSender::new(tx); let exec_request = ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".into(), command: vec!["cat".into(), "/tmp/readme.txt".into()], reason: Some("need filesystem access".into()), + available_decisions: vec![ReviewDecision::Approved, ReviewDecision::Abort], network_approval_context: None, - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: None, additional_permissions: Some(PermissionProfile { file_system: Some(FileSystemPermissions { - read: Some(vec![PathBuf::from("/tmp/readme.txt")]), - write: Some(vec![PathBuf::from("/tmp/out.txt")]), + read: Some(vec![absolute_path("/tmp/readme.txt")]), + write: Some(vec![absolute_path("/tmp/out.txt")]), }), ..Default::default() }), @@ -961,7 +1126,7 @@ mod tests { let view = ApprovalOverlay::new(exec_request, tx, Features::with_defaults()); assert_snapshot!( "approval_overlay_additional_permissions_prompt", - render_overlay_lines(&view, 120) + normalize_snapshot_paths(render_overlay_lines(&view, 120)) ); } @@ -970,24 +1135,26 @@ mod tests { let (tx, _rx) = unbounded_channel::(); let tx = AppEventSender::new(tx); let exec_request = ApprovalRequest::Exec { + thread_id: ThreadId::new(), + thread_label: None, id: "test".into(), command: vec!["curl".into(), "https://example.com".into()], reason: Some("network request blocked".into()), + available_decisions: vec![ + ReviewDecision::Approved, + ReviewDecision::ApprovedForSession, + ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: NetworkPolicyAmendment { + host: "example.com".to_string(), + action: NetworkPolicyRuleAction::Allow, + }, + }, + ReviewDecision::Abort, + ], network_approval_context: Some(NetworkApprovalContext { host: "example.com".to_string(), protocol: NetworkApprovalProtocol::Https, }), - proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec!["curl".into()])), - proposed_network_policy_amendments: Some(vec![ - NetworkPolicyAmendment { - host: "example.com".to_string(), - action: NetworkPolicyRuleAction::Allow, - }, - NetworkPolicyAmendment { - host: "example.com".to_string(), - action: NetworkPolicyRuleAction::Deny, - }, - ]), additional_permissions: None, }; @@ -1061,7 +1228,11 @@ mod tests { let mut decision = None; while let Ok(ev) = rx.try_recv() { - if let AppEvent::CodexOp(Op::ExecApproval { decision: d, .. }) = ev { + if let AppEvent::SubmitThreadOp { + op: Op::ExecApproval { decision: d, .. }, + .. + } = ev + { decision = Some(d); break; } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 7892119966..c084650660 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -31,8 +31,8 @@ //! //! # Submission and Prompt Expansion //! -//! When steer is enabled, `Enter` submits immediately. `Tab` requests queuing while a task is -//! running; if no task is running, `Tab` submits just like Enter so input is never dropped. +//! `Enter` submits immediately. `Tab` requests queuing while a task is running; if no task is +//! running, `Tab` submits just like Enter so input is never dropped. //! `Tab` does not submit when entering a `!` shell command. //! //! On submit/queue paths, the composer: @@ -43,6 +43,11 @@ //! - Prunes local attached images so only placeholders that survive expansion are sent. //! - Preserves remote image URLs as separate attachments even when text is empty. //! +//! When these paths clear the visible textarea after a successful submit or slash-command +//! dispatch, they intentionally preserve the textarea kill buffer. That lets users `Ctrl+K` part +//! of a draft, perform a composer action such as changing reasoning level, and then `Ctrl+Y` the +//! killed text back into the now-empty draft. +//! //! The numeric auto-submit path used by the slash popup performs the same pending-paste expansion //! and attachment pruning, and clears pending paste state on success. //! Slash commands with arguments (like `/plan` and `/review`) reuse the same preparation path so @@ -173,6 +178,7 @@ use super::paste_burst::PasteBurst; use super::skill_popup::MentionItem; use super::skill_popup::SkillPopup; use super::slash_commands; +use super::slash_commands::BuiltinCommandFlags; use crate::bottom_pane::paste_burst::FlushResult; use crate::bottom_pane::prompt_args::expand_custom_prompt; use crate::bottom_pane::prompt_args::expand_if_numeric_with_positional_args; @@ -189,6 +195,7 @@ use codex_protocol::custom_prompts::CustomPrompt; use codex_protocol::custom_prompts::PROMPTS_CMD_PREFIX; use codex_protocol::models::local_image_label_text; use codex_protocol::user_input::ByteRange; +use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use codex_protocol::user_input::TextElement; use codex_utils_fuzzy_match::fuzzy_match; @@ -229,6 +236,12 @@ use tokio::runtime::Handle; /// placeholder in the UI. const LARGE_PASTE_CHAR_THRESHOLD: usize = 1000; +fn user_input_too_large_message(actual_chars: usize) -> String { + format!( + "Message exceeds the maximum length of {MAX_USER_INPUT_TEXT_CHARS} characters ({actual_chars} provided)." + ) +} + /// Result returned when the user interacts with the text area. #[derive(Debug, PartialEq)] pub enum InputResult { @@ -382,14 +395,14 @@ pub(crate) struct ChatComposer { dismissed_mention_popup_token: Option, mention_bindings: HashMap, recent_submission_mention_bindings: Vec, - /// When enabled, `Enter` submits immediately and `Tab` requests queuing behavior. - steer_enabled: bool, collaboration_modes_enabled: bool, config: ChatComposerConfig, collaboration_mode_indicator: Option, connectors_enabled: bool, + fast_command_enabled: bool, personality_command_enabled: bool, realtime_conversation_enabled: bool, + audio_device_selection_enabled: bool, windows_degraded_sandbox_active: bool, status_line_value: Option>, status_line_enabled: bool, @@ -418,6 +431,18 @@ enum ActivePopup { const FOOTER_SPACING_HEIGHT: u16 = 0; impl ChatComposer { + fn builtin_command_flags(&self) -> BuiltinCommandFlags { + BuiltinCommandFlags { + collaboration_modes_enabled: self.collaboration_modes_enabled, + connectors_enabled: self.connectors_enabled, + fast_command_enabled: self.fast_command_enabled, + personality_command_enabled: self.personality_command_enabled, + realtime_conversation_enabled: self.realtime_conversation_enabled, + audio_device_selection_enabled: self.audio_device_selection_enabled, + allow_elevate_sandbox: self.windows_degraded_sandbox_active, + } + } + pub fn new( has_input_focus: bool, app_event_tx: AppEventSender, @@ -489,13 +514,14 @@ impl ChatComposer { dismissed_mention_popup_token: None, mention_bindings: HashMap::new(), recent_submission_mention_bindings: Vec::new(), - steer_enabled: false, collaboration_modes_enabled: false, config, collaboration_mode_indicator: None, connectors_enabled: false, + fast_command_enabled: false, personality_command_enabled: false, realtime_conversation_enabled: false, + audio_device_selection_enabled: false, windows_degraded_sandbox_active: false, status_line_value: None, status_line_enabled: false, @@ -550,17 +576,6 @@ impl ChatComposer { ordered } - /// Enables or disables "Steer" behavior for submission keys. - /// - /// When steer is enabled, `Enter` produces [`InputResult::Submitted`] (send immediately) and - /// `Tab` produces [`InputResult::Queued`] when a task is running; otherwise it submits - /// immediately. `Tab` does not submit when the input is a `!` shell command. - /// When steer is disabled, `Enter` produces [`InputResult::Queued`], preserving the default - /// "queue while a task is running" behavior. - pub fn set_steer_enabled(&mut self, enabled: bool) { - self.steer_enabled = enabled; - } - pub fn set_collaboration_modes_enabled(&mut self, enabled: bool) { self.collaboration_modes_enabled = enabled; } @@ -569,6 +584,10 @@ impl ChatComposer { self.connectors_enabled = enabled; } + pub fn set_fast_command_enabled(&mut self, enabled: bool) { + self.fast_command_enabled = enabled; + } + pub fn set_collaboration_mode_indicator( &mut self, indicator: Option, @@ -584,6 +603,13 @@ impl ChatComposer { self.realtime_conversation_enabled = enabled; } + pub fn set_audio_device_selection_enabled(&mut self, enabled: bool) { + self.audio_device_selection_enabled = enabled; + } + + /// Compatibility shim for tests that still toggle the removed steer mode flag. + #[cfg(test)] + pub fn set_steer_enabled(&mut self, _enabled: bool) {} pub fn set_voice_transcription_enabled(&mut self, enabled: bool) { self.voice_state.transcription_enabled = enabled; if !enabled { @@ -2083,16 +2109,10 @@ impl ChatComposer { path.to_string() }; - // Replace the slice `[start_idx, end_idx)` with the chosen path and a trailing space. - let mut new_text = - String::with_capacity(text.len() - (end_idx - start_idx) + inserted.len() + 1); - new_text.push_str(&text[..start_idx]); - new_text.push_str(&inserted); - new_text.push(' '); - new_text.push_str(&text[end_idx..]); - - // Path replacement is plain text; rebuild without carrying elements. - self.textarea.set_text_clearing_elements(&new_text); + // Replace just the active `@token` so unrelated text elements, such as + // large-paste placeholders, remain atomic and can still expand on submit. + self.textarea + .replace_range(start_idx..end_idx, &format!("{inserted} ")); let new_cursor = start_idx.saturating_add(inserted.len()).saturating_add(1); self.textarea.set_cursor(new_cursor); } @@ -2261,15 +2281,9 @@ impl ChatComposer { { let treat_as_plain_text = input_starts_with_space || name.contains('/'); if !treat_as_plain_text { - let is_builtin = slash_commands::find_builtin_command( - name, - self.collaboration_modes_enabled, - self.connectors_enabled, - self.personality_command_enabled, - self.realtime_conversation_enabled, - self.windows_degraded_sandbox_active, - ) - .is_some(); + let is_builtin = + slash_commands::find_builtin_command(name, self.builtin_command_flags()) + .is_some(); let prompt_prefix = format!("{PROMPTS_CMD_PREFIX}:"); let is_known_prompt = name .strip_prefix(&prompt_prefix) @@ -2323,6 +2337,22 @@ impl ChatComposer { text_elements = expanded.text_elements; } } + let actual_chars = text.chars().count(); + if actual_chars > MAX_USER_INPUT_TEXT_CHARS { + let message = user_input_too_large_message(actual_chars); + self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::new_error_event(message), + ))); + self.set_text_content_with_mention_bindings( + original_input.clone(), + original_text_elements, + original_local_image_paths, + original_mention_bindings, + ); + self.pending_pastes.clone_from(&original_pending_pastes); + self.textarea.set_cursor(original_input.len()); + return None; + } // Custom prompt expansion can remove or rewrite image placeholders, so prune any // attachments that no longer have a corresponding placeholder in the expanded text. self.prune_attached_images_for_submission(&text, &text_elements); @@ -2461,14 +2491,8 @@ impl ChatComposer { let first_line = self.textarea.text().lines().next().unwrap_or(""); if let Some((name, rest, _rest_offset)) = parse_slash_name(first_line) && rest.is_empty() - && let Some(cmd) = slash_commands::find_builtin_command( - name, - self.collaboration_modes_enabled, - self.connectors_enabled, - self.personality_command_enabled, - self.realtime_conversation_enabled, - self.windows_degraded_sandbox_active, - ) + && let Some(cmd) = + slash_commands::find_builtin_command(name, self.builtin_command_flags()) { if self.reject_slash_command_if_unavailable(cmd) { return Some(InputResult::None); @@ -2496,14 +2520,7 @@ impl ChatComposer { return None; } - let cmd = slash_commands::find_builtin_command( - name, - self.collaboration_modes_enabled, - self.connectors_enabled, - self.personality_command_enabled, - self.realtime_conversation_enabled, - self.windows_degraded_sandbox_active, - )?; + let cmd = slash_commands::find_builtin_command(name, self.builtin_command_flags())?; if !cmd.supports_inline_args() { return None; @@ -2735,25 +2752,12 @@ impl ChatComposer { modifiers: KeyModifiers::NONE, kind: KeyEventKind::Press, .. - } if self.steer_enabled && !self.is_bang_shell_command() => { - self.handle_submission(self.is_task_running) - } - KeyEvent { - code: KeyCode::Tab, - modifiers: KeyModifiers::NONE, - kind: KeyEventKind::Press, - .. - } if self.is_task_running && !self.is_bang_shell_command() => { - self.handle_submission(true) - } + } if !self.is_bang_shell_command() => self.handle_submission(self.is_task_running), KeyEvent { code: KeyCode::Enter, modifiers: KeyModifiers::NONE, .. - } => { - let should_queue = !self.steer_enabled; - self.handle_submission(should_queue) - } + } => self.handle_submission(false), input => self.handle_input_basic(input), } } @@ -3153,7 +3157,6 @@ impl ChatComposer { use_shift_enter_hint: self.use_shift_enter_hint, is_task_running: self.is_task_running, quit_shortcut_key: self.quit_shortcut_key, - steer_enabled: self.steer_enabled, collaboration_modes_enabled: self.collaboration_modes_enabled, is_wsl, context_window_percent: self.context_window_percent, @@ -3329,15 +3332,8 @@ impl ChatComposer { } fn is_known_slash_name(&self, name: &str) -> bool { - let is_builtin = slash_commands::find_builtin_command( - name, - self.collaboration_modes_enabled, - self.connectors_enabled, - self.personality_command_enabled, - self.realtime_conversation_enabled, - self.windows_degraded_sandbox_active, - ) - .is_some(); + let is_builtin = + slash_commands::find_builtin_command(name, self.builtin_command_flags()).is_some(); if is_builtin { return true; } @@ -3391,14 +3387,7 @@ impl ChatComposer { return rest_after_name.is_empty(); } - if slash_commands::has_builtin_prefix( - name, - self.collaboration_modes_enabled, - self.connectors_enabled, - self.personality_command_enabled, - self.realtime_conversation_enabled, - self.windows_degraded_sandbox_active, - ) { + if slash_commands::has_builtin_prefix(name, self.builtin_command_flags()) { return true; } @@ -3449,15 +3438,19 @@ impl ChatComposer { if is_editing_slash_command_name { let collaboration_modes_enabled = self.collaboration_modes_enabled; let connectors_enabled = self.connectors_enabled; + let fast_command_enabled = self.fast_command_enabled; let personality_command_enabled = self.personality_command_enabled; let realtime_conversation_enabled = self.realtime_conversation_enabled; + let audio_device_selection_enabled = self.audio_device_selection_enabled; let mut command_popup = CommandPopup::new( self.custom_prompts.clone(), CommandPopupFlags { collaboration_modes_enabled, connectors_enabled, + fast_command_enabled, personality_command_enabled, realtime_conversation_enabled, + audio_device_selection_enabled, windows_degraded_sandbox_active: self.windows_degraded_sandbox_active, }, ); @@ -4103,15 +4096,13 @@ impl ChatComposer { !footer_props.is_task_running && self.collaboration_mode_indicator.is_some(); let show_shortcuts_hint = match footer_props.mode { FooterMode::ComposerEmpty => !self.is_in_paste_burst(), + FooterMode::ComposerHasDraft => false, FooterMode::QuitShortcutReminder | FooterMode::ShortcutOverlay - | FooterMode::EscHint - | FooterMode::ComposerHasDraft => false, + | FooterMode::EscHint => false, }; let show_queue_hint = match footer_props.mode { - FooterMode::ComposerHasDraft => { - footer_props.is_task_running && footer_props.steer_enabled - } + FooterMode::ComposerHasDraft => footer_props.is_task_running, FooterMode::QuitShortcutReminder | FooterMode::ComposerEmpty | FooterMode::ShortcutOverlay @@ -4138,10 +4129,13 @@ impl ChatComposer { .as_ref() .map(|line| line.clone().dim()); let status_line_candidate = footer_props.status_line_enabled - && matches!( - footer_props.mode, - FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft - ); + && match footer_props.mode { + FooterMode::ComposerEmpty => true, + FooterMode::ComposerHasDraft => !footer_props.is_task_running, + FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + | FooterMode::EscHint => false, + }; let mut truncated_status_line = if status_line_candidate { status_line.as_ref().map(|line| { truncate_line_with_ellipsis_if_overflow(line.clone(), available_width) @@ -4207,7 +4201,7 @@ impl ChatComposer { can_show_left_with_context(hint_rect, left_width, right_width); let has_override = self.footer_flash_visible() || self.footer_hint_override.is_some(); - let single_line_layout = if has_override { + let single_line_layout = if has_override || status_line_active { None } else { match footer_props.mode { @@ -4735,10 +4729,9 @@ mod tests { }, ); - // Textarea has content, agent running, steer enabled: queue hint is shown. + // Textarea has content, agent running: queue hint is shown. snapshot_composer_state_with_width("footer_collapse_queue_full", 120, true, |composer| { setup_collab_footer(composer, 98, None); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }); @@ -4748,7 +4741,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, None); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4759,7 +4751,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, None); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4770,7 +4761,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, None); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4781,20 +4771,18 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, None); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, ); - // Textarea has content, plan mode active, agent running, steer enabled: queue hint + mode. + // Textarea has content, plan mode active, agent running: queue hint + mode. snapshot_composer_state_with_width( "footer_collapse_plan_queue_full", 120, true, |composer| { setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4805,7 +4793,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4816,7 +4803,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4827,7 +4813,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4838,7 +4823,6 @@ mod tests { true, |composer| { setup_collab_footer(composer, 98, Some(CollaborationModeIndicator::Plan)); - composer.set_steer_enabled(true); composer.set_task_running(true); composer.set_text_content("Test".to_string(), Vec::new(), Vec::new()); }, @@ -4910,11 +4894,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); composer.set_text_content("draft text".to_string(), Vec::new(), Vec::new()); assert_eq!(composer.clear_for_ctrl_c(), Some("draft text".to_string())); @@ -4978,7 +4957,6 @@ mod tests { assert_eq!(composer.pending_pastes, vec![(placeholder.clone(), large)]); assert_eq!(composer.textarea.element_payloads(), vec![placeholder]); - composer.set_steer_enabled(true); let (result, _needs_redraw) = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); match result { @@ -5132,13 +5110,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); let (result, needs_redraw) = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); @@ -5181,10 +5152,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); // Force an active paste burst so this test doesn't depend on tight timing. composer @@ -5292,10 +5259,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); assert_eq!(composer.footer_mode, FooterMode::ShortcutOverlay); @@ -5546,7 +5509,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let input = "npx -y @kaeawc/auto-mobile@latest"; composer.textarea.insert_str(input); @@ -5582,10 +5544,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); assert!(composer.is_in_paste_burst()); @@ -5617,10 +5575,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('あ'), KeyModifiers::NONE)); @@ -5763,9 +5717,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); let mut now = Instant::now(); let step = Duration::from_millis(1); @@ -5781,7 +5732,7 @@ mod tests { ); now += step; - let (result, _) = composer.handle_submission_with_time(!composer.steer_enabled, now); + let (result, _) = composer.handle_submission_with_time(false, now); assert!( matches!(result, InputResult::None), "Enter during a burst should insert newline, not submit" @@ -5917,9 +5868,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); let needs_redraw = composer.handle_paste("hello".to_string()); assert!(needs_redraw); @@ -5949,9 +5897,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); - composer.set_steer_enabled(true); // Ensure composer is empty and press Enter. assert!(composer.textarea.text().is_empty()); @@ -5981,7 +5926,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let large = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 10); let needs_redraw = composer.handle_paste(large.clone()); @@ -6001,6 +5945,118 @@ mod tests { assert!(composer.pending_pastes.is_empty()); } + #[test] + fn submit_at_character_limit_succeeds() { + 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( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_steer_enabled(true); + let input = "x".repeat(MAX_USER_INPUT_TEXT_CHARS); + composer.textarea.set_text_clearing_elements(&input); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert!(matches!( + result, + InputResult::Submitted { text, .. } if text == input + )); + } + + #[test] + fn oversized_submit_reports_error_and_restores_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + let (tx, mut rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_steer_enabled(true); + let input = "x".repeat(MAX_USER_INPUT_TEXT_CHARS + 1); + composer.textarea.set_text_clearing_elements(&input); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_eq!(InputResult::None, result); + assert_eq!(composer.textarea.text(), input); + + let mut found_error = false; + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + let message = cell + .display_lines(80) + .into_iter() + .map(|line| line.to_string()) + .collect::>() + .join("\n"); + assert!(message.contains(&user_input_too_large_message(input.chars().count()))); + found_error = true; + break; + } + } + assert!(found_error, "expected oversized-input error history cell"); + } + + #[test] + fn oversized_queued_submission_reports_error_and_restores_draft() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + let (tx, mut rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_steer_enabled(false); + let input = "x".repeat(MAX_USER_INPUT_TEXT_CHARS + 1); + composer.textarea.set_text_clearing_elements(&input); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_eq!(InputResult::None, result); + assert_eq!(composer.textarea.text(), input); + + let mut found_error = false; + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + let message = cell + .display_lines(80) + .into_iter() + .map(|line| line.to_string()) + .collect::>() + .join("\n"); + assert!(message.contains(&user_input_too_large_message(input.chars().count()))); + found_error = true; + break; + } + } + assert!(found_error, "expected oversized-input error history cell"); + } + /// Behavior: editing that removes a paste placeholder should also clear the associated /// `pending_pastes` entry so it cannot be submitted accidentally. #[test] @@ -6019,7 +6075,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.handle_paste(large); assert_eq!(composer.pending_pastes.len(), 1); @@ -6153,7 +6208,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); // Type "/mo" humanlike so paste-burst doesn’t interfere. type_chars_humanlike(&mut composer, &['/', 'm', 'o']); @@ -6182,7 +6236,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); type_chars_humanlike(&mut composer, &['/', 'm', 'o']); match &composer.active_popup { @@ -6214,7 +6267,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); // Type "/res" humanlike so paste-burst doesn’t interfere. type_chars_humanlike(&mut composer, &['/', 'r', 'e', 's']); @@ -6324,6 +6376,78 @@ mod tests { assert!(composer.textarea.is_empty(), "composer should be cleared"); } + #[test] + fn kill_buffer_persists_after_submit() { + 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( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_steer_enabled(true); + composer.textarea.insert_str("restore me"); + composer.textarea.set_cursor(0); + + let (_result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL)); + assert!(composer.textarea.is_empty()); + + composer.textarea.insert_str("hello"); + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!(result, InputResult::Submitted { .. })); + assert!(composer.textarea.is_empty()); + + let (_result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)); + assert_eq!(composer.textarea.text(), "restore me"); + } + + #[test] + fn kill_buffer_persists_after_slash_command_dispatch() { + 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( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.textarea.insert_str("restore me"); + composer.textarea.set_cursor(0); + + let (_result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL)); + assert!(composer.textarea.is_empty()); + + composer.textarea.insert_str("/diff"); + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + match result { + InputResult::Command(cmd) => { + assert_eq!(cmd.command(), "diff"); + } + _ => panic!("expected Command result for '/diff'"), + } + assert!(composer.textarea.is_empty()); + + let (_result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)); + assert_eq!(composer.textarea.text(), "restore me"); + } + #[test] fn slash_command_disabled_while_task_running_keeps_text() { use crossterm::event::KeyCode; @@ -6729,7 +6853,7 @@ mod tests { } #[test] - fn tab_submits_when_no_task_running_in_steer_mode() { + fn tab_submits_when_no_task_running() { use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; @@ -6743,7 +6867,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); type_chars_humanlike(&mut composer, &['h', 'i']); @@ -6758,7 +6881,7 @@ mod tests { } #[test] - fn tab_does_not_submit_for_bang_shell_command_in_steer_mode() { + fn tab_does_not_submit_for_bang_shell_command() { use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; @@ -6772,7 +6895,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_task_running(false); type_chars_humanlike(&mut composer, &['!', 'l', 's']); @@ -6866,6 +6988,61 @@ mod tests { } } + #[test] + fn file_completion_preserves_large_paste_placeholder_elements() { + 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( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + + let large = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 5); + let placeholder = format!("[Pasted Content {} chars]", large.chars().count()); + + composer.handle_paste(large.clone()); + composer.insert_str(" @ma"); + composer.on_file_search_result( + "ma".to_string(), + vec![FileMatch { + score: 1, + path: PathBuf::from("src/main.rs"), + root: PathBuf::from("/tmp"), + indices: None, + }], + ); + + let (_result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); + + let text = composer.textarea.text().to_string(); + assert_eq!(text, format!("{placeholder} src/main.rs ")); + let elements = composer.textarea.text_elements(); + assert_eq!(elements.len(), 1); + assert_eq!(elements[0].placeholder(&text), Some(placeholder.as_str())); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + match result { + InputResult::Submitted { + text, + text_elements, + } => { + assert_eq!(text, format!("{large} src/main.rs")); + assert!(text_elements.is_empty()); + } + _ => panic!("expected Submitted"), + } + } + /// Behavior: multiple paste operations can coexist; placeholders should be expanded to their /// original content on submission. #[test] @@ -6883,7 +7060,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); // Define test cases: (paste content, is_large) let test_cases = [ @@ -7164,7 +7340,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let path = PathBuf::from("/tmp/image1.png"); composer.attach_image(path.clone()); composer.handle_paste(" hi".into()); @@ -7203,7 +7378,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let mention_bindings = vec![MentionBinding { mention: "figma".to_string(), @@ -7237,7 +7411,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let remote_image_url = "https://example.com/remote.png".to_string(); composer.set_remote_image_urls(vec![remote_image_url.clone()]); let path = PathBuf::from("/tmp/image1.png"); @@ -7304,7 +7477,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); type_chars_humanlike(&mut composer, &['f', 'i', 'r', 's', 't']); let (result, _needs_redraw) = @@ -7370,7 +7542,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let large_content = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 5); composer.handle_paste(large_content.clone()); @@ -7414,7 +7585,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let large_content = format!(" {}", "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 5)); composer.handle_paste(large_content.clone()); @@ -7458,7 +7628,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let pasted = "line1\r\nline2\r\n".to_string(); composer.handle_paste(pasted); @@ -7502,7 +7671,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.textarea.set_text_clearing_elements("/unknown "); composer.textarea.set_cursor("/unknown ".len()); @@ -7549,7 +7717,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); let path = PathBuf::from("/tmp/image2.png"); composer.attach_image(path.clone()); let (result, _) = @@ -7861,7 +8028,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); // Inject prompts as if received via event. composer.set_custom_prompts(vec![CustomPrompt { @@ -7901,7 +8067,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -7937,7 +8102,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -7977,7 +8141,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8033,7 +8196,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8090,7 +8252,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8139,7 +8300,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); // Create a custom prompt with positional args (no named args like $USER) composer.set_custom_prompts(vec![CustomPrompt { @@ -8204,7 +8364,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8263,7 +8422,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer .textarea @@ -8300,7 +8458,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer .textarea @@ -8438,7 +8595,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8477,7 +8633,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8516,7 +8671,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8560,7 +8714,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8601,7 +8754,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(false); composer.set_custom_prompts(vec![CustomPrompt { name: "my-prompt".to_string(), @@ -8616,9 +8768,10 @@ mod tests { .set_text_clearing_elements("/prompts:my-prompt foo "); composer.textarea.set_cursor(composer.textarea.text().len()); composer.attach_image(PathBuf::from("/tmp/unused.png")); + composer.set_task_running(true); let (result, _needs_redraw) = - composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); assert!(matches!( result, @@ -8631,6 +8784,57 @@ mod tests { ); } + #[test] + fn prompt_expansion_over_character_limit_reports_error_and_restores_draft() { + let (tx, mut rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_steer_enabled(true); + + composer.set_custom_prompts(vec![CustomPrompt { + name: "my-prompt".to_string(), + path: "/tmp/my-prompt.md".to_string().into(), + content: "Echo: $1".to_string(), + description: None, + argument_hint: None, + }]); + + let oversized_arg = "x".repeat(MAX_USER_INPUT_TEXT_CHARS); + let original_input = format!("/prompts:my-prompt {oversized_arg}"); + composer + .textarea + .set_text_clearing_elements(&original_input); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_eq!(InputResult::None, result); + assert_eq!(composer.textarea.text(), original_input); + + let actual_chars = format!("Echo: {oversized_arg}").chars().count(); + let mut found_error = false; + while let Ok(event) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = event { + let message = cell + .display_lines(80) + .into_iter() + .map(|line| line.to_string()) + .collect::>() + .join("\n"); + assert!(message.contains(&user_input_too_large_message(actual_chars))); + found_error = true; + break; + } + } + assert!(found_error, "expected oversized-input error history cell"); + } + #[test] fn selecting_custom_prompt_with_positional_args_submits_numeric_expansion() { let prompt_text = "Header: $1\nArgs: $ARGUMENTS\n"; @@ -8674,7 +8878,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "elegant".to_string(), @@ -8747,7 +8950,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "price".to_string(), @@ -8786,7 +8988,6 @@ mod tests { "Ask Codex to do anything".to_string(), false, ); - composer.set_steer_enabled(true); composer.set_custom_prompts(vec![CustomPrompt { name: "repeat".to_string(), diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 83b523cc23..1f774f2c74 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -38,24 +38,35 @@ pub(crate) struct CommandPopup { pub(crate) struct CommandPopupFlags { pub(crate) collaboration_modes_enabled: bool, pub(crate) connectors_enabled: bool, + pub(crate) fast_command_enabled: bool, pub(crate) personality_command_enabled: bool, pub(crate) realtime_conversation_enabled: bool, + pub(crate) audio_device_selection_enabled: bool, pub(crate) windows_degraded_sandbox_active: bool, } +impl From for slash_commands::BuiltinCommandFlags { + fn from(value: CommandPopupFlags) -> Self { + Self { + collaboration_modes_enabled: value.collaboration_modes_enabled, + connectors_enabled: value.connectors_enabled, + fast_command_enabled: value.fast_command_enabled, + personality_command_enabled: value.personality_command_enabled, + realtime_conversation_enabled: value.realtime_conversation_enabled, + audio_device_selection_enabled: value.audio_device_selection_enabled, + allow_elevate_sandbox: value.windows_degraded_sandbox_active, + } + } +} + impl CommandPopup { pub(crate) fn new(mut prompts: Vec, flags: CommandPopupFlags) -> Self { // Keep built-in availability in sync with the composer. - let builtins: Vec<(&'static str, SlashCommand)> = slash_commands::builtins_for_input( - flags.collaboration_modes_enabled, - flags.connectors_enabled, - flags.personality_command_enabled, - flags.realtime_conversation_enabled, - flags.windows_degraded_sandbox_active, - ) - .into_iter() - .filter(|(name, _)| !name.starts_with("debug")) - .collect(); + let builtins: Vec<(&'static str, SlashCommand)> = + slash_commands::builtins_for_input(flags.into()) + .into_iter() + .filter(|(name, _)| !name.starts_with("debug")) + .collect(); // Exclude prompts that collide with builtin command names and sort by name. let exclude: HashSet = builtins.iter().map(|(n, _)| (*n).to_string()).collect(); prompts.retain(|p| !exclude.contains(&p.name)); @@ -340,7 +351,7 @@ mod tests { CommandItem::UserPrompt(_) => None, }) .collect(); - assert_eq!(cmds, vec!["model", "mention", "mcp"]); + assert_eq!(cmds, vec!["model", "mention", "mcp", "multi-agents"]); } #[test] @@ -496,8 +507,10 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, connectors_enabled: false, + fast_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: false, + audio_device_selection_enabled: false, windows_degraded_sandbox_active: false, }, ); @@ -516,8 +529,10 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, connectors_enabled: false, + fast_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: false, + audio_device_selection_enabled: false, windows_degraded_sandbox_active: false, }, ); @@ -536,8 +551,10 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, connectors_enabled: false, + fast_command_enabled: false, personality_command_enabled: false, realtime_conversation_enabled: false, + audio_device_selection_enabled: false, windows_degraded_sandbox_active: false, }, ); @@ -564,8 +581,10 @@ mod tests { CommandPopupFlags { collaboration_modes_enabled: true, connectors_enabled: false, + fast_command_enabled: false, personality_command_enabled: true, realtime_conversation_enabled: false, + audio_device_selection_enabled: false, windows_degraded_sandbox_active: false, }, ); @@ -577,6 +596,37 @@ mod tests { } } + #[test] + fn settings_command_hidden_when_audio_device_selection_is_disabled() { + let mut popup = CommandPopup::new( + Vec::new(), + CommandPopupFlags { + collaboration_modes_enabled: false, + connectors_enabled: false, + fast_command_enabled: false, + personality_command_enabled: true, + realtime_conversation_enabled: true, + audio_device_selection_enabled: false, + windows_degraded_sandbox_active: false, + }, + ); + popup.on_composer_text_change("/aud".to_string()); + + let cmds: Vec<&str> = popup + .filtered_items() + .into_iter() + .filter_map(|item| match item { + CommandItem::Builtin(cmd) => Some(cmd.command()), + CommandItem::UserPrompt(_) => None, + }) + .collect(); + + assert!( + !cmds.contains(&"settings"), + "expected '/settings' to be hidden when audio device selection is disabled, got {cmds:?}" + ); + } + #[test] fn debug_commands_are_hidden_from_popup() { let popup = CommandPopup::new(Vec::new(), CommandPopupFlags::default()); diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 03d3779c57..33368faa45 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -27,8 +27,8 @@ use super::popup_consts::standard_popup_hint_line; use super::textarea::TextArea; use super::textarea::TextAreaState; -const BASE_BUG_ISSUE_URL: &str = - "https://github.com/openai/codex/issues/new?template=2-bug-report.yml"; +const BASE_CLI_BUG_ISSUE_URL: &str = + "https://github.com/openai/codex/issues/new?template=3-cli.yml"; /// Internal routing link for employee feedback follow-ups. This must not be shown to external users. const CODEX_FEEDBACK_INTERNAL_URL: &str = "http://go/codex-feedback-internal"; @@ -102,6 +102,7 @@ impl FeedbackNoteView { self.include_logs, &log_file_paths, Some(SessionSource::Cli), + None, ); match result { @@ -389,7 +390,7 @@ fn issue_url_for_category( | FeedbackCategory::Other => Some(match feedback_audience { FeedbackAudience::OpenAiEmployee => slack_feedback_url(thread_id), FeedbackAudience::External => { - format!("{BASE_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}") + format!("{BASE_CLI_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}") } }), FeedbackCategory::GoodResult => None, @@ -675,10 +676,7 @@ mod tests { ); let bug_url_non_employee = issue_url_for_category(FeedbackCategory::Bug, "t", FeedbackAudience::External); - let expected_external_url = format!("{BASE_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20t"); - assert_eq!( - bug_url_non_employee.as_deref(), - Some(expected_external_url.as_str()) - ); + let expected_external_url = "https://github.com/openai/codex/issues/new?template=3-cli.yml&steps=Uploaded%20thread:%20t"; + assert_eq!(bug_url_non_employee.as_deref(), Some(expected_external_url)); } } diff --git a/codex-rs/tui/src/bottom_pane/footer.rs b/codex-rs/tui/src/bottom_pane/footer.rs index 28005a172a..2ad23272ea 100644 --- a/codex-rs/tui/src/bottom_pane/footer.rs +++ b/codex-rs/tui/src/bottom_pane/footer.rs @@ -59,7 +59,6 @@ pub(crate) struct FooterProps { pub(crate) esc_backtrack_hint: bool, pub(crate) use_shift_enter_hint: bool, pub(crate) is_task_running: bool, - pub(crate) steer_enabled: bool, pub(crate) collaboration_modes_enabled: bool, pub(crate) is_wsl: bool, /// Which key the user must press again to quit. @@ -126,8 +125,8 @@ pub(crate) enum FooterMode { ComposerEmpty, /// Base single-line footer when the composer contains a draft. /// - /// The shortcuts hint is suppressed here; when a task is running with - /// steer enabled, this mode can show the queue hint instead. + /// The shortcuts hint is suppressed here; when a task is running, this + /// mode can show the queue hint instead. ComposerHasDraft, } @@ -173,13 +172,13 @@ pub(crate) fn reset_mode_after_activity(current: FooterMode) -> FooterMode { pub(crate) fn footer_height(props: &FooterProps) -> u16 { let show_shortcuts_hint = match props.mode { FooterMode::ComposerEmpty => true, - FooterMode::QuitShortcutReminder - | FooterMode::ShortcutOverlay - | FooterMode::EscHint - | FooterMode::ComposerHasDraft => false, + FooterMode::ComposerHasDraft => false, + FooterMode::QuitShortcutReminder | FooterMode::ShortcutOverlay | FooterMode::EscHint => { + false + } }; let show_queue_hint = match props.mode { - FooterMode::ComposerHasDraft => props.is_task_running && props.steer_enabled, + FooterMode::ComposerHasDraft => props.is_task_running, FooterMode::QuitShortcutReminder | FooterMode::ComposerEmpty | FooterMode::ShortcutOverlay @@ -563,13 +562,18 @@ fn footer_from_props_lines( show_shortcuts_hint: bool, show_queue_hint: bool, ) -> Vec> { - // If status line content is present, show it for base modes. + // If status line content is present, show it for passive composer states. + // Active draft states still prefer the queue hint over the passive status + // line so the footer stays actionable while a task is running. if props.status_line_enabled && let Some(status_line) = &props.status_line_value - && matches!( - props.mode, - FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft - ) + && match props.mode { + FooterMode::ComposerEmpty => true, + FooterMode::ComposerHasDraft => !props.is_task_running, + FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + | FooterMode::EscHint => false, + } { return vec![status_line.clone().dim()]; } @@ -602,6 +606,8 @@ fn footer_from_props_lines( let state = LeftSideState { hint: if show_queue_hint { SummaryHintKind::QueueMessage + } else if show_shortcuts_hint { + SummaryHintKind::Shortcuts } else { SummaryHintKind::None }, @@ -1014,25 +1020,33 @@ mod tests { let show_cycle_hint = !props.is_task_running; let show_shortcuts_hint = match props.mode { FooterMode::ComposerEmpty => true, + FooterMode::ComposerHasDraft => false, FooterMode::QuitShortcutReminder | FooterMode::ShortcutOverlay - | FooterMode::EscHint - | FooterMode::ComposerHasDraft => false, + | FooterMode::EscHint => false, }; let show_queue_hint = match props.mode { - FooterMode::ComposerHasDraft => props.is_task_running && props.steer_enabled, + FooterMode::ComposerHasDraft => props.is_task_running, FooterMode::QuitShortcutReminder | FooterMode::ComposerEmpty | FooterMode::ShortcutOverlay | FooterMode::EscHint => false, }; - let left_mode_indicator = if props.status_line_enabled { + let status_line_active = props.status_line_enabled + && match props.mode { + FooterMode::ComposerEmpty => true, + FooterMode::ComposerHasDraft => !props.is_task_running, + FooterMode::QuitShortcutReminder + | FooterMode::ShortcutOverlay + | FooterMode::EscHint => false, + }; + let left_mode_indicator = if status_line_active { None } else { collaboration_mode_indicator }; let available_width = area.width.saturating_sub(FOOTER_INDENT_COLS as u16) as usize; - let mut truncated_status_line = if props.status_line_enabled + let mut truncated_status_line = if status_line_active && matches!( props.mode, FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft @@ -1045,7 +1059,7 @@ mod tests { } else { None }; - let mut left_width = if props.status_line_enabled { + let mut left_width = if status_line_active { truncated_status_line .as_ref() .map(|line| line.width() as u16) @@ -1059,7 +1073,7 @@ mod tests { show_queue_hint, ) }; - let right_line = if props.status_line_enabled { + let right_line = if status_line_active { let full = mode_indicator_line(collaboration_mode_indicator, show_cycle_hint); let compact = mode_indicator_line(collaboration_mode_indicator, false); let full_width = full.as_ref().map(|line| line.width() as u16).unwrap_or(0); @@ -1078,7 +1092,7 @@ mod tests { .as_ref() .map(|line| line.width() as u16) .unwrap_or(0); - if props.status_line_enabled + if status_line_active && let Some(max_left) = max_left_width_for_right(area, right_width) && left_width > max_left && let Some(line) = props @@ -1098,21 +1112,24 @@ mod tests { props.mode, FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft ) { - let (summary_left, show_context) = single_line_footer_layout( - area, - right_width, - left_mode_indicator, - show_cycle_hint, - show_shortcuts_hint, - show_queue_hint, - ); - match summary_left { - SummaryLeft::Default => { - if props.status_line_enabled { - if let Some(line) = truncated_status_line.clone() { - render_footer_line(area, f.buffer_mut(), line); - } - } else { + if status_line_active { + if let Some(line) = truncated_status_line.clone() { + render_footer_line(area, f.buffer_mut(), line); + } + if can_show_left_and_context && let Some(line) = &right_line { + render_context_right(area, f.buffer_mut(), line); + } + } else { + let (summary_left, show_context) = single_line_footer_layout( + area, + right_width, + left_mode_indicator, + show_cycle_hint, + show_shortcuts_hint, + show_queue_hint, + ); + match summary_left { + SummaryLeft::Default => { render_footer_from_props( area, f.buffer_mut(), @@ -1123,14 +1140,14 @@ mod tests { show_queue_hint, ); } + SummaryLeft::Custom(line) => { + render_footer_line(area, f.buffer_mut(), line); + } + SummaryLeft::None => {} } - SummaryLeft::Custom(line) => { - render_footer_line(area, f.buffer_mut(), line); + if show_context && let Some(line) = &right_line { + render_context_right(area, f.buffer_mut(), line); } - SummaryLeft::None => {} - } - if show_context && let Some(line) = &right_line { - render_context_right(area, f.buffer_mut(), line); } } else { render_footer_from_props( @@ -1189,7 +1206,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1207,7 +1223,6 @@ mod tests { esc_backtrack_hint: true, use_shift_enter_hint: true, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1225,7 +1240,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1243,7 +1257,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1261,7 +1274,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1279,7 +1291,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1297,7 +1308,6 @@ mod tests { esc_backtrack_hint: true, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1315,7 +1325,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1333,7 +1342,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1344,24 +1352,6 @@ mod tests { }, ); - snapshot_footer( - "footer_composer_has_draft_queue_hint_disabled", - FooterProps { - mode: FooterMode::ComposerHasDraft, - esc_backtrack_hint: false, - use_shift_enter_hint: false, - is_task_running: true, - steer_enabled: false, - collaboration_modes_enabled: false, - is_wsl: false, - quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), - context_window_percent: None, - context_window_used_tokens: None, - status_line_value: None, - status_line_enabled: false, - }, - ); - snapshot_footer( "footer_composer_has_draft_queue_hint_enabled", FooterProps { @@ -1369,7 +1359,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, - steer_enabled: true, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1385,7 +1374,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1414,7 +1402,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1436,7 +1423,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1448,12 +1434,43 @@ mod tests { snapshot_footer("footer_status_line_overrides_shortcuts", props); + let props = FooterProps { + mode: FooterMode::ComposerHasDraft, + esc_backtrack_hint: false, + use_shift_enter_hint: false, + is_task_running: true, + collaboration_modes_enabled: false, + is_wsl: false, + quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), + context_window_percent: None, + context_window_used_tokens: None, + status_line_value: Some(Line::from("Status line content".to_string())), + status_line_enabled: true, + }; + + snapshot_footer("footer_status_line_yields_to_queue_hint", props); + + let props = FooterProps { + mode: FooterMode::ComposerHasDraft, + esc_backtrack_hint: false, + use_shift_enter_hint: false, + is_task_running: false, + collaboration_modes_enabled: false, + is_wsl: false, + quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), + context_window_percent: None, + context_window_used_tokens: None, + status_line_value: Some(Line::from("Status line content".to_string())), + status_line_enabled: true, + }; + + snapshot_footer("footer_status_line_overrides_draft_idle", props); + let props = FooterProps { mode: FooterMode::ComposerEmpty, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1475,7 +1492,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1497,7 +1513,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: false, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1520,7 +1535,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), @@ -1547,7 +1561,6 @@ mod tests { esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, - steer_enabled: false, collaboration_modes_enabled: true, is_wsl: false, quit_shortcut_key: key_hint::ctrl(KeyCode::Char('c')), diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 3202a61621..02c7faeebb 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -129,6 +129,7 @@ pub(crate) enum CancellationEvent { NotHandled, } +use crate::bottom_pane::prompt_args::parse_slash_name; pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::ChatComposerConfig; pub(crate) use chat_composer::InputResult; @@ -265,10 +266,6 @@ impl BottomPane { let _ = self.take_mention_bindings(); } - pub fn set_steer_enabled(&mut self, enabled: bool) { - self.composer.set_steer_enabled(enabled); - } - pub fn set_collaboration_modes_enabled(&mut self, enabled: bool) { self.composer.set_collaboration_modes_enabled(enabled); self.request_redraw(); @@ -297,11 +294,21 @@ impl BottomPane { self.request_redraw(); } + pub fn set_fast_command_enabled(&mut self, enabled: bool) { + self.composer.set_fast_command_enabled(enabled); + self.request_redraw(); + } + pub fn set_realtime_conversation_enabled(&mut self, enabled: bool) { self.composer.set_realtime_conversation_enabled(enabled); self.request_redraw(); } + pub fn set_audio_device_selection_enabled(&mut self, enabled: bool) { + self.composer.set_audio_device_selection_enabled(enabled); + self.request_redraw(); + } + pub fn set_voice_transcription_enabled(&mut self, enabled: bool) { self.composer.set_voice_transcription_enabled(enabled); self.request_redraw(); @@ -397,11 +404,20 @@ impl BottomPane { self.request_redraw(); InputResult::None } else { + let is_agent_command = self + .composer_text() + .lines() + .next() + .and_then(parse_slash_name) + .is_some_and(|(name, _, _)| name == "agent"); + // If a task is running and a status line is visible, allow Esc to // send an interrupt even while the composer has focus. // When a popup is active, prefer dismissing it over interrupting the task. if key_event.code == KeyCode::Esc + && matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat) && self.is_task_running + && !is_agent_command && !self.composer.popup_active() && let Some(status) = &self.status { @@ -811,6 +827,11 @@ impl BottomPane { self.is_task_running } + #[cfg(test)] + pub(crate) fn has_active_view(&self) -> bool { + !self.view_stack.is_empty() + } + /// Return true when the pane is in the regular composer state without any /// overlays or popups and not running a task. This is the safe context to /// use Esc-Esc for backtracking from the main view. @@ -1114,12 +1135,16 @@ mod tests { fn exec_request() -> ApprovalRequest { ApprovalRequest::Exec { + thread_id: codex_protocol::ThreadId::new(), + thread_label: None, id: "1".to_string(), command: vec!["echo".into(), "ok".into()], reason: None, + available_decisions: vec![ + codex_protocol::protocol::ReviewDecision::Approved, + codex_protocol::protocol::ReviewDecision::Abort, + ], network_approval_context: None, - proposed_execpolicy_amendment: None, - proposed_network_policy_amendments: None, additional_permissions: None, } } @@ -1519,7 +1544,6 @@ mod tests { dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: PathBuf::from("test-skill"), scope: SkillScope::User, }]), @@ -1583,6 +1607,90 @@ mod tests { assert_eq!(pane.composer_text(), "/"); } + #[test] + fn esc_with_agent_command_without_popup_does_not_interrupt_task() { + let (tx_raw, mut rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut pane = BottomPane::new(BottomPaneParams { + app_event_tx: tx, + frame_requester: FrameRequester::test_dummy(), + has_input_focus: true, + enhanced_keys_supported: false, + placeholder_text: "Ask Codex to do anything".to_string(), + disable_paste_burst: false, + animations_enabled: true, + skills: Some(Vec::new()), + }); + + pane.set_task_running(true); + + // Repro: `/agent ` hides the popup (cursor past command name). Esc should + // keep editing command text instead of interrupting the running task. + pane.insert_str("/agent "); + assert!( + !pane.composer.popup_active(), + "expected command popup to be hidden after entering `/agent `" + ); + + pane.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + + while let Ok(ev) = rx.try_recv() { + assert!( + !matches!(ev, AppEvent::CodexOp(Op::Interrupt)), + "expected Esc to not send Op::Interrupt while typing `/agent`" + ); + } + assert_eq!(pane.composer_text(), "/agent "); + } + + #[test] + fn esc_release_after_dismissing_agent_picker_does_not_interrupt_task() { + let (tx_raw, mut rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut pane = BottomPane::new(BottomPaneParams { + app_event_tx: tx, + frame_requester: FrameRequester::test_dummy(), + has_input_focus: true, + enhanced_keys_supported: false, + placeholder_text: "Ask Codex to do anything".to_string(), + disable_paste_burst: false, + animations_enabled: true, + skills: Some(Vec::new()), + }); + + pane.set_task_running(true); + pane.show_selection_view(SelectionViewParams { + title: Some("Agents".to_string()), + items: vec![SelectionItem { + name: "Main".to_string(), + ..Default::default() + }], + ..Default::default() + }); + + pane.handle_key_event(KeyEvent::new_with_kind( + KeyCode::Esc, + KeyModifiers::NONE, + KeyEventKind::Press, + )); + pane.handle_key_event(KeyEvent::new_with_kind( + KeyCode::Esc, + KeyModifiers::NONE, + KeyEventKind::Release, + )); + + while let Ok(ev) = rx.try_recv() { + assert!( + !matches!(ev, AppEvent::CodexOp(Op::Interrupt)), + "expected Esc release after dismissing agent picker to not interrupt" + ); + } + assert!( + pane.no_modal_or_popup_active(), + "expected Esc press to dismiss the agent picker" + ); + } + #[test] fn esc_interrupts_running_task_when_no_popup() { let (tx_raw, mut rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index 86c131e6db..85b301386b 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -8,66 +8,47 @@ use codex_utils_fuzzy_match::fuzzy_match; use crate::slash_command::SlashCommand; use crate::slash_command::built_in_slash_commands; +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct BuiltinCommandFlags { + pub(crate) collaboration_modes_enabled: bool, + pub(crate) connectors_enabled: bool, + pub(crate) fast_command_enabled: bool, + pub(crate) personality_command_enabled: bool, + pub(crate) realtime_conversation_enabled: bool, + pub(crate) audio_device_selection_enabled: bool, + pub(crate) allow_elevate_sandbox: bool, +} + /// Return the built-ins that should be visible/usable for the current input. -pub(crate) fn builtins_for_input( - collaboration_modes_enabled: bool, - connectors_enabled: bool, - personality_command_enabled: bool, - realtime_conversation_enabled: bool, - allow_elevate_sandbox: bool, -) -> Vec<(&'static str, SlashCommand)> { +pub(crate) fn builtins_for_input(flags: BuiltinCommandFlags) -> Vec<(&'static str, SlashCommand)> { built_in_slash_commands() .into_iter() - .filter(|(_, cmd)| allow_elevate_sandbox || *cmd != SlashCommand::ElevateSandbox) + .filter(|(_, cmd)| flags.allow_elevate_sandbox || *cmd != SlashCommand::ElevateSandbox) .filter(|(_, cmd)| { - collaboration_modes_enabled + flags.collaboration_modes_enabled || !matches!(*cmd, SlashCommand::Collab | SlashCommand::Plan) }) - .filter(|(_, cmd)| connectors_enabled || *cmd != SlashCommand::Apps) - .filter(|(_, cmd)| personality_command_enabled || *cmd != SlashCommand::Personality) - .filter(|(_, cmd)| realtime_conversation_enabled || *cmd != SlashCommand::Realtime) + .filter(|(_, cmd)| flags.connectors_enabled || *cmd != SlashCommand::Apps) + .filter(|(_, cmd)| flags.fast_command_enabled || *cmd != SlashCommand::Fast) + .filter(|(_, cmd)| flags.personality_command_enabled || *cmd != SlashCommand::Personality) + .filter(|(_, cmd)| flags.realtime_conversation_enabled || *cmd != SlashCommand::Realtime) + .filter(|(_, cmd)| flags.audio_device_selection_enabled || *cmd != SlashCommand::Settings) .collect() } /// Find a single built-in command by exact name, after applying the gating rules. -pub(crate) fn find_builtin_command( - name: &str, - collaboration_modes_enabled: bool, - connectors_enabled: bool, - personality_command_enabled: bool, - realtime_conversation_enabled: bool, - allow_elevate_sandbox: bool, -) -> Option { - builtins_for_input( - collaboration_modes_enabled, - connectors_enabled, - personality_command_enabled, - realtime_conversation_enabled, - allow_elevate_sandbox, - ) - .into_iter() - .find(|(command_name, _)| *command_name == name) - .map(|(_, cmd)| cmd) +pub(crate) fn find_builtin_command(name: &str, flags: BuiltinCommandFlags) -> Option { + builtins_for_input(flags) + .into_iter() + .find(|(command_name, _)| *command_name == name) + .map(|(_, cmd)| cmd) } /// Whether any visible built-in fuzzily matches the provided prefix. -pub(crate) fn has_builtin_prefix( - name: &str, - collaboration_modes_enabled: bool, - connectors_enabled: bool, - personality_command_enabled: bool, - realtime_conversation_enabled: bool, - allow_elevate_sandbox: bool, -) -> bool { - builtins_for_input( - collaboration_modes_enabled, - connectors_enabled, - personality_command_enabled, - realtime_conversation_enabled, - allow_elevate_sandbox, - ) - .into_iter() - .any(|(command_name, _)| fuzzy_match(command_name, name).is_some()) +pub(crate) fn has_builtin_prefix(name: &str, flags: BuiltinCommandFlags) -> bool { + builtins_for_input(flags) + .into_iter() + .any(|(command_name, _)| fuzzy_match(command_name, name).is_some()) } #[cfg(test)] @@ -75,25 +56,58 @@ mod tests { use super::*; use pretty_assertions::assert_eq; + fn all_enabled_flags() -> BuiltinCommandFlags { + BuiltinCommandFlags { + collaboration_modes_enabled: true, + connectors_enabled: true, + fast_command_enabled: true, + personality_command_enabled: true, + realtime_conversation_enabled: true, + audio_device_selection_enabled: true, + allow_elevate_sandbox: true, + } + } + #[test] fn debug_command_still_resolves_for_dispatch() { - let cmd = find_builtin_command("debug-config", true, true, true, false, false); + let cmd = find_builtin_command("debug-config", all_enabled_flags()); assert_eq!(cmd, Some(SlashCommand::DebugConfig)); } #[test] fn clear_command_resolves_for_dispatch() { assert_eq!( - find_builtin_command("clear", true, true, true, false, false), + find_builtin_command("clear", all_enabled_flags()), Some(SlashCommand::Clear) ); } + #[test] + fn fast_command_is_hidden_when_disabled() { + let mut flags = all_enabled_flags(); + flags.fast_command_enabled = false; + assert_eq!(find_builtin_command("fast", flags), None); + } + #[test] fn realtime_command_is_hidden_when_realtime_is_disabled() { - assert_eq!( - find_builtin_command("realtime", true, true, true, false, false), - None - ); + let mut flags = all_enabled_flags(); + flags.realtime_conversation_enabled = false; + assert_eq!(find_builtin_command("realtime", flags), None); + } + + #[test] + fn settings_command_is_hidden_when_realtime_is_disabled() { + let mut flags = all_enabled_flags(); + flags.realtime_conversation_enabled = false; + flags.audio_device_selection_enabled = false; + assert_eq!(find_builtin_command("settings", flags), None); + } + + #[test] + fn settings_command_is_hidden_when_audio_device_selection_is_disabled() { + let mut flags = all_enabled_flags(); + flags.audio_device_selection_enabled = false; + assert_eq!(find_builtin_command("settings", flags), None); } } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_cross_thread_prompt.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_cross_thread_prompt.snap new file mode 100644 index 0000000000..ddd106c638 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__approval_overlay__tests__approval_overlay_cross_thread_prompt.snap @@ -0,0 +1,14 @@ +--- +source: tui/src/bottom_pane/approval_overlay.rs +expression: "render_overlay_lines(&view, 80)" +--- + Would you like to run the following command? + + Thread: Robie [explorer] + + $ echo hi + +› 1. Yes, proceed (y) + 2. No, and tell Codex what to do differently (esc) + + Press enter to confirm or esc to cancel or o to open thread diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_status_line_overrides_draft_idle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_status_line_overrides_draft_idle.snap new file mode 100644 index 0000000000..bb0e2d33b9 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_status_line_overrides_draft_idle.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/bottom_pane/footer.rs +expression: terminal.backend() +--- +" Status line content " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_status_line_yields_to_queue_hint.snap similarity index 60% rename from codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap rename to codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_status_line_yields_to_queue_hint.snap index 6fdeda07b1..71370d83ba 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_composer_has_draft_queue_hint_disabled.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_status_line_yields_to_queue_hint.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 100% context left " +" tab to queue message 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index fbb30a0322..81ff502837 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -1,3 +1,15 @@ +//! The textarea owns editable composer text, placeholder elements, cursor/wrap state, and a +//! single-entry kill buffer. +//! +//! Whole-buffer replacement APIs intentionally rebuild only the visible draft state. They clear +//! element ranges and derived cursor/wrapping caches, but they keep the kill buffer intact so a +//! caller can clear or rewrite the draft and still allow `Ctrl+Y` to restore the user's most +//! recent `Ctrl+K`. This is the contract higher-level composer flows rely on after submit, +//! slash-command dispatch, and other synthetic clears. +//! +//! This module does not implement an Emacs-style multi-entry kill ring. It keeps only the most +//! recent killed span. + use crate::key_hint::is_altgr; use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement as UserTextElement; @@ -38,6 +50,14 @@ pub(crate) struct TextElementSnapshot { pub(crate) text: String, } +/// `TextArea` is the editable buffer behind the TUI composer. +/// +/// It owns the raw UTF-8 text, placeholder-like text elements that must move atomically with +/// edits, cursor/wrapping state for rendering, and a single-entry kill buffer for `Ctrl+K` / +/// `Ctrl+Y` style editing. Callers may replace the entire visible buffer through +/// [`Self::set_text_clearing_elements`] or [`Self::set_text_with_elements`] without disturbing the +/// kill buffer; if they incorrectly assume those methods fully reset editing state, a later yank +/// will appear to restore stale text from the user's perspective. #[derive(Debug)] pub(crate) struct TextArea { text: String, @@ -74,12 +94,21 @@ impl TextArea { } } - /// Replace the textarea text and clear any existing text elements. + /// Replace the visible textarea text and clear any existing text elements. + /// + /// This is the "fresh buffer" path for callers that want plain text with no placeholder + /// ranges. It intentionally preserves the current kill buffer, because higher-level flows such + /// as submit or slash-command dispatch clear the draft through this method and still want + /// `Ctrl+Y` to recover the user's most recent kill. pub fn set_text_clearing_elements(&mut self, text: &str) { self.set_text_inner(text, None); } - /// Replace the textarea text and set the provided text elements. + /// Replace the visible textarea text and rebuild the provided text elements. + /// + /// As with [`Self::set_text_clearing_elements`], this resets only state derived from the + /// visible buffer. The kill buffer survives so callers restoring drafts or external edits do + /// not silently discard a pending yank target. pub fn set_text_with_elements(&mut self, text: &str, elements: &[UserTextElement]) { self.set_text_inner(text, Some(elements)); } @@ -109,10 +138,11 @@ impl TextArea { self.elements.sort_by_key(|e| e.range.start); } // Stage 3: clamp the cursor and reset derived state tied to the prior content. + // The kill buffer is editing history rather than visible-buffer state, so full-buffer + // replacements intentionally leave it alone. self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos); self.wrap_cache.replace(None); self.preferred_col = None; - self.kill_buffer.clear(); } pub fn text(&self) -> &str { @@ -552,6 +582,12 @@ impl TextArea { } } + /// Kill from the cursor to the end of the current logical line. + /// + /// If the cursor is already at end-of-line and a trailing newline exists, this kills that + /// newline so repeated invocations continue making progress. The removed text becomes the next + /// yank target and remains available even if a caller later clears or rewrites the visible + /// buffer via `set_text_*`. pub fn kill_to_end_of_line(&mut self) { let eol = self.end_of_current_line(); let range = if self.cursor_pos == eol { @@ -582,6 +618,11 @@ impl TextArea { } } + /// Insert the most recently killed text at the cursor. + /// + /// This uses the textarea's single-entry kill buffer. Because whole-buffer replacement APIs do + /// not clear that buffer, `yank` can restore text after composer-level clears such as submit + /// and slash-command dispatch. pub fn yank(&mut self) { if self.kill_buffer.is_empty() { return; @@ -1735,6 +1776,21 @@ mod tests { assert_eq!(t.cursor(), 5); } + #[test] + fn kill_buffer_persists_across_set_text() { + let mut t = ta_with("restore me"); + t.set_cursor(0); + t.kill_to_end_of_line(); + assert!(t.text().is_empty()); + + t.set_text_clearing_elements("/diff"); + t.set_text_clearing_elements(""); + t.yank(); + + assert_eq!(t.text(), "restore me"); + assert_eq!(t.cursor(), "restore me".len()); + } + #[test] fn cursor_left_and_right_handle_graphemes() { let mut t = ta_with("a👍b"); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 533aa10561..51f39c1f2a 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -37,6 +37,9 @@ use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; +use crate::app_event::RealtimeAudioDeviceKind; +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +use crate::audio_device::list_realtime_audio_device_names; use crate::bottom_pane::StatusLineItem; use crate::bottom_pane::StatusLineSetupView; use crate::status::RateLimitWindowDisplay; @@ -60,7 +63,9 @@ use codex_core::find_thread_name_by_id; use codex_core::git_info::current_branch_name; use codex_core::git_info::get_git_repo_root; use codex_core::git_info::local_git_branches; +use codex_core::mcp::McpManager; use codex_core::models_manager::manager::ModelsManager; +use codex_core::plugins::PluginsManager; use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; use codex_core::skills::model::SkillMetadata; use codex_core::terminal::TerminalName; @@ -76,6 +81,7 @@ use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Settings; #[cfg(target_os = "windows")] use codex_protocol::config_types::WindowsSandboxLevel; @@ -159,6 +165,10 @@ const PLAN_IMPLEMENTATION_TITLE: &str = "Implement this plan?"; const PLAN_IMPLEMENTATION_YES: &str = "Yes, implement this plan"; const PLAN_IMPLEMENTATION_NO: &str = "No, stay in Plan mode"; const PLAN_IMPLEMENTATION_CODING_MESSAGE: &str = "Implement the plan."; +const MULTI_AGENT_ENABLE_TITLE: &str = "Enable multi-agent?"; +const MULTI_AGENT_ENABLE_YES: &str = "Yes, enable"; +const MULTI_AGENT_ENABLE_NO: &str = "Not now"; +const MULTI_AGENT_ENABLE_NOTICE: &str = "Multi-agent will be enabled in the next session."; const PLAN_MODE_REASONING_SCOPE_TITLE: &str = "Apply reasoning change"; const PLAN_MODE_REASONING_SCOPE_PLAN_ONLY: &str = "Apply to Plan mode override"; const PLAN_MODE_REASONING_SCOPE_ALL_MODES: &str = "Apply to global default and Plan mode override"; @@ -459,6 +469,7 @@ pub(crate) struct ChatWidgetInit { pub(crate) is_first_run: bool, pub(crate) feedback_audience: FeedbackAudience, pub(crate) model: Option, + pub(crate) startup_tooltip_override: Option, // Shared latch so we only warn once about invalid status-line item IDs. pub(crate) status_line_invalid_items_warned: Arc, pub(crate) otel_manager: OtelManager, @@ -600,6 +611,8 @@ pub(crate) struct ChatWidget { frame_requester: FrameRequester, // Whether to include the initial welcome banner on session configured show_welcome_banner: bool, + // One-shot tooltip override for the primary startup session. + startup_tooltip_override: Option, // When resuming an existing session (selected via resume picker), avoid an // immediate redraw on SessionConfigured to prevent a gratuitous UI flicker. suppress_session_configured_redraw: bool, @@ -855,6 +868,10 @@ impl ChatWidget { && cfg!(not(target_os = "linux")) } + fn realtime_audio_device_selection_enabled(&self) -> bool { + self.realtime_conversation_enabled() && cfg!(feature = "voice-input") + } + /// Synchronize the bottom-pane "task running" indicator with the current lifecycles. /// /// The bottom pane only has one running flag, but this module treats it as a derived state of @@ -1135,13 +1152,20 @@ impl ChatWidget { Some(event.reasoning_effort), None, ); + if let Some(mask) = self.active_collaboration_mask.as_mut() { + mask.model = Some(model_for_header.clone()); + mask.reasoning_effort = Some(event.reasoning_effort); + } self.refresh_model_display(); + self.sync_fast_command_enabled(); self.sync_personality_command_enabled(); + let startup_tooltip_override = self.startup_tooltip_override.take(); let session_info_cell = history_cell::new_session_info( &self.config, &model_for_header, event, self.show_welcome_banner, + startup_tooltip_override, self.auth_manager .auth_cached() .and_then(|auth| auth.account_plan_type()), @@ -1550,6 +1574,41 @@ impl ChatWidget { }); } + pub(crate) fn open_multi_agent_enable_prompt(&mut self) { + let items = vec![ + SelectionItem { + name: MULTI_AGENT_ENABLE_YES.to_string(), + description: Some( + "Save the setting now. You will need a new session to use it.".to_string(), + ), + actions: vec![Box::new(|tx| { + tx.send(AppEvent::UpdateFeatureFlags { + updates: vec![(Feature::Collab, true)], + }); + tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::new_warning_event(MULTI_AGENT_ENABLE_NOTICE.to_string()), + ))); + })], + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: MULTI_AGENT_ENABLE_NO.to_string(), + description: Some("Keep multi-agent disabled.".to_string()), + dismiss_on_select: true, + ..Default::default() + }, + ]; + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some(MULTI_AGENT_ENABLE_TITLE.to_string()), + subtitle: Some("Multi-agent is currently disabled in your config.".to_string()), + footer_hint: Some(standard_popup_hint_line()), + items, + ..Default::default() + }); + } + pub(crate) fn set_token_info(&mut self, info: Option) { match info { Some(info) => self.apply_token_info(info), @@ -2568,13 +2627,15 @@ impl ChatWidget { .unwrap_or_else(|_| ev.command.join(" ")); self.notify(Notification::ExecApprovalRequested { command }); + let available_decisions = ev.effective_available_decisions(); let request = ApprovalRequest::Exec { + thread_id: self.thread_id.unwrap_or_default(), + thread_label: None, id: ev.effective_approval_id(), command: ev.command, reason: ev.reason, + available_decisions, network_approval_context: ev.network_approval_context, - proposed_execpolicy_amendment: ev.proposed_execpolicy_amendment, - proposed_network_policy_amendments: ev.proposed_network_policy_amendments, additional_permissions: ev.additional_permissions, }; self.bottom_pane @@ -2586,6 +2647,8 @@ impl ChatWidget { self.flush_answer_stream_with_separator(); let request = ApprovalRequest::ApplyPatch { + thread_id: self.thread_id.unwrap_or_default(), + thread_label: None, id: ev.call_id, reason: ev.reason, changes: ev.changes.clone(), @@ -2608,6 +2671,8 @@ impl ChatWidget { }); let request = ApprovalRequest::McpElicitation { + thread_id: self.thread_id.unwrap_or_default(), + thread_label: None, server_name: ev.server_name, request_id: ev.id, message: ev.message, @@ -2617,6 +2682,12 @@ impl ChatWidget { self.request_redraw(); } + pub(crate) fn push_approval_request(&mut self, request: ApprovalRequest) { + self.bottom_pane + .push_approval_request(request, &self.config.features); + self.request_redraw(); + } + pub(crate) fn handle_request_user_input_now(&mut self, ev: RequestUserInputEvent) { self.flush_answer_stream_with_separator(); self.bottom_pane.push_user_input_request(ev); @@ -2748,6 +2819,7 @@ impl ChatWidget { is_first_run, feedback_audience, model, + startup_tooltip_override, status_line_invalid_items_warned, otel_manager, } = common; @@ -2845,6 +2917,7 @@ impl ChatWidget { queued_user_messages: VecDeque::new(), queued_message_edit_binding, show_welcome_banner: is_first_run, + startup_tooltip_override, suppress_session_configured_redraw: false, pending_notification: None, quit_shortcut_expires_at: None, @@ -2876,19 +2949,20 @@ impl ChatWidget { }; widget.prefetch_rate_limits(); - widget - .bottom_pane - .set_steer_enabled(widget.config.features.enabled(Feature::Steer)); widget.bottom_pane.set_voice_transcription_enabled( widget.config.features.enabled(Feature::VoiceTranscription), ); widget .bottom_pane .set_realtime_conversation_enabled(widget.realtime_conversation_enabled()); + widget + .bottom_pane + .set_audio_device_selection_enabled(widget.realtime_audio_device_selection_enabled()); widget .bottom_pane .set_status_line_enabled(!widget.configured_status_line_items().is_empty()); widget.bottom_pane.set_collaboration_modes_enabled(true); + widget.sync_fast_command_enabled(); widget.sync_personality_command_enabled(); widget .bottom_pane @@ -2926,6 +3000,7 @@ impl ChatWidget { is_first_run, feedback_audience, model, + startup_tooltip_override, status_line_invalid_items_warned, otel_manager, } = common; @@ -3026,6 +3101,7 @@ impl ChatWidget { queued_user_messages: VecDeque::new(), queued_message_edit_binding, show_welcome_banner: is_first_run, + startup_tooltip_override, suppress_session_configured_redraw: false, pending_notification: None, quit_shortcut_expires_at: None, @@ -3053,19 +3129,20 @@ impl ChatWidget { }; widget.prefetch_rate_limits(); - widget - .bottom_pane - .set_steer_enabled(widget.config.features.enabled(Feature::Steer)); widget.bottom_pane.set_voice_transcription_enabled( widget.config.features.enabled(Feature::VoiceTranscription), ); widget .bottom_pane .set_realtime_conversation_enabled(widget.realtime_conversation_enabled()); + widget + .bottom_pane + .set_audio_device_selection_enabled(widget.realtime_audio_device_selection_enabled()); widget .bottom_pane .set_status_line_enabled(!widget.configured_status_line_items().is_empty()); widget.bottom_pane.set_collaboration_modes_enabled(true); + widget.sync_fast_command_enabled(); widget.sync_personality_command_enabled(); widget .bottom_pane @@ -3092,6 +3169,7 @@ impl ChatWidget { is_first_run: _, feedback_audience, model, + startup_tooltip_override: _, status_line_invalid_items_warned, otel_manager, } = common; @@ -3188,6 +3266,7 @@ impl ChatWidget { queued_user_messages: VecDeque::new(), queued_message_edit_binding, show_welcome_banner: false, + startup_tooltip_override: None, suppress_session_configured_redraw: true, pending_notification: None, quit_shortcut_expires_at: None, @@ -3219,19 +3298,20 @@ impl ChatWidget { }; widget.prefetch_rate_limits(); - widget - .bottom_pane - .set_steer_enabled(widget.config.features.enabled(Feature::Steer)); widget.bottom_pane.set_voice_transcription_enabled( widget.config.features.enabled(Feature::VoiceTranscription), ); widget .bottom_pane .set_realtime_conversation_enabled(widget.realtime_conversation_enabled()); + widget + .bottom_pane + .set_audio_device_selection_enabled(widget.realtime_audio_device_selection_enabled()); widget .bottom_pane .set_status_line_enabled(!widget.configured_status_line_items().is_empty()); widget.bottom_pane.set_collaboration_modes_enabled(true); + widget.sync_fast_command_enabled(); widget.sync_personality_command_enabled(); widget .bottom_pane @@ -3354,7 +3434,7 @@ impl ChatWidget { else { return; }; - // Steer submissions during active final-answer streaming can race with turn + // Submissions during active final-answer streaming can race with turn // completion and strand the UI in a running state. Queue those inputs instead // of injecting immediately; `on_task_complete()` drains this FIFO via // `maybe_send_next_queued_input()`, so no typed prompt is dropped. @@ -3362,7 +3442,7 @@ impl ChatWidget { && !self.is_plan_streaming_in_tui() && self.stream_controller.is_none(); if should_submit_now { - // Submitted is only emitted when steer is enabled. + // Submitted is emitted when user submits. // Reset any reasoning header only when we are actually submitting a turn. self.reasoning_buffer.clear(); self.full_reasoning_buffer.clear(); @@ -3530,6 +3610,14 @@ impl ChatWidget { SlashCommand::Model => { self.open_model_popup(); } + SlashCommand::Fast => { + let next_tier = if self.config.service_tier.is_some() { + None + } else { + Some(ServiceTier::Fast) + }; + self.set_service_tier_selection(next_tier); + } SlashCommand::Realtime => { if !self.realtime_conversation_enabled() { return; @@ -3540,6 +3628,12 @@ impl ChatWidget { self.start_realtime_conversation(); } } + SlashCommand::Settings => { + if !self.realtime_audio_device_selection_enabled() { + return; + } + self.open_realtime_audio_popup(); + } SlashCommand::Personality => { self.open_personality_popup(); } @@ -3567,7 +3661,7 @@ impl ChatWidget { } self.open_collaboration_modes_popup(); } - SlashCommand::Agent => { + SlashCommand::Agent | SlashCommand::MultiAgents => { self.app_event_tx.send(AppEvent::OpenAgentPicker); } SlashCommand::Approvals => { @@ -3803,6 +3897,27 @@ impl ChatWidget { let trimmed = args.trim(); match cmd { + SlashCommand::Fast => { + if trimmed.is_empty() { + self.dispatch_command(cmd); + return; + } + match trimmed.to_ascii_lowercase().as_str() { + "on" => self.set_service_tier_selection(Some(ServiceTier::Fast)), + "off" => self.set_service_tier_selection(None), + "status" => { + let status = if self.config.service_tier.is_some() { + "on" + } else { + "off" + }; + self.add_info_message(format!("Fast mode is {status}."), None); + } + _ => { + self.add_error_message("Usage: /fast [on|off|status]".to_string()); + } + } + } SlashCommand::Rename if !trimmed.is_empty() => { self.otel_manager.counter("codex.thread.rename", 1, &[]); let Some((prepared_args, _prepared_elements)) = @@ -4141,6 +4256,7 @@ impl ChatWidget { .personality .filter(|_| self.config.features.enabled(Feature::Personality)) .filter(|_| self.current_model_supports_personality()); + let service_tier = self.fast_mode_enabled().then_some(self.config.service_tier); let op = Op::UserTurn { items, cwd: self.config.cwd.clone(), @@ -4148,7 +4264,8 @@ impl ChatWidget { sandbox_policy: self.config.permissions.sandbox_policy.get().clone(), model: effective_mode.model().to_string(), effort: effective_mode.reasoning_effort(), - summary: self.config.model_reasoning_summary, + summary: None, + service_tier, final_output_json_schema: None, collaboration_mode, personality, @@ -4464,7 +4581,7 @@ impl ChatWidget { | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) | EventMsg::DynamicToolCallRequest(_) - | EventMsg::SkillRequestApproval(_) => {} + | EventMsg::DynamicToolCallResponse(_) => {} EventMsg::RealtimeConversationStarted(ev) => { if !from_replay { self.on_realtime_conversation_started(ev); @@ -5129,6 +5246,7 @@ impl ChatWidget { model: Some(switch_model_for_events.clone()), effort: Some(Some(default_effort)), summary: None, + service_tier: None, collaboration_mode: None, personality: None, })); @@ -5248,6 +5366,7 @@ impl ChatWidget { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, windows_sandbox_level: None, personality: Some(personality), @@ -5279,6 +5398,161 @@ impl ChatWidget { }); } + pub(crate) fn open_realtime_audio_popup(&mut self) { + let items = [ + RealtimeAudioDeviceKind::Microphone, + RealtimeAudioDeviceKind::Speaker, + ] + .into_iter() + .map(|kind| { + let description = Some(format!( + "Current: {}", + self.current_realtime_audio_selection_label(kind) + )); + let actions: Vec = vec![Box::new(move |tx| { + tx.send(AppEvent::OpenRealtimeAudioDeviceSelection { kind }); + })]; + SelectionItem { + name: kind.title().to_string(), + description, + actions, + dismiss_on_select: true, + ..Default::default() + } + }) + .collect(); + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some("Settings".to_string()), + subtitle: Some("Configure settings for Codex.".to_string()), + footer_hint: Some(standard_popup_hint_line()), + items, + ..Default::default() + }); + } + + #[cfg(all(not(target_os = "linux"), feature = "voice-input"))] + pub(crate) fn open_realtime_audio_device_selection(&mut self, kind: RealtimeAudioDeviceKind) { + match list_realtime_audio_device_names(kind) { + Ok(device_names) => { + self.open_realtime_audio_device_selection_with_names(kind, device_names); + } + Err(err) => { + self.add_error_message(format!( + "Failed to load realtime {} devices: {err}", + kind.noun() + )); + } + } + } + + #[cfg(any(target_os = "linux", not(feature = "voice-input")))] + pub(crate) fn open_realtime_audio_device_selection(&mut self, kind: RealtimeAudioDeviceKind) { + let _ = kind; + } + + #[cfg(all(not(target_os = "linux"), feature = "voice-input"))] + fn open_realtime_audio_device_selection_with_names( + &mut self, + kind: RealtimeAudioDeviceKind, + device_names: Vec, + ) { + let current_selection = self.current_realtime_audio_device_name(kind); + let current_available = current_selection + .as_deref() + .is_some_and(|name| device_names.iter().any(|device_name| device_name == name)); + let mut items = vec![SelectionItem { + name: "System default".to_string(), + description: Some("Use your operating system default device.".to_string()), + is_current: current_selection.is_none(), + actions: vec![Box::new(move |tx| { + tx.send(AppEvent::PersistRealtimeAudioDeviceSelection { kind, name: None }); + })], + dismiss_on_select: true, + ..Default::default() + }]; + + if let Some(selection) = current_selection.as_deref() + && !current_available + { + items.push(SelectionItem { + name: format!("Unavailable: {selection}"), + description: Some("Configured device is not currently available.".to_string()), + is_current: true, + is_disabled: true, + disabled_reason: Some("Reconnect the device or choose another one.".to_string()), + ..Default::default() + }); + } + + items.extend(device_names.into_iter().map(|device_name| { + let persisted_name = device_name.clone(); + let actions: Vec = vec![Box::new(move |tx| { + tx.send(AppEvent::PersistRealtimeAudioDeviceSelection { + kind, + name: Some(persisted_name.clone()), + }); + })]; + SelectionItem { + is_current: current_selection.as_deref() == Some(device_name.as_str()), + name: device_name, + actions, + dismiss_on_select: true, + ..Default::default() + } + })); + + let mut header = ColumnRenderable::new(); + header.push(Line::from(format!("Select {}", kind.title()).bold())); + header.push(Line::from( + "Saved devices apply to realtime voice only.".dim(), + )); + + self.bottom_pane.show_selection_view(SelectionViewParams { + header: Box::new(header), + footer_hint: Some(standard_popup_hint_line()), + items, + ..Default::default() + }); + } + + pub(crate) fn open_realtime_audio_restart_prompt(&mut self, kind: RealtimeAudioDeviceKind) { + let restart_actions: Vec = vec![Box::new(move |tx| { + tx.send(AppEvent::RestartRealtimeAudioDevice { kind }); + })]; + let items = vec![ + SelectionItem { + name: "Restart now".to_string(), + description: Some(format!("Restart local {} audio now.", kind.noun())), + actions: restart_actions, + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "Apply later".to_string(), + description: Some(format!( + "Keep the current {} until local audio starts again.", + kind.noun() + )), + dismiss_on_select: true, + ..Default::default() + }, + ]; + + let mut header = ColumnRenderable::new(); + header.push(Line::from(format!("Restart {} now?", kind.title()).bold())); + header.push(Line::from( + "Configuration is saved. Restart local audio to use it immediately.".dim(), + )); + + self.bottom_pane.show_selection_view(SelectionViewParams { + header: Box::new(header), + footer_hint: Some(standard_popup_hint_line()), + items, + ..Default::default() + }); + } + fn model_menu_header(&self, title: &str, subtitle: &str) -> Box { let title = title.to_string(); let subtitle = subtitle.to_string(); @@ -6006,6 +6280,7 @@ impl ChatWidget { model: None, effort: None, summary: None, + service_tier: None, collaboration_mode: None, personality: None, })); @@ -6525,9 +6800,6 @@ impl ChatWidget { } else { self.config.features.disable(feature); } - if feature == Feature::Steer { - self.bottom_pane.set_steer_enabled(enabled); - } if feature == Feature::VoiceTranscription { self.bottom_pane.set_voice_transcription_enabled(enabled); } @@ -6535,6 +6807,8 @@ impl ChatWidget { let realtime_conversation_enabled = self.realtime_conversation_enabled(); self.bottom_pane .set_realtime_conversation_enabled(realtime_conversation_enabled); + self.bottom_pane + .set_audio_device_selection_enabled(self.realtime_audio_device_selection_enabled()); if !realtime_conversation_enabled && self.realtime_conversation.is_live() { self.request_realtime_conversation_close(Some( "Realtime voice mode was closed because the feature was disabled.".to_string(), @@ -6542,6 +6816,9 @@ impl ChatWidget { self.reset_realtime_conversation_state(); } } + if feature == Feature::FastMode { + self.sync_fast_command_enabled(); + } if feature == Feature::Personality { self.sync_personality_command_enabled(); } @@ -6624,6 +6901,30 @@ impl ChatWidget { self.config.personality = Some(personality); } + /// Set Fast mode in the widget's config copy. + pub(crate) fn set_service_tier(&mut self, service_tier: Option) { + self.config.service_tier = service_tier; + } + + pub(crate) fn current_service_tier(&self) -> Option { + self.config.service_tier + } + + fn fast_mode_enabled(&self) -> bool { + self.config.features.enabled(Feature::FastMode) + } + + pub(crate) fn set_realtime_audio_device( + &mut self, + kind: RealtimeAudioDeviceKind, + name: Option, + ) { + match kind { + RealtimeAudioDeviceKind::Microphone => self.config.realtime_audio.microphone = name, + RealtimeAudioDeviceKind::Speaker => self.config.realtime_audio.speaker = name, + } + } + /// Set the syntax theme override in the widget's config copy. pub(crate) fn set_tui_theme(&mut self, theme: Option) { self.config.tui_theme = theme; @@ -6642,6 +6943,25 @@ impl ChatWidget { self.refresh_model_display(); } + fn set_service_tier_selection(&mut self, service_tier: Option) { + self.set_service_tier(service_tier); + self.app_event_tx + .send(AppEvent::CodexOp(Op::OverrideTurnContext { + cwd: None, + approval_policy: None, + sandbox_policy: None, + windows_sandbox_level: None, + model: None, + effort: None, + summary: None, + service_tier: Some(service_tier), + collaboration_mode: None, + personality: None, + })); + self.app_event_tx + .send(AppEvent::PersistServiceTierSelection { service_tier }); + } + pub(crate) fn current_model(&self) -> &str { if !self.collaboration_modes_enabled() { return self.current_collaboration_mode.model(); @@ -6652,6 +6972,27 @@ impl ChatWidget { .unwrap_or_else(|| self.current_collaboration_mode.model()) } + pub(crate) fn realtime_conversation_is_live(&self) -> bool { + self.realtime_conversation.is_active() + } + + fn current_realtime_audio_device_name(&self, kind: RealtimeAudioDeviceKind) -> Option { + match kind { + RealtimeAudioDeviceKind::Microphone => self.config.realtime_audio.microphone.clone(), + RealtimeAudioDeviceKind::Speaker => self.config.realtime_audio.speaker.clone(), + } + } + + fn current_realtime_audio_selection_label(&self, kind: RealtimeAudioDeviceKind) -> String { + self.current_realtime_audio_device_name(kind) + .unwrap_or_else(|| "System default".to_string()) + } + + fn sync_fast_command_enabled(&mut self) { + self.bottom_pane + .set_fast_command_enabled(self.fast_mode_enabled()); + } + fn sync_personality_command_enabled(&mut self) { self.bottom_pane .set_personality_command_enabled(self.config.features.enabled(Feature::Personality)); @@ -6966,7 +7307,10 @@ impl ChatWidget { } pub(crate) fn add_mcp_output(&mut self) { - if self.config.mcp_servers.is_empty() { + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new( + self.config.codex_home.clone(), + ))); + if mcp_manager.effective_servers(&self.config, None).is_empty() { self.add_to_history(history_cell::empty_mcp_output()); } else { self.submit_op(Op::ListMcpTools); @@ -7338,6 +7682,11 @@ impl ChatWidget { self.bottom_pane.pending_thread_approvals() } + #[cfg(test)] + pub(crate) fn has_active_view(&self) -> bool { + self.bottom_pane.has_active_view() + } + pub(crate) fn show_esc_backtrack_hint(&mut self) { self.bottom_pane.show_esc_backtrack_hint(); } diff --git a/codex-rs/tui/src/chatwidget/agent.rs b/codex-rs/tui/src/chatwidget/agent.rs index 63d519a7a5..e14a9e3628 100644 --- a/codex-rs/tui/src/chatwidget/agent.rs +++ b/codex-rs/tui/src/chatwidget/agent.rs @@ -13,6 +13,17 @@ use tokio::sync::mpsc::unbounded_channel; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; +const TUI_NOTIFY_CLIENT: &str = "codex-tui"; + +async fn initialize_app_server_client_name(thread: &CodexThread) { + if let Err(err) = thread + .set_app_server_client_name(Some(TUI_NOTIFY_CLIENT.to_string())) + .await + { + tracing::error!("failed to set app server client name: {err}"); + } +} + /// Spawn the agent bootstrapper and op forwarding loop, returning the /// `UnboundedSender` used by the UI to submit operations. pub(crate) fn spawn_agent( @@ -42,6 +53,7 @@ pub(crate) fn spawn_agent( return; } }; + initialize_app_server_client_name(thread.as_ref()).await; // Forward the captured `SessionConfigured` event so it can be rendered in the UI. let ev = codex_protocol::protocol::Event { @@ -87,6 +99,8 @@ pub(crate) fn spawn_agent_from_existing( let app_event_tx_clone = app_event_tx; tokio::spawn(async move { + initialize_app_server_client_name(thread.as_ref()).await; + // Forward the captured `SessionConfigured` event so it can be rendered in the UI. let ev = codex_protocol::protocol::Event { id: "".to_string(), @@ -123,6 +137,7 @@ pub(crate) fn spawn_op_forwarder(thread: std::sync::Arc) -> Unbound let (codex_op_tx, mut codex_op_rx) = unbounded_channel::(); tokio::spawn(async move { + initialize_app_server_client_name(thread.as_ref()).await; while let Some(op) = codex_op_rx.recv().await { if let Err(e) = thread.submit(op).await { tracing::error!("failed to submit op: {e}"); diff --git a/codex-rs/tui/src/chatwidget/realtime.rs b/codex-rs/tui/src/chatwidget/realtime.rs index 2cf97188b3..2970ac4d3a 100644 --- a/codex-rs/tui/src/chatwidget/realtime.rs +++ b/codex-rs/tui/src/chatwidget/realtime.rs @@ -41,6 +41,10 @@ impl RealtimeConversationUiState { | RealtimeConversationPhase::Stopping ) } + + pub(super) fn is_active(&self) -> bool { + matches!(self.phase, RealtimeConversationPhase::Active) + } } #[derive(Clone, Debug, PartialEq)] @@ -179,12 +183,13 @@ impl ChatWidget { ev: RealtimeConversationRealtimeEvent, ) { match ev.payload { - RealtimeEvent::SessionCreated { session_id } => { + RealtimeEvent::SessionUpdated { session_id, .. } => { self.realtime_conversation.session_id = Some(session_id); } - RealtimeEvent::SessionUpdated { .. } => {} RealtimeEvent::AudioOut(frame) => self.enqueue_realtime_audio_out(&frame), RealtimeEvent::ConversationItemAdded(_item) => {} + RealtimeEvent::ConversationItemDone { .. } => {} + RealtimeEvent::HandoffRequested(_) => {} RealtimeEvent::Error(message) => { self.add_error_message(format!("Realtime voice error: {message}")); self.reset_realtime_conversation_state(); @@ -207,7 +212,7 @@ impl ChatWidget { { if self.realtime_conversation.audio_player.is_none() { self.realtime_conversation.audio_player = - crate::voice::RealtimeAudioPlayer::start().ok(); + crate::voice::RealtimeAudioPlayer::start(&self.config).ok(); } if let Some(player) = &self.realtime_conversation.audio_player && let Err(err) = player.enqueue_frame(frame) @@ -231,7 +236,10 @@ impl ChatWidget { self.realtime_conversation.meter_placeholder_id = Some(placeholder_id.clone()); self.request_redraw(); - let capture = match crate::voice::VoiceCapture::start_realtime(self.app_event_tx.clone()) { + let capture = match crate::voice::VoiceCapture::start_realtime( + &self.config, + self.app_event_tx.clone(), + ) { Ok(capture) => capture, Err(err) => { self.remove_transcription_placeholder(&placeholder_id); @@ -250,7 +258,7 @@ impl ChatWidget { self.realtime_conversation.capture = Some(capture); if self.realtime_conversation.audio_player.is_none() { self.realtime_conversation.audio_player = - crate::voice::RealtimeAudioPlayer::start().ok(); + crate::voice::RealtimeAudioPlayer::start(&self.config).ok(); } std::thread::spawn(move || { @@ -275,8 +283,50 @@ impl ChatWidget { #[cfg(target_os = "linux")] fn start_realtime_local_audio(&mut self) {} + #[cfg(all(not(target_os = "linux"), feature = "voice-input"))] + pub(crate) fn restart_realtime_audio_device(&mut self, kind: RealtimeAudioDeviceKind) { + if !self.realtime_conversation.is_active() { + return; + } + + match kind { + RealtimeAudioDeviceKind::Microphone => { + self.stop_realtime_microphone(); + self.start_realtime_local_audio(); + } + RealtimeAudioDeviceKind::Speaker => { + self.stop_realtime_speaker(); + match crate::voice::RealtimeAudioPlayer::start(&self.config) { + Ok(player) => { + self.realtime_conversation.audio_player = Some(player); + } + Err(err) => { + self.add_error_message(format!("Failed to start speaker output: {err}")); + } + } + } + } + self.request_redraw(); + } + + #[cfg(any(target_os = "linux", not(feature = "voice-input")))] + pub(crate) fn restart_realtime_audio_device(&mut self, kind: RealtimeAudioDeviceKind) { + let _ = kind; + } + #[cfg(not(target_os = "linux"))] fn stop_realtime_local_audio(&mut self) { + self.stop_realtime_microphone(); + self.stop_realtime_speaker(); + } + + #[cfg(target_os = "linux")] + fn stop_realtime_local_audio(&mut self) { + self.realtime_conversation.meter_placeholder_id = None; + } + + #[cfg(not(target_os = "linux"))] + fn stop_realtime_microphone(&mut self) { if let Some(flag) = self.realtime_conversation.capture_stop_flag.take() { flag.store(true, Ordering::Relaxed); } @@ -286,13 +336,12 @@ impl ChatWidget { if let Some(id) = self.realtime_conversation.meter_placeholder_id.take() { self.remove_transcription_placeholder(&id); } + } + + #[cfg(not(target_os = "linux"))] + fn stop_realtime_speaker(&mut self) { if let Some(player) = self.realtime_conversation.audio_player.take() { player.clear(); } } - - #[cfg(target_os = "linux")] - fn stop_realtime_local_audio(&mut self) { - self.realtime_conversation.meter_placeholder_id = None; - } } diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index a30e7954f3..efca42872b 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -191,7 +191,6 @@ fn protocol_skill_to_core(skill: &ProtocolSkillMetadata) -> SkillMetadata { }), policy: None, permission_profile: None, - permissions: None, path_to_skills_md: skill.path.clone(), scope: skill.scope, } diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap index 2147714e2e..9b5bb54b9f 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap @@ -5,12 +5,13 @@ expression: popup Select Model and Effort Access legacy models by running codex -m or in your config.toml -› 1. gpt-5.2-codex (default) Frontier agentic coding model. - 2. gpt-5.1-codex-max Codex-optimized flagship for deep and fast +› 1. gpt-5.3-codex (default) Latest frontier agentic coding model. + 2. gpt-5.2-codex Frontier agentic coding model. + 3. gpt-5.1-codex-max Codex-optimized flagship for deep and fast reasoning. - 3. gpt-5.2 Latest frontier model with improvements across + 4. gpt-5.2 Latest frontier model with improvements across knowledge, reasoning and coding - 4. gpt-5.1-codex-mini Optimized for codex. Cheaper, faster, but less + 5. gpt-5.1-codex-mini Optimized for codex. Cheaper, faster, but less capable. Press enter to select reasoning effort, or esc to dismiss. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__multi_agent_enable_prompt.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__multi_agent_enable_prompt.snap new file mode 100644 index 0000000000..ac25d9526c --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__multi_agent_enable_prompt.snap @@ -0,0 +1,12 @@ +--- +source: tui/src/chatwidget/tests.rs +assertion_line: 6001 +expression: popup +--- + Enable multi-agent? + Multi-agent is currently disabled in your config. + +› 1. Yes, enable Save the setting now. You will need a new session to use it. + 2. Not now Keep multi-agent disabled. + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_audio_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_audio_selection_popup.snap new file mode 100644 index 0000000000..8c60f961f9 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_audio_selection_popup.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Settings + Configure settings for Codex. + +› 1. Microphone Current: System default + 2. Speaker Current: System default + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_audio_selection_popup_narrow.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_audio_selection_popup_narrow.snap new file mode 100644 index 0000000000..8c60f961f9 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_audio_selection_popup_narrow.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Settings + Configure settings for Codex. + +› 1. Microphone Current: System default + 2. Speaker Current: System default + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_microphone_picker_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_microphone_picker_popup.snap new file mode 100644 index 0000000000..3095e6da97 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__realtime_microphone_picker_popup.snap @@ -0,0 +1,18 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Select Microphone + Saved devices apply to realtime voice only. + + 1. System default Use your operating system + default device. +› 2. Unavailable: Studio Mic (current) (disabled) Configured device is not + currently available. + (disabled: Reconnect the + device or choose another + one.) + 3. Built-in Mic + 4. USB Mic + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 22ba19af63..a720559b5c 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -7,6 +7,8 @@ use super::*; use crate::app_event::AppEvent; use crate::app_event::ExitMode; +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +use crate::app_event::RealtimeAudioDeviceKind; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::FeedbackAudience; use crate::bottom_pane::LocalImageAttachment; @@ -25,6 +27,7 @@ use codex_core::config::types::WindowsSandboxModeToml; use codex_core::config_loader::RequirementSource; use codex_core::features::FEATURES; use codex_core::features::Feature; +use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_core::models_manager::manager::ModelsManager; use codex_core::skills::model::SkillMetadata; use codex_core::terminal::TerminalName; @@ -35,6 +38,7 @@ use codex_protocol::account::PlanType; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Personality; +use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::Settings; use codex_protocol::items::AgentMessageContent; use codex_protocol::items::AgentMessageItem; @@ -157,6 +161,7 @@ async fn resumed_initial_messages_render_history() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -226,6 +231,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -285,6 +291,7 @@ async fn replayed_user_message_preserves_remote_image_urls() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -351,6 +358,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: expected_sandbox.clone(), cwd: expected_cwd.clone(), @@ -392,6 +400,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -443,6 +452,7 @@ async fn replayed_user_message_with_only_local_images_does_not_render_history_ce thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -553,6 +563,7 @@ async fn submission_preserves_text_elements_and_local_images() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -635,6 +646,7 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -728,6 +740,7 @@ async fn enter_with_only_remote_images_submits_user_turn() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -750,8 +763,8 @@ async fn enter_with_only_remote_images_submits_user_turn() { chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - let items = match next_submit_op(&mut op_rx) { - Op::UserTurn { items, .. } => items, + let (items, summary) = match next_submit_op(&mut op_rx) { + Op::UserTurn { items, summary, .. } => (items, summary), other => panic!("expected Op::UserTurn, got {other:?}"), }; assert_eq!( @@ -760,6 +773,7 @@ async fn enter_with_only_remote_images_submits_user_turn() { image_url: remote_url.clone(), }] ); + assert_eq!(summary, None); assert!(chat.remote_image_urls().is_empty()); let mut user_cell = None; @@ -790,6 +804,7 @@ async fn shift_enter_with_only_remote_images_does_not_submit_user_turn() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -828,6 +843,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_modal_is_active() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -866,6 +882,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -905,6 +922,7 @@ async fn submission_prefers_selected_duplicate_skill_path() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -932,7 +950,6 @@ async fn submission_prefers_selected_duplicate_skill_path() { dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: repo_skill_path, scope: SkillScope::Repo, }, @@ -944,7 +961,6 @@ async fn submission_prefers_selected_duplicate_skill_path() { dependencies: None, policy: None, permission_profile: None, - permissions: None, path_to_skills_md: user_skill_path.clone(), scope: SkillScope::User, }, @@ -1577,6 +1593,7 @@ async fn helpers_are_available_and_do_not_panic() { is_first_run: true, feedback_audience: FeedbackAudience::External, model: Some(resolved_model), + startup_tooltip_override: None, status_line_invalid_items_warned: Arc::new(AtomicBool::new(false)), otel_manager, }; @@ -1631,12 +1648,16 @@ async fn make_chatwidget_manual( animations_enabled: cfg.animations, skills: None, }); - bottom.set_steer_enabled(true); bottom.set_collaboration_modes_enabled(true); let auth_manager = codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("test")); let codex_home = cfg.codex_home.clone(); - let models_manager = Arc::new(ModelsManager::new(codex_home, auth_manager.clone(), None)); + let models_manager = Arc::new(ModelsManager::new( + codex_home, + auth_manager.clone(), + None, + CollaborationModesConfig::default(), + )); let reasoning_effort = None; let base_mode = CollaborationMode { mode: ModeKind::Default, @@ -1697,6 +1718,7 @@ async fn make_chatwidget_manual( forked_from: None, frame_requester: FrameRequester::test_dummy(), show_welcome_banner: true, + startup_tooltip_override: None, queued_user_messages: VecDeque::new(), queued_message_edit_binding: crate::key_hint::alt(KeyCode::Up), suppress_session_configured_redraw: false, @@ -1762,6 +1784,7 @@ fn set_chatgpt_auth(chat: &mut ChatWidget) { chat.config.codex_home.clone(), chat.auth_manager.clone(), None, + CollaborationModesConfig::default(), )); } @@ -2784,6 +2807,7 @@ async fn exec_approval_emits_proposed_command_and_decision_history() { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -2833,6 +2857,7 @@ async fn exec_approval_uses_approval_id_when_present() { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }), }); @@ -2841,7 +2866,11 @@ async fn exec_approval_uses_approval_id_when_present() { let mut found = false; while let Ok(app_ev) = rx.try_recv() { - if let AppEvent::CodexOp(Op::ExecApproval { id, decision, .. }) = app_ev { + if let AppEvent::SubmitThreadOp { + op: Op::ExecApproval { id, decision, .. }, + .. + } = app_ev + { assert_eq!(id, "approval-subcommand"); assert_matches!(decision, codex_protocol::protocol::ReviewDecision::Approved); found = true; @@ -2869,6 +2898,7 @@ async fn exec_approval_decision_truncates_multiline_and_long_commands() { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -2923,6 +2953,7 @@ async fn exec_approval_decision_truncates_multiline_and_long_commands() { proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -3428,7 +3459,7 @@ async fn unified_exec_begin_restores_working_status_snapshot() { } #[tokio::test] -async fn steer_enter_queues_while_plan_stream_is_active() { +async fn enter_queues_while_plan_stream_is_active() { let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.set_feature_enabled(Feature::CollaborationModes, true); @@ -3552,7 +3583,7 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() } #[tokio::test] -async fn steer_enter_submits_when_plan_stream_is_not_active() { +async fn enter_submits_when_plan_stream_is_not_active() { let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.set_feature_enabled(Feature::CollaborationModes, true); @@ -4407,6 +4438,7 @@ async fn plan_slash_command_with_args_submits_prompt_in_plan_mode() { thread_name: None, model: "test-model".to_string(), model_provider_id: "test-provider".to_string(), + service_tier: None, approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), cwd: PathBuf::from("/home/user/project"), @@ -4475,6 +4507,7 @@ async fn collaboration_modes_defaults_to_code_on_startup() { is_first_run: true, feedback_audience: FeedbackAudience::External, model: Some(resolved_model.clone()), + startup_tooltip_override: None, status_line_invalid_items_warned: Arc::new(AtomicBool::new(false)), otel_manager, }; @@ -4524,6 +4557,7 @@ async fn experimental_mode_plan_is_ignored_on_startup() { is_first_run: true, feedback_audience: FeedbackAudience::External, model: Some(resolved_model.clone()), + startup_tooltip_override: None, status_line_invalid_items_warned: Arc::new(AtomicBool::new(false)), otel_manager, }; @@ -5970,6 +6004,35 @@ async fn experimental_popup_shows_js_repl_node_requirement() { ); } +#[tokio::test] +async fn multi_agent_enable_prompt_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.open_multi_agent_enable_prompt(); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("multi_agent_enable_prompt", popup); +} + +#[tokio::test] +async fn multi_agent_enable_prompt_updates_feature_and_emits_notice() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + + chat.open_multi_agent_enable_prompt(); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert_matches!( + rx.try_recv(), + Ok(AppEvent::UpdateFeatureFlags { updates }) if updates == vec![(Feature::Collab, true)] + ); + let cell = match rx.try_recv() { + Ok(AppEvent::InsertHistoryCell(cell)) => cell, + other => panic!("expected InsertHistoryCell event, got {other:?}"), + }; + let rendered = lines_to_single_string(&cell.display_lines(120)); + assert!(rendered.contains("Multi-agent will be enabled in the next session.")); +} + #[tokio::test] async fn model_selection_popup_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5-codex")).await; @@ -5990,6 +6053,62 @@ async fn personality_selection_popup_snapshot() { assert_snapshot!("personality_selection_popup", popup); } +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +#[tokio::test] +async fn realtime_audio_selection_popup_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await; + chat.open_realtime_audio_popup(); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("realtime_audio_selection_popup", popup); +} + +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +#[tokio::test] +async fn realtime_audio_selection_popup_narrow_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await; + chat.open_realtime_audio_popup(); + + let popup = render_bottom_popup(&chat, 56); + assert_snapshot!("realtime_audio_selection_popup_narrow", popup); +} + +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +#[tokio::test] +async fn realtime_microphone_picker_popup_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await; + chat.config.realtime_audio.microphone = Some("Studio Mic".to_string()); + chat.open_realtime_audio_device_selection_with_names( + RealtimeAudioDeviceKind::Microphone, + vec!["Built-in Mic".to_string(), "USB Mic".to_string()], + ); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("realtime_microphone_picker_popup", popup); +} + +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +#[tokio::test] +async fn realtime_audio_picker_emits_persist_event() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await; + chat.open_realtime_audio_device_selection_with_names( + RealtimeAudioDeviceKind::Speaker, + vec!["Desk Speakers".to_string(), "Headphones".to_string()], + ); + + chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_matches!( + rx.try_recv(), + Ok(AppEvent::PersistRealtimeAudioDeviceSelection { + kind: RealtimeAudioDeviceKind::Speaker, + name: Some(name), + }) if name == "Headphones" + ); +} + #[tokio::test] async fn model_picker_hides_show_in_picker_false_models_from_cache() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("test-visible-model")).await; @@ -6008,6 +6127,7 @@ async fn model_picker_hides_show_in_picker_false_models_from_cache() { is_default: false, upgrade: None, show_in_picker, + availability_nux: None, supported_in_api: true, input_modalities: default_input_modalities(), }; @@ -6276,6 +6396,7 @@ async fn single_reasoning_option_skips_selection() { is_default: false, upgrade: None, show_in_picker: true, + availability_nux: None, supported_in_api: true, input_modalities: default_input_modalities(), }; @@ -6413,6 +6534,61 @@ async fn disabled_slash_command_while_task_running_snapshot() { assert_snapshot!(blob); } +#[tokio::test] +async fn fast_slash_command_updates_and_persists_local_service_tier() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.3-codex")).await; + chat.set_feature_enabled(Feature::FastMode, true); + + chat.dispatch_command(SlashCommand::Fast); + + let events = std::iter::from_fn(|| rx.try_recv().ok()).collect::>(); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::CodexOp(Op::OverrideTurnContext { + service_tier: Some(Some(ServiceTier::Fast)), + .. + }) + )), + "expected fast-mode override app event; events: {events:?}" + ); + assert!( + events.iter().any(|event| matches!( + event, + AppEvent::PersistServiceTierSelection { + service_tier: Some(ServiceTier::Fast), + } + )), + "expected fast-mode persistence app event; events: {events:?}" + ); + + assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty)); +} + +#[tokio::test] +async fn user_turn_carries_service_tier_after_fast_toggle() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.3-codex")).await; + chat.thread_id = Some(ThreadId::new()); + set_chatgpt_auth(&mut chat); + chat.set_feature_enabled(Feature::FastMode, true); + + chat.dispatch_command(SlashCommand::Fast); + + let _events = std::iter::from_fn(|| rx.try_recv().ok()).collect::>(); + + chat.bottom_pane + .set_composer_text("hello".to_string(), Vec::new(), Vec::new()); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + match next_submit_op(&mut op_rx) { + Op::UserTurn { + service_tier: Some(Some(ServiceTier::Fast)), + .. + } => {} + other => panic!("expected Op::UserTurn with fast service tier, got {other:?}"), + } +} + #[tokio::test] async fn approvals_popup_shows_disabled_presets() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; @@ -6742,6 +6918,7 @@ async fn approval_modal_exec_snapshot() -> anyhow::Result<()> { ])), proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -6802,6 +6979,7 @@ async fn approval_modal_exec_without_reason_snapshot() -> anyhow::Result<()> { ])), proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -6849,6 +7027,7 @@ async fn approval_modal_exec_multiline_prefix_hides_execpolicy_option_snapshot() proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)), proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -7215,6 +7394,7 @@ async fn status_widget_and_approval_modal_snapshot() { ])), proposed_network_policy_amendments: None, additional_permissions: None, + available_decisions: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -7558,10 +7738,14 @@ async fn apply_patch_approval_sends_op_with_call_id() { // Approve via key press 'y' chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - // Expect a CodexOp with PatchApproval carrying the call id. + // Expect a thread-scoped PatchApproval op carrying the call id. let mut found = false; while let Ok(app_ev) = rx.try_recv() { - if let AppEvent::CodexOp(Op::PatchApproval { id, decision }) = app_ev { + if let AppEvent::SubmitThreadOp { + op: Op::PatchApproval { id, decision }, + .. + } = app_ev + { assert_eq!(id, "call-999"); assert_matches!(decision, codex_protocol::protocol::ReviewDecision::Approved); found = true; @@ -7592,16 +7776,16 @@ async fn apply_patch_full_flow_integration_like() { }), }); - // 2) User approves via 'y' and App receives a CodexOp + // 2) User approves via 'y' and App receives a thread-scoped op chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); let mut maybe_op: Option = None; while let Ok(app_ev) = rx.try_recv() { - if let AppEvent::CodexOp(op) = app_ev { + if let AppEvent::SubmitThreadOp { op, .. } = app_ev { maybe_op = Some(op); break; } } - let op = maybe_op.expect("expected CodexOp after key press"); + let op = maybe_op.expect("expected thread-scoped op after key press"); // 3) App forwards to widget.submit_op, which pushes onto codex_op_tx chat.submit_op(op); diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 32591945fa..7d0ab018b8 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -14,6 +14,12 @@ //! palettes for truecolor / 256-color / 16-color terminals so add/delete lines //! remain visually distinct even when quantizing to limited palettes. //! +//! **Syntax-theme scope backgrounds:** when the active syntax theme defines +//! background colors for `markup.inserted` / `markup.deleted` (or fallback +//! `diff.inserted` / `diff.deleted`) scopes, those colors override the +//! hardcoded palette for rich color levels. ANSI-16 mode always uses +//! foreground-only styling regardless of theme scope backgrounds. +//! //! **Highlighting strategy for `Update` diffs:** the renderer highlights each //! hunk as a single concatenated block rather than line-by-line. This //! preserves syntect's parser state across consecutive lines within a hunk @@ -69,8 +75,11 @@ const LIGHT_256_DEL_NUM_BG_IDX: u8 = 217; const LIGHT_256_GUTTER_FG_IDX: u8 = 236; use crate::color::is_light; +use crate::color::perceptual_distance; use crate::exec_command::relativize_to_home; use crate::render::Insets; +use crate::render::highlight::DiffScopeBackgroundRgbs; +use crate::render::highlight::diff_scope_background_rgbs; use crate::render::highlight::exceeds_highlight_limits; use crate::render::highlight::highlight_code_to_styled_spans; use crate::render::line_utils::prefix_lines; @@ -78,11 +87,14 @@ use crate::render::renderable::ColumnRenderable; use crate::render::renderable::InsetRenderable; use crate::render::renderable::Renderable; use crate::terminal_palette::StdoutColorLevel; +use crate::terminal_palette::XTERM_COLORS; use crate::terminal_palette::default_bg; use crate::terminal_palette::indexed_color; use crate::terminal_palette::rgb_color; use crate::terminal_palette::stdout_color_level; use codex_core::git_info::get_git_repo_root; +use codex_core::terminal::TerminalName; +use codex_core::terminal::terminal_info; use codex_protocol::protocol::FileChange; /// Classifies a diff line for gutter sign rendering and style selection. @@ -104,12 +116,20 @@ pub(crate) enum DiffLineType { /// the terminal's queried background color. When the background cannot be /// determined (common in CI or piped output), `Dark` is used as the safe /// default. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] enum DiffTheme { Dark, Light, } +/// Palette depth the diff renderer will target. +/// +/// This is the *renderer's own* notion of color depth, derived from — but not +/// identical to — the raw [`StdoutColorLevel`] reported by `supports-color`. +/// The indirection exists because some terminals (notably Windows Terminal) +/// advertise only ANSI-16 support while actually rendering truecolor sequences +/// correctly; [`diff_color_level_for_terminal`] promotes those cases so the +/// diff output uses the richer palette. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum DiffColorLevel { TrueColor, @@ -117,6 +137,161 @@ enum DiffColorLevel { Ansi16, } +/// Subset of [`DiffColorLevel`] that supports tinted backgrounds. +/// +/// ANSI-16 terminals render backgrounds with bold, saturated palette entries +/// that overpower syntax tokens. This type encodes the invariant "we have +/// enough color depth for pastel tints" so that background-producing helpers +/// (`add_line_bg`, `del_line_bg`, `light_add_num_bg`, `light_del_num_bg`) +/// never need an unreachable ANSI-16 arm. +/// +/// Construct via [`RichDiffColorLevel::from_diff_color_level`], which returns +/// `None` for ANSI-16 — callers branch on the `Option` and skip backgrounds +/// entirely when `None`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RichDiffColorLevel { + TrueColor, + Ansi256, +} + +impl RichDiffColorLevel { + /// Extract a rich level, returning `None` for ANSI-16. + fn from_diff_color_level(level: DiffColorLevel) -> Option { + match level { + DiffColorLevel::TrueColor => Some(Self::TrueColor), + DiffColorLevel::Ansi256 => Some(Self::Ansi256), + DiffColorLevel::Ansi16 => None, + } + } +} + +/// Pre-resolved background colors for insert and delete diff lines. +/// +/// Computed once per `render_change` call from the active syntax theme's +/// scope backgrounds (via [`resolve_diff_backgrounds`]) and then threaded +/// through every style helper so individual lines never re-query the theme. +/// +/// Both fields are `None` when the color level is ANSI-16 — callers fall +/// back to foreground-only styling in that case. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct ResolvedDiffBackgrounds { + add: Option, + del: Option, +} + +/// Precomputed render state for diff line styling. +/// +/// This bundles the terminal-derived theme and color depth plus theme-resolved +/// diff backgrounds so callers rendering many lines can compute once per render +/// pass and reuse it across all line calls. +#[derive(Clone, Copy, Debug)] +pub(crate) struct DiffRenderStyleContext { + theme: DiffTheme, + color_level: DiffColorLevel, + diff_backgrounds: ResolvedDiffBackgrounds, +} + +/// Resolve diff backgrounds for production rendering. +/// +/// Queries the active syntax theme for `markup.inserted` / `markup.deleted` +/// (and `diff.*` fallbacks), then delegates to [`resolve_diff_backgrounds_for`]. +fn resolve_diff_backgrounds( + theme: DiffTheme, + color_level: DiffColorLevel, +) -> ResolvedDiffBackgrounds { + resolve_diff_backgrounds_for(theme, color_level, diff_scope_background_rgbs()) +} + +/// Snapshot the current terminal environment into a reusable style context. +/// +/// Queries `diff_theme`, `diff_color_level`, and the active syntax theme's +/// scope backgrounds once, bundling them into a [`DiffRenderStyleContext`] +/// that callers thread through every line-rendering call in a single pass. +/// +/// Call this at the top of each render frame — not per line — so the diff +/// palette stays consistent within a frame even if the user swaps themes +/// mid-render (theme picker live preview). +pub(crate) fn current_diff_render_style_context() -> DiffRenderStyleContext { + let theme = diff_theme(); + let color_level = diff_color_level(); + let diff_backgrounds = resolve_diff_backgrounds(theme, color_level); + DiffRenderStyleContext { + theme, + color_level, + diff_backgrounds, + } +} + +/// Core background-resolution logic, kept pure for testability. +/// +/// Starts from the hardcoded fallback palette and then overrides with theme +/// scope backgrounds when both (a) the color level is rich enough and (b) the +/// theme defines a matching scope. This means the fallback palette is always +/// the baseline and theme scopes are strictly additive. +fn resolve_diff_backgrounds_for( + theme: DiffTheme, + color_level: DiffColorLevel, + scope_backgrounds: DiffScopeBackgroundRgbs, +) -> ResolvedDiffBackgrounds { + let mut resolved = fallback_diff_backgrounds(theme, color_level); + let Some(level) = RichDiffColorLevel::from_diff_color_level(color_level) else { + return resolved; + }; + + if let Some(rgb) = scope_backgrounds.inserted { + resolved.add = Some(color_from_rgb_for_level(rgb, level)); + } + if let Some(rgb) = scope_backgrounds.deleted { + resolved.del = Some(color_from_rgb_for_level(rgb, level)); + } + resolved +} + +/// Hardcoded palette backgrounds, used when the syntax theme provides no +/// diff-specific scope backgrounds. Returns empty backgrounds for ANSI-16. +fn fallback_diff_backgrounds( + theme: DiffTheme, + color_level: DiffColorLevel, +) -> ResolvedDiffBackgrounds { + match RichDiffColorLevel::from_diff_color_level(color_level) { + Some(level) => ResolvedDiffBackgrounds { + add: Some(add_line_bg(theme, level)), + del: Some(del_line_bg(theme, level)), + }, + None => ResolvedDiffBackgrounds::default(), + } +} + +/// Convert an RGB triple to the appropriate ratatui `Color` for the given +/// rich color level — passthrough for truecolor, quantized for ANSI-256. +fn color_from_rgb_for_level(rgb: (u8, u8, u8), color_level: RichDiffColorLevel) -> Color { + match color_level { + RichDiffColorLevel::TrueColor => rgb_color(rgb), + RichDiffColorLevel::Ansi256 => quantize_rgb_to_ansi256(rgb), + } +} + +/// Find the closest ANSI-256 color (indices 16–255) to `target` using +/// perceptual distance. +/// +/// Skips the first 16 entries (system colors) because their actual RGB +/// values depend on the user's terminal configuration and are unreliable +/// for distance calculations. +fn quantize_rgb_to_ansi256(target: (u8, u8, u8)) -> Color { + let best_index = XTERM_COLORS + .iter() + .enumerate() + .skip(16) + .min_by(|(_, a), (_, b)| { + perceptual_distance(**a, target).total_cmp(&perceptual_distance(**b, target)) + }) + .map(|(index, _)| index as u8); + match best_index { + Some(index) => indexed_color(index), + None => indexed_color(DARK_256_ADD_LINE_BG_IDX), + } +} + pub struct DiffSummary { changes: HashMap, cwd: PathBuf, @@ -300,8 +475,7 @@ fn render_change( width: usize, lang: Option<&str>, ) { - let theme = diff_theme(); - let color_level = diff_color_level(); + let style_context = current_diff_render_style_context(); match change { FileChange::Add { content } => { // Pre-highlight the entire file content as a whole. @@ -317,8 +491,9 @@ fn render_change( width, line_number_width, Some(spans), - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, )); } else { out.extend(push_wrapped_diff_line_inner_with_theme_and_color_level( @@ -328,8 +503,9 @@ fn render_change( width, line_number_width, None, - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, )); } } @@ -347,8 +523,9 @@ fn render_change( width, line_number_width, Some(spans), - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, )); } else { out.extend(push_wrapped_diff_line_inner_with_theme_and_color_level( @@ -358,8 +535,9 @@ fn render_change( width, line_number_width, None, - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, )); } } @@ -414,7 +592,11 @@ fn render_change( let spacer = format!("{:width$} ", "", width = line_number_width.max(1)); let spacer_span = RtSpan::styled( spacer, - style_gutter_for(DiffLineType::Context, theme, color_level), + style_gutter_for( + DiffLineType::Context, + style_context.theme, + style_context.color_level, + ), ); out.push(RtLine::from(vec![spacer_span, "⋮".dim()])); } @@ -454,8 +636,9 @@ fn render_change( width, line_number_width, Some(syn), - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ), ); } else { @@ -467,8 +650,9 @@ fn render_change( width, line_number_width, None, - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ), ); } @@ -485,8 +669,9 @@ fn render_change( width, line_number_width, Some(syn), - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ), ); } else { @@ -498,8 +683,9 @@ fn render_change( width, line_number_width, None, - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ), ); } @@ -516,8 +702,9 @@ fn render_change( width, line_number_width, Some(syn), - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ), ); } else { @@ -529,8 +716,9 @@ fn render_change( width, line_number_width, None, - theme, - color_level, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ), ); } @@ -588,74 +776,19 @@ pub(crate) fn calculate_add_remove_from_diff(diff: &str) -> (usize, usize) { } } -/// Render a single diff line (no syntax highlighting) as one or more wrapped -/// ratatui `Line`s. The first output line carries the gutter sign; continuation -/// lines are indented under the line number column. -pub(crate) fn push_wrapped_diff_line( - line_number: usize, - kind: DiffLineType, - text: &str, - width: usize, - line_number_width: usize, -) -> Vec> { - push_wrapped_diff_line_inner(line_number, kind, text, width, line_number_width, None) -} - -/// Render a single diff line with pre-computed syntax spans. The sign character -/// uses the diff color; content gets syntax colors with a dim overlay for delete -/// lines. -pub(crate) fn push_wrapped_diff_line_with_syntax( - line_number: usize, - kind: DiffLineType, - text: &str, - width: usize, - line_number_width: usize, - syntax_spans: &[RtSpan<'static>], -) -> Vec> { - push_wrapped_diff_line_inner( - line_number, - kind, - text, - width, - line_number_width, - Some(syntax_spans), - ) -} - -fn push_wrapped_diff_line_inner( - line_number: usize, - kind: DiffLineType, - text: &str, - width: usize, - line_number_width: usize, - syntax_spans: Option<&[RtSpan<'static>]>, -) -> Vec> { - push_wrapped_diff_line_inner_with_theme( - line_number, - kind, - text, - width, - line_number_width, - syntax_spans, - diff_theme(), - ) -} - -/// Core line renderer: builds one or more wrapped `RtLine`s for a single diff -/// line, applying gutter, sign, content, and full-width background styles -/// according to the given `theme`. +/// Render a single plain-text (non-syntax-highlighted) diff line, wrapped to +/// `width` columns, using a pre-computed [`DiffRenderStyleContext`]. /// -/// Split out from `push_wrapped_diff_line_inner` so that tests can exercise -/// specific `DiffTheme` variants without depending on the terminal's queried -/// background. -fn push_wrapped_diff_line_inner_with_theme( +/// This is the convenience entry point used by the theme picker preview and +/// any caller that does not have syntax spans. Delegates to the inner +/// rendering core with `syntax_spans = None`. +pub(crate) fn push_wrapped_diff_line_with_style_context( line_number: usize, kind: DiffLineType, text: &str, width: usize, line_number_width: usize, - syntax_spans: Option<&[RtSpan<'static>]>, - theme: DiffTheme, + style_context: DiffRenderStyleContext, ) -> Vec> { push_wrapped_diff_line_inner_with_theme_and_color_level( line_number, @@ -663,9 +796,39 @@ fn push_wrapped_diff_line_inner_with_theme( text, width, line_number_width, - syntax_spans, - theme, - diff_color_level(), + None, + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, + ) +} + +/// Render a syntax-highlighted diff line, wrapped to `width` columns, using +/// a pre-computed [`DiffRenderStyleContext`]. +/// +/// Like [`push_wrapped_diff_line_with_style_context`] but overlays +/// `syntax_spans` (from [`highlight_code_to_styled_spans`]) onto the diff +/// coloring. Delete lines receive a `DIM` modifier so syntax colors do not +/// overpower the removal cue. +pub(crate) fn push_wrapped_diff_line_with_syntax_and_style_context( + line_number: usize, + kind: DiffLineType, + text: &str, + width: usize, + line_number_width: usize, + syntax_spans: &[RtSpan<'static>], + style_context: DiffRenderStyleContext, +) -> Vec> { + push_wrapped_diff_line_inner_with_theme_and_color_level( + line_number, + kind, + text, + width, + line_number_width, + Some(syntax_spans), + style_context.theme, + style_context.color_level, + style_context.diff_backgrounds, ) } @@ -679,6 +842,7 @@ fn push_wrapped_diff_line_inner_with_theme_and_color_level( syntax_spans: Option<&[RtSpan<'static>]>, theme: DiffTheme, color_level: DiffColorLevel, + diff_backgrounds: ResolvedDiffBackgrounds, ) -> Vec> { let ln_str = line_number.to_string(); @@ -690,18 +854,18 @@ fn push_wrapped_diff_line_inner_with_theme_and_color_level( let (sign_char, sign_style, content_style) = match kind { DiffLineType::Insert => ( '+', - style_sign_add(theme, color_level), - style_add(theme, color_level), + style_sign_add(theme, color_level, diff_backgrounds), + style_add(theme, color_level, diff_backgrounds), ), DiffLineType::Delete => ( '-', - style_sign_del(theme, color_level), - style_del(theme, color_level), + style_sign_del(theme, color_level, diff_backgrounds), + style_del(theme, color_level, diff_backgrounds), ), DiffLineType::Context => (' ', style_context(), style_context()), }; - let line_bg = style_line_bg_for(kind, theme, color_level); + let line_bg = style_line_bg_for(kind, diff_backgrounds); let gutter_style = style_gutter_for(kind, theme, color_level); // When we have syntax spans, compose them with the diff style for a richer @@ -876,11 +1040,75 @@ fn diff_theme() -> DiffTheme { diff_theme_for_bg(default_bg()) } +/// Return the [`DiffColorLevel`] for the current terminal session. +/// +/// This is the environment-reading adapter: it samples runtime signals +/// (`supports-color` level, terminal name, `WT_SESSION`, and `FORCE_COLOR`) +/// and forwards them to [`diff_color_level_for_terminal`]. +/// +/// Keeping env reads in this thin wrapper lets +/// [`diff_color_level_for_terminal`] stay pure and easy to unit test. fn diff_color_level() -> DiffColorLevel { - match stdout_color_level() { + diff_color_level_for_terminal( + stdout_color_level(), + terminal_info().name, + std::env::var_os("WT_SESSION").is_some(), + has_force_color_override(), + ) +} + +/// Returns whether `FORCE_COLOR` is explicitly set. +fn has_force_color_override() -> bool { + std::env::var_os("FORCE_COLOR").is_some() +} + +/// Map a raw [`StdoutColorLevel`] to a [`DiffColorLevel`] using +/// Windows Terminal-specific truecolor promotion rules. +/// +/// This helper is intentionally pure (no env access) so tests can validate +/// the policy table by passing explicit inputs. +/// +/// Windows Terminal fully supports 24-bit color but the `supports-color` +/// crate often reports only ANSI-16 there because no `COLORTERM` variable +/// is set. We detect Windows Terminal two ways — via `terminal_name` +/// (parsed from `WT_SESSION` / `TERM_PROGRAM` by `terminal_info()`) and +/// via the raw `has_wt_session` flag. +/// +/// These signals are intentionally not equivalent: `terminal_name` is a +/// derived classification with `TERM_PROGRAM` precedence, so `WT_SESSION` +/// can be present while `terminal_name` is not `WindowsTerminal`. +/// +/// When `WT_SESSION` is present, we promote to truecolor unconditionally +/// unless `FORCE_COLOR` is set. This keeps Windows Terminal rendering rich +/// by default while preserving explicit `FORCE_COLOR` user intent. +/// +/// Outside `WT_SESSION`, only ANSI-16 is promoted for identified +/// `WindowsTerminal` sessions; `Unknown` stays conservative. +fn diff_color_level_for_terminal( + stdout_level: StdoutColorLevel, + terminal_name: TerminalName, + has_wt_session: bool, + has_force_color_override: bool, +) -> DiffColorLevel { + if has_wt_session && !has_force_color_override { + return DiffColorLevel::TrueColor; + } + + let base = match stdout_level { StdoutColorLevel::TrueColor => DiffColorLevel::TrueColor, StdoutColorLevel::Ansi256 => DiffColorLevel::Ansi256, StdoutColorLevel::Ansi16 | StdoutColorLevel::Unknown => DiffColorLevel::Ansi16, + }; + + // Outside `WT_SESSION`, keep the existing Windows Terminal promotion for + // ANSI-16 sessions that likely support truecolor. + if stdout_level == StdoutColorLevel::Ansi16 + && terminal_name == TerminalName::WindowsTerminal + && !has_force_color_override + { + DiffColorLevel::TrueColor + } else { + base } } @@ -907,10 +1135,14 @@ fn diff_color_level() -> DiffColorLevel { /// Full-width background applied to the `RtLine` itself (not individual spans). /// Context lines intentionally leave the background unset so the terminal /// default shows through. -fn style_line_bg_for(kind: DiffLineType, theme: DiffTheme, color_level: DiffColorLevel) -> Style { +fn style_line_bg_for(kind: DiffLineType, diff_backgrounds: ResolvedDiffBackgrounds) -> Style { match kind { - DiffLineType::Insert => Style::default().bg(add_line_bg(theme, color_level)), - DiffLineType::Delete => Style::default().bg(del_line_bg(theme, color_level)), + DiffLineType::Insert => diff_backgrounds + .add + .map_or_else(Style::default, |bg| Style::default().bg(bg)), + DiffLineType::Delete => diff_backgrounds + .del + .map_or_else(Style::default, |bg| Style::default().bg(bg)), DiffLineType::Context => Style::default(), } } @@ -919,25 +1151,21 @@ fn style_context() -> Style { Style::default() } -fn add_line_bg(theme: DiffTheme, color_level: DiffColorLevel) -> Color { +fn add_line_bg(theme: DiffTheme, color_level: RichDiffColorLevel) -> Color { match (theme, color_level) { - (DiffTheme::Dark, DiffColorLevel::TrueColor) => rgb_color(DARK_TC_ADD_LINE_BG_RGB), - (DiffTheme::Dark, DiffColorLevel::Ansi256) => indexed_color(DARK_256_ADD_LINE_BG_IDX), - (DiffTheme::Dark, DiffColorLevel::Ansi16) => Color::Green, - (DiffTheme::Light, DiffColorLevel::TrueColor) => rgb_color(LIGHT_TC_ADD_LINE_BG_RGB), - (DiffTheme::Light, DiffColorLevel::Ansi256) => indexed_color(LIGHT_256_ADD_LINE_BG_IDX), - (DiffTheme::Light, DiffColorLevel::Ansi16) => Color::LightGreen, + (DiffTheme::Dark, RichDiffColorLevel::TrueColor) => rgb_color(DARK_TC_ADD_LINE_BG_RGB), + (DiffTheme::Dark, RichDiffColorLevel::Ansi256) => indexed_color(DARK_256_ADD_LINE_BG_IDX), + (DiffTheme::Light, RichDiffColorLevel::TrueColor) => rgb_color(LIGHT_TC_ADD_LINE_BG_RGB), + (DiffTheme::Light, RichDiffColorLevel::Ansi256) => indexed_color(LIGHT_256_ADD_LINE_BG_IDX), } } -fn del_line_bg(theme: DiffTheme, color_level: DiffColorLevel) -> Color { +fn del_line_bg(theme: DiffTheme, color_level: RichDiffColorLevel) -> Color { match (theme, color_level) { - (DiffTheme::Dark, DiffColorLevel::TrueColor) => rgb_color(DARK_TC_DEL_LINE_BG_RGB), - (DiffTheme::Dark, DiffColorLevel::Ansi256) => indexed_color(DARK_256_DEL_LINE_BG_IDX), - (DiffTheme::Dark, DiffColorLevel::Ansi16) => Color::Red, - (DiffTheme::Light, DiffColorLevel::TrueColor) => rgb_color(LIGHT_TC_DEL_LINE_BG_RGB), - (DiffTheme::Light, DiffColorLevel::Ansi256) => indexed_color(LIGHT_256_DEL_LINE_BG_IDX), - (DiffTheme::Light, DiffColorLevel::Ansi16) => Color::LightRed, + (DiffTheme::Dark, RichDiffColorLevel::TrueColor) => rgb_color(DARK_TC_DEL_LINE_BG_RGB), + (DiffTheme::Dark, RichDiffColorLevel::Ansi256) => indexed_color(DARK_256_DEL_LINE_BG_IDX), + (DiffTheme::Light, RichDiffColorLevel::TrueColor) => rgb_color(LIGHT_TC_DEL_LINE_BG_RGB), + (DiffTheme::Light, RichDiffColorLevel::Ansi256) => indexed_color(LIGHT_256_DEL_LINE_BG_IDX), } } @@ -949,19 +1177,17 @@ fn light_gutter_fg(color_level: DiffColorLevel) -> Color { } } -fn light_add_num_bg(color_level: DiffColorLevel) -> Color { +fn light_add_num_bg(color_level: RichDiffColorLevel) -> Color { match color_level { - DiffColorLevel::TrueColor => rgb_color(LIGHT_TC_ADD_NUM_BG_RGB), - DiffColorLevel::Ansi256 => indexed_color(LIGHT_256_ADD_NUM_BG_IDX), - DiffColorLevel::Ansi16 => Color::Green, + RichDiffColorLevel::TrueColor => rgb_color(LIGHT_TC_ADD_NUM_BG_RGB), + RichDiffColorLevel::Ansi256 => indexed_color(LIGHT_256_ADD_NUM_BG_IDX), } } -fn light_del_num_bg(color_level: DiffColorLevel) -> Color { +fn light_del_num_bg(color_level: RichDiffColorLevel) -> Color { match color_level { - DiffColorLevel::TrueColor => rgb_color(LIGHT_TC_DEL_NUM_BG_RGB), - DiffColorLevel::Ansi256 => indexed_color(LIGHT_256_DEL_NUM_BG_IDX), - DiffColorLevel::Ansi16 => Color::Red, + RichDiffColorLevel::TrueColor => rgb_color(LIGHT_TC_DEL_NUM_BG_RGB), + RichDiffColorLevel::Ansi256 => indexed_color(LIGHT_256_DEL_NUM_BG_IDX), } } @@ -969,13 +1195,23 @@ fn light_del_num_bg(color_level: DiffColorLevel) -> Color { /// tinted background so numbers contrast against the pastel line fill. On /// dark backgrounds a simple `DIM` modifier is sufficient. fn style_gutter_for(kind: DiffLineType, theme: DiffTheme, color_level: DiffColorLevel) -> Style { - match (theme, kind) { - (DiffTheme::Light, DiffLineType::Insert) => Style::default() + match ( + theme, + kind, + RichDiffColorLevel::from_diff_color_level(color_level), + ) { + (DiffTheme::Light, DiffLineType::Insert, None) => { + Style::default().fg(light_gutter_fg(color_level)) + } + (DiffTheme::Light, DiffLineType::Delete, None) => { + Style::default().fg(light_gutter_fg(color_level)) + } + (DiffTheme::Light, DiffLineType::Insert, Some(level)) => Style::default() .fg(light_gutter_fg(color_level)) - .bg(light_add_num_bg(color_level)), - (DiffTheme::Light, DiffLineType::Delete) => Style::default() + .bg(light_add_num_bg(level)), + (DiffTheme::Light, DiffLineType::Delete, Some(level)) => Style::default() .fg(light_gutter_fg(color_level)) - .bg(light_del_num_bg(color_level)), + .bg(light_del_num_bg(level)), _ => style_gutter_dim(), } } @@ -983,44 +1219,81 @@ fn style_gutter_for(kind: DiffLineType, theme: DiffTheme, color_level: DiffColor /// Sign character (`+`) for insert lines. On dark terminals it inherits the /// full content style (green fg + tinted bg). On light terminals it uses only /// a green foreground and lets the line-level bg show through. -fn style_sign_add(theme: DiffTheme, color_level: DiffColorLevel) -> Style { +fn style_sign_add( + theme: DiffTheme, + color_level: DiffColorLevel, + diff_backgrounds: ResolvedDiffBackgrounds, +) -> Style { match theme { DiffTheme::Light => Style::default().fg(Color::Green), - DiffTheme::Dark => style_add(theme, color_level), + DiffTheme::Dark => style_add(theme, color_level, diff_backgrounds), } } /// Sign character (`-`) for delete lines. Mirror of [`style_sign_add`]. -fn style_sign_del(theme: DiffTheme, color_level: DiffColorLevel) -> Style { +fn style_sign_del( + theme: DiffTheme, + color_level: DiffColorLevel, + diff_backgrounds: ResolvedDiffBackgrounds, +) -> Style { match theme { DiffTheme::Light => Style::default().fg(Color::Red), - DiffTheme::Dark => style_del(theme, color_level), + DiffTheme::Dark => style_del(theme, color_level, diff_backgrounds), } } /// Content style for insert lines (plain, non-syntax-highlighted text). -fn style_add(theme: DiffTheme, color_level: DiffColorLevel) -> Style { - match (theme, color_level) { - (DiffTheme::Dark, DiffColorLevel::Ansi16) => Style::default() - .fg(Color::Black) - .bg(add_line_bg(theme, color_level)), - (DiffTheme::Light, _) => Style::default().bg(add_line_bg(theme, color_level)), - (DiffTheme::Dark, _) => Style::default() - .fg(Color::Green) - .bg(add_line_bg(theme, color_level)), +/// +/// Foreground-only on ANSI-16. On rich levels, uses the pre-resolved +/// background from `diff_backgrounds` — which is the theme scope color when +/// available, or the hardcoded palette otherwise. Dark themes add an +/// explicit green foreground for readability over the tinted background; +/// light themes rely on the default (dark) foreground against the pastel. +/// +/// When no background is resolved (e.g. a theme that defines no diff +/// scopes and the fallback palette is somehow empty), the style degrades +/// to foreground-only so the line is still legible. +fn style_add( + theme: DiffTheme, + color_level: DiffColorLevel, + diff_backgrounds: ResolvedDiffBackgrounds, +) -> Style { + match (theme, color_level, diff_backgrounds.add) { + (_, DiffColorLevel::Ansi16, _) => Style::default().fg(Color::Green), + (DiffTheme::Light, DiffColorLevel::TrueColor, Some(bg)) + | (DiffTheme::Light, DiffColorLevel::Ansi256, Some(bg)) => Style::default().bg(bg), + (DiffTheme::Dark, DiffColorLevel::TrueColor, Some(bg)) + | (DiffTheme::Dark, DiffColorLevel::Ansi256, Some(bg)) => { + Style::default().fg(Color::Green).bg(bg) + } + (DiffTheme::Light, DiffColorLevel::TrueColor, None) + | (DiffTheme::Light, DiffColorLevel::Ansi256, None) => Style::default(), + (DiffTheme::Dark, DiffColorLevel::TrueColor, None) + | (DiffTheme::Dark, DiffColorLevel::Ansi256, None) => Style::default().fg(Color::Green), } } /// Content style for delete lines (plain, non-syntax-highlighted text). -fn style_del(theme: DiffTheme, color_level: DiffColorLevel) -> Style { - match (theme, color_level) { - (DiffTheme::Dark, DiffColorLevel::Ansi16) => Style::default() - .fg(Color::Black) - .bg(del_line_bg(theme, color_level)), - (DiffTheme::Light, _) => Style::default().bg(del_line_bg(theme, color_level)), - (DiffTheme::Dark, _) => Style::default() - .fg(Color::Red) - .bg(del_line_bg(theme, color_level)), +/// +/// Mirror of [`style_add`] with red foreground and the delete-side +/// resolved background. +fn style_del( + theme: DiffTheme, + color_level: DiffColorLevel, + diff_backgrounds: ResolvedDiffBackgrounds, +) -> Style { + match (theme, color_level, diff_backgrounds.del) { + (_, DiffColorLevel::Ansi16, _) => Style::default().fg(Color::Red), + (DiffTheme::Light, DiffColorLevel::TrueColor, Some(bg)) + | (DiffTheme::Light, DiffColorLevel::Ansi256, Some(bg)) => Style::default().bg(bg), + (DiffTheme::Dark, DiffColorLevel::TrueColor, Some(bg)) + | (DiffTheme::Dark, DiffColorLevel::Ansi256, Some(bg)) => { + Style::default().fg(Color::Red).bg(bg) + } + (DiffTheme::Light, DiffColorLevel::TrueColor, None) + | (DiffTheme::Light, DiffColorLevel::Ansi256, None) => Style::default(), + (DiffTheme::Dark, DiffColorLevel::TrueColor, None) + | (DiffTheme::Dark, DiffColorLevel::Ansi256, None) => Style::default().fg(Color::Red), } } @@ -1037,37 +1310,49 @@ mod tests { use ratatui::backend::TestBackend; use ratatui::text::Text; use ratatui::widgets::Paragraph; - - #[test] - fn dark_ansi16_add_style_has_contrast() { - let style = style_add(DiffTheme::Dark, DiffColorLevel::Ansi16); - assert_eq!(style.fg, Some(Color::Black)); - assert_eq!(style.bg, Some(Color::Green)); - assert_ne!(style.fg, style.bg); - } - - #[test] - fn dark_ansi16_del_style_has_contrast() { - let style = style_del(DiffTheme::Dark, DiffColorLevel::Ansi16); - assert_eq!(style.fg, Some(Color::Black)); - assert_eq!(style.bg, Some(Color::Red)); - assert_ne!(style.fg, style.bg); - } - - #[test] - fn dark_ansi16_sign_styles_have_contrast() { - let add_sign = style_sign_add(DiffTheme::Dark, DiffColorLevel::Ansi16); - assert_eq!(add_sign.fg, Some(Color::Black)); - assert_eq!(add_sign.bg, Some(Color::Green)); - assert_ne!(add_sign.fg, add_sign.bg); - - let del_sign = style_sign_del(DiffTheme::Dark, DiffColorLevel::Ansi16); - assert_eq!(del_sign.fg, Some(Color::Black)); - assert_eq!(del_sign.bg, Some(Color::Red)); - assert_ne!(del_sign.fg, del_sign.bg); - } use ratatui::widgets::WidgetRef; use ratatui::widgets::Wrap; + + #[test] + fn ansi16_add_style_uses_foreground_only() { + let style = style_add( + DiffTheme::Dark, + DiffColorLevel::Ansi16, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16), + ); + assert_eq!(style.fg, Some(Color::Green)); + assert_eq!(style.bg, None); + } + + #[test] + fn ansi16_del_style_uses_foreground_only() { + let style = style_del( + DiffTheme::Dark, + DiffColorLevel::Ansi16, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16), + ); + assert_eq!(style.fg, Some(Color::Red)); + assert_eq!(style.bg, None); + } + + #[test] + fn ansi16_sign_styles_use_foreground_only() { + let add_sign = style_sign_add( + DiffTheme::Dark, + DiffColorLevel::Ansi16, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16), + ); + assert_eq!(add_sign.fg, Some(Color::Green)); + assert_eq!(add_sign.bg, None); + + let del_sign = style_sign_del( + DiffTheme::Dark, + DiffColorLevel::Ansi16, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16), + ); + assert_eq!(del_sign.fg, Some(Color::Red)); + assert_eq!(del_sign.bg, None); + } fn diff_summary_for_tests(changes: &HashMap) -> Vec> { create_diff_summary(changes, &PathBuf::from("/"), 80) } @@ -1205,8 +1490,14 @@ mod tests { let long_line = "this is a very long line that should wrap across multiple terminal columns and continue"; // Call the wrapping function directly so we can precisely control the width - let lines = - push_wrapped_diff_line(1, DiffLineType::Insert, long_line, 80, line_number_width(1)); + let lines = push_wrapped_diff_line_with_style_context( + 1, + DiffLineType::Insert, + long_line, + 80, + line_number_width(1), + current_diff_render_style_context(), + ); // Render into a small terminal to capture the visual layout snapshot_lines("wrap_behavior_insert", lines, 90, 8); @@ -1413,13 +1704,14 @@ mod tests { highlight_code_to_styled_spans(long_rust, "rust").expect("rust highlighting"); let spans = &syntax_spans[0]; - let lines = push_wrapped_diff_line_with_syntax( + let lines = push_wrapped_diff_line_with_syntax_and_style_context( 1, DiffLineType::Insert, long_rust, 80, line_number_width(1), spans, + current_diff_render_style_context(), ); assert!( @@ -1439,13 +1731,14 @@ mod tests { highlight_code_to_styled_spans(long_rust, "rust").expect("rust highlighting"); let spans = &syntax_spans[0]; - let lines = push_wrapped_diff_line_with_syntax( + let lines = push_wrapped_diff_line_with_syntax_and_style_context( 1, DiffLineType::Insert, long_rust, 80, line_number_width(1), spans, + current_diff_render_style_context(), ); snapshot_lines_text("syntax_highlighted_insert_wraps_text", &lines); @@ -1466,21 +1759,47 @@ mod tests { snapshot_diff_gallery("diff_gallery_120x40", 120, 40); } + #[test] + fn ui_snapshot_ansi16_insert_delete_no_background() { + let mut lines = push_wrapped_diff_line_inner_with_theme_and_color_level( + 1, + DiffLineType::Insert, + "added in ansi16 mode", + 80, + line_number_width(2), + None, + DiffTheme::Dark, + DiffColorLevel::Ansi16, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16), + ); + lines.extend(push_wrapped_diff_line_inner_with_theme_and_color_level( + 2, + DiffLineType::Delete, + "deleted in ansi16 mode", + 80, + line_number_width(2), + None, + DiffTheme::Dark, + DiffColorLevel::Ansi16, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16), + )); + + snapshot_lines("ansi16_insert_delete_no_background", lines, 40, 4); + } + #[test] fn truecolor_dark_theme_uses_configured_backgrounds() { assert_eq!( style_line_bg_for( DiffLineType::Insert, - DiffTheme::Dark, - DiffColorLevel::TrueColor + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::TrueColor) ), Style::default().bg(rgb_color(DARK_TC_ADD_LINE_BG_RGB)) ); assert_eq!( style_line_bg_for( DiffLineType::Delete, - DiffTheme::Dark, - DiffColorLevel::TrueColor + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::TrueColor) ), Style::default().bg(rgb_color(DARK_TC_DEL_LINE_BG_RGB)) ); @@ -1507,49 +1826,151 @@ mod tests { assert_eq!( style_line_bg_for( DiffLineType::Insert, - DiffTheme::Dark, - DiffColorLevel::Ansi256 + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi256) ), Style::default().bg(indexed_color(DARK_256_ADD_LINE_BG_IDX)) ); assert_eq!( style_line_bg_for( DiffLineType::Delete, - DiffTheme::Dark, - DiffColorLevel::Ansi256 + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi256) ), Style::default().bg(indexed_color(DARK_256_DEL_LINE_BG_IDX)) ); assert_ne!( style_line_bg_for( DiffLineType::Insert, - DiffTheme::Dark, - DiffColorLevel::Ansi256 + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi256) ), style_line_bg_for( DiffLineType::Delete, - DiffTheme::Dark, - DiffColorLevel::Ansi256 + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi256) ), "256-color mode should keep add/delete backgrounds distinct" ); } + #[test] + fn theme_scope_backgrounds_override_truecolor_fallback_when_available() { + let backgrounds = resolve_diff_backgrounds_for( + DiffTheme::Dark, + DiffColorLevel::TrueColor, + DiffScopeBackgroundRgbs { + inserted: Some((1, 2, 3)), + deleted: Some((4, 5, 6)), + }, + ); + assert_eq!( + style_line_bg_for(DiffLineType::Insert, backgrounds), + Style::default().bg(rgb_color((1, 2, 3))) + ); + assert_eq!( + style_line_bg_for(DiffLineType::Delete, backgrounds), + Style::default().bg(rgb_color((4, 5, 6))) + ); + } + + #[test] + fn theme_scope_backgrounds_quantize_to_ansi256() { + let backgrounds = resolve_diff_backgrounds_for( + DiffTheme::Dark, + DiffColorLevel::Ansi256, + DiffScopeBackgroundRgbs { + inserted: Some((0, 95, 0)), + deleted: None, + }, + ); + assert_eq!( + style_line_bg_for(DiffLineType::Insert, backgrounds), + Style::default().bg(indexed_color(22)) + ); + assert_eq!( + style_line_bg_for(DiffLineType::Delete, backgrounds), + Style::default().bg(indexed_color(DARK_256_DEL_LINE_BG_IDX)) + ); + } + + #[test] + fn ui_snapshot_theme_scope_background_resolution() { + let backgrounds = resolve_diff_backgrounds_for( + DiffTheme::Dark, + DiffColorLevel::TrueColor, + DiffScopeBackgroundRgbs { + inserted: Some((12, 34, 56)), + deleted: None, + }, + ); + let snapshot = format!( + "insert={:?}\ndelete={:?}", + style_line_bg_for(DiffLineType::Insert, backgrounds).bg, + style_line_bg_for(DiffLineType::Delete, backgrounds).bg, + ); + assert_snapshot!("theme_scope_background_resolution", snapshot); + } + + #[test] + fn ansi16_disables_line_and_gutter_backgrounds() { + assert_eq!( + style_line_bg_for( + DiffLineType::Insert, + fallback_diff_backgrounds(DiffTheme::Dark, DiffColorLevel::Ansi16) + ), + Style::default() + ); + assert_eq!( + style_line_bg_for( + DiffLineType::Delete, + fallback_diff_backgrounds(DiffTheme::Light, DiffColorLevel::Ansi16) + ), + Style::default() + ); + assert_eq!( + style_gutter_for( + DiffLineType::Insert, + DiffTheme::Light, + DiffColorLevel::Ansi16 + ), + Style::default().fg(Color::Black) + ); + assert_eq!( + style_gutter_for( + DiffLineType::Delete, + DiffTheme::Light, + DiffColorLevel::Ansi16 + ), + Style::default().fg(Color::Black) + ); + let themed_backgrounds = resolve_diff_backgrounds_for( + DiffTheme::Light, + DiffColorLevel::Ansi16, + DiffScopeBackgroundRgbs { + inserted: Some((8, 9, 10)), + deleted: Some((11, 12, 13)), + }, + ); + assert_eq!( + style_line_bg_for(DiffLineType::Insert, themed_backgrounds), + Style::default() + ); + assert_eq!( + style_line_bg_for(DiffLineType::Delete, themed_backgrounds), + Style::default() + ); + } + #[test] fn light_truecolor_theme_uses_readable_gutter_and_line_backgrounds() { assert_eq!( style_line_bg_for( DiffLineType::Insert, - DiffTheme::Light, - DiffColorLevel::TrueColor + fallback_diff_backgrounds(DiffTheme::Light, DiffColorLevel::TrueColor) ), Style::default().bg(rgb_color(LIGHT_TC_ADD_LINE_BG_RGB)) ); assert_eq!( style_line_bg_for( DiffLineType::Delete, - DiffTheme::Light, - DiffColorLevel::TrueColor + fallback_diff_backgrounds(DiffTheme::Light, DiffColorLevel::TrueColor) ), Style::default().bg(rgb_color(LIGHT_TC_DEL_LINE_BG_RGB)) ); @@ -1586,6 +2007,7 @@ mod tests { None, DiffTheme::Light, DiffColorLevel::TrueColor, + fallback_diff_backgrounds(DiffTheme::Light, DiffColorLevel::TrueColor), ); assert!( @@ -1608,6 +2030,97 @@ mod tests { assert_eq!(lines[1].style.bg, Some(rgb_color(LIGHT_TC_ADD_LINE_BG_RGB))); } + #[test] + fn windows_terminal_promotes_ansi16_to_truecolor_for_diffs() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Ansi16, + TerminalName::WindowsTerminal, + false, + false, + ), + DiffColorLevel::TrueColor + ); + } + + #[test] + fn wt_session_promotes_ansi16_to_truecolor_for_diffs() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Ansi16, + TerminalName::Unknown, + true, + false, + ), + DiffColorLevel::TrueColor + ); + } + + #[test] + fn non_windows_terminal_keeps_ansi16_diff_palette() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Ansi16, + TerminalName::WezTerm, + false, + false, + ), + DiffColorLevel::Ansi16 + ); + } + + #[test] + fn wt_session_promotes_unknown_color_level_to_truecolor() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Unknown, + TerminalName::WindowsTerminal, + true, + false, + ), + DiffColorLevel::TrueColor + ); + } + + #[test] + fn non_wt_windows_terminal_keeps_unknown_color_level_conservative() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Unknown, + TerminalName::WindowsTerminal, + false, + false, + ), + DiffColorLevel::Ansi16 + ); + } + + #[test] + fn explicit_force_override_keeps_ansi16_on_windows_terminal() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Ansi16, + TerminalName::WindowsTerminal, + false, + true, + ), + DiffColorLevel::Ansi16 + ); + } + + #[test] + fn explicit_force_override_keeps_ansi256_on_windows_terminal() { + assert_eq!( + diff_color_level_for_terminal( + StdoutColorLevel::Ansi256, + TerminalName::WindowsTerminal, + true, + true, + ), + DiffColorLevel::Ansi256 + ); + } + #[test] fn add_diff_uses_path_extension_for_highlighting() { let mut changes: HashMap = HashMap::new(); @@ -1769,12 +2282,13 @@ mod tests { #[test] fn fallback_wrapping_uses_display_width_for_tabs_and_wide_chars() { let width = 8; - let lines = push_wrapped_diff_line( + let lines = push_wrapped_diff_line_with_style_context( 1, DiffLineType::Insert, "abcd\t界🙂", width, line_number_width(1), + current_diff_render_style_context(), ); assert!(lines.len() >= 2, "expected wrapped output, got {lines:?}"); diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 78312db27d..76e92ca0e3 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -39,6 +39,8 @@ use crate::wrapping::adaptive_wrap_lines; use base64::Engine; use codex_core::config::Config; use codex_core::config::types::McpServerTransportConfig; +use codex_core::mcp::McpManager; +use codex_core::plugins::PluginsManager; use codex_core::web_search::web_search_detail; use codex_otel::RuntimeMetricsSummary; use codex_protocol::account::PlanType; @@ -73,6 +75,7 @@ use std::collections::HashMap; use std::io::Cursor; use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; use std::time::Duration; use std::time::Instant; use tracing::error; @@ -1041,6 +1044,7 @@ pub(crate) fn new_session_info( requested_model: &str, event: SessionConfiguredEvent, is_first_event: bool, + tooltip_override: Option, auth_plan: Option, ) -> SessionInfoCell { let SessionConfiguredEvent { @@ -1094,7 +1098,9 @@ pub(crate) fn new_session_info( parts.push(Box::new(PlainHistoryCell { lines: help_lines })); } else { if config.show_tooltips - && let Some(tooltips) = tooltips::get_tooltip(auth_plan).map(TooltipHistoryCell::new) + && let Some(tooltips) = tooltip_override + .or_else(|| tooltips::get_tooltip(auth_plan)) + .map(TooltipHistoryCell::new) { parts.push(Box::new(tooltips)); } @@ -1710,7 +1716,9 @@ pub(crate) fn new_mcp_tools_output( lines.push("".into()); } - let mut servers: Vec<_> = config.mcp_servers.iter().collect(); + let mcp_manager = McpManager::new(Arc::new(PluginsManager::new(config.codex_home.clone()))); + let effective_servers = mcp_manager.effective_servers(config, None); + let mut servers: Vec<_> = effective_servers.iter().collect(); servers.sort_by(|(a, _), (b, _)| a.cmp(b)); for (server, cfg) in servers { @@ -2396,13 +2404,19 @@ mod tests { use codex_core::config::types::McpServerTransportConfig; use codex_otel::RuntimeMetricTotals; use codex_otel::RuntimeMetricsSummary; + use codex_protocol::ThreadId; + use codex_protocol::account::PlanType; use codex_protocol::models::WebSearchAction; use codex_protocol::parse_command::ParsedCommand; + use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::McpAuthStatus; + use codex_protocol::protocol::SandboxPolicy; + use codex_protocol::protocol::SessionConfiguredEvent; use dirs::home_dir; use pretty_assertions::assert_eq; use serde_json::json; use std::collections::HashMap; + use std::path::PathBuf; use codex_protocol::mcp::CallToolResult; use codex_protocol::mcp::Tool; @@ -2463,6 +2477,26 @@ mod tests { .expect("resource link content should serialize") } + fn session_configured_event(model: &str) -> SessionConfiguredEvent { + SessionConfiguredEvent { + session_id: ThreadId::new(), + forked_from_id: None, + thread_name: None, + model: model.to_string(), + model_provider_id: "test-provider".to_string(), + service_tier: None, + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + cwd: PathBuf::from("/tmp/project"), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + network_proxy: None, + rollout_path: Some(PathBuf::new()), + } + } + #[test] fn unified_exec_interaction_cell_renders_input() { let cell = @@ -2547,6 +2581,73 @@ mod tests { insta::assert_snapshot!(rendered); } + #[tokio::test] + async fn session_info_uses_availability_nux_tooltip_override() { + let config = test_config().await; + let cell = new_session_info( + &config, + "gpt-5", + session_configured_event("gpt-5"), + false, + Some("Model just became available".to_string()), + Some(PlanType::Free), + ); + + let rendered = render_transcript(&cell).join("\n"); + assert!(rendered.contains("Model just became available")); + } + + #[tokio::test] + async fn session_info_availability_nux_tooltip_snapshot() { + let mut config = test_config().await; + config.cwd = PathBuf::from("/tmp/project"); + let cell = new_session_info( + &config, + "gpt-5", + session_configured_event("gpt-5"), + false, + Some("Model just became available".to_string()), + Some(PlanType::Free), + ); + + let rendered = render_transcript(&cell).join("\n"); + insta::assert_snapshot!(rendered); + } + + #[tokio::test] + async fn session_info_first_event_suppresses_tooltips_and_nux() { + let config = test_config().await; + let cell = new_session_info( + &config, + "gpt-5", + session_configured_event("gpt-5"), + true, + Some("Model just became available".to_string()), + Some(PlanType::Free), + ); + + let rendered = render_transcript(&cell).join("\n"); + assert!(!rendered.contains("Model just became available")); + assert!(rendered.contains("To get started")); + } + + #[tokio::test] + async fn session_info_hides_tooltips_when_disabled() { + let mut config = test_config().await; + config.show_tooltips = false; + let cell = new_session_info( + &config, + "gpt-5", + session_configured_event("gpt-5"), + false, + Some("Model just became available".to_string()), + Some(PlanType::Free), + ); + + let rendered = render_transcript(&cell).join("\n"); + assert!(!rendered.contains("Model just became available")); + } + #[test] fn ps_output_multiline_snapshot() { let cell = new_unified_exec_processes_output(vec![ @@ -2602,6 +2703,16 @@ mod tests { insta::assert_snapshot!(rendered); } + #[test] + fn error_event_oversized_input_snapshot() { + let cell = new_error_event( + "Message exceeds the maximum length of 1048576 characters (1048577 provided)." + .to_string(), + ); + let rendered = render_lines(&cell.display_lines(120)).join("\n"); + insta::assert_snapshot!(rendered); + } + #[tokio::test] async fn mcp_tools_output_masks_sensitive_values() { let mut config = test_config().await; @@ -2623,6 +2734,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }; let mut servers = config.mcp_servers.get().clone(); servers.insert("docs".to_string(), stdio_config); @@ -2646,6 +2758,7 @@ mod tests { enabled_tools: None, disabled_tools: None, scopes: None, + oauth_resource: None, }; servers.insert("http".to_string(), http_config); config diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index d51f42b2ff..5d36ec441d 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -31,8 +31,10 @@ use codex_core::find_thread_path_by_name_str; use codex_core::format_exec_policy_error_with_source; use codex_core::path_utils; use codex_core::read_session_meta_line; +use codex_core::state_db::get_state_db; use codex_core::terminal::Multiplexer; use codex_core::windows_sandbox::WindowsSandboxLevelExt; +use codex_protocol::ThreadId; use codex_protocol::config_types::AltScreenMode; use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::WindowsSandboxLevel; @@ -61,6 +63,8 @@ mod app_backtrack; mod app_event; mod app_event_sender; mod ascii_animation; +#[cfg(all(not(target_os = "linux"), feature = "voice-input"))] +mod audio_device; mod bottom_pane; mod chatwidget; mod cli; @@ -121,6 +125,7 @@ mod voice; mod voice { use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; + use codex_core::config::Config; use codex_protocol::protocol::RealtimeAudioFrame; use std::sync::Arc; use std::sync::Mutex; @@ -144,7 +149,7 @@ mod voice { Err("voice input is unavailable in this build".to_string()) } - pub fn start_realtime(_tx: AppEventSender) -> Result { + pub fn start_realtime(_config: &Config, _tx: AppEventSender) -> Result { Err("voice input is unavailable in this build".to_string()) } @@ -184,7 +189,7 @@ mod voice { } impl RealtimeAudioPlayer { - pub(crate) fn start() -> Result { + pub(crate) fn start(_config: &Config) -> Result { Err("voice output is unavailable in this build".to_string()) } @@ -665,7 +670,19 @@ async fn run_ratatui_app( find_thread_path_by_name_str(&config.codex_home, id_str).await? }; match path { - Some(path) => resume_picker::SessionSelection::Fork(path), + Some(path) => { + let thread_id = + match resolve_session_thread_id(path.as_path(), is_uuid.then_some(id_str)) + .await + { + Some(thread_id) => thread_id, + None => return missing_session_exit(id_str, "fork"), + }; + resume_picker::SessionSelection::Fork(resume_picker::SessionTarget { + path, + thread_id, + }) + } None => return missing_session_exit(id_str, "fork"), } } else if cli.fork_last { @@ -682,11 +699,37 @@ async fn run_ratatui_app( ) .await { - Ok(page) => page - .items - .first() - .map(|it| resume_picker::SessionSelection::Fork(it.path.clone())) - .unwrap_or(resume_picker::SessionSelection::StartFresh), + Ok(page) => match page.items.first() { + Some(item) => { + match resolve_session_thread_id(item.path.as_path(), None).await { + Some(thread_id) => resume_picker::SessionSelection::Fork( + resume_picker::SessionTarget { + path: item.path.clone(), + thread_id, + }, + ), + None => { + let rollout_path = item.path.display(); + error!( + "Error reading session metadata from latest rollout: {rollout_path}" + ); + restore(); + session_log::log_session_end(); + let _ = tui.terminal.clear(); + return Ok(AppExitInfo { + token_usage: codex_protocol::protocol::TokenUsage::default(), + thread_id: None, + thread_name: None, + update_action: None, + exit_reason: ExitReason::Fatal(format!( + "Found latest saved session at {rollout_path}, but failed to read its metadata. Run `codex fork` to choose from existing sessions." + )), + }); + } + } + } + None => resume_picker::SessionSelection::StartFresh, + }, Err(_) => resume_picker::SessionSelection::StartFresh, } } else if cli.fork_picker { @@ -715,7 +758,21 @@ async fn run_ratatui_app( find_thread_path_by_name_str(&config.codex_home, id_str).await? }; match path { - Some(path) => resume_picker::SessionSelection::Resume(path), + Some(path) => { + let thread_id = match resolve_session_thread_id( + path.as_path(), + is_uuid.then_some(id_str), + ) + .await + { + Some(thread_id) => thread_id, + None => return missing_session_exit(id_str, "resume"), + }; + resume_picker::SessionSelection::Resume(resume_picker::SessionTarget { + path, + thread_id, + }) + } None => return missing_session_exit(id_str, "resume"), } } else if cli.resume_last { @@ -737,7 +794,30 @@ async fn run_ratatui_app( ) .await { - Ok(Some(path)) => resume_picker::SessionSelection::Resume(path), + Ok(Some(path)) => match resolve_session_thread_id(path.as_path(), None).await { + Some(thread_id) => { + resume_picker::SessionSelection::Resume(resume_picker::SessionTarget { + path, + thread_id, + }) + } + None => { + let rollout_path = path.display(); + error!("Error reading session metadata from latest rollout: {rollout_path}"); + restore(); + session_log::log_session_end(); + let _ = tui.terminal.clear(); + return Ok(AppExitInfo { + token_usage: codex_protocol::protocol::TokenUsage::default(), + thread_id: None, + thread_name: None, + update_action: None, + exit_reason: ExitReason::Fatal(format!( + "Found latest saved session at {rollout_path}, but failed to read its metadata. Run `codex resume` to choose from existing sessions." + )), + }); + } + }, _ => resume_picker::SessionSelection::StartFresh, } } else if cli.resume_picker { @@ -761,15 +841,27 @@ async fn run_ratatui_app( let current_cwd = config.cwd.clone(); let allow_prompt = cli.cwd.is_none(); - let action_and_path_if_resume_or_fork = match &session_selection { - resume_picker::SessionSelection::Resume(path) => Some((CwdPromptAction::Resume, path)), - resume_picker::SessionSelection::Fork(path) => Some((CwdPromptAction::Fork, path)), + let action_and_target_session_if_resume_or_fork = match &session_selection { + resume_picker::SessionSelection::Resume(target_session) => { + Some((CwdPromptAction::Resume, target_session)) + } + resume_picker::SessionSelection::Fork(target_session) => { + Some((CwdPromptAction::Fork, target_session)) + } _ => None, }; - let fallback_cwd = match action_and_path_if_resume_or_fork { - Some((action, path)) => { - match resolve_cwd_for_resume_or_fork(&mut tui, ¤t_cwd, path, action, allow_prompt) - .await? + let fallback_cwd = match action_and_target_session_if_resume_or_fork { + Some((action, target_session)) => { + match resolve_cwd_for_resume_or_fork( + &mut tui, + &config, + ¤t_cwd, + target_session.thread_id, + &target_session.path, + action, + allow_prompt, + ) + .await? { ResolveCwdOutcome::Continue(cwd) => cwd, ResolveCwdOutcome::Exit => { @@ -851,12 +943,35 @@ async fn run_ratatui_app( app_result } -pub(crate) async fn read_session_cwd(path: &Path) -> Option { +pub(crate) async fn resolve_session_thread_id( + path: &Path, + id_str_if_uuid: Option<&str>, +) -> Option { + match id_str_if_uuid { + Some(id_str) => ThreadId::from_string(id_str).ok(), + None => read_session_meta_line(path) + .await + .ok() + .map(|meta_line| meta_line.meta.id), + } +} + +pub(crate) async fn read_session_cwd( + config: &Config, + thread_id: ThreadId, + path: &Path, +) -> Option { + if let Some(state_db_ctx) = get_state_db(config, None).await + && let Ok(Some(metadata)) = state_db_ctx.get_thread(thread_id).await + { + return Some(metadata.cwd); + } + // Prefer the latest TurnContext cwd so resume/fork reflects the most recent - // session directory (for the changed-cwd prompt). The alternative would be - // mutating the SessionMeta line when the session cwd changes, but the rollout - // is an append-only JSONL log and rewriting the head would be error-prone. - // When rollouts move to SQLite, we can drop this scan. + // session directory (for the changed-cwd prompt) when DB data is unavailable. + // The alternative would be mutating the SessionMeta line when the session cwd + // changes, but the rollout is an append-only JSONL log and rewriting the head + // would be error-prone. if let Some(cwd) = parse_latest_turn_context_cwd(path).await { return Some(cwd); } @@ -908,12 +1023,14 @@ pub(crate) enum ResolveCwdOutcome { pub(crate) async fn resolve_cwd_for_resume_or_fork( tui: &mut Tui, + config: &Config, current_cwd: &Path, + thread_id: ThreadId, path: &Path, action: CwdPromptAction, allow_prompt: bool, ) -> color_eyre::Result { - let Some(history_cwd) = read_session_cwd(path).await else { + let Some(history_cwd) = read_session_cwd(config, thread_id, path).await else { return Ok(ResolveCwdOutcome::Continue(None)); }; if allow_prompt && cwds_differ(current_cwd, &history_cwd) { @@ -1071,11 +1188,14 @@ mod tests { use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::ProjectConfig; + use codex_core::features::Feature; + use codex_protocol::ThreadId; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; + use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::TurnContextItem; use serial_test::serial; use tempfile::TempDir; @@ -1152,14 +1272,19 @@ mod tests { TurnContextItem { turn_id: None, cwd, + current_date: None, + timezone: None, approval_policy: config.permissions.approval_policy.value(), sandbox_policy: config.permissions.sandbox_policy.get().clone(), network: None, model, personality: None, collaboration_mode: None, + realtime_active: Some(false), effort: config.model_reasoning_effort, - summary: config.model_reasoning_summary, + summary: config + .model_reasoning_summary + .unwrap_or(codex_protocol::config_types::ReasoningSummary::Auto), user_instructions: None, developer_instructions: None, final_output_json_schema: None, @@ -1194,7 +1319,9 @@ mod tests { } std::fs::write(&rollout_path, text)?; - let cwd = read_session_cwd(&rollout_path).await.expect("expected cwd"); + let cwd = read_session_cwd(&config, ThreadId::new(), &rollout_path) + .await + .expect("expected cwd"); assert_eq!(cwd, second); Ok(()) } @@ -1234,7 +1361,9 @@ mod tests { } std::fs::write(&rollout_path, text)?; - let session_cwd = read_session_cwd(&rollout_path).await.expect("expected cwd"); + let session_cwd = read_session_cwd(&config, ThreadId::new(), &rollout_path) + .await + .expect("expected cwd"); assert_eq!(session_cwd, latest); assert!(cwds_differ(¤t, &session_cwd)); Ok(()) @@ -1339,7 +1468,7 @@ trust_level = "untrusted" #[tokio::test] async fn read_session_cwd_falls_back_to_session_meta() -> std::io::Result<()> { let temp_dir = TempDir::new()?; - let _config = build_config(&temp_dir).await?; + let config = build_config(&temp_dir).await?; let session_cwd = temp_dir.path().join("session"); std::fs::create_dir_all(&session_cwd)?; @@ -1361,8 +1490,67 @@ trust_level = "untrusted" ); std::fs::write(&rollout_path, text)?; - let cwd = read_session_cwd(&rollout_path).await.expect("expected cwd"); + let cwd = read_session_cwd(&config, ThreadId::new(), &rollout_path) + .await + .expect("expected cwd"); assert_eq!(cwd, session_cwd); Ok(()) } + + #[tokio::test] + async fn read_session_cwd_prefers_sqlite_when_thread_id_present() -> std::io::Result<()> { + let temp_dir = TempDir::new()?; + let mut config = build_config(&temp_dir).await?; + config.features.enable(Feature::Sqlite); + + let thread_id = ThreadId::new(); + let rollout_cwd = temp_dir.path().join("rollout-cwd"); + let sqlite_cwd = temp_dir.path().join("sqlite-cwd"); + std::fs::create_dir_all(&rollout_cwd)?; + std::fs::create_dir_all(&sqlite_cwd)?; + + let rollout_path = temp_dir.path().join("rollout.jsonl"); + let rollout_line = RolloutLine { + timestamp: "t0".to_string(), + item: RolloutItem::TurnContext(build_turn_context(&config, rollout_cwd)), + }; + std::fs::write( + &rollout_path, + format!( + "{}\n", + serde_json::to_string(&rollout_line).expect("serialize rollout") + ), + )?; + + let runtime = codex_state::StateRuntime::init( + config.codex_home.clone(), + config.model_provider_id.clone(), + None, + ) + .await + .map_err(std::io::Error::other)?; + runtime + .mark_backfill_complete(None) + .await + .map_err(std::io::Error::other)?; + + let mut builder = codex_state::ThreadMetadataBuilder::new( + thread_id, + rollout_path.clone(), + chrono::Utc::now(), + SessionSource::Cli, + ); + builder.cwd = sqlite_cwd.clone(); + let metadata = builder.build(config.model_provider_id.as_str()); + runtime + .upsert_thread(&metadata) + .await + .map_err(std::io::Error::other)?; + + let cwd = read_session_cwd(&config, thread_id, &rollout_path) + .await + .expect("expected cwd"); + assert_eq!(cwd, sqlite_cwd); + Ok(()) + } } diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index ba8b47d5ed..2bbe19b6f7 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -2,6 +2,7 @@ use crate::render::highlight::highlight_code_to_lines; use crate::render::line_utils::line_to_static; use crate::wrapping::RtOptions; use crate::wrapping::adaptive_wrap_line; +use codex_utils_string::normalize_markdown_hash_location_suffix; use pulldown_cmark::CodeBlockKind; use pulldown_cmark::CowStr; use pulldown_cmark::Event; @@ -14,6 +15,8 @@ use ratatui::style::Style; use ratatui::text::Line; use ratatui::text::Span; use ratatui::text::Text; +use regex_lite::Regex; +use std::sync::LazyLock; struct MarkdownStyles { h1: Style, @@ -85,6 +88,48 @@ pub(crate) fn render_markdown_text_with_width(input: &str, width: Option) w.text } +#[derive(Clone, Debug)] +struct LinkState { + destination: String, + show_destination: bool, + hidden_location_suffix: Option, + label_start_span_idx: usize, + label_styled: bool, +} + +fn should_render_link_destination(dest_url: &str) -> bool { + !is_local_path_like_link(dest_url) +} + +static COLON_LOCATION_SUFFIX_RE: LazyLock = + LazyLock::new( + || match Regex::new(r":\d+(?::\d+)?(?:[-–]\d+(?::\d+)?)?$") { + Ok(regex) => regex, + Err(error) => panic!("invalid location suffix regex: {error}"), + }, + ); + +// Covered by load_location_suffix_regexes. +static HASH_LOCATION_SUFFIX_RE: LazyLock = + LazyLock::new(|| match Regex::new(r"^L\d+(?:C\d+)?(?:-L\d+(?:C\d+)?)?$") { + Ok(regex) => regex, + Err(error) => panic!("invalid hash location regex: {error}"), + }); + +fn is_local_path_like_link(dest_url: &str) -> bool { + dest_url.starts_with("file://") + || dest_url.starts_with('/') + || dest_url.starts_with("~/") + || dest_url.starts_with("./") + || dest_url.starts_with("../") + || dest_url.starts_with("\\\\") + || matches!( + dest_url.as_bytes(), + [drive, b':', separator, ..] + if drive.is_ascii_alphabetic() && matches!(separator, b'/' | b'\\') + ) +} + struct Writer<'a, I> where I: Iterator>, @@ -95,7 +140,7 @@ where inline_styles: Vec