diff --git a/.github/ISSUE_TEMPLATE/3-cli.yml b/.github/ISSUE_TEMPLATE/3-cli.yml index 4aff813e5f..37229c7f2b 100644 --- a/.github/ISSUE_TEMPLATE/3-cli.yml +++ b/.github/ISSUE_TEMPLATE/3-cli.yml @@ -2,7 +2,6 @@ name: πŸ’» CLI Bug description: Report an issue in the Codex CLI labels: - bug - - needs triage body: - type: markdown attributes: @@ -41,9 +40,9 @@ body: id: terminal attributes: label: What terminal emulator and version are you using (if applicable)? - description: Also note any multiplexer in use (screen / tmux / zellij) description: | - E.g, VSCode, Terminal.app, iTerm2, Ghostty, Windows Terminal (WSL / PowerShell) + Also note any multiplexer in use (screen / tmux / zellij). + E.g., VS Code, Terminal.app, iTerm2, Ghostty, Windows Terminal (WSL / PowerShell) - type: textarea id: actual attributes: diff --git a/.github/ISSUE_TEMPLATE/5-feature-request.yml b/.github/ISSUE_TEMPLATE/5-feature-request.yml index 55ff9fbbcd..745c347965 100644 --- a/.github/ISSUE_TEMPLATE/5-feature-request.yml +++ b/.github/ISSUE_TEMPLATE/5-feature-request.yml @@ -10,7 +10,7 @@ body: Before you submit a feature: 1. Search existing issues for similar features. If you find one, πŸ‘ it rather than opening a new one. - 2. The Codex team will try to balance the varying needs of the community when prioritizing or rejecting new features. Not all features will be accepted. See [Contributing](https://github.com/openai/codex#contributing) for more details. + 2. The Codex team will try to balance the varying needs of the community when prioritizing or rejecting new features. Not all features will be accepted. See [Contributing](https://github.com/openai/codex/blob/main/docs/contributing.md) for more details. - type: input id: variant diff --git a/.github/ISSUE_TEMPLATE/6-docs-issue.yml b/.github/ISSUE_TEMPLATE/6-docs-issue.yml index 456602e6ac..1957b6035a 100644 --- a/.github/ISSUE_TEMPLATE/6-docs-issue.yml +++ b/.github/ISSUE_TEMPLATE/6-docs-issue.yml @@ -1,6 +1,6 @@ name: πŸ“— Documentation Issue description: Tell us if there is missing or incorrect documentation -labels: [docs] +labels: [documentation] body: - type: markdown attributes: @@ -24,4 +24,4 @@ body: - type: textarea attributes: label: Where did you find it? - description: If possible, please provide the URL(s) where you found this issue. \ No newline at end of file + description: If possible, please provide the URL(s) where you found this issue. diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index bb67fe6896..9eeb8f1028 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -6,25 +6,37 @@ updates: directory: .github/actions/codex schedule: interval: weekly + cooldown: + default-days: 7 - package-ecosystem: cargo directories: - codex-rs - codex-rs/* schedule: interval: weekly + cooldown: + default-days: 7 - package-ecosystem: devcontainers directory: / schedule: interval: weekly + cooldown: + default-days: 7 - package-ecosystem: docker directory: codex-cli schedule: interval: weekly + cooldown: + default-days: 7 - package-ecosystem: github-actions directory: / schedule: interval: weekly + cooldown: + default-days: 7 - package-ecosystem: rust-toolchain directory: codex-rs schedule: interval: weekly + cooldown: + default-days: 7 diff --git a/AGENTS.md b/AGENTS.md index 6939d146b0..1b5e005130 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ When UI or text output changes intentionally, update the snapshots as follows: If you don’t have the tool: -- `cargo install cargo-insta` +- `cargo install --locked cargo-insta` ### Test assertions diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index e079e3af0e..3174ce5ecd 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -665,6 +665,7 @@ "aws-lc-rs_1.16.2": "{\"dependencies\":[{\"name\":\"aws-lc-fips-sys\",\"optional\":true,\"req\":\"^0.13.1\"},{\"default_features\":false,\"name\":\"aws-lc-sys\",\"optional\":true,\"req\":\"^0.39.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^4.4\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.5.0\"},{\"kind\":\"dev\",\"name\":\"paste\",\"req\":\"^1.0.15\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.11.1\"},{\"name\":\"untrusted\",\"optional\":true,\"req\":\"^0.7.1\"},{\"name\":\"zeroize\",\"req\":\"^1.8.1\"}],\"features\":{\"alloc\":[],\"asan\":[\"aws-lc-sys?/asan\",\"aws-lc-fips-sys?/asan\"],\"bindgen\":[\"aws-lc-sys?/bindgen\",\"aws-lc-fips-sys?/bindgen\"],\"default\":[\"aws-lc-sys\",\"alloc\",\"ring-io\",\"ring-sig-verify\"],\"dev-tests-only\":[],\"fips\":[\"dep:aws-lc-fips-sys\"],\"non-fips\":[\"aws-lc-sys\"],\"prebuilt-nasm\":[\"aws-lc-sys?/prebuilt-nasm\"],\"ring-io\":[\"dep:untrusted\"],\"ring-sig-verify\":[\"dep:untrusted\"],\"test_logging\":[],\"unstable\":[]}}", "aws-lc-sys_0.39.0": "{\"dependencies\":[{\"kind\":\"build\",\"name\":\"bindgen\",\"optional\":true,\"req\":\"^0.72.0\"},{\"features\":[\"parallel\"],\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.26\"},{\"kind\":\"build\",\"name\":\"cmake\",\"req\":\"^0.1.54\"},{\"kind\":\"build\",\"name\":\"dunce\",\"req\":\"^1.0.5\"},{\"kind\":\"build\",\"name\":\"fs_extra\",\"req\":\"^1.3.0\"}],\"features\":{\"all-bindings\":[],\"asan\":[],\"bindgen\":[\"dep:bindgen\"],\"default\":[\"all-bindings\"],\"disable-prebuilt-nasm\":[],\"fips\":[\"dep:bindgen\"],\"prebuilt-nasm\":[],\"ssl\":[\"bindgen\",\"all-bindings\"]}}", "aws-runtime_1.5.17": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"arbitrary\",\"req\":\"^1.3\"},{\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"features\":[\"http0-compat\"],\"name\":\"aws-sigv4\",\"req\":\"^1.3.7\"},{\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"name\":\"aws-smithy-eventstream\",\"optional\":true,\"req\":\"^0.60.14\"},{\"name\":\"aws-smithy-http\",\"req\":\"^0.62.6\"},{\"kind\":\"dev\",\"name\":\"aws-smithy-protocol-test\",\"req\":\"^0.63.7\"},{\"features\":[\"client\"],\"name\":\"aws-smithy-runtime\",\"req\":\"^1.9.5\"},{\"features\":[\"client\"],\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"name\":\"aws-types\",\"req\":\"^1.3.11\"},{\"name\":\"bytes\",\"req\":\"^1.10.0\"},{\"kind\":\"dev\",\"name\":\"bytes-utils\",\"req\":\"^0.1.2\"},{\"kind\":\"dev\",\"name\":\"convert_case\",\"req\":\"^0.6.0\"},{\"name\":\"fastrand\",\"req\":\"^2.3.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.29\"},{\"name\":\"http-02x\",\"package\":\"http\",\"req\":\"^0.2.9\"},{\"name\":\"http-1x\",\"optional\":true,\"package\":\"http\",\"req\":\"^1.1.0\"},{\"name\":\"http-body-04x\",\"package\":\"http-body\",\"req\":\"^0.4.5\"},{\"name\":\"http-body-1x\",\"optional\":true,\"package\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.14\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.2\"},{\"name\":\"regex-lite\",\"optional\":true,\"req\":\"^0.1.5\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1\"},{\"features\":[\"macros\",\"rt\",\"time\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.23.1\"},{\"name\":\"tracing\",\"req\":\"^0.1.40\"},{\"features\":[\"env-filter\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3.17\"},{\"kind\":\"dev\",\"name\":\"tracing-test\",\"req\":\"^0.2.4\"},{\"name\":\"uuid\",\"req\":\"^1\"}],\"features\":{\"event-stream\":[\"dep:aws-smithy-eventstream\",\"aws-sigv4/sign-eventstream\"],\"http-02x\":[],\"http-1x\":[\"dep:http-1x\",\"dep:http-body-1x\"],\"sigv4a\":[\"aws-sigv4/sigv4a\"],\"test-util\":[\"dep:regex-lite\"]}}", + "aws-sdk-signin_1.2.0": "{\"dependencies\":[{\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"name\":\"aws-runtime\",\"req\":\"^1.5.17\"},{\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"name\":\"aws-smithy-http\",\"req\":\"^0.62.6\"},{\"name\":\"aws-smithy-json\",\"req\":\"^0.61.8\"},{\"features\":[\"client\"],\"name\":\"aws-smithy-runtime\",\"req\":\"^1.9.5\"},{\"features\":[\"client\",\"http-02x\"],\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"name\":\"aws-types\",\"req\":\"^1.3.11\"},{\"name\":\"bytes\",\"req\":\"^1.4.0\"},{\"name\":\"fastrand\",\"req\":\"^2.0.0\"},{\"name\":\"http\",\"req\":\"^0.2.9\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"name\":\"regex-lite\",\"req\":\"^0.1.5\"},{\"features\":[\"macros\",\"test-util\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.23.1\"},{\"name\":\"tracing\",\"req\":\"^0.1\"}],\"features\":{\"behavior-version-latest\":[],\"default\":[\"rustls\",\"default-https-client\",\"rt-tokio\"],\"default-https-client\":[\"aws-smithy-runtime/default-https-client\"],\"gated-tests\":[],\"rt-tokio\":[\"aws-smithy-async/rt-tokio\",\"aws-smithy-types/rt-tokio\"],\"rustls\":[\"aws-smithy-runtime/tls-rustls\"],\"test-util\":[\"aws-credential-types/test-util\",\"aws-smithy-runtime/test-util\"]}}", "aws-sdk-sso_1.91.0": "{\"dependencies\":[{\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"name\":\"aws-runtime\",\"req\":\"^1.5.17\"},{\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"name\":\"aws-smithy-http\",\"req\":\"^0.62.6\"},{\"name\":\"aws-smithy-json\",\"req\":\"^0.61.8\"},{\"features\":[\"client\"],\"name\":\"aws-smithy-runtime\",\"req\":\"^1.9.5\"},{\"features\":[\"client\",\"http-02x\"],\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"name\":\"aws-types\",\"req\":\"^1.3.11\"},{\"name\":\"bytes\",\"req\":\"^1.4.0\"},{\"name\":\"fastrand\",\"req\":\"^2.0.0\"},{\"name\":\"http\",\"req\":\"^0.2.9\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"name\":\"regex-lite\",\"req\":\"^0.1.5\"},{\"features\":[\"macros\",\"test-util\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.23.1\"},{\"name\":\"tracing\",\"req\":\"^0.1\"}],\"features\":{\"behavior-version-latest\":[],\"default\":[\"rustls\",\"default-https-client\",\"rt-tokio\"],\"default-https-client\":[\"aws-smithy-runtime/default-https-client\"],\"gated-tests\":[],\"rt-tokio\":[\"aws-smithy-async/rt-tokio\",\"aws-smithy-types/rt-tokio\"],\"rustls\":[\"aws-smithy-runtime/tls-rustls\"],\"test-util\":[\"aws-credential-types/test-util\",\"aws-smithy-runtime/test-util\"]}}", "aws-sdk-ssooidc_1.93.0": "{\"dependencies\":[{\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"name\":\"aws-runtime\",\"req\":\"^1.5.17\"},{\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"name\":\"aws-smithy-http\",\"req\":\"^0.62.6\"},{\"name\":\"aws-smithy-json\",\"req\":\"^0.61.8\"},{\"features\":[\"client\"],\"name\":\"aws-smithy-runtime\",\"req\":\"^1.9.5\"},{\"features\":[\"client\",\"http-02x\"],\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"name\":\"aws-types\",\"req\":\"^1.3.11\"},{\"name\":\"bytes\",\"req\":\"^1.4.0\"},{\"name\":\"fastrand\",\"req\":\"^2.0.0\"},{\"name\":\"http\",\"req\":\"^0.2.9\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"name\":\"regex-lite\",\"req\":\"^0.1.5\"},{\"features\":[\"macros\",\"test-util\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.23.1\"},{\"name\":\"tracing\",\"req\":\"^0.1\"}],\"features\":{\"behavior-version-latest\":[],\"default\":[\"rustls\",\"default-https-client\",\"rt-tokio\"],\"default-https-client\":[\"aws-smithy-runtime/default-https-client\"],\"gated-tests\":[],\"rt-tokio\":[\"aws-smithy-async/rt-tokio\",\"aws-smithy-types/rt-tokio\"],\"rustls\":[\"aws-smithy-runtime/tls-rustls\"],\"test-util\":[\"aws-credential-types/test-util\",\"aws-smithy-runtime/test-util\"]}}", "aws-sdk-sts_1.95.0": "{\"dependencies\":[{\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-credential-types\",\"req\":\"^1.2.11\"},{\"name\":\"aws-runtime\",\"req\":\"^1.5.17\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-runtime\",\"req\":\"^1.5.17\"},{\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-async\",\"req\":\"^1.2.7\"},{\"name\":\"aws-smithy-http\",\"req\":\"^0.62.6\"},{\"features\":[\"test-util\",\"wire-mock\"],\"kind\":\"dev\",\"name\":\"aws-smithy-http-client\",\"req\":\"^1.1.5\"},{\"name\":\"aws-smithy-json\",\"req\":\"^0.61.8\"},{\"kind\":\"dev\",\"name\":\"aws-smithy-protocol-test\",\"req\":\"^0.63.7\"},{\"name\":\"aws-smithy-query\",\"req\":\"^0.60.9\"},{\"features\":[\"client\"],\"name\":\"aws-smithy-runtime\",\"req\":\"^1.9.5\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-runtime\",\"req\":\"^1.9.5\"},{\"features\":[\"client\",\"http-02x\"],\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-runtime-api\",\"req\":\"^1.9.3\"},{\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"features\":[\"test-util\"],\"kind\":\"dev\",\"name\":\"aws-smithy-types\",\"req\":\"^1.3.5\"},{\"name\":\"aws-smithy-xml\",\"req\":\"^0.60.13\"},{\"name\":\"aws-types\",\"req\":\"^1.3.11\"},{\"name\":\"fastrand\",\"req\":\"^2.0.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.25\"},{\"name\":\"http\",\"req\":\"^0.2.9\"},{\"kind\":\"dev\",\"name\":\"http-1x\",\"package\":\"http\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"name\":\"regex-lite\",\"req\":\"^0.1.5\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"features\":[\"macros\",\"test-util\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.23.1\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"json\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3.16\"}],\"features\":{\"behavior-version-latest\":[],\"default\":[\"rustls\",\"default-https-client\",\"rt-tokio\"],\"default-https-client\":[\"aws-smithy-runtime/default-https-client\"],\"gated-tests\":[],\"rt-tokio\":[\"aws-smithy-async/rt-tokio\",\"aws-smithy-types/rt-tokio\"],\"rustls\":[\"aws-smithy-runtime/tls-rustls\"],\"test-util\":[\"aws-credential-types/test-util\",\"aws-smithy-runtime/test-util\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index c656a791a6..0b84570781 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -757,6 +757,7 @@ checksum = "96571e6996817bf3d58f6b569e4b9fd2e9d2fcf9f7424eed07b2ce9bb87535e5" dependencies = [ "aws-credential-types", "aws-runtime", + "aws-sdk-signin", "aws-sdk-sso", "aws-sdk-ssooidc", "aws-sdk-sts", @@ -767,15 +768,20 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", + "base64-simd", "bytes", "fastrand", "hex", "http 1.4.0", + "p256", + "rand 0.8.5", "ring", + "sha2", "time", "tokio", "tracing", "url", + "uuid", "zeroize", ] @@ -838,6 +844,28 @@ dependencies = [ "uuid", ] +[[package]] +name = "aws-sdk-signin" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c084bd63941916e1348cb8d9e05ac2e49bdd40a380e9167702683184c6c6be53" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-sso" version = "1.91.0" @@ -2712,6 +2740,7 @@ dependencies = [ "tokio", "tokio-tungstenite", "tokio-util", + "toml 0.9.11+spec-1.1.0", "tracing", "uuid", "wiremock", @@ -3417,6 +3446,7 @@ dependencies = [ "codex-otel", "codex-protocol", "codex-state", + "codex-utils-absolute-path", "codex-utils-path", "codex-utils-string", "pretty_assertions", @@ -3608,17 +3638,13 @@ dependencies = [ "codex-protocol", "codex-rollout", "codex-state", + "codex-utils-absolute-path", "pretty_assertions", - "prost 0.14.3", "serde", "serde_json", "tempfile", "thiserror 2.0.18", "tokio", - "tokio-stream", - "tonic", - "tonic-prost", - "tonic-prost-build", "tracing", "uuid", ] @@ -3931,7 +3957,6 @@ dependencies = [ "codex-core", "codex-model-provider-info", "codex-protocol", - "codex-utils-absolute-path", "pretty_assertions", ] diff --git a/codex-rs/agent-graph-store/Cargo.toml b/codex-rs/agent-graph-store/Cargo.toml index e221ef61b2..9ecd827194 100644 --- a/codex-rs/agent-graph-store/Cargo.toml +++ b/codex-rs/agent-graph-store/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_agent_graph_store" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/analytics/src/analytics_client_tests.rs b/codex-rs/analytics/src/analytics_client_tests.rs index 880adfc254..6fd910646b 100644 --- a/codex-rs/analytics/src/analytics_client_tests.rs +++ b/codex-rs/analytics/src/analytics_client_tests.rs @@ -170,6 +170,7 @@ fn sample_thread_start_response( model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp").abs(), + workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnFailure, approvals_reviewer: AppServerApprovalsReviewer::User, @@ -226,6 +227,7 @@ fn sample_thread_resume_response_with_source( model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp").abs(), + workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnFailure, approvals_reviewer: AppServerApprovalsReviewer::User, diff --git a/codex-rs/analytics/src/client.rs b/codex-rs/analytics/src/client.rs index 6d6d446560..6d46b2ce57 100644 --- a/codex-rs/analytics/src/client.rs +++ b/codex-rs/analytics/src/client.rs @@ -340,8 +340,9 @@ impl AnalyticsEventsClient { }); } - pub fn track_server_response(&self, response: ServerResponse) { + pub fn track_server_response(&self, completed_at_ms: u64, response: ServerResponse) { self.record_fact(AnalyticsFact::ServerResponse { + completed_at_ms, response: Box::new(response), }); } diff --git a/codex-rs/analytics/src/client_tests.rs b/codex-rs/analytics/src/client_tests.rs index 3021d558d6..2f5814c59a 100644 --- a/codex-rs/analytics/src/client_tests.rs +++ b/codex-rs/analytics/src/client_tests.rs @@ -108,6 +108,7 @@ fn sample_thread_start_response() -> ClientResponsePayload { model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp").abs(), + workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnFailure, approvals_reviewer: AppServerApprovalsReviewer::User, @@ -125,6 +126,7 @@ fn sample_thread_resume_response() -> ClientResponsePayload { model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp").abs(), + workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnFailure, approvals_reviewer: AppServerApprovalsReviewer::User, @@ -142,6 +144,7 @@ fn sample_thread_fork_response() -> ClientResponsePayload { model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp").abs(), + workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnFailure, approvals_reviewer: AppServerApprovalsReviewer::User, diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index 23afd83b75..eaa7daf8f8 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -18,6 +18,7 @@ use crate::facts::TurnStatus; use crate::facts::TurnSteerRejectionReason; use crate::facts::TurnSteerResult; use crate::facts::TurnSubmissionType; +use crate::now_unix_millis; use crate::now_unix_seconds; use codex_app_server_protocol::CodexErrorInfo; use codex_app_server_protocol::CommandExecutionSource; @@ -261,7 +262,7 @@ pub struct GuardianReviewTrackContext { approval_request_source: GuardianApprovalRequestSource, reviewed_action: GuardianReviewedAction, review_timeout_ms: u64, - started_at: u64, + pub started_at_ms: u64, started_instant: Instant, } @@ -283,7 +284,7 @@ impl GuardianReviewTrackContext { approval_request_source, reviewed_action, review_timeout_ms, - started_at: now_unix_seconds(), + started_at_ms: now_unix_millis(), started_instant: Instant::now(), } } @@ -316,7 +317,7 @@ impl GuardianReviewTrackContext { tool_call_count: None, time_to_first_token_ms: result.time_to_first_token_ms, completion_latency_ms: Some(self.started_instant.elapsed().as_millis() as u64), - started_at: self.started_at, + started_at: self.started_at_ms / 1_000, completed_at: Some(now_unix_seconds()), input_tokens: result.token_usage.as_ref().map(|usage| usage.input_tokens), cached_input_tokens: result diff --git a/codex-rs/analytics/src/facts.rs b/codex-rs/analytics/src/facts.rs index 861e6534a2..d0446e8c0c 100644 --- a/codex-rs/analytics/src/facts.rs +++ b/codex-rs/analytics/src/facts.rs @@ -296,6 +296,7 @@ pub(crate) enum AnalyticsFact { request: Box, }, ServerResponse { + completed_at_ms: u64, response: Box, }, Notification(Box), diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs index d35fb96602..2ddb59c0cf 100644 --- a/codex-rs/analytics/src/reducer.rs +++ b/codex-rs/analytics/src/reducer.rs @@ -325,6 +325,7 @@ impl AnalyticsReducer { } => {} AnalyticsFact::ServerResponse { response: _response, + .. } => {} AnalyticsFact::Custom(input) => match input { CustomAnalyticsFact::SubAgentThreadStarted(input) => { diff --git a/codex-rs/ansi-escape/Cargo.toml b/codex-rs/ansi-escape/Cargo.toml index 3ebad2bdef..9e0f8a8123 100644 --- a/codex-rs/ansi-escape/Cargo.toml +++ b/codex-rs/ansi-escape/Cargo.toml @@ -7,6 +7,8 @@ license.workspace = true [lib] name = "codex_ansi_escape" path = "src/lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/app-server-client/Cargo.toml b/codex-rs/app-server-client/Cargo.toml index fee29db47e..ac284cbdfe 100644 --- a/codex-rs/app-server-client/Cargo.toml +++ b/codex-rs/app-server-client/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_app_server_client" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/app-server-protocol/Cargo.toml b/codex-rs/app-server-protocol/Cargo.toml index 0cb50d8549..0749b07e08 100644 --- a/codex-rs/app-server-protocol/Cargo.toml +++ b/codex-rs/app-server-protocol/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_app_server_protocol" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index cac1c33d9b..65ee575185 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1845,31 +1845,6 @@ } ] }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileNetworkPermissions": { "properties": { "enabled": { @@ -1884,20 +1859,11 @@ "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" @@ -2091,8 +2057,18 @@ ], "type": "object" }, + "PluginShareUpdateDiscoverability": { + "enum": [ + "UNLISTED", + "PRIVATE" + ], + "type": "string" + }, "PluginShareUpdateTargetsParams": { "properties": { + "discoverability": { + "$ref": "#/definitions/PluginShareUpdateDiscoverability" + }, "remotePluginId": { "type": "string" }, @@ -2104,6 +2080,7 @@ } }, "required": [ + "discoverability", "remotePluginId", "shareTargets" ], @@ -3106,13 +3083,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ @@ -3212,24 +3182,6 @@ ], "type": "object" }, - "SkillsListExtraRootsForCwd": { - "properties": { - "cwd": { - "type": "string" - }, - "extraUserRoots": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "extraUserRoots" - ], - "type": "object" - }, "SkillsListParams": { "properties": { "cwds": { @@ -3242,17 +3194,6 @@ "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" - ] } }, "type": "object" @@ -3408,7 +3349,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for fork. The server rejects this field because the source permission profile value is preserved across fork." }, "serviceTier": { "type": [ @@ -3819,7 +3761,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for resume. The server rejects this field because the persisted permission profile value is preserved across resume." }, "serviceTier": { "type": [ @@ -4096,6 +4039,31 @@ ], "type": "object" }, + "TurnItemsView": { + "oneOf": [ + { + "description": "`items` was not loaded for this turn. The field is intentionally empty.", + "enum": [ + "notLoaded" + ], + "type": "string" + }, + { + "description": "`items` contains only a display summary for this turn.", + "enum": [ + "summary" + ], + "type": "string" + }, + { + "description": "`items` contains every ThreadItem available from persisted app-server history for this turn.", + "enum": [ + "full" + ], + "type": "string" + } + ] + }, "TurnStartParams": { "properties": { "approvalPolicy": { @@ -4174,7 +4142,7 @@ "type": "null" } ], - "description": "Override the sandbox policy for this turn and subsequent turns." + "description": "Deprecated for turns. The server rejects this field because the thread permission profile value is not mutable through `turn/start`." }, "serviceTier": { "description": "Override the service tier for this turn and subsequent turns.", @@ -6181,4 +6149,4 @@ } ], "title": "ClientRequest" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json index ce587a7f10..5b6c4cd185 100644 --- a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json @@ -593,6 +593,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -602,6 +607,7 @@ }, "required": [ "itemId", + "startedAtMs", "threadId", "turnId" ], diff --git a/codex-rs/app-server-protocol/schema/json/FileChangeRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/FileChangeRequestApprovalParams.json index f52e98cd0d..f17388aa53 100644 --- a/codex-rs/app-server-protocol/schema/json/FileChangeRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/FileChangeRequestApprovalParams.json @@ -18,6 +18,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -27,6 +32,7 @@ }, "required": [ "itemId", + "startedAtMs", "threadId", "turnId" ], diff --git a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json index adb50dee43..1383da6124 100644 --- a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json @@ -297,6 +297,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -308,6 +313,7 @@ "cwd", "itemId", "permissions", + "startedAtMs", "threadId", "turnId" ], diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 5dc3c09a44..4e9e63d302 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1963,6 +1963,11 @@ "action": { "$ref": "#/definitions/GuardianApprovalReviewAction" }, + "completedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review completed.", + "format": "int64", + "type": "integer" + }, "decisionSource": { "$ref": "#/definitions/AutoReviewDecisionSource" }, @@ -1973,6 +1978,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -1989,9 +1999,11 @@ }, "required": [ "action", + "completedAtMs", "decisionSource", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], @@ -2010,6 +2022,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -2028,6 +2045,7 @@ "action", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index 51cab50810..9844eac0b8 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -417,6 +417,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -426,6 +431,7 @@ }, "required": [ "itemId", + "startedAtMs", "threadId", "turnId" ], @@ -598,6 +604,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -607,6 +618,7 @@ }, "required": [ "itemId", + "startedAtMs", "threadId", "turnId" ], @@ -1587,6 +1599,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -1598,6 +1615,7 @@ "cwd", "itemId", "permissions", + "startedAtMs", "threadId", "turnId" ], 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 5e24845729..5a8a208486 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 @@ -2146,6 +2146,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -2155,6 +2160,7 @@ }, "required": [ "itemId", + "startedAtMs", "threadId", "turnId" ], @@ -2411,6 +2417,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -2420,6 +2431,7 @@ }, "required": [ "itemId", + "startedAtMs", "threadId", "turnId" ], @@ -3591,6 +3603,11 @@ "null" ] }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this approval request started.", + "format": "int64", + "type": "integer" + }, "threadId": { "type": "string" }, @@ -3602,6 +3619,7 @@ "cwd", "itemId", "permissions", + "startedAtMs", "threadId", "turnId" ], @@ -5516,14 +5534,6 @@ "id": { "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", "type": "string" - }, - "modifications": { - "default": [], - "description": "Bounded user-requested modifications applied on top of the named profile, if any.", - "items": { - "$ref": "#/definitions/v2/ActivePermissionProfileModification" - }, - "type": "array" } }, "required": [ @@ -5531,31 +5541,6 @@ ], "type": "object" }, - "ActivePermissionProfileModification": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/v2/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootActivePermissionProfileModificationType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootActivePermissionProfileModification", - "type": "object" - } - ] - }, "AddCreditsNudgeCreditType": { "enum": [ "credits", @@ -9878,6 +9863,11 @@ "action": { "$ref": "#/definitions/v2/GuardianApprovalReviewAction" }, + "completedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review completed.", + "format": "int64", + "type": "integer" + }, "decisionSource": { "$ref": "#/definitions/v2/AutoReviewDecisionSource" }, @@ -9888,6 +9878,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -9904,9 +9899,11 @@ }, "required": [ "action", + "completedAtMs", "decisionSource", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], @@ -9927,6 +9924,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -9945,6 +9947,7 @@ "action", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], @@ -11619,31 +11622,6 @@ } ] }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/v2/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileNetworkPermissions": { "properties": { "enabled": { @@ -11658,20 +11636,11 @@ "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/v2/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" @@ -12378,9 +12347,19 @@ ], "type": "object" }, + "PluginShareUpdateDiscoverability": { + "enum": [ + "UNLISTED", + "PRIVATE" + ], + "type": "string" + }, "PluginShareUpdateTargetsParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "discoverability": { + "$ref": "#/definitions/v2/PluginShareUpdateDiscoverability" + }, "remotePluginId": { "type": "string" }, @@ -12392,6 +12371,7 @@ } }, "required": [ + "discoverability", "remotePluginId", "shareTargets" ], @@ -12401,6 +12381,9 @@ "PluginShareUpdateTargetsResponse": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "discoverability": { + "$ref": "#/definitions/v2/PluginShareDiscoverability" + }, "principals": { "items": { "$ref": "#/definitions/v2/PluginSharePrincipal" @@ -12409,6 +12392,7 @@ } }, "required": [ + "discoverability", "principals" ], "title": "PluginShareUpdateTargetsResponse", @@ -14257,13 +14241,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/v2/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ @@ -14730,24 +14707,6 @@ ], "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": { @@ -14761,17 +14720,6 @@ "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/v2/SkillsListExtraRootsForCwd" - }, - "type": [ - "array", - "null" - ] } }, "title": "SkillsListParams", @@ -15280,7 +15228,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for fork. The server rejects this field because the source permission profile value is preserved across fork." }, "serviceTier": { "type": [ @@ -16783,7 +16732,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for resume. The server rejects this field because the persisted permission profile value is preserved across resume." }, "serviceTier": { "type": [ @@ -17825,7 +17775,7 @@ "type": "null" } ], - "description": "Override the sandbox policy for this turn and subsequent turns." + "description": "Deprecated for turns. The server rejects this field because the thread permission profile value is not mutable through `turn/start`." }, "serviceTier": { "description": "Override the service tier for this turn and subsequent turns.", @@ -18389,4 +18339,4 @@ }, "title": "CodexAppServerProtocol", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 6153a54eb9..464c272c1d 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -143,14 +143,6 @@ "id": { "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", "type": "string" - }, - "modifications": { - "default": [], - "description": "Bounded user-requested modifications applied on top of the named profile, if any.", - "items": { - "$ref": "#/definitions/ActivePermissionProfileModification" - }, - "type": "array" } }, "required": [ @@ -158,31 +150,6 @@ ], "type": "object" }, - "ActivePermissionProfileModification": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootActivePermissionProfileModificationType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootActivePermissionProfileModification", - "type": "object" - } - ] - }, "AddCreditsNudgeCreditType": { "enum": [ "credits", @@ -6489,6 +6456,11 @@ "action": { "$ref": "#/definitions/GuardianApprovalReviewAction" }, + "completedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review completed.", + "format": "int64", + "type": "integer" + }, "decisionSource": { "$ref": "#/definitions/AutoReviewDecisionSource" }, @@ -6499,6 +6471,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -6515,9 +6492,11 @@ }, "required": [ "action", + "completedAtMs", "decisionSource", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], @@ -6538,6 +6517,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -6556,6 +6540,7 @@ "action", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], @@ -8230,31 +8215,6 @@ } ] }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileNetworkPermissions": { "properties": { "enabled": { @@ -8269,20 +8229,11 @@ "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" @@ -8989,9 +8940,19 @@ ], "type": "object" }, + "PluginShareUpdateDiscoverability": { + "enum": [ + "UNLISTED", + "PRIVATE" + ], + "type": "string" + }, "PluginShareUpdateTargetsParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "discoverability": { + "$ref": "#/definitions/PluginShareUpdateDiscoverability" + }, "remotePluginId": { "type": "string" }, @@ -9003,6 +8964,7 @@ } }, "required": [ + "discoverability", "remotePluginId", "shareTargets" ], @@ -9012,6 +8974,9 @@ "PluginShareUpdateTargetsResponse": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "discoverability": { + "$ref": "#/definitions/PluginShareDiscoverability" + }, "principals": { "items": { "$ref": "#/definitions/PluginSharePrincipal" @@ -9020,6 +8985,7 @@ } }, "required": [ + "discoverability", "principals" ], "title": "PluginShareUpdateTargetsResponse", @@ -10868,13 +10834,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ @@ -12616,24 +12575,6 @@ ], "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": { @@ -12647,17 +12588,6 @@ "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", @@ -13166,7 +13096,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for fork. The server rejects this field because the source permission profile value is preserved across fork." }, "serviceTier": { "type": [ @@ -14669,7 +14600,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for resume. The server rejects this field because the persisted permission profile value is preserved across resume." }, "serviceTier": { "type": [ @@ -15711,7 +15643,7 @@ "type": "null" } ], - "description": "Override the sandbox policy for this turn and subsequent turns." + "description": "Deprecated for turns. The server rejects this field because the thread permission profile value is not mutable through `turn/start`." }, "serviceTier": { "description": "Override the service tier for this turn and subsequent turns.", @@ -16274,4 +16206,4 @@ }, "title": "CodexAppServerProtocolV2", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json b/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json index f29483862c..6a1098fda4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json @@ -441,13 +441,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json index 98f44e50a2..991d4de050 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json @@ -574,6 +574,11 @@ "action": { "$ref": "#/definitions/GuardianApprovalReviewAction" }, + "completedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review completed.", + "format": "int64", + "type": "integer" + }, "decisionSource": { "$ref": "#/definitions/AutoReviewDecisionSource" }, @@ -584,6 +589,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -600,9 +610,11 @@ }, "required": [ "action", + "completedAtMs", "decisionSource", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json index 16e47c2d72..75ffeb753a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json @@ -574,6 +574,11 @@ "description": "Stable identifier for this review.", "type": "string" }, + "startedAtMs": { + "description": "Unix timestamp (in milliseconds) when this review started.", + "format": "int64", + "type": "integer" + }, "targetItemId": { "description": "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", "type": [ @@ -592,6 +597,7 @@ "action", "review", "reviewId", + "startedAtMs", "threadId", "turnId" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsParams.json b/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsParams.json index 080ec980a1..f6b44c92eb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsParams.json @@ -23,9 +23,19 @@ "principalType" ], "type": "object" + }, + "PluginShareUpdateDiscoverability": { + "enum": [ + "UNLISTED", + "PRIVATE" + ], + "type": "string" } }, "properties": { + "discoverability": { + "$ref": "#/definitions/PluginShareUpdateDiscoverability" + }, "remotePluginId": { "type": "string" }, @@ -37,6 +47,7 @@ } }, "required": [ + "discoverability", "remotePluginId", "shareTargets" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsResponse.json index 28fcb665ba..fe47f1f4af 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginShareUpdateTargetsResponse.json @@ -1,6 +1,14 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { + "PluginShareDiscoverability": { + "enum": [ + "LISTED", + "UNLISTED", + "PRIVATE" + ], + "type": "string" + }, "PluginSharePrincipal": { "properties": { "name": { @@ -30,6 +38,9 @@ } }, "properties": { + "discoverability": { + "$ref": "#/definitions/PluginShareDiscoverability" + }, "principals": { "items": { "$ref": "#/definitions/PluginSharePrincipal" @@ -38,6 +49,7 @@ } }, "required": [ + "discoverability", "principals" ], "title": "PluginShareUpdateTargetsResponse", diff --git a/codex-rs/app-server-protocol/schema/json/v2/SkillsListParams.json b/codex-rs/app-server-protocol/schema/json/v2/SkillsListParams.json index 77d12e9175..a9a8a9ef8d 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/SkillsListParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/SkillsListParams.json @@ -1,25 +1,5 @@ { "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "SkillsListExtraRootsForCwd": { - "properties": { - "cwd": { - "type": "string" - }, - "extraUserRoots": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "cwd", - "extraUserRoots" - ], - "type": "object" - } - }, "properties": { "cwds": { "description": "When empty, defaults to the current session working directory.", @@ -31,17 +11,6 @@ "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", 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 29d67403cd..033b101e7b 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json @@ -64,48 +64,14 @@ } ] }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" @@ -212,7 +178,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for fork. The server rejects this field because the source permission profile value is preserved across fork." }, "serviceTier": { "type": [ 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 6e74ab4ac8..2415a52bb2 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -18,14 +18,6 @@ "id": { "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", "type": "string" - }, - "modifications": { - "default": [], - "description": "Bounded user-requested modifications applied on top of the named profile, if any.", - "items": { - "$ref": "#/definitions/ActivePermissionProfileModification" - }, - "type": "array" } }, "required": [ @@ -33,31 +25,6 @@ ], "type": "object" }, - "ActivePermissionProfileModification": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootActivePermissionProfileModificationType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootActivePermissionProfileModification", - "type": "object" - } - ] - }, "AgentPath": { "type": "string" }, @@ -1160,13 +1127,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ 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 5f07fe0149..8a1ea00d89 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -298,48 +298,14 @@ } ] }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" @@ -1091,7 +1057,8 @@ { "type": "null" } - ] + ], + "description": "Deprecated for resume. The server rejects this field because the persisted permission profile value is preserved across resume." }, "serviceTier": { "type": [ 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 727b7a3fb2..f0c6fa8ba1 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -18,14 +18,6 @@ "id": { "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", "type": "string" - }, - "modifications": { - "default": [], - "description": "Bounded user-requested modifications applied on top of the named profile, if any.", - "items": { - "$ref": "#/definitions/ActivePermissionProfileModification" - }, - "type": "array" } }, "required": [ @@ -33,31 +25,6 @@ ], "type": "object" }, - "ActivePermissionProfileModification": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootActivePermissionProfileModificationType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootActivePermissionProfileModification", - "type": "object" - } - ] - }, "AgentPath": { "type": "string" }, @@ -1160,13 +1127,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ 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 9a60049a61..984d0cb153 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -90,48 +90,14 @@ ], "type": "object" }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" 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 bf03f0fb55..bd669a98be 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -18,14 +18,6 @@ "id": { "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", "type": "string" - }, - "modifications": { - "default": [], - "description": "Bounded user-requested modifications applied on top of the named profile, if any.", - "items": { - "$ref": "#/definitions/ActivePermissionProfileModification" - }, - "type": "array" } }, "required": [ @@ -33,31 +25,6 @@ ], "type": "object" }, - "ActivePermissionProfileModification": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootActivePermissionProfileModificationType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootActivePermissionProfileModification", - "type": "object" - } - ] - }, "AgentPath": { "type": "string" }, @@ -1160,13 +1127,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ 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 1ef33d4301..7d9eb91d06 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -114,48 +114,14 @@ ], "type": "string" }, - "PermissionProfileModificationParams": { - "oneOf": [ - { - "description": "Additional concrete directory that should be writable.", - "properties": { - "path": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": { - "enum": [ - "additionalWritableRoot" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParamsType", - "type": "string" - } - }, - "required": [ - "path", - "type" - ], - "title": "AdditionalWritableRootPermissionProfileModificationParams", - "type": "object" - } - ] - }, "PermissionProfileSelectionParams": { "oneOf": [ { - "description": "Select a named built-in or user-defined profile and optionally apply bounded modifications that Codex knows how to validate.", + "description": "Select a named built-in or user-defined profile. This updates profile identity metadata only; it does not replace the thread's effective permissions profile.", "properties": { "id": { "type": "string" }, - "modifications": { - "items": { - "$ref": "#/definitions/PermissionProfileModificationParams" - }, - "type": [ - "array", - "null" - ] - }, "type": { "enum": [ "profile" @@ -295,13 +261,6 @@ ], "title": "WorkspaceWriteSandboxPolicyType", "type": "string" - }, - "writableRoots": { - "default": [], - "items": { - "$ref": "#/definitions/AbsolutePathBuf" - }, - "type": "array" } }, "required": [ @@ -576,7 +535,7 @@ "type": "null" } ], - "description": "Override the sandbox policy for this turn and subsequent turns." + "description": "Deprecated for turns. The server rejects this field because the thread permission profile value is not mutable through `turn/start`." }, "serviceTier": { "description": "Override the service tier for this turn and subsequent turns.", diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts index cbc8c6ef0a..73f9efcab5 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts @@ -1,7 +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 { ActivePermissionProfileModification } from "./ActivePermissionProfileModification"; export type ActivePermissionProfile = { /** @@ -13,9 +12,4 @@ id: string, * Parent profile identifier once permissions profiles support * inheritance. This is currently always `null`. */ -extends: string | null, -/** - * Bounded user-requested modifications applied on top of the named - * profile, if any. - */ -modifications: Array, }; +extends: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfileModification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfileModification.ts deleted file mode 100644 index 1cbee6868a..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfileModification.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 ActivePermissionProfileModification = { "type": "additionalWritableRoot", path: AbsolutePathBuf, }; 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 ca2d0b0aa0..0e9100836a 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts @@ -8,6 +8,9 @@ import type { NetworkApprovalContext } from "./NetworkApprovalContext"; import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; export type CommandExecutionRequestApprovalParams = {threadId: string, turnId: string, itemId: string, /** + * Unix timestamp (in milliseconds) when this approval request started. + */ +startedAtMs: number, /** * Unique identifier for this specific approval callback. * * For regular shell/unified_exec approvals, this is null. diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FileChangeRequestApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FileChangeRequestApprovalParams.ts index c514ed6219..2db7be9ec4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FileChangeRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FileChangeRequestApprovalParams.ts @@ -3,6 +3,10 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. export type FileChangeRequestApprovalParams = { threadId: string, turnId: string, itemId: string, +/** + * Unix timestamp (in milliseconds) when this approval request started. + */ +startedAtMs: number, /** * Optional explanatory reason (e.g. request for extra write access). */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewCompletedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewCompletedNotification.ts index 5b162cf4b9..32d12be608 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewCompletedNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewCompletedNotification.ts @@ -10,6 +10,14 @@ import type { GuardianApprovalReviewAction } from "./GuardianApprovalReviewActio * shape is expected to change soon. */ export type ItemGuardianApprovalReviewCompletedNotification = { threadId: string, turnId: string, +/** + * Unix timestamp (in milliseconds) when this review started. + */ +startedAtMs: number, +/** + * Unix timestamp (in milliseconds) when this review completed. + */ +completedAtMs: number, /** * Stable identifier for this review. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewStartedNotification.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewStartedNotification.ts index 81ba2cdebf..92d34fdebc 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewStartedNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ItemGuardianApprovalReviewStartedNotification.ts @@ -9,6 +9,10 @@ import type { GuardianApprovalReviewAction } from "./GuardianApprovalReviewActio * shape is expected to change soon. */ export type ItemGuardianApprovalReviewStartedNotification = { threadId: string, turnId: string, +/** + * Unix timestamp (in milliseconds) when this review started. + */ +startedAtMs: number, /** * Stable identifier for this review. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileModificationParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileModificationParams.ts deleted file mode 100644 index c619edcea8..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileModificationParams.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 PermissionProfileModificationParams = { "type": "additionalWritableRoot", path: AbsolutePathBuf, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileSelectionParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileSelectionParams.ts index a415bd0028..c55fc29245 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileSelectionParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PermissionProfileSelectionParams.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 { PermissionProfileModificationParams } from "./PermissionProfileModificationParams"; -export type PermissionProfileSelectionParams = { "type": "profile", id: string, modifications?: Array | null, }; +export type PermissionProfileSelectionParams = { "type": "profile", id: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionsRequestApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PermissionsRequestApprovalParams.ts index 308670a809..509f60923b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionsRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PermissionsRequestApprovalParams.ts @@ -4,4 +4,8 @@ import type { AbsolutePathBuf } from "../AbsolutePathBuf"; import type { RequestPermissionProfile } from "./RequestPermissionProfile"; -export type PermissionsRequestApprovalParams = { threadId: string, turnId: string, itemId: string, cwd: AbsolutePathBuf, reason: string | null, permissions: RequestPermissionProfile, }; +export type PermissionsRequestApprovalParams = { threadId: string, turnId: string, itemId: string, +/** + * Unix timestamp (in milliseconds) when this approval request started. + */ +startedAtMs: number, cwd: AbsolutePathBuf, reason: string | null, permissions: RequestPermissionProfile, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsListExtraRootsForCwd.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateDiscoverability.ts similarity index 62% rename from codex-rs/app-server-protocol/schema/typescript/v2/SkillsListExtraRootsForCwd.ts rename to codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateDiscoverability.ts index c18cd4ba1d..fd601987af 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsListExtraRootsForCwd.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateDiscoverability.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 SkillsListExtraRootsForCwd = { cwd: string, extraUserRoots: Array, }; +export type PluginShareUpdateDiscoverability = "UNLISTED" | "PRIVATE"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsParams.ts index 53ef2b3025..eecd4be82b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsParams.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 { PluginShareTarget } from "./PluginShareTarget"; +import type { PluginShareUpdateDiscoverability } from "./PluginShareUpdateDiscoverability"; -export type PluginShareUpdateTargetsParams = { remotePluginId: string, shareTargets: Array, }; +export type PluginShareUpdateTargetsParams = { remotePluginId: string, discoverability: PluginShareUpdateDiscoverability, shareTargets: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsResponse.ts index 3d6f6e9ee0..0ce722460f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PluginShareUpdateTargetsResponse.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 { PluginShareDiscoverability } from "./PluginShareDiscoverability"; import type { PluginSharePrincipal } from "./PluginSharePrincipal"; -export type PluginShareUpdateTargetsResponse = { principals: Array, }; +export type PluginShareUpdateTargetsResponse = { principals: Array, discoverability: PluginShareDiscoverability, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts index 5575701ff2..1715d7710e 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SandboxPolicy.ts @@ -1,7 +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"; import type { NetworkAccess } from "./NetworkAccess"; -export type SandboxPolicy = { "type": "dangerFullAccess" } | { "type": "readOnly", networkAccess: boolean, } | { "type": "externalSandbox", networkAccess: NetworkAccess, } | { "type": "workspaceWrite", writableRoots: Array, networkAccess: boolean, excludeTmpdirEnvVar: boolean, excludeSlashTmp: boolean, }; +export type SandboxPolicy = { "type": "dangerFullAccess" } | { "type": "readOnly", networkAccess: boolean, } | { "type": "externalSandbox", networkAccess: NetworkAccess, } | { "type": "workspaceWrite", networkAccess: boolean, excludeTmpdirEnvVar: boolean, excludeSlashTmp: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsListParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsListParams.ts index ad714a3297..4adeb38b3b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsListParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsListParams.ts @@ -1,7 +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 { SkillsListExtraRootsForCwd } from "./SkillsListExtraRootsForCwd"; export type SkillsListParams = { /** @@ -11,8 +10,4 @@ cwds?: Array, /** * When true, bypass the skills cache and re-scan skills from disk. */ -forceReload?: boolean, -/** - * Optional per-cwd extra roots to scan as user-scoped skills. - */ -perCwdExtraUserRoots?: Array | null, }; +forceReload?: boolean, }; 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 6076a4bb14..2facd2daaf 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts @@ -23,7 +23,11 @@ model?: string | null, modelProvider?: string | null, serviceTier?: string | nul * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, ephemeral?: boolean, /** +approvalsReviewer?: ApprovalsReviewer | null, /** + * Deprecated for fork. The server rejects this field because the source + * permission profile value is preserved across fork. + */ +sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, ephemeral?: boolean, /** * Optional client-supplied analytics source classification for this forked thread. */ threadSource?: ThreadSource | null}; 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 6d1dbdca4f..cf343dc28c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts @@ -25,4 +25,8 @@ model?: string | null, modelProvider?: string | null, serviceTier?: string | nul * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null}; +approvalsReviewer?: ApprovalsReviewer | null, /** + * Deprecated for resume. The server rejects this field because the + * persisted permission profile value is preserved across resume. + */ +sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts index b04919d86b..b2324294d1 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts @@ -21,7 +21,8 @@ approvalPolicy?: AskForApproval | null, /** * subsequent turns. */ approvalsReviewer?: ApprovalsReviewer | null, /** - * Override the sandbox policy for this turn and subsequent turns. + * Deprecated for turns. The server rejects this field because the + * thread permission profile value is not mutable through `turn/start`. */ sandboxPolicy?: SandboxPolicy | null, /** * Override the model for this turn and subsequent turns. 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 950dd9839a..03004573a7 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -5,7 +5,6 @@ export type { AccountLoginCompletedNotification } from "./AccountLoginCompletedN export type { AccountRateLimitsUpdatedNotification } from "./AccountRateLimitsUpdatedNotification"; export type { AccountUpdatedNotification } from "./AccountUpdatedNotification"; export type { ActivePermissionProfile } from "./ActivePermissionProfile"; -export type { ActivePermissionProfileModification } from "./ActivePermissionProfileModification"; export type { AddCreditsNudgeCreditType } from "./AddCreditsNudgeCreditType"; export type { AddCreditsNudgeEmailStatus } from "./AddCreditsNudgeEmailStatus"; export type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions"; @@ -255,7 +254,6 @@ export type { PatchChangeKind } from "./PatchChangeKind"; export type { PermissionGrantScope } from "./PermissionGrantScope"; export type { PermissionProfile } from "./PermissionProfile"; export type { PermissionProfileFileSystemPermissions } from "./PermissionProfileFileSystemPermissions"; -export type { PermissionProfileModificationParams } from "./PermissionProfileModificationParams"; export type { PermissionProfileNetworkPermissions } from "./PermissionProfileNetworkPermissions"; export type { PermissionProfileSelectionParams } from "./PermissionProfileSelectionParams"; export type { PermissionsRequestApprovalParams } from "./PermissionsRequestApprovalParams"; @@ -287,6 +285,7 @@ export type { PluginSharePrincipalType } from "./PluginSharePrincipalType"; export type { PluginShareSaveParams } from "./PluginShareSaveParams"; export type { PluginShareSaveResponse } from "./PluginShareSaveResponse"; export type { PluginShareTarget } from "./PluginShareTarget"; +export type { PluginShareUpdateDiscoverability } from "./PluginShareUpdateDiscoverability"; export type { PluginShareUpdateTargetsParams } from "./PluginShareUpdateTargetsParams"; export type { PluginShareUpdateTargetsResponse } from "./PluginShareUpdateTargetsResponse"; export type { PluginSkillReadParams } from "./PluginSkillReadParams"; @@ -336,7 +335,6 @@ export type { SkillsChangedNotification } from "./SkillsChangedNotification"; export type { SkillsConfigWriteParams } from "./SkillsConfigWriteParams"; export type { SkillsConfigWriteResponse } from "./SkillsConfigWriteResponse"; export type { SkillsListEntry } from "./SkillsListEntry"; -export type { SkillsListExtraRootsForCwd } from "./SkillsListExtraRootsForCwd"; export type { SkillsListParams } from "./SkillsListParams"; export type { SkillsListResponse } from "./SkillsListResponse"; export type { SortDirection } from "./SortDirection"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index e79c99a9c9..d66f292bb6 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -581,6 +581,13 @@ client_request_definitions! { serialization: None, response: v2::ThreadTurnsListResponse, }, + #[experimental("thread/turns/items/list")] + ThreadTurnsItemsList => "thread/turns/items/list" { + params: v2::ThreadTurnsItemsListParams, + // Explicitly concurrent: this primarily reads append-only rollout storage. + serialization: None, + response: v2::ThreadTurnsItemsListResponse, + }, /// Append raw Responses API items to the thread history without starting a user turn. ThreadInjectItems => "thread/inject_items" { params: v2::ThreadInjectItemsParams, @@ -1649,7 +1656,6 @@ mod tests { params: v2::SkillsListParams { cwds: Vec::new(), force_reload: false, - per_cwd_extra_user_roots: None, }, }; assert_eq!( @@ -1843,10 +1849,23 @@ mod tests { cursor: None, limit: None, sort_direction: None, + items_view: None, }, }; assert_eq!(thread_turns_list.serialization_scope(), None); + let thread_turns_items_list = ClientRequest::ThreadTurnsItemsList { + request_id: request_id(), + params: v2::ThreadTurnsItemsListParams { + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + cursor: None, + limit: None, + sort_direction: None, + }, + }; + assert_eq!(thread_turns_items_list.serialization_scope(), None); + let mcp_resource_read = ClientRequest::McpResourceRead { request_id: request_id(), params: v2::McpResourceReadParams { @@ -2202,6 +2221,7 @@ mod tests { model_provider: "openai".to_string(), service_tier: None, cwd, + workspace_roots: vec![], instruction_sources: vec![absolute_path("/tmp/AGENTS.md")], approval_policy: v2::AskForApproval::OnFailure, approvals_reviewer: v2::ApprovalsReviewer::User, @@ -2246,6 +2266,7 @@ mod tests { "modelProvider": "openai", "serviceTier": null, "cwd": absolute_path_string("tmp"), + "workspaceRoots": [], "instructionSources": [absolute_path_string("tmp/AGENTS.md")], "approvalPolicy": "on-failure", "approvalsReviewer": "user", @@ -2947,6 +2968,7 @@ mod tests { thread_id: "thr_123".to_string(), turn_id: "turn_123".to_string(), item_id: "call_123".to_string(), + started_at_ms: 0, approval_id: None, reason: None, network_approval_context: None, diff --git a/codex-rs/app-server-protocol/src/protocol/item_builders.rs b/codex-rs/app-server-protocol/src/protocol/item_builders.rs index 69ba331ce6..17e0f9aef4 100644 --- a/codex-rs/app-server-protocol/src/protocol/item_builders.rs +++ b/codex-rs/app-server-protocol/src/protocol/item_builders.rs @@ -243,6 +243,7 @@ pub fn guardian_auto_approval_review_notification( thread_id: conversation_id.to_string(), turn_id, review_id: assessment.id.clone(), + started_at_ms: assessment.started_at_ms, target_item_id: assessment.target_item_id.clone(), review, action, @@ -258,6 +259,10 @@ pub fn guardian_auto_approval_review_notification( thread_id: conversation_id.to_string(), turn_id, review_id: assessment.id.clone(), + started_at_ms: assessment.started_at_ms, + completed_at_ms: assessment + .completed_at_ms + .unwrap_or(assessment.started_at_ms), target_item_id: assessment.target_item_id.clone(), decision_source: assessment .decision_source 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 1f45180c9e..1121d3a35b 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -2143,6 +2143,8 @@ mod tests { id: "review-guardian-exec".into(), target_item_id: Some("guardian-exec".into()), turn_id: "turn-1".into(), + started_at_ms: 1_000, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -2160,6 +2162,8 @@ mod tests { id: "review-guardian-exec".into(), target_item_id: Some("guardian-exec".into()), turn_id: "turn-1".into(), + started_at_ms: 1_000, + completed_at_ms: Some(1_042), status: GuardianAssessmentStatus::Denied, risk_level: Some(codex_protocol::protocol::GuardianRiskLevel::High), user_authorization: Some(codex_protocol::protocol::GuardianUserAuthorization::Low), @@ -2222,6 +2226,8 @@ mod tests { id: "review-guardian-execve".into(), target_item_id: Some("guardian-execve".into()), turn_id: "turn-1".into(), + started_at_ms: 2_000, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -2525,6 +2531,7 @@ mod tests { EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { call_id: "patch-call".into(), turn_id: turn_id.to_string(), + started_at_ms: 0, changes: [( PathBuf::from("README.md"), codex_protocol::protocol::FileChange::Add { diff --git a/codex-rs/app-server-protocol/src/protocol/v2/item.rs b/codex-rs/app-server-protocol/src/protocol/v2/item.rs index 2c3a926c91..0e22c48590 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/item.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/item.rs @@ -1073,6 +1073,9 @@ pub struct ItemStartedNotification { pub struct ItemGuardianApprovalReviewStartedNotification { pub thread_id: String, pub turn_id: String, + /// Unix timestamp (in milliseconds) when this review started. + #[ts(type = "number")] + pub started_at_ms: i64, /// Stable identifier for this review. pub review_id: String, /// Identifier for the reviewed item or tool call when one exists. @@ -1099,6 +1102,12 @@ pub struct ItemGuardianApprovalReviewStartedNotification { pub struct ItemGuardianApprovalReviewCompletedNotification { pub thread_id: String, pub turn_id: String, + /// Unix timestamp (in milliseconds) when this review started. + #[ts(type = "number")] + pub started_at_ms: i64, + /// Unix timestamp (in milliseconds) when this review completed. + #[ts(type = "number")] + pub completed_at_ms: i64, /// Stable identifier for this review. pub review_id: String, /// Identifier for the reviewed item or tool call when one exists. @@ -1248,6 +1257,9 @@ pub struct CommandExecutionRequestApprovalParams { pub thread_id: String, pub turn_id: String, pub item_id: String, + /// Unix timestamp (in milliseconds) when this approval request started. + #[ts(type = "number")] + pub started_at_ms: i64, /// Unique identifier for this specific approval callback. /// /// For regular shell/unified_exec approvals, this is null. @@ -1321,6 +1333,9 @@ pub struct FileChangeRequestApprovalParams { pub thread_id: String, pub turn_id: String, pub item_id: String, + /// Unix timestamp (in milliseconds) when this approval request started. + #[ts(type = "number")] + pub started_at_ms: i64, /// Optional explanatory reason (e.g. request for extra write access). #[ts(optional = nullable)] pub reason: Option, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/permissions.rs b/codex-rs/app-server-protocol/src/protocol/v2/permissions.rs index 8ce47e58cb..0b6b74a61c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/permissions.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/permissions.rs @@ -5,7 +5,6 @@ use codex_protocol::approvals::NetworkApprovalProtocol as CoreNetworkApprovalPro use codex_protocol::approvals::NetworkPolicyAmendment as CoreNetworkPolicyAmendment; use codex_protocol::approvals::NetworkPolicyRuleAction as CoreNetworkPolicyRuleAction; use codex_protocol::models::ActivePermissionProfile as CoreActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification as CoreActivePermissionProfileModification; use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile; use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions; use codex_protocol::models::ManagedFileSystemPermissions as CoreManagedFileSystemPermissions; @@ -437,41 +436,6 @@ pub struct ActivePermissionProfile { /// inheritance. This is currently always `null`. #[serde(default)] pub extends: Option, - /// Bounded user-requested modifications applied on top of the named - /// profile, if any. - #[serde(default)] - pub modifications: Vec, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] -#[serde(tag = "type", rename_all = "camelCase")] -#[ts(tag = "type")] -#[ts(export_to = "v2/")] -pub enum ActivePermissionProfileModification { - /// Additional concrete directory that should be writable. - #[serde(rename_all = "camelCase")] - #[ts(rename_all = "camelCase")] - AdditionalWritableRoot { path: AbsolutePathBuf }, -} - -impl From for ActivePermissionProfileModification { - fn from(value: CoreActivePermissionProfileModification) -> Self { - match value { - CoreActivePermissionProfileModification::AdditionalWritableRoot { path } => { - Self::AdditionalWritableRoot { path } - } - } - } -} - -impl From for CoreActivePermissionProfileModification { - fn from(value: ActivePermissionProfileModification) -> Self { - match value { - ActivePermissionProfileModification::AdditionalWritableRoot { path } => { - Self::AdditionalWritableRoot { path } - } - } - } } impl From for ActivePermissionProfile { @@ -479,11 +443,6 @@ impl From for ActivePermissionProfile { Self { id: value.id, extends: value.extends, - modifications: value - .modifications - .into_iter() - .map(ActivePermissionProfileModification::from) - .collect(), } } } @@ -493,11 +452,6 @@ impl From for CoreActivePermissionProfile { Self { id: value.id, extends: value.extends, - modifications: value - .modifications - .into_iter() - .map(CoreActivePermissionProfileModification::from) - .collect(), } } } @@ -507,26 +461,12 @@ impl From for CoreActivePermissionProfile { #[ts(tag = "type")] #[ts(export_to = "v2/")] pub enum PermissionProfileSelectionParams { - /// Select a named built-in or user-defined profile and optionally apply - /// bounded modifications that Codex knows how to validate. + /// Select a named built-in or user-defined profile. This updates profile + /// identity metadata only; it does not replace the thread's effective + /// permissions profile. #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] - Profile { - id: String, - #[ts(optional = nullable)] - modifications: Option>, - }, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] -#[serde(tag = "type", rename_all = "camelCase")] -#[ts(tag = "type")] -#[ts(export_to = "v2/")] -pub enum PermissionProfileModificationParams { - /// Additional concrete directory that should be writable. - #[serde(rename_all = "camelCase")] - #[ts(rename_all = "camelCase")] - AdditionalWritableRoot { path: AbsolutePathBuf }, + Profile { id: String }, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] @@ -607,8 +547,6 @@ pub enum SandboxPolicy { #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] WorkspaceWrite { - #[serde(default)] - writable_roots: Vec, #[serde(default)] network_access: bool, #[serde(default)] @@ -636,8 +574,8 @@ enum SandboxPolicyDeserialize { }, #[serde(rename_all = "camelCase")] WorkspaceWrite { - #[serde(default)] - writable_roots: Vec, + #[serde(default, rename = "writableRoots")] + _writable_roots: Vec, #[serde(default)] read_only_access: Option, #[serde(default)] @@ -678,7 +616,7 @@ impl<'de> Deserialize<'de> for SandboxPolicy { Ok(SandboxPolicy::ExternalSandbox { network_access }) } SandboxPolicyDeserialize::WorkspaceWrite { - writable_roots, + _writable_roots: _, read_only_access, network_access, exclude_tmpdir_env_var, @@ -690,7 +628,6 @@ impl<'de> Deserialize<'de> for SandboxPolicy { )); } Ok(SandboxPolicy::WorkspaceWrite { - writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, @@ -720,12 +657,10 @@ impl SandboxPolicy { } } SandboxPolicy::WorkspaceWrite { - writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, } => codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { - writable_roots: writable_roots.clone(), network_access: *network_access, exclude_tmpdir_env_var: *exclude_tmpdir_env_var, exclude_slash_tmp: *exclude_slash_tmp, @@ -752,12 +687,10 @@ impl From for SandboxPolicy { } } codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { - writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, } => SandboxPolicy::WorkspaceWrite { - writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, @@ -826,6 +759,9 @@ pub struct PermissionsRequestApprovalParams { pub thread_id: String, pub turn_id: String, pub item_id: String, + /// Unix timestamp (in milliseconds) when this approval request started. + #[ts(type = "number")] + pub started_at_ms: i64, pub cwd: AbsolutePathBuf, pub reason: Option, pub permissions: RequestPermissionProfile, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs index 20d68e6e55..6f425b4a6a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs @@ -15,7 +15,7 @@ use serde::Serialize; use std::path::PathBuf; use ts_rs::TS; -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct SkillsListParams { @@ -26,19 +26,6 @@ pub struct SkillsListParams { /// When true, bypass the skills cache and re-scan skills from disk. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub force_reload: bool, - - /// Optional per-cwd extra roots to scan as user-scoped skills. - #[serde(default)] - #[ts(optional = nullable)] - pub per_cwd_extra_user_roots: Option>, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "camelCase")] -#[ts(export_to = "v2/")] -pub struct SkillsListExtraRootsForCwd { - pub cwd: PathBuf, - pub extra_user_roots: Vec, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -231,6 +218,7 @@ pub struct PluginShareSaveResponse { #[ts(export_to = "v2/")] pub struct PluginShareUpdateTargetsParams { pub remote_plugin_id: String, + pub discoverability: PluginShareUpdateDiscoverability, pub share_targets: Vec, } @@ -239,6 +227,7 @@ pub struct PluginShareUpdateTargetsParams { #[ts(export_to = "v2/")] pub struct PluginShareUpdateTargetsResponse { pub principals: Vec, + pub discoverability: PluginShareDiscoverability, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -288,6 +277,17 @@ pub enum PluginShareDiscoverability { Private, } +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[ts(export_to = "v2/")] +pub enum PluginShareUpdateDiscoverability { + #[serde(rename = "UNLISTED")] + #[ts(rename = "UNLISTED")] + Unlisted, + #[serde(rename = "PRIVATE")] + #[ts(rename = "PRIVATE")] + Private, +} + #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] #[ts(export_to = "v2/")] pub enum PluginSharePrincipalType { diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index 4e923c5804..dd504aab96 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -95,6 +95,59 @@ fn turn_defaults_legacy_missing_items_view_to_full() { assert_eq!(turn.items_view, TurnItemsView::Full); } +#[test] +fn thread_turns_list_params_accepts_items_view() { + let params = serde_json::from_value::(json!({ + "threadId": "thr_123", + "cursor": null, + "limit": 25, + "sortDirection": "desc", + "itemsView": "notLoaded", + })) + .expect("thread turns list params should deserialize"); + + assert_eq!(params.thread_id, "thr_123"); + assert_eq!(params.items_view, Some(TurnItemsView::NotLoaded)); +} + +#[test] +fn thread_turns_items_list_round_trips() { + let params = ThreadTurnsItemsListParams { + thread_id: "thr_123".to_string(), + turn_id: "turn_456".to_string(), + cursor: Some("cursor_1".to_string()), + limit: Some(50), + sort_direction: Some(SortDirection::Asc), + }; + + assert_eq!( + serde_json::to_value(¶ms).expect("serialize params"), + json!({ + "threadId": "thr_123", + "turnId": "turn_456", + "cursor": "cursor_1", + "limit": 50, + "sortDirection": "asc", + }) + ); + let response = ThreadTurnsItemsListResponse { + data: vec![ThreadItem::ContextCompaction { + id: "item_1".to_string(), + }], + next_cursor: None, + backwards_cursor: Some("cursor_0".to_string()), + }; + + assert_eq!( + serde_json::to_value(&response).expect("serialize response"), + json!({ + "data": [{"type": "contextCompaction", "id": "item_1"}], + "nextCursor": null, + "backwardsCursor": "cursor_0", + }) + ); +} + #[test] fn thread_list_params_accepts_single_cwd() { let params = serde_json::from_value::(json!({ @@ -224,6 +277,7 @@ fn command_execution_request_approval_rejects_relative_additional_permission_pat "threadId": "thr_123", "turnId": "turn_123", "itemId": "call_123", + "startedAtMs": 1, "command": "cat file", "cwd": absolute_path_string("tmp"), "commandActions": null, @@ -264,6 +318,7 @@ fn permissions_request_approval_uses_request_permission_profile() { "threadId": "thr_123", "turnId": "turn_123", "itemId": "call_123", + "startedAtMs": 1, "cwd": absolute_path_string("repo"), "reason": "Select a workspace root", "permissions": { @@ -326,6 +381,7 @@ fn permissions_request_approval_rejects_macos_permissions() { "threadId": "thr_123", "turnId": "turn_123", "itemId": "call_123", + "startedAtMs": 1, "cwd": absolute_path_string("repo"), "reason": "Select a workspace root", "permissions": { @@ -1963,7 +2019,6 @@ fn mcp_server_elicitation_response_serializes_nullable_content() { #[test] fn sandbox_policy_round_trips_workspace_write_access() { let v2_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -1973,7 +2028,6 @@ fn sandbox_policy_round_trips_workspace_write_access() { assert_eq!( core_policy, codex_protocol::protocol::SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -2019,7 +2073,6 @@ fn sandbox_policy_deserializes_legacy_workspace_write_full_access_field() { assert_eq!( policy, SandboxPolicy::WorkspaceWrite { - writable_roots: vec![absolute_path("/workspace")], network_access: true, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -2452,33 +2505,20 @@ fn skills_list_params_serialization_uses_force_reload() { serde_json::to_value(SkillsListParams { cwds: Vec::new(), force_reload: false, - per_cwd_extra_user_roots: None, }) .unwrap(), - json!({ - "perCwdExtraUserRoots": null, - }), + json!({}), ); assert_eq!( serde_json::to_value(SkillsListParams { cwds: vec![PathBuf::from("/repo")], force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: PathBuf::from("/repo"), - extra_user_roots: vec![PathBuf::from("/shared/skills"), PathBuf::from("/tmp/x")], - }]), }) .unwrap(), json!({ "cwds": ["/repo"], "forceReload": true, - "perCwdExtraUserRoots": [ - { - "cwd": "/repo", - "extraUserRoots": ["/shared/skills", "/tmp/x"], - } - ], }), ); } @@ -2893,6 +2933,7 @@ fn plugin_share_params_and_response_serialization_use_camel_case_fields() { assert_eq!( serde_json::to_value(PluginShareUpdateTargetsParams { remote_plugin_id: "plugins~Plugin_00000000000000000000000000000000".to_string(), + discoverability: PluginShareUpdateDiscoverability::Unlisted, share_targets: vec![PluginShareTarget { principal_type: PluginSharePrincipalType::Group, principal_id: "group-1".to_string(), @@ -2901,6 +2942,7 @@ fn plugin_share_params_and_response_serialization_use_camel_case_fields() { .unwrap(), json!({ "remotePluginId": "plugins~Plugin_00000000000000000000000000000000", + "discoverability": "UNLISTED", "shareTargets": [{ "principalType": "group", "principalId": "group-1", @@ -2915,6 +2957,7 @@ fn plugin_share_params_and_response_serialization_use_camel_case_fields() { principal_id: "user-1".to_string(), name: "Gavin".to_string(), }], + discoverability: PluginShareDiscoverability::Unlisted, }) .unwrap(), json!({ @@ -2923,6 +2966,7 @@ fn plugin_share_params_and_response_serialization_use_camel_case_fields() { "principalId": "user-1", "name": "Gavin", }], + "discoverability": "UNLISTED", }), ); @@ -3362,6 +3406,7 @@ fn turn_start_params_preserve_explicit_null_service_tier() { responsesapi_client_metadata: None, environments: None, cwd: None, + workspace_roots: None, approval_policy: None, approvals_reviewer: None, sandbox_policy: None, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs index 5f293ff8f6..3a80405cef 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -6,9 +6,11 @@ use super::PermissionProfileSelectionParams; use super::SandboxMode; use super::SandboxPolicy; use super::Thread; +use super::ThreadItem; use super::ThreadSource; use super::Turn; use super::TurnEnvironmentParams; +use super::TurnItemsView; use super::shared::v2_enum_from_core; use codex_experimental_api_macros::ExperimentalApi; use codex_protocol::config_types::Personality; @@ -105,6 +107,11 @@ pub struct ThreadStartParams { pub service_tier: Option>, #[ts(optional = nullable)] pub cwd: Option, + /// Optional workspace roots for this thread. Omitted uses the server's + /// configured roots, usually seeded from `cwd`. + #[experimental("thread/start.workspaceRoots")] + #[ts(optional = nullable)] + pub workspace_roots: Option>, #[experimental(nested)] #[ts(optional = nullable)] pub approval_policy: Option, @@ -114,9 +121,8 @@ pub struct ThreadStartParams { pub approvals_reviewer: Option, #[ts(optional = nullable)] pub sandbox: Option, - /// Named profile selection for this thread. Cannot be combined with - /// `sandbox`. Use bounded `modifications` for supported turn/thread - /// adjustments instead of replacing the full permissions profile. + /// Named profile selection for this new thread's initial permissions. + /// Cannot be combined with `sandbox`. #[experimental("thread/start.permissions")] #[ts(optional = nullable)] pub permissions: Option, @@ -193,6 +199,11 @@ pub struct ThreadStartResponse { pub model_provider: String, pub service_tier: Option, pub cwd: AbsolutePathBuf, + /// Workspace roots used to realize symbolic `:project_roots` permission + /// entries for this thread. + #[experimental("thread/start.workspaceRoots")] + #[serde(default)] + pub workspace_roots: Vec, /// Instruction source files currently loaded for this thread. #[serde(default)] pub instruction_sources: Vec, @@ -262,6 +273,11 @@ pub struct ThreadResumeParams { pub service_tier: Option>, #[ts(optional = nullable)] pub cwd: Option, + /// Optional replacement workspace roots for the resumed thread. Omitted + /// preserves the persisted or configured roots. + #[experimental("thread/resume.workspaceRoots")] + #[ts(optional = nullable)] + pub workspace_roots: Option>, #[experimental(nested)] #[ts(optional = nullable)] pub approval_policy: Option, @@ -269,11 +285,13 @@ pub struct ThreadResumeParams { /// and subsequent turns. #[ts(optional = nullable)] pub approvals_reviewer: Option, + /// Deprecated for resume. The server rejects this field because the + /// persisted permission profile value is preserved across resume. #[ts(optional = nullable)] pub sandbox: Option, /// Named profile selection for the resumed thread. Cannot be combined - /// with `sandbox`. Use bounded `modifications` for supported thread - /// adjustments instead of replacing the full permissions profile. + /// with `sandbox`. This updates profile identity metadata without + /// replacing the effective permissions profile. #[experimental("thread/resume.permissions")] #[ts(optional = nullable)] pub permissions: Option, @@ -308,6 +326,11 @@ pub struct ThreadResumeResponse { pub model_provider: String, pub service_tier: Option, pub cwd: AbsolutePathBuf, + /// Workspace roots used to realize symbolic `:project_roots` permission + /// entries for this thread. + #[experimental("thread/resume.workspaceRoots")] + #[serde(default)] + pub workspace_roots: Vec, /// Instruction source files currently loaded for this thread. #[serde(default)] pub instruction_sources: Vec, @@ -368,6 +391,11 @@ pub struct ThreadForkParams { pub service_tier: Option>, #[ts(optional = nullable)] pub cwd: Option, + /// Optional replacement workspace roots for the forked thread. Omitted + /// preserves the source thread roots when available. + #[experimental("thread/fork.workspaceRoots")] + #[ts(optional = nullable)] + pub workspace_roots: Option>, #[experimental(nested)] #[ts(optional = nullable)] pub approval_policy: Option, @@ -375,11 +403,13 @@ pub struct ThreadForkParams { /// and subsequent turns. #[ts(optional = nullable)] pub approvals_reviewer: Option, + /// Deprecated for fork. The server rejects this field because the source + /// permission profile value is preserved across fork. #[ts(optional = nullable)] pub sandbox: Option, /// Named profile selection for the forked thread. Cannot be combined with - /// `sandbox`. Use bounded `modifications` for supported thread - /// adjustments instead of replacing the full permissions profile. + /// `sandbox`. This updates profile identity metadata without replacing the + /// effective permissions profile. #[experimental("thread/fork.permissions")] #[ts(optional = nullable)] pub permissions: Option, @@ -417,6 +447,11 @@ pub struct ThreadForkResponse { pub model_provider: String, pub service_tier: Option, pub cwd: AbsolutePathBuf, + /// Workspace roots used to realize symbolic `:project_roots` permission + /// entries for this thread. + #[experimental("thread/fork.workspaceRoots")] + #[serde(default)] + pub workspace_roots: Vec, /// Instruction source files currently loaded for this thread. #[serde(default)] pub instruction_sources: Vec, @@ -1005,6 +1040,9 @@ pub struct ThreadTurnsListParams { /// Optional turn pagination direction; defaults to descending. #[ts(optional = nullable)] pub sort_direction: Option, + /// How much item detail to include for each returned turn; defaults to summary. + #[ts(optional = nullable)] + pub items_view: Option, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -1022,6 +1060,36 @@ pub struct ThreadTurnsListResponse { pub backwards_cursor: Option, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTurnsItemsListParams { + pub thread_id: String, + pub turn_id: String, + /// Opaque cursor to pass to the next call to continue after the last item. + #[ts(optional = nullable)] + pub cursor: Option, + /// Optional item page size. + #[ts(optional = nullable)] + pub limit: Option, + /// Optional item pagination direction; defaults to ascending. + #[ts(optional = nullable)] + pub sort_direction: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadTurnsItemsListResponse { + pub data: Vec, + /// Opaque cursor to pass to the next call to continue after the last item. + /// if None, there are no more items to return. + pub next_cursor: Option, + /// Opaque cursor to pass as `cursor` when reversing `sortDirection`. + /// This is only populated when the page contains at least one item. + pub backwards_cursor: Option, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs index 61a09bfbf5..4580e0f49d 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs @@ -64,6 +64,11 @@ pub struct TurnStartParams { /// Override the working directory for this turn and subsequent turns. #[ts(optional = nullable)] pub cwd: Option, + /// Replace the workspace roots for this turn and subsequent turns. Omitted + /// preserves the current roots. + #[experimental("turn/start.workspaceRoots")] + #[ts(optional = nullable)] + pub workspace_roots: Option>, /// Override the approval policy for this turn and subsequent turns. #[experimental(nested)] #[ts(optional = nullable)] @@ -72,13 +77,13 @@ pub struct TurnStartParams { /// subsequent turns. #[ts(optional = nullable)] pub approvals_reviewer: Option, - /// Override the sandbox policy for this turn and subsequent turns. + /// Deprecated for turns. The server rejects this field because the + /// thread permission profile value is not mutable through `turn/start`. #[ts(optional = nullable)] pub sandbox_policy: Option, /// Select a named permissions profile for this turn and subsequent turns. - /// Cannot be combined with `sandboxPolicy`. Use bounded `modifications` - /// for supported turn adjustments instead of replacing the full - /// permissions profile. + /// Cannot be combined with `sandboxPolicy`. This updates profile identity + /// metadata without replacing the effective permissions profile. #[experimental("turn/start.permissions")] #[ts(optional = nullable)] pub permissions: Option, diff --git a/codex-rs/app-server-test-client/Cargo.toml b/codex-rs/app-server-test-client/Cargo.toml index 32d2588fdf..603a5caf22 100644 --- a/codex-rs/app-server-test-client/Cargo.toml +++ b/codex-rs/app-server-test-client/Cargo.toml @@ -23,3 +23,7 @@ tracing-subscriber = { workspace = true } tungstenite = { workspace = true } url = { workspace = true } uuid = { workspace = true, features = ["v4"] } + +[lib] +test = false +doctest = false diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index edea431c61..e67f6e02f3 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -1945,6 +1945,7 @@ impl CodexClient { thread_id, turn_id, item_id, + started_at_ms: _, approval_id, reason, network_approval_context, @@ -2020,6 +2021,7 @@ impl CodexClient { thread_id, turn_id, item_id, + started_at_ms: _, reason, grant_root, } = params; diff --git a/codex-rs/app-server-transport/Cargo.toml b/codex-rs/app-server-transport/Cargo.toml index d1f89c5b59..175890962e 100644 --- a/codex-rs/app-server-transport/Cargo.toml +++ b/codex-rs/app-server-transport/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_app_server_transport" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 55481b6d5d..b4a5e64a89 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -15,6 +15,7 @@ path = "src/bin/notify_capture.rs" [lib] name = "codex_app_server" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index babfac99ba..55fd71f98e 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -88,7 +88,7 @@ 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. Like `thread/start`, `thread/fork` also accepts `ephemeral: true` for an in-memory temporary thread. 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 or experimental `permissions` profile selection, approval policy, approvals reviewer, etc. This immediately returns the new turn object. The app-server emits `turn/started` when that turn actually begins running. +- 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, workspace roots, approval policy, approvals reviewer, and the active permission profile name. The permission profile value associated with the thread is not mutable through `turn/start`. 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. @@ -143,13 +143,14 @@ Example with notification opt-out: ## API Overview - `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. When the request includes a `cwd` and the resolved sandbox is `workspace-write` or full access, app-server also marks that project as trusted in the user `config.toml`. Pass `sessionStartSource: "clear"` when starting a replacement thread after clearing the current session so `SessionStart` hooks receive `source: "clear"` instead of the default `"startup"`. For permissions, prefer experimental `permissions` profile selection; the legacy `sandbox` shorthand is still accepted but cannot be combined with `permissions`. Experimental `environments` selects the sticky execution environments for turns on the thread; omit it to use the server default, pass `[]` to disable environments, or pass explicit environment ids with per-environment `cwd`. -- `thread/resume` β€” reopen an existing thread by id so subsequent `turn/start` calls append to it. Accepts the same permission override rules as `thread/start`. -- `thread/fork` β€” fork an existing thread into a new thread id by copying the stored history; if the source thread is currently mid-turn, the fork records the same interruption marker as `turn/interrupt` instead of inheriting an unmarked partial turn suffix. The returned `thread.forkedFromId` points at the source thread when known. Accepts `ephemeral: true` for an in-memory temporary fork, emits `thread/started` (including the current `thread.status`), and auto-subscribes you to turn/item events for the new thread. Experimental clients can pass `excludeTurns: true` when they plan to page fork history via `thread/turns/list` instead of receiving the full turn array immediately. Accepts the same permission override rules as `thread/start`. +- `thread/resume` β€” reopen an existing thread by id so subsequent `turn/start` calls append to it. The stored permission profile value is preserved; clients may update `workspaceRoots` or use `permissions` to update the active profile name after validating that the profile id exists. The legacy `sandbox` shorthand is not accepted for resume. +- `thread/fork` β€” fork an existing thread into a new thread id by copying the stored history; if the source thread is currently mid-turn, the fork records the same interruption marker as `turn/interrupt` instead of inheriting an unmarked partial turn suffix. The returned `thread.forkedFromId` points at the source thread when known. Accepts `ephemeral: true` for an in-memory temporary fork, emits `thread/started` (including the current `thread.status`), and auto-subscribes you to turn/item events for the new thread. Experimental clients can pass `excludeTurns: true` when they plan to page fork history via `thread/turns/list` instead of receiving the full turn array immediately. Like resume, fork preserves the source permission profile value while allowing explicit `workspaceRoots` or active profile name updates. - `thread/start`, `thread/resume`, and `thread/fork` responses include the legacy `sandbox` compatibility projection. Experimental clients can read response `permissionProfile` for the exact active runtime permissions and `activePermissionProfile` for the named or implicit built-in profile identity/provenance when known. - `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/turns/list` β€” experimental; page through a stored thread’s turn history without resuming it; supports cursor-based pagination with `sortDirection`, `nextCursor`, and `backwardsCursor`. +- `thread/turns/list` β€” experimental; page through a stored thread’s turn history without resuming it; supports cursor-based pagination with `sortDirection`, `itemsView`, `nextCursor`, and `backwardsCursor`. +- `thread/turns/items/list` β€” experimental; reserved for paging full items for one turn. The API shape is present, but app-server currently returns an unsupported-method JSON-RPC error. - `thread/metadata/update` β€” patch stored thread metadata in sqlite; currently supports updating persisted `gitInfo` fields and returns the refreshed `thread`. - `thread/memoryMode/set` β€” experimental; set a thread’s persisted memory eligibility to `"enabled"` or `"disabled"` for either a loaded thread or a stored rollout; returns `{}` on success. - `memory/reset` β€” experimental; clear the current `CODEX_HOME/memories` directory and reset persisted memory stage data in sqlite while preserving existing thread memory modes; returns `{}` on success. @@ -167,7 +168,7 @@ Example with notification opt-out: - `thread/shellCommand` β€” run a user-initiated `!` shell command against a thread; this runs unsandboxed with full access rather than inheriting the thread sandbox policy. Returns `{}` immediately while progress streams through standard turn/item notifications and any active turn receives the formatted output in its message stream. - `thread/backgroundTerminals/clean` β€” terminate all running background terminals for a thread (experimental; requires `capabilities.experimentalApi`); returns `{}` when the cleanup request is accepted. - `thread/rollback` β€” drop the last N turns from the agent’s in-memory context and persist a rollback marker in the rollout so future resumes see the pruned history; returns the updated `thread` (with `turns` populated) on success. -- `turn/start` β€” add user input to a thread and begin Codex generation; responds with the initial `turn` object and streams `turn/started`, `item/*`, and `turn/completed` notifications. Prefer experimental `permissions` profile selection for permission overrides; the legacy `sandboxPolicy` field is still accepted but cannot be combined with `permissions`. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode". +- `turn/start` β€” add user input to a thread and begin Codex generation; responds with the initial `turn` object and streams `turn/started`, `item/*`, and `turn/completed` notifications. It can update `workspaceRoots` and use experimental `permissions` profile selection to update the active profile name, but it cannot change the thread's permission profile value; `sandboxPolicy` is rejected. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode". - `thread/inject_items` β€” append raw Responses API items to a loaded thread’s model-visible history without starting a user turn; returns `{}` on success. - `turn/steer` β€” add user input to an already in-flight regular turn without starting a new turn; returns the active `turnId` that accepted the input. Review and manual compaction turns reject `turn/steer`. - `turn/interrupt` β€” request cancellation of an in-flight turn by `(thread_id, turn_id)`; success is an empty `{}` response and the turn finishes with `status: "interrupted"`. @@ -241,6 +242,7 @@ Start a fresh thread when you need a new Codex conversation. // current config settings. "model": "gpt-5.1-codex", "cwd": "/Users/me/project", + "workspaceRoots": ["/Users/me/project"], "approvalPolicy": "never", "sandbox": "workspaceWrite", // Prefer experimental profile selection: @@ -278,7 +280,7 @@ Start a fresh thread when you need a new Codex conversation. Valid `personality` values are `"friendly"`, `"pragmatic"`, and `"none"`. When `"none"` is selected, the personality placeholder is replaced with an empty string. -To continue a stored session, call `thread/resume` with the `thread.id` you previously recorded. The response shape matches `thread/start`. When the stored session includes persisted token usage, the server emits `thread/tokenUsage/updated` immediately after the response so clients can render restored usage before the next turn starts. You can also pass the same configuration overrides supported by `thread/start`, including `approvalsReviewer`. +To continue a stored session, call `thread/resume` with the `thread.id` you previously recorded. The response shape matches `thread/start`. When the stored session includes persisted token usage, the server emits `thread/tokenUsage/updated` immediately after the response so clients can render restored usage before the next turn starts. You can pass non-permission configuration overrides such as `approvalsReviewer`; the stored permission profile value is preserved unless you start a new thread. Use `workspaceRoots` to replace the thread root list, and use `permissions` only to update the active profile name after validating the id exists. By default, `thread/resume` includes the reconstructed turn history in `thread.turns`. Experimental clients can pass `excludeTurns: true` to return only thread metadata and live resume state, then call `thread/turns/list` separately if they want to page the turn history over the network. In that mode the server also skips replaying restored `thread/tokenUsage/updated`, which avoids rebuilding turns just to attribute historical usage. @@ -424,13 +426,14 @@ Use `thread/read` to fetch a stored thread by id without resuming it. Pass `incl Use `thread/turns/list` with `capabilities.experimentalApi = true` to page a stored thread’s turn history without resuming it. By default, results are sorted descending so clients can start at the present and fetch older turns with `nextCursor`. The response also includes `backwardsCursor`; pass it as `cursor` on a later request with `sortDirection: "asc"` to fetch turns newer than the first item from the earlier page. -Every returned `Turn` includes `itemsView`, which tells clients whether the `items` array was omitted intentionally (`notLoaded`), contains only summary items (`summary`), or contains every item available from persisted app-server history (`full`). Current `thread/turns/list` responses return `full` turns. +Every returned `Turn` includes `itemsView`, which tells clients whether the `items` array was omitted intentionally (`notLoaded`), contains only summary items (`summary`), or contains every item available from persisted app-server history (`full`). Pass `itemsView` to choose the returned detail level; omitted `itemsView` defaults to `"summary"`. ```json { "method": "thread/turns/list", "id": 24, "params": { "threadId": "thr_123", "limit": 50, - "sortDirection": "desc" + "sortDirection": "desc", + "itemsView": "summary" } } { "id": 24, "result": { "data": [ ... ], @@ -439,6 +442,19 @@ Every returned `Turn` includes `itemsView`, which tells clients whether the `ite } } ``` +`thread/turns/items/list` is the planned hydration API for fetching full items for one turn: + +```json +{ "method": "thread/turns/items/list", "id": 25, "params": { + "threadId": "thr_123", + "turnId": "turn_456", + "limit": 100, + "sortDirection": "asc" +} } +``` + +This method currently returns JSON-RPC `-32601` with message `thread/turns/items/list is not supported yet`. + ### Example: Update stored thread metadata Use `thread/metadata/update` to patch sqlite-backed metadata for a thread without resuming it. Today this supports persisted `gitInfo`; omitted fields are left unchanged, while explicit `null` clears a stored value. @@ -632,19 +648,15 @@ You can optionally specify config overrides on the new turn. If specified, these "input": [ { "type": "text", "text": "Run tests" } ], // Below are optional config overrides "cwd": "/Users/me/project", + "workspaceRoots": ["/Users/me/project", "/Users/me/project/packages/api"], // Experimental: turn-scoped environment selection. "environments": [ { "environmentId": "local", "cwd": "/Users/me/project" } ], "approvalPolicy": "unlessTrusted", - "sandboxPolicy": { - "type": "workspaceWrite", - "writableRoots": ["/Users/me/project"], - "networkAccess": true - }, - // Prefer experimental profile selection: + // Optional: validate and record the active profile name without changing + // the thread's permission profile value. // "permissions": { "type": "profile", "id": ":workspace" } - // Do not send both "sandboxPolicy" and "permissions". "model": "gpt-5.1-codex", "effort": "medium", "summary": "concise", @@ -1470,21 +1482,13 @@ $skill-creator Add a new skill for triaging flaky CI and include step-by-step us ``` Use `skills/list` to fetch the available skills (optionally scoped by `cwds`, with `forceReload`). -You can also add `perCwdExtraUserRoots` to scan additional absolute paths as `user` scope for specific `cwd` entries. -Entries whose `cwd` is not present in `cwds` are ignored. `skills/list` might reuse a cached skills result per `cwd`; setting `forceReload` to `true` refreshes the result from disk. The server also emits `skills/changed` notifications when watched local skill files change. Treat this as an invalidation signal and re-run `skills/list` with your current params when needed. ```json { "method": "skills/list", "id": 25, "params": { "cwds": ["/Users/me/project", "/Users/me/other-project"], - "forceReload": true, - "perCwdExtraUserRoots": [ - { - "cwd": "/Users/me/project", - "extraUserRoots": ["/Users/me/shared-skills"] - } - ] + "forceReload": true } } { "id": 25, "result": { "data": [{ diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 64215566ee..1f2f289b05 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -511,6 +511,7 @@ pub(crate) async fn apply_bespoke_event_handling( thread_id: conversation_id.to_string(), turn_id: event.turn_id.clone(), item_id: item_id.clone(), + started_at_ms: event.started_at_ms, reason: event.reason.clone(), grant_root: event.grant_root.clone(), }; @@ -542,6 +543,7 @@ pub(crate) async fn apply_bespoke_event_handling( call_id, approval_id, turn_id, + started_at_ms, command, cwd, reason, @@ -615,6 +617,7 @@ pub(crate) async fn apply_bespoke_event_handling( thread_id: conversation_id.to_string(), turn_id: turn_id.clone(), item_id: call_id.clone(), + started_at_ms, approval_id: approval_id.clone(), reason, network_approval_context, @@ -764,6 +767,7 @@ pub(crate) async fn apply_bespoke_event_handling( thread_id: conversation_id.to_string(), turn_id: request.turn_id.clone(), item_id: request.call_id.clone(), + started_at_ms: request.started_at_ms, cwd: request_cwd.clone(), reason: request.reason, permissions: request.permissions.into(), @@ -2249,6 +2253,9 @@ mod tests { id: format!("review-{id}"), target_item_id: Some(id.to_string()), turn_id: turn_id.to_string(), + started_at_ms: 1_000, + completed_at_ms: (!matches!(status, GuardianAssessmentStatus::InProgress)) + .then_some(1_042), status, risk_level, user_authorization, @@ -2313,6 +2320,8 @@ mod tests { id: "review-1".to_string(), target_item_id: Some("item-1".to_string()), turn_id: String::new(), + started_at_ms: 1_000, + completed_at_ms: None, status: codex_protocol::protocol::GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -2326,6 +2335,7 @@ mod tests { ServerNotification::ItemGuardianApprovalReviewStarted(payload) => { assert_eq!(payload.thread_id, conversation_id.to_string()); assert_eq!(payload.turn_id, "turn-from-event"); + assert_eq!(payload.started_at_ms, 1_000); assert_eq!(payload.review_id, "review-1"); assert_eq!(payload.target_item_id.as_deref(), Some("item-1")); assert_eq!( @@ -2356,6 +2366,8 @@ mod tests { id: "review-2".to_string(), target_item_id: Some("item-2".to_string()), turn_id: "turn-from-assessment".to_string(), + started_at_ms: 1_000, + completed_at_ms: Some(1_042), status: codex_protocol::protocol::GuardianAssessmentStatus::Denied, risk_level: Some(codex_protocol::protocol::GuardianRiskLevel::High), user_authorization: Some(codex_protocol::protocol::GuardianUserAuthorization::Low), @@ -2371,6 +2383,8 @@ mod tests { ServerNotification::ItemGuardianApprovalReviewCompleted(payload) => { assert_eq!(payload.thread_id, conversation_id.to_string()); assert_eq!(payload.turn_id, "turn-from-assessment"); + assert_eq!(payload.started_at_ms, 1_000); + assert_eq!(payload.completed_at_ms, 1_042); assert_eq!(payload.review_id, "review-2"); assert_eq!(payload.target_item_id.as_deref(), Some("item-2")); assert_eq!(payload.decision_source, AutoReviewDecisionSource::Agent); @@ -2406,6 +2420,8 @@ mod tests { id: "review-3".to_string(), target_item_id: None, turn_id: "turn-from-assessment".to_string(), + started_at_ms: 1_000, + completed_at_ms: Some(1_042), status: codex_protocol::protocol::GuardianAssessmentStatus::Aborted, risk_level: None, user_authorization: None, diff --git a/codex-rs/app-server/src/error_code.rs b/codex-rs/app-server/src/error_code.rs index 0054d2988f..48e401f7bc 100644 --- a/codex-rs/app-server/src/error_code.rs +++ b/codex-rs/app-server/src/error_code.rs @@ -1,6 +1,7 @@ use codex_app_server_protocol::JSONRPCErrorError; pub(crate) const INVALID_REQUEST_ERROR_CODE: i64 = -32600; +pub(crate) const METHOD_NOT_FOUND_ERROR_CODE: i64 = -32601; pub const INVALID_PARAMS_ERROR_CODE: i64 = -32602; pub(crate) const INTERNAL_ERROR_CODE: i64 = -32603; pub(crate) const OVERLOADED_ERROR_CODE: i64 = -32001; @@ -10,6 +11,10 @@ pub(crate) fn invalid_request(message: impl Into) -> JSONRPCErrorError { error(INVALID_REQUEST_ERROR_CODE, message) } +pub(crate) fn method_not_found(message: impl Into) -> JSONRPCErrorError { + error(METHOD_NOT_FOUND_ERROR_CODE, message) +} + pub(crate) fn invalid_params(message: impl Into) -> JSONRPCErrorError { error(INVALID_PARAMS_ERROR_CODE, message) } diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 2ca0a87d84..7006c40343 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -1008,6 +1008,9 @@ impl MessageProcessor { ClientRequest::ThreadTurnsList { params, .. } => { self.thread_processor.thread_turns_list(params).await } + ClientRequest::ThreadTurnsItemsList { params, .. } => { + self.thread_processor.thread_turns_items_list(params).await + } ClientRequest::ThreadShellCommand { params, .. } => { self.thread_processor .thread_shell_command(&request_id, params) diff --git a/codex-rs/app-server/src/message_processor_tracing_tests.rs b/codex-rs/app-server/src/message_processor_tracing_tests.rs index 516e042301..5e243dcdd9 100644 --- a/codex-rs/app-server/src/message_processor_tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor_tracing_tests.rs @@ -658,6 +658,7 @@ async fn turn_start_jsonrpc_span_parents_core_turn_spans() -> Result<()> { }], responsesapi_client_metadata: None, cwd: None, + workspace_roots: None, approval_policy: None, sandbox_policy: None, permissions: None, diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index a7420f8c78..cbe196cd98 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -2,6 +2,8 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::AtomicI64; use std::sync::atomic::Ordering; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ClientResponsePayload; @@ -357,8 +359,10 @@ impl OutgoingMessageSender { match entry { Some((id, entry)) => { + let completed_at_ms = now_unix_timestamp_ms(); if let Ok(response) = entry.request.response_from_result(result.clone()) { - self.analytics_events_client.track_server_response(response); + self.analytics_events_client + .track_server_response(completed_at_ms, response); } if let Err(err) = entry.callback.send(Ok(result)) { warn!("could not notify callback for {id:?} due to: {err:?}"); @@ -648,6 +652,15 @@ impl OutgoingMessageSender { } } +fn now_unix_timestamp_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .try_into() + .unwrap_or_default() +} + #[cfg(test)] mod tests { use std::time::Duration; @@ -903,6 +916,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "item-1".to_string(), + started_at_ms: 0, approval_id: None, reason: None, network_approval_context: None, @@ -1195,6 +1209,7 @@ mod tests { thread_id: thread_id.to_string(), turn_id: "turn-1".to_string(), item_id: "call-2".to_string(), + started_at_ms: 0, reason: None, grant_root: None, }, diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 795b5d4c32..c44c8c451c 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -100,7 +100,6 @@ 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::PermissionProfileModificationParams; use codex_app_server_protocol::PermissionProfileSelectionParams; use codex_app_server_protocol::PluginDetail; use codex_app_server_protocol::PluginInstallParams; @@ -124,6 +123,7 @@ use codex_app_server_protocol::PluginSharePrincipalType; use codex_app_server_protocol::PluginShareSaveParams; use codex_app_server_protocol::PluginShareSaveResponse; use codex_app_server_protocol::PluginShareTarget; +use codex_app_server_protocol::PluginShareUpdateDiscoverability; use codex_app_server_protocol::PluginShareUpdateTargetsParams; use codex_app_server_protocol::PluginShareUpdateTargetsResponse; use codex_app_server_protocol::PluginSkillReadParams; @@ -215,6 +215,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::ThreadTurnsItemsListParams; use codex_app_server_protocol::ThreadTurnsListParams; use codex_app_server_protocol::ThreadTurnsListResponse; use codex_app_server_protocol::ThreadUnarchiveParams; @@ -350,6 +351,8 @@ use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; #[cfg(test)] use codex_protocol::items::TurnItem; +use codex_protocol::models::ActivePermissionProfile; +use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseItem; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::protocol::AgentStatus; diff --git a/codex-rs/app-server/src/request_processors/catalog_processor.rs b/codex-rs/app-server/src/request_processors/catalog_processor.rs index b26748d551..89082492c1 100644 --- a/codex-rs/app-server/src/request_processors/catalog_processor.rs +++ b/codex-rs/app-server/src/request_processors/catalog_processor.rs @@ -382,44 +382,12 @@ impl CatalogRequestProcessor { &self, params: SkillsListParams, ) -> Result { - let SkillsListParams { - cwds, - force_reload, - per_cwd_extra_user_roots, - } = params; + let SkillsListParams { cwds, force_reload } = params; let cwds = if cwds.is_empty() { vec![self.config.cwd.to_path_buf()] } else { cwds }; - let cwd_set: HashSet = cwds.iter().cloned().collect(); - - let mut extra_roots_by_cwd: HashMap> = HashMap::new(); - for entry in per_cwd_extra_user_roots.unwrap_or_default() { - if !cwd_set.contains(&entry.cwd) { - warn!( - cwd = %entry.cwd.display(), - "ignoring per-cwd extra roots for cwd not present in skills/list cwds" - ); - continue; - } - - let mut valid_extra_roots = Vec::new(); - for root in entry.extra_user_roots { - let root = - AbsolutePathBuf::from_absolute_path_checked(root.as_path()).map_err(|_| { - invalid_request(format!( - "skills/list perCwdExtraUserRoots extraUserRoots paths must be absolute: {}", - root.display() - )) - })?; - valid_extra_roots.push(root); - } - extra_roots_by_cwd - .entry(entry.cwd) - .or_default() - .extend(valid_extra_roots); - } let config = self.load_latest_config(/*fallback_cwd*/ None).await?; let auth = self.auth_manager.auth().await; @@ -436,7 +404,6 @@ impl CatalogRequestProcessor { let mut data = futures::stream::iter(cwds.into_iter().enumerate()) .map(|(index, cwd)| { let config = &config; - let extra_roots_by_cwd = &extra_roots_by_cwd; let fs = fs.clone(); let plugins_manager = &plugins_manager; let skills_manager = &skills_manager; @@ -458,9 +425,6 @@ impl CatalogRequestProcessor { ); } }; - let extra_roots = extra_roots_by_cwd - .get(&cwd) - .map_or(&[][..], std::vec::Vec::as_slice); let effective_skill_roots = if workspace_codex_plugins_enabled { let plugins_input = config.plugins_config_input(); plugins_manager @@ -479,12 +443,7 @@ impl CatalogRequestProcessor { config.bundled_skills_enabled(), ); let outcome = skills_manager - .skills_for_cwd_with_extra_user_roots( - &skills_input, - force_reload, - extra_roots, - fs, - ) + .skills_for_cwd(&skills_input, force_reload, fs) .await; let errors = errors_to_info(&outcome.errors); let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths); diff --git a/codex-rs/app-server/src/request_processors/command_exec_processor.rs b/codex-rs/app-server/src/request_processors/command_exec_processor.rs index 3236a67627..7c112abc82 100644 --- a/codex-rs/app-server/src/request_processors/command_exec_processor.rs +++ b/codex-rs/app-server/src/request_processors/command_exec_processor.rs @@ -200,7 +200,8 @@ impl CommandExecRequestProcessor { } else { ExecCapturePolicy::ShellTool }; - let sandbox_cwd = if permission_profile.is_some() { + let has_request_permission_profile = permission_profile.is_some(); + let sandbox_cwd = if has_request_permission_profile { cwd.clone() } else { self.config.cwd.clone() @@ -283,10 +284,16 @@ impl CommandExecRequestProcessor { None => None, }; + let workspace_roots = if has_request_permission_profile { + vec![sandbox_cwd.clone()] + } else { + self.config.workspace_roots.clone() + }; let exec_request = codex_core::exec::build_exec_request( exec_params, &effective_permission_profile, &sandbox_cwd, + &workspace_roots, &codex_linux_sandbox_exe, use_legacy_landlock, ) diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index cc5de4058a..65bb390851 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -133,6 +133,33 @@ fn remote_plugin_share_discoverability( } } +fn remote_plugin_share_update_discoverability( + discoverability: PluginShareUpdateDiscoverability, +) -> codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability { + match discoverability { + PluginShareUpdateDiscoverability::Unlisted => { + codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability::Unlisted + } + PluginShareUpdateDiscoverability::Private => { + codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability::Private + } + } +} + +fn validate_client_plugin_share_targets( + targets: &[PluginShareTarget], +) -> Result<(), JSONRPCErrorError> { + if targets + .iter() + .any(|target| target.principal_type == PluginSharePrincipalType::Workspace) + { + return Err(invalid_request( + "shareTargets cannot include workspace principals; use discoverability UNLISTED for workspace link access", + )); + } + Ok(()) +} + fn remote_plugin_share_targets( targets: Vec, ) -> Vec { @@ -729,9 +756,17 @@ impl PluginRequestProcessor { } if remote_plugin_id.is_some() && (discoverability.is_some() || share_targets.is_some()) { return Err(invalid_request( - "discoverability and shareTargets are only supported when creating a plugin share; use plugin/share/updateTargets to update share targets", + "discoverability and shareTargets are only supported when creating a plugin share; use plugin/share/updateTargets to update share settings", )); } + if discoverability == Some(PluginShareDiscoverability::Listed) { + return Err(invalid_request( + "discoverability LISTED is not supported for plugin/share/save; use UNLISTED or PRIVATE", + )); + } + if let Some(share_targets) = share_targets.as_ref() { + validate_client_plugin_share_targets(share_targets)?; + } let remote_plugin_service_config = RemotePluginServiceConfig { chatgpt_base_url: config.chatgpt_base_url.clone(), @@ -765,11 +800,14 @@ impl PluginRequestProcessor { let (config, auth) = self.load_plugin_share_config_and_auth().await?; let PluginShareUpdateTargetsParams { remote_plugin_id, + discoverability, share_targets, } = params; if remote_plugin_id.is_empty() || !is_valid_remote_plugin_id(&remote_plugin_id) { return Err(invalid_request("invalid remote plugin id")); } + validate_client_plugin_share_targets(&share_targets)?; + let requested_share_targets = share_targets.clone(); let remote_plugin_service_config = RemotePluginServiceConfig { chatgpt_base_url: config.chatgpt_base_url.clone(), @@ -779,6 +817,7 @@ impl PluginRequestProcessor { auth.as_ref(), &remote_plugin_id, remote_plugin_share_targets(share_targets), + remote_plugin_share_update_discoverability(discoverability), ) .await .map_err(|err| { @@ -790,7 +829,14 @@ impl PluginRequestProcessor { .principals .into_iter() .map(plugin_share_principal_from_remote) + .filter(|principal| { + requested_share_targets.iter().any(|target| { + target.principal_type == principal.principal_type + && target.principal_id == principal.principal_id + }) + }) .collect(), + discoverability: remote_plugin_share_discoverability_to_info(result.discoverability), }) } @@ -1487,6 +1533,22 @@ fn remote_plugin_share_context_to_info( } } +fn remote_plugin_share_discoverability_to_info( + discoverability: codex_core_plugins::remote::RemotePluginShareDiscoverability, +) -> PluginShareDiscoverability { + match discoverability { + codex_core_plugins::remote::RemotePluginShareDiscoverability::Listed => { + PluginShareDiscoverability::Listed + } + codex_core_plugins::remote::RemotePluginShareDiscoverability::Unlisted => { + PluginShareDiscoverability::Unlisted + } + codex_core_plugins::remote::RemotePluginShareDiscoverability::Private => { + PluginShareDiscoverability::Private + } + } +} + fn remote_plugin_detail_to_info( detail: RemoteCatalogPluginDetail, apps: Vec, diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index ef44a2b178..386a02388b 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -588,11 +588,13 @@ pub(super) async fn handle_pending_thread_resume_request( permission_profile, active_permission_profile, cwd, + workspace_roots, reasoning_effort, .. } = pending.config_snapshot; let instruction_sources = pending.instruction_sources; - let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path()); + let sandbox = + thread_response_sandbox_policy(&permission_profile, &workspace_roots, cwd.as_path()); let active_permission_profile = thread_response_active_permission_profile(active_permission_profile); let session_id = conversation.session_configured().session_id.to_string(); @@ -608,6 +610,7 @@ pub(super) async fn handle_pending_thread_resume_request( approval_policy: approval_policy.into(), approvals_reviewer: approvals_reviewer.into(), sandbox, + workspace_roots, permission_profile: Some(permission_profile.into()), active_permission_profile, reasoning_effort, diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index d83f5e631f..ee5efdc9c5 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -1,4 +1,5 @@ use super::*; +use crate::error_code::method_not_found; const THREAD_LIST_DEFAULT_LIMIT: usize = 25; const THREAD_LIST_MAX_LIMIT: usize = 100; @@ -16,6 +17,99 @@ struct ThreadListFilters { use_state_db_only: bool, } +#[derive(Clone)] +struct PersistedThreadPermissionState { + permission_profile: PermissionProfile, + active_permission_profile: Option, + workspace_roots: Vec, +} + +fn absolute_path_from_history_path( + path: &Path, + base: Option<&AbsolutePathBuf>, +) -> Option { + if let Ok(path) = AbsolutePathBuf::try_from(path) { + Some(path) + } else if let Some(base) = base { + Some(AbsolutePathBuf::resolve_path_against_base( + path, + base.as_path(), + )) + } else { + AbsolutePathBuf::relative_to_current_dir(path).ok() + } +} + +fn roots_or_cwd( + roots: Vec, + cwd: Option<&AbsolutePathBuf>, +) -> Vec { + if roots.is_empty() { + cwd.cloned().into_iter().collect() + } else { + roots + } +} + +fn persisted_thread_permission_state( + history: &InitialHistory, + fallback_cwd: Option<&Path>, + fallback_sandbox_policy: Option<&codex_protocol::protocol::SandboxPolicy>, +) -> Option { + let mut cwd = + fallback_cwd.and_then(|cwd| absolute_path_from_history_path(cwd, /*base*/ None)); + let mut workspace_roots = None; + let mut permission_profile = None; + let mut active_permission_profile = None; + + for item in history.get_rollout_items() { + match item { + RolloutItem::SessionMeta(meta_line) => { + cwd = absolute_path_from_history_path(meta_line.meta.cwd.as_path(), cwd.as_ref()) + .or(cwd); + workspace_roots = Some(roots_or_cwd(meta_line.meta.workspace_roots, cwd.as_ref())); + } + RolloutItem::TurnContext(context) => { + cwd = absolute_path_from_history_path(context.cwd.as_path(), cwd.as_ref()).or(cwd); + workspace_roots = Some(roots_or_cwd(context.workspace_roots, cwd.as_ref())); + let context_cwd = cwd + .as_ref() + .map(AbsolutePathBuf::as_path) + .unwrap_or(context.cwd.as_path()); + permission_profile = Some(context.permission_profile.unwrap_or_else(|| { + PermissionProfile::from_legacy_sandbox_policy_for_cwd( + &context.sandbox_policy, + context_cwd, + ) + })); + } + RolloutItem::EventMsg(EventMsg::SessionConfigured(event)) => { + cwd = Some(event.cwd.clone()); + workspace_roots = Some(roots_or_cwd(event.workspace_roots, cwd.as_ref())); + permission_profile = Some(event.permission_profile); + active_permission_profile = event.active_permission_profile; + } + RolloutItem::ResponseItem(_) | RolloutItem::Compacted(_) | RolloutItem::EventMsg(_) => { + } + } + } + + if permission_profile.is_none() { + let cwd = cwd.as_ref()?; + let fallback_sandbox_policy = fallback_sandbox_policy?; + permission_profile = Some(PermissionProfile::from_legacy_sandbox_policy_for_cwd( + fallback_sandbox_policy, + cwd.as_path(), + )); + } + + Some(PersistedThreadPermissionState { + permission_profile: permission_profile?, + active_permission_profile, + workspace_roots: roots_or_cwd(workspace_roots.unwrap_or_default(), cwd.as_ref()), + }) +} + fn collect_resume_override_mismatches( request: &ThreadResumeParams, config_snapshot: &ThreadConfigSnapshot, @@ -591,6 +685,15 @@ impl ThreadRequestProcessor { .map(|response| Some(response.into())) } + pub(crate) async fn thread_turns_items_list( + &self, + _params: ThreadTurnsItemsListParams, + ) -> Result, JSONRPCErrorError> { + Err(method_not_found( + "thread/turns/items/list is not supported yet", + )) + } + pub(crate) async fn thread_shell_command( &self, request_id: &ConnectionRequestId, @@ -788,6 +891,7 @@ impl ThreadRequestProcessor { model_provider, service_tier, cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox, @@ -821,6 +925,7 @@ impl ThreadRequestProcessor { model_provider, service_tier, cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox, @@ -1138,6 +1243,7 @@ impl ThreadRequestProcessor { let sandbox = thread_response_sandbox_policy( &config_snapshot.permission_profile, + &config_snapshot.workspace_roots, config_snapshot.cwd.as_path(), ); let active_permission_profile = @@ -1153,6 +1259,7 @@ impl ThreadRequestProcessor { approval_policy: config_snapshot.approval_policy.into(), approvals_reviewer: config_snapshot.approvals_reviewer.into(), sandbox, + workspace_roots: config_snapshot.workspace_roots, permission_profile: Some(config_snapshot.permission_profile.into()), active_permission_profile, reasoning_effort: config_snapshot.reasoning_effort, @@ -1185,6 +1292,7 @@ impl ThreadRequestProcessor { model_provider: Option, service_tier: Option>, cwd: Option, + workspace_roots: Option>, approval_policy: Option, approvals_reviewer: Option, sandbox: Option, @@ -1198,6 +1306,8 @@ impl ThreadRequestProcessor { model_provider, service_tier, cwd: cwd.map(PathBuf::from), + workspace_roots: workspace_roots + .map(|roots| roots.into_iter().map(|root| root.to_path_buf()).collect()), approval_policy: approval_policy .map(codex_app_server_protocol::AskForApproval::to_core), approvals_reviewer: approvals_reviewer @@ -1214,6 +1324,40 @@ impl ThreadRequestProcessor { overrides } + async fn validate_active_permission_profile_selection( + &self, + permissions: PermissionProfileSelectionParams, + request_overrides: Option>, + cwd: Option, + fallback_cwd: Option, + ) -> Result { + let mut overrides = ConfigOverrides { + cwd, + 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() + }; + apply_permission_profile_selection_to_config_overrides(&mut overrides, Some(permissions)); + let config = self + .config_manager + .load_for_cwd(request_overrides, overrides, fallback_cwd) + .await + .map_err(|err| config_load_error(&err))?; + if let Some(warning) = config.startup_warnings.iter().find(|warning| { + warning.contains("Configured value for `permission_profile` is disallowed") + }) { + return Err(invalid_request(format!( + "invalid permission profile selection: {warning}" + ))); + } + config + .permissions + .active_permission_profile() + .ok_or_else(|| { + invalid_request("permission profile selection did not resolve to a named profile") + }) + } + fn parse_environment_selections( &self, environments: Option>, @@ -2072,7 +2216,9 @@ impl ThreadRequestProcessor { cursor, limit, sort_direction, + items_view, } = params; + let items_view = items_view.unwrap_or(TurnItemsView::Summary); let thread_uuid = ThreadId::from_string(&thread_id) .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; @@ -2101,7 +2247,7 @@ impl ThreadRequestProcessor { } else { None }; - let turns = reconstruct_thread_turns_for_turns_list( + let mut turns = reconstruct_thread_turns_for_turns_list( &items, self.thread_watch_manager .loaded_status_for_thread(&thread_uuid.to_string()) @@ -2109,6 +2255,41 @@ impl ThreadRequestProcessor { has_live_running_thread, active_turn, ); + for turn in &mut turns { + match items_view { + TurnItemsView::NotLoaded => { + turn.items.clear(); + turn.items_view = TurnItemsView::NotLoaded; + } + TurnItemsView::Summary => { + let first_user_message = turn + .items + .iter() + .find(|item| matches!(item, ThreadItem::UserMessage { .. })) + .cloned(); + let final_agent_message = turn + .items + .iter() + .rev() + .find(|item| matches!(item, ThreadItem::AgentMessage { .. })) + .cloned(); + turn.items = match (first_user_message, final_agent_message) { + (Some(user_message), Some(agent_message)) + if user_message.id() != agent_message.id() => + { + vec![user_message, agent_message] + } + (Some(user_message), _) => vec![user_message], + (None, Some(agent_message)) => vec![agent_message], + (None, None) => Vec::new(), + }; + turn.items_view = TurnItemsView::Summary; + } + TurnItemsView::Full => { + turn.items_view = TurnItemsView::Full; + } + } + } let page = paginate_thread_turns( turns, cursor.as_deref(), @@ -2274,6 +2455,15 @@ impl ThreadRequestProcessor { .await; return Ok(()); } + if params.sandbox.is_some() { + self.outgoing + .send_error( + request_id, + invalid_request("`sandbox` cannot be used to change thread permissions"), + ) + .await; + return Ok(()); + } if params.persist_extended_history { self.send_persist_extended_history_deprecation_notice(request_id.connection_id) .await; @@ -2311,9 +2501,10 @@ impl ThreadRequestProcessor { model_provider, service_tier, cwd, + workspace_roots, approval_policy, approvals_reviewer, - sandbox, + sandbox: _sandbox, permissions, config: mut request_overrides, base_instructions, @@ -2341,19 +2532,68 @@ impl ThreadRequestProcessor { }; let history_cwd = thread_history.session_cwd(); + let persisted_permission_state = persisted_thread_permission_state( + &thread_history, + history_cwd.as_deref(), + resume_source_thread + .as_ref() + .map(|thread| &thread.sandbox_policy), + ); + let active_permission_profile = if let Some(permissions) = permissions { + match self + .validate_active_permission_profile_selection( + permissions, + request_overrides.clone(), + cwd.clone().map(PathBuf::from), + history_cwd.clone(), + ) + .await + { + Ok(active_permission_profile) => Some(active_permission_profile), + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return Ok(()); + } + } + } else { + persisted_permission_state + .as_ref() + .and_then(|state| state.active_permission_profile.clone()) + }; + let workspace_roots_were_explicit = workspace_roots.is_some(); let mut typesafe_overrides = self.build_thread_config_overrides( model, model_provider, service_tier, cwd, + workspace_roots, approval_policy, approvals_reviewer, - sandbox, - permissions, + /*sandbox*/ None, + /*permissions*/ None, base_instructions, developer_instructions, personality, ); + if let Some(persisted_permission_state) = persisted_permission_state { + typesafe_overrides.permission_profile = + Some(persisted_permission_state.permission_profile.clone()); + if !workspace_roots_were_explicit { + typesafe_overrides.workspace_roots = Some( + persisted_permission_state + .workspace_roots + .iter() + .map(codex_utils_absolute_path::AbsolutePathBuf::to_path_buf) + .collect(), + ); + } + } else if !workspace_roots_were_explicit + && let Some(root) = history_cwd + .as_deref() + .and_then(|cwd| absolute_path_from_history_path(cwd, /*base*/ None)) + { + typesafe_overrides.workspace_roots = Some(vec![root.to_path_buf()]); + } self.load_and_apply_persisted_resume_metadata( &thread_history, &mut request_overrides, @@ -2362,7 +2602,7 @@ impl ThreadRequestProcessor { .await; // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let config = match self + let mut config = match self .config_manager .load_for_cwd(request_overrides, typesafe_overrides, history_cwd) .await @@ -2374,6 +2614,7 @@ impl ThreadRequestProcessor { return Ok(()); } }; + config.permissions.active_permission_profile = active_permission_profile; let instruction_sources = Self::instruction_sources_from_config(&config).await; let response_history = thread_history.clone(); @@ -2467,6 +2708,7 @@ impl ThreadRequestProcessor { let config_snapshot = codex_thread.config_snapshot().await; let sandbox = thread_response_sandbox_policy( &config_snapshot.permission_profile, + &config_snapshot.workspace_roots, config_snapshot.cwd.as_path(), ); let active_permission_profile = thread_response_active_permission_profile( @@ -2483,6 +2725,7 @@ impl ThreadRequestProcessor { approval_policy: session_configured.approval_policy.into(), approvals_reviewer: session_configured.approvals_reviewer.into(), sandbox, + workspace_roots: config_snapshot.workspace_roots, permission_profile: Some(config_snapshot.permission_profile.into()), active_permission_profile, reasoning_effort: session_configured.reasoning_effort, @@ -2941,6 +3184,7 @@ impl ThreadRequestProcessor { model_provider, service_tier, cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox, @@ -2959,6 +3203,11 @@ impl ThreadRequestProcessor { "`permissions` cannot be combined with `sandbox`", )); } + if sandbox.is_some() { + return Err(invalid_request( + "`sandbox` cannot be used to change thread permissions", + )); + } if persist_extended_history { self.send_persist_extended_history_deprecation_notice(request_id.connection_id) .await; @@ -3001,26 +3250,62 @@ impl ThreadRequestProcessor { } else { Some(cli_overrides) }; + let fork_history = InitialHistory::Forked(history_items.clone()); + let persisted_permission_state = persisted_thread_permission_state( + &fork_history, + history_cwd.as_deref(), + Some(&source_thread.sandbox_policy), + ) + .ok_or_else(|| { + invalid_request("thread history is missing persisted permission configuration") + })?; + let active_permission_profile = if let Some(permissions) = permissions { + Some( + self.validate_active_permission_profile_selection( + permissions, + request_overrides.clone(), + cwd.clone().map(PathBuf::from), + history_cwd.clone(), + ) + .await?, + ) + } else { + persisted_permission_state.active_permission_profile.clone() + }; + let workspace_roots_were_explicit = workspace_roots.is_some(); let mut typesafe_overrides = self.build_thread_config_overrides( model, model_provider, service_tier, cwd, + workspace_roots, approval_policy, approvals_reviewer, - sandbox, - permissions, + /*sandbox*/ None, + /*permissions*/ None, base_instructions, developer_instructions, /*personality*/ None, ); + typesafe_overrides.permission_profile = + Some(persisted_permission_state.permission_profile.clone()); + if !workspace_roots_were_explicit { + typesafe_overrides.workspace_roots = Some( + persisted_permission_state + .workspace_roots + .iter() + .map(codex_utils_absolute_path::AbsolutePathBuf::to_path_buf) + .collect(), + ); + } typesafe_overrides.ephemeral = ephemeral.then_some(true); // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let config = self + let mut config = self .config_manager .load_for_cwd(request_overrides, typesafe_overrides, history_cwd) .await .map_err(|err| config_load_error(&err))?; + config.permissions.active_permission_profile = active_permission_profile; let fallback_model_provider = config.model_provider_id.clone(); let instruction_sources = Self::instruction_sources_from_config(&config).await; @@ -3124,6 +3409,7 @@ impl ThreadRequestProcessor { let config_snapshot = forked_thread.config_snapshot().await; let sandbox = thread_response_sandbox_policy( &config_snapshot.permission_profile, + &config_snapshot.workspace_roots, config_snapshot.cwd.as_path(), ); let active_permission_profile = @@ -3139,6 +3425,7 @@ impl ThreadRequestProcessor { approval_policy: session_configured.approval_policy.into(), approvals_reviewer: session_configured.approvals_reviewer.into(), sandbox, + workspace_roots: config_snapshot.workspace_roots, permission_profile: Some(config_snapshot.permission_profile.into()), active_permission_profile, reasoning_effort: session_configured.reasoning_effort, @@ -3496,19 +3783,30 @@ fn normalize_thread_turns_status( enum ThreadReadViewError { InvalidRequest(String), + Unsupported(&'static str), Internal(String), } fn thread_read_view_error(err: ThreadReadViewError) -> JSONRPCErrorError { match err { ThreadReadViewError::InvalidRequest(message) => invalid_request(message), + ThreadReadViewError::Unsupported(operation) => { + unsupported_thread_store_operation(operation) + } ThreadReadViewError::Internal(message) => internal_error(message), } } +fn unsupported_thread_store_operation(operation: &'static str) -> JSONRPCErrorError { + method_not_found(format!("{operation} is not supported yet")) +} + fn thread_store_list_error(err: ThreadStoreError) -> JSONRPCErrorError { match err { ThreadStoreError::InvalidRequest { message } => invalid_request(message), + ThreadStoreError::Unsupported { operation } => { + unsupported_thread_store_operation(operation) + } err => internal_error(format!("failed to list threads: {err}")), } } @@ -3516,6 +3814,9 @@ fn thread_store_list_error(err: ThreadStoreError) -> JSONRPCErrorError { fn thread_store_resume_read_error(err: ThreadStoreError) -> JSONRPCErrorError { match err { ThreadStoreError::InvalidRequest { message } => invalid_request(message), + ThreadStoreError::Unsupported { operation } => { + unsupported_thread_store_operation(operation) + } ThreadStoreError::ThreadNotFound { thread_id } => { invalid_request(format!("no rollout found for thread id {thread_id}")) } @@ -3538,6 +3839,7 @@ fn thread_turns_list_history_load_error( ThreadStoreError::InvalidRequest { message } => { ThreadReadViewError::InvalidRequest(message) } + ThreadStoreError::Unsupported { operation } => ThreadReadViewError::Unsupported(operation), err => ThreadReadViewError::Internal(format!( "failed to load thread history for thread {thread_id}: {err}" )), @@ -3564,6 +3866,7 @@ fn thread_read_history_load_error( ThreadStoreError::InvalidRequest { message } => { ThreadReadViewError::InvalidRequest(message) } + ThreadStoreError::Unsupported { operation } => ThreadReadViewError::Unsupported(operation), err => ThreadReadViewError::Internal(format!( "failed to load thread history for thread {thread_id}: {err}" )), @@ -3579,6 +3882,9 @@ fn conversation_summary_thread_id_read_error( ThreadStoreError::InvalidRequest { message } if message == no_rollout_message => { conversation_summary_not_found_error(conversation_id) } + ThreadStoreError::Unsupported { operation } => { + unsupported_thread_store_operation(operation) + } ThreadStoreError::ThreadNotFound { thread_id } if thread_id == conversation_id => { conversation_summary_not_found_error(conversation_id) } @@ -3601,6 +3907,9 @@ fn conversation_summary_rollout_path_read_error( ) -> JSONRPCErrorError { match err { ThreadStoreError::InvalidRequest { message } => invalid_request(message), + ThreadStoreError::Unsupported { operation } => { + unsupported_thread_store_operation(operation) + } err => internal_error(format!( "failed to load conversation summary from {}: {}", path.display(), @@ -3615,6 +3924,9 @@ fn thread_store_write_error(operation: &str, err: ThreadStoreError) -> JSONRPCEr invalid_request(format!("thread not found: {thread_id}")) } ThreadStoreError::InvalidRequest { message } => invalid_request(message), + ThreadStoreError::Unsupported { operation } => { + unsupported_thread_store_operation(operation) + } err => internal_error(format!("failed to {operation}: {err}")), } } @@ -3622,6 +3934,9 @@ fn thread_store_write_error(operation: &str, err: ThreadStoreError) -> JSONRPCEr fn thread_store_archive_error(operation: &str, err: ThreadStoreError) -> JSONRPCErrorError { match err { ThreadStoreError::InvalidRequest { message } => invalid_request(message), + ThreadStoreError::Unsupported { + operation: unsupported_operation, + } => unsupported_thread_store_operation(unsupported_operation), err => internal_error(format!("failed to {operation} thread: {err}")), } } diff --git a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs index 5642dbbe81..422c7ecf26 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs @@ -630,6 +630,7 @@ mod thread_processor_behavior_tests { model_provider: None, service_tier: Some(Some("priority".to_string())), cwd: None, + workspace_roots: None, approval_policy: None, approvals_reviewer: None, sandbox: None, @@ -650,6 +651,7 @@ mod thread_processor_behavior_tests { permission_profile: codex_protocol::models::PermissionProfile::Disabled, active_permission_profile: None, cwd, + workspace_roots: Vec::new(), ephemeral: false, reasoning_effort: None, personality: None, diff --git a/codex-rs/app-server/src/request_processors/thread_summary.rs b/codex-rs/app-server/src/request_processors/thread_summary.rs index 875bd3deaf..726f23fc24 100644 --- a/codex-rs/app-server/src/request_processors/thread_summary.rs +++ b/codex-rs/app-server/src/request_processors/thread_summary.rs @@ -179,30 +179,24 @@ pub(super) fn apply_permission_profile_selection_to_config_overrides( overrides: &mut ConfigOverrides, permissions: Option, ) { - let Some(PermissionProfileSelectionParams::Profile { id, modifications }) = permissions else { + let Some(PermissionProfileSelectionParams::Profile { id }) = permissions else { return; }; overrides.default_permissions = Some(id); - overrides - .additional_writable_roots - .extend(modifications.unwrap_or_default().into_iter().map( - |modification| match modification { - PermissionProfileModificationParams::AdditionalWritableRoot { path } => { - path.to_path_buf() - } - }, - )); } pub(super) fn thread_response_sandbox_policy( permission_profile: &codex_protocol::models::PermissionProfile, + workspace_roots: &[AbsolutePathBuf], cwd: &Path, ) -> codex_app_server_protocol::SandboxPolicy { - let file_system_policy = permission_profile.file_system_sandbox_policy(); + let materialized_permission_profile = + permission_profile.materialize_project_roots_with_workspace_roots(workspace_roots); + let file_system_policy = materialized_permission_profile.file_system_sandbox_policy(); let sandbox_policy = codex_sandboxing::compatibility_sandbox_policy_for_permission_profile( - permission_profile, + &materialized_permission_profile, &file_system_policy, - permission_profile.network_sandbox_policy(), + materialized_permission_profile.network_sandbox_policy(), cwd, ); sandbox_policy.into() diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index bdc5847b0d..62aeb81ba2 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -354,6 +354,7 @@ impl TurnRequestProcessor { let turn_has_input = !mapped_items.is_empty(); let has_any_overrides = params.cwd.is_some() + || params.workspace_roots.is_some() || params.approval_policy.is_some() || params.approvals_reviewer.is_some() || params.sandbox_policy.is_some() @@ -370,52 +371,55 @@ impl TurnRequestProcessor { "`permissions` cannot be combined with `sandboxPolicy`", )); } + if params.sandbox_policy.is_some() { + return Err(invalid_request( + "`sandboxPolicy` cannot be used to change thread permissions", + )); + } let cwd = params.cwd; + let workspace_roots = params.workspace_roots; let approval_policy = params.approval_policy.map(AskForApproval::to_core); let approvals_reviewer = params .approvals_reviewer .map(codex_app_server_protocol::ApprovalsReviewer::to_core); let sandbox_policy = params.sandbox_policy.map(|p| p.to_core()); - let (permission_profile, active_permission_profile) = - if let Some(permissions) = params.permissions { - let snapshot = thread.config_snapshot().await; - let mut overrides = ConfigOverrides { - cwd: cwd.clone(), - 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() - }; - apply_permission_profile_selection_to_config_overrides( - &mut overrides, - Some(permissions), - ); - let config = self - .config_manager - .load_for_cwd( - /*request_overrides*/ None, - overrides, - Some(snapshot.cwd.to_path_buf()), - ) - .await - .map_err(|err| config_load_error(&err))?; - // Startup config is allowed to fall back when requirements - // disallow a configured profile. An explicit turn request - // is different: reject it before accepting user input. - if let Some(warning) = config.startup_warnings.iter().find(|warning| { - warning.contains("Configured value for `permission_profile` is disallowed") - }) { - return Err(invalid_request(format!( - "invalid turn context override: {warning}" - ))); - } - ( - Some(config.permissions.permission_profile()), - config.permissions.active_permission_profile(), - ) - } else { - (None, None) + let active_permission_profile = if let Some(permissions) = params.permissions { + let snapshot = thread.config_snapshot().await; + let mut overrides = ConfigOverrides { + cwd: cwd.clone(), + 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() }; + apply_permission_profile_selection_to_config_overrides( + &mut overrides, + Some(permissions), + ); + let config = self + .config_manager + .load_for_cwd( + /*request_overrides*/ None, + overrides, + Some(snapshot.cwd.to_path_buf()), + ) + .await + .map_err(|err| config_load_error(&err))?; + // Startup config is allowed to fall back when requirements + // disallow a configured profile. An explicit turn request + // is different: reject it before accepting user input. + if let Some(warning) = config.startup_warnings.iter().find(|warning| { + warning.contains("Configured value for `permission_profile` is disallowed") + }) { + return Err(invalid_request(format!( + "invalid turn context override: {warning}" + ))); + } + config.permissions.active_permission_profile() + } else { + None + }; + let permission_profile = None; let model = params.model; let effort = params.effort.map(Some); let summary = params.summary; @@ -429,6 +433,9 @@ impl TurnRequestProcessor { thread .validate_turn_context_overrides(CodexThreadTurnContextOverrides { cwd: cwd.clone(), + workspace_roots: workspace_roots + .clone() + .map(|roots| roots.into_iter().map(|root| root.to_path_buf()).collect()), approval_policy, approvals_reviewer, sandbox_policy: sandbox_policy.clone(), @@ -454,6 +461,7 @@ impl TurnRequestProcessor { final_output_json_schema: params.output_schema, responsesapi_client_metadata: params.responsesapi_client_metadata, cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox_policy, diff --git a/codex-rs/app-server/src/transport_tests.rs b/codex-rs/app-server/src/transport_tests.rs index 1600b8be87..5790e46a17 100644 --- a/codex-rs/app-server/src/transport_tests.rs +++ b/codex-rs/app-server/src/transport_tests.rs @@ -258,6 +258,7 @@ async fn command_execution_request_approval_strips_additional_permissions_withou thread_id: "thr_123".to_string(), turn_id: "turn_123".to_string(), item_id: "call_123".to_string(), + started_at_ms: 0, approval_id: None, reason: Some("Need extra read access".to_string()), network_approval_context: None, @@ -322,6 +323,7 @@ async fn command_execution_request_approval_keeps_additional_permissions_with_ca thread_id: "thr_123".to_string(), turn_id: "turn_123".to_string(), item_id: "call_123".to_string(), + started_at_ms: 0, approval_id: None, reason: Some("Need extra read access".to_string()), network_approval_context: None, diff --git a/codex-rs/app-server/tests/common/Cargo.toml b/codex-rs/app-server/tests/common/Cargo.toml index aef2f58dff..5b245f40d2 100644 --- a/codex-rs/app-server/tests/common/Cargo.toml +++ b/codex-rs/app-server/tests/common/Cargo.toml @@ -6,6 +6,8 @@ license.workspace = true [lib] path = "lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index c2a49d8fa6..81a5b2b401 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -89,6 +89,7 @@ use codex_app_server_protocol::ThreadRollbackParams; use codex_app_server_protocol::ThreadSetNameParams; use codex_app_server_protocol::ThreadShellCommandParams; use codex_app_server_protocol::ThreadStartParams; +use codex_app_server_protocol::ThreadTurnsItemsListParams; use codex_app_server_protocol::ThreadTurnsListParams; use codex_app_server_protocol::ThreadUnarchiveParams; use codex_app_server_protocol::ThreadUnsubscribeParams; @@ -522,6 +523,15 @@ impl McpProcess { self.send_request("thread/turns/list", params).await } + /// Send a `thread/turns/items/list` JSON-RPC request. + pub async fn send_thread_turns_items_list_request( + &mut self, + params: ThreadTurnsItemsListParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("thread/turns/items/list", params).await + } + /// Send a `model/list` JSON-RPC request. pub async fn send_list_models_request( &mut self, diff --git a/codex-rs/app-server/tests/common/rollout.rs b/codex-rs/app-server/tests/common/rollout.rs index 6b2a9a0abe..6c113297d7 100644 --- a/codex-rs/app-server/tests/common/rollout.rs +++ b/codex-rs/app-server/tests/common/rollout.rs @@ -135,6 +135,7 @@ pub fn create_fake_rollout_with_source( forked_from_id: None, timestamp: meta_rfc3339.to_string(), cwd: PathBuf::from("/"), + workspace_roots: Vec::new(), originator: "codex".to_string(), cli_version: "0.0.0".to_string(), source, @@ -219,6 +220,7 @@ pub fn create_fake_rollout_with_text_elements( forked_from_id: None, timestamp: meta_rfc3339.to_string(), cwd: PathBuf::from("/"), + workspace_roots: Vec::new(), originator: "codex".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::Cli, diff --git a/codex-rs/app-server/tests/suite/conversation_summary.rs b/codex-rs/app-server/tests/suite/conversation_summary.rs index c06ff8599a..754d1f9467 100644 --- a/codex-rs/app-server/tests/suite/conversation_summary.rs +++ b/codex-rs/app-server/tests/suite/conversation_summary.rs @@ -12,7 +12,6 @@ use codex_app_server_protocol::GetConversationSummaryParams; use codex_app_server_protocol::GetConversationSummaryResponse; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeParams; -use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_arg0::Arg0DispatchPaths; @@ -46,7 +45,6 @@ const CREATED_AT_RFC3339: &str = "2025-01-02T12:00:00.000Z"; const UPDATED_AT_RFC3339: &str = "2025-01-02T12:00:00.000Z"; const PREVIEW: &str = "Summarize this conversation"; const MODEL_PROVIDER: &str = "openai"; -const INVALID_REQUEST_ERROR_CODE: i64 = -32600; fn expected_summary(conversation_id: ThreadId, path: PathBuf) -> ConversationSummary { ConversationSummary { @@ -114,37 +112,6 @@ async fn get_conversation_summary_by_thread_id_reads_rollout() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn get_conversation_summary_by_rollout_path_rejects_remote_thread_store() -> Result<()> { - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - r#"experimental_thread_store_endpoint = "http://127.0.0.1:1" -"#, - )?; - - 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: PathBuf::from("sessions/2025/01/02/rollout.jsonl"), - }) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error.error.message, - "rollout path queries are only supported with the local thread store" - ); - Ok(()) -} - #[tokio::test] async fn get_conversation_summary_by_thread_id_reads_pathless_store_thread() -> Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/app-server/tests/suite/v2/plugin_share.rs b/codex-rs/app-server/tests/suite/v2/plugin_share.rs index 09b39ca241..dc1f56d487 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_share.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_share.rs @@ -219,7 +219,7 @@ async fn plugin_share_save_forwards_access_policy() -> Result<()> { .and(body_json(json!({ "file_id": "file_123", "etag": "\"upload_etag_123\"", - "discoverability": "PRIVATE", + "discoverability": "UNLISTED", "share_targets": [ { "principal_type": "user", @@ -227,7 +227,7 @@ async fn plugin_share_save_forwards_access_policy() -> Result<()> { }, { "principal_type": "workspace", - "principal_id": "workspace-1", + "principal_id": "account-123", }, ], }))) @@ -247,16 +247,12 @@ async fn plugin_share_save_forwards_access_policy() -> Result<()> { "plugin/share/save", Some(json!({ "pluginPath": expected_plugin_path, - "discoverability": "PRIVATE", + "discoverability": "UNLISTED", "shareTargets": [ { "principalType": "user", "principalId": "user-1", }, - { - "principalType": "workspace", - "principalId": "workspace-1", - }, ], })), ) @@ -279,6 +275,124 @@ async fn plugin_share_save_forwards_access_policy() -> Result<()> { Ok(()) } +#[tokio::test] +async fn plugin_share_save_rejects_listed_discoverability() -> Result<()> { + let codex_home = TempDir::new()?; + let plugin_root = TempDir::new()?; + let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; + let server = MockServer::start().await; + write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .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_raw_request( + "plugin/share/save", + Some(json!({ + "pluginPath": AbsolutePathBuf::try_from(plugin_path)?, + "discoverability": "LISTED", + })), + ) + .await?; + + let error: JSONRPCError = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(error.error.code, -32600); + assert_eq!( + error.error.message, + "discoverability LISTED is not supported for plugin/share/save; use UNLISTED or PRIVATE" + ); + Ok(()) +} + +#[tokio::test] +async fn plugin_share_rejects_workspace_targets_from_client() -> Result<()> { + let codex_home = TempDir::new()?; + let plugin_root = TempDir::new()?; + let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; + let server = MockServer::start().await; + write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .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_raw_request( + "plugin/share/save", + Some(json!({ + "pluginPath": AbsolutePathBuf::try_from(plugin_path)?, + "discoverability": "UNLISTED", + "shareTargets": [ + { + "principalType": "workspace", + "principalId": "account-123", + }, + ], + })), + ) + .await?; + + let error: JSONRPCError = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(error.error.code, -32600); + assert_eq!( + error.error.message, + "shareTargets cannot include workspace principals; use discoverability UNLISTED for workspace link access" + ); + + let request_id = mcp + .send_raw_request( + "plugin/share/updateTargets", + Some(json!({ + "remotePluginId": "plugins_123", + "discoverability": "UNLISTED", + "shareTargets": [ + { + "principalType": "workspace", + "principalId": "account-123", + }, + ], + })), + ) + .await?; + + let error: JSONRPCError = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(error.error.code, -32600); + assert_eq!( + error.error.message, + "shareTargets cannot include workspace principals; use discoverability UNLISTED for workspace link access" + ); + Ok(()) +} + #[tokio::test] async fn plugin_share_save_rejects_access_policy_for_existing_plugin() -> Result<()> { let codex_home = TempDir::new()?; @@ -323,7 +437,7 @@ async fn plugin_share_save_rejects_access_policy_for_existing_plugin() -> Result assert_eq!(error.error.code, -32600); assert_eq!( error.error.message, - "discoverability and shareTargets are only supported when creating a plugin share; use plugin/share/updateTargets to update share targets" + "discoverability and shareTargets are only supported when creating a plugin share; use plugin/share/updateTargets to update share settings" ); Ok(()) } @@ -420,24 +534,39 @@ async fn plugin_share_update_targets_updates_share_targets() -> Result<()> { )?; Mock::given(method("PUT")) - .and(path("/backend-api/public/plugins/plugins_123/shares")) + .and(path("/backend-api/ps/plugins/plugins_123/shares")) .and(header("authorization", "Bearer chatgpt-token")) .and(header("chatgpt-account-id", "account-123")) .and(body_json(json!({ + "discoverability": "UNLISTED", "targets": [ { "principal_type": "user", "principal_id": "user-1", }, + { + "principal_type": "workspace", + "principal_id": "account-123", + }, ], }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "principals": [ + { + "principal_type": "user", + "principal_id": "owner-1", + "name": "Owner", + }, { "principal_type": "user", "principal_id": "user-1", "name": "Gavin", }, + { + "principal_type": "workspace", + "principal_id": "account-123", + "name": "Workspace", + }, ], }))) .expect(1) @@ -451,6 +580,7 @@ async fn plugin_share_update_targets_updates_share_targets() -> Result<()> { "plugin/share/updateTargets", Some(json!({ "remotePluginId": "plugins_123", + "discoverability": "UNLISTED", "shareTargets": [ { "principalType": "user", @@ -476,6 +606,7 @@ async fn plugin_share_update_targets_updates_share_targets() -> Result<()> { principal_id: "user-1".to_string(), name: "Gavin".to_string(), }], + discoverability: codex_app_server_protocol::PluginShareDiscoverability::Unlisted, } ); Ok(()) diff --git a/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs b/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs index b04eb12a45..e5c0b2c53f 100644 --- a/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs +++ b/codex-rs/app-server/tests/suite/v2/remote_thread_store.rs @@ -3,9 +3,8 @@ //! //! The app-server startup path should honor `experimental_thread_store` //! by routing all thread persistence through the configured store. This suite uses -//! the thread-store crate's test-only in-memory store, which exercises the same -//! config-driven selection path as a remote store without requiring the real gRPC -//! service. +//! the thread-store crate's test-only in-memory store to exercise the non-local +//! config-driven selection path without touching local rollout or sqlite storage. //! //! The important failure mode is accidentally materializing local persistence //! while a non-local store is configured. After `thread/start` and a simple turn, diff --git a/codex-rs/app-server/tests/suite/v2/skills_list.rs b/codex-rs/app-server/tests/suite/v2/skills_list.rs index cbfeb32870..473e081b00 100644 --- a/codex-rs/app-server/tests/suite/v2/skills_list.rs +++ b/codex-rs/app-server/tests/suite/v2/skills_list.rs @@ -11,7 +11,6 @@ use codex_app_server_protocol::PluginListParams; use codex_app_server_protocol::PluginListResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SkillsChangedNotification; -use codex_app_server_protocol::SkillsListExtraRootsForCwd; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::SkillsListResponse; use codex_app_server_protocol::ThreadStartParams; @@ -133,44 +132,6 @@ fn write_cached_remote_plugin_with_skill( Ok(skill_path) } -#[tokio::test] -async fn skills_list_includes_skills_from_per_cwd_extra_user_roots() -> Result<()> { - let codex_home = TempDir::new()?; - let cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&extra_root, "extra-skill")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(response)?; - assert_eq!(data.len(), 1); - assert_eq!(data[0].cwd.as_path(), cwd.path()); - assert!( - data[0] - .skills - .iter() - .any(|skill| skill.name == "extra-skill") - ); - Ok(()) -} - #[tokio::test] async fn skills_list_loads_remote_installed_plugin_skills_from_cache() -> Result<()> { let codex_home = TempDir::new()?; @@ -266,7 +227,6 @@ async fn skills_list_loads_remote_installed_plugin_skills_from_cache() -> Result .send_skills_list_request(SkillsListParams { cwds: vec![cwd.path().to_path_buf()], force_reload: true, - per_cwd_extra_user_roots: None, }) .await?; let stale_skills_list_response: JSONRPCResponse = timeout( @@ -317,7 +277,6 @@ async fn skills_list_loads_remote_installed_plugin_skills_from_cache() -> Result .send_skills_list_request(SkillsListParams { cwds: vec![cwd.path().to_path_buf()], force_reload: false, - per_cwd_extra_user_roots: None, }) .await?; let skills_list_response: JSONRPCResponse = timeout( @@ -392,7 +351,6 @@ async fn skills_list_excludes_plugin_skills_when_workspace_codex_plugins_disable .send_skills_list_request(SkillsListParams { cwds: vec![repo_root.path().to_path_buf()], force_reload: true, - per_cwd_extra_user_roots: None, }) .await?; @@ -424,9 +382,13 @@ async fn skills_list_excludes_plugin_skills_when_workspace_codex_plugins_disable async fn skills_list_skips_cwd_roots_when_environment_disabled() -> Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; - let extra_root = TempDir::new()?; write_skill(&codex_home, "home-skill")?; - write_skill(&extra_root, "extra-skill")?; + let repo_skill_dir = cwd.path().join(".codex/skills/repo-skill"); + std::fs::create_dir_all(&repo_skill_dir)?; + std::fs::write( + repo_skill_dir.join("SKILL.md"), + "---\nname: repo-skill\ndescription: from repo root\n---\n\n# Body\n", + )?; let mut mcp = McpProcess::new_with_env( codex_home.path(), @@ -439,10 +401,6 @@ async fn skills_list_skips_cwd_roots_when_environment_disabled() -> Result<()> { .send_skills_list_request(SkillsListParams { cwds: vec![cwd.path().to_path_buf()], force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), }) .await?; @@ -465,41 +423,7 @@ async fn skills_list_skips_cwd_roots_when_environment_disabled() -> Result<()> { data[0] .skills .iter() - .all(|skill| skill.name != "extra-skill") - ); - Ok(()) -} - -#[tokio::test] -async fn skills_list_rejects_relative_extra_user_roots() -> Result<()> { - let codex_home = TempDir::new()?; - let cwd = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![std::path::PathBuf::from("relative/skills")], - }]), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert!( - err.error - .message - .contains("perCwdExtraUserRoots extraUserRoots paths must be absolute"), - "unexpected error: {}", - err.error.message + .all(|skill| skill.name != "repo-skill") ); Ok(()) } @@ -517,7 +441,6 @@ async fn skills_list_accepts_relative_cwds() -> Result<()> { .send_skills_list_request(SkillsListParams { cwds: vec![relative_cwd.clone()], force_reload: true, - per_cwd_extra_user_roots: None, }) .await?; @@ -549,7 +472,6 @@ async fn skills_list_preserves_requested_cwd_order() -> Result<()> { second_cwd.path().to_path_buf(), ], force_reload: true, - per_cwd_extra_user_roots: None, }) .await?; @@ -571,61 +493,19 @@ async fn skills_list_preserves_requested_cwd_order() -> Result<()> { Ok(()) } -#[tokio::test] -async fn skills_list_ignores_per_cwd_extra_roots_for_unknown_cwd() -> Result<()> { - let codex_home = TempDir::new()?; - let requested_cwd = TempDir::new()?; - let unknown_cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&extra_root, "ignored-extra-skill")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![requested_cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: unknown_cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(response)?; - assert_eq!(data.len(), 1); - assert_eq!(data[0].cwd.as_path(), requested_cwd.path()); - assert!( - data[0] - .skills - .iter() - .all(|skill| skill.name != "ignored-extra-skill") - ); - Ok(()) -} - #[tokio::test] async fn skills_list_uses_cached_result_until_force_reload() -> Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&extra_root, "late-extra-skill")?; let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - // Seed the cwd cache first without extra roots. + // Seed the cwd cache before the cwd-local skill exists. let first_request_id = mcp .send_skills_list_request(SkillsListParams { cwds: vec![cwd.path().to_path_buf()], force_reload: false, - per_cwd_extra_user_roots: None, }) .await?; let first_response: JSONRPCResponse = timeout( @@ -642,14 +522,17 @@ async fn skills_list_uses_cached_result_until_force_reload() -> Result<()> { .all(|skill| skill.name != "late-extra-skill") ); + let skill_dir = cwd.path().join(".codex/skills/late-extra-skill"); + std::fs::create_dir_all(&skill_dir)?; + std::fs::write( + skill_dir.join("SKILL.md"), + "---\nname: late-extra-skill\ndescription: late skill\n---\n\n# Body\n", + )?; + let second_request_id = mcp .send_skills_list_request(SkillsListParams { cwds: vec![cwd.path().to_path_buf()], force_reload: false, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), }) .await?; let second_response: JSONRPCResponse = timeout( @@ -670,10 +553,6 @@ async fn skills_list_uses_cached_result_until_force_reload() -> Result<()> { .send_skills_list_request(SkillsListParams { cwds: vec![cwd.path().to_path_buf()], force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), }) .await?; let third_response: JSONRPCResponse = timeout( @@ -709,6 +588,7 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<( approvals_reviewer: None, sandbox: None, permissions: None, + workspace_roots: None, config: None, service_name: None, base_instructions: None, 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 8394f9839e..3eb262bd2b 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -33,7 +33,6 @@ use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; use std::path::Path; -use std::path::PathBuf; use tempfile::TempDir; use tokio::time::timeout; use wiremock::Mock; @@ -51,7 +50,6 @@ use super::analytics::wait_for_analytics_payload; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); #[cfg(not(windows))] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); -const INTERNAL_ERROR_CODE: i64 = -32603; #[tokio::test] async fn thread_fork_creates_new_thread_and_emits_started() -> Result<()> { @@ -269,37 +267,6 @@ async fn thread_fork_can_load_source_by_path() -> Result<()> { Ok(()) } -#[tokio::test] -async fn thread_fork_by_path_uses_remote_thread_store_error() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - let codex_home = TempDir::new()?; - create_config_toml_with_remote_thread_store(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let fork_id = mcp - .send_thread_fork_request(ThreadForkParams { - thread_id: "not-a-valid-thread-id".to_string(), - path: Some(PathBuf::from("sessions/2025/01/05/rollout.jsonl")), - ..Default::default() - }) - .await?; - let fork_err: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(fork_id)), - ) - .await??; - - assert_eq!(fork_err.error.code, INTERNAL_ERROR_CODE); - assert_eq!( - fork_err.error.message, - "failed to read thread: thread-store internal error: remote thread store does not support read_thread_by_rollout_path" - ); - - Ok(()) -} - #[tokio::test] async fn thread_fork_emits_restored_token_usage_before_next_turn() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; @@ -779,33 +746,6 @@ stream_max_retries = 0 ) } -fn create_config_toml_with_remote_thread_store( - 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" -experimental_thread_store_endpoint = "http://127.0.0.1:1" - -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 -"# - ), - ) -} - fn create_config_toml_with_chatgpt_base_url( codex_home: &Path, server_uri: &str, diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rs index 80254d8f47..c8872c47bf 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_list.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs @@ -610,6 +610,7 @@ sqlite = true codex_home: codex_home.path().to_path_buf(), sqlite_home: codex_home.path().to_path_buf(), cwd: codex_home.path().to_path_buf(), + workspace_roots: Vec::new(), model_provider_id: "mock_provider".to_string(), generate_memories: false, }; 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 0e9a7a9a05..c1fca44a44 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_read.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_read.rs @@ -31,6 +31,7 @@ use codex_app_server_protocol::ThreadSetNameResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::ThreadStatus; +use codex_app_server_protocol::ThreadTurnsItemsListParams; use codex_app_server_protocol::ThreadTurnsListParams; use codex_app_server_protocol::ThreadTurnsListResponse; use codex_app_server_protocol::TurnItemsView; @@ -46,6 +47,7 @@ use codex_core::config::ConfigBuilder; use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_protocol::models::BaseInstructions; +use codex_protocol::protocol::AgentMessageEvent; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource as ProtocolSessionSource; @@ -223,6 +225,7 @@ async fn thread_turns_list_can_page_backward_and_forward() -> Result<()> { cursor: None, limit: Some(2), sort_direction: Some(SortDirection::Desc), + items_view: None, }) .await?; let read_resp: JSONRPCResponse = timeout( @@ -238,7 +241,7 @@ async fn thread_turns_list_can_page_backward_and_forward() -> Result<()> { assert_eq!(turn_user_texts(&data), vec!["third", "second"]); assert!( data.iter() - .all(|turn| turn.items_view == TurnItemsView::Full) + .all(|turn| turn.items_view == TurnItemsView::Summary) ); let next_cursor = next_cursor.expect("expected nextCursor for older turns"); let backwards_cursor = backwards_cursor.expect("expected backwardsCursor for newest turn"); @@ -249,6 +252,7 @@ async fn thread_turns_list_can_page_backward_and_forward() -> Result<()> { cursor: Some(next_cursor), limit: Some(10), sort_direction: Some(SortDirection::Desc), + items_view: None, }) .await?; let read_resp: JSONRPCResponse = timeout( @@ -267,6 +271,7 @@ async fn thread_turns_list_can_page_backward_and_forward() -> Result<()> { cursor: Some(backwards_cursor), limit: Some(10), sort_direction: Some(SortDirection::Asc), + items_view: None, }) .await?; let read_resp: JSONRPCResponse = timeout( @@ -280,6 +285,74 @@ async fn thread_turns_list_can_page_backward_and_forward() -> Result<()> { Ok(()) } +#[tokio::test] +async fn thread_turns_list_supports_requested_items_view() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let filename_ts = "2025-01-05T12-00-00"; + let conversation_id = create_fake_rollout_with_text_elements( + codex_home.path(), + filename_ts, + "2025-01-05T12:00:00Z", + "first", + vec![], + Some("mock_provider"), + /*git_info*/ None, + )?; + let rollout_path = rollout_path(codex_home.path(), filename_ts, &conversation_id); + append_agent_message(rollout_path.as_path(), "2025-01-05T12:01:00Z", "draft")?; + append_agent_message(rollout_path.as_path(), "2025-01-05T12:02:00Z", "final")?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let full = read_single_turn_items_view( + &mut mcp, + conversation_id.as_str(), + Some(TurnItemsView::Full), + ) + .await?; + assert_eq!(full.items_view, TurnItemsView::Full); + assert_eq!( + turn_agent_texts(std::slice::from_ref(&full)), + vec!["draft", "final"] + ); + + let summary = read_single_turn_items_view( + &mut mcp, + conversation_id.as_str(), + Some(TurnItemsView::Summary), + ) + .await?; + assert_eq!(summary.items_view, TurnItemsView::Summary); + assert_eq!( + turn_user_texts(std::slice::from_ref(&summary)), + vec!["first"] + ); + assert_eq!( + turn_agent_texts(std::slice::from_ref(&summary)), + vec!["final"] + ); + + let not_loaded = read_single_turn_items_view( + &mut mcp, + conversation_id.as_str(), + Some(TurnItemsView::NotLoaded), + ) + .await?; + assert_eq!(not_loaded.items_view, TurnItemsView::NotLoaded); + assert!(not_loaded.items.is_empty()); + assert_eq!(not_loaded.id, full.id); + assert_eq!(not_loaded.status, full.status); + assert_eq!(not_loaded.started_at, full.started_at); + assert_eq!(not_loaded.completed_at, full.completed_at); + assert_eq!(not_loaded.duration_ms, full.duration_ms); + + Ok(()) +} + #[tokio::test] async fn thread_turns_list_reads_store_history_without_rollout_path() -> Result<()> { let codex_home = TempDir::new()?; @@ -334,6 +407,7 @@ async fn thread_turns_list_reads_store_history_without_rollout_path() -> Result< cursor: None, limit: Some(10), sort_direction: Some(SortDirection::Asc), + items_view: None, }, }) .await? @@ -583,6 +657,7 @@ async fn thread_turns_list_rejects_cursor_when_anchor_turn_is_rolled_back() -> R cursor: None, limit: Some(2), sort_direction: Some(SortDirection::Desc), + items_view: None, }) .await?; let read_resp: JSONRPCResponse = timeout( @@ -607,6 +682,7 @@ async fn thread_turns_list_rejects_cursor_when_anchor_turn_is_rolled_back() -> R cursor: Some(backwards_cursor), limit: Some(10), sort_direction: Some(SortDirection::Asc), + items_view: None, }) .await?; let read_err: JSONRPCError = timeout( @@ -963,6 +1039,7 @@ async fn thread_turns_list_rejects_unmaterialized_loaded_thread() -> Result<()> cursor: None, limit: None, sort_direction: None, + items_view: None, }) .await?; let read_err: JSONRPCError = timeout( @@ -983,6 +1060,39 @@ async fn thread_turns_list_rejects_unmaterialized_loaded_thread() -> Result<()> Ok(()) } +#[tokio::test] +async fn thread_turns_items_list_returns_unsupported() -> 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 read_id = mcp + .send_thread_turns_items_list_request(ThreadTurnsItemsListParams { + thread_id: "thr_123".to_string(), + turn_id: "turn_456".to_string(), + cursor: None, + limit: None, + sort_direction: None, + }) + .await?; + let read_err: JSONRPCError = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(read_id)), + ) + .await??; + + assert_eq!(read_err.error.code, -32601); + assert_eq!( + read_err.error.message, + "thread/turns/items/list is not supported yet" + ); + + Ok(()) +} + #[tokio::test] async fn thread_read_reports_system_error_idle_flag_after_failed_turn() -> Result<()> { let server = responses::start_mock_server().await; @@ -1068,6 +1178,24 @@ fn append_user_message(path: &Path, timestamp: &str, text: &str) -> std::io::Res ) } +fn append_agent_message(path: &Path, timestamp: &str, text: &str) -> anyhow::Result<()> { + let mut file = std::fs::OpenOptions::new().append(true).open(path)?; + writeln!( + file, + "{}", + json!({ + "timestamp": timestamp, + "type": "event_msg", + "payload": serde_json::to_value(EventMsg::AgentMessage(AgentMessageEvent { + message: text.to_string(), + phase: None, + memory_citation: None, + }))?, + }) + )?; + Ok(()) +} + fn append_thread_rollback(path: &Path, timestamp: &str, num_turns: u32) -> std::io::Result<()> { let mut file = std::fs::OpenOptions::new().append(true).open(path)?; writeln!( @@ -1084,6 +1212,31 @@ fn append_thread_rollback(path: &Path, timestamp: &str, num_turns: u32) -> std:: ) } +async fn read_single_turn_items_view( + mcp: &mut McpProcess, + thread_id: &str, + items_view: Option, +) -> anyhow::Result { + let read_id = mcp + .send_thread_turns_list_request(ThreadTurnsListParams { + thread_id: thread_id.to_string(), + cursor: None, + limit: Some(10), + sort_direction: Some(SortDirection::Asc), + items_view, + }) + .await?; + let read_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(read_id)), + ) + .await??; + let ThreadTurnsListResponse { mut data, .. } = + to_response::(read_resp)?; + assert_eq!(data.len(), 1); + Ok(data.remove(0)) +} + fn turn_user_texts(turns: &[codex_app_server_protocol::Turn]) -> Vec<&str> { turns .iter() @@ -1100,6 +1253,17 @@ fn turn_user_texts(turns: &[codex_app_server_protocol::Turn]) -> Vec<&str> { .collect() } +fn turn_agent_texts(turns: &[codex_app_server_protocol::Turn]) -> Vec<&str> { + turns + .iter() + .flat_map(|turn| &turn.items) + .filter_map(|item| match item { + ThreadItem::AgentMessage { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect() +} + struct InMemoryThreadStoreId { store_id: String, } @@ -1124,6 +1288,7 @@ async fn seed_pathless_store_thread( dynamic_tools: Vec::new(), metadata: ThreadPersistenceMetadata { cwd: None, + workspace_roots: Vec::new(), model_provider: "test-provider".to_string(), memory_mode: ThreadMemoryMode::Disabled, }, 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 7d7de25515..fcff0c57ce 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -95,7 +95,6 @@ use super::analytics::wait_for_analytics_payload; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25); #[cfg(not(windows))] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); -const INTERNAL_ERROR_CODE: i64 = -32603; const CODEX_5_2_INSTRUCTIONS_TEMPLATE_DEFAULT: &str = "You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals."; fn normalized_existing_path(path: impl AsRef) -> Result { @@ -745,37 +744,6 @@ async fn thread_goal_clear_deletes_goal_and_notifies() -> Result<()> { Ok(()) } -#[tokio::test] -async fn thread_resume_by_path_uses_remote_thread_store_error() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - let codex_home = TempDir::new()?; - create_config_toml_with_remote_thread_store(codex_home.path(), &server.uri())?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let resume_id = mcp - .send_thread_resume_request(ThreadResumeParams { - thread_id: "ignored-when-path-is-present".to_string(), - path: Some(PathBuf::from("sessions/2025/01/05/rollout.jsonl")), - ..Default::default() - }) - .await?; - let resume_err: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(resume_id)), - ) - .await??; - - assert_eq!(resume_err.error.code, INTERNAL_ERROR_CODE); - assert_eq!( - resume_err.error.message, - "failed to read thread: thread-store internal error: remote thread store does not support read_thread_by_rollout_path" - ); - - Ok(()) -} - #[tokio::test] async fn thread_resume_emits_restored_token_usage_before_next_turn() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; @@ -1207,6 +1175,7 @@ stream_max_retries = 0 forked_from_id: None, timestamp: "2025-01-05T12:00:00Z".to_string(), cwd: repo_path.clone(), + workspace_roots: Vec::new(), originator: "codex".to_string(), cli_version: "0.0.0".to_string(), source: RolloutSessionSource::Cli, @@ -2928,36 +2897,6 @@ stream_max_retries = 0 ) } -fn create_config_toml_with_remote_thread_store( - 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 = "gpt-5.3-codex" -approval_policy = "never" -sandbox_mode = "read-only" -experimental_thread_store_endpoint = "http://127.0.0.1:1" - -model_provider = "mock_provider" - -[features] -personality = true - -[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 -"# - ), - ) -} - fn create_config_toml_with_chatgpt_base_url( codex_home: &std::path::Path, server_uri: &str, diff --git a/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs b/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs index eebc4077df..b7cfba2f95 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs @@ -151,6 +151,7 @@ async fn thread_shell_command_history_responses_exclude_persisted_command_execut cursor: None, limit: None, sort_direction: Some(SortDirection::Asc), + items_view: None, }) .await?; let turns_list_resp: JSONRPCResponse = timeout( 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 e5c5c5adbb..ded5f25790 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -330,7 +330,7 @@ async fn turn_start_emits_thread_scoped_warning_notification_for_trimmed_skills( assert_eq!(warning.thread_id.as_deref(), Some(thread.id.as_str())); assert_eq!( warning.message, - "Exceeded skills context budget of 2%. All skill descriptions were removed and 7 additional skills were not included in the model-visible skills list." + "Exceeded skills context budget of 2%. All skill descriptions were removed and 12 additional skills were not included in the model-visible skills list." ); timeout( @@ -775,7 +775,6 @@ async fn turn_start_rejects_invalid_permission_selection_before_starting_turn() }], permissions: Some(PermissionProfileSelectionParams::Profile { id: ":danger-no-sandbox".to_string(), - modifications: None, }), ..Default::default() }) @@ -1651,7 +1650,6 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { text_elements: Vec::new(), }], approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), - sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), model: Some("mock-model".to_string()), effort: Some(ReasoningEffort::Medium), summary: Some(ReasoningSummary::Auto), @@ -1819,7 +1817,7 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> { } #[tokio::test] -async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { +async fn turn_start_updates_cwd_without_replacing_workspace_roots_v2() -> Result<()> { skip_if_no_network!(Ok(())); let tmp = TempDir::new()?; @@ -1873,7 +1871,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { .await??; let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; - // first turn with workspace-write sandbox and first_cwd + // first turn with first_cwd as the thread's workspace root let first_turn = mcp .send_turn_start_request(TurnStartParams { environments: None, @@ -1884,14 +1882,10 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { }], responsesapi_client_metadata: None, cwd: Some(first_cwd.clone()), + workspace_roots: Some(vec![first_cwd.try_into()?]), approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), approvals_reviewer: None, - sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::WorkspaceWrite { - writable_roots: vec![first_cwd.try_into()?], - network_access: false, - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - }), + sandbox_policy: None, permissions: None, model: Some("mock-model".to_string()), effort: Some(ReasoningEffort::Medium), @@ -1914,7 +1908,8 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { .await??; mcp.clear_message_buffer(); - // second turn with workspace-write and second_cwd, ensure exec begins in second_cwd + // second turn changes cwd only; workspace roots stay on first_cwd while + // exec begins in second_cwd. let second_turn = mcp .send_turn_start_request(TurnStartParams { environments: None, @@ -1925,9 +1920,10 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { }], responsesapi_client_metadata: None, cwd: Some(second_cwd.clone()), + workspace_roots: None, approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), approvals_reviewer: None, - sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), + sandbox_policy: None, permissions: None, model: Some("mock-model".to_string()), effort: Some(ReasoningEffort::Medium), @@ -3321,7 +3317,6 @@ async fn command_execution_notifications_include_process_id() -> Result<()> { text: "run a command".to_string(), text_elements: Vec::new(), }], - sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), ..Default::default() }) .await?; @@ -3417,7 +3412,7 @@ async fn command_execution_notifications_include_process_id() -> Result<()> { } #[tokio::test] -async fn turn_start_with_elevated_override_does_not_persist_project_trust() -> Result<()> { +async fn turn_start_rejects_sandbox_policy_and_does_not_persist_project_trust() -> Result<()> { let responses = vec![create_final_assistant_message_sse_response("Done")?]; let server = create_mock_responses_server_sequence_unchecked(responses).await; @@ -3459,16 +3454,25 @@ async fn turn_start_with_elevated_override_does_not_persist_project_trust() -> R ..Default::default() }) .await?; - timeout( + let err: JSONRPCError = timeout( DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(turn_request)), + mcp.read_stream_until_error_message(RequestId::Integer(turn_request)), ) .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), + assert_eq!(err.error.code, INVALID_REQUEST_ERROR_CODE); + assert_eq!( + err.error.message, + "`sandboxPolicy` cannot be used to change thread permissions" + ); + let turn_started = tokio::time::timeout( + std::time::Duration::from_millis(250), + mcp.read_stream_until_notification_message("turn/started"), ) - .await??; + .await; + assert!( + turn_started.is_err(), + "did not expect a turn/started notification after rejected sandboxPolicy" + ); let config_toml = std::fs::read_to_string(codex_home.path().join("config.toml"))?; assert!(!config_toml.contains("trust_level = \"trusted\"")); 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 31247418e5..c20eb58883 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 @@ -104,6 +104,7 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> { .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), cwd: Some(workspace.to_string_lossy().into_owned()), + sandbox: Some(codex_app_server_protocol::SandboxMode::DangerFullAccess), ..Default::default() }) .await?; @@ -123,7 +124,6 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> { }], cwd: Some(workspace.clone()), approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), - sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::DangerFullAccess), model: Some("mock-model".to_string()), effort: Some(codex_protocol::openai_models::ReasoningEffort::Medium), summary: Some(codex_protocol::config_types::ReasoningSummary::Auto), @@ -515,6 +515,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() .send_thread_start_request(ThreadStartParams { model: Some("mock-model".to_string()), cwd: Some(workspace.to_string_lossy().into_owned()), + sandbox: Some(codex_app_server_protocol::SandboxMode::WorkspaceWrite), ..Default::default() }) .await?; @@ -533,13 +534,9 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() text_elements: Vec::new(), }], cwd: Some(workspace.clone()), + workspace_roots: Some(vec![workspace.clone().try_into()?]), approval_policy: Some(codex_app_server_protocol::AskForApproval::UnlessTrusted), - sandbox_policy: Some(codex_app_server_protocol::SandboxPolicy::WorkspaceWrite { - writable_roots: vec![workspace.clone().try_into()?], - network_access: false, - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - }), + sandbox_policy: None, model: Some("mock-model".to_string()), effort: Some(codex_protocol::openai_models::ReasoningEffort::Medium), summary: Some(codex_protocol::config_types::ReasoningSummary::Auto), diff --git a/codex-rs/apply-patch/Cargo.toml b/codex-rs/apply-patch/Cargo.toml index ba4fa5e48e..2584338618 100644 --- a/codex-rs/apply-patch/Cargo.toml +++ b/codex-rs/apply-patch/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_apply_patch" path = "src/lib.rs" +doctest = false [[bin]] name = "apply_patch" diff --git a/codex-rs/arg0/Cargo.toml b/codex-rs/arg0/Cargo.toml index 8da0fcbd0b..7ee21a770e 100644 --- a/codex-rs/arg0/Cargo.toml +++ b/codex-rs/arg0/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_arg0" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/async-utils/Cargo.toml b/codex-rs/async-utils/Cargo.toml index 891af17a5f..9f81ff818e 100644 --- a/codex-rs/async-utils/Cargo.toml +++ b/codex-rs/async-utils/Cargo.toml @@ -14,3 +14,6 @@ tokio-util.workspace = true [dev-dependencies] pretty_assertions.workspace = true + +[lib] +doctest = false diff --git a/codex-rs/aws-auth/Cargo.toml b/codex-rs/aws-auth/Cargo.toml index 9e49f7bbe5..6bb5a69ae9 100644 --- a/codex-rs/aws-auth/Cargo.toml +++ b/codex-rs/aws-auth/Cargo.toml @@ -13,7 +13,7 @@ path = "src/lib.rs" workspace = true [dependencies] -aws-config = { workspace = true } +aws-config = { workspace = true, features = ["credentials-login"] } aws-credential-types = { workspace = true } aws-sigv4 = { workspace = true } aws-types = { workspace = true } diff --git a/codex-rs/backend-client/Cargo.toml b/codex-rs/backend-client/Cargo.toml index d2e374ae2a..f7b0c8b0f5 100644 --- a/codex-rs/backend-client/Cargo.toml +++ b/codex-rs/backend-client/Cargo.toml @@ -7,6 +7,7 @@ publish = false [lib] path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/builtin-mcps/Cargo.toml b/codex-rs/builtin-mcps/Cargo.toml index ee61f96750..9eb2123329 100644 --- a/codex-rs/builtin-mcps/Cargo.toml +++ b/codex-rs/builtin-mcps/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_builtin_mcps" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/chatgpt/Cargo.toml b/codex-rs/chatgpt/Cargo.toml index 62cb56a022..6b0e010964 100644 --- a/codex-rs/chatgpt/Cargo.toml +++ b/codex-rs/chatgpt/Cargo.toml @@ -27,3 +27,6 @@ codex-utils-cargo-bin = { workspace = true } pretty_assertions = { workspace = true } serde_json = { workspace = true } tempfile = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index cdee241b42..f2a289bf62 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" [lib] name = "codex_cli" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/cloud-requirements/Cargo.toml b/codex-rs/cloud-requirements/Cargo.toml index 59f8741cdb..cc7aefc478 100644 --- a/codex-rs/cloud-requirements/Cargo.toml +++ b/codex-rs/cloud-requirements/Cargo.toml @@ -30,3 +30,6 @@ tracing = { workspace = true } pretty_assertions = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["macros", "rt", "test-util", "time"] } + +[lib] +doctest = false diff --git a/codex-rs/cloud-tasks-client/Cargo.toml b/codex-rs/cloud-tasks-client/Cargo.toml index 929c3e3136..df8ec12b20 100644 --- a/codex-rs/cloud-tasks-client/Cargo.toml +++ b/codex-rs/cloud-tasks-client/Cargo.toml @@ -7,6 +7,8 @@ version.workspace = true [lib] name = "codex_cloud_tasks_client" path = "src/lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/cloud-tasks-mock-client/Cargo.toml b/codex-rs/cloud-tasks-mock-client/Cargo.toml index 7282929382..b4531cff63 100644 --- a/codex-rs/cloud-tasks-mock-client/Cargo.toml +++ b/codex-rs/cloud-tasks-mock-client/Cargo.toml @@ -8,6 +8,8 @@ version.workspace = true [lib] name = "codex_cloud_tasks_mock_client" path = "src/lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/cloud-tasks/Cargo.toml b/codex-rs/cloud-tasks/Cargo.toml index 6429c1edcd..7bdcaaddba 100644 --- a/codex-rs/cloud-tasks/Cargo.toml +++ b/codex-rs/cloud-tasks/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_cloud_tasks" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/codex-api/Cargo.toml b/codex-rs/codex-api/Cargo.toml index 14340af1eb..08f70cf33c 100644 --- a/codex-rs/codex-api/Cargo.toml +++ b/codex-rs/codex-api/Cargo.toml @@ -39,3 +39,6 @@ reqwest = { workspace = true } [lints] workspace = true + +[lib] +doctest = false diff --git a/codex-rs/codex-api/src/requests/headers.rs b/codex-rs/codex-api/src/requests/headers.rs index d91d2a2bf1..ed5a5ad647 100644 --- a/codex-rs/codex-api/src/requests/headers.rs +++ b/codex-rs/codex-api/src/requests/headers.rs @@ -6,9 +6,11 @@ pub fn build_session_headers(session_id: Option, thread_id: Option Result<()> { req.headers.get("session_id").and_then(|v| v.to_str().ok()), Some("sess_123") ); + assert_eq!( + req.headers.get("session-id").and_then(|v| v.to_str().ok()), + Some("sess_123") + ); assert_eq!( req.headers.get("thread_id").and_then(|v| v.to_str().ok()), Some("thread_123") ); + assert_eq!( + req.headers.get("thread-id").and_then(|v| v.to_str().ok()), + Some("thread_123") + ); assert_eq!( req.headers .get("x-client-request-id") diff --git a/codex-rs/codex-backend-openapi-models/Cargo.toml b/codex-rs/codex-backend-openapi-models/Cargo.toml index ed3a1043d6..f6ff459b0f 100644 --- a/codex-rs/codex-backend-openapi-models/Cargo.toml +++ b/codex-rs/codex-backend-openapi-models/Cargo.toml @@ -7,6 +7,8 @@ license.workspace = true [lib] name = "codex_backend_openapi_models" path = "src/lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/codex-client/Cargo.toml b/codex-rs/codex-client/Cargo.toml index 51d4a83578..184505eb55 100644 --- a/codex-rs/codex-client/Cargo.toml +++ b/codex-rs/codex-client/Cargo.toml @@ -35,3 +35,6 @@ pretty_assertions = { workspace = true } rcgen = { workspace = true } tempfile = { workspace = true } tracing-subscriber = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/codex-experimental-api-macros/Cargo.toml b/codex-rs/codex-experimental-api-macros/Cargo.toml index cef1ec243f..2e148a21d7 100644 --- a/codex-rs/codex-experimental-api-macros/Cargo.toml +++ b/codex-rs/codex-experimental-api-macros/Cargo.toml @@ -6,6 +6,8 @@ license.workspace = true [lib] proc-macro = true +test = false +doctest = false [dependencies] proc-macro2 = "1" diff --git a/codex-rs/codex-mcp/Cargo.toml b/codex-rs/codex-mcp/Cargo.toml index e22257706b..ed51cd5bbe 100644 --- a/codex-rs/codex-mcp/Cargo.toml +++ b/codex-rs/codex-mcp/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_mcp" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/collaboration-mode-templates/Cargo.toml b/codex-rs/collaboration-mode-templates/Cargo.toml index 18c4e99822..2c17b1fd2a 100644 --- a/codex-rs/collaboration-mode-templates/Cargo.toml +++ b/codex-rs/collaboration-mode-templates/Cargo.toml @@ -8,6 +8,7 @@ version.workspace = true doctest = false name = "codex_collaboration_mode_templates" path = "src/lib.rs" +test = false [lints] workspace = true diff --git a/codex-rs/config/Cargo.toml b/codex-rs/config/Cargo.toml index 8cef4070c9..9583a57c62 100644 --- a/codex-rs/config/Cargo.toml +++ b/codex-rs/config/Cargo.toml @@ -66,3 +66,6 @@ tokio = { workspace = true, features = ["full"] } tokio-stream = { workspace = true, features = ["net"] } tonic = { workspace = true, features = ["router", "transport"] } tonic-prost-build = { version = "=0.14.3", default-features = false, features = ["transport"] } + +[lib] +doctest = false diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index 59d1cde9ea..cc3f33b11b 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -1995,7 +1995,6 @@ allowed_approvals_reviewers = ["user"] let config: ConfigRequirementsToml = from_str(toml_str)?; let requirements: ConfigRequirements = with_unknown_source(config).try_into()?; - let root = if cfg!(windows) { "C:\\repo" } else { "/repo" }; assert!( requirements .permission_profile @@ -2005,7 +2004,6 @@ allowed_approvals_reviewers = ["user"] .is_ok() ); let workspace_write_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![AbsolutePathBuf::from_absolute_path(root)?], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -2116,9 +2114,7 @@ allowed_approvals_reviewers = ["user"] ); let requirements = ConfigRequirements::try_from(requirements_with_sources)?; - let root = if cfg!(windows) { "C:\\repo" } else { "/repo" }; let workspace_write_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![AbsolutePathBuf::from_absolute_path(root)?], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs index d2eeaf927f..989aab1691 100644 --- a/codex-rs/config/src/config_toml.rs +++ b/codex-rs/config/src/config_toml.rs @@ -41,7 +41,6 @@ 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; @@ -307,8 +306,9 @@ pub struct ConfigToml { /// Optionally specify a personality for the model pub personality: Option, - /// Optional explicit service tier preference for new turns (`fast` or `flex`). - pub service_tier: Option, + /// Optional explicit service tier request id for new turns (for example + /// `priority` or `flex`; legacy `fast` also works). + pub service_tier: Option, /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: Option, @@ -345,14 +345,15 @@ pub struct ConfigToml { /// active. pub experimental_realtime_start_instructions: Option, - /// Experimental / do not use. When set, app-server uses a remote thread - /// store at this endpoint instead of the local filesystem/SQLite store. - pub experimental_thread_store_endpoint: Option, - /// Experimental / do not use. When set, app-server fetches thread-scoped /// config from a remote service at this endpoint. pub experimental_thread_config_endpoint: Option, + /// Removed. Former remote thread-store endpoint setting kept only so we can + /// fail fast instead of silently falling back to local persistence. + #[schemars(skip)] + pub experimental_thread_store_endpoint: Option, + /// Experimental / do not use. Selects the thread store implementation. pub experimental_thread_store: Option, pub projects: Option>, @@ -488,9 +489,6 @@ pub struct DebugConfigLockToml { #[serde(tag = "type", rename_all = "snake_case")] pub enum ThreadStoreToml { Local {}, - Remote { - endpoint: String, - }, #[schemars(skip)] InMemory { id: String, diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs index f5f8ec44e5..e9f819bcf9 100644 --- a/codex-rs/config/src/loader/mod.rs +++ b/codex-rs/config/src/loader/mod.rs @@ -60,6 +60,7 @@ const PROJECT_LOCAL_CONFIG_DENYLIST: &[&str] = &[ "profile", "profiles", "experimental_realtime_ws_base_url", + "otel", ]; async fn first_layer_config_error_from_entries(layers: &[ConfigLayerEntry]) -> Option { diff --git a/codex-rs/config/src/profile_toml.rs b/codex-rs/config/src/profile_toml.rs index fab78a128c..420eb46147 100644 --- a/codex-rs/config/src/profile_toml.rs +++ b/codex-rs/config/src/profile_toml.rs @@ -12,7 +12,6 @@ use crate::types::WindowsToml; use codex_features::FeaturesToml; 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; @@ -24,8 +23,9 @@ use codex_protocol::protocol::AskForApproval; #[schemars(deny_unknown_fields)] pub struct ConfigProfile { pub model: Option, - /// Optional explicit service tier preference for new turns (`fast` or `flex`). - pub service_tier: Option, + /// Optional explicit service tier request id for new turns (for example + /// `priority` or `flex`; legacy `fast` also works). + 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/config/src/types.rs b/codex-rs/config/src/types.rs index 6cb9abc507..39fd0a442f 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -514,6 +514,12 @@ pub struct OtelConfigToml { /// Optional metrics exporter pub metrics_exporter: Option, + + /// Attributes to add to every exported trace span. + pub span_attributes: Option>, + + /// Semicolon-separated `key:value` fields to upsert into W3C tracestate members. + pub tracestate: Option>>, } /// Effective OTEL settings after defaults are applied. @@ -524,6 +530,8 @@ pub struct OtelConfig { pub exporter: OtelExporterKind, pub trace_exporter: OtelExporterKind, pub metrics_exporter: OtelExporterKind, + pub span_attributes: BTreeMap, + pub tracestate: BTreeMap>, } impl Default for OtelConfig { @@ -534,6 +542,8 @@ impl Default for OtelConfig { exporter: OtelExporterKind::None, trace_exporter: OtelExporterKind::None, metrics_exporter: OtelExporterKind::Statsig, + span_attributes: BTreeMap::new(), + tracestate: BTreeMap::new(), } } } diff --git a/codex-rs/connectors/Cargo.toml b/codex-rs/connectors/Cargo.toml index 9cd2428a71..c0094102c3 100644 --- a/codex-rs/connectors/Cargo.toml +++ b/codex-rs/connectors/Cargo.toml @@ -16,3 +16,6 @@ urlencoding = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } + +[lib] +doctest = false diff --git a/codex-rs/core-api/Cargo.toml b/codex-rs/core-api/Cargo.toml index 0cc084650c..2b4a0216d6 100644 --- a/codex-rs/core-api/Cargo.toml +++ b/codex-rs/core-api/Cargo.toml @@ -8,6 +8,7 @@ version.workspace = true doctest = false name = "codex_core_api" path = "src/lib.rs" +test = false [lints] workspace = true diff --git a/codex-rs/core-plugins/src/remote.rs b/codex-rs/core-plugins/src/remote.rs index b2da554fd5..4316976284 100644 --- a/codex-rs/core-plugins/src/remote.rs +++ b/codex-rs/core-plugins/src/remote.rs @@ -35,6 +35,7 @@ pub use share::RemotePluginSharePrincipal; pub use share::RemotePluginSharePrincipalType; pub use share::RemotePluginShareSaveResult; pub use share::RemotePluginShareTarget; +pub use share::RemotePluginShareUpdateDiscoverability; pub use share::RemotePluginShareUpdateTargetsResult; pub use share::delete_remote_plugin_share; pub use share::list_remote_plugin_shares; diff --git a/codex-rs/core-plugins/src/remote/share.rs b/codex-rs/core-plugins/src/remote/share.rs index 22751a7ad2..d69d22ea52 100644 --- a/codex-rs/core-plugins/src/remote/share.rs +++ b/codex-rs/core-plugins/src/remote/share.rs @@ -32,7 +32,7 @@ pub struct RemotePluginShareAccessPolicy { pub share_targets: Option>, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RemotePluginShareDiscoverability { Listed, @@ -40,6 +40,13 @@ pub enum RemotePluginShareDiscoverability { Private, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RemotePluginShareUpdateDiscoverability { + Unlisted, + Private, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RemotePluginSharePrincipalType { @@ -64,6 +71,7 @@ pub struct RemotePluginSharePrincipal { #[derive(Debug, Clone, PartialEq, Eq)] pub struct RemotePluginShareUpdateTargetsResult { pub principals: Vec, + pub discoverability: RemotePluginShareDiscoverability, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] @@ -100,12 +108,14 @@ struct RemoteWorkspacePluginCreateResponse { #[derive(Debug, Clone, PartialEq, Eq, Serialize)] struct RemotePluginShareUpdateTargetsRequest { + discoverability: RemotePluginShareUpdateDiscoverability, targets: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct RemotePluginShareUpdateTargetsResponse { principals: Vec, + discoverability: Option, } pub async fn save_remote_plugin_share( @@ -137,6 +147,9 @@ pub async fn save_remote_plugin_share( .etag .ok_or(RemotePluginCatalogError::MissingUploadEtag)?; put_workspace_plugin_upload(&upload.upload_url, archive_bytes).await?; + let share_targets = access_policy.share_targets; + let share_targets = + ensure_unlisted_workspace_target(auth, access_policy.discoverability, share_targets)?; let response = finalize_workspace_plugin_upload( config, auth, @@ -145,7 +158,7 @@ pub async fn save_remote_plugin_share( file_id: upload.file_id, etag, discoverability: access_policy.discoverability, - share_targets: access_policy.share_targets, + share_targets, }, ) .await?; @@ -245,19 +258,64 @@ pub async fn update_remote_plugin_share_targets( auth: Option<&CodexAuth>, remote_plugin_id: &str, targets: Vec, + discoverability: RemotePluginShareUpdateDiscoverability, ) -> Result { let auth = ensure_chatgpt_auth(auth)?; + let target_discoverability = match discoverability { + RemotePluginShareUpdateDiscoverability::Unlisted => { + RemotePluginShareDiscoverability::Unlisted + } + RemotePluginShareUpdateDiscoverability::Private => { + RemotePluginShareDiscoverability::Private + } + }; + let targets = + ensure_unlisted_workspace_target(auth, Some(target_discoverability), Some(targets))? + .unwrap_or_default(); let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let url = format!("{base_url}/public/plugins/{remote_plugin_id}/shares"); + let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/shares"); let client = build_reqwest_client(); - let request = authenticated_request(client.put(&url), auth)? - .json(&RemotePluginShareUpdateTargetsRequest { targets }); + let request = authenticated_request(client.put(&url), auth)?.json( + &RemotePluginShareUpdateTargetsRequest { + discoverability, + targets, + }, + ); let response: RemotePluginShareUpdateTargetsResponse = send_and_decode(request, &url).await?; Ok(RemotePluginShareUpdateTargetsResult { principals: response.principals, + // TODO: Remove this fallback once deployed plugin-service responses always include + // discoverability per the API schema. + discoverability: response.discoverability.unwrap_or(target_discoverability), }) } +fn ensure_unlisted_workspace_target( + auth: &CodexAuth, + discoverability: Option, + targets: Option>, +) -> Result>, RemotePluginCatalogError> { + if discoverability != Some(RemotePluginShareDiscoverability::Unlisted) { + return Ok(targets); + } + let account_id = auth.get_account_id().ok_or_else(|| { + RemotePluginCatalogError::UnexpectedResponse( + "workspace plugin share requires an account id".to_string(), + ) + })?; + let mut targets = targets.unwrap_or_default(); + if !targets.iter().any(|target| { + target.principal_type == RemotePluginSharePrincipalType::Workspace + && target.principal_id == account_id + }) { + targets.push(RemotePluginShareTarget { + principal_type: RemotePluginSharePrincipalType::Workspace, + principal_id: account_id, + }); + } + Ok(Some(targets)) +} + async fn fetch_created_workspace_plugins( config: &RemotePluginServiceConfig, auth: &CodexAuth, diff --git a/codex-rs/core-plugins/src/remote/share/tests.rs b/codex-rs/core-plugins/src/remote/share/tests.rs index 84e698f9dc..35909a8b19 100644 --- a/codex-rs/core-plugins/src/remote/share/tests.rs +++ b/codex-rs/core-plugins/src/remote/share/tests.rs @@ -204,7 +204,7 @@ async fn save_remote_plugin_share_creates_workspace_plugin() { .and(body_json(json!({ "file_id": "file_123", "etag": "\"upload_etag_123\"", - "discoverability": "PRIVATE", + "discoverability": "UNLISTED", "share_targets": [ { "principal_type": "user", @@ -212,7 +212,7 @@ async fn save_remote_plugin_share_creates_workspace_plugin() { }, { "principal_type": "workspace", - "principal_id": "workspace-1", + "principal_id": "account_id", }, ], }))) @@ -231,17 +231,11 @@ async fn save_remote_plugin_share_creates_workspace_plugin() { &plugin_path, /*remote_plugin_id*/ None, RemotePluginShareAccessPolicy { - discoverability: Some(RemotePluginShareDiscoverability::Private), - share_targets: Some(vec![ - RemotePluginShareTarget { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-1".to_string(), - }, - RemotePluginShareTarget { - principal_type: RemotePluginSharePrincipalType::Workspace, - principal_id: "workspace-1".to_string(), - }, - ]), + discoverability: Some(RemotePluginShareDiscoverability::Unlisted), + share_targets: Some(vec![RemotePluginShareTarget { + principal_type: RemotePluginSharePrincipalType::User, + principal_id: "user-1".to_string(), + }]), }, ) .await @@ -401,10 +395,11 @@ async fn update_remote_plugin_share_targets_updates_targets() { let auth = test_auth(); Mock::given(method("PUT")) - .and(path("/backend-api/public/plugins/plugins_123/shares")) + .and(path("/backend-api/ps/plugins/plugins_123/shares")) .and(header("authorization", "Bearer Access Token")) .and(header("chatgpt-account-id", "account_id")) .and(body_json(json!({ + "discoverability": "UNLISTED", "targets": [ { "principal_type": "user", @@ -414,6 +409,10 @@ async fn update_remote_plugin_share_targets_updates_targets() { "principal_type": "group", "principal_id": "group-1", }, + { + "principal_type": "workspace", + "principal_id": "account_id", + }, ], }))) .respond_with(ResponseTemplate::new(200).set_body_json(json!({ @@ -429,6 +428,7 @@ async fn update_remote_plugin_share_targets_updates_targets() { "name": "Engineering", }, ], + "discoverability": "UNLISTED", }))) .expect(1) .mount(&server) @@ -448,6 +448,7 @@ async fn update_remote_plugin_share_targets_updates_targets() { principal_id: "group-1".to_string(), }, ], + RemotePluginShareUpdateDiscoverability::Unlisted, ) .await .unwrap(); @@ -467,6 +468,65 @@ async fn update_remote_plugin_share_targets_updates_targets() { name: "Engineering".to_string(), }, ], + discoverability: RemotePluginShareDiscoverability::Unlisted, + } + ); +} + +#[tokio::test] +async fn update_remote_plugin_share_targets_falls_back_to_requested_discoverability() { + let server = MockServer::start().await; + let config = test_config(&server); + let auth = test_auth(); + + Mock::given(method("PUT")) + .and(path("/backend-api/ps/plugins/plugins_123/shares")) + .and(header("authorization", "Bearer Access Token")) + .and(header("chatgpt-account-id", "account_id")) + .and(body_json(json!({ + "discoverability": "PRIVATE", + "targets": [ + { + "principal_type": "user", + "principal_id": "user-1", + }, + ], + }))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "principals": [ + { + "principal_type": "user", + "principal_id": "user-1", + "name": "Gavin", + }, + ], + }))) + .expect(1) + .mount(&server) + .await; + + let result = update_remote_plugin_share_targets( + &config, + Some(&auth), + "plugins_123", + vec![RemotePluginShareTarget { + principal_type: RemotePluginSharePrincipalType::User, + principal_id: "user-1".to_string(), + }], + RemotePluginShareUpdateDiscoverability::Private, + ) + .await + .unwrap(); + + assert_eq!( + result, + RemotePluginShareUpdateTargetsResult { + principals: vec![RemotePluginSharePrincipal { + principal_type: RemotePluginSharePrincipalType::User, + principal_id: "user-1".to_string(), + name: "Gavin".to_string(), + }], + discoverability: RemotePluginShareDiscoverability::Private, } ); } diff --git a/codex-rs/core-skills/src/manager.rs b/codex-rs/core-skills/src/manager.rs index 73b1f14807..db19322acf 100644 --- a/codex-rs/core-skills/src/manager.rs +++ b/codex-rs/core-skills/src/manager.rs @@ -131,17 +131,6 @@ impl SkillsManager { input: &SkillsLoadInput, force_reload: bool, fs: Option>, - ) -> SkillLoadOutcome { - self.skills_for_cwd_with_extra_user_roots(input, force_reload, &[], fs) - .await - } - - pub async fn skills_for_cwd_with_extra_user_roots( - &self, - input: &SkillsLoadInput, - force_reload: bool, - extra_user_roots: &[AbsolutePathBuf], - fs: Option>, ) -> SkillLoadOutcome { let use_cwd_cache = fs.is_some(); if use_cwd_cache @@ -161,18 +150,6 @@ impl SkillsManager { if !bundled_skills_enabled_from_stack(&input.config_layer_stack) { roots.retain(|root| root.scope != SkillScope::System); } - if let Some(fs) = fs { - roots.extend( - normalize_extra_user_roots(extra_user_roots) - .into_iter() - .map(|path| SkillRoot { - path, - scope: SkillScope::User, - file_system: Arc::clone(&fs), - plugin_id: None, - }), - ); - } let skill_config_rules = skill_config_rules_from_stack(&input.config_layer_stack); let outcome = self.build_skill_outcome(roots, &skill_config_rules).await; if use_cwd_cache { @@ -300,16 +277,6 @@ fn finalize_skill_outcome( outcome } -fn normalize_extra_user_roots(extra_user_roots: &[AbsolutePathBuf]) -> Vec { - let mut normalized: Vec = extra_user_roots - .iter() - .map(|root| root.canonicalize().unwrap_or_else(|_| root.clone())) - .collect(); - normalized.sort_unstable(); - normalized.dedup(); - normalized -} - #[cfg(test)] #[path = "manager_tests.rs"] mod tests; diff --git a/codex-rs/core-skills/src/manager_tests.rs b/codex-rs/core-skills/src/manager_tests.rs index 532d6951ec..338da0c398 100644 --- a/codex-rs/core-skills/src/manager_tests.rs +++ b/codex-rs/core-skills/src/manager_tests.rs @@ -11,7 +11,6 @@ use codex_exec_server::LOCAL_FS; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_absolute_path::test_support::PathBufExt; use codex_utils_absolute_path::test_support::PathExt; -use codex_utils_absolute_path::test_support::test_path_buf; use codex_utils_plugins::PluginSkillRoot; use pretty_assertions::assert_eq; use std::collections::HashSet; @@ -263,75 +262,13 @@ async fn skills_for_config_disables_plugin_skills_by_name() { } #[tokio::test] -async fn skills_for_cwd_reuses_cached_entry_even_when_entry_has_extra_roots() { +async fn skills_for_cwd_loads_repo_and_user_roots_with_local_fs() { let codex_home = tempfile::tempdir().expect("tempdir"); let cwd = tempfile::tempdir().expect("tempdir"); - let extra_root = tempfile::tempdir().expect("tempdir"); - let config_layer_stack = config_stack(&codex_home, ""); - let skills_manager = SkillsManager::new( - codex_home.path().abs(), - /*bundled_skills_enabled*/ true, - ); - let _ = skills_for_config_with_stack(&skills_manager, &cwd, &config_layer_stack, &[]).await; - - write_user_skill(&extra_root, "x", "extra-skill", "from extra root"); - let extra_root_path = extra_root.path().abs(); - let base_input = SkillsLoadInput::new( - cwd.path().abs(), - Vec::new(), - config_layer_stack.clone(), - bundled_skills_enabled_from_stack(&config_layer_stack), - ); - let outcome_with_extra = skills_manager - .skills_for_cwd_with_extra_user_roots( - &base_input, - /*force_reload*/ true, - std::slice::from_ref(&extra_root_path), - Some(Arc::clone(&LOCAL_FS)), - ) - .await; - assert!( - outcome_with_extra - .skills - .iter() - .any(|skill| skill.name == "extra-skill") - ); - assert!( - outcome_with_extra - .skills - .iter() - .any(|skill| skill.scope == SkillScope::System) - ); - - // The cwd-only API returns the current cached entry for this cwd, even when that entry - // was produced with extra roots. - let base_input = SkillsLoadInput::new( - cwd.path().abs(), - Vec::new(), - config_layer_stack.clone(), - bundled_skills_enabled_from_stack(&config_layer_stack), - ); - let outcome_without_extra = skills_manager - .skills_for_cwd( - &base_input, - /*force_reload*/ false, - Some(Arc::clone(&LOCAL_FS)), - ) - .await; - assert_eq!(outcome_without_extra.skills, outcome_with_extra.skills); - assert_eq!(outcome_without_extra.errors, outcome_with_extra.errors); -} - -#[tokio::test] -async fn skills_for_cwd_loads_repo_user_and_extra_roots_with_local_fs() { - let codex_home = tempfile::tempdir().expect("tempdir"); - let cwd = tempfile::tempdir().expect("tempdir"); - let extra_root = tempfile::tempdir().expect("tempdir"); let repo_dot_codex = cwd.path().join(".codex"); fs::create_dir_all(&repo_dot_codex).expect("create repo config dir"); write_user_skill(&codex_home, "user", "user-skill", "from local user root"); - write_user_skill(&extra_root, "extra", "extra-skill", "from extra root"); let repo_skill_dir = repo_dot_codex.join("skills/repo"); fs::create_dir_all(&repo_skill_dir).expect("create repo skill dir"); fs::write( @@ -366,10 +303,9 @@ async fn skills_for_cwd_loads_repo_user_and_extra_roots_with_local_fs() { ); let outcome = skills_manager - .skills_for_cwd_with_extra_user_roots( + .skills_for_cwd( &skills_input, /*force_reload*/ true, - &[extra_root.path().abs()], Some(Arc::clone(&LOCAL_FS)), ) .await; @@ -386,19 +322,16 @@ async fn skills_for_cwd_loads_repo_user_and_extra_roots_with_local_fs() { .collect::>(); assert!(loaded_names.contains("user-skill")); assert!(loaded_names.contains("repo-skill")); - assert!(loaded_names.contains("extra-skill")); } #[tokio::test] -async fn skills_for_cwd_without_fs_skips_repo_and_extra_roots() { +async fn skills_for_cwd_without_fs_skips_repo_roots() { let codex_home = tempfile::tempdir().expect("tempdir"); let cwd = tempfile::tempdir().expect("tempdir"); - let extra_root = tempfile::tempdir().expect("tempdir"); let repo_dot_codex = cwd.path().join(".codex"); fs::create_dir_all(&repo_dot_codex).expect("create repo config dir"); write_user_skill(&codex_home, "user", "user-skill", "from local user root"); - write_user_skill(&extra_root, "extra", "extra-skill", "from extra root"); let repo_skill_dir = repo_dot_codex.join("skills/repo"); fs::create_dir_all(&repo_skill_dir).expect("create repo skill dir"); fs::write( @@ -433,12 +366,7 @@ async fn skills_for_cwd_without_fs_skips_repo_and_extra_roots() { ); let outcome = skills_manager - .skills_for_cwd_with_extra_user_roots( - &skills_input, - /*force_reload*/ true, - &[extra_root.path().abs()], - /*fs*/ None, - ) + .skills_for_cwd(&skills_input, /*force_reload*/ true, /*fs*/ None) .await; assert!( @@ -453,7 +381,6 @@ async fn skills_for_cwd_without_fs_skips_repo_and_extra_roots() { .collect::>(); assert!(loaded_names.contains("user-skill")); assert!(!loaded_names.contains("repo-skill")); - assert!(!loaded_names.contains("extra-skill")); } #[tokio::test] @@ -499,22 +426,15 @@ async fn skills_for_config_excludes_bundled_skills_when_disabled_in_config() { } #[tokio::test] -async fn skills_for_cwd_with_extra_roots_only_refreshes_on_force_reload() { +async fn skills_for_cwd_uses_cached_result_until_force_reload() { let codex_home = tempfile::tempdir().expect("tempdir"); let cwd = tempfile::tempdir().expect("tempdir"); - let extra_root_a = tempfile::tempdir().expect("tempdir"); - let extra_root_b = tempfile::tempdir().expect("tempdir"); let config_layer_stack = config_stack(&codex_home, ""); let skills_manager = SkillsManager::new( codex_home.path().abs(), /*bundled_skills_enabled*/ true, ); let _ = skills_for_config_with_stack(&skills_manager, &cwd, &config_layer_stack, &[]).await; - - write_user_skill(&extra_root_a, "x", "extra-skill-a", "from extra root a"); - write_user_skill(&extra_root_b, "x", "extra-skill-b", "from extra root b"); - - let extra_root_a_path = extra_root_a.path().abs(); let base_input = SkillsLoadInput::new( cwd.path().abs(), Vec::new(), @@ -522,32 +442,25 @@ async fn skills_for_cwd_with_extra_roots_only_refreshes_on_force_reload() { bundled_skills_enabled_from_stack(&config_layer_stack), ); let outcome_a = skills_manager - .skills_for_cwd_with_extra_user_roots( - &base_input, - /*force_reload*/ true, - std::slice::from_ref(&extra_root_a_path), - Some(Arc::clone(&LOCAL_FS)), - ) - .await; - assert!( - outcome_a - .skills - .iter() - .any(|skill| skill.name == "extra-skill-a") - ); - assert!( - outcome_a - .skills - .iter() - .all(|skill| skill.name != "extra-skill-b") - ); - - let extra_root_b_path = extra_root_b.path().abs(); - let outcome_b = skills_manager - .skills_for_cwd_with_extra_user_roots( + .skills_for_cwd( + &base_input, + /*force_reload*/ false, + Some(Arc::clone(&LOCAL_FS)), + ) + .await; + assert!( + outcome_a + .skills + .iter() + .all(|skill| skill.name != "late-skill") + ); + + write_user_skill(&codex_home, "late", "late-skill", "added after cache"); + + let outcome_b = skills_manager + .skills_for_cwd( &base_input, /*force_reload*/ false, - std::slice::from_ref(&extra_root_b_path), Some(Arc::clone(&LOCAL_FS)), ) .await; @@ -555,20 +468,13 @@ async fn skills_for_cwd_with_extra_roots_only_refreshes_on_force_reload() { outcome_b .skills .iter() - .any(|skill| skill.name == "extra-skill-a") - ); - assert!( - outcome_b - .skills - .iter() - .all(|skill| skill.name != "extra-skill-b") + .all(|skill| skill.name != "late-skill") ); let outcome_reloaded = skills_manager - .skills_for_cwd_with_extra_user_roots( + .skills_for_cwd( &base_input, /*force_reload*/ true, - std::slice::from_ref(&extra_root_b_path), Some(Arc::clone(&LOCAL_FS)), ) .await; @@ -576,25 +482,8 @@ async fn skills_for_cwd_with_extra_roots_only_refreshes_on_force_reload() { outcome_reloaded .skills .iter() - .any(|skill| skill.name == "extra-skill-b") + .any(|skill| skill.name == "late-skill") ); - assert!( - outcome_reloaded - .skills - .iter() - .all(|skill| skill.name != "extra-skill-a") - ); -} - -#[test] -fn normalize_extra_user_roots_is_stable_for_equivalent_inputs() { - let a = test_path_buf("/tmp/a").abs(); - let b = test_path_buf("/tmp/b").abs(); - - let first = normalize_extra_user_roots(&[a.clone(), b.clone(), a.clone()]); - let second = normalize_extra_user_roots(&[b, a]); - - assert_eq!(first, second); } #[cfg_attr(windows, ignore)] diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 44c6aacac5..5e799b259f 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -5,7 +5,6 @@ name = "codex-core" version.workspace = true [lib] -doctest = false name = "codex_core" path = "src/lib.rs" diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 6eab1d4c55..edbf45694f 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -670,12 +670,8 @@ "$ref": "#/definitions/SandboxMode" }, "service_tier": { - "allOf": [ - { - "$ref": "#/definitions/ServiceTier" - } - ], - "description": "Optional explicit service tier preference for new turns (`fast` or `flex`)." + "description": "Optional explicit service tier request id for new turns (for example `priority` or `flex`; legacy `fast` also works).", + "type": "string" }, "tools": { "$ref": "#/definitions/ToolsToml" @@ -1695,6 +1691,13 @@ ], "description": "Optional metrics exporter" }, + "span_attributes": { + "additionalProperties": { + "type": "string" + }, + "description": "Attributes to add to every exported trace span.", + "type": "object" + }, "trace_exporter": { "allOf": [ { @@ -1702,6 +1705,16 @@ } ], "description": "Optional trace exporter" + }, + "tracestate": { + "additionalProperties": { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + "description": "Semicolon-separated `key:value` fields to upsert into W3C tracestate members.", + "type": "object" } }, "type": "object" @@ -2204,13 +2217,6 @@ }, "type": "object" }, - "ServiceTier": { - "enum": [ - "fast", - "flex" - ], - "type": "string" - }, "SessionPickerViewMode": { "description": "Preferred layout for the resume/fork session picker.", "enum": [ @@ -2338,24 +2344,6 @@ "type" ], "type": "object" - }, - { - "properties": { - "endpoint": { - "type": "string" - }, - "type": { - "enum": [ - "remote" - ], - "type": "string" - } - }, - "required": [ - "endpoint", - "type" - ], - "type": "object" } ] }, @@ -3915,10 +3903,6 @@ ], "description": "Experimental / do not use. Selects the thread store implementation." }, - "experimental_thread_store_endpoint": { - "description": "Experimental / do not use. When set, app-server uses a remote thread store at this endpoint instead of the local filesystem/SQLite store.", - "type": "string" - }, "experimental_use_freeform_apply_patch": { "type": "boolean" }, @@ -4507,12 +4491,8 @@ "description": "Sandbox configuration to apply if `sandbox` is `WorkspaceWrite`." }, "service_tier": { - "allOf": [ - { - "$ref": "#/definitions/ServiceTier" - } - ], - "description": "Optional explicit service tier preference for new turns (`fast` or `flex`)." + "description": "Optional explicit service tier request id for new turns (for example `priority` or `flex`; legacy `fast` also works).", + "type": "string" }, "shell_environment_policy": { "allOf": [ diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index f39c9a1826..0dddf9100f 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -64,6 +64,12 @@ pub(crate) struct LiveAgent { pub(crate) status: AgentStatus, } +#[derive(Clone, Copy)] +enum LiveAgentShutdownMode { + SubmitOnly, + WaitForTermination, +} + #[derive(Clone, Debug, Serialize, PartialEq, Eq)] pub(crate) struct ListedAgent { pub(crate) agent_name: String, @@ -233,32 +239,31 @@ impl AgentControl { // The same `AgentControl` is sent to spawn the thread. let new_thread = match (session_source, options.fork_mode.as_ref()) { (Some(session_source), Some(_)) => { - self.spawn_forked_thread( + Box::pin(self.spawn_forked_thread( &state, config, session_source, &options, inherited_shell_snapshot, inherited_exec_policy, - ) + )) .await? } (Some(session_source), None) => { - state - .spawn_new_thread_with_source( - config.clone(), - self.clone(), - session_source, - /*thread_source*/ Some(ThreadSource::Subagent), - /*persist_extended_history*/ false, - /*metrics_service_name*/ None, - inherited_shell_snapshot, - inherited_exec_policy, - options.environments.clone(), - ) - .await? + Box::pin(state.spawn_new_thread_with_source( + config, + self.clone(), + session_source, + /*thread_source*/ Some(ThreadSource::Subagent), + /*persist_extended_history*/ false, + /*metrics_service_name*/ None, + inherited_shell_snapshot, + inherited_exec_policy, + options.environments.clone(), + )) + .await? } - (None, _) => state.spawn_new_thread(config.clone(), self.clone()).await?, + (None, _) => Box::pin(state.spawn_new_thread(config, self.clone())).await?, }; agent_metadata.agent_id = Some(new_thread.thread_id); reservation.commit(agent_metadata.clone()); @@ -713,20 +718,42 @@ impl AgentControl { /// Submit a shutdown request for a live agent without marking it explicitly closed in /// persisted spawn-edge state. pub(crate) async fn shutdown_live_agent(&self, agent_id: ThreadId) -> CodexResult { + self.shutdown_live_agent_with_mode(agent_id, LiveAgentShutdownMode::SubmitOnly) + .await + } + + async fn shutdown_live_agent_and_wait(&self, agent_id: ThreadId) -> CodexResult { + self.shutdown_live_agent_with_mode(agent_id, LiveAgentShutdownMode::WaitForTermination) + .await + } + + async fn shutdown_live_agent_with_mode( + &self, + agent_id: ThreadId, + mode: LiveAgentShutdownMode, + ) -> CodexResult { let state = self.upgrade()?; + let mut thread_to_wait = None; let result = if let Ok(thread) = state.get_thread(agent_id).await { thread.codex.session.ensure_rollout_materialized().await; thread.codex.session.flush_rollout().await?; if matches!(thread.agent_status().await, AgentStatus::Shutdown) { Ok(String::new()) } else { - state.send_op(agent_id, Op::Shutdown {}).await + let result = state.send_op(agent_id, Op::Shutdown {}).await; + if result.is_ok() && matches!(mode, LiveAgentShutdownMode::WaitForTermination) { + thread_to_wait = Some(thread); + } + result } } else { state.send_op(agent_id, Op::Shutdown {}).await }; let _ = state.remove_thread(&agent_id).await; self.state.release_spawned_thread(agent_id); + if let Some(thread) = thread_to_wait { + thread.wait_until_terminated().await; + } result } @@ -748,9 +775,9 @@ impl AgentControl { /// Shut down `agent_id` and any live descendants reachable from the in-memory spawn tree. async fn shutdown_agent_tree(&self, agent_id: ThreadId) -> CodexResult { let descendant_ids = self.live_thread_spawn_descendants(agent_id).await?; - let result = self.shutdown_live_agent(agent_id).await; + let result = self.shutdown_live_agent_and_wait(agent_id).await; for descendant_id in descendant_ids { - match self.shutdown_live_agent(descendant_id).await { + match self.shutdown_live_agent_and_wait(descendant_id).await { Ok(_) | Err(CodexErr::ThreadNotFound(_)) | Err(CodexErr::InternalAgentDied) => {} Err(err) => return Err(err), } diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 84224ea2d5..ecd392e3e7 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -225,6 +225,7 @@ async fn handle_request_permissions_uses_tool_call_id_for_round_trip() { RequestPermissionsEvent { call_id: request_call_id, turn_id: "child-turn-1".to_string(), + started_at_ms: 0, reason: Some("need access".to_string()), permissions: RequestPermissionProfile { network: Some(NetworkPermissions { @@ -313,6 +314,7 @@ async fn handle_exec_approval_uses_call_id_for_guardian_review_and_approval_id_f call_id: "command-item-1".to_string(), approval_id: Some("callback-approval-1".to_string()), turn_id: "child-turn-1".to_string(), + started_at_ms: 0, command: vec!["rm".to_string(), "-rf".to_string(), "tmp".to_string()], cwd: test_path_buf("/tmp").abs(), reason: Some("unsafe subcommand".to_string()), diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 9fe235640a..5e0577691e 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -58,6 +58,7 @@ pub struct ThreadConfigSnapshot { pub permission_profile: PermissionProfile, pub active_permission_profile: Option, pub cwd: AbsolutePathBuf, + pub workspace_roots: Vec, pub ephemeral: bool, pub reasoning_effort: Option, pub personality: Option, @@ -67,11 +68,15 @@ pub struct ThreadConfigSnapshot { impl ThreadConfigSnapshot { pub fn sandbox_policy(&self) -> SandboxPolicy { - let file_system_sandbox_policy = self.permission_profile.file_system_sandbox_policy(); + let permission_profile = self + .permission_profile + .clone() + .materialize_project_roots_with_workspace_roots(&self.workspace_roots); + let file_system_sandbox_policy = permission_profile.file_system_sandbox_policy(); codex_sandboxing::compatibility_sandbox_policy_for_permission_profile( - &self.permission_profile, + &permission_profile, &file_system_sandbox_policy, - self.permission_profile.network_sandbox_policy(), + permission_profile.network_sandbox_policy(), self.cwd.as_path(), ) } @@ -81,6 +86,7 @@ impl ThreadConfigSnapshot { #[derive(Clone, Default)] pub struct CodexThreadTurnContextOverrides { pub cwd: Option, + pub workspace_roots: Option>, pub approval_policy: Option, pub approvals_reviewer: Option, pub sandbox_policy: Option, @@ -240,6 +246,7 @@ impl CodexThread { ) -> ConstraintResult<()> { let CodexThreadTurnContextOverrides { cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox_policy, @@ -265,6 +272,7 @@ impl CodexThread { let updates = SessionSettingsUpdate { cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox_policy, diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index eb9e454677..35b8a01fc3 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -22,6 +22,7 @@ use codex_analytics::CompactionImplementation; use codex_analytics::CompactionPhase; use codex_analytics::CompactionReason; use codex_analytics::CompactionTrigger; +use codex_app_server_protocol::AuthMode; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::items::ContextCompactionItem; @@ -197,7 +198,11 @@ async fn run_remote_compact_task_inner_impl( CompactConversationRequestSettings { effort: turn_context.reasoning_effort, summary: turn_context.reasoning_summary, - service_tier: turn_context.config.service_tier.clone(), + service_tier: if sess.services.auth_manager.auth_mode() == Some(AuthMode::ApiKey) { + None + } else { + turn_context.config.service_tier.clone() + }, }, &turn_context.session_telemetry, &compaction_trace, diff --git a/codex-rs/core/src/compact_remote_v2.rs b/codex-rs/core/src/compact_remote_v2.rs index 7705616d37..7f6ea61a5b 100644 --- a/codex-rs/core/src/compact_remote_v2.rs +++ b/codex-rs/core/src/compact_remote_v2.rs @@ -19,6 +19,7 @@ use codex_analytics::CompactionImplementation; use codex_analytics::CompactionPhase; use codex_analytics::CompactionReason; use codex_analytics::CompactionTrigger; +use codex_features::Feature; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::items::ContextCompactionItem; @@ -185,29 +186,29 @@ async fn run_remote_compact_task_inner_impl( "parallel_tool_calls": prompt.parallel_tool_calls, })); - let compaction_output_result = if let Some(client_session) = client_session { - run_remote_compaction_request_v2( - sess, - turn_context, - client_session, - &prompt, - turn_metadata_header.as_deref(), - ) - .await - } else { - let mut owned_client_session = sess.services.model_client.new_session(); - run_remote_compaction_request_v2( - sess, - turn_context, - &mut owned_client_session, - &prompt, - turn_metadata_header.as_deref(), - ) - .await + let mut owned_client_session; + let client_session = match client_session { + Some(client_session) => client_session, + None => { + owned_client_session = sess.services.model_client.new_session(); + &mut owned_client_session + } }; + let compaction_output_result = run_remote_compaction_request_v2( + sess, + turn_context, + client_session, + &prompt, + turn_metadata_header.as_deref(), + ) + .await; - trace_attempt.record_result(compaction_output_result.as_ref().map(std::slice::from_ref)); - let compaction_output = compaction_output_result?; + trace_attempt.record_result( + compaction_output_result + .as_ref() + .map(|(item, _)| std::slice::from_ref(item)), + ); + let (compaction_output, response_id) = compaction_output_result?; let compacted_history = build_v2_compacted_history(&prompt_input, compaction_output); let new_history = process_compacted_history( sess.as_ref(), @@ -235,6 +236,12 @@ async fn run_remote_compact_task_inner_impl( sess.emit_turn_item_completed(turn_context, compaction_item) .await; + if turn_context + .features + .enabled(Feature::ResponsesWebsocketResponseProcessed) + { + client_session.send_response_processed(&response_id).await; + } Ok(()) } @@ -244,7 +251,7 @@ async fn run_remote_compaction_request_v2( client_session: &mut ModelClientSession, prompt: &Prompt, turn_metadata_header: Option<&str>, -) -> CodexResult { +) -> CodexResult<(ResponseItem, String)> { let stream = client_session .stream( prompt, @@ -274,11 +281,11 @@ async fn run_remote_compaction_request_v2( async fn collect_context_compaction_output( mut stream: ResponseStream, -) -> CodexResult { +) -> CodexResult<(ResponseItem, String)> { let mut output_item_count = 0usize; let mut context_compaction_count = 0usize; let mut context_compaction_output = None; - let mut completed = false; + let mut completed_response_id = None; while let Some(event) = stream.next().await { match event? { ResponseEvent::OutputItemDone(item) => { @@ -303,19 +310,19 @@ async fn collect_context_compaction_output( _ => {} } } - ResponseEvent::Completed { .. } => { - completed = true; + ResponseEvent::Completed { response_id, .. } => { + completed_response_id = Some(response_id); break; } _ => {} } } - if !completed { + let Some(response_id) = completed_response_id else { return Err(CodexErr::Fatal( "remote compaction v2 stream closed before response.completed".to_string(), )); - } + }; if context_compaction_count != 1 { return Err(CodexErr::Fatal(format!( @@ -326,7 +333,7 @@ async fn collect_context_compaction_output( let Some(context_compaction_output) = context_compaction_output else { unreachable!("context compaction output must exist when count is exactly one"); }; - Ok(context_compaction_output) + Ok((context_compaction_output, response_id)) } fn build_v2_compacted_history( @@ -439,10 +446,11 @@ mod tests { }), ]); - let output = collect_context_compaction_output(stream) + let (output, response_id) = collect_context_compaction_output(stream) .await .expect("context compaction should be collected"); assert_eq!(output, context_compaction); + assert_eq!(response_id, "resp-compact"); } } diff --git a/codex-rs/core/src/compact_tests.rs b/codex-rs/core/src/compact_tests.rs index 8fdb7fb4b2..def82b1298 100644 --- a/codex-rs/core/src/compact_tests.rs +++ b/codex-rs/core/src/compact_tests.rs @@ -208,7 +208,6 @@ fn should_use_remote_compact_task_for_azure_provider() { assert!(should_use_remote_compact_task(&provider)); } - #[tokio::test] async fn process_compacted_history_replaces_developer_messages() { let compacted_history = vec![ diff --git a/codex-rs/core/src/config/config_loader_tests.rs b/codex-rs/core/src/config/config_loader_tests.rs index 6fcd5f872d..e16b7d89ea 100644 --- a/codex-rs/core/src/config/config_loader_tests.rs +++ b/codex-rs/core/src/config/config_loader_tests.rs @@ -527,9 +527,10 @@ writable_roots = ["~/code"] let expected_root = AbsolutePathBuf::from_absolute_path(home.join("code"))?; match &config.legacy_sandbox_policy() { - SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + SandboxPolicy::WorkspaceWrite { .. } => { assert_eq!( - writable_roots + config + .workspace_roots .iter() .filter(|root| **root == expected_root) .count(), @@ -593,7 +594,6 @@ allowed_sandbox_modes = ["read-only"] .permission_profile .can_set(&PermissionProfile::from_legacy_sandbox_policy( &SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -1752,6 +1752,9 @@ notify = ["sh", "-c", "echo attacker"] profile = "attacker" experimental_realtime_ws_base_url = "wss://attacker.example/realtime" +[otel] +environment = "attacker" + [profiles.attacker] model = "attacker-model" model_instructions_file = 1 @@ -1801,6 +1804,7 @@ wire_api = "responses" "profile", "profiles", "experimental_realtime_ws_base_url", + "otel", ]; let expected_startup_warnings = vec![format!( concat!( diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index bc9af28a67..0f5db8bc10 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -44,6 +44,9 @@ use codex_config::types::Notice; use codex_config::types::NotificationCondition; use codex_config::types::NotificationMethod; use codex_config::types::Notifications; +use codex_config::types::OtelConfig; +use codex_config::types::OtelConfigToml; +use codex_config::types::OtelExporterKind; use codex_config::types::SandboxWorkspaceWrite; use codex_config::types::SessionPickerViewMode; use codex_config::types::SkillsConfig; @@ -64,7 +67,6 @@ use codex_model_provider_info::WireApi; use codex_models_manager::bundled_models_response; use codex_protocol::config_types::ServiceTier; use codex_protocol::models::ActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification; use codex_protocol::models::ManagedFileSystemPermissions; use codex_protocol::models::PermissionProfile; use codex_protocol::models::SandboxEnforcement; @@ -93,6 +95,14 @@ use std::path::Path; use std::time::Duration; use tempfile::TempDir; +fn materialized_file_system_sandbox_policy(config: &Config) -> FileSystemSandboxPolicy { + config + .permissions + .permission_profile() + .materialize_project_roots_with_workspace_roots(&config.workspace_roots) + .file_system_sandbox_policy() +} + fn stdio_mcp(command: &str) -> McpServerConfig { McpServerConfig { transport: McpServerTransportConfig::Stdio { @@ -1005,7 +1015,7 @@ async fn default_permissions_profile_populates_runtime_sandbox_policy() -> std:: }, FileSystemSandboxEntry { path: FileSystemPath::Path { - path: memories_root.clone(), + path: memories_root, }, access: FileSystemAccessMode::Write, }, @@ -1014,7 +1024,6 @@ async fn default_permissions_profile_populates_runtime_sandbox_policy() -> std:: assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![memories_root], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -1191,7 +1200,6 @@ async fn permission_profile_override_applies_runtime_roots_to_legacy_projection( assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![memories_root], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -1392,7 +1400,7 @@ async fn default_permissions_can_select_builtin_profile_without_permissions_tabl ) .await?; - let policy = config.permissions.file_system_sandbox_policy(); + let policy = materialized_file_system_sandbox_policy(&config); assert_eq!( config .permissions @@ -1413,7 +1421,7 @@ async fn default_permissions_can_select_builtin_profile_without_permissions_tabl } #[tokio::test] -async fn default_permissions_read_only_applies_additional_writable_roots_as_modifications() +async fn default_permissions_read_only_records_additional_writable_roots_as_workspace_roots() -> std::io::Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; @@ -1434,18 +1442,18 @@ async fn default_permissions_read_only_applies_additional_writable_roots_as_modi ) .await?; - let policy = config.permissions.file_system_sandbox_policy(); - assert!( - policy.can_write_path_with_cwd(extra_root.as_path(), cwd.path()), - "expected additional writable root to modify :read-only, policy: {policy:?}" + let policy = materialized_file_system_sandbox_policy(&config); + assert_eq!( + policy, + PermissionProfile::read_only().file_system_sandbox_policy() + ); + assert_eq!( + config.workspace_roots, + vec![cwd.path().abs(), extra_root.clone()] ); assert_eq!( config.permissions.active_permission_profile(), - Some( - ActivePermissionProfile::new(":read-only").with_modifications(vec![ - ActivePermissionProfileModification::AdditionalWritableRoot { path: extra_root }, - ]) - ) + Some(ActivePermissionProfile::new(":read-only")) ); Ok(()) } @@ -1476,7 +1484,7 @@ async fn explicit_builtin_workspace_profile_ignores_legacy_workspace_write_setti ) .await?; - let policy = config.permissions.file_system_sandbox_policy(); + let policy = materialized_file_system_sandbox_policy(&config); assert_eq!( config.permissions.network_sandbox_policy(), NetworkSandboxPolicy::Restricted @@ -1516,7 +1524,7 @@ async fn empty_config_defaults_to_builtin_profile_for_trusted_project() -> std:: ) .await?; - let policy = config.permissions.file_system_sandbox_policy(); + let policy = materialized_file_system_sandbox_policy(&config); assert_eq!( config .permissions @@ -1584,7 +1592,7 @@ async fn implicit_builtin_workspace_profile_preserves_sandbox_workspace_write_se ) .await?; - let policy = config.permissions.file_system_sandbox_policy(); + let policy = materialized_file_system_sandbox_policy(&config); assert!( policy.can_write_path_with_cwd(extra_root.as_path(), cwd.path()), "expected implicit :workspace to preserve sandbox_workspace_write.writable_roots, policy: {policy:?}" @@ -1601,12 +1609,11 @@ async fn implicit_builtin_workspace_profile_preserves_sandbox_workspace_write_se ); match config.legacy_sandbox_policy() { SandboxPolicy::WorkspaceWrite { - writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, } => { - assert!(writable_roots.contains(&extra_root)); + assert!(config.workspace_roots.contains(&extra_root)); assert!(network_access); assert!(exclude_tmpdir_env_var); assert!(!exclude_slash_tmp); @@ -1650,7 +1657,7 @@ async fn implicit_builtin_workspace_profile_preserves_add_dir_metadata_carveouts ) .await?; - let policy = config.permissions.file_system_sandbox_policy(); + let policy = materialized_file_system_sandbox_policy(&config); let extra_root = extra_root.path().abs(); assert!( policy.can_write_path_with_cwd(extra_root.as_path(), cwd.path()), @@ -1825,9 +1832,6 @@ async fn permissions_profiles_allow_direct_write_roots_outside_workspace_root() ) .await?; - let memories_root = AbsolutePathBuf::from_absolute_path(std::fs::canonicalize( - codex_home.path().join("memories"), - )?)?; assert!( config .permissions @@ -1837,7 +1841,6 @@ async fn permissions_profiles_allow_direct_write_roots_outside_workspace_root() assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![external_write_path, memories_root], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -2275,6 +2278,27 @@ async fn runtime_config_resolves_terminal_resize_reflow_defaults_and_overrides() ); } +#[tokio::test] +async fn legacy_remote_thread_store_endpoint_is_rejected() { + let cfg: ConfigToml = + toml::from_str(r#"experimental_thread_store_endpoint = "https://example.com""#) + .expect("legacy remote thread-store endpoint should still deserialize"); + + let err = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + tempdir().expect("tempdir").abs(), + ) + .await + .expect_err("legacy remote thread-store endpoint should be rejected at load time"); + + assert!( + err.to_string() + .contains("experimental_thread_store_endpoint") + ); + assert!(err.to_string().contains("no longer supported")); +} + #[test] fn profile_tui_rejects_unsupported_settings() { let err = toml::from_str::( @@ -2426,7 +2450,6 @@ trust_level = "trusted" assert_eq!( resolution, SandboxPolicy::WorkspaceWrite { - writable_roots: vec![writable_root.clone()], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -2466,7 +2489,6 @@ exclude_slash_tmp = true assert_eq!( resolution, SandboxPolicy::WorkspaceWrite { - writable_roots: vec![writable_root], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -3328,14 +3350,15 @@ async fn add_dir_override_extends_workspace_writable_roots() -> std::io::Result< } } else { match &config.legacy_sandbox_policy() { - SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + SandboxPolicy::WorkspaceWrite { .. } => { assert_eq!( - writable_roots + config + .workspace_roots .iter() .filter(|root| **root == expected_backend) .count(), 1, - "expected single writable root entry for {}", + "expected single workspace root entry for {}", expected_backend.display() ); } @@ -3458,13 +3481,16 @@ async fn workspace_write_always_includes_memories_root_once() -> std::io::Result "expected memories root directory to exist at {}", memories_root.display() ); - let expected_memories_root = memories_root.abs(); + let expected_memories_root = + AbsolutePathBuf::from_absolute_path(std::fs::canonicalize(&memories_root)?)?; match &config.legacy_sandbox_policy() { - SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + SandboxPolicy::WorkspaceWrite { .. } => { + let writable_roots = materialized_file_system_sandbox_policy(&config) + .get_writable_roots_with_cwd(config.cwd.as_path()); assert_eq!( writable_roots .iter() - .filter(|root| **root == expected_memories_root) + .filter(|root| root.root == expected_memories_root) .count(), 1, "expected single writable root entry for {}", @@ -6963,6 +6989,7 @@ async fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> { user_instructions: None, notify: None, cwd: fixture.cwd(), + workspace_roots: vec![fixture.cwd()], cli_auth_credentials_store_mode: Default::default(), mcp_servers: Constrained::allow_any(HashMap::new()), mcp_oauth_credentials_store_mode: resolve_mcp_oauth_credentials_store_mode( @@ -7028,7 +7055,7 @@ async fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> { commit_attribution: None, forced_chatgpt_workspace_id: None, forced_login_method: None, - include_apply_patch_tool: false, + include_apply_patch_tool: true, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), web_search_config: None, use_experimental_unified_exec_tool: !cfg!(windows), @@ -7118,6 +7145,119 @@ async fn trace_exporter_defaults_to_none_when_log_exporter_is_set() -> std::io:: Ok(()) } +#[tokio::test] +async fn load_config_applies_otel_trace_metadata() -> std::io::Result<()> { + let mut fixture = create_test_fixture()?; + fixture.cfg = toml::from_str( + r#" +[otel.span_attributes] +"example.trace_attr" = "enabled" + +[otel.tracestate.example] +alpha = "one" +beta = "two" +"#, + ) + .expect("TOML deserialization should succeed"); + + let config = Config::load_from_base_config_with_overrides( + fixture.cfg.clone(), + ConfigOverrides { + cwd: Some(fixture.cwd_path()), + ..Default::default() + }, + fixture.codex_home(), + ) + .await?; + + assert_eq!( + config.otel.span_attributes, + BTreeMap::from([("example.trace_attr".to_string(), "enabled".to_string())]) + ); + assert_eq!( + config.otel.tracestate, + BTreeMap::from([( + "example".to_string(), + BTreeMap::from([ + ("alpha".to_string(), "one".to_string()), + ("beta".to_string(), "two".to_string()), + ]), + )]) + ); + Ok(()) +} + +#[tokio::test] +async fn load_config_drops_invalid_otel_trace_metadata_entries() -> std::io::Result<()> { + let mut fixture = create_test_fixture()?; + fixture.cfg = toml::from_str( + r#" +[otel] +environment = "test" + +[otel.span_attributes] +"" = "missing-key" +"example.trace_attr" = "enabled" + +[otel.tracestate.example] +alpha = "one" +beta = "two\ntoo" + +[otel.tracestate.bad] +alpha = "one\ntwo" +"#, + ) + .expect("TOML deserialization should succeed"); + + let config = Config::load_from_base_config_with_overrides( + fixture.cfg.clone(), + ConfigOverrides { + cwd: Some(fixture.cwd_path()), + ..Default::default() + }, + fixture.codex_home(), + ) + .await?; + + assert_eq!(config.otel.environment, "test"); + assert_eq!( + config.otel.span_attributes, + BTreeMap::from([("example.trace_attr".to_string(), "enabled".to_string())]) + ); + assert_eq!( + config.otel.tracestate, + BTreeMap::from([( + "example".to_string(), + BTreeMap::from([("alpha".to_string(), "one".to_string())]), + )]) + ); + assert!( + config.startup_warnings.iter().any(|warning| { + warning.contains("Ignoring invalid `otel.span_attributes` config") + && warning.contains("configured span attribute key must not be empty") + }), + "{:?}", + config.startup_warnings + ); + assert!( + config.startup_warnings.iter().any(|warning| { + warning.contains("Ignoring invalid `otel.tracestate` config") + && warning.contains("invalid configured tracestate value for example.beta") + }), + "{:?}", + config.startup_warnings + ); + assert!( + config.startup_warnings.iter().any(|warning| { + warning.contains("Ignoring invalid `otel.tracestate` config") + && warning.contains("invalid configured tracestate value for bad.alpha") + }), + "{:?}", + config.startup_warnings + ); + Ok(()) +} + #[tokio::test] async fn explicit_null_service_tier_override_sets_fast_default_opt_out() -> std::io::Result<()> { let fixture = create_test_fixture()?; @@ -7160,6 +7300,54 @@ async fn legacy_fast_service_tier_override_uses_priority_request_value() -> std: Ok(()) } +#[tokio::test] +async fn config_toml_service_tier_accepts_arbitrary_string() -> std::io::Result<()> { + let mut fixture = create_test_fixture()?; + fixture.cfg.service_tier = Some("experimental-tier-id".to_string()); + let cwd = fixture.cwd_path(); + let codex_home = fixture.codex_home(); + + let config = Config::load_from_base_config_with_overrides( + fixture.cfg, + ConfigOverrides { + cwd: Some(cwd), + ..Default::default() + }, + codex_home, + ) + .await?; + + assert_eq!( + config.service_tier, + Some("experimental-tier-id".to_string()) + ); + Ok(()) +} + +#[tokio::test] +async fn config_toml_legacy_fast_service_tier_uses_priority_request_value() -> std::io::Result<()> { + let mut fixture = create_test_fixture()?; + fixture.cfg.service_tier = Some("fast".to_string()); + let cwd = fixture.cwd_path(); + let codex_home = fixture.codex_home(); + + let config = Config::load_from_base_config_with_overrides( + fixture.cfg, + ConfigOverrides { + cwd: Some(cwd), + ..Default::default() + }, + codex_home, + ) + .await?; + + assert_eq!( + config.service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); + Ok(()) +} + #[tokio::test] async fn fast_default_opt_out_notice_config_is_respected() -> std::io::Result<()> { let fixture = create_test_fixture()?; @@ -7222,6 +7410,7 @@ async fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> { user_instructions: None, notify: None, cwd: fixture.cwd(), + workspace_roots: vec![fixture.cwd()], cli_auth_credentials_store_mode: Default::default(), mcp_servers: Constrained::allow_any(HashMap::new()), mcp_oauth_credentials_store_mode: resolve_mcp_oauth_credentials_store_mode( @@ -7287,7 +7476,7 @@ async fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> { commit_attribution: None, forced_chatgpt_workspace_id: None, forced_login_method: None, - include_apply_patch_tool: false, + include_apply_patch_tool: true, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), web_search_config: None, use_experimental_unified_exec_tool: !cfg!(windows), @@ -7380,6 +7569,7 @@ async fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> { user_instructions: None, notify: None, cwd: fixture.cwd(), + workspace_roots: vec![fixture.cwd()], cli_auth_credentials_store_mode: Default::default(), mcp_servers: Constrained::allow_any(HashMap::new()), mcp_oauth_credentials_store_mode: resolve_mcp_oauth_credentials_store_mode( @@ -7445,7 +7635,7 @@ async fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> { commit_attribution: None, forced_chatgpt_workspace_id: None, forced_login_method: None, - include_apply_patch_tool: false, + include_apply_patch_tool: true, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), web_search_config: None, use_experimental_unified_exec_tool: !cfg!(windows), @@ -7523,6 +7713,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> { user_instructions: None, notify: None, cwd: fixture.cwd(), + workspace_roots: vec![fixture.cwd()], cli_auth_credentials_store_mode: Default::default(), mcp_servers: Constrained::allow_any(HashMap::new()), mcp_oauth_credentials_store_mode: resolve_mcp_oauth_credentials_store_mode( @@ -7588,7 +7779,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> { commit_attribution: None, forced_chatgpt_workspace_id: None, forced_login_method: None, - include_apply_patch_tool: false, + include_apply_patch_tool: true, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), web_search_config: None, use_experimental_unified_exec_tool: !cfg!(windows), diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index b2dfbcb2b8..bcbd81bc6c 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -37,7 +37,6 @@ use codex_config::profile_toml::ConfigProfile; use codex_config::sandbox_mode_requirement_for_permission_profile; use codex_config::types::ApprovalsReviewer; use codex_config::types::AuthCredentialsStoreMode; -use codex_config::types::DEFAULT_OTEL_ENVIRONMENT; use codex_config::types::History; use codex_config::types::McpServerConfig; use codex_config::types::McpServerDisabledReason; @@ -46,9 +45,6 @@ use codex_config::types::MemoriesConfig; use codex_config::types::ModelAvailabilityNuxConfig; use codex_config::types::Notice; use codex_config::types::OAuthCredentialsStoreMode; -use codex_config::types::OtelConfig; -use codex_config::types::OtelConfigToml; -use codex_config::types::OtelExporterKind; use codex_config::types::SessionPickerViewMode; use codex_config::types::ToolSuggestConfig; use codex_config::types::ToolSuggestDisabledTool; @@ -93,7 +89,6 @@ use codex_protocol::config_types::WebSearchConfig; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::ActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification; use codex_protocol::models::PermissionProfile; use codex_protocol::models::SandboxEnforcement; use codex_protocol::openai_models::ModelsResponse; @@ -132,6 +127,7 @@ pub(crate) mod agent_roles; pub mod edit; mod managed_features; mod network_proxy_spec; +mod otel; mod permissions; #[cfg(test)] mod schema; @@ -383,8 +379,6 @@ pub enum ThreadStoreConfig { /// Persist threads locally using rollout JSONL files and sqlite metadata. #[default] Local, - /// Persist threads through the remote thread-store service. - Remote { endpoint: String }, /// In-memory thread store for test and debug configurations. InMemory { id: String }, } @@ -571,6 +565,10 @@ pub struct Config { /// layer are resolved against this path. pub cwd: AbsolutePathBuf, + /// Absolute roots that define the writable project/workspace set for + /// symbolic `:project_roots` permission entries. + pub workspace_roots: Vec, + /// Preferred store for CLI auth credentials. /// file (default): Use a file in the Codex home directory. /// keyring: Use an OS-specific keyring service. @@ -1736,17 +1734,11 @@ fn resolve_tool_suggest_config_from_config( } } -fn thread_store_config( - thread_store: Option, - legacy_remote_endpoint: Option, -) -> ThreadStoreConfig { +fn thread_store_config(thread_store: Option) -> ThreadStoreConfig { match thread_store { Some(ThreadStoreToml::Local {}) => ThreadStoreConfig::Local, - Some(ThreadStoreToml::Remote { endpoint }) => ThreadStoreConfig::Remote { endpoint }, Some(ThreadStoreToml::InMemory { id }) => ThreadStoreConfig::InMemory { id }, - None => legacy_remote_endpoint.map_or(ThreadStoreConfig::Local, |endpoint| { - ThreadStoreConfig::Remote { endpoint } - }), + None => ThreadStoreConfig::Local, } } @@ -1858,6 +1850,11 @@ fn apply_managed_filesystem_constraints( } } +fn dedupe_absolute_paths(paths: &mut Vec) { + let mut seen = HashSet::new(); + paths.retain(|path| seen.insert(path.clone())); +} + /// Optional overrides for user configuration (e.g., from CLI flags). #[derive(Default, Debug, Clone)] pub struct ConfigOverrides { @@ -1886,6 +1883,9 @@ pub struct ConfigOverrides { pub ephemeral: Option, /// Additional directories that should be treated as writable roots for this session. pub additional_writable_roots: Vec, + /// Explicit workspace roots for this session. When set, this is the full + /// root list rather than an additive override. + pub workspace_roots: Option>, } /// Resolves the OSS provider from CLI override, profile config, or global config. @@ -2100,6 +2100,13 @@ impl Config { ) -> std::io::Result { // Keep the large config-construction future off small test thread stacks. Box::pin(async move { + if cfg.experimental_thread_store_endpoint.is_some() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "`experimental_thread_store_endpoint` is no longer supported; remove it from config.toml", + )); + } + validate_model_providers(&cfg.model_providers) .map_err(|message| std::io::Error::new(std::io::ErrorKind::InvalidInput, message))?; // Ensure that every field of ConfigRequirements is applied to the final @@ -2153,6 +2160,7 @@ impl Config { tools_web_search_request: override_tools_web_search_request, ephemeral, additional_writable_roots, + workspace_roots: workspace_roots_override, } = overrides; if sandbox_mode.is_some() && permission_profile.is_some() { @@ -2240,11 +2248,10 @@ impl Config { } } }))?; - let mut additional_writable_roots: Vec = additional_writable_roots + let requested_additional_writable_roots: Vec = additional_writable_roots .into_iter() .map(|path| AbsolutePathBuf::resolve_path_against_base(path, resolved_cwd.as_path())) .collect(); - let requested_additional_writable_roots = additional_writable_roots.clone(); let repo_root = resolve_root_git_project_for_trust(fs, &resolved_cwd).await; let active_project = cfg .get_active_project( @@ -2286,12 +2293,7 @@ impl Config { }; let memories_root = memory_root(&codex_home); std::fs::create_dir_all(&memories_root)?; - if !additional_writable_roots - .iter() - .any(|existing| existing == &memories_root) - { - additional_writable_roots.push(memories_root); - } + let internal_writable_roots = vec![memories_root]; let profiles_are_active = default_permissions_override.is_some() || matches!( @@ -2301,6 +2303,31 @@ impl Config { || permission_config_syntax.is_none(); let using_implicit_builtin_profile = permission_config_syntax.is_none() && default_permissions.is_none(); + let should_seed_legacy_workspace_roots = + default_permissions.is_none() + && matches!( + permission_config_syntax, + None | Some(PermissionConfigSyntax::Legacy) + ); + let mut workspace_roots = match workspace_roots_override { + Some(workspace_roots) => workspace_roots + .into_iter() + .map(|path| { + AbsolutePathBuf::resolve_path_against_base(path, resolved_cwd.as_path()) + }) + .collect(), + None => { + let mut workspace_roots = vec![resolved_cwd.clone()]; + workspace_roots.extend(requested_additional_writable_roots.clone()); + if should_seed_legacy_workspace_roots + && let Some(sandbox_workspace_write) = cfg.sandbox_workspace_write.as_ref() + { + workspace_roots.extend(sandbox_workspace_write.writable_roots.clone()); + } + workspace_roots + } + }; + dedupe_absolute_paths(&mut workspace_roots); let ( configured_network_proxy_config, permission_profile, @@ -2337,10 +2364,7 @@ impl Config { ); if matches!(sandbox_policy, SandboxPolicy::WorkspaceWrite { .. }) { file_system_sandbox_policy = file_system_sandbox_policy - .with_additional_writable_roots( - resolved_cwd.as_path(), - &additional_writable_roots, - ); + .with_additional_legacy_workspace_writable_roots(&internal_writable_roots); permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( permission_profile.enforcement(), &file_system_sandbox_policy, @@ -2391,28 +2415,8 @@ impl Config { resolved_cwd.as_path(), ); if matches!(sandbox_policy, SandboxPolicy::WorkspaceWrite { .. }) { - file_system_sandbox_policy = if using_implicit_builtin_profile { - file_system_sandbox_policy - .with_additional_legacy_workspace_writable_roots( - &additional_writable_roots, - ) - } else { - file_system_sandbox_policy.with_additional_writable_roots( - resolved_cwd.as_path(), - &additional_writable_roots, - ) - }; - permission_profile = PermissionProfile::from_runtime_permissions( - &file_system_sandbox_policy, - network_sandbox_policy, - ); - } else if matches!(permission_profile, PermissionProfile::Managed { .. }) - && !requested_additional_writable_roots.is_empty() - { - file_system_sandbox_policy = file_system_sandbox_policy.with_additional_writable_roots( - resolved_cwd.as_path(), - &requested_additional_writable_roots, - ); + file_system_sandbox_policy = file_system_sandbox_policy + .with_additional_legacy_workspace_writable_roots(&internal_writable_roots); permission_profile = PermissionProfile::from_runtime_permissions( &file_system_sandbox_policy, network_sandbox_policy, @@ -2429,22 +2433,7 @@ impl Config { // when doing so would lose roots, network, or tmp settings. None } else { - let active_permission_profile = if !requested_additional_writable_roots.is_empty() - && matches!(permission_profile, PermissionProfile::Managed { .. }) - { - ActivePermissionProfile::new(default_permissions).with_modifications( - requested_additional_writable_roots - .iter() - .cloned() - .map(|path| { - ActivePermissionProfileModification::AdditionalWritableRoot { path } - }) - .collect(), - ) - } else { - ActivePermissionProfile::new(default_permissions) - }; - Some(active_permission_profile) + Some(ActivePermissionProfile::new(default_permissions)) }; ( configured_network_proxy_config, @@ -2483,25 +2472,25 @@ impl Config { } let (mut file_system_sandbox_policy, network_sandbox_policy) = permission_profile.to_runtime_permissions(); - // `additional_writable_roots` is a legacy workspace-write knob. It - // only applies when the derived managed profile has workspace-style - // write access to the project roots; read-only, disabled, external, - // and future non-workspace profiles must not silently grow extra - // write access. + // Internal writable roots only apply when the derived managed + // profile has workspace-style write access to the project roots; + // read-only, disabled, external, and future non-workspace profiles + // must not silently grow extra write access. + let materialized_file_system_sandbox_policy = permission_profile + .materialize_project_roots_with_workspace_roots(&workspace_roots) + .file_system_sandbox_policy(); if matches!(permission_profile.enforcement(), SandboxEnforcement::Managed) - && file_system_sandbox_policy.can_write_path_with_cwd( + && materialized_file_system_sandbox_policy.can_write_path_with_cwd( resolved_cwd.as_path(), resolved_cwd.as_path(), ) - && !file_system_sandbox_policy.has_full_disk_write_access() + && !materialized_file_system_sandbox_policy.has_full_disk_write_access() { - // Keep legacy behavior for extra writable roots while storing - // the result as the canonical permission profile. Explicit - // extra roots are concrete paths, so their metadata carveouts - // are also concrete rather than symbolic `:project_roots` - // entries. + // Keep Codex runtime write access while storing the result as + // the canonical permission profile. Workspace roots themselves + // are held separately on the thread. file_system_sandbox_policy = file_system_sandbox_policy - .with_additional_legacy_workspace_writable_roots(&additional_writable_roots); + .with_additional_legacy_workspace_writable_roots(&internal_writable_roots); permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( permission_profile.enforcement(), &file_system_sandbox_policy, @@ -2738,10 +2727,7 @@ impl Config { notices.fast_default_opt_out = Some(true); None } - None => config_profile - .service_tier - .or(cfg.service_tier) - .map(|service_tier| service_tier.request_value().to_string()), + None => config_profile.service_tier.or(cfg.service_tier), }; let service_tier = service_tier.and_then(|service_tier| { match ServiceTier::from_request_value(&service_tier) { @@ -2978,6 +2964,7 @@ impl Config { .value .set(effective_permission_profile) .map_err(std::io::Error::from)?; + let otel = otel::resolve_config(cfg.otel.unwrap_or_default(), &mut startup_warnings); let config = Self { model, service_tier, @@ -2987,6 +2974,7 @@ impl Config { model_provider_id, model_provider, cwd: resolved_cwd, + workspace_roots, startup_warnings, permissions: Permissions { approval_policy: constrained_approval_policy.value, @@ -3124,10 +3112,7 @@ impl Config { experimental_realtime_ws_startup_context: cfg.experimental_realtime_ws_startup_context, experimental_realtime_start_instructions: cfg.experimental_realtime_start_instructions, experimental_thread_config_endpoint: cfg.experimental_thread_config_endpoint, - experimental_thread_store: thread_store_config( - cfg.experimental_thread_store, - cfg.experimental_thread_store_endpoint, - ), + experimental_thread_store: thread_store_config(cfg.experimental_thread_store), forced_chatgpt_workspace_id, forced_login_method, include_apply_patch_tool: include_apply_patch_tool_flag, @@ -3205,26 +3190,7 @@ impl Config { .as_ref() .map(|t| t.keymap.clone()) .unwrap_or_default(), - otel: { - let t: OtelConfigToml = cfg.otel.unwrap_or_default(); - let log_user_prompt = t.log_user_prompt.unwrap_or(false); - let environment = t - .environment - .unwrap_or(DEFAULT_OTEL_ENVIRONMENT.to_string()); - let exporter = t.exporter.unwrap_or(OtelExporterKind::None); - // OTLP HTTP endpoints are signal-specific in our config, so - // enabling log export must not implicitly send spans to a - // /v1/logs endpoint. - let trace_exporter = t.trace_exporter.unwrap_or(OtelExporterKind::None); - let metrics_exporter = t.metrics_exporter.unwrap_or(OtelExporterKind::Statsig); - OtelConfig { - log_user_prompt, - environment, - exporter, - trace_exporter, - metrics_exporter, - } - }, + otel, }; Ok(config) }) diff --git a/codex-rs/core/src/config/otel.rs b/codex-rs/core/src/config/otel.rs new file mode 100644 index 0000000000..cb65d304d1 --- /dev/null +++ b/codex-rs/core/src/config/otel.rs @@ -0,0 +1,117 @@ +use std::collections::BTreeMap; +use std::fmt::Display; + +use codex_config::types::DEFAULT_OTEL_ENVIRONMENT; +use codex_config::types::OtelConfig; +use codex_config::types::OtelConfigToml; +use codex_config::types::OtelExporterKind; + +pub(crate) fn resolve_config( + config: OtelConfigToml, + startup_warnings: &mut Vec, +) -> OtelConfig { + let log_user_prompt = config.log_user_prompt.unwrap_or(false); + let environment = config + .environment + .unwrap_or_else(|| DEFAULT_OTEL_ENVIRONMENT.to_string()); + let exporter = config.exporter.unwrap_or(OtelExporterKind::None); + // OTLP HTTP endpoints are signal-specific in our config, so enabling log + // export must not implicitly send spans to a /v1/logs endpoint. + let trace_exporter = config.trace_exporter.unwrap_or(OtelExporterKind::None); + let metrics_exporter = config.metrics_exporter.unwrap_or(OtelExporterKind::Statsig); + // Provider initialization installs process-global OTEL state. Sanitize + // user-editable trace metadata here so malformed config is reported as a + // startup warning instead of making startup fail. + let span_attributes = resolve_span_attributes(config.span_attributes, startup_warnings); + let tracestate = resolve_tracestate(config.tracestate, startup_warnings); + + OtelConfig { + log_user_prompt, + environment, + exporter, + trace_exporter, + metrics_exporter, + span_attributes, + tracestate, + } +} + +fn resolve_span_attributes( + span_attributes: Option>, + startup_warnings: &mut Vec, +) -> BTreeMap { + let Some(span_attributes) = span_attributes else { + return BTreeMap::new(); + }; + + let mut valid_attributes = BTreeMap::new(); + for (key, value) in span_attributes { + let attribute = BTreeMap::from([(key.clone(), value.clone())]); + if let Err(err) = codex_otel::validate_span_attributes(&attribute) { + push_invalid_config_warning("otel.span_attributes", err, startup_warnings); + continue; + } + valid_attributes.insert(key, value); + } + + valid_attributes +} + +fn resolve_tracestate( + tracestate: Option>>, + startup_warnings: &mut Vec, +) -> BTreeMap> { + let Some(tracestate) = tracestate else { + return BTreeMap::new(); + }; + + let mut valid_entries = BTreeMap::new(); + for (member_key, fields) in tracestate { + let fields = resolve_tracestate_member_fields(&member_key, fields, startup_warnings); + if fields.is_empty() { + continue; + } + if let Err(err) = codex_otel::validate_tracestate_member(&member_key, &fields) { + push_invalid_config_warning("otel.tracestate", err, startup_warnings); + continue; + } + valid_entries.insert(member_key, fields); + } + + // Tracestate members can be valid individually while the combined W3C + // tracestate header is not, so validate the filtered set before handing it + // to provider initialization. + if let Err(err) = codex_otel::validate_tracestate_entries(&valid_entries) { + push_invalid_config_warning("otel.tracestate", err, startup_warnings); + return BTreeMap::new(); + } + + valid_entries +} + +fn resolve_tracestate_member_fields( + member_key: &str, + fields: BTreeMap, + startup_warnings: &mut Vec, +) -> BTreeMap { + let mut valid_fields = BTreeMap::new(); + for (field_key, value) in fields { + let field = BTreeMap::from([(field_key.clone(), value.clone())]); + if let Err(err) = codex_otel::validate_tracestate_member(member_key, &field) { + push_invalid_config_warning("otel.tracestate", err, startup_warnings); + continue; + } + valid_fields.insert(field_key, value); + } + valid_fields +} + +fn push_invalid_config_warning( + config_key: &str, + err: impl Display, + startup_warnings: &mut Vec, +) { + let message = format!("Ignoring invalid `{config_key}` config: {err}"); + tracing::warn!("{message}"); + startup_warnings.push(message); +} diff --git a/codex-rs/core/src/config/permissions.rs b/codex-rs/core/src/config/permissions.rs index b51a8973a3..cb1bf2e52e 100644 --- a/codex-rs/core/src/config/permissions.rs +++ b/codex-rs/core/src/config/permissions.rs @@ -59,12 +59,12 @@ pub(crate) fn builtin_permission_profile( BUILT_IN_READ_ONLY_PROFILE => Some(PermissionProfile::read_only()), BUILT_IN_WORKSPACE_PROFILE => Some(match workspace_write { Some(SandboxWorkspaceWrite { - writable_roots, + writable_roots: _, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, }) => PermissionProfile::workspace_write_with( - writable_roots, + &[], if *network_access { NetworkSandboxPolicy::Enabled } else { diff --git a/codex-rs/core/src/context/permissions_instructions_tests.rs b/codex-rs/core/src/context/permissions_instructions_tests.rs index 16d5dc631a..97948ad5ad 100644 --- a/codex-rs/core/src/context/permissions_instructions_tests.rs +++ b/codex-rs/core/src/context/permissions_instructions_tests.rs @@ -56,7 +56,6 @@ fn builds_permissions_with_network_access_override() { #[test] fn builds_permissions_from_policy() { let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index 74f4d29bfb..c1777f4213 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -123,6 +123,7 @@ fn reference_context_item() -> TurnContextItem { turn_id: Some("reference-turn".to_string()), trace_id: None, cwd: PathBuf::from("/tmp/reference-cwd"), + workspace_roots: Vec::new(), current_date: Some("2026-03-23".to_string()), timezone: Some("America/Los_Angeles".to_string()), approval_policy: AskForApproval::OnRequest, diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index 1bc2cb0895..0b83899128 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -50,14 +50,19 @@ fn build_permissions_update_item( let prev = previous?; if prev.permission_profile() == next.permission_profile() + && prev.workspace_roots == next.workspace_roots && prev.approval_policy == next.approval_policy.value() { return None; } + let permission_profile = next + .permission_profile + .clone() + .materialize_project_roots_with_workspace_roots(&next.workspace_roots); Some( PermissionsInstructions::from_permission_profile( - &next.permission_profile, + &permission_profile, next.approval_policy.value(), next.config.approvals_reviewer, exec_policy, diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index fd5cd7bcdc..c01537e895 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -294,6 +294,7 @@ pub async fn process_exec_tool_call( params: ExecParams, permission_profile: &PermissionProfile, sandbox_cwd: &AbsolutePathBuf, + workspace_roots: &[AbsolutePathBuf], codex_linux_sandbox_exe: &Option, use_legacy_landlock: bool, stdout_stream: Option, @@ -302,6 +303,7 @@ pub async fn process_exec_tool_call( params, permission_profile, sandbox_cwd, + workspace_roots, codex_linux_sandbox_exe, use_legacy_landlock, )?; @@ -316,6 +318,7 @@ pub fn build_exec_request( params: ExecParams, permission_profile: &PermissionProfile, sandbox_cwd: &AbsolutePathBuf, + workspace_roots: &[AbsolutePathBuf], codex_linux_sandbox_exe: &Option, use_legacy_landlock: bool, ) -> Result { @@ -377,6 +380,7 @@ pub fn build_exec_request( enforce_managed_network, network: network.as_ref(), sandbox_policy_cwd: sandbox_cwd, + workspace_roots, codex_linux_sandbox_exe: codex_linux_sandbox_exe.as_deref(), use_legacy_landlock, windows_sandbox_level, diff --git a/codex-rs/core/src/exec_tests.rs b/codex-rs/core/src/exec_tests.rs index 9d335a81c7..f875fc5f34 100644 --- a/codex-rs/core/src/exec_tests.rs +++ b/codex-rs/core/src/exec_tests.rs @@ -365,6 +365,7 @@ async fn process_exec_tool_call_preserves_full_buffer_capture_policy() -> Result }, &permission_profile, &cwd, + &[], &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, @@ -470,7 +471,6 @@ fn windows_restricted_token_allows_legacy_restricted_policies() { #[test] fn windows_restricted_token_allows_legacy_workspace_write_policies() { let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -528,7 +528,6 @@ fn windows_restricted_token_rejects_split_only_filesystem_policies() { let docs = temp_dir.path().join("docs"); std::fs::create_dir_all(&docs).expect("create docs"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -573,7 +572,6 @@ fn windows_restricted_token_rejects_root_write_read_only_carveouts() { let docs = temp_dir.path().join("docs"); std::fs::create_dir_all(&docs).expect("create docs"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -619,7 +617,6 @@ fn windows_restricted_token_supports_full_read_split_write_read_carveouts() { let docs = cwd.join("docs"); std::fs::create_dir_all(docs.as_path()).expect("create docs"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -711,7 +708,6 @@ fn windows_elevated_supports_split_write_read_carveouts() { std::fs::create_dir_all(&docs).expect("create docs"); let expected_docs = dunce::canonicalize(&docs).expect("canonical docs"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -767,7 +763,6 @@ fn windows_elevated_rejects_unreadable_split_carveouts() { let blocked = temp_dir.path().join("blocked"); std::fs::create_dir_all(&blocked).expect("create blocked"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -816,7 +811,6 @@ fn windows_elevated_rejects_unreadable_split_carveouts() { fn windows_elevated_rejects_unreadable_globs() { let temp_dir = tempfile::TempDir::new().expect("tempdir"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -867,7 +861,6 @@ fn windows_elevated_rejects_reopened_writable_descendants() { let nested = docs.join("nested"); std::fs::create_dir_all(&nested).expect("create nested"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -1040,6 +1033,7 @@ async fn process_exec_tool_call_respects_cancellation_token() -> Result<()> { params, &PermissionProfile::Disabled, &cwd, + &[], &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs index 850d84dd2a..bba2167cef 100644 --- a/codex-rs/core/src/guardian/review.rs +++ b/codex-rs/core/src/guardian/review.rs @@ -23,6 +23,7 @@ use tokio_util::sync::CancellationToken; use crate::session::session::Session; use crate::session::turn_context::TurnContext; +use crate::turn_timing::now_unix_timestamp_ms; use super::GUARDIAN_REVIEW_TIMEOUT; use super::GUARDIAN_REVIEWER_NAME; @@ -251,6 +252,7 @@ async fn run_guardian_review( guardian_reviewed_action(&request), GUARDIAN_REVIEW_TIMEOUT.as_millis() as u64, ); + let started_at_ms = review_tracking.started_at_ms.try_into().unwrap_or_default(); session .send_event( turn.as_ref(), @@ -258,6 +260,8 @@ async fn run_guardian_review( id: review_id.clone(), target_item_id: target_item_id.clone(), turn_id: assessment_turn_id.clone(), + started_at_ms, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -289,6 +293,8 @@ async fn run_guardian_review( id: review_id, target_item_id, turn_id: assessment_turn_id.clone(), + started_at_ms, + completed_at_ms: Some(now_unix_timestamp_ms()), status: GuardianAssessmentStatus::Aborted, risk_level: None, user_authorization: None, @@ -372,6 +378,8 @@ async fn run_guardian_review( id: review_id, target_item_id, turn_id: assessment_turn_id.clone(), + started_at_ms, + completed_at_ms: Some(now_unix_timestamp_ms()), status: GuardianAssessmentStatus::TimedOut, risk_level: None, user_authorization: None, @@ -402,6 +410,8 @@ async fn run_guardian_review( id: review_id, target_item_id, turn_id: assessment_turn_id.clone(), + started_at_ms, + completed_at_ms: Some(now_unix_timestamp_ms()), status: GuardianAssessmentStatus::Aborted, risk_level: None, user_authorization: None, @@ -495,6 +505,8 @@ async fn run_guardian_review( id: review_id, target_item_id, turn_id: assessment_turn_id.clone(), + started_at_ms, + completed_at_ms: Some(now_unix_timestamp_ms()), status, risk_level: Some(assessment.risk_level), user_authorization: Some(assessment.user_authorization), diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs index 41914570f3..0cd1f06994 100644 --- a/codex-rs/core/src/otel_init.rs +++ b/codex-rs/core/src/otel_init.rs @@ -89,6 +89,8 @@ pub fn build_provider( trace_exporter, metrics_exporter, runtime_metrics, + span_attributes: config.otel.span_attributes.clone(), + tracestate: config.otel.tracestate.clone(), }) } diff --git a/codex-rs/core/src/personality_migration_tests.rs b/codex-rs/core/src/personality_migration_tests.rs index 699e06fe67..7bc0ea82f8 100644 --- a/codex-rs/core/src/personality_migration_tests.rs +++ b/codex-rs/core/src/personality_migration_tests.rs @@ -47,6 +47,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R forked_from_id: None, timestamp: TEST_TIMESTAMP.to_string(), cwd: std::path::PathBuf::from("."), + workspace_roots: Vec::new(), originator: "test_originator".to_string(), cli_version: "test_version".to_string(), source: SessionSource::Cli, diff --git a/codex-rs/core/src/rollout.rs b/codex-rs/core/src/rollout.rs index e0d268dc2d..5b855c9cfc 100644 --- a/codex-rs/core/src/rollout.rs +++ b/codex-rs/core/src/rollout.rs @@ -37,6 +37,10 @@ impl codex_rollout::RolloutConfigView for Config { self.cwd.as_path() } + fn workspace_roots(&self) -> &[codex_utils_absolute_path::AbsolutePathBuf] { + &self.workspace_roots + } + fn model_provider_id(&self) -> &str { self.model_provider_id.as_str() } diff --git a/codex-rs/core/src/safety_tests.rs b/codex-rs/core/src/safety_tests.rs index d699172498..15849568a7 100644 --- a/codex-rs/core/src/safety_tests.rs +++ b/codex-rs/core/src/safety_tests.rs @@ -33,7 +33,6 @@ fn test_writable_roots_constraint() { // Policy limited to the workspace only; exclude system temp roots so // only `cwd` is writable by default. let policy_workspace_only = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -51,17 +50,16 @@ fn test_writable_roots_constraint() { &cwd, )); - // With the parent dir explicitly added as a writable root, the - // outside write should be permitted. - let policy_with_parent = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![parent], - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; + // With the parent dir explicitly added as a workspace root, the outside + // write should be permitted. + let file_system_policy_with_parent = + FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { + path: FileSystemPath::Path { path: parent }, + access: FileSystemAccessMode::Write, + }]); assert!(is_write_patch_constrained_to_writable_paths( &add_outside, - &FileSystemSandboxPolicy::from(&policy_with_parent), + &file_system_policy_with_parent, &cwd, )); } @@ -101,7 +99,6 @@ fn granular_with_all_flags_true_matches_on_request_for_out_of_root_patch() { let outside_path = parent.join("outside.txt"); let add_outside = ApplyPatchAction::new_add_for_test(&outside_path, "".to_string()); let policy_workspace_only = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -145,7 +142,6 @@ fn granular_sandbox_approval_false_rejects_out_of_root_patch() { let outside_path = parent.join("outside.txt"); let add_outside = ApplyPatchAction::new_add_for_test(&outside_path, "".to_string()); let policy_workspace_only = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -295,7 +291,6 @@ fn missing_project_dot_codex_config_requires_approval() { let config_path = cwd.join(".codex").join("config.toml"); let action = ApplyPatchAction::new_add_for_test(&config_path, "".to_string()); let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, diff --git a/codex-rs/core/src/session/config_lock.rs b/codex-rs/core/src/session/config_lock.rs index 10f2242647..3e8c36734d 100644 --- a/codex-rs/core/src/session/config_lock.rs +++ b/codex-rs/core/src/session/config_lock.rs @@ -109,10 +109,7 @@ fn save_session_resolved_fields(sc: &SessionConfiguration, lock_config: &mut Con lock_config.model = Some(sc.collaboration_mode.model().to_string()); lock_config.model_reasoning_effort = sc.collaboration_mode.reasoning_effort(); lock_config.model_reasoning_summary = sc.model_reasoning_summary; - lock_config.service_tier = sc - .service_tier - .as_deref() - .and_then(codex_protocol::config_types::ServiceTier::from_request_value); + lock_config.service_tier = sc.service_tier.clone(); lock_config.instructions = Some(sc.base_instructions.clone()); lock_config.developer_instructions = sc.developer_instructions.clone(); lock_config.compact_prompt = sc.compact_prompt.clone(); diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 03f29bac53..6ff8785c76 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -143,6 +143,7 @@ pub(super) async fn user_input_or_turn_inner( items, SessionSettingsUpdate { cwd: Some(cwd), + workspace_roots: None, approval_policy: Some(approval_policy), approvals_reviewer, sandbox_policy: Some(sandbox_policy), @@ -163,6 +164,7 @@ pub(super) async fn user_input_or_turn_inner( } Op::UserInputWithTurnContext { cwd, + workspace_roots, approval_policy, approvals_reviewer, sandbox_policy, @@ -195,6 +197,8 @@ pub(super) async fn user_input_or_turn_inner( items, SessionSettingsUpdate { cwd, + workspace_roots: workspace_roots + .map(|roots| roots.into_iter().map(|root| root.to_path_buf()).collect()), approval_policy, approvals_reviewer, sandbox_policy, diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 6d4b275421..18a436e49e 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -617,6 +617,7 @@ impl Codex { active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: environment_selections.to_selections(), @@ -1956,6 +1957,7 @@ impl Session { call_id, approval_id, turn_id: turn_context.sub_id.clone(), + started_at_ms: now_unix_timestamp_ms(), command, cwd, reason, @@ -2002,6 +2004,7 @@ impl Session { let event = EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { call_id, turn_id: turn_context.sub_id.clone(), + started_at_ms: now_unix_timestamp_ms(), changes, reason, grant_root, @@ -2165,6 +2168,7 @@ impl Session { let event = EventMsg::RequestPermissions(RequestPermissionsEvent { call_id: call_id.clone(), turn_id: turn_context.sub_id.clone(), + started_at_ms: now_unix_timestamp_ms(), reason: args.reason, permissions: requested_permissions, cwd: Some(cwd), @@ -2610,9 +2614,13 @@ impl Session { developer_sections.push(model_switch_message); } if turn_context.config.include_permissions_instructions { + let permission_profile = turn_context + .permission_profile + .clone() + .materialize_project_roots_with_workspace_roots(&turn_context.workspace_roots); developer_sections.push( PermissionsInstructions::from_permission_profile( - &turn_context.permission_profile, + &permission_profile, turn_context.approval_policy.value(), turn_context.config.approvals_reviewer, self.services.exec_policy.current().as_ref(), diff --git a/codex-rs/core/src/session/review.rs b/codex-rs/core/src/session/review.rs index 7d4b1b736a..ca16f0f70c 100644 --- a/codex-rs/core/src/session/review.rs +++ b/codex-rs/core/src/session/review.rs @@ -143,6 +143,7 @@ pub(super) async fn spawn_review_thread( windows_sandbox_level: parent_turn_context.windows_sandbox_level, shell_environment_policy: parent_turn_context.shell_environment_policy.clone(), cwd: parent_turn_context.cwd.clone(), + workspace_roots: parent_turn_context.workspace_roots.clone(), final_output_json_schema: None, codex_self_exe: parent_turn_context.codex_self_exe.clone(), codex_linux_sandbox_exe: parent_turn_context.codex_linux_sandbox_exe.clone(), diff --git a/codex-rs/core/src/session/rollout_reconstruction_tests.rs b/codex-rs/core/src/session/rollout_reconstruction_tests.rs index 5cfcc38053..df87ca2429 100644 --- a/codex-rs/core/src/session/rollout_reconstruction_tests.rs +++ b/codex-rs/core/src/session/rollout_reconstruction_tests.rs @@ -61,6 +61,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -102,6 +103,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -912,6 +914,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -990,6 +993,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1021,6 +1025,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1136,6 +1141,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo turn_id: Some(current_turn_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1250,6 +1256,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1402,6 +1409,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index f72a173c80..5c3051e6e2 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -75,6 +75,9 @@ pub(crate) struct SessionConfiguration { /// execution sandbox are resolved against this directory **instead** of /// the process-wide current working directory. pub(super) cwd: AbsolutePathBuf, + /// Workspace roots used to materialize symbolic `:project_roots` + /// permission entries for this thread. + pub(super) workspace_roots: Vec, /// Directory containing all Codex state for this session. pub(super) codex_home: AbsolutePathBuf, /// Optional user-facing name for the thread, updated during the session. @@ -112,12 +115,13 @@ impl SessionConfiguration { } pub(super) fn sandbox_policy(&self) -> SandboxPolicy { - self.permission_profile() + let permission_profile = self.materialized_permission_profile(); + permission_profile .to_legacy_sandbox_policy(&self.cwd) .unwrap_or_else(|_| { let file_system_sandbox_policy = self.file_system_sandbox_policy(); codex_sandboxing::compatibility_sandbox_policy_for_permission_profile( - self.permission_profile.get(), + &permission_profile, &file_system_sandbox_policy, self.network_sandbox_policy(), &self.cwd, @@ -126,13 +130,21 @@ impl SessionConfiguration { } pub(super) fn file_system_sandbox_policy(&self) -> FileSystemSandboxPolicy { - self.permission_profile.get().file_system_sandbox_policy() + self.materialized_permission_profile() + .file_system_sandbox_policy() } pub(super) fn network_sandbox_policy(&self) -> NetworkSandboxPolicy { self.permission_profile.get().network_sandbox_policy() } + fn materialized_permission_profile(&self) -> PermissionProfile { + self.permission_profile + .get() + .clone() + .materialize_project_roots_with_workspace_roots(&self.workspace_roots) + } + pub(super) fn thread_config_snapshot(&self) -> ThreadConfigSnapshot { ThreadConfigSnapshot { model: self.collaboration_mode.model().to_string(), @@ -143,6 +155,7 @@ impl SessionConfiguration { permission_profile: self.permission_profile(), active_permission_profile: self.active_permission_profile(), cwd: self.cwd.clone(), + workspace_roots: self.workspace_roots.clone(), ephemeral: self.original_config_do_not_use.ephemeral, reasoning_effort: self.collaboration_mode.reasoning_effort(), personality: self.personality, @@ -223,6 +236,20 @@ impl SessionConfiguration { let cwd_changed = absolute_cwd.as_path() != self.cwd.as_path(); next_configuration.cwd = absolute_cwd; + if let Some(workspace_roots) = updates.workspace_roots.clone() { + let mut workspace_roots: Vec = workspace_roots + .into_iter() + .map(|path| { + AbsolutePathBuf::resolve_path_against_base( + normalize_for_native_workdir(path.as_path()), + next_configuration.cwd.as_path(), + ) + }) + .collect(); + dedupe_absolute_paths(&mut workspace_roots); + next_configuration.workspace_roots = workspace_roots; + } + if let Some(permission_profile) = updates.permission_profile.clone() { let active_permission_profile = updates.active_permission_profile.clone().or_else(|| { @@ -273,6 +300,8 @@ impl SessionConfiguration { current_network_sandbox_policy, ), )?; + } else if let Some(active_permission_profile) = updates.active_permission_profile.clone() { + next_configuration.active_permission_profile = Some(active_permission_profile); } if let Some(app_server_client_name) = updates.app_server_client_name.clone() { next_configuration.app_server_client_name = Some(app_server_client_name); @@ -306,9 +335,15 @@ impl SessionConfiguration { } } +fn dedupe_absolute_paths(paths: &mut Vec) { + let mut seen = std::collections::HashSet::new(); + paths.retain(|path| seen.insert(path.clone())); +} + #[derive(Default, Clone)] pub(crate) struct SessionSettingsUpdate { pub(crate) cwd: Option, + pub(crate) workspace_roots: Option>, pub(crate) approval_policy: Option, pub(crate) approvals_reviewer: Option, pub(crate) sandbox_policy: Option, @@ -424,6 +459,7 @@ impl Session { dynamic_tools: session_configuration.dynamic_tools.clone(), metadata: ThreadPersistenceMetadata { cwd: Some(config.cwd.to_path_buf()), + workspace_roots: config.workspace_roots.clone(), model_provider: config.model_provider_id.clone(), memory_mode: if config.memories.generate_memories { ThreadMemoryMode::Enabled @@ -446,6 +482,7 @@ impl Session { include_archived: true, metadata: ThreadPersistenceMetadata { cwd: Some(config.cwd.to_path_buf()), + workspace_roots: config.workspace_roots.clone(), model_provider: config.model_provider_id.clone(), memory_mode: if config.memories.generate_memories { ThreadMemoryMode::Enabled @@ -917,6 +954,7 @@ impl Session { permission_profile: session_configuration.permission_profile(), active_permission_profile: session_configuration.active_permission_profile(), cwd: session_configuration.cwd.clone(), + workspace_roots: session_configuration.workspace_roots.clone(), reasoning_effort: session_configuration.collaboration_mode.reasoning_effort(), initial_messages, network_proxy: session_network_proxy.filter(|_| { diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index b63b16cbf4..0260d10bb6 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1975,6 +1975,7 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() { turn_id: Some(turn_context.sub_id.clone()), trace_id: turn_context.trace_id.clone(), cwd: turn_context.cwd.to_path_buf(), + workspace_roots: turn_context.workspace_roots.clone(), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -2580,6 +2581,7 @@ async fn set_rate_limits_retains_previous_credits() { active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: Vec::new(), @@ -2684,6 +2686,7 @@ async fn set_rate_limits_updates_plan_type_when_present() { active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: Vec::new(), @@ -2950,6 +2953,7 @@ async fn attach_thread_persistence(session: &mut Session) -> PathBuf { dynamic_tools: Vec::new(), metadata: ThreadPersistenceMetadata { cwd: Some(config.cwd.to_path_buf()), + workspace_roots: config.workspace_roots.clone(), model_provider: config.model_provider_id.clone(), memory_mode: if config.memories.generate_memories { ThreadMemoryMode::Enabled @@ -3161,6 +3165,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: Vec::new(), @@ -3203,7 +3208,6 @@ async fn session_configuration_apply_preserves_profile_file_system_policy_on_cwd session_configuration.cwd = original_cwd.abs(); let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -3237,9 +3241,15 @@ async fn session_configuration_apply_preserves_profile_file_system_policy_on_cwd .expect("cwd-only update should succeed"); assert_eq!( - updated.file_system_sandbox_policy(), + updated.permission_profile().file_system_sandbox_policy(), file_system_sandbox_policy ); + let expected_materialized_file_system_policy = file_system_sandbox_policy + .materialize_project_roots_with_workspace_roots(&updated.workspace_roots); + assert_eq!( + updated.file_system_sandbox_policy(), + expected_materialized_file_system_policy + ); } #[tokio::test] @@ -3289,9 +3299,16 @@ async fn session_configuration_apply_permission_profile_preserves_existing_deny_ expected_file_system_policy.glob_scan_max_depth = Some(2); expected_file_system_policy.entries.push(deny_entry); assert_eq!( - updated.file_system_sandbox_policy(), + updated.permission_profile().file_system_sandbox_policy(), expected_file_system_policy ); + let expected_materialized_file_system_policy = expected_file_system_policy + .clone() + .materialize_project_roots_with_workspace_roots(&updated.workspace_roots); + assert_eq!( + updated.file_system_sandbox_policy(), + expected_materialized_file_system_policy + ); } #[tokio::test] @@ -3308,7 +3325,7 @@ async fn session_configuration_apply_permission_profile_accepts_direct_write_roo let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Path { - path: external_write_path.clone(), + path: external_write_path, }, access: FileSystemAccessMode::Write, }]); @@ -3332,7 +3349,6 @@ async fn session_configuration_apply_permission_profile_accepts_direct_write_roo assert_eq!( updated.sandbox_policy(), SandboxPolicy::WorkspaceWrite { - writable_roots: vec![external_write_path], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -3427,14 +3443,15 @@ enabled = false } #[tokio::test] -async fn session_configuration_apply_rederives_legacy_file_system_policy_on_cwd_update() { +async fn session_configuration_apply_preserves_legacy_workspace_roots_on_cwd_update() { let mut session_configuration = make_session_configuration_for_tests().await; let workspace = tempfile::tempdir().expect("create temp dir"); let project_root = workspace.path().join("project"); let original_cwd = project_root.join("subdir"); - session_configuration.cwd = original_cwd.abs(); + let original_cwd = original_cwd.abs(); + session_configuration.cwd = original_cwd.clone(); + session_configuration.workspace_roots = vec![original_cwd.clone()]; let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -3453,20 +3470,19 @@ async fn session_configuration_apply_rederives_legacy_file_system_policy_on_cwd_ let updated = session_configuration .apply(&SessionSettingsUpdate { - cwd: Some(project_root.clone()), + cwd: Some(project_root), ..Default::default() }) .expect("cwd-only update should succeed"); - let expected_file_system_policy = FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd( - &updated.sandbox_policy(), - &project_root, - ); + let expected_file_system_policy = file_system_sandbox_policy + .materialize_project_roots_with_workspace_roots(std::slice::from_ref(&original_cwd)); + assert_eq!(updated.workspace_roots, vec![original_cwd.clone()]); assert!( updated .file_system_sandbox_policy() - .is_semantically_equivalent_to(&expected_file_system_policy, &project_root), - "cwd-only update should rederive the legacy filesystem policy for the new cwd" + .is_semantically_equivalent_to(&expected_file_system_policy, original_cwd.as_path()), + "cwd-only update should preserve the existing workspace roots" ); } @@ -3687,6 +3703,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: Vec::new(), @@ -3795,6 +3812,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: default_environments, @@ -4022,6 +4040,7 @@ async fn make_session_with_config_and_rx( active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: default_environments, @@ -4124,6 +4143,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx( active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: default_environments, @@ -4770,6 +4790,7 @@ fn op_kind_distinguishes_turn_ops() { final_output_json_schema: None, responsesapi_client_metadata: None, cwd: None, + workspace_roots: None, approval_policy: None, approvals_reviewer: None, sandbox_policy: None, @@ -5165,6 +5186,7 @@ async fn shutdown_complete_does_not_append_to_thread_store_after_shutdown() { dynamic_tools: Vec::new(), metadata: ThreadPersistenceMetadata { cwd: Some(config.cwd.to_path_buf()), + workspace_roots: config.workspace_roots.clone(), model_provider: config.model_provider_id.clone(), memory_mode: if config.memories.generate_memories { ThreadMemoryMode::Enabled @@ -5510,6 +5532,7 @@ where active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), + workspace_roots: config.workspace_roots.clone(), codex_home: config.codex_home.clone(), thread_name: None, environments: default_environments, diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index d4fe30063f..a0ed332311 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -70,6 +70,7 @@ pub(crate) struct TurnContext { /// by the model as well as sandbox policies are resolved against this path /// instead of `std::env::current_dir()`. pub(crate) cwd: AbsolutePathBuf, + pub(crate) workspace_roots: Vec, pub(crate) current_date: Option, pub(crate) timezone: Option, pub(crate) app_server_client_name: Option, @@ -104,7 +105,10 @@ impl TurnContext { } pub(crate) fn file_system_sandbox_policy(&self) -> FileSystemSandboxPolicy { - self.permission_profile.file_system_sandbox_policy() + self.permission_profile + .clone() + .materialize_project_roots_with_workspace_roots(&self.workspace_roots) + .file_system_sandbox_policy() } pub(crate) fn network_sandbox_policy(&self) -> NetworkSandboxPolicy { @@ -253,6 +257,7 @@ impl TurnContext { thread_source: self.thread_source, environments: self.environments.clone(), cwd: self.cwd.clone(), + workspace_roots: self.workspace_roots.clone(), current_date: self.current_date.clone(), timezone: self.timezone.clone(), app_server_client_name: self.app_server_client_name.clone(), @@ -314,6 +319,7 @@ impl TurnContext { FileSystemSandboxContext { permissions, cwd: Some(self.cwd.clone()), + workspace_roots: self.workspace_roots.clone(), windows_sandbox_level: self.windows_sandbox_level, windows_sandbox_private_desktop: self .config @@ -349,6 +355,7 @@ impl TurnContext { turn_id: Some(self.sub_id.clone()), trace_id: self.trace_id.clone(), cwd: self.cwd.to_path_buf(), + workspace_roots: self.workspace_roots.clone(), current_date: self.current_date.clone(), timezone: self.timezone.clone(), approval_policy: self.approval_policy.value(), @@ -411,6 +418,7 @@ impl Session { let config = session_configuration.original_config_do_not_use.clone(); let mut per_turn_config = (*config).clone(); per_turn_config.cwd = cwd; + per_turn_config.workspace_roots = session_configuration.workspace_roots.clone(); per_turn_config.model_reasoning_effort = session_configuration.collaboration_mode.reasoning_effort(); per_turn_config.model_reasoning_summary = session_configuration.model_reasoning_summary; @@ -548,6 +556,7 @@ impl Session { thread_source: session_configuration.thread_source, environments, cwd, + workspace_roots: session_configuration.workspace_roots.clone(), current_date: Some(current_date), timezone: Some(timezone), app_server_client_name: session_configuration.app_server_client_name.clone(), diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index a19832717d..003f2786b0 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -57,7 +57,6 @@ use codex_thread_store::LocalThreadStore; use codex_thread_store::LocalThreadStoreConfig; use codex_thread_store::ReadThreadByRolloutPathParams; use codex_thread_store::ReadThreadParams; -use codex_thread_store::RemoteThreadStore; use codex_thread_store::StoredThread; use codex_thread_store::ThreadStore; use codex_thread_store::ThreadStoreError; @@ -277,7 +276,6 @@ pub fn thread_store_from_config( LocalThreadStoreConfig::from_config(config), state_db, )), - ThreadStoreConfig::Remote { endpoint } => Arc::new(RemoteThreadStore::new(endpoint)), ThreadStoreConfig::InMemory { id } => InMemoryThreadStore::for_id(id), } } diff --git a/codex-rs/core/src/tools/handlers/apply_patch_tests.rs b/codex-rs/core/src/tools/handlers/apply_patch_tests.rs index c0d4d17f32..92b4f6a45e 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch_tests.rs @@ -246,7 +246,6 @@ fn write_permissions_for_paths_skip_dirs_already_writable_under_workspace_root() let file_path = AbsolutePathBuf::try_from(nested.join("file.txt")) .expect("nested file path should be absolute"); let sandbox_policy = FileSystemSandboxPolicy::from(&SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: false, @@ -268,7 +267,6 @@ fn write_permissions_for_paths_keep_dirs_outside_workspace_root() { .expect("outside file path should be absolute"); let cwd_abs = cwd.abs(); let sandbox_policy = FileSystemSandboxPolicy::from(&SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, diff --git a/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs b/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs index 7d47290c10..c2636f5531 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs @@ -24,84 +24,89 @@ impl ToolHandler for Handler { matches!(payload, ToolPayload::Function { .. }) } - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - let arguments = function_arguments(payload)?; - let args: CloseAgentArgs = parse_arguments(&arguments)?; - let agent_id = parse_agent_id_target(&args.target)?; - let receiver_agent = session - .services - .agent_control - .get_agent_metadata(agent_id) - .unwrap_or_default(); - session - .send_event( - &turn, - CollabCloseBeginEvent { - call_id: call_id.clone(), - started_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id: agent_id, + fn handle( + &self, + invocation: ToolInvocation, + ) -> impl std::future::Future> + Send { + Box::pin(async move { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + let arguments = function_arguments(payload)?; + let args: CloseAgentArgs = parse_arguments(&arguments)?; + let agent_id = parse_agent_id_target(&args.target)?; + let receiver_agent = session + .services + .agent_control + .get_agent_metadata(agent_id) + .unwrap_or_default(); + session + .send_event( + &turn, + CollabCloseBeginEvent { + call_id: call_id.clone(), + started_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id: agent_id, + } + .into(), + ) + .await; + let status = match session + .services + .agent_control + .subscribe_status(agent_id) + .await + { + Ok(mut status_rx) => status_rx.borrow_and_update().clone(), + Err(err) => { + let status = session.services.agent_control.get_status(agent_id).await; + session + .send_event( + &turn, + CollabCloseEndEvent { + call_id: call_id.clone(), + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id: agent_id, + receiver_agent_nickname: receiver_agent.agent_nickname.clone(), + receiver_agent_role: receiver_agent.agent_role.clone(), + status, + } + .into(), + ) + .await; + return Err(collab_agent_error(agent_id, err)); } - .into(), - ) - .await; - let status = match session - .services - .agent_control - .subscribe_status(agent_id) - .await - { - Ok(mut status_rx) => status_rx.borrow_and_update().clone(), - Err(err) => { - let status = session.services.agent_control.get_status(agent_id).await; - session - .send_event( - &turn, - CollabCloseEndEvent { - call_id: call_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id: agent_id, - receiver_agent_nickname: receiver_agent.agent_nickname.clone(), - receiver_agent_role: receiver_agent.agent_role.clone(), - status, - } - .into(), - ) - .await; - return Err(collab_agent_error(agent_id, err)); - } - }; - let result = Box::pin(session.services.agent_control.close_agent(agent_id)) - .await - .map_err(|err| collab_agent_error(agent_id, err)) - .map(|_| ()); - session - .send_event( - &turn, - CollabCloseEndEvent { - call_id, - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id: agent_id, - receiver_agent_nickname: receiver_agent.agent_nickname, - receiver_agent_role: receiver_agent.agent_role, - status: status.clone(), - } - .into(), - ) - .await; - result?; + }; + let result = Box::pin(session.services.agent_control.close_agent(agent_id)) + .await + .map_err(|err| collab_agent_error(agent_id, err)) + .map(|_| ()); + session + .send_event( + &turn, + CollabCloseEndEvent { + call_id, + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id: agent_id, + receiver_agent_nickname: receiver_agent.agent_nickname, + receiver_agent_role: receiver_agent.agent_role, + status: status.clone(), + } + .into(), + ) + .await; + result?; - Ok(CloseAgentResult { - previous_status: status, + Ok(CloseAgentResult { + previous_status: status, + }) }) } } diff --git a/codex-rs/core/src/tools/handlers/multi_agents/resume_agent.rs b/codex-rs/core/src/tools/handlers/multi_agents/resume_agent.rs index 0b86c9abdf..9ad4af3a48 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/resume_agent.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/resume_agent.rs @@ -26,111 +26,116 @@ impl ToolHandler for Handler { matches!(payload, ToolPayload::Function { .. }) } - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - let arguments = function_arguments(payload)?; - let args: ResumeAgentArgs = parse_arguments(&arguments)?; - let receiver_thread_id = ThreadId::from_string(&args.id).map_err(|err| { - FunctionCallError::RespondToModel(format!("invalid agent id {}: {err:?}", args.id)) - })?; - let receiver_agent = session - .services - .agent_control - .get_agent_metadata(receiver_thread_id) - .unwrap_or_default(); - let child_depth = next_thread_spawn_depth(&turn.session_source); - let max_depth = turn.config.agent_max_depth; - if exceeds_thread_spawn_depth_limit(child_depth, max_depth) { - return Err(FunctionCallError::RespondToModel( - "Agent depth limit reached. Solve the task yourself.".to_string(), - )); - } + fn handle( + &self, + invocation: ToolInvocation, + ) -> impl std::future::Future> + Send { + Box::pin(async move { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + let arguments = function_arguments(payload)?; + let args: ResumeAgentArgs = parse_arguments(&arguments)?; + let receiver_thread_id = ThreadId::from_string(&args.id).map_err(|err| { + FunctionCallError::RespondToModel(format!("invalid agent id {}: {err:?}", args.id)) + })?; + let receiver_agent = session + .services + .agent_control + .get_agent_metadata(receiver_thread_id) + .unwrap_or_default(); + let child_depth = next_thread_spawn_depth(&turn.session_source); + let max_depth = turn.config.agent_max_depth; + if exceeds_thread_spawn_depth_limit(child_depth, max_depth) { + return Err(FunctionCallError::RespondToModel( + "Agent depth limit reached. Solve the task yourself.".to_string(), + )); + } - session - .send_event( - &turn, - CollabResumeBeginEvent { - call_id: call_id.clone(), - started_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, + session + .send_event( + &turn, + CollabResumeBeginEvent { + call_id: call_id.clone(), + started_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id, + receiver_agent_nickname: receiver_agent.agent_nickname.clone(), + receiver_agent_role: receiver_agent.agent_role.clone(), + } + .into(), + ) + .await; + + let mut status = session + .services + .agent_control + .get_status(receiver_thread_id) + .await; + let (receiver_agent, error) = if matches!(status, AgentStatus::NotFound) { + match Box::pin(try_resume_closed_agent( + &session, + &turn, receiver_thread_id, - receiver_agent_nickname: receiver_agent.agent_nickname.clone(), - receiver_agent_role: receiver_agent.agent_role.clone(), - } - .into(), - ) - .await; - - let mut status = session - .services - .agent_control - .get_status(receiver_thread_id) - .await; - let (receiver_agent, error) = if matches!(status, AgentStatus::NotFound) { - match Box::pin(try_resume_closed_agent( - &session, - &turn, - receiver_thread_id, - child_depth, - )) - .await - { - Ok(()) => { - status = session - .services - .agent_control - .get_status(receiver_thread_id) - .await; - ( - session + child_depth, + )) + .await + { + Ok(()) => { + status = session .services .agent_control - .get_agent_metadata(receiver_thread_id) - .unwrap_or(receiver_agent), - None, - ) - } - Err(err) => { - status = session - .services - .agent_control - .get_status(receiver_thread_id) - .await; - (receiver_agent, Some(err)) + .get_status(receiver_thread_id) + .await; + ( + session + .services + .agent_control + .get_agent_metadata(receiver_thread_id) + .unwrap_or(receiver_agent), + None, + ) + } + Err(err) => { + status = session + .services + .agent_control + .get_status(receiver_thread_id) + .await; + (receiver_agent, Some(err)) + } } + } else { + (receiver_agent, None) + }; + session + .send_event( + &turn, + CollabResumeEndEvent { + call_id, + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id, + receiver_agent_nickname: receiver_agent.agent_nickname, + receiver_agent_role: receiver_agent.agent_role, + status: status.clone(), + } + .into(), + ) + .await; + + if let Some(err) = error { + return Err(err); } - } else { - (receiver_agent, None) - }; - session - .send_event( - &turn, - CollabResumeEndEvent { - call_id, - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id, - receiver_agent_nickname: receiver_agent.agent_nickname, - receiver_agent_role: receiver_agent.agent_role, - status: status.clone(), - } - .into(), - ) - .await; + turn.session_telemetry + .counter("codex.multi_agent.resume", /*inc*/ 1, &[]); - if let Some(err) = error { - return Err(err); - } - turn.session_telemetry - .counter("codex.multi_agent.resume", /*inc*/ 1, &[]); - - Ok(ResumeAgentResult { status }) + Ok(ResumeAgentResult { status }) + }) } } diff --git a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs index 40e9cc5d38..804f4cda63 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs @@ -41,157 +41,162 @@ impl ToolHandler for Handler { matches!(payload, ToolPayload::Function { .. }) } - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - let arguments = function_arguments(payload)?; - let args: SpawnAgentArgs = parse_arguments(&arguments)?; - let role_name = args - .agent_type - .as_deref() - .map(str::trim) - .filter(|role| !role.is_empty()); - let input_items = parse_collab_input(args.message, args.items)?; - let prompt = render_input_preview(&input_items); - let session_source = turn.session_source.clone(); - let child_depth = next_thread_spawn_depth(&session_source); - let max_depth = turn.config.agent_max_depth; - if exceeds_thread_spawn_depth_limit(child_depth, max_depth) { - return Err(FunctionCallError::RespondToModel( - "Agent depth limit reached. Solve the task yourself.".to_string(), - )); - } - session - .send_event( - &turn, - CollabAgentSpawnBeginEvent { - call_id: call_id.clone(), - started_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - prompt: prompt.clone(), - model: args.model.clone().unwrap_or_default(), - reasoning_effort: args.reasoning_effort.unwrap_or_default(), - } - .into(), - ) - .await; - let mut config = - build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?; - if args.fork_context { - reject_full_fork_spawn_overrides( - role_name, - args.model.as_deref(), - args.reasoning_effort, - )?; - } else { - apply_requested_spawn_agent_model_overrides( - &session, - turn.as_ref(), - &mut config, - args.model.as_deref(), - args.reasoning_effort, - ) - .await?; - apply_role_to_config(&mut config, role_name) - .await - .map_err(FunctionCallError::RespondToModel)?; - } - apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?; - apply_spawn_agent_overrides(&mut config, child_depth); - - let result = Box::pin(session.services.agent_control.spawn_agent_with_metadata( - config, - input_items, - Some(thread_spawn_source( - session.conversation_id, - &turn.session_source, - child_depth, - role_name, - /*task_name*/ None, - )?), - SpawnAgentOptions { - fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()), - fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory), - environments: Some(turn.environments.to_selections()), - }, - )) - .await - .map_err(collab_spawn_error); - let (new_thread_id, new_agent_metadata, status) = match &result { - Ok(spawned_agent) => ( - Some(spawned_agent.thread_id), - Some(spawned_agent.metadata.clone()), - spawned_agent.status.clone(), - ), - Err(_) => (None, None, AgentStatus::NotFound), - }; - let agent_snapshot = match new_thread_id { - Some(thread_id) => { - session - .services - .agent_control - .get_agent_config_snapshot(thread_id) - .await + fn handle( + &self, + invocation: ToolInvocation, + ) -> impl std::future::Future> + Send { + Box::pin(async move { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + let arguments = function_arguments(payload)?; + let args: SpawnAgentArgs = parse_arguments(&arguments)?; + let role_name = args + .agent_type + .as_deref() + .map(str::trim) + .filter(|role| !role.is_empty()); + let input_items = parse_collab_input(args.message, args.items)?; + let prompt = render_input_preview(&input_items); + let session_source = turn.session_source.clone(); + let child_depth = next_thread_spawn_depth(&session_source); + let max_depth = turn.config.agent_max_depth; + if exceeds_thread_spawn_depth_limit(child_depth, max_depth) { + return Err(FunctionCallError::RespondToModel( + "Agent depth limit reached. Solve the task yourself.".to_string(), + )); } - None => None, - }; - let (_new_agent_path, new_agent_nickname, new_agent_role) = - match (&agent_snapshot, new_agent_metadata) { - (Some(snapshot), _) => ( - snapshot.session_source.get_agent_path().map(String::from), - snapshot.session_source.get_nickname(), - snapshot.session_source.get_agent_role(), - ), - (None, Some(metadata)) => ( - metadata.agent_path.map(String::from), - metadata.agent_nickname, - metadata.agent_role, - ), - (None, None) => (None, None, None), - }; - let effective_model = agent_snapshot - .as_ref() - .map(|snapshot| snapshot.model.clone()) - .unwrap_or_else(|| args.model.clone().unwrap_or_default()); - let effective_reasoning_effort = agent_snapshot - .as_ref() - .and_then(|snapshot| snapshot.reasoning_effort) - .unwrap_or(args.reasoning_effort.unwrap_or_default()); - let nickname = new_agent_nickname.clone(); - session - .send_event( - &turn, - CollabAgentSpawnEndEvent { - call_id, - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - new_thread_id, - new_agent_nickname, - new_agent_role, - prompt, - model: effective_model, - reasoning_effort: effective_reasoning_effort, - status, - } - .into(), - ) - .await; - let new_thread_id = result?.thread_id; - let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME); - turn.session_telemetry.counter( - "codex.multi_agent.spawn", - /*inc*/ 1, - &[("role", role_tag)], - ); + session + .send_event( + &turn, + CollabAgentSpawnBeginEvent { + call_id: call_id.clone(), + started_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + prompt: prompt.clone(), + model: args.model.clone().unwrap_or_default(), + reasoning_effort: args.reasoning_effort.unwrap_or_default(), + } + .into(), + ) + .await; + let mut config = + build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?; + if args.fork_context { + reject_full_fork_spawn_overrides( + role_name, + args.model.as_deref(), + args.reasoning_effort, + )?; + } else { + apply_requested_spawn_agent_model_overrides( + &session, + turn.as_ref(), + &mut config, + args.model.as_deref(), + args.reasoning_effort, + ) + .await?; + apply_role_to_config(&mut config, role_name) + .await + .map_err(FunctionCallError::RespondToModel)?; + } + apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?; + apply_spawn_agent_overrides(&mut config, child_depth); - Ok(SpawnAgentResult { - agent_id: new_thread_id.to_string(), - nickname, + let result = Box::pin(session.services.agent_control.spawn_agent_with_metadata( + config, + input_items, + Some(thread_spawn_source( + session.conversation_id, + &turn.session_source, + child_depth, + role_name, + /*task_name*/ None, + )?), + SpawnAgentOptions { + fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()), + fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory), + environments: Some(turn.environments.to_selections()), + }, + )) + .await + .map_err(collab_spawn_error); + let (new_thread_id, new_agent_metadata, status) = match &result { + Ok(spawned_agent) => ( + Some(spawned_agent.thread_id), + Some(spawned_agent.metadata.clone()), + spawned_agent.status.clone(), + ), + Err(_) => (None, None, AgentStatus::NotFound), + }; + let agent_snapshot = match new_thread_id { + Some(thread_id) => { + session + .services + .agent_control + .get_agent_config_snapshot(thread_id) + .await + } + None => None, + }; + let (_new_agent_path, new_agent_nickname, new_agent_role) = + match (&agent_snapshot, new_agent_metadata) { + (Some(snapshot), _) => ( + snapshot.session_source.get_agent_path().map(String::from), + snapshot.session_source.get_nickname(), + snapshot.session_source.get_agent_role(), + ), + (None, Some(metadata)) => ( + metadata.agent_path.map(String::from), + metadata.agent_nickname, + metadata.agent_role, + ), + (None, None) => (None, None, None), + }; + let effective_model = agent_snapshot + .as_ref() + .map(|snapshot| snapshot.model.clone()) + .unwrap_or_else(|| args.model.clone().unwrap_or_default()); + let effective_reasoning_effort = agent_snapshot + .as_ref() + .and_then(|snapshot| snapshot.reasoning_effort) + .unwrap_or(args.reasoning_effort.unwrap_or_default()); + let nickname = new_agent_nickname.clone(); + session + .send_event( + &turn, + CollabAgentSpawnEndEvent { + call_id, + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + new_thread_id, + new_agent_nickname, + new_agent_role, + prompt, + model: effective_model, + reasoning_effort: effective_reasoning_effort, + status, + } + .into(), + ) + .await; + let new_thread_id = result?.thread_id; + let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME); + turn.session_telemetry.counter( + "codex.multi_agent.spawn", + /*inc*/ 1, + &[("role", role_tag)], + ); + + Ok(SpawnAgentResult { + agent_id: new_thread_id.to_string(), + nickname, + }) }) } } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_common.rs b/codex-rs/core/src/tools/handlers/multi_agents_common.rs index c01755cb2b..75f5120c79 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_common.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_common.rs @@ -269,6 +269,7 @@ pub(crate) fn apply_spawn_agent_runtime_overrides( config.permissions.shell_environment_policy = turn.shell_environment_policy.clone(); config.codex_linux_sandbox_exe = turn.codex_linux_sandbox_exe.clone(); config.cwd = turn.cwd.clone(); + config.workspace_roots = turn.workspace_roots.clone(); config .permissions .set_permission_profile(turn.permission_profile()) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 43503be8c1..e7110b2502 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -3176,10 +3176,11 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr let parent_thread_id = parent.thread_id; let parent_session = parent.thread.codex.session.clone(); + let child_turn = parent_session.new_default_turn().await; let child_spawn_output = SpawnAgentHandler::default() .handle(invocation( parent_session.clone(), - parent_session.new_default_turn().await, + child_turn, "spawn_agent", function_payload(json!({"message": "hello child"})), )) diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs index d3a290d363..a0b06eaffe 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs @@ -24,96 +24,101 @@ impl ToolHandler for Handler { matches!(payload, ToolPayload::Function { .. }) } - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - let arguments = function_arguments(payload)?; - let args: CloseAgentArgs = parse_arguments(&arguments)?; - let agent_id = resolve_agent_target(&session, &turn, &args.target).await?; - let receiver_agent = session - .services - .agent_control - .get_agent_metadata(agent_id) - .unwrap_or_default(); - if receiver_agent - .agent_path - .as_ref() - .is_some_and(AgentPath::is_root) - { - return Err(FunctionCallError::RespondToModel( - "root is not a spawned agent".to_string(), - )); - } - session - .send_event( - &turn, - CollabCloseBeginEvent { - call_id: call_id.clone(), - started_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id: agent_id, - } - .into(), - ) - .await; - let status = match session - .services - .agent_control - .subscribe_status(agent_id) - .await - { - Ok(mut status_rx) => status_rx.borrow_and_update().clone(), - Err(err) => { - let status = session.services.agent_control.get_status(agent_id).await; - session - .send_event( - &turn, - CollabCloseEndEvent { - call_id: call_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id: agent_id, - receiver_agent_nickname: receiver_agent.agent_nickname.clone(), - receiver_agent_role: receiver_agent.agent_role.clone(), - status, - } - .into(), - ) - .await; - return Err(collab_agent_error(agent_id, err)); + fn handle( + &self, + invocation: ToolInvocation, + ) -> impl std::future::Future> + Send { + Box::pin(async move { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + let arguments = function_arguments(payload)?; + let args: CloseAgentArgs = parse_arguments(&arguments)?; + let agent_id = resolve_agent_target(&session, &turn, &args.target).await?; + let receiver_agent = session + .services + .agent_control + .get_agent_metadata(agent_id) + .unwrap_or_default(); + if receiver_agent + .agent_path + .as_ref() + .is_some_and(AgentPath::is_root) + { + return Err(FunctionCallError::RespondToModel( + "root is not a spawned agent".to_string(), + )); } - }; - let result = session - .services - .agent_control - .close_agent(agent_id) - .await - .map_err(|err| collab_agent_error(agent_id, err)) - .map(|_| ()); - session - .send_event( - &turn, - CollabCloseEndEvent { - call_id, - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - receiver_thread_id: agent_id, - receiver_agent_nickname: receiver_agent.agent_nickname, - receiver_agent_role: receiver_agent.agent_role, - status: status.clone(), + session + .send_event( + &turn, + CollabCloseBeginEvent { + call_id: call_id.clone(), + started_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id: agent_id, + } + .into(), + ) + .await; + let status = match session + .services + .agent_control + .subscribe_status(agent_id) + .await + { + Ok(mut status_rx) => status_rx.borrow_and_update().clone(), + Err(err) => { + let status = session.services.agent_control.get_status(agent_id).await; + session + .send_event( + &turn, + CollabCloseEndEvent { + call_id: call_id.clone(), + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id: agent_id, + receiver_agent_nickname: receiver_agent.agent_nickname.clone(), + receiver_agent_role: receiver_agent.agent_role.clone(), + status, + } + .into(), + ) + .await; + return Err(collab_agent_error(agent_id, err)); } - .into(), - ) - .await; - result?; + }; + let result = session + .services + .agent_control + .close_agent(agent_id) + .await + .map_err(|err| collab_agent_error(agent_id, err)) + .map(|_| ()); + session + .send_event( + &turn, + CollabCloseEndEvent { + call_id, + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + receiver_thread_id: agent_id, + receiver_agent_nickname: receiver_agent.agent_nickname, + receiver_agent_role: receiver_agent.agent_role, + status: status.clone(), + } + .into(), + ) + .await; + result?; - Ok(CloseAgentResult { - previous_status: status, + Ok(CloseAgentResult { + previous_status: status, + }) }) } } diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index fc44d3df47..34e6f1f195 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -43,188 +43,192 @@ impl ToolHandler for Handler { matches!(payload, ToolPayload::Function { .. }) } - async fn handle(&self, invocation: ToolInvocation) -> Result { - let ToolInvocation { - session, - turn, - payload, - call_id, - .. - } = invocation; - let arguments = function_arguments(payload)?; - let args: SpawnAgentArgs = parse_arguments(&arguments)?; - let fork_mode = args.fork_mode()?; - let role_name = args - .agent_type - .as_deref() - .map(str::trim) - .filter(|role| !role.is_empty()); + fn handle( + &self, + invocation: ToolInvocation, + ) -> impl std::future::Future> + Send { + Box::pin(async move { + let ToolInvocation { + session, + turn, + payload, + call_id, + .. + } = invocation; + let arguments = function_arguments(payload)?; + let args: SpawnAgentArgs = parse_arguments(&arguments)?; + let fork_mode = args.fork_mode()?; + let role_name = args + .agent_type + .as_deref() + .map(str::trim) + .filter(|role| !role.is_empty()); - let initial_operation = parse_collab_input(Some(args.message), /*items*/ None)?; - let prompt = render_input_preview(&initial_operation); + let initial_operation = parse_collab_input(Some(args.message), /*items*/ None)?; + let prompt = render_input_preview(&initial_operation); - let session_source = turn.session_source.clone(); - let child_depth = next_thread_spawn_depth(&session_source); - session - .send_event( - &turn, - CollabAgentSpawnBeginEvent { - call_id: call_id.clone(), - started_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - prompt: prompt.clone(), - model: args.model.clone().unwrap_or_default(), - reasoning_effort: args.reasoning_effort.unwrap_or_default(), - } - .into(), - ) - .await; - let mut config = - build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?; - if matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory)) { - reject_full_fork_spawn_overrides( - role_name, - args.model.as_deref(), - args.reasoning_effort, - )?; - } else { - apply_requested_spawn_agent_model_overrides( - &session, - turn.as_ref(), - &mut config, - args.model.as_deref(), - args.reasoning_effort, - ) - .await?; - apply_role_to_config(&mut config, role_name) - .await - .map_err(FunctionCallError::RespondToModel)?; - } - apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?; - apply_spawn_agent_overrides(&mut config, child_depth); - - let spawn_source = thread_spawn_source( - session.conversation_id, - &turn.session_source, - child_depth, - role_name, - Some(args.task_name.clone()), - )?; - let result = session - .services - .agent_control - .spawn_agent_with_metadata( - config, - match (spawn_source.get_agent_path(), initial_operation) { - (Some(recipient), Op::UserInput { items, .. }) - if items - .iter() - .all(|item| matches!(item, UserInput::Text { .. })) => - { - Op::InterAgentCommunication { - communication: InterAgentCommunication::new( - turn.session_source - .get_agent_path() - .unwrap_or_else(AgentPath::root), - recipient, - Vec::new(), - prompt.clone(), - /*trigger_turn*/ true, - ), - } + let session_source = turn.session_source.clone(); + let child_depth = next_thread_spawn_depth(&session_source); + session + .send_event( + &turn, + CollabAgentSpawnBeginEvent { + call_id: call_id.clone(), + started_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + prompt: prompt.clone(), + model: args.model.clone().unwrap_or_default(), + reasoning_effort: args.reasoning_effort.unwrap_or_default(), } - (_, initial_operation) => initial_operation, - }, - Some(spawn_source), - SpawnAgentOptions { - fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()), - fork_mode, - environments: Some(turn.environments.to_selections()), - }, + .into(), + ) + .await; + let mut config = + build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?; + if matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory)) { + reject_full_fork_spawn_overrides( + role_name, + args.model.as_deref(), + args.reasoning_effort, + )?; + } else { + apply_requested_spawn_agent_model_overrides( + &session, + turn.as_ref(), + &mut config, + args.model.as_deref(), + args.reasoning_effort, + ) + .await?; + apply_role_to_config(&mut config, role_name) + .await + .map_err(FunctionCallError::RespondToModel)?; + } + apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?; + apply_spawn_agent_overrides(&mut config, child_depth); + + let spawn_source = thread_spawn_source( + session.conversation_id, + &turn.session_source, + child_depth, + role_name, + Some(args.task_name.clone()), + )?; + let result = Box::pin( + session.services.agent_control.spawn_agent_with_metadata( + config, + match (spawn_source.get_agent_path(), initial_operation) { + (Some(recipient), Op::UserInput { items, .. }) + if items + .iter() + .all(|item| matches!(item, UserInput::Text { .. })) => + { + Op::InterAgentCommunication { + communication: InterAgentCommunication::new( + turn.session_source + .get_agent_path() + .unwrap_or_else(AgentPath::root), + recipient, + Vec::new(), + prompt.clone(), + /*trigger_turn*/ true, + ), + } + } + (_, initial_operation) => initial_operation, + }, + Some(spawn_source), + SpawnAgentOptions { + fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()), + fork_mode, + environments: Some(turn.environments.to_selections()), + }, + ), ) .await .map_err(collab_spawn_error); - let (new_thread_id, new_agent_metadata, status) = match &result { - Ok(spawned_agent) => ( - Some(spawned_agent.thread_id), - Some(spawned_agent.metadata.clone()), - spawned_agent.status.clone(), - ), - Err(_) => (None, None, AgentStatus::NotFound), - }; - let agent_snapshot = match new_thread_id { - Some(thread_id) => { - session - .services - .agent_control - .get_agent_config_snapshot(thread_id) - .await - } - None => None, - }; - let (new_agent_path, new_agent_nickname, new_agent_role) = - match (&agent_snapshot, new_agent_metadata) { - (Some(snapshot), _) => ( - snapshot.session_source.get_agent_path().map(String::from), - snapshot.session_source.get_nickname(), - snapshot.session_source.get_agent_role(), + let (new_thread_id, new_agent_metadata, status) = match &result { + Ok(spawned_agent) => ( + Some(spawned_agent.thread_id), + Some(spawned_agent.metadata.clone()), + spawned_agent.status.clone(), ), - (None, Some(metadata)) => ( - metadata.agent_path.map(String::from), - metadata.agent_nickname, - metadata.agent_role, - ), - (None, None) => (None, None, None), + Err(_) => (None, None, AgentStatus::NotFound), }; - let effective_model = agent_snapshot - .as_ref() - .map(|snapshot| snapshot.model.clone()) - .unwrap_or_else(|| args.model.clone().unwrap_or_default()); - let effective_reasoning_effort = agent_snapshot - .as_ref() - .and_then(|snapshot| snapshot.reasoning_effort) - .unwrap_or(args.reasoning_effort.unwrap_or_default()); - let nickname = new_agent_nickname.clone(); - session - .send_event( - &turn, - CollabAgentSpawnEndEvent { - call_id, - completed_at_ms: now_unix_timestamp_ms(), - sender_thread_id: session.conversation_id, - new_thread_id, - new_agent_nickname, - new_agent_role, - prompt, - model: effective_model, - reasoning_effort: effective_reasoning_effort, - status, + let agent_snapshot = match new_thread_id { + Some(thread_id) => { + session + .services + .agent_control + .get_agent_config_snapshot(thread_id) + .await } - .into(), - ) - .await; - let _ = result?; - let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME); - turn.session_telemetry.counter( - "codex.multi_agent.spawn", - /*inc*/ 1, - &[("role", role_tag)], - ); - let task_name = new_agent_path.ok_or_else(|| { - FunctionCallError::RespondToModel( - "spawned agent is missing a canonical task name".to_string(), - ) - })?; + None => None, + }; + let (new_agent_path, new_agent_nickname, new_agent_role) = + match (&agent_snapshot, new_agent_metadata) { + (Some(snapshot), _) => ( + snapshot.session_source.get_agent_path().map(String::from), + snapshot.session_source.get_nickname(), + snapshot.session_source.get_agent_role(), + ), + (None, Some(metadata)) => ( + metadata.agent_path.map(String::from), + metadata.agent_nickname, + metadata.agent_role, + ), + (None, None) => (None, None, None), + }; + let effective_model = agent_snapshot + .as_ref() + .map(|snapshot| snapshot.model.clone()) + .unwrap_or_else(|| args.model.clone().unwrap_or_default()); + let effective_reasoning_effort = agent_snapshot + .as_ref() + .and_then(|snapshot| snapshot.reasoning_effort) + .unwrap_or(args.reasoning_effort.unwrap_or_default()); + let nickname = new_agent_nickname.clone(); + session + .send_event( + &turn, + CollabAgentSpawnEndEvent { + call_id, + completed_at_ms: now_unix_timestamp_ms(), + sender_thread_id: session.conversation_id, + new_thread_id, + new_agent_nickname, + new_agent_role, + prompt, + model: effective_model, + reasoning_effort: effective_reasoning_effort, + status, + } + .into(), + ) + .await; + let _ = result?; + let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME); + turn.session_telemetry.counter( + "codex.multi_agent.spawn", + /*inc*/ 1, + &[("role", role_tag)], + ); + let task_name = new_agent_path.ok_or_else(|| { + FunctionCallError::RespondToModel( + "spawned agent is missing a canonical task name".to_string(), + ) + })?; - let hide_agent_metadata = turn.config.multi_agent_v2.hide_spawn_agent_metadata; - if hide_agent_metadata { - Ok(SpawnAgentResult::HiddenMetadata { task_name }) - } else { - Ok(SpawnAgentResult::WithNickname { - task_name, - nickname, - }) - } + let hide_agent_metadata = turn.config.multi_agent_v2.hide_spawn_agent_metadata; + if hide_agent_metadata { + Ok(SpawnAgentResult::HiddenMetadata { task_name }) + } else { + Ok(SpawnAgentResult::WithNickname { + task_name, + nickname, + }) + } + }) } } diff --git a/codex-rs/core/src/tools/handlers/view_image.rs b/codex-rs/core/src/tools/handlers/view_image.rs index d52a844159..6e4a25c0a0 100644 --- a/codex-rs/core/src/tools/handlers/view_image.rs +++ b/codex-rs/core/src/tools/handlers/view_image.rs @@ -17,6 +17,7 @@ use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; use crate::tools::handlers::parse_arguments; +use crate::tools::handlers::resolve_tool_environment; use crate::tools::handlers::view_image_spec::ViewImageToolOptions; use crate::tools::handlers::view_image_spec::create_view_image_tool; use crate::tools::registry::ToolHandler; @@ -33,6 +34,7 @@ impl Default for ViewImageHandler { Self { options: ViewImageToolOptions { can_request_original_image_detail: false, + include_environment_id: false, }, } } @@ -50,6 +52,8 @@ const VIEW_IMAGE_UNSUPPORTED_MESSAGE: &str = #[derive(Deserialize)] struct ViewImageArgs { path: String, + #[serde(default)] + environment_id: Option, detail: Option, } @@ -106,12 +110,16 @@ impl ToolHandler for ViewImageHandler { } }; - let args: ViewImageArgs = parse_arguments(&arguments)?; + let ViewImageArgs { + path, + environment_id, + detail, + } = parse_arguments(&arguments)?; // `view_image` accepts only its documented detail values: omit // `detail` for the default path or set it to `original`. // Other string values remain invalid rather than being silently // reinterpreted. - let detail = match args.detail.as_deref() { + let detail = match detail.as_deref() { None => None, Some("original") => Some(ViewImageDetail::Original), Some(detail) => { @@ -121,20 +129,24 @@ impl ToolHandler for ViewImageHandler { } }; - let abs_path = turn.resolve_path(Some(args.path)); - let Some(environment) = turn.environments.primary() else { + let Some(turn_environment) = + resolve_tool_environment(turn.as_ref(), environment_id.as_deref())? + else { return Err(FunctionCallError::RespondToModel( "view_image is unavailable in this session".to_string(), )); }; - let sandbox = environment - .environment - .is_remote() - .then(|| turn.file_system_sandbox_context(/*additional_permissions*/ None)); + let cwd = turn_environment.cwd.clone(); + let abs_path = cwd.join(path); + let sandbox = turn_environment.environment.is_remote().then(|| { + let mut sandbox = + turn.file_system_sandbox_context(/*additional_permissions*/ None); + sandbox.cwd = Some(cwd.clone()); + sandbox + }); + let fs = turn_environment.environment.get_filesystem(); - let metadata = environment - .environment - .get_filesystem() + let metadata = fs .get_metadata(&abs_path, sandbox.as_ref()) .await .map_err(|error| { @@ -150,9 +162,7 @@ impl ToolHandler for ViewImageHandler { abs_path.display() ))); } - let file_bytes = environment - .environment - .get_filesystem() + let file_bytes = fs .read_file(&abs_path, sandbox.as_ref()) .await .map_err(|error| { diff --git a/codex-rs/core/src/tools/handlers/view_image_spec.rs b/codex-rs/core/src/tools/handlers/view_image_spec.rs index 28953cc9b3..7d1422a037 100644 --- a/codex-rs/core/src/tools/handlers/view_image_spec.rs +++ b/codex-rs/core/src/tools/handlers/view_image_spec.rs @@ -9,6 +9,7 @@ use std::collections::BTreeMap; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ViewImageToolOptions { pub can_request_original_image_detail: bool, + pub include_environment_id: bool, } pub fn create_view_image_tool(options: ViewImageToolOptions) -> ToolSpec { @@ -24,6 +25,15 @@ pub fn create_view_image_tool(options: ViewImageToolOptions) -> ToolSpec { )), ); } + if options.include_environment_id { + properties.insert( + "environment_id".to_string(), + JsonSchema::string(Some( + "Optional selected environment id to target. Omit this to use the primary environment." + .to_string(), + )), + ); + } ToolSpec::Function(ResponsesApiTool { name: VIEW_IMAGE_TOOL_NAME.to_string(), diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index c618d778d6..5bfda3603e 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -83,6 +83,7 @@ impl ToolOrchestrator { enforce_managed_network: attempt.enforce_managed_network, manager: attempt.manager, sandbox_cwd: attempt.sandbox_cwd, + workspace_roots: attempt.workspace_roots, codex_linux_sandbox_exe: attempt.codex_linux_sandbox_exe, use_legacy_landlock: attempt.use_legacy_landlock, windows_sandbox_level: attempt.windows_sandbox_level, @@ -234,6 +235,7 @@ impl ToolOrchestrator { enforce_managed_network: managed_network_active, manager: &self.sandbox, sandbox_cwd, + workspace_roots: &turn_ctx.workspace_roots, codex_linux_sandbox_exe: turn_ctx.codex_linux_sandbox_exe.as_ref(), use_legacy_landlock, windows_sandbox_level: turn_ctx.windows_sandbox_level, @@ -352,6 +354,7 @@ impl ToolOrchestrator { enforce_managed_network: managed_network_active, manager: &self.sandbox, sandbox_cwd, + workspace_roots: &turn_ctx.workspace_roots, codex_linux_sandbox_exe: None, use_legacy_landlock, windows_sandbox_level: turn_ctx.windows_sandbox_level, diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index 1ab249fb0a..c4b7f45490 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -91,6 +91,7 @@ impl ApplyPatchRuntime { Some(FileSystemSandboxContext { permissions, cwd: Some(attempt.sandbox_cwd.clone()), + workspace_roots: attempt.workspace_roots.to_vec(), windows_sandbox_level: attempt.windows_sandbox_level, windows_sandbox_private_desktop: attempt.windows_sandbox_private_desktop, use_legacy_landlock: attempt.use_legacy_landlock, diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index 173fa3e2a0..580d5eab64 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -149,6 +149,7 @@ fn file_system_sandbox_context_uses_active_attempt() { enforce_managed_network: false, manager: &manager, sandbox_cwd: &path, + workspace_roots: std::slice::from_ref(&path), codex_linux_sandbox_exe: None, use_legacy_landlock: true, windows_sandbox_level: WindowsSandboxLevel::RestrictedToken, @@ -201,6 +202,7 @@ fn no_sandbox_attempt_has_no_file_system_context() { enforce_managed_network: false, manager: &manager, sandbox_cwd: &path, + workspace_roots: std::slice::from_ref(&path), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, diff --git a/codex-rs/core/src/tools/runtimes/mod_tests.rs b/codex-rs/core/src/tools/runtimes/mod_tests.rs index fd10f22242..83669a36cb 100644 --- a/codex-rs/core/src/tools/runtimes/mod_tests.rs +++ b/codex-rs/core/src/tools/runtimes/mod_tests.rs @@ -111,6 +111,7 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow:: enforce_managed_network: false, manager: &manager, sandbox_cwd: &cwd, + workspace_roots: std::slice::from_ref(&cwd), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index fef8db5ca9..935f118194 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -168,6 +168,7 @@ pub(super) async fn try_run_zsh_fork( windows_sandbox_level, arg0, sandbox_policy_cwd, + workspace_roots: attempt.workspace_roots.to_vec(), codex_linux_sandbox_exe: ctx.turn.codex_linux_sandbox_exe.clone(), use_legacy_landlock: ctx.turn.features.use_legacy_landlock(), }; @@ -232,7 +233,7 @@ pub(super) async fn try_run_zsh_fork( pub(crate) async fn prepare_unified_exec_zsh_fork( req: &crate::tools::runtimes::unified_exec::UnifiedExecRequest, - _attempt: &SandboxAttempt<'_>, + attempt: &SandboxAttempt<'_>, ctx: &ToolCtx, exec_request: ExecRequest, shell_zsh_path: &std::path::Path, @@ -269,6 +270,7 @@ pub(crate) async fn prepare_unified_exec_zsh_fork( windows_sandbox_level: exec_request.windows_sandbox_level, arg0: exec_request.arg0.clone(), sandbox_policy_cwd: exec_request.windows_sandbox_policy_cwd.clone(), + workspace_roots: attempt.workspace_roots.to_vec(), codex_linux_sandbox_exe: ctx.turn.codex_linux_sandbox_exe.clone(), use_legacy_landlock: ctx.turn.features.use_legacy_landlock(), }; @@ -753,6 +755,7 @@ struct CoreShellCommandExecutor { windows_sandbox_level: WindowsSandboxLevel, arg0: Option, sandbox_policy_cwd: AbsolutePathBuf, + workspace_roots: Vec, codex_linux_sandbox_exe: Option, use_legacy_landlock: bool, } @@ -923,6 +926,7 @@ impl CoreShellCommandExecutor { enforce_managed_network: self.network.is_some(), network: self.network.as_ref(), sandbox_policy_cwd: &self.sandbox_policy_cwd, + workspace_roots: &self.workspace_roots, codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.as_deref(), use_legacy_landlock: self.use_legacy_landlock, windows_sandbox_level: self.windows_sandbox_level, diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index c17247beb4..1073d163d3 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -376,6 +376,7 @@ pub(crate) struct SandboxAttempt<'a> { pub enforce_managed_network: bool, pub(crate) manager: &'a SandboxManager, pub(crate) sandbox_cwd: &'a AbsolutePathBuf, + pub(crate) workspace_roots: &'a [AbsolutePathBuf], pub codex_linux_sandbox_exe: Option<&'a std::path::PathBuf>, pub use_legacy_landlock: bool, pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, @@ -398,6 +399,7 @@ impl<'a> SandboxAttempt<'a> { enforce_managed_network: self.enforce_managed_network, network, sandbox_policy_cwd: self.sandbox_cwd, + workspace_roots: self.workspace_roots, codex_linux_sandbox_exe: self .codex_linux_sandbox_exe .map(std::path::PathBuf::as_path), diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index 6445099618..ddad2cbf4e 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -289,8 +289,11 @@ pub fn build_tool_registry_builder( } if config.environment_mode.has_environment() { + let include_environment_id = + matches!(config.environment_mode, ToolEnvironmentMode::Multiple); builder.register_handler(Arc::new(ViewImageHandler::new(ViewImageToolOptions { can_request_original_image_detail: config.can_request_original_image_detail, + include_environment_id, }))); } diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index a77c5c2e19..3fa8797c50 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -129,6 +129,7 @@ fn test_full_toolset_specs_for_gpt5_codex_unified_exec_web_search() { create_image_generation_tool("png"), create_view_image_tool(ViewImageToolOptions { can_request_original_image_detail: config.can_request_original_image_detail, + include_environment_id: false, }), ] { expected.insert(spec.name().to_string(), spec); @@ -628,6 +629,48 @@ fn disabled_environment_omits_environment_backed_tools() { assert_lacks_tool_name(&tools, VIEW_IMAGE_TOOL_NAME); } +#[test] +fn view_image_spec_includes_environment_id_only_for_multiple_selected_environments() { + let model_info = model_info(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &Features::with_defaults(), + image_generation_tool_auth_allowed: true, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + permission_profile: &PermissionProfile::Disabled, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let (single_environment_tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*deferred_mcp_tools*/ None, + &[], + ); + assert_process_tool_environment_id( + &single_environment_tools, + VIEW_IMAGE_TOOL_NAME, + /*expected_present*/ false, + ); + + let multi_environment_config = + tools_config.with_environment_mode(ToolEnvironmentMode::Multiple); + let (multi_environment_tools, _) = build_specs( + &multi_environment_config, + /*mcp_tools*/ None, + /*deferred_mcp_tools*/ None, + &[], + ); + assert_process_tool_environment_id( + &multi_environment_tools, + VIEW_IMAGE_TOOL_NAME, + /*expected_present*/ true, + ); +} + #[test] fn test_build_specs_agent_job_worker_tools_enabled() { let model_info = model_info(); diff --git a/codex-rs/core/tests/common/Cargo.toml b/codex-rs/core/tests/common/Cargo.toml index 8c1a79f02d..e22a287267 100644 --- a/codex-rs/core/tests/common/Cargo.toml +++ b/codex-rs/core/tests/common/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true [lib] path = "lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 7082d26089..dd4f2cdd5a 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -72,6 +72,7 @@ const SUBMIT_TURN_COMPLETE_TIMEOUT: Duration = Duration::from_secs(30); #[derive(Debug)] pub struct TestEnv { environment: codex_exec_server::Environment, + exec_server_url: Option, cwd: AbsolutePathBuf, local_cwd_temp_dir: Option>, remote_container_name: Option, @@ -85,6 +86,7 @@ impl TestEnv { codex_exec_server::Environment::create_for_tests(/*exec_server_url*/ None)?; Ok(Self { environment, + exec_server_url: None, cwd, local_cwd_temp_dir: Some(local_cwd_temp_dir), remote_container_name: None, @@ -99,10 +101,6 @@ impl TestEnv { &self.environment } - pub fn exec_server_url(&self) -> Option<&str> { - self.environment.exec_server_url() - } - fn local_cwd_temp_dir(&self) -> Option> { self.local_cwd_temp_dir.clone() } @@ -122,7 +120,7 @@ pub async fn test_env() -> Result { Some(remote_env) => { let websocket_url = remote_exec_server_url()?; let environment = - codex_exec_server::Environment::create_for_tests(Some(websocket_url))?; + codex_exec_server::Environment::create_for_tests(Some(websocket_url.clone()))?; let cwd = remote_aware_cwd_path(); environment .get_filesystem() @@ -134,6 +132,7 @@ pub async fn test_env() -> Result { .await?; Ok(TestEnv { environment, + exec_server_url: Some(websocket_url), cwd, local_cwd_temp_dir: None, remote_container_name: Some(remote_env.container_name), @@ -384,7 +383,7 @@ impl TestCodexBuilder { let exec_server_url = self .exec_server_url .clone() - .or_else(|| test_env.exec_server_url().map(str::to_owned)); + .or_else(|| test_env.exec_server_url.clone()); let local_runtime_paths = codex_exec_server::ExecServerRuntimePaths::new( std::env::current_exe()?, /*codex_linux_sandbox_exe*/ None, @@ -511,6 +510,7 @@ impl TestCodexBuilder { load_default_config_for_test(home).await }; config.cwd = cwd_override; + config.workspace_roots = vec![config.cwd.clone()]; config.model_provider = model_provider; if let Ok(path) = codex_utils_cargo_bin::cargo_bin("codex") { config.codex_self_exe = Some(path); @@ -535,6 +535,7 @@ impl TestCodexBuilder { for mutator in mutators { mutator(&mut config); } + config.workspace_roots = vec![config.cwd.clone()]; ensure_test_model_catalog(&mut config)?; if config.include_apply_patch_tool { diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 2538c850e3..fdb7f464c5 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -826,7 +826,6 @@ fn scenarios() -> Vec { use AskForApproval::*; let workspace_write = |network_access| SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -2001,7 +2000,6 @@ async fn approving_apply_patch_for_session_skips_future_prompts_for_same_file() let server = start_mock_server().await; let approval_policy = AskForApproval::OnRequest; let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -2757,7 +2755,6 @@ allow_local_binding = true )?; let approval_policy = AskForApproval::OnFailure; let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -3037,7 +3034,6 @@ allow_local_binding = true )?; let approval_policy = AskForApproval::OnFailure; let turn_sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 432b57de9f..d23af820f5 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -764,7 +764,9 @@ async fn includes_session_id_thread_id_and_model_headers_in_request() { let request = resp_mock.single_request(); assert_eq!(request.path(), "/v1/responses"); let request_session_id = request.header("session_id").expect("session_id header"); + let request_session_id_hyphenated = request.header("session-id").expect("session-id header"); let request_thread_id = request.header("thread_id").expect("thread_id header"); + let request_thread_id_hyphenated = request.header("thread-id").expect("thread-id header"); let request_authorization = request .header("authorization") .expect("authorization header"); @@ -776,7 +778,12 @@ async fn includes_session_id_thread_id_and_model_headers_in_request() { let thread_id_string = expected_thread_id.to_string(); assert_eq!(request_session_id, expected_session_id.to_string()); + assert_eq!( + request_session_id_hyphenated, + expected_session_id.to_string() + ); assert_eq!(request_thread_id, thread_id_string.as_str()); + assert_eq!(request_thread_id_hyphenated, thread_id_string.as_str()); assert_eq!(request_originator, originator().value); assert_eq!(request_authorization, "Bearer Test API Key"); assert_eq!( @@ -1038,12 +1045,19 @@ async fn chatgpt_auth_sends_correct_request() { let request_body = request.body_json(); let request_session_id = request.header("session_id").expect("session_id header"); + let request_session_id_hyphenated = request.header("session-id").expect("session-id header"); let request_thread_id = request.header("thread_id").expect("thread_id header"); + let request_thread_id_hyphenated = request.header("thread-id").expect("thread-id header"); let installation_id = std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME)) .expect("read installation id"); assert_eq!(request_session_id, expected_session_id.to_string()); + assert_eq!( + request_session_id_hyphenated, + expected_session_id.to_string() + ); assert_eq!(request_thread_id, expected_thread_id.to_string()); + assert_eq!(request_thread_id_hyphenated, expected_thread_id.to_string()); assert_eq!(request_originator, originator().value); assert_eq!(request_authorization, "Bearer Access Token"); @@ -1680,7 +1694,7 @@ async fn includes_no_effort_in_request() -> anyhow::Result<()> { .get("reasoning") .and_then(|t| t.get("effort")) .and_then(|v| v.as_str()), - Some("xhigh") + Some("medium") ); Ok(()) @@ -1722,7 +1736,7 @@ async fn includes_default_reasoning_effort_in_request_when_defined_by_model_info .get("reasoning") .and_then(|t| t.get("effort")) .and_then(|v| v.as_str()), - Some("xhigh") + Some("medium") ); Ok(()) diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 796b85ca5e..21fbbd2f58 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -225,6 +225,81 @@ async fn responses_websocket_sends_response_processed_when_feature_enabled() { server.shutdown().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_websocket_sends_response_processed_after_remote_compaction_v2() { + skip_if_no_network!(); + + let server = start_websocket_server(vec![vec![ + vec![ + ev_response_created("resp-prewarm"), + ev_completed("resp-prewarm"), + ], + vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "hi"), + ev_completed("resp-1"), + ], + vec![], + vec![ + json!({ + "type": "response.output_item.done", + "item": { + "type": "context_compaction", + "encrypted_content": "ENCRYPTED_CONTEXT_COMPACTION_SUMMARY", + } + }), + ev_completed("resp-compact"), + ], + vec![], + ]]) + .await; + + let mut builder = test_codex().with_config(|config| { + config + .features + .enable(Feature::RemoteCompactionV2) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::ResponsesWebsocketResponseProcessed) + .expect("test config should allow feature update"); + }); + let test = builder + .build_with_websocket_server(&server) + .await + .expect("build websocket codex"); + + test.submit_turn("hello") + .await + .expect("submission should send response.processed after processing"); + + test.codex + .submit(Op::Compact) + .await + .expect("compact submission should succeed"); + wait_for_event(&test.codex, |msg| matches!(msg, EventMsg::TurnComplete(_))).await; + + let compact_processed = server + .wait_for_request(/*connection_index*/ 0, /*request_index*/ 4) + .await; + assert_eq!( + compact_processed.body_json(), + json!({ + "type": "response.processed", + "response_id": "resp-compact", + }) + ); + + let connection = server.single_connection(); + assert_eq!(connection.len(), 5); + assert_eq!( + connection[3].body_json()["type"].as_str(), + Some("response.create") + ); + + server.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn responses_websocket_omits_response_processed_without_feature() { skip_if_no_network!(); diff --git a/codex-rs/core/tests/suite/compact_remote.rs b/codex-rs/core/tests/suite/compact_remote.rs index 3da841ba79..bec0ea436f 100644 --- a/codex-rs/core/tests/suite/compact_remote.rs +++ b/codex-rs/core/tests/suite/compact_remote.rs @@ -664,15 +664,16 @@ async fn assert_remote_manual_compact_request_parity( } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn remote_manual_compact_api_auth_reuses_prompt_cache_key() -> Result<()> { +async fn remote_manual_compact_api_auth_omits_service_tier_and_reuses_prompt_cache_key() +-> Result<()> { skip_if_no_network!(Ok(())); assert_remote_manual_compact_request_parity( CodexAuth::from_api_key("dummy"), Some(ServiceTier::Fast), - Some("priority"), + /*expected_service_tier*/ None, "remote_manual_compact_api_auth_prompt_cache_key_request_diff", - "After five varied API-key-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields.", + "After five varied API-key-auth turns, remote manual compaction omits service_tier, reuses prompt_cache_key, and still omits responses-only fields.", ) .await?; @@ -689,7 +690,7 @@ async fn remote_manual_compact_chatgpt_auth_reuses_service_tier_and_prompt_cache Some(ServiceTier::Fast), Some("priority"), "remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff", - "After five varied ChatGPT-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields.", + "After five varied ChatGPT-auth turns, remote manual compaction reuses service_tier and prompt_cache_key while omitting responses-only fields.", ) .await?; diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index 923d223e13..b75ec1a6de 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -53,6 +53,7 @@ where params, &PermissionProfile::read_only(), &cwd, + &[], &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index 4d6259a599..bf5b27de8c 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -575,9 +575,13 @@ async fn permissions_message_includes_writable_roots() -> Result<()> { let permissions = permissions_texts(&req.single_request()); let normalize_line_endings = |s: &str| s.replace("\r\n", "\n"); let exec_policy = load_exec_policy(&test.config.config_layer_stack).await?; - let sandbox_policy = test.config.legacy_sandbox_policy(); - let expected = PermissionsInstructions::from_policy( - &sandbox_policy, + let permission_profile = test + .config + .permissions + .permission_profile() + .materialize_project_roots_with_workspace_roots(&test.config.workspace_roots); + let expected = PermissionsInstructions::from_permission_profile( + &permission_profile, AskForApproval::OnRequest, test.config.approvals_reviewer, &exec_policy, diff --git a/codex-rs/core/tests/suite/personality_migration.rs b/codex-rs/core/tests/suite/personality_migration.rs index 0b89a9cfba..f38c2b53f3 100644 --- a/codex-rs/core/tests/suite/personality_migration.rs +++ b/codex-rs/core/tests/suite/personality_migration.rs @@ -63,6 +63,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R forked_from_id: None, timestamp: TEST_TIMESTAMP.to_string(), cwd: std::path::PathBuf::from("."), + workspace_roots: Vec::new(), originator: "test_originator".to_string(), cli_version: "test_version".to_string(), source: SessionSource::Cli, @@ -109,6 +110,7 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re forked_from_id: None, timestamp: TEST_TIMESTAMP.to_string(), cwd: std::path::PathBuf::from("."), + workspace_roots: Vec::new(), originator: "test_originator".to_string(), cli_version: "test_version".to_string(), source: SessionSource::Cli, diff --git a/codex-rs/core/tests/suite/request_permissions.rs b/codex-rs/core/tests/suite/request_permissions.rs index 455c1fabb9..7a8d09f065 100644 --- a/codex-rs/core/tests/suite/request_permissions.rs +++ b/codex-rs/core/tests/suite/request_permissions.rs @@ -285,7 +285,6 @@ async fn expect_request_permissions_event( fn workspace_write_excluding_tmp() -> SandboxPolicy { SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index cb545df351..ea9f2c1808 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -29,6 +29,7 @@ fn resume_history( turn_id: Some(turn_id.clone()), trace_id: None, cwd: config.cwd.to_path_buf(), + workspace_roots: config.workspace_roots.clone(), current_date: None, timezone: None, approval_policy: config.permissions.approval_policy.value(), diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_api_auth_prompt_cache_key_request_diff.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_api_auth_prompt_cache_key_request_diff.snap index 4527899106..750250f86a 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_api_auth_prompt_cache_key_request_diff.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_api_auth_prompt_cache_key_request_diff.snap @@ -2,7 +2,7 @@ source: core/tests/suite/compact_remote.rs expression: "context_snapshot::format_request_body_diff_snapshot(scenario,\n\"Last Normal /responses Request\", &normal_request,\n\"Remote /responses/compact Request\", &compact_request,\n&ContextSnapshotOptions::default(),)" --- -Scenario: After five varied API-key-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields. +Scenario: After five varied API-key-auth turns, remote manual compaction omits service_tier, reuses prompt_cache_key, and still omits responses-only fields. --- Last Normal /responses Request +++ Remote /responses/compact Request @@ -38,6 +38,7 @@ Scenario: After five varied API-key-auth turns, remote manual compaction reuses + ], + "role": "assistant", + "type": "message" +- "service_tier": "priority", - "store": false, - "stream": true, - "tool_choice": "auto", diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff.snap b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff.snap index 40baae2674..e28ddd30d1 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__compact_remote__remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff.snap @@ -2,7 +2,7 @@ source: core/tests/suite/compact_remote.rs expression: "context_snapshot::format_request_body_diff_snapshot(scenario,\n\"Last Normal /responses Request\", &normal_request,\n\"Remote /responses/compact Request\", &compact_request,\n&ContextSnapshotOptions::default(),)" --- -Scenario: After five varied ChatGPT-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields. +Scenario: After five varied ChatGPT-auth turns, remote manual compaction reuses service_tier and prompt_cache_key while omitting responses-only fields. --- Last Normal /responses Request +++ Remote /responses/compact Request diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index 34d60dd4aa..12185c09da 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -142,6 +142,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { forked_from_id: None, timestamp: "2026-01-27T12:00:00Z".to_string(), cwd: codex_home.to_path_buf(), + workspace_roots: Vec::new(), originator: "test".to_string(), cli_version: "test".to_string(), source: SessionSource::default(), diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index b856074540..7ba76eaa4d 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -772,6 +772,20 @@ async fn shell_timeout_includes_timeout_prefix_and_metadata() -> Result<()> { "timeout output missing `command timed out`: {stdout}" ); } else { + let normalized_output = output_str + .replace("\r\n", "\n") + .replace('\r', "\n") + .trim_end_matches('\n') + .to_string(); + + let shell_output_pattern = r"(?s)^Exit code: 124\nWall time: [0-9]+(?:\.[0-9]+)? seconds\nOutput:\ncommand timed out after [0-9]+ milliseconds\n(?:.*)?$"; + if Regex::new(shell_output_pattern) + .expect("shell timeout output regex should compile") + .is_match(&normalized_output) + { + return Ok(()); + } + // Fallback: accept the signal classification path to deflake the test. let signal_pattern = r"(?is)^execution error:.*signal.*$"; assert_regex_match(signal_pattern, output_str); diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 19c2e66730..cf06f94792 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -4,6 +4,9 @@ use anyhow::Context; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_exec_server::CreateDirectoryOptions; +use codex_exec_server::LOCAL_ENVIRONMENT_ID; +use codex_exec_server::REMOTE_ENVIRONMENT_ID; +use codex_exec_server::RemoveOptions; use codex_login::CodexAuth; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::PermissionProfile; @@ -18,13 +21,18 @@ use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; +use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::user_input::UserInput; +use core_test_support::PathBufExt; +use core_test_support::PathExt; +use core_test_support::get_remote_test_env; use core_test_support::responses; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_models_once; +use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; @@ -39,8 +47,13 @@ use image::Rgba; use image::load_from_memory; use pretty_assertions::assert_eq; use serde_json::Value; +use serde_json::json; +use std::fs; use std::io::Cursor; use std::path::PathBuf; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; +use tempfile::TempDir; use tokio::time::Duration; use wiremock::BodyPrintLimit; use wiremock::MockServer; @@ -390,6 +403,179 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn view_image_routes_to_selected_local_environment() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex(); + let test = builder.build(&server).await?; + write_workspace_file( + &test, + "local.png", + png_bytes(/*width*/ 1, /*height*/ 1, [0, 255, 0, 255])?, + ) + .await?; + let call_id = "call-view-image-local-env"; + let response_mock = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_function_call( + call_id, + "view_image", + &json!({ + "path": "local.png", + "environment_id": LOCAL_ENVIRONMENT_ID, + }) + .to_string(), + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + test.submit_turn_with_environments( + "route local view image", + Some(vec![TurnEnvironmentSelection { + environment_id: LOCAL_ENVIRONMENT_ID.to_string(), + cwd: test.config.cwd.clone(), + }]), + ) + .await?; + + let output = response_mock + .last_request() + .context("missing request containing local view_image output")? + .function_call_output(call_id); + let output_items = output + .get("output") + .and_then(Value::as_array) + .context("view_image output should be content items")?; + assert_eq!(output_items.len(), 1); + let image_url = output_items[0] + .get("image_url") + .and_then(Value::as_str) + .context("view_image output should include image_url")?; + assert!( + image_url.starts_with("data:image/png;base64,"), + "unexpected image_url: {image_url}", + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + let Some(_remote_env) = get_remote_test_env() else { + return Ok(()); + }; + + let server = start_mock_server().await; + let mut builder = test_codex(); + let test = builder.build_remote_aware(&server).await?; + let local_cwd = TempDir::new()?; + fs::write(local_cwd.path().join("remote.png"), b"not a remote image")?; + let local_selection = TurnEnvironmentSelection { + environment_id: LOCAL_ENVIRONMENT_ID.to_string(), + cwd: local_cwd.path().abs(), + }; + let remote_cwd = PathBuf::from(format!( + "/tmp/codex-view-image-routing-{}", + SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() + )) + .abs(); + let image_path = remote_cwd.join("remote.png"); + test.fs() + .create_directory( + &remote_cwd, + CreateDirectoryOptions { recursive: true }, + /*sandbox*/ None, + ) + .await?; + let png = BASE64_STANDARD.decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=", + )?; + test.fs() + .write_file(&image_path, png, /*sandbox*/ None) + .await?; + let remote_selection = TurnEnvironmentSelection { + environment_id: REMOTE_ENVIRONMENT_ID.to_string(), + cwd: remote_cwd.clone(), + }; + let call_id = "call-view-image-multi-env"; + let response_mock = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_function_call( + call_id, + "view_image", + &json!({ + "path": "remote.png", + "environment_id": REMOTE_ENVIRONMENT_ID, + }) + .to_string(), + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + test.submit_turn_with_environments( + "route view image", + Some(vec![local_selection, remote_selection]), + ) + .await?; + + let output = response_mock + .last_request() + .context("missing request containing view_image output")? + .function_call_output(call_id) + .clone(); + let output_items = output + .get("output") + .and_then(Value::as_array) + .context("view_image output should be content items")?; + assert_eq!(output_items.len(), 1); + let image_url = output_items[0] + .get("image_url") + .and_then(Value::as_str) + .context("view_image output should include image_url")?; + assert!( + image_url.starts_with("data:image/png;base64,"), + "unexpected image_url: {image_url}", + ); + + test.fs() + .remove( + &remote_cwd, + RemoveOptions { + recursive: true, + force: true, + }, + /*sandbox*/ None, + ) + .await?; + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn view_image_tool_can_preserve_original_resolution_when_requested_on_gpt5_3_codex() -> anyhow::Result<()> { diff --git a/codex-rs/exec-server/BUILD.bazel b/codex-rs/exec-server/BUILD.bazel index 5f3efe6211..224536da8e 100644 --- a/codex-rs/exec-server/BUILD.bazel +++ b/codex-rs/exec-server/BUILD.bazel @@ -3,6 +3,9 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "exec-server", crate_name = "codex_exec_server", + deps_extra = [ + "@crates//:toml", + ], # Keep the crate's integration tests single-threaded under Bazel because # they install process-global test-binary dispatch state, and the remote # exec-server cases already rely on serialization around the full CLI path. diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.toml index 1495397c78..c466a234c1 100644 --- a/codex-rs/exec-server/Cargo.toml +++ b/codex-rs/exec-server/Cargo.toml @@ -28,6 +28,7 @@ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } +toml = { workspace = true } tokio = { workspace = true, features = [ "fs", "io-std", diff --git a/codex-rs/exec-server/src/client.rs b/codex-rs/exec-server/src/client.rs index 47359393d3..ff3cf37904 100644 --- a/codex-rs/exec-server/src/client.rs +++ b/codex-rs/exec-server/src/client.rs @@ -17,13 +17,14 @@ use tokio::sync::mpsc; use tokio::sync::watch; use tokio::time::timeout; -use tokio_tungstenite::connect_async; use tracing::debug; use crate::ProcessId; use crate::client_api::ExecServerClientConnectOptions; +use crate::client_api::ExecServerTransportParams; use crate::client_api::HttpClient; use crate::client_api::RemoteExecServerConnectArgs; +use crate::client_api::StdioExecServerConnectArgs; use crate::connection::JsonRpcConnection; use crate::process::ExecProcessEvent; use crate::process::ExecProcessEventLog; @@ -105,6 +106,16 @@ impl From for ExecServerClientConnectOptions { } } +impl From for ExecServerClientConnectOptions { + fn from(value: StdioExecServerConnectArgs) -> Self { + Self { + client_name: value.client_name, + initialize_timeout: value.initialize_timeout, + resume_session_id: value.resume_session_id, + } + } +} + impl RemoteExecServerConnectArgs { pub fn new(websocket_url: String, client_name: String) -> Self { Self { @@ -180,29 +191,25 @@ pub struct ExecServerClient { #[derive(Clone)] pub(crate) struct LazyRemoteExecServerClient { - websocket_url: String, + transport_params: ExecServerTransportParams, client: Arc>, } impl LazyRemoteExecServerClient { - pub(crate) fn new(websocket_url: String) -> Self { + pub(crate) fn new(transport_params: ExecServerTransportParams) -> Self { Self { - websocket_url, + transport_params, client: Arc::new(OnceCell::new()), } } pub(crate) async fn get(&self) -> Result { self.client - .get_or_try_init(|| async { - ExecServerClient::connect_websocket(RemoteExecServerConnectArgs { - websocket_url: self.websocket_url.clone(), - client_name: "codex-environment".to_string(), - connect_timeout: Duration::from_secs(5), - initialize_timeout: Duration::from_secs(5), - resume_session_id: None, - }) - .await + // TODO: Add reconnect/disconnect handling here instead of reusing + // the first successfully initialized connection forever. + .get_or_try_init(|| { + let transport_params = self.transport_params.clone(); + async move { ExecServerClient::connect_for_transport(transport_params).await } }) .await .cloned() @@ -269,32 +276,6 @@ pub enum ExecServerError { } impl ExecServerClient { - pub async fn connect_websocket( - args: RemoteExecServerConnectArgs, - ) -> Result { - let websocket_url = args.websocket_url.clone(); - let connect_timeout = args.connect_timeout; - let (stream, _) = timeout(connect_timeout, connect_async(websocket_url.as_str())) - .await - .map_err(|_| ExecServerError::WebSocketConnectTimeout { - url: websocket_url.clone(), - timeout: connect_timeout, - })? - .map_err(|source| ExecServerError::WebSocketConnect { - url: websocket_url.clone(), - source, - })?; - - Self::connect( - JsonRpcConnection::from_websocket( - stream, - format!("exec-server websocket {websocket_url}"), - ), - args.into(), - ) - .await - } - pub async fn initialize( &self, options: ExecServerClientConnectOptions, @@ -443,7 +424,7 @@ impl ExecServerClient { .clone() } - async fn connect( + pub(crate) async fn connect( connection: JsonRpcConnection, options: ExecServerClientConnectOptions, ) -> Result { @@ -893,18 +874,30 @@ mod tests { use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use pretty_assertions::assert_eq; + use std::collections::HashMap; + #[cfg(unix)] + use std::path::Path; + #[cfg(unix)] + use std::process::Command; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncWrite; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; use tokio::io::duplex; use tokio::sync::mpsc; + use tokio::sync::oneshot; use tokio::time::Duration; + #[cfg(unix)] + use tokio::time::sleep; use tokio::time::timeout; use super::ExecServerClient; use super::ExecServerClientConnectOptions; use crate::ProcessId; + #[cfg(not(windows))] + use crate::client_api::ExecServerTransportParams; + use crate::client_api::StdioExecServerCommand; + use crate::client_api::StdioExecServerConnectArgs; use crate::connection::JsonRpcConnection; use crate::process::ExecProcessEvent; use crate::protocol::EXEC_CLOSED_METHOD; @@ -942,6 +935,191 @@ mod tests { .expect("json-rpc line should write"); } + #[cfg(not(windows))] + #[tokio::test] + async fn connect_stdio_command_initializes_json_rpc_client() { + let client = ExecServerClient::connect_stdio_command(StdioExecServerConnectArgs { + command: StdioExecServerCommand { + program: "sh".to_string(), + args: vec![ + "-c".to_string(), + "read _line; printf '%s\\n' '{\"id\":1,\"result\":{\"sessionId\":\"stdio-test\"}}'; read _line; sleep 60".to_string(), + ], + env: HashMap::new(), + cwd: None, + }, + client_name: "stdio-test-client".to_string(), + initialize_timeout: Duration::from_secs(1), + resume_session_id: None, + }) + .await + .expect("stdio client should connect"); + + assert_eq!(client.session_id().as_deref(), Some("stdio-test")); + } + + #[cfg(not(windows))] + #[tokio::test] + async fn connect_for_transport_initializes_stdio_command() { + let client = ExecServerClient::connect_for_transport( + ExecServerTransportParams::StdioCommand(StdioExecServerCommand { + program: "sh".to_string(), + args: vec![ + "-c".to_string(), + "read _line; printf '%s\\n' '{\"id\":1,\"result\":{\"sessionId\":\"stdio-test\"}}'; read _line; sleep 60".to_string(), + ], + env: HashMap::new(), + cwd: None, + }), + ) + .await + .expect("stdio transport should connect"); + + assert_eq!(client.session_id().as_deref(), Some("stdio-test")); + } + + #[cfg(windows)] + #[tokio::test] + async fn connect_stdio_command_initializes_json_rpc_client_on_windows() { + let client = ExecServerClient::connect_stdio_command(StdioExecServerConnectArgs { + command: StdioExecServerCommand { + program: "powershell".to_string(), + args: vec![ + "-NoProfile".to_string(), + "-Command".to_string(), + "$null = [Console]::In.ReadLine(); [Console]::Out.WriteLine('{\"id\":1,\"result\":{\"sessionId\":\"stdio-test\"}}'); $null = [Console]::In.ReadLine(); Start-Sleep -Seconds 60".to_string(), + ], + env: HashMap::new(), + cwd: None, + }, + client_name: "stdio-test-client".to_string(), + initialize_timeout: Duration::from_secs(1), + resume_session_id: None, + }) + .await + .expect("stdio client should connect"); + + assert_eq!(client.session_id().as_deref(), Some("stdio-test")); + } + + #[cfg(unix)] + #[tokio::test] + async fn dropping_stdio_client_terminates_spawned_process() { + let tempdir = tempfile::tempdir().expect("tempdir should be created"); + let pid_file = tempdir.path().join("server.pid"); + let child_pid_file = tempdir.path().join("server-child.pid"); + let stdio_script = format!( + "read _line; \ + echo \"$$\" > {}; \ + sleep 60 >/dev/null 2>&1 & echo \"$!\" > {}; \ + printf '%s\\n' '{{\"id\":1,\"result\":{{\"sessionId\":\"stdio-test\"}}}}'; \ + read _line; \ + wait", + shell_quote(pid_file.as_path()), + shell_quote(child_pid_file.as_path()), + ); + + let client = ExecServerClient::connect_stdio_command(StdioExecServerConnectArgs { + command: StdioExecServerCommand { + program: "sh".to_string(), + args: vec!["-c".to_string(), stdio_script], + env: HashMap::new(), + cwd: None, + }, + client_name: "stdio-test-client".to_string(), + initialize_timeout: Duration::from_secs(1), + resume_session_id: None, + }) + .await + .expect("stdio client should connect"); + let server_pid = read_pid_file(pid_file.as_path()).await; + let child_pid = read_pid_file(child_pid_file.as_path()).await; + assert!( + process_exists(server_pid), + "spawned stdio process should be running before client drop" + ); + assert!( + process_exists(child_pid), + "spawned stdio child process should be running before client drop" + ); + + drop(client); + + wait_for_process_exit(server_pid).await; + wait_for_process_exit(child_pid).await; + } + + #[cfg(unix)] + #[tokio::test] + async fn malformed_stdio_message_terminates_spawned_process() { + let tempdir = tempfile::tempdir().expect("tempdir should be created"); + let pid_file = tempdir.path().join("server.pid"); + let stdio_script = format!( + "read _line; \ + echo \"$$\" > {}; \ + printf '%s\\n' 'not-json'; \ + sleep 60", + shell_quote(pid_file.as_path()), + ); + + let result = ExecServerClient::connect_stdio_command(StdioExecServerConnectArgs { + command: StdioExecServerCommand { + program: "sh".to_string(), + args: vec!["-c".to_string(), stdio_script], + env: HashMap::new(), + cwd: None, + }, + client_name: "stdio-test-client".to_string(), + initialize_timeout: Duration::from_secs(1), + resume_session_id: None, + }) + .await; + assert!(result.is_err(), "malformed stdio server should not connect"); + + let server_pid = read_pid_file(pid_file.as_path()).await; + wait_for_process_exit(server_pid).await; + } + + #[cfg(unix)] + async fn read_pid_file(path: &Path) -> u32 { + for _ in 0..20 { + if let Ok(contents) = std::fs::read_to_string(path) { + return contents + .trim() + .parse() + .expect("pid file should contain a pid"); + } + sleep(Duration::from_millis(50)).await; + } + panic!("pid file {} should be written", path.display()); + } + + #[cfg(unix)] + async fn wait_for_process_exit(pid: u32) { + for _ in 0..20 { + if !process_exists(pid) { + return; + } + sleep(Duration::from_millis(100)).await; + } + panic!("process {pid} should exit"); + } + + #[cfg(unix)] + fn process_exists(pid: u32) -> bool { + Command::new("kill") + .arg("-0") + .arg(pid.to_string()) + .status() + .is_ok_and(|status| status.success()) + } + + #[cfg(unix)] + fn shell_quote(path: &Path) -> String { + let value = path.to_string_lossy(); + format!("'{}'", value.replace('\'', "'\\''")) + } + #[tokio::test] async fn process_events_are_delivered_in_seq_order_when_notifications_are_reordered() { let (client_stdin, server_reader) = duplex(1 << 20); @@ -1085,6 +1263,92 @@ mod tests { server.await.expect("server task should finish"); } + #[tokio::test] + async fn transport_disconnect_fails_sessions_and_rejects_new_sessions() { + let (client_stdin, server_reader) = duplex(1 << 20); + let (mut server_writer, client_stdout) = duplex(1 << 20); + let (disconnect_tx, disconnect_rx) = oneshot::channel(); + let server = tokio::spawn(async move { + let mut lines = BufReader::new(server_reader).lines(); + let initialize = read_jsonrpc_line(&mut lines).await; + let request = match initialize { + JSONRPCMessage::Request(request) if request.method == INITIALIZE_METHOD => request, + other => panic!("expected initialize request, got {other:?}"), + }; + write_jsonrpc_line( + &mut server_writer, + JSONRPCMessage::Response(JSONRPCResponse { + id: request.id, + result: serde_json::to_value(InitializeResponse { + session_id: "session-1".to_string(), + }) + .expect("initialize response should serialize"), + }), + ) + .await; + + let initialized = read_jsonrpc_line(&mut lines).await; + match initialized { + JSONRPCMessage::Notification(notification) + if notification.method == INITIALIZED_METHOD => {} + other => panic!("expected initialized notification, got {other:?}"), + } + + let _ = disconnect_rx.await; + drop(server_writer); + }); + + let client = ExecServerClient::connect( + JsonRpcConnection::from_stdio( + client_stdout, + client_stdin, + "test-exec-server-client".to_string(), + ), + ExecServerClientConnectOptions::default(), + ) + .await + .expect("client should connect"); + + let process_id = ProcessId::from("disconnect"); + let session = client + .register_session(&process_id) + .await + .expect("session should register"); + let mut events = session.subscribe_events(); + + disconnect_tx.send(()).expect("disconnect should signal"); + + let event = timeout(Duration::from_secs(1), events.recv()) + .await + .expect("session failure should not time out") + .expect("session event stream should stay open"); + let ExecProcessEvent::Failed(message) = event else { + panic!("expected session failure after disconnect, got {event:?}"); + }; + assert_eq!(message, "exec-server transport disconnected"); + + let response = session + .read( + /*after_seq*/ None, /*max_bytes*/ None, /*wait_ms*/ None, + ) + .await + .expect("disconnected session read should synthesize a response"); + assert_eq!( + response.failure.as_deref(), + Some("exec-server transport disconnected") + ); + assert!(response.closed); + + let new_session = client.register_session(&ProcessId::from("new")).await; + assert!(matches!( + new_session, + Err(super::ExecServerError::Disconnected(_)) + )); + + drop(client); + server.await.expect("server task should finish"); + } + #[tokio::test] async fn wake_notifications_do_not_block_other_sessions() { let (client_stdin, server_reader) = duplex(1 << 20); diff --git a/codex-rs/exec-server/src/client_api.rs b/codex-rs/exec-server/src/client_api.rs index b1761b69f1..8adfadd6e7 100644 --- a/codex-rs/exec-server/src/client_api.rs +++ b/codex-rs/exec-server/src/client_api.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; +use std::path::PathBuf; use std::time::Duration; use futures::future::BoxFuture; @@ -25,6 +27,32 @@ pub struct RemoteExecServerConnectArgs { pub resume_session_id: Option, } +/// Stdio connection arguments for a command-backed exec-server. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct StdioExecServerConnectArgs { + pub command: StdioExecServerCommand, + pub client_name: String, + pub initialize_timeout: Duration, + pub resume_session_id: Option, +} + +/// Structured process command used to start an exec-server over stdio. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct StdioExecServerCommand { + pub program: String, + pub args: Vec, + pub env: HashMap, + pub cwd: Option, +} + +/// Parameters used to connect to a remote exec-server environment. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ExecServerTransportParams { + WebSocketUrl(String), + #[allow(dead_code)] + StdioCommand(StdioExecServerCommand), +} + /// Sends HTTP requests through a runtime-selected transport. /// /// This is the HTTP capability counterpart to [`crate::ExecBackend`]. Callers diff --git a/codex-rs/exec-server/src/client_transport.rs b/codex-rs/exec-server/src/client_transport.rs new file mode 100644 index 0000000000..3fccfa25c5 --- /dev/null +++ b/codex-rs/exec-server/src/client_transport.rs @@ -0,0 +1,127 @@ +use std::process::Stdio; +use std::time::Duration; + +use tokio::io::AsyncBufReadExt; +use tokio::io::BufReader; +use tokio::process::Command; +use tokio::time::timeout; +use tokio_tungstenite::connect_async; +use tracing::debug; +use tracing::warn; + +use crate::ExecServerClient; +use crate::ExecServerError; +use crate::client_api::RemoteExecServerConnectArgs; +use crate::client_api::StdioExecServerCommand; +use crate::client_api::StdioExecServerConnectArgs; +use crate::connection::JsonRpcConnection; + +const ENVIRONMENT_CLIENT_NAME: &str = "codex-environment"; +const ENVIRONMENT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +const ENVIRONMENT_INITIALIZE_TIMEOUT: Duration = Duration::from_secs(5); + +impl ExecServerClient { + pub(crate) async fn connect_for_transport( + transport_params: crate::client_api::ExecServerTransportParams, + ) -> Result { + match transport_params { + crate::client_api::ExecServerTransportParams::WebSocketUrl(websocket_url) => { + Self::connect_websocket(RemoteExecServerConnectArgs { + websocket_url, + client_name: ENVIRONMENT_CLIENT_NAME.to_string(), + connect_timeout: ENVIRONMENT_CONNECT_TIMEOUT, + initialize_timeout: ENVIRONMENT_INITIALIZE_TIMEOUT, + resume_session_id: None, + }) + .await + } + crate::client_api::ExecServerTransportParams::StdioCommand(command) => { + Self::connect_stdio_command(StdioExecServerConnectArgs { + command, + client_name: ENVIRONMENT_CLIENT_NAME.to_string(), + initialize_timeout: ENVIRONMENT_INITIALIZE_TIMEOUT, + resume_session_id: None, + }) + .await + } + } + } + + pub async fn connect_websocket( + args: RemoteExecServerConnectArgs, + ) -> Result { + let websocket_url = args.websocket_url.clone(); + let connect_timeout = args.connect_timeout; + let (stream, _) = timeout(connect_timeout, connect_async(websocket_url.as_str())) + .await + .map_err(|_| ExecServerError::WebSocketConnectTimeout { + url: websocket_url.clone(), + timeout: connect_timeout, + })? + .map_err(|source| ExecServerError::WebSocketConnect { + url: websocket_url.clone(), + source, + })?; + + Self::connect( + JsonRpcConnection::from_websocket( + stream, + format!("exec-server websocket {websocket_url}"), + ), + args.into(), + ) + .await + } + + pub(crate) async fn connect_stdio_command( + args: StdioExecServerConnectArgs, + ) -> Result { + let mut child = stdio_command_process(&args.command) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(ExecServerError::Spawn)?; + + let stdin = child.stdin.take().ok_or_else(|| { + ExecServerError::Protocol("spawned exec-server command has no stdin".to_string()) + })?; + let stdout = child.stdout.take().ok_or_else(|| { + ExecServerError::Protocol("spawned exec-server command has no stdout".to_string()) + })?; + if let Some(stderr) = child.stderr.take() { + tokio::spawn(async move { + let mut lines = BufReader::new(stderr).lines(); + loop { + match lines.next_line().await { + Ok(Some(line)) => debug!("exec-server stdio stderr: {line}"), + Ok(None) => break, + Err(err) => { + warn!("failed to read exec-server stdio stderr: {err}"); + break; + } + } + } + }); + } + + Self::connect( + JsonRpcConnection::from_stdio(stdout, stdin, "exec-server stdio command".to_string()) + .with_child_process(child), + args.into(), + ) + .await + } +} + +fn stdio_command_process(stdio_command: &StdioExecServerCommand) -> Command { + let mut command = Command::new(&stdio_command.program); + command.args(&stdio_command.args); + command.envs(&stdio_command.env); + if let Some(cwd) = &stdio_command.cwd { + command.current_dir(cwd); + } + #[cfg(unix)] + command.process_group(0); + command +} diff --git a/codex-rs/exec-server/src/connection.rs b/codex-rs/exec-server/src/connection.rs index 71f4f31059..c990c89338 100644 --- a/codex-rs/exec-server/src/connection.rs +++ b/codex-rs/exec-server/src/connection.rs @@ -1,12 +1,21 @@ +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::time::Duration; + use codex_app_server_protocol::JSONRPCMessage; use futures::SinkExt; use futures::StreamExt; use tokio::io::AsyncRead; use tokio::io::AsyncWrite; +use tokio::process::Child; use tokio::sync::mpsc; use tokio::sync::watch; +use tokio::time::timeout; use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::tungstenite::Message; +use tracing::debug; +use tracing::warn; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncWriteExt; @@ -14,6 +23,7 @@ use tokio::io::BufReader; use tokio::io::BufWriter; pub(crate) const CHANNEL_CAPACITY: usize = 128; +const STDIO_TERMINATION_GRACE_PERIOD: Duration = Duration::from_secs(2); #[derive(Debug)] pub(crate) enum JsonRpcConnectionEvent { @@ -22,11 +32,186 @@ pub(crate) enum JsonRpcConnectionEvent { Disconnected { reason: Option }, } +#[derive(Clone)] +pub(crate) enum JsonRpcTransport { + Plain, + Stdio { transport: StdioTransport }, +} + +impl JsonRpcTransport { + fn from_child_process(child_process: Child) -> Self { + Self::Stdio { + transport: StdioTransport::spawn(child_process), + } + } + + pub(crate) fn terminate(&self) { + match self { + Self::Plain => {} + Self::Stdio { transport } => transport.terminate(), + } + } +} + +#[derive(Clone)] +pub(crate) struct StdioTransport { + handle: Arc, +} + +struct StdioTransportHandle { + terminate_tx: watch::Sender, + terminate_requested: AtomicBool, +} + +impl StdioTransport { + fn spawn(child_process: Child) -> Self { + let (terminate_tx, terminate_rx) = watch::channel(false); + let handle = Arc::new(StdioTransportHandle { + terminate_tx, + terminate_requested: AtomicBool::new(false), + }); + spawn_stdio_child_supervisor(child_process, terminate_rx); + Self { handle } + } + + fn terminate(&self) { + self.handle.terminate(); + } +} + +impl StdioTransportHandle { + fn terminate(&self) { + if !self.terminate_requested.swap(true, Ordering::AcqRel) { + let _ = self.terminate_tx.send(true); + } + } +} + +impl Drop for StdioTransportHandle { + fn drop(&mut self) { + self.terminate(); + } +} + +fn spawn_stdio_child_supervisor(mut child_process: Child, mut terminate_rx: watch::Receiver) { + let process_group_id = child_process.id(); + tokio::spawn(async move { + tokio::select! { + result = child_process.wait() => { + log_stdio_child_wait_result(result); + kill_process_tree(&mut child_process, process_group_id); + } + () = wait_for_stdio_termination(&mut terminate_rx) => { + terminate_stdio_child(&mut child_process, process_group_id).await; + } + } + }); +} + +async fn wait_for_stdio_termination(terminate_rx: &mut watch::Receiver) { + loop { + if *terminate_rx.borrow() { + return; + } + if terminate_rx.changed().await.is_err() { + return; + } + } +} + +async fn terminate_stdio_child(child_process: &mut Child, process_group_id: Option) { + terminate_process_tree(child_process, process_group_id); + match timeout(STDIO_TERMINATION_GRACE_PERIOD, child_process.wait()).await { + Ok(result) => { + log_stdio_child_wait_result(result); + } + Err(_) => { + kill_process_tree(child_process, process_group_id); + log_stdio_child_wait_result(child_process.wait().await); + } + } +} + +fn terminate_process_tree(child_process: &mut Child, process_group_id: Option) { + let Some(process_group_id) = process_group_id else { + kill_direct_child(child_process, "terminate"); + return; + }; + + #[cfg(unix)] + if let Err(err) = codex_utils_pty::process_group::terminate_process_group(process_group_id) { + warn!("failed to terminate exec-server stdio process group {process_group_id}: {err}"); + kill_direct_child(child_process, "terminate"); + } + + #[cfg(windows)] + if !kill_windows_process_tree(process_group_id) { + kill_direct_child(child_process, "terminate"); + } + + #[cfg(not(any(unix, windows)))] + { + let _ = process_group_id; + kill_direct_child(child_process, "terminate"); + } +} + +fn kill_process_tree(child_process: &mut Child, process_group_id: Option) { + let Some(process_group_id) = process_group_id else { + kill_direct_child(child_process, "kill"); + return; + }; + + #[cfg(unix)] + if let Err(err) = codex_utils_pty::process_group::kill_process_group(process_group_id) { + warn!("failed to kill exec-server stdio process group {process_group_id}: {err}"); + } + + #[cfg(windows)] + if !kill_windows_process_tree(process_group_id) { + kill_direct_child(child_process, "kill"); + } + + #[cfg(not(any(unix, windows)))] + { + let _ = process_group_id; + kill_direct_child(child_process, "kill"); + } +} + +fn kill_direct_child(child_process: &mut Child, action: &str) { + if let Err(err) = child_process.start_kill() { + debug!("failed to {action} exec-server stdio child: {err}"); + } +} + +#[cfg(windows)] +fn kill_windows_process_tree(pid: u32) -> bool { + let pid = pid.to_string(); + match std::process::Command::new("taskkill") + .args(["/PID", pid.as_str(), "/T", "/F"]) + .status() + { + Ok(status) => status.success(), + Err(err) => { + warn!("failed to run taskkill for exec-server stdio process tree {pid}: {err}"); + false + } + } +} + +fn log_stdio_child_wait_result(result: std::io::Result) { + if let Err(err) = result { + debug!("failed to wait for exec-server stdio child: {err}"); + } +} + pub(crate) struct JsonRpcConnection { - outgoing_tx: mpsc::Sender, - incoming_rx: mpsc::Receiver, - disconnected_rx: watch::Receiver, - task_handles: Vec>, + pub(crate) outgoing_tx: mpsc::Sender, + pub(crate) incoming_rx: mpsc::Receiver, + pub(crate) disconnected_rx: watch::Receiver, + pub(crate) task_handles: Vec>, + pub(crate) transport: JsonRpcTransport, } impl JsonRpcConnection { @@ -117,6 +302,7 @@ impl JsonRpcConnection { incoming_rx, disconnected_rx, task_handles: vec![reader_task, writer_task], + transport: JsonRpcTransport::Plain, } } @@ -251,23 +437,13 @@ impl JsonRpcConnection { incoming_rx, disconnected_rx, task_handles: vec![reader_task, writer_task], + transport: JsonRpcTransport::Plain, } } - pub(crate) fn into_parts( - self, - ) -> ( - mpsc::Sender, - mpsc::Receiver, - watch::Receiver, - Vec>, - ) { - ( - self.outgoing_tx, - self.incoming_rx, - self.disconnected_rx, - self.task_handles, - ) + pub(crate) fn with_child_process(mut self, child_process: Child) -> Self { + self.transport = JsonRpcTransport::from_child_process(child_process); + self } } diff --git a/codex-rs/exec-server/src/environment.rs b/codex-rs/exec-server/src/environment.rs index 855989dafb..d13ba6d3bc 100644 --- a/codex-rs/exec-server/src/environment.rs +++ b/codex-rs/exec-server/src/environment.rs @@ -7,9 +7,13 @@ use crate::ExecutorFileSystem; use crate::HttpClient; use crate::client::LazyRemoteExecServerClient; use crate::client::http_client::ReqwestHttpClient; +use crate::client_api::ExecServerTransportParams; use crate::environment_provider::DefaultEnvironmentProvider; +use crate::environment_provider::EnvironmentDefault; use crate::environment_provider::EnvironmentProvider; +use crate::environment_provider::EnvironmentProviderSnapshot; use crate::environment_provider::normalize_exec_server_url; +use crate::environment_toml::environment_provider_from_codex_home; use crate::local_file_system::LocalFileSystem; use crate::local_process::LocalProcess; use crate::process::ExecBackend; @@ -31,8 +35,8 @@ pub const CODEX_EXEC_SERVER_URL_ENV_VAR: &str = "CODEX_EXEC_SERVER_URL"; /// shell/filesystem tool availability. /// /// Remote environments create remote filesystem and execution backends that -/// lazy-connect to the configured exec-server on first use. The websocket is -/// not opened when the manager or environment is constructed. +/// lazy-connect to the configured exec-server on first use. The remote +/// transport is not opened when the manager or environment is constructed. #[derive(Debug)] pub struct EnvironmentManager { default_environment: Option, @@ -71,9 +75,11 @@ impl EnvironmentManager { /// Builds a test-only manager with environment access disabled. pub fn disabled_for_tests(local_runtime_paths: ExecServerRuntimePaths) -> Self { - let mut manager = Self::from_environments(HashMap::new(), local_runtime_paths); - manager.default_environment = None; - manager + Self { + default_environment: None, + environments: HashMap::new(), + local_environment: Arc::new(Environment::local(local_runtime_paths)), + } } /// Builds a test-only manager from a raw exec-server URL value. @@ -94,20 +100,29 @@ impl EnvironmentManager { Self::from_default_provider_url(exec_server_url, local_runtime_paths).await } + /// Builds a manager from `CODEX_HOME` and local runtime paths used when + /// creating local filesystem helpers. + /// + /// If `CODEX_HOME/environments.toml` is present, it defines the configured + /// environments. Otherwise this preserves the legacy + /// `CODEX_EXEC_SERVER_URL` behavior. + pub async fn from_codex_home( + codex_home: impl AsRef, + local_runtime_paths: ExecServerRuntimePaths, + ) -> Result { + let provider = environment_provider_from_codex_home(codex_home.as_ref())?; + Self::from_provider(provider.as_ref(), local_runtime_paths).await + } + async fn from_default_provider_url( exec_server_url: Option, local_runtime_paths: ExecServerRuntimePaths, ) -> Self { - let environment_disabled = normalize_exec_server_url(exec_server_url.clone()).1; let provider = DefaultEnvironmentProvider::new(exec_server_url); - let provider_environments = provider.environments(&local_runtime_paths); - let mut manager = Self::from_environments(provider_environments, local_runtime_paths); - if environment_disabled { - // TODO: Remove this legacy `CODEX_EXEC_SERVER_URL=none` crutch once - // environment attachment defaulting moves out of EnvironmentManager. - manager.default_environment = None; + match Self::from_provider(&provider, local_runtime_paths).await { + Ok(manager) => manager, + Err(err) => panic!("default provider should create valid environments: {err}"), } - manager } /// Builds a manager from a provider-supplied startup snapshot. @@ -118,16 +133,20 @@ impl EnvironmentManager { where P: EnvironmentProvider + ?Sized, { - Self::from_provider_environments( - provider.get_environments(&local_runtime_paths).await?, + Self::from_provider_snapshot( + provider.snapshot(&local_runtime_paths).await?, local_runtime_paths, ) } - fn from_provider_environments( - environments: HashMap, + fn from_provider_snapshot( + snapshot: EnvironmentProviderSnapshot, local_runtime_paths: ExecServerRuntimePaths, ) -> Result { + let EnvironmentProviderSnapshot { + environments, + default, + } = snapshot; for id in environments.keys() { if id.is_empty() { return Err(ExecServerError::Protocol( @@ -136,21 +155,16 @@ impl EnvironmentManager { } } - Ok(Self::from_environments(environments, local_runtime_paths)) - } - - fn from_environments( - environments: HashMap, - local_runtime_paths: ExecServerRuntimePaths, - ) -> Self { - // TODO: Stop deriving a default environment here once omitted - // environment attachment is owned by thread/session setup. - let default_environment = if environments.contains_key(REMOTE_ENVIRONMENT_ID) { - Some(REMOTE_ENVIRONMENT_ID.to_string()) - } else if environments.contains_key(LOCAL_ENVIRONMENT_ID) { - Some(LOCAL_ENVIRONMENT_ID.to_string()) - } else { - None + let default_environment = match default { + EnvironmentDefault::Disabled => None, + EnvironmentDefault::EnvironmentId(environment_id) => { + if !environments.contains_key(&environment_id) { + return Err(ExecServerError::Protocol(format!( + "default environment `{environment_id}` is not configured" + ))); + } + Some(environment_id) + } }; let local_environment = Arc::new(Environment::local(local_runtime_paths)); let environments = environments @@ -158,11 +172,11 @@ impl EnvironmentManager { .map(|(id, environment)| (id, Arc::new(environment))) .collect(); - Self { + Ok(Self { default_environment, environments, local_environment, - } + }) } /// Returns the default environment instance. @@ -195,6 +209,7 @@ impl EnvironmentManager { #[derive(Clone)] pub struct Environment { exec_server_url: Option, + remote_transport: Option, exec_backend: Arc, filesystem: Arc, http_client: Arc, @@ -206,6 +221,7 @@ impl Environment { pub fn default_for_tests() -> Self { Self { exec_server_url: None, + remote_transport: None, exec_backend: Arc::new(LocalProcess::default()), filesystem: Arc::new(LocalFileSystem::unsandboxed()), http_client: Arc::new(ReqwestHttpClient), @@ -261,6 +277,7 @@ impl Environment { pub(crate) fn local(local_runtime_paths: ExecServerRuntimePaths) -> Self { Self { exec_server_url: None, + remote_transport: None, exec_backend: Arc::new(LocalProcess::default()), filesystem: Arc::new(LocalFileSystem::with_runtime_paths( local_runtime_paths.clone(), @@ -274,13 +291,30 @@ impl Environment { exec_server_url: String, local_runtime_paths: Option, ) -> Self { - let client = LazyRemoteExecServerClient::new(exec_server_url.clone()); + Self::remote_with_transport( + ExecServerTransportParams::WebSocketUrl(exec_server_url), + local_runtime_paths, + ) + } + + pub(crate) fn remote_with_transport( + remote_transport: ExecServerTransportParams, + local_runtime_paths: Option, + ) -> Self { + let exec_server_url = match &remote_transport { + ExecServerTransportParams::WebSocketUrl(exec_server_url) => { + Some(exec_server_url.clone()) + } + ExecServerTransportParams::StdioCommand(_) => None, + }; + let client = LazyRemoteExecServerClient::new(remote_transport.clone()); let exec_backend: Arc = Arc::new(RemoteProcess::new(client.clone())); let filesystem: Arc = Arc::new(RemoteFileSystem::new(client.clone())); Self { - exec_server_url: Some(exec_server_url), + exec_server_url, + remote_transport: Some(remote_transport), exec_backend, filesystem, http_client: Arc::new(client), @@ -289,7 +323,7 @@ impl Environment { } pub fn is_remote(&self) -> bool { - self.exec_server_url.is_some() + self.remote_transport.is_some() } /// Returns the remote exec-server URL when this environment is remote. @@ -323,10 +357,28 @@ mod tests { use super::EnvironmentManager; use super::LOCAL_ENVIRONMENT_ID; use super::REMOTE_ENVIRONMENT_ID; + use crate::EnvironmentProvider; + use crate::ExecServerError; use crate::ExecServerRuntimePaths; use crate::ProcessId; + use crate::environment_provider::EnvironmentDefault; + use crate::environment_provider::EnvironmentProviderSnapshot; use pretty_assertions::assert_eq; + struct TestEnvironmentProvider { + snapshot: EnvironmentProviderSnapshot, + } + + #[async_trait::async_trait] + impl EnvironmentProvider for TestEnvironmentProvider { + async fn snapshot( + &self, + _local_runtime_paths: &ExecServerRuntimePaths, + ) -> Result { + Ok(self.snapshot.clone()) + } + } + fn test_runtime_paths() -> ExecServerRuntimePaths { ExecServerRuntimePaths::new( std::env::current_exe().expect("current exe"), @@ -417,15 +469,20 @@ mod tests { } #[tokio::test] - async fn environment_manager_builds_from_provider_environments() { - let manager = EnvironmentManager::from_environments( - HashMap::from([( - REMOTE_ENVIRONMENT_ID.to_string(), - Environment::create_for_tests(Some("ws://127.0.0.1:8765".to_string())) - .expect("remote environment"), - )]), - test_runtime_paths(), - ); + async fn environment_manager_builds_from_provider() { + let provider = TestEnvironmentProvider { + snapshot: EnvironmentProviderSnapshot { + environments: HashMap::from([( + REMOTE_ENVIRONMENT_ID.to_string(), + Environment::create_for_tests(Some("ws://127.0.0.1:8765".to_string())) + .expect("remote environment"), + )]), + default: EnvironmentDefault::EnvironmentId(REMOTE_ENVIRONMENT_ID.to_string()), + }, + }; + let manager = EnvironmentManager::from_provider(&provider, test_runtime_paths()) + .await + .expect("environment manager"); assert_eq!( manager.default_environment_id(), @@ -443,11 +500,15 @@ mod tests { #[tokio::test] async fn environment_manager_rejects_empty_environment_id() { - let err = EnvironmentManager::from_provider_environments( - HashMap::from([("".to_string(), Environment::default_for_tests())]), - test_runtime_paths(), - ) - .expect_err("empty id should fail"); + let provider = TestEnvironmentProvider { + snapshot: EnvironmentProviderSnapshot { + environments: HashMap::from([("".to_string(), Environment::default_for_tests())]), + default: EnvironmentDefault::Disabled, + }, + }; + let err = EnvironmentManager::from_provider(&provider, test_runtime_paths()) + .await + .expect_err("empty id should fail"); assert_eq!( err.to_string(), @@ -455,6 +516,73 @@ mod tests { ); } + #[tokio::test] + async fn environment_manager_uses_explicit_provider_default() { + let provider = TestEnvironmentProvider { + snapshot: EnvironmentProviderSnapshot { + environments: HashMap::from([ + ( + LOCAL_ENVIRONMENT_ID.to_string(), + Environment::default_for_tests(), + ), + ( + "devbox".to_string(), + Environment::create_for_tests(Some("ws://127.0.0.1:8765".to_string())) + .expect("remote environment"), + ), + ]), + default: EnvironmentDefault::EnvironmentId("devbox".to_string()), + }, + }; + let manager = EnvironmentManager::from_provider(&provider, test_runtime_paths()) + .await + .expect("manager"); + + assert_eq!(manager.default_environment_id(), Some("devbox")); + assert!(manager.default_environment().expect("default").is_remote()); + } + + #[tokio::test] + async fn environment_manager_disables_provider_default() { + let provider = TestEnvironmentProvider { + snapshot: EnvironmentProviderSnapshot { + environments: HashMap::from([( + LOCAL_ENVIRONMENT_ID.to_string(), + Environment::default_for_tests(), + )]), + default: EnvironmentDefault::Disabled, + }, + }; + let manager = EnvironmentManager::from_provider(&provider, test_runtime_paths()) + .await + .expect("manager"); + + assert_eq!(manager.default_environment_id(), None); + assert!(manager.default_environment().is_none()); + assert!(manager.get_environment(LOCAL_ENVIRONMENT_ID).is_some()); + } + + #[tokio::test] + async fn environment_manager_rejects_unknown_provider_default() { + let provider = TestEnvironmentProvider { + snapshot: EnvironmentProviderSnapshot { + environments: HashMap::from([( + LOCAL_ENVIRONMENT_ID.to_string(), + Environment::default_for_tests(), + )]), + default: EnvironmentDefault::EnvironmentId("missing".to_string()), + }, + }; + let err = EnvironmentManager::from_provider(&provider, test_runtime_paths()) + .await + .expect_err("unknown default should fail"); + + assert_eq!( + err.to_string(), + "exec-server protocol error: default environment `missing` is not configured" + ); + } + #[tokio::test] async fn environment_manager_uses_provider_supplied_local_environment() { let manager = EnvironmentManager::create_for_tests( diff --git a/codex-rs/exec-server/src/environment_provider.rs b/codex-rs/exec-server/src/environment_provider.rs index 7c8db07e85..0e4bcc5191 100644 --- a/codex-rs/exec-server/src/environment_provider.rs +++ b/codex-rs/exec-server/src/environment_provider.rs @@ -11,16 +11,29 @@ use crate::environment::REMOTE_ENVIRONMENT_ID; /// Lists the concrete environments available to Codex. /// -/// Implementations should return the provider-owned startup snapshot that -/// `EnvironmentManager` will cache. Providers that want the local environment to -/// be addressable by id should include it explicitly in the returned map. +/// Implementations own a startup snapshot containing both the available +/// environment list and default environment selection. Providers that want the +/// local environment to be addressable by id should include it explicitly in +/// the returned map. #[async_trait] pub trait EnvironmentProvider: Send + Sync { - /// Returns the environments available for a new manager. - async fn get_environments( + /// Returns the provider-owned environment startup snapshot. + async fn snapshot( &self, local_runtime_paths: &ExecServerRuntimePaths, - ) -> Result, ExecServerError>; + ) -> Result; +} + +#[derive(Clone, Debug)] +pub struct EnvironmentProviderSnapshot { + pub environments: HashMap, + pub default: EnvironmentDefault, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EnvironmentDefault { + Disabled, + EnvironmentId(String), } /// Default provider backed by `CODEX_EXEC_SERVER_URL`. @@ -40,15 +53,15 @@ impl DefaultEnvironmentProvider { Self::new(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok()) } - pub(crate) fn environments( + pub(crate) fn snapshot_inner( &self, local_runtime_paths: &ExecServerRuntimePaths, - ) -> HashMap { + ) -> EnvironmentProviderSnapshot { let mut environments = HashMap::from([( LOCAL_ENVIRONMENT_ID.to_string(), Environment::local(local_runtime_paths.clone()), )]); - let exec_server_url = normalize_exec_server_url(self.exec_server_url.clone()).0; + let (exec_server_url, disabled) = normalize_exec_server_url(self.exec_server_url.clone()); if let Some(exec_server_url) = exec_server_url { environments.insert( @@ -57,17 +70,28 @@ impl DefaultEnvironmentProvider { ); } - environments + let default = if disabled { + EnvironmentDefault::Disabled + } else if environments.contains_key(REMOTE_ENVIRONMENT_ID) { + EnvironmentDefault::EnvironmentId(REMOTE_ENVIRONMENT_ID.to_string()) + } else { + EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string()) + }; + + EnvironmentProviderSnapshot { + environments, + default, + } } } #[async_trait] impl EnvironmentProvider for DefaultEnvironmentProvider { - async fn get_environments( + async fn snapshot( &self, local_runtime_paths: &ExecServerRuntimePaths, - ) -> Result, ExecServerError> { - Ok(self.environments(local_runtime_paths)) + ) -> Result { + Ok(self.snapshot_inner(local_runtime_paths)) } } @@ -98,10 +122,11 @@ mod tests { async fn default_provider_returns_local_environment_when_url_is_missing() { let provider = DefaultEnvironmentProvider::new(/*exec_server_url*/ None); let runtime_paths = test_runtime_paths(); - let environments = provider - .get_environments(&runtime_paths) + let snapshot = provider + .snapshot(&runtime_paths) .await .expect("environments"); + let environments = snapshot.environments; assert!(!environments[LOCAL_ENVIRONMENT_ID].is_remote()); assert_eq!( @@ -109,42 +134,54 @@ mod tests { Some(&runtime_paths) ); assert!(!environments.contains_key(REMOTE_ENVIRONMENT_ID)); + assert_eq!( + snapshot.default, + EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string()) + ); } #[tokio::test] async fn default_provider_returns_local_environment_when_url_is_empty() { let provider = DefaultEnvironmentProvider::new(Some(String::new())); let runtime_paths = test_runtime_paths(); - let environments = provider - .get_environments(&runtime_paths) + let snapshot = provider + .snapshot(&runtime_paths) .await .expect("environments"); + let environments = snapshot.environments; assert!(!environments[LOCAL_ENVIRONMENT_ID].is_remote()); assert!(!environments.contains_key(REMOTE_ENVIRONMENT_ID)); + assert_eq!( + snapshot.default, + EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string()) + ); } #[tokio::test] async fn default_provider_returns_local_environment_for_none_value() { let provider = DefaultEnvironmentProvider::new(Some("none".to_string())); let runtime_paths = test_runtime_paths(); - let environments = provider - .get_environments(&runtime_paths) + let snapshot = provider + .snapshot(&runtime_paths) .await .expect("environments"); + let environments = snapshot.environments; assert!(!environments[LOCAL_ENVIRONMENT_ID].is_remote()); assert!(!environments.contains_key(REMOTE_ENVIRONMENT_ID)); + assert_eq!(snapshot.default, EnvironmentDefault::Disabled); } #[tokio::test] async fn default_provider_adds_remote_environment_for_websocket_url() { let provider = DefaultEnvironmentProvider::new(Some("ws://127.0.0.1:8765".to_string())); let runtime_paths = test_runtime_paths(); - let environments = provider - .get_environments(&runtime_paths) + let snapshot = provider + .snapshot(&runtime_paths) .await .expect("environments"); + let environments = snapshot.environments; assert!(!environments[LOCAL_ENVIRONMENT_ID].is_remote()); let remote_environment = &environments[REMOTE_ENVIRONMENT_ID]; @@ -153,6 +190,10 @@ mod tests { remote_environment.exec_server_url(), Some("ws://127.0.0.1:8765") ); + assert_eq!( + snapshot.default, + EnvironmentDefault::EnvironmentId(REMOTE_ENVIRONMENT_ID.to_string()) + ); } #[tokio::test] @@ -160,12 +201,12 @@ mod tests { let provider = DefaultEnvironmentProvider::new(Some(" ws://127.0.0.1:8765 ".to_string())); let runtime_paths = test_runtime_paths(); let environments = provider - .get_environments(&runtime_paths) + .snapshot(&runtime_paths) .await .expect("environments"); assert_eq!( - environments[REMOTE_ENVIRONMENT_ID].exec_server_url(), + environments.environments[REMOTE_ENVIRONMENT_ID].exec_server_url(), Some("ws://127.0.0.1:8765") ); } diff --git a/codex-rs/exec-server/src/environment_toml.rs b/codex-rs/exec-server/src/environment_toml.rs new file mode 100644 index 0000000000..99808d7896 --- /dev/null +++ b/codex-rs/exec-server/src/environment_toml.rs @@ -0,0 +1,708 @@ +use std::collections::HashMap; +use std::collections::HashSet; +use std::path::Path; +use std::path::PathBuf; + +use async_trait::async_trait; +use serde::Deserialize; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; + +use crate::DefaultEnvironmentProvider; +use crate::Environment; +use crate::EnvironmentProvider; +use crate::ExecServerError; +use crate::ExecServerRuntimePaths; +use crate::client_api::ExecServerTransportParams; +use crate::client_api::StdioExecServerCommand; +use crate::environment::LOCAL_ENVIRONMENT_ID; +use crate::environment_provider::EnvironmentDefault; +use crate::environment_provider::EnvironmentProviderSnapshot; + +const ENVIRONMENTS_TOML_FILE: &str = "environments.toml"; +const MAX_ENVIRONMENT_ID_LEN: usize = 64; + +#[derive(Deserialize, Debug, Default)] +#[serde(deny_unknown_fields)] +struct EnvironmentsToml { + default: Option, + + #[serde(default)] + environments: Vec, +} + +#[derive(Deserialize, Debug, Default, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct EnvironmentToml { + id: String, + url: Option, + program: Option, + args: Option>, + env: Option>, + cwd: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct TomlEnvironmentProvider { + default: EnvironmentDefault, + environments: HashMap, +} + +impl TomlEnvironmentProvider { + #[cfg(test)] + fn new(config: EnvironmentsToml) -> Result { + Self::new_with_config_dir(config, /*config_dir*/ None) + } + + fn new_with_config_dir( + config: EnvironmentsToml, + config_dir: Option<&Path>, + ) -> Result { + let mut ids = HashSet::from([LOCAL_ENVIRONMENT_ID.to_string()]); + let mut environments = HashMap::with_capacity(config.environments.len()); + for item in config.environments { + let (id, transport) = parse_environment_toml(item, config_dir)?; + if !ids.insert(id.clone()) { + return Err(ExecServerError::Protocol(format!( + "environment id `{id}` is duplicated" + ))); + } + environments.insert(id, transport); + } + let default = normalize_default_environment_id(config.default.as_deref(), &ids)?; + Ok(Self { + default, + environments, + }) + } +} + +#[async_trait] +impl EnvironmentProvider for TomlEnvironmentProvider { + async fn snapshot( + &self, + local_runtime_paths: &ExecServerRuntimePaths, + ) -> Result { + let mut environments = HashMap::from([( + LOCAL_ENVIRONMENT_ID.to_string(), + Environment::local(local_runtime_paths.clone()), + )]); + + for (id, transport_params) in &self.environments { + environments.insert( + id.clone(), + Environment::remote_with_transport( + transport_params.clone(), + Some(local_runtime_paths.clone()), + ), + ); + } + + Ok(EnvironmentProviderSnapshot { + environments, + default: self.default.clone(), + }) + } +} + +fn parse_environment_toml( + item: EnvironmentToml, + config_dir: Option<&Path>, +) -> Result<(String, ExecServerTransportParams), ExecServerError> { + let EnvironmentToml { + id, + url, + program, + args, + env, + cwd, + } = item; + validate_environment_id(&id)?; + if program.is_none() && (args.is_some() || env.is_some() || cwd.is_some()) { + return Err(ExecServerError::Protocol(format!( + "environment `{id}` args, env, and cwd require program" + ))); + } + + let transport_params = match (url, program) { + (Some(url), None) => { + let url = validate_websocket_url(url)?; + ExecServerTransportParams::WebSocketUrl(url) + } + (None, Some(program)) => { + let program = program.trim().to_string(); + if program.is_empty() { + return Err(ExecServerError::Protocol(format!( + "environment `{id}` program cannot be empty" + ))); + } + let cwd = normalize_stdio_cwd(&id, cwd, config_dir)?; + ExecServerTransportParams::StdioCommand(StdioExecServerCommand { + program, + args: args.unwrap_or_default(), + env: env.unwrap_or_default(), + cwd, + }) + } + (None, None) | (Some(_), Some(_)) => { + return Err(ExecServerError::Protocol(format!( + "environment `{id}` must set exactly one of url or program" + ))); + } + }; + + Ok((id, transport_params)) +} + +fn normalize_stdio_cwd( + id: &str, + cwd: Option, + config_dir: Option<&Path>, +) -> Result, ExecServerError> { + let Some(cwd) = cwd else { + return Ok(None); + }; + if cwd.is_absolute() { + return Ok(Some(cwd)); + } + let Some(config_dir) = config_dir else { + return Err(ExecServerError::Protocol(format!( + "environment `{id}` cwd must be absolute" + ))); + }; + Ok(Some(config_dir.join(cwd))) +} + +pub(crate) fn environment_provider_from_codex_home( + codex_home: &Path, +) -> Result, ExecServerError> { + let path = codex_home.join(ENVIRONMENTS_TOML_FILE); + if !path.try_exists().map_err(|err| { + ExecServerError::Protocol(format!( + "failed to inspect environment config `{}`: {err}", + path.display() + )) + })? { + return Ok(Box::new(DefaultEnvironmentProvider::from_env())); + } + + let environments = load_environments_toml(&path)?; + Ok(Box::new(TomlEnvironmentProvider::new_with_config_dir( + environments, + Some(codex_home), + )?)) +} + +fn normalize_default_environment_id( + default: Option<&str>, + ids: &HashSet, +) -> Result { + let Some(default) = default.map(str::trim) else { + return Ok(EnvironmentDefault::EnvironmentId( + LOCAL_ENVIRONMENT_ID.to_string(), + )); + }; + if default.is_empty() { + return Err(ExecServerError::Protocol( + "default environment id cannot be empty".to_string(), + )); + } + if !default.eq_ignore_ascii_case("none") && !ids.contains(default) { + return Err(ExecServerError::Protocol(format!( + "default environment `{default}` is not configured" + ))); + } + if default.eq_ignore_ascii_case("none") { + Ok(EnvironmentDefault::Disabled) + } else { + Ok(EnvironmentDefault::EnvironmentId(default.to_string())) + } +} + +fn validate_environment_id(id: &str) -> Result<(), ExecServerError> { + let trimmed_id = id.trim(); + if trimmed_id.is_empty() { + return Err(ExecServerError::Protocol( + "environment id cannot be empty".to_string(), + )); + } + if trimmed_id != id { + return Err(ExecServerError::Protocol(format!( + "environment id `{id}` must not contain surrounding whitespace" + ))); + } + if id == LOCAL_ENVIRONMENT_ID || id.eq_ignore_ascii_case("none") { + return Err(ExecServerError::Protocol(format!( + "environment id `{id}` is reserved" + ))); + } + if id.len() > MAX_ENVIRONMENT_ID_LEN { + return Err(ExecServerError::Protocol(format!( + "environment id `{id}` cannot be longer than {MAX_ENVIRONMENT_ID_LEN} characters" + ))); + } + if !id + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') + { + return Err(ExecServerError::Protocol(format!( + "environment id `{id}` must contain only ASCII letters, numbers, '-' or '_'" + ))); + } + Ok(()) +} + +fn validate_websocket_url(url: String) -> Result { + let url = url.trim(); + if url.is_empty() { + return Err(ExecServerError::Protocol( + "environment url cannot be empty".to_string(), + )); + } + if !url.starts_with("ws://") && !url.starts_with("wss://") { + return Err(ExecServerError::Protocol(format!( + "environment url `{url}` must use ws:// or wss://" + ))); + } + url.into_client_request().map_err(|err| { + ExecServerError::Protocol(format!("environment url `{url}` is invalid: {err}")) + })?; + Ok(url.to_string()) +} + +fn load_environments_toml(path: &Path) -> Result { + let contents = std::fs::read_to_string(path).map_err(|err| { + ExecServerError::Protocol(format!( + "failed to read environment config `{}`: {err}", + path.display() + )) + })?; + + toml::from_str(&contents).map_err(|err| { + ExecServerError::Protocol(format!( + "failed to parse environment config `{}`: {err}", + path.display() + )) + }) +} + +#[cfg(test)] +mod tests { + use pretty_assertions::assert_eq; + use tempfile::tempdir; + + use super::*; + + fn test_runtime_paths() -> ExecServerRuntimePaths { + ExecServerRuntimePaths::new( + std::env::current_exe().expect("current exe"), + /*codex_linux_sandbox_exe*/ None, + ) + .expect("runtime paths") + } + + #[tokio::test] + async fn toml_provider_adds_implicit_local_and_configured_environments() { + let ssh_transport = ExecServerTransportParams::StdioCommand(StdioExecServerCommand { + program: "ssh".to_string(), + args: vec![ + "dev".to_string(), + "codex exec-server --listen stdio".to_string(), + ], + env: HashMap::from([("CODEX_LOG".to_string(), "debug".to_string())]), + cwd: None, + }); + let provider = TomlEnvironmentProvider::new(EnvironmentsToml { + default: Some("ssh-dev".to_string()), + environments: vec![ + EnvironmentToml { + id: "devbox".to_string(), + url: Some(" ws://127.0.0.1:8765 ".to_string()), + ..Default::default() + }, + EnvironmentToml { + id: "ssh-dev".to_string(), + program: Some(" ssh ".to_string()), + args: Some(vec![ + "dev".to_string(), + "codex exec-server --listen stdio".to_string(), + ]), + env: Some(HashMap::from([( + "CODEX_LOG".to_string(), + "debug".to_string(), + )])), + ..Default::default() + }, + ], + }) + .expect("provider"); + let runtime_paths = test_runtime_paths(); + + let snapshot = provider + .snapshot(&runtime_paths) + .await + .expect("environments"); + let EnvironmentProviderSnapshot { + environments, + default, + } = snapshot; + + assert!(!environments[LOCAL_ENVIRONMENT_ID].is_remote()); + assert_eq!( + environments["devbox"].exec_server_url(), + Some("ws://127.0.0.1:8765") + ); + assert_eq!(provider.environments["ssh-dev"], ssh_transport); + assert!(environments["ssh-dev"].is_remote()); + assert_eq!(environments["ssh-dev"].exec_server_url(), None); + assert_eq!( + default, + EnvironmentDefault::EnvironmentId("ssh-dev".to_string()) + ); + } + + #[tokio::test] + async fn toml_provider_default_omitted_selects_local() { + let provider = TomlEnvironmentProvider::new(EnvironmentsToml::default()).expect("provider"); + let snapshot = provider + .snapshot(&test_runtime_paths()) + .await + .expect("environments"); + + assert_eq!( + snapshot.default, + EnvironmentDefault::EnvironmentId(LOCAL_ENVIRONMENT_ID.to_string()) + ); + } + + #[tokio::test] + async fn toml_provider_default_none_disables_default() { + let provider = TomlEnvironmentProvider::new(EnvironmentsToml { + default: Some("none".to_string()), + environments: Vec::new(), + }) + .expect("provider"); + let snapshot = provider + .snapshot(&test_runtime_paths()) + .await + .expect("environments"); + + assert_eq!(snapshot.default, EnvironmentDefault::Disabled); + } + + #[test] + fn toml_provider_rejects_invalid_environments() { + let cases = [ + ( + EnvironmentToml { + id: "local".to_string(), + url: Some("ws://127.0.0.1:8765".to_string()), + ..Default::default() + }, + "environment id `local` is reserved", + ), + ( + EnvironmentToml { + id: " devbox ".to_string(), + url: Some("ws://127.0.0.1:8765".to_string()), + ..Default::default() + }, + "environment id ` devbox ` must not contain surrounding whitespace", + ), + ( + EnvironmentToml { + id: "dev box".to_string(), + url: Some("ws://127.0.0.1:8765".to_string()), + ..Default::default() + }, + "environment id `dev box` must contain only ASCII letters, numbers, '-' or '_'", + ), + ( + EnvironmentToml { + id: "devbox".to_string(), + url: Some("http://127.0.0.1:8765".to_string()), + ..Default::default() + }, + "environment url `http://127.0.0.1:8765` must use ws:// or wss://", + ), + ( + EnvironmentToml { + id: "devbox".to_string(), + url: Some("ws://127.0.0.1:8765".to_string()), + program: Some("codex".to_string()), + ..Default::default() + }, + "environment `devbox` must set exactly one of url or program", + ), + ( + EnvironmentToml { + id: "devbox".to_string(), + program: Some(" ".to_string()), + ..Default::default() + }, + "environment `devbox` program cannot be empty", + ), + ( + EnvironmentToml { + id: "devbox".to_string(), + args: Some(Vec::new()), + ..Default::default() + }, + "environment `devbox` args, env, and cwd require program", + ), + ]; + + for (item, expected) in cases { + let err = TomlEnvironmentProvider::new(EnvironmentsToml { + default: None, + environments: vec![item], + }) + .expect_err("invalid item should fail"); + + assert_eq!( + err.to_string(), + format!("exec-server protocol error: {expected}") + ); + } + } + + #[test] + fn toml_provider_resolves_relative_stdio_cwd_from_config_dir() { + let config_dir = tempdir().expect("tempdir"); + let provider = TomlEnvironmentProvider::new_with_config_dir( + EnvironmentsToml { + default: None, + environments: vec![EnvironmentToml { + id: "ssh-dev".to_string(), + program: Some("ssh".to_string()), + cwd: Some(PathBuf::from("workspace")), + ..Default::default() + }], + }, + Some(config_dir.path()), + ) + .expect("provider"); + + assert_eq!( + provider.environments["ssh-dev"], + ExecServerTransportParams::StdioCommand(StdioExecServerCommand { + program: "ssh".to_string(), + args: Vec::new(), + env: HashMap::new(), + cwd: Some(config_dir.path().join("workspace")), + }) + ); + } + + #[test] + fn toml_provider_rejects_relative_stdio_cwd_without_config_dir() { + let err = TomlEnvironmentProvider::new(EnvironmentsToml { + default: None, + environments: vec![EnvironmentToml { + id: "ssh-dev".to_string(), + program: Some("ssh".to_string()), + cwd: Some(PathBuf::from("workspace")), + ..Default::default() + }], + }) + .expect_err("relative cwd without config dir should fail"); + + assert_eq!( + err.to_string(), + "exec-server protocol error: environment `ssh-dev` cwd must be absolute" + ); + } + + #[test] + fn toml_provider_rejects_duplicate_ids() { + let err = TomlEnvironmentProvider::new(EnvironmentsToml { + default: None, + environments: vec![ + EnvironmentToml { + id: "devbox".to_string(), + url: Some("ws://127.0.0.1:8765".to_string()), + ..Default::default() + }, + EnvironmentToml { + id: "devbox".to_string(), + program: Some("codex".to_string()), + ..Default::default() + }, + ], + }) + .expect_err("duplicate id should fail"); + + assert_eq!( + err.to_string(), + "exec-server protocol error: environment id `devbox` is duplicated" + ); + } + + #[test] + fn toml_provider_rejects_overlong_id() { + let id = "a".repeat(MAX_ENVIRONMENT_ID_LEN + 1); + let err = TomlEnvironmentProvider::new(EnvironmentsToml { + default: None, + environments: vec![EnvironmentToml { + id: id.clone(), + url: Some("ws://127.0.0.1:8765".to_string()), + ..Default::default() + }], + }) + .expect_err("overlong id should fail"); + + assert_eq!( + err.to_string(), + format!( + "exec-server protocol error: environment id `{id}` cannot be longer than {MAX_ENVIRONMENT_ID_LEN} characters" + ) + ); + } + + #[test] + fn toml_provider_rejects_unknown_default() { + let err = TomlEnvironmentProvider::new(EnvironmentsToml { + default: Some("missing".to_string()), + environments: Vec::new(), + }) + .expect_err("unknown default should fail"); + + assert_eq!( + err.to_string(), + "exec-server protocol error: default environment `missing` is not configured" + ); + } + + #[test] + fn load_environments_toml_reads_root_environment_list() { + let codex_home = tempdir().expect("tempdir"); + let path = codex_home.path().join(ENVIRONMENTS_TOML_FILE); + std::fs::write( + &path, + r#" +default = "ssh-dev" + +[[environments]] +id = "devbox" +url = "ws://127.0.0.1:4512" + +[[environments]] +id = "ssh-dev" +program = "ssh" +args = ["dev", "codex exec-server --listen stdio"] +cwd = "/tmp" +[environments.env] +CODEX_LOG = "debug" +"#, + ) + .expect("write environments.toml"); + + let environments = load_environments_toml(&path).expect("environments.toml"); + + assert_eq!(environments.default.as_deref(), Some("ssh-dev")); + assert_eq!(environments.environments.len(), 2); + assert_eq!(environments.environments[0].id, "devbox"); + assert_eq!( + environments.environments[1], + EnvironmentToml { + id: "ssh-dev".to_string(), + program: Some("ssh".to_string()), + args: Some(vec![ + "dev".to_string(), + "codex exec-server --listen stdio".to_string(), + ]), + env: Some(HashMap::from([( + "CODEX_LOG".to_string(), + "debug".to_string(), + )])), + cwd: Some(PathBuf::from("/tmp")), + ..Default::default() + } + ); + } + + #[test] + fn load_environments_toml_rejects_unknown_fields() { + let codex_home = tempdir().expect("tempdir"); + let cases = [ + ("unknown = true\n", "unknown field `unknown`"), + ( + r#" +[[environments]] +id = "devbox" +url = "ws://127.0.0.1:4512" +unknown = true +"#, + "unknown field `unknown`", + ), + ]; + + for (index, (contents, expected)) in cases.into_iter().enumerate() { + let path = codex_home.path().join(format!("environments-{index}.toml")); + std::fs::write(&path, contents).expect("write environments.toml"); + + let err = load_environments_toml(&path).expect_err("unknown field should fail"); + + assert!( + err.to_string().contains(expected), + "expected `{err}` to contain `{expected}`" + ); + } + } + + #[test] + fn toml_provider_rejects_malformed_websocket_url() { + let err = TomlEnvironmentProvider::new(EnvironmentsToml { + default: None, + environments: vec![EnvironmentToml { + id: "devbox".to_string(), + url: Some("ws://".to_string()), + ..Default::default() + }], + }) + .expect_err("malformed websocket url should fail"); + + assert!( + err.to_string() + .contains("environment url `ws://` is invalid"), + "expected malformed URL error, got `{err}`" + ); + } + + #[tokio::test] + async fn environment_provider_from_codex_home_uses_present_environments_file() { + let codex_home = tempdir().expect("tempdir"); + std::fs::write( + codex_home.path().join(ENVIRONMENTS_TOML_FILE), + r#" +default = "none" +"#, + ) + .expect("write environments.toml"); + + let provider = + environment_provider_from_codex_home(codex_home.path()).expect("environment provider"); + + let snapshot = provider + .snapshot(&test_runtime_paths()) + .await + .expect("environments"); + + assert!(snapshot.environments.contains_key(LOCAL_ENVIRONMENT_ID)); + assert_eq!(snapshot.default, EnvironmentDefault::Disabled); + } + + #[tokio::test] + async fn environment_provider_from_codex_home_falls_back_when_file_is_missing() { + let codex_home = tempdir().expect("tempdir"); + + let provider = + environment_provider_from_codex_home(codex_home.path()).expect("environment provider"); + + let snapshot = provider + .snapshot(&test_runtime_paths()) + .await + .expect("environments"); + + assert!(snapshot.environments.contains_key(LOCAL_ENVIRONMENT_ID)); + } +} diff --git a/codex-rs/exec-server/src/fs_sandbox.rs b/codex-rs/exec-server/src/fs_sandbox.rs index 76b0f22b2b..887caab53c 100644 --- a/codex-rs/exec-server/src/fs_sandbox.rs +++ b/codex-rs/exec-server/src/fs_sandbox.rs @@ -109,6 +109,7 @@ impl FileSystemSandboxRunner { enforce_managed_network: false, network: None, sandbox_policy_cwd: cwd.as_path(), + workspace_roots: &sandbox_context.workspace_roots, codex_linux_sandbox_exe: self.runtime_paths.codex_linux_sandbox_exe.as_deref(), use_legacy_landlock: sandbox_context.use_legacy_landlock, windows_sandbox_level: sandbox_context.windows_sandbox_level, diff --git a/codex-rs/exec-server/src/lib.rs b/codex-rs/exec-server/src/lib.rs index d860d59aba..85de8258f2 100644 --- a/codex-rs/exec-server/src/lib.rs +++ b/codex-rs/exec-server/src/lib.rs @@ -1,8 +1,10 @@ mod client; mod client_api; +mod client_transport; mod connection; mod environment; mod environment_provider; +mod environment_toml; mod fs_helper; mod fs_helper_main; mod fs_sandbox; diff --git a/codex-rs/exec-server/src/rpc.rs b/codex-rs/exec-server/src/rpc.rs index 723b99f502..e4f2ff554a 100644 --- a/codex-rs/exec-server/src/rpc.rs +++ b/codex-rs/exec-server/src/rpc.rs @@ -23,6 +23,7 @@ use tokio::task::JoinHandle; use crate::connection::JsonRpcConnection; use crate::connection::JsonRpcConnectionEvent; +use crate::connection::JsonRpcTransport; #[derive(Debug)] pub(crate) enum RpcCallError { @@ -58,11 +59,9 @@ pub(crate) enum RpcServerOutboundMessage { request_id: RequestId, error: JSONRPCErrorError, }, - #[allow(dead_code)] Notification(JSONRPCNotification), } -#[allow(dead_code)] #[derive(Clone)] pub(crate) struct RpcNotificationSender { outgoing_tx: mpsc::Sender, @@ -84,7 +83,6 @@ impl RpcNotificationSender { .map_err(|_| internal_error("RPC connection closed while sending response".into())) } - #[allow(dead_code)] pub(crate) async fn notify( &self, method: &str, @@ -229,43 +227,55 @@ pub(crate) struct RpcClient { disconnected_rx: watch::Receiver, next_request_id: AtomicI64, transport_tasks: Vec>, + transport: JsonRpcTransport, reader_task: JoinHandle<()>, } impl RpcClient { pub(crate) fn new(connection: JsonRpcConnection) -> (Self, mpsc::Receiver) { - let (write_tx, mut incoming_rx, disconnected_rx, transport_tasks) = connection.into_parts(); + let JsonRpcConnection { + outgoing_tx: write_tx, + mut incoming_rx, + disconnected_rx, + task_handles: transport_tasks, + transport, + } = connection; let pending = Arc::new(Mutex::new(HashMap::::new())); let (event_tx, event_rx) = mpsc::channel(128); let pending_for_reader = Arc::clone(&pending); + let transport_for_reader = transport.clone(); let reader_task = tokio::spawn(async move { - while let Some(event) = incoming_rx.recv().await { + let disconnect_reason = loop { + let Some(event) = incoming_rx.recv().await else { + break None; + }; match event { JsonRpcConnectionEvent::Message(message) => { if let Err(err) = handle_server_message(&pending_for_reader, &event_tx, message).await { let _ = err; - break; + break None; } } JsonRpcConnectionEvent::MalformedMessage { reason } => { let _ = reason; - break; + break None; } JsonRpcConnectionEvent::Disconnected { reason } => { - let _ = event_tx.send(RpcClientEvent::Disconnected { reason }).await; - drain_pending(&pending_for_reader).await; - return; + break reason; } } - } + }; let _ = event_tx - .send(RpcClientEvent::Disconnected { reason: None }) + .send(RpcClientEvent::Disconnected { + reason: disconnect_reason, + }) .await; drain_pending(&pending_for_reader).await; + transport_for_reader.terminate(); }); ( @@ -275,6 +285,7 @@ impl RpcClient { disconnected_rx, next_request_id: AtomicI64::new(1), transport_tasks, + transport, reader_task, }, event_rx, @@ -357,7 +368,6 @@ impl RpcClient { } #[cfg(test)] - #[allow(dead_code)] pub(crate) async fn pending_request_count(&self) -> usize { self.pending.lock().await.len() } @@ -365,6 +375,7 @@ impl RpcClient { impl Drop for RpcClient { fn drop(&mut self) { + self.transport.terminate(); for task in &self.transport_tasks { task.abort(); } @@ -565,11 +576,9 @@ mod tests { async fn rpc_client_matches_out_of_order_responses_by_request_id() { let (client_stdin, server_reader) = tokio::io::duplex(4096); let (mut server_writer, client_stdout) = tokio::io::duplex(4096); - let (client, _events_rx) = RpcClient::new(JsonRpcConnection::from_stdio( - client_stdout, - client_stdin, - "test-rpc".to_string(), - )); + let connection = + JsonRpcConnection::from_stdio(client_stdout, client_stdin, "test-rpc".to_string()); + let (client, _events_rx) = RpcClient::new(connection); let server = tokio::spawn(async move { let mut lines = BufReader::new(server_reader).lines(); diff --git a/codex-rs/exec-server/src/server/processor.rs b/codex-rs/exec-server/src/server/processor.rs index dc1a9b9ffe..6fc0723f0c 100644 --- a/codex-rs/exec-server/src/server/processor.rs +++ b/codex-rs/exec-server/src/server/processor.rs @@ -47,8 +47,13 @@ async fn run_connection( runtime_paths: ExecServerRuntimePaths, ) { let router = Arc::new(build_router()); - let (json_outgoing_tx, mut incoming_rx, mut disconnected_rx, connection_tasks) = - connection.into_parts(); + let JsonRpcConnection { + outgoing_tx: json_outgoing_tx, + mut incoming_rx, + mut disconnected_rx, + task_handles: connection_tasks, + transport: _transport, + } = connection; let (outgoing_tx, mut outgoing_rx) = mpsc::channel::(CHANNEL_CAPACITY); let notifications = RpcNotificationSender::new(outgoing_tx.clone()); diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index 632e479404..546e4e44fb 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" [lib] name = "codex_exec" path = "src/lib.rs" +doctest = false [[test]] name = "all" 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 2465507d0c..92248c19ec 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -219,7 +219,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { session_configured_event: &SessionConfiguredEvent, ) { const VERSION: &str = env!("CARGO_PKG_VERSION"); - eprintln!("OpenAI Codex v{VERSION} (research preview)\n--------"); + eprintln!("OpenAI Codex v{VERSION}\n--------"); for (key, value) in config_summary_entries(config, session_configured_event) { eprintln!("{} {}", format!("{key}:").style(self.bold), value); } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index b035a19517..fc5526ed3d 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -25,7 +25,6 @@ use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::McpServerElicitationAction; use codex_app_server_protocol::McpServerElicitationRequestResponse; -use codex_app_server_protocol::PermissionProfileModificationParams; use codex_app_server_protocol::PermissionProfileSelectionParams; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ReviewStartParams; @@ -82,7 +81,6 @@ use codex_protocol::SessionId; use codex_protocol::ThreadId; use codex_protocol::config_types::SandboxMode; use codex_protocol::models::ActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::ReviewRequest; @@ -423,6 +421,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result show_raw_agent_reasoning: oss.then_some(true), tools_web_search_request: None, ephemeral: ephemeral.then_some(true), + workspace_roots: None, additional_writable_roots: add_dir, }; @@ -773,6 +772,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { responsesapi_client_metadata: None, environments: None, cwd: Some(default_cwd), + workspace_roots: None, approval_policy: Some(default_approval_policy.into()), approvals_reviewer: None, sandbox_policy: None, @@ -944,6 +944,7 @@ fn thread_start_params_from_config(config: &Config) -> ThreadStartParams { model: config.model.clone(), model_provider: Some(config.model_provider_id.clone()), cwd: Some(config.cwd.to_string_lossy().to_string()), + workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(config), sandbox: sandbox.flatten(), @@ -967,6 +968,7 @@ fn thread_resume_params_from_config(config: &Config, thread_id: String) -> Threa model: config.model.clone(), model_provider: Some(config.model_provider_id.clone()), cwd: Some(config.cwd.to_string_lossy().to_string()), + workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(config), sandbox: sandbox.flatten(), @@ -986,19 +988,7 @@ fn permissions_selection_from_config(config: &Config) -> Option PermissionProfileSelectionParams { - let modifications = active - .modifications - .into_iter() - .map(|modification| match modification { - ActivePermissionProfileModification::AdditionalWritableRoot { path } => { - PermissionProfileModificationParams::AdditionalWritableRoot { path } - } - }) - .collect::>(); - PermissionProfileSelectionParams::Profile { - id: active.id, - modifications: (!modifications.is_empty()).then_some(modifications), - } + PermissionProfileSelectionParams::Profile { id: active.id } } fn sandbox_mode_from_permission_profile( @@ -1152,7 +1142,8 @@ fn session_configured_from_thread_response( approvals_reviewer, permission_profile, active_permission_profile, - cwd, + cwd: cwd.clone(), + workspace_roots: vec![cwd], reasoning_effort, initial_messages: None, network_proxy: None, diff --git a/codex-rs/exec/src/lib_tests.rs b/codex-rs/exec/src/lib_tests.rs index c12b483e89..b26e4cf31c 100644 --- a/codex-rs/exec/src/lib_tests.rs +++ b/codex-rs/exec/src/lib_tests.rs @@ -558,11 +558,11 @@ fn sample_thread_start_response() -> ThreadStartResponse { model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp").abs(), + workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: codex_app_server_protocol::AskForApproval::OnRequest, approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::AutoReview, sandbox: codex_app_server_protocol::SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, 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 efda58f412..7b7cb87c8c 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -121,6 +121,7 @@ fn session_configured_produces_thread_started_event() { permission_profile: PermissionProfile::read_only(), active_permission_profile: None, cwd: test_path_buf("/tmp/project").abs(), + workspace_roots: Vec::new(), reasoning_effort: None, initial_messages: None, network_proxy: None, diff --git a/codex-rs/exec/tests/suite/sandbox.rs b/codex-rs/exec/tests/suite/sandbox.rs index feb1a7b8c8..8e9d6b18d8 100644 --- a/codex-rs/exec/tests/suite/sandbox.rs +++ b/codex-rs/exec/tests/suite/sandbox.rs @@ -16,6 +16,7 @@ async fn spawn_command_under_sandbox( command_cwd: AbsolutePathBuf, sandbox_policy: &SandboxPolicy, sandbox_cwd: &AbsolutePathBuf, + additional_workspace_roots: &[AbsolutePathBuf], stdio_policy: StdioPolicy, env: HashMap, ) -> std::io::Result { @@ -28,6 +29,8 @@ async fn spawn_command_under_sandbox( use std::process::Stdio; let codex_linux_sandbox_exe = None; + let mut workspace_roots = vec![sandbox_cwd.clone()]; + workspace_roots.extend_from_slice(additional_workspace_roots); let exec_request = build_exec_request( ExecParams { command, @@ -44,6 +47,7 @@ async fn spawn_command_under_sandbox( }, &PermissionProfile::from_legacy_sandbox_policy(sandbox_policy), sandbox_cwd, + &workspace_roots, &codex_linux_sandbox_exe, /*use_legacy_landlock*/ false, ) @@ -85,6 +89,7 @@ async fn spawn_command_under_sandbox( command_cwd: AbsolutePathBuf, sandbox_policy: &SandboxPolicy, sandbox_cwd: &AbsolutePathBuf, + additional_workspace_roots: &[AbsolutePathBuf], stdio_policy: StdioPolicy, env: HashMap, ) -> std::io::Result { @@ -93,7 +98,10 @@ async fn spawn_command_under_sandbox( let codex_linux_sandbox_exe = core_test_support::find_codex_linux_sandbox_exe() .map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?; - let permission_profile = PermissionProfile::from_legacy_sandbox_policy(sandbox_policy); + let mut workspace_roots = vec![sandbox_cwd.clone()]; + workspace_roots.extend_from_slice(additional_workspace_roots); + let permission_profile = PermissionProfile::from_legacy_sandbox_policy(sandbox_policy) + .materialize_project_roots_with_workspace_roots(&workspace_roots); spawn_command_under_linux_sandbox( codex_linux_sandbox_exe, command, @@ -145,6 +153,7 @@ async fn can_apply_linux_sandbox_policy( command_cwd.clone(), policy, sandbox_cwd, + &[], StdioPolicy::RedirectForShellTool, env, ) @@ -181,7 +190,6 @@ async fn python_multiprocessing_lock_works_under_sandbox() { let writable_roots: Vec = vec!["/dev/shm".try_into().unwrap()]; let policy = SandboxPolicy::WorkspaceWrite { - writable_roots, network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -212,6 +220,7 @@ if __name__ == '__main__': command_cwd, &policy, &sandbox_cwd, + &writable_roots, StdioPolicy::Inherit, sandbox_env, ) @@ -255,6 +264,7 @@ async fn python_getpwuid_works_under_sandbox() { command_cwd, &policy, &sandbox_cwd, + &[], StdioPolicy::RedirectForShellTool, sandbox_env, ) @@ -295,7 +305,6 @@ async fn sandbox_distinguishes_command_and_policy_cwds() { // writable only because it is under the sandbox policy cwd, not because it // is under a writable root. let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -311,6 +320,7 @@ async fn sandbox_distinguishes_command_and_policy_cwds() { command_root.clone(), &policy, &canonical_sandbox_root, + &[], StdioPolicy::Inherit, sandbox_env.clone(), ) @@ -342,6 +352,7 @@ async fn sandbox_distinguishes_command_and_policy_cwds() { command_root, &policy, &canonical_sandbox_root, + &[], StdioPolicy::Inherit, sandbox_env, ) @@ -376,7 +387,6 @@ async fn sandbox_blocks_first_time_dot_codex_creation() { let dot_codex = repo_root.join(".codex"); let config_toml = dot_codex.join("config.toml"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -392,6 +402,7 @@ async fn sandbox_blocks_first_time_dot_codex_creation() { repo_root.clone(), &policy, &repo_root, + &[], StdioPolicy::RedirectForShellTool, sandbox_env, ) @@ -546,6 +557,7 @@ where command_cwd, policy, &sandbox_cwd, + &[], stdio_policy, HashMap::from([("IN_SANDBOX".into(), "1".into())]), ) diff --git a/codex-rs/execpolicy-legacy/Cargo.toml b/codex-rs/execpolicy-legacy/Cargo.toml index 17628a0478..bc0f2c4002 100644 --- a/codex-rs/execpolicy-legacy/Cargo.toml +++ b/codex-rs/execpolicy-legacy/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" [lib] name = "codex_execpolicy_legacy" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/execpolicy/Cargo.toml b/codex-rs/execpolicy/Cargo.toml index 2105ce27d5..b22226a79e 100644 --- a/codex-rs/execpolicy/Cargo.toml +++ b/codex-rs/execpolicy/Cargo.toml @@ -8,6 +8,7 @@ description = "Codex exec policy: prefix-based Starlark rules for command decisi [lib] name = "codex_execpolicy" path = "src/lib.rs" +doctest = false [[bin]] name = "codex-execpolicy" diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 6c8ce49894..721069a5bd 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -818,8 +818,8 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::ApplyPatchFreeform, key: "apply_patch_freeform", - stage: Stage::UnderDevelopment, - default_enabled: false, + stage: Stage::Stable, + default_enabled: true, }, FeatureSpec { id: Feature::ApplyPatchStreamingEvents, diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index 5464fa7a61..55d2d8ba27 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -578,7 +578,7 @@ fn materialize_resolved_enabled_writes_all_features_and_preserves_custom_config( FeatureConfigSource::default(), FeatureOverrides::default(), ); - assert_eq!(replayed.enabled(Feature::ApplyPatchFreeform), false); + assert_eq!(replayed.enabled(Feature::ApplyPatchFreeform), true); } #[test] diff --git a/codex-rs/feedback/Cargo.toml b/codex-rs/feedback/Cargo.toml index 94af597f69..032f0398be 100644 --- a/codex-rs/feedback/Cargo.toml +++ b/codex-rs/feedback/Cargo.toml @@ -17,3 +17,6 @@ tracing-subscriber = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/file-search/Cargo.toml b/codex-rs/file-search/Cargo.toml index 7a62a4a1df..e235898982 100644 --- a/codex-rs/file-search/Cargo.toml +++ b/codex-rs/file-search/Cargo.toml @@ -11,6 +11,7 @@ path = "src/main.rs" [lib] name = "codex_file_search" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/file-system/Cargo.toml b/codex-rs/file-system/Cargo.toml index 63eaccffd2..85e083567b 100644 --- a/codex-rs/file-system/Cargo.toml +++ b/codex-rs/file-system/Cargo.toml @@ -12,3 +12,7 @@ async-trait = { workspace = true } codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } serde = { workspace = true, features = ["derive"] } + +[lib] +test = false +doctest = false diff --git a/codex-rs/file-system/src/lib.rs b/codex-rs/file-system/src/lib.rs index 026523eb2f..97e3a8bf7b 100644 --- a/codex-rs/file-system/src/lib.rs +++ b/codex-rs/file-system/src/lib.rs @@ -50,6 +50,8 @@ pub struct FileSystemSandboxContext { pub permissions: PermissionProfile, #[serde(default, skip_serializing_if = "Option::is_none")] pub cwd: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub workspace_roots: Vec, pub windows_sandbox_level: WindowsSandboxLevel, #[serde(default)] pub windows_sandbox_private_desktop: bool, @@ -77,16 +79,34 @@ impl FileSystemSandboxContext { permissions: PermissionProfile, cwd: AbsolutePathBuf, ) -> Self { - Self::from_permissions_and_cwd(permissions, Some(cwd)) + Self::from_permission_profile_with_workspace_roots(permissions, cwd.clone(), vec![cwd]) } fn from_permissions_and_cwd( permissions: PermissionProfile, cwd: Option, + ) -> Self { + let workspace_roots = cwd.iter().cloned().collect(); + Self::from_permissions_cwd_and_workspace_roots(permissions, cwd, workspace_roots) + } + + pub fn from_permission_profile_with_workspace_roots( + permissions: PermissionProfile, + cwd: AbsolutePathBuf, + workspace_roots: Vec, + ) -> Self { + Self::from_permissions_cwd_and_workspace_roots(permissions, Some(cwd), workspace_roots) + } + + fn from_permissions_cwd_and_workspace_roots( + permissions: PermissionProfile, + cwd: Option, + workspace_roots: Vec, ) -> Self { Self { permissions, cwd, + workspace_roots, windows_sandbox_level: WindowsSandboxLevel::Disabled, windows_sandbox_private_desktop: false, use_legacy_landlock: false, diff --git a/codex-rs/git-utils/Cargo.toml b/codex-rs/git-utils/Cargo.toml index 38616d46ac..9f9c6d0c1d 100644 --- a/codex-rs/git-utils/Cargo.toml +++ b/codex-rs/git-utils/Cargo.toml @@ -33,3 +33,6 @@ walkdir = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/install-context/Cargo.toml b/codex-rs/install-context/Cargo.toml index ce4eeefe77..52938a0812 100644 --- a/codex-rs/install-context/Cargo.toml +++ b/codex-rs/install-context/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_install_context" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/keyring-store/Cargo.toml b/codex-rs/keyring-store/Cargo.toml index dd3686ee59..7a4499687b 100644 --- a/codex-rs/keyring-store/Cargo.toml +++ b/codex-rs/keyring-store/Cargo.toml @@ -22,3 +22,7 @@ keyring = { workspace = true, features = ["windows-native"] } [target.'cfg(any(target_os = "freebsd", target_os = "openbsd"))'.dependencies] keyring = { workspace = true, features = ["sync-secret-service"] } + +[lib] +test = false +doctest = false diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index aaacee27fa..1ae2e6b5f5 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -11,6 +11,7 @@ path = "src/main.rs" [lib] name = "codex_linux_sandbox" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/lmstudio/Cargo.toml b/codex-rs/lmstudio/Cargo.toml index 66ae4dc5f5..e43d0b3bbe 100644 --- a/codex-rs/lmstudio/Cargo.toml +++ b/codex-rs/lmstudio/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_lmstudio" path = "src/lib.rs" +doctest = false [dependencies] diff --git a/codex-rs/login/Cargo.toml b/codex-rs/login/Cargo.toml index 161d1b862c..e914fa0c7a 100644 --- a/codex-rs/login/Cargo.toml +++ b/codex-rs/login/Cargo.toml @@ -52,3 +52,6 @@ regex-lite = { workspace = true } serial_test = { workspace = true } tempfile = { workspace = true } wiremock = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/mcp-server/Cargo.toml b/codex-rs/mcp-server/Cargo.toml index 74873023da..ffe729aae1 100644 --- a/codex-rs/mcp-server/Cargo.toml +++ b/codex-rs/mcp-server/Cargo.toml @@ -11,6 +11,7 @@ path = "src/main.rs" [lib] name = "codex_mcp_server" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index b462022dbc..4e2d5c08e5 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -222,6 +222,7 @@ async fn run_codex_tool_session_inner( let approval_id = ev.effective_approval_id(); let ExecApprovalRequestEvent { turn_id: _, + started_at_ms: _, command, cwd, call_id, @@ -278,6 +279,7 @@ async fn run_codex_tool_session_inner( EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { call_id, turn_id: _, + started_at_ms: _, reason, grant_root, changes, diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index b2882643ce..7d507f24b2 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -309,6 +309,7 @@ mod tests { permission_profile: PermissionProfile::read_only(), active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), + workspace_roots: Vec::new(), reasoning_effort: Some(ReasoningEffort::default()), initial_messages: None, network_proxy: None, @@ -354,6 +355,7 @@ mod tests { permission_profile: PermissionProfile::read_only(), active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), + workspace_roots: Vec::new(), reasoning_effort: Some(ReasoningEffort::default()), initial_messages: None, network_proxy: None, @@ -421,6 +423,7 @@ mod tests { permission_profile: PermissionProfile::read_only(), active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), + workspace_roots: Vec::new(), reasoning_effort: Some(ReasoningEffort::default()), initial_messages: None, network_proxy: None, diff --git a/codex-rs/mcp-server/tests/common/Cargo.toml b/codex-rs/mcp-server/tests/common/Cargo.toml index d642cca824..e97042dd53 100644 --- a/codex-rs/mcp-server/tests/common/Cargo.toml +++ b/codex-rs/mcp-server/tests/common/Cargo.toml @@ -6,6 +6,8 @@ license.workspace = true [lib] path = "lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/memories/mcp/Cargo.toml b/codex-rs/memories/mcp/Cargo.toml index 42789a54dc..847154808c 100644 --- a/codex-rs/memories/mcp/Cargo.toml +++ b/codex-rs/memories/mcp/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_memories_mcp" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/memories/read/Cargo.toml b/codex-rs/memories/read/Cargo.toml index 57aff37d6d..af11826ff2 100644 --- a/codex-rs/memories/read/Cargo.toml +++ b/codex-rs/memories/read/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_memories_read" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/memories/write/Cargo.toml b/codex-rs/memories/write/Cargo.toml index 53d8705964..ebe6b0f2a8 100644 --- a/codex-rs/memories/write/Cargo.toml +++ b/codex-rs/memories/write/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_memories_write" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/memories/write/src/phase2.rs b/codex-rs/memories/write/src/phase2.rs index 7a3841f8c3..7ba92feb23 100644 --- a/codex-rs/memories/write/src/phase2.rs +++ b/codex-rs/memories/write/src/phase2.rs @@ -17,9 +17,15 @@ use codex_config::Constrained; use codex_core::config::Config; use codex_features::Feature; use codex_protocol::ThreadId; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AgentStatus; use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::TokenUsage; use codex_protocol::user_input::UserInput; use codex_state::Stage1Output; @@ -315,18 +321,25 @@ mod agent { .features .disable(Feature::SkillMcpDependencyInstall); - // Sandbox policy - let writable_roots = vec![root]; // The consolidation agent only needs local memory-root write access and no network. - let consolidation_sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots, - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { path: root }, + access: FileSystemAccessMode::Write, + }, + ]); agent_config .permissions - .set_legacy_sandbox_policy(consolidation_sandbox_policy, agent_config.cwd.as_path()) + .set_permission_profile(PermissionProfile::from_runtime_permissions( + &file_system_policy, + NetworkSandboxPolicy::Restricted, + )) .ok()?; agent_config.model = Some( diff --git a/codex-rs/memories/write/src/runtime.rs b/codex-rs/memories/write/src/runtime.rs index 53a10934a5..65e3fa1cc1 100644 --- a/codex-rs/memories/write/src/runtime.rs +++ b/codex-rs/memories/write/src/runtime.rs @@ -174,7 +174,7 @@ impl MemoryStartupContext { let session_source = self.thread.config_snapshot().await.session_source; let model_client = ModelClient::new( Some(Arc::clone(&self.auth_manager)), - SessionId::from(self.thread_id), + SessionId::from(self.thread_id), // We use thread_id to detach this query from the foreground user session. self.thread_id, installation_id, config.model_provider.clone(), diff --git a/codex-rs/message-history/Cargo.toml b/codex-rs/message-history/Cargo.toml index 34bffd687a..b67933d1d7 100644 --- a/codex-rs/message-history/Cargo.toml +++ b/codex-rs/message-history/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_message_history" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/model-provider/src/amazon_bedrock/auth.rs b/codex-rs/model-provider/src/amazon_bedrock/auth.rs index 96c233207f..f3101b0ae9 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/auth.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/auth.rs @@ -20,7 +20,6 @@ use super::mantle::aws_auth_config; use super::mantle::region_from_config; const AWS_BEARER_TOKEN_BEDROCK_ENV_VAR: &str = "AWS_BEARER_TOKEN_BEDROCK"; -const LEGACY_SESSION_ID_HEADER: &str = "session_id"; pub(super) enum BedrockAuthMethod { EnvBearerToken { token: String, region: String }, @@ -87,10 +86,18 @@ fn aws_auth_error_to_auth_error(error: AwsAuthError) -> AuthError { } fn remove_headers_not_preserved_by_bedrock_mantle(headers: &mut HeaderMap) { - // The Bedrock Mantle front door does not preserve this legacy OpenAI header - // for SigV4 verification. Signing it makes the richer Codex agent request - // fail even though raw Responses requests work. - headers.remove(LEGACY_SESSION_ID_HEADER); + // The Bedrock Mantle front door does not preserve legacy OpenAI + // compatibility headers that use snake_case, such as `session_id` and + // `thread_id`, before SigV4 verification. Signing that header class makes + // richer Codex agent requests fail even though raw Responses requests work. + let headers_to_remove = headers + .keys() + .filter(|name| name.as_str().contains('_')) + .cloned() + .collect::>(); + for name in headers_to_remove { + headers.remove(name); + } } /// AWS SigV4 auth provider for Bedrock Mantle OpenAI-compatible requests. @@ -182,10 +189,18 @@ mod tests { } #[test] - fn bedrock_mantle_sigv4_strips_legacy_session_id_header() { + fn bedrock_mantle_sigv4_strips_headers_not_preserved_by_mantle() { let mut headers = HeaderMap::new(); headers.insert( - LEGACY_SESSION_ID_HEADER, + "session_id", + HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"), + ); + headers.insert( + "thread_id", + HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"), + ); + headers.insert( + "future_identity_header", HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"), ); headers.insert( @@ -195,7 +210,9 @@ mod tests { remove_headers_not_preserved_by_bedrock_mantle(&mut headers); - assert!(!headers.contains_key(LEGACY_SESSION_ID_HEADER)); + assert!(!headers.contains_key("session_id")); + assert!(!headers.contains_key("thread_id")); + assert!(!headers.contains_key("future_identity_header")); assert_eq!( headers .get("x-client-request-id") diff --git a/codex-rs/models-manager/models.json b/codex-rs/models-manager/models.json index c025fe36ad..bd57d371b2 100644 --- a/codex-rs/models-manager/models.json +++ b/codex-rs/models-manager/models.json @@ -1,6 +1,6 @@ { "models": [ - { + { "prefer_websockets": true, "support_verbosity": true, "default_verbosity": "low", @@ -82,6 +82,13 @@ "team" ], "supports_search_tool": true, + "service_tiers": [ + { + "id": "priority", + "name": "Fast", + "description": "1.5x speed, increased usage" + } + ], "additional_speed_tiers": [ "fast" ], @@ -111,7 +118,7 @@ "slug": "gpt-5.4", "display_name": "gpt-5.4", "description": "Strong model for everyday coding.", - "default_reasoning_level": "xhigh", + "default_reasoning_level": "medium", "supported_reasoning_levels": [ { "effort": "low", @@ -164,6 +171,18 @@ "team" ], "supports_search_tool": true, + "service_tiers": [ + { + "id": "priority", + "name": "Fast", + "description": "1.5x speed, increased usage" + }, + { + "id": "ultrafast", + "name": "Ultrafast", + "description": "The fastest available responses for latency-sensitive work." + } + ], "additional_speed_tiers": [ "fast" ], @@ -249,6 +268,7 @@ "team" ], "supports_search_tool": true, + "service_tiers": [], "additional_speed_tiers": [], "supports_reasoning_summaries": true }, @@ -332,6 +352,7 @@ "team" ], "supports_search_tool": true, + "service_tiers": [], "additional_speed_tiers": [], "supports_reasoning_summaries": true }, @@ -411,6 +432,7 @@ "team" ], "supports_search_tool": true, + "service_tiers": [], "additional_speed_tiers": [], "supports_reasoning_summaries": true }, @@ -491,6 +513,7 @@ "team" ], "supports_search_tool": true, + "service_tiers": [], "additional_speed_tiers": [], "supports_reasoning_summaries": true } diff --git a/codex-rs/network-proxy/Cargo.toml b/codex-rs/network-proxy/Cargo.toml index 1d9a3375e5..d3a19a41ca 100644 --- a/codex-rs/network-proxy/Cargo.toml +++ b/codex-rs/network-proxy/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_network_proxy" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/ollama/Cargo.toml b/codex-rs/ollama/Cargo.toml index cd6380b83b..5d30fbda28 100644 --- a/codex-rs/ollama/Cargo.toml +++ b/codex-rs/ollama/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_ollama" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/otel/README.md b/codex-rs/otel/README.md index 3739f5f026..afae1b2f03 100644 --- a/codex-rs/otel/README.md +++ b/codex-rs/otel/README.md @@ -39,6 +39,8 @@ let settings = OtelSettings { tls: None, }, metrics_exporter: OtelExporter::None, + span_attributes: std::collections::BTreeMap::new(), + tracestate: std::collections::BTreeMap::new(), }; if let Some(provider) = OtelProvider::from(&settings)? { @@ -49,6 +51,26 @@ if let Some(provider) = OtelProvider::from(&settings)? { } ``` +Configured span attributes and W3C tracestate member fields are applied to +exported trace spans and propagated trace context: + +```toml +[otel.span_attributes] +"example.trace_attr" = "enabled" + +[otel.tracestate.example] +alpha = "one" +beta = "two" +``` + +Configured tracestate members and encoded values must be valid W3C tracestate. +Each nested table is encoded as semicolon-separated `key:value` fields inside +that member. If propagated trace context already has the named member, Codex +upserts configured fields and preserves other fields in that member. This +config shape does not support setting opaque tracestate member values. Invalid +trace metadata entries are ignored during config load and reported as startup +warnings. + ## SessionTelemetry (events) `SessionTelemetry` adds consistent metadata to tracing events and helps record diff --git a/codex-rs/otel/src/config.rs b/codex-rs/otel/src/config.rs index fa088df7d5..ab60ea601e 100644 --- a/codex-rs/otel/src/config.rs +++ b/codex-rs/otel/src/config.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeMap; use std::collections::HashMap; use std::path::PathBuf; @@ -34,6 +35,18 @@ pub(crate) fn resolve_exporter(exporter: &OtelExporter) -> OtelExporter { } } +/// Validates configured span attributes before they are attached to exported spans. +pub fn validate_span_attributes(attributes: &BTreeMap) -> std::io::Result<()> { + if attributes.keys().any(String::is_empty) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "configured span attribute key must not be empty", + )); + } + + Ok(()) +} + #[derive(Clone, Debug)] pub struct OtelSettings { pub environment: String, @@ -44,6 +57,8 @@ pub struct OtelSettings { pub trace_exporter: OtelExporter, pub metrics_exporter: OtelExporter, pub runtime_metrics: bool, + pub span_attributes: BTreeMap, + pub tracestate: BTreeMap>, } /// Resolved Statsig metrics settings that another process can use to recreate diff --git a/codex-rs/otel/src/lib.rs b/codex-rs/otel/src/lib.rs index 431ed331a0..1a689d3684 100644 --- a/codex-rs/otel/src/lib.rs +++ b/codex-rs/otel/src/lib.rs @@ -16,6 +16,7 @@ pub use crate::config::OtelHttpProtocol; pub use crate::config::OtelSettings; pub use crate::config::OtelTlsConfig; pub use crate::config::StatsigMetricsSettings; +pub use crate::config::validate_span_attributes; pub use crate::events::session_telemetry::AuthEnvTelemetryMetadata; pub use crate::events::session_telemetry::SessionTelemetry; pub use crate::events::session_telemetry::SessionTelemetryMetadata; @@ -31,6 +32,8 @@ pub use crate::trace_context::set_parent_from_context; pub use crate::trace_context::set_parent_from_w3c_trace_context; pub use crate::trace_context::span_w3c_trace_context; pub use crate::trace_context::traceparent_context_from_env; +pub use crate::trace_context::validate_tracestate_entries; +pub use crate::trace_context::validate_tracestate_member; pub use codex_utils_string::sanitize_metric_tag_value; #[derive(Debug, Clone, Serialize, Display)] diff --git a/codex-rs/otel/src/provider.rs b/codex-rs/otel/src/provider.rs index 72a1c7c9b5..26f732da71 100644 --- a/codex-rs/otel/src/provider.rs +++ b/codex-rs/otel/src/provider.rs @@ -7,8 +7,10 @@ use crate::metrics::MetricsConfig; use crate::targets::is_log_export_target; use crate::targets::is_trace_safe_target; use gethostname::gethostname; +use opentelemetry::Context; use opentelemetry::KeyValue; use opentelemetry::global; +use opentelemetry::trace::Span as _; use opentelemetry::trace::TracerProvider as _; use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; use opentelemetry_otlp::LogExporter; @@ -22,15 +24,22 @@ use opentelemetry_otlp::WithTonicConfig; use opentelemetry_otlp::tonic_types::metadata::MetadataMap; use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig; use opentelemetry_sdk::Resource; +use opentelemetry_sdk::error::OTelSdkResult; use opentelemetry_sdk::logs::SdkLoggerProvider; use opentelemetry_sdk::propagation::TraceContextPropagator; use opentelemetry_sdk::runtime; use opentelemetry_sdk::trace::BatchSpanProcessor; use opentelemetry_sdk::trace::SdkTracerProvider; +use opentelemetry_sdk::trace::Span; +use opentelemetry_sdk::trace::SpanData; +use opentelemetry_sdk::trace::SpanProcessor; use opentelemetry_sdk::trace::Tracer; +use opentelemetry_sdk::trace::TracerProviderBuilder; use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor as TokioBatchSpanProcessor; use opentelemetry_semantic_conventions as semconv; +use std::collections::BTreeMap; use std::error::Error; +use std::time::Duration; use tracing::debug; use tracing_subscriber::Layer; use tracing_subscriber::registry::LookupSpan; @@ -68,8 +77,26 @@ impl OtelProvider { pub fn from(settings: &OtelSettings) -> Result, Box> { let log_enabled = !matches!(settings.exporter, OtelExporter::None); let trace_enabled = !matches!(settings.trace_exporter, OtelExporter::None); - let metric_exporter = crate::config::resolve_exporter(&settings.metrics_exporter); + let metrics_enabled = !matches!(metric_exporter, OtelExporter::None); + + if !log_enabled && !trace_enabled && !metrics_enabled { + // Tracestate propagation is process-global; clear it when these + // settings do not install an active provider. + crate::trace_context::set_tracestate_entries(BTreeMap::new())?; + debug!("No OTEL exporter enabled in settings."); + return Ok(None); + } + + // Provider setup installs process-global OTEL state that cannot be + // rolled back. Validate trace metadata before any setup path can + // mutate those globals, and keep span attribute checks aligned with + // config loading when traces are exported. + if trace_enabled { + crate::config::validate_span_attributes(&settings.span_attributes)?; + } + crate::trace_context::validate_tracestate_entries(&settings.tracestate)?; + let metrics = if matches!(metric_exporter, OtelExporter::None) { None } else { @@ -85,20 +112,6 @@ impl OtelProvider { Some(MetricsClient::new(config)?) }; - if let Some(metrics) = metrics.as_ref() { - crate::metrics::install_global(metrics.clone()); - if matches!(settings.metrics_exporter, OtelExporter::Statsig) { - crate::metrics::install_global_statsig_settings(StatsigMetricsSettings { - environment: settings.environment.clone(), - }); - } - } - - if !log_enabled && !trace_enabled && metrics.is_none() { - debug!("No OTEL exporter enabled in settings."); - return Ok(None); - } - let log_resource = make_resource(settings, ResourceKind::Logs); let trace_resource = make_resource(settings, ResourceKind::Traces); let logger = log_enabled @@ -106,17 +119,32 @@ impl OtelProvider { .transpose()?; let tracer_provider = trace_enabled - .then(|| build_tracer_provider(&trace_resource, &settings.trace_exporter)) + .then(|| { + build_tracer_provider( + &trace_resource, + &settings.trace_exporter, + settings.span_attributes.clone(), + ) + }) .transpose()?; let tracer = tracer_provider .as_ref() .map(|provider| provider.tracer(settings.service_name.clone())); + crate::trace_context::set_tracestate_entries(settings.tracestate.clone())?; if let Some(provider) = tracer_provider.clone() { global::set_tracer_provider(provider); global::set_text_map_propagator(TraceContextPropagator::new()); } + if let Some(metrics) = metrics.as_ref() { + crate::metrics::install_global(metrics.clone()); + if matches!(settings.metrics_exporter, OtelExporter::Statsig) { + crate::metrics::install_global_statsig_settings(StatsigMetricsSettings { + environment: settings.environment.clone(), + }); + } + } Ok(Some(Self { logger, tracer_provider, @@ -222,6 +250,47 @@ fn normalize_host_name(host_name: &str) -> Option { (!host_name.is_empty()).then(|| host_name.to_owned()) } +fn tracer_provider_builder( + resource: &Resource, + span_attributes: BTreeMap, +) -> TracerProviderBuilder { + let builder = SdkTracerProvider::builder().with_resource(resource.clone()); + if span_attributes.is_empty() { + builder + } else { + builder.with_span_processor(SpanAttributesProcessor { + attributes: span_attributes, + }) + } +} + +/// Applies configured attributes when spans start. +/// +/// Resource attributes describe the provider process. These attributes are +/// per-span metadata, so they need to be attached before each span is exported. +#[derive(Debug)] +struct SpanAttributesProcessor { + attributes: BTreeMap, +} + +impl SpanProcessor for SpanAttributesProcessor { + fn on_start(&self, span: &mut Span, _cx: &Context) { + for (key, value) in self.attributes.iter() { + span.set_attribute(KeyValue::new(key.clone(), value.clone())); + } + } + + fn on_end(&self, _span: SpanData) {} + + fn force_flush(&self) -> OTelSdkResult { + Ok(()) + } + + fn shutdown_with_timeout(&self, _timeout: Duration) -> OTelSdkResult { + Ok(()) + } +} + fn build_logger( resource: &Resource, exporter: &OtelExporter, @@ -294,9 +363,10 @@ fn build_logger( fn build_tracer_provider( resource: &Resource, exporter: &OtelExporter, + span_attributes: BTreeMap, ) -> Result> { let span_exporter = match crate::config::resolve_exporter(exporter) { - OtelExporter::None => return Ok(SdkTracerProvider::builder().build()), + OtelExporter::None => return Ok(tracer_provider_builder(resource, span_attributes).build()), OtelExporter::Statsig => unreachable!("statsig exporter should be resolved"), OtelExporter::OtlpGrpc { endpoint, @@ -353,8 +423,7 @@ fn build_tracer_provider( TokioBatchSpanProcessor::builder(exporter_builder.build()?, runtime::Tokio) .build(); - return Ok(SdkTracerProvider::builder() - .with_resource(resource.clone()) + return Ok(tracer_provider_builder(resource, span_attributes) .with_span_processor(processor) .build()); } @@ -382,8 +451,7 @@ fn build_tracer_provider( let processor = BatchSpanProcessor::builder(span_exporter).build(); - Ok(SdkTracerProvider::builder() - .with_resource(resource.clone()) + Ok(tracer_provider_builder(resource, span_attributes) .with_span_processor(processor) .build()) } @@ -467,6 +535,8 @@ mod tests { trace_exporter: OtelExporter::None, metrics_exporter: OtelExporter::None, runtime_metrics: false, + span_attributes: BTreeMap::new(), + tracestate: BTreeMap::new(), } } } diff --git a/codex-rs/otel/src/trace_context.rs b/codex-rs/otel/src/trace_context.rs index 010078e990..c625a416a7 100644 --- a/codex-rs/otel/src/trace_context.rs +++ b/codex-rs/otel/src/trace_context.rs @@ -1,11 +1,16 @@ +use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::collections::HashMap; use std::env; +use std::str::FromStr; use std::sync::OnceLock; +use std::sync::RwLock; use codex_protocol::protocol::W3cTraceContext; use opentelemetry::Context; use opentelemetry::propagation::TextMapPropagator; use opentelemetry::trace::TraceContextExt; +use opentelemetry::trace::TraceState; use opentelemetry_sdk::propagation::TraceContextPropagator; use tracing::Span; use tracing::debug; @@ -16,6 +21,11 @@ const TRACEPARENT_ENV_VAR: &str = "TRACEPARENT"; const TRACESTATE_ENV_VAR: &str = "TRACESTATE"; static TRACEPARENT_CONTEXT: OnceLock> = OnceLock::new(); +// Trace context propagation can happen outside the provider object, so configured +// tracestate lives beside the process-global tracer provider. +static TRACESTATE_ENTRIES: OnceLock>>> = + OnceLock::new(); + pub fn current_span_w3c_trace_context() -> Option { span_w3c_trace_context(&Span::current()) } @@ -28,13 +38,28 @@ pub fn span_w3c_trace_context(span: &Span) -> Option { let mut headers = HashMap::new(); TraceContextPropagator::new().inject_context(&context, &mut headers); + let tracestate = headers.remove("tracestate"); + let configured_tracestate_guard = tracestate_entries() + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner); Some(W3cTraceContext { traceparent: headers.remove("traceparent"), - tracestate: headers.remove("tracestate"), + tracestate: merge_tracestate_entries(tracestate.as_deref(), &configured_tracestate_guard), }) } +pub(crate) fn set_tracestate_entries( + entries: BTreeMap>, +) -> Result<(), Box> { + validate_tracestate_entries(&entries)?; + let mut guard = tracestate_entries() + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *guard = entries; + Ok(()) +} + pub fn current_span_trace_id() -> Option { let context = Span::current().context(); let span = context.span(); @@ -103,6 +128,177 @@ fn load_traceparent_context() -> Option { } } +fn tracestate_entries() -> &'static RwLock>> { + TRACESTATE_ENTRIES.get_or_init(|| RwLock::new(BTreeMap::new())) +} + +fn merge_tracestate_entries( + tracestate: Option<&str>, + configured_entries: &BTreeMap>, +) -> Option { + let mut trace_state = tracestate + .and_then(|tracestate| match TraceState::from_str(tracestate) { + Ok(trace_state) => Some(trace_state), + Err(err) => { + warn!("ignoring invalid tracestate while propagating trace context: {err}"); + None + } + }) + .unwrap_or_default(); + + // TraceState::insert places members at the front. Reverse iteration keeps + // deterministic map order while upserting fields inside configured members. + for (key, fields) in configured_entries.iter().rev() { + let value = merge_tracestate_member_fields(trace_state.get(key), fields); + trace_state = match trace_state.insert(key.clone(), value) { + Ok(trace_state) => trace_state, + Err(err) => { + warn!("ignoring configured tracestate while propagating trace context: {err}"); + break; + } + }; + } + + let tracestate = trace_state.header(); + (!tracestate.is_empty()).then_some(tracestate) +} + +/// Validates configured tracestate members before they are propagated in W3C trace context. +pub fn validate_tracestate_entries( + entries: &BTreeMap>, +) -> Result<(), Box> { + // Reject malformed entries before installing them so propagated trace + // context remains acceptable to other W3C Trace Context extractors. The + // SDK validates member keys and list structure, but configured member + // fields are joined into header values here and need stricter validation. + let entries = entries + .iter() + .map(|(key, fields)| encode_tracestate_member_fields(key, fields)) + .collect::, _>>()?; + TraceState::from_key_value( + entries + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())), + ) + .map_err(|err| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("invalid configured tracestate: {err}"), + ) + })?; + Ok(()) +} + +/// Validates one configured tracestate member and its encoded field value. +pub fn validate_tracestate_member( + member_key: &str, + fields: &BTreeMap, +) -> Result<(), Box> { + let (key, value) = encode_tracestate_member_fields(member_key, fields)?; + TraceState::from_key_value([(key.as_str(), value.as_str())]).map_err(|err| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("invalid configured tracestate: {err}"), + ) + })?; + Ok(()) +} + +fn encode_tracestate_member_fields( + member_key: &str, + fields: &BTreeMap, +) -> Result<(String, String), Box> { + // Configured fields are encoded into one opaque tracestate member value. + // Validate both the field grammar and the final header value so malformed + // config cannot produce propagated trace context that downstream W3C + // extractors reject. + let mut encoded = Vec::with_capacity(fields.len()); + for (field_key, value) in fields { + if !is_configured_tracestate_field_key(field_key) { + return Err(invalid_tracestate_config(format!( + "invalid configured tracestate field key {member_key}.{field_key}" + ))); + } + if !is_configured_tracestate_field_value(value) { + return Err(invalid_tracestate_config(format!( + "invalid configured tracestate value for {member_key}.{field_key}" + ))); + } + encoded.push(format!("{field_key}:{value}")); + } + let value = encoded.join(";"); + if !is_header_safe_tracestate_member_value(&value) { + return Err(invalid_tracestate_config(format!( + "invalid configured tracestate value for {member_key}" + ))); + } + Ok((member_key.to_string(), value)) +} + +fn is_configured_tracestate_field_key(field_key: &str) -> bool { + !field_key.is_empty() + && field_key + .bytes() + .all(|byte| matches!(byte, b'!'..=b'~') && !matches!(byte, b':' | b';' | b',' | b'=')) +} + +fn is_configured_tracestate_field_value(value: &str) -> bool { + value + .bytes() + .all(|byte| is_tracestate_member_value_byte(byte) && byte != b';') +} + +fn is_header_safe_tracestate_member_value(value: &str) -> bool { + value.is_empty() + || (value.bytes().all(is_tracestate_member_value_byte) + && value.as_bytes().last().is_some_and(|byte| *byte != b' ')) +} + +fn is_tracestate_member_value_byte(byte: u8) -> bool { + matches!(byte, b' '..=b'~') && !matches!(byte, b',' | b'=') +} + +fn invalid_tracestate_config(message: String) -> Box { + Box::new(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + message, + )) +} + +fn merge_tracestate_member_fields( + existing: Option<&str>, + configured_fields: &BTreeMap, +) -> String { + // W3C TraceState treats member values as opaque strings. The config models + // values as semicolon-separated key:value fields so selected fields can be + // upserted without replacing unrelated fields in the same member. + let mut fields = Vec::new(); + let mut seen = BTreeSet::new(); + + if let Some(existing) = existing { + for field in existing.split(';').filter(|field| !field.is_empty()) { + if let Some((field_key, _)) = field.split_once(':') { + if let Some(value) = configured_fields.get(field_key) { + if seen.insert(field_key) { + fields.push(format!("{field_key}:{value}")); + } + continue; + } + seen.insert(field_key); + } + fields.push(field.to_string()); + } + } + + fields.extend( + configured_fields + .iter() + .filter(|(field_key, _)| !seen.contains(field_key.as_str())) + .map(|(field_key, value)| format!("{field_key}:{value}")), + ); + fields.join(";") +} + #[cfg(test)] mod tests { use super::context_from_trace_headers; diff --git a/codex-rs/otel/tests/suite/otlp_http_loopback.rs b/codex-rs/otel/tests/suite/otlp_http_loopback.rs index fd4e3531d8..4c2dd36f76 100644 --- a/codex-rs/otel/tests/suite/otlp_http_loopback.rs +++ b/codex-rs/otel/tests/suite/otlp_http_loopback.rs @@ -5,18 +5,25 @@ use codex_otel::OtelHttpProtocol; use codex_otel::OtelProvider; use codex_otel::OtelSettings; use codex_otel::Result; +use codex_otel::current_span_w3c_trace_context; +use codex_otel::set_parent_from_w3c_trace_context; +use codex_protocol::protocol::W3cTraceContext; +use std::collections::BTreeMap; use std::collections::HashMap; use std::io::Read as _; use std::io::Write as _; use std::net::TcpListener; use std::net::TcpStream; use std::path::PathBuf; +use std::sync::Mutex; use std::sync::mpsc; use std::thread; use std::time::Duration; use std::time::Instant; use tracing_subscriber::layer::SubscriberExt; +static TRACE_CONTEXT_CONFIG_LOCK: Mutex<()> = Mutex::new(()); + struct CapturedRequest { path: String, content_type: Option, @@ -217,9 +224,41 @@ fn otlp_http_exporter_sends_metrics_to_collector() -> Result<()> { Ok(()) } +#[test] +fn otel_provider_rejects_header_unsafe_configured_tracestate() { + let result = OtelProvider::from(&OtelSettings { + environment: "test".to_string(), + service_name: "codex-cli".to_string(), + service_version: env!("CARGO_PKG_VERSION").to_string(), + codex_home: PathBuf::from("."), + exporter: OtelExporter::None, + trace_exporter: OtelExporter::OtlpHttp { + endpoint: "http://127.0.0.1:1/v1/traces".to_string(), + headers: HashMap::new(), + protocol: OtelHttpProtocol::Json, + tls: None, + }, + metrics_exporter: OtelExporter::None, + runtime_metrics: false, + span_attributes: BTreeMap::new(), + tracestate: BTreeMap::from([( + "example".to_string(), + BTreeMap::from([("alpha".to_string(), "one\ntwo".to_string())]), + )]), + }); + + let Err(err) = result else { + panic!("expected header-unsafe configured tracestate to be rejected"); + }; + assert!(err.to_string().contains("configured tracestate value")); +} + #[test] fn otlp_http_exporter_sends_traces_to_collector() -> std::result::Result<(), Box> { + let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); let addr = listener.local_addr().expect("local_addr"); listener.set_nonblocking(true).expect("set_nonblocking"); @@ -266,12 +305,23 @@ fn otlp_http_exporter_sends_traces_to_collector() }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + span_attributes: BTreeMap::from([( + "test.configured_attribute".to_string(), + "configured-value".to_string(), + )]), + tracestate: BTreeMap::from([( + "example".to_string(), + BTreeMap::from([ + ("alpha".to_string(), "one".to_string()), + ("beta".to_string(), "two".to_string()), + ]), + )]), })? .expect("otel provider"); let tracing_layer = otel.tracing_layer().expect("tracing layer"); let subscriber = tracing_subscriber::registry().with(tracing_layer); - tracing::subscriber::with_default(subscriber, || { + let propagated_trace = tracing::subscriber::with_default(subscriber, || { let span = tracing::info_span!( "trace-loopback", otel.name = "trace-loopback", @@ -279,11 +329,28 @@ fn otlp_http_exporter_sends_traces_to_collector() rpc.system = "jsonrpc", rpc.method = "trace-loopback", ); + assert!(set_parent_from_w3c_trace_context( + &span, + &W3cTraceContext { + traceparent: Some( + "00-00000000000000000000000000000001-0000000000000002-01".to_string(), + ), + tracestate: Some("example=alpha:zero;keep:yes,other=value".to_string()), + }, + )); let _guard = span.enter(); + let propagated_trace = + current_span_w3c_trace_context().expect("current span should have trace context"); tracing::info!("trace loopback event"); + propagated_trace }); otel.shutdown(); + assert_eq!( + propagated_trace.tracestate.as_deref(), + Some("example=alpha:one;keep:yes;beta:two,other=value") + ); + server.join().expect("server join"); let captured = rx.recv_timeout(Duration::from_secs(1)).expect("captured"); @@ -321,6 +388,11 @@ fn otlp_http_exporter_sends_traces_to_collector() "expected service name not found; body prefix: {}", &body.chars().take(2000).collect::() ); + assert!( + body.contains("test.configured_attribute") && body.contains("configured-value"), + "expected configured span attribute not found; body prefix: {}", + &body.chars().take(2000).collect::() + ); Ok(()) } @@ -328,6 +400,9 @@ fn otlp_http_exporter_sends_traces_to_collector() #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn otlp_http_exporter_sends_traces_to_collector_in_tokio_runtime() -> std::result::Result<(), Box> { + let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); let addr = listener.local_addr().expect("local_addr"); listener.set_nonblocking(true).expect("set_nonblocking"); @@ -374,6 +449,8 @@ async fn otlp_http_exporter_sends_traces_to_collector_in_tokio_runtime() }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + span_attributes: BTreeMap::new(), + tracestate: BTreeMap::new(), })? .expect("otel provider"); let tracing_layer = otel.tracing_layer().expect("tracing layer"); @@ -436,6 +513,9 @@ async fn otlp_http_exporter_sends_traces_to_collector_in_tokio_runtime() #[test] fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime() -> std::result::Result<(), Box> { + let _trace_context_config_guard = TRACE_CONTEXT_CONFIG_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); let addr = listener.local_addr().expect("local_addr"); listener.set_nonblocking(true).expect("set_nonblocking"); @@ -490,6 +570,8 @@ fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime( }, metrics_exporter: OtelExporter::None, runtime_metrics: false, + span_attributes: BTreeMap::new(), + tracestate: BTreeMap::new(), }) .map_err(|err| err.to_string())? .expect("otel provider"); diff --git a/codex-rs/process-hardening/Cargo.toml b/codex-rs/process-hardening/Cargo.toml index 7cc88ed608..60a5729ff5 100644 --- a/codex-rs/process-hardening/Cargo.toml +++ b/codex-rs/process-hardening/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_process_hardening" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index 1de72dda37..876976f3c5 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [lib] name = "codex_protocol" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index 73283e3eb6..ace096359c 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -187,6 +187,12 @@ pub struct GuardianAssessmentEvent { /// Uses `#[serde(default)]` for backwards compatibility. #[serde(default)] pub turn_id: String, + #[serde(default)] + #[ts(type = "number")] + pub started_at_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional, type = "number")] + pub completed_at_ms: Option, pub status: GuardianAssessmentStatus, /// Coarse risk label. Omitted while the assessment is in progress. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -223,6 +229,8 @@ pub struct ExecApprovalRequestEvent { /// Uses `#[serde(default)]` for backwards compatibility. #[serde(default)] pub turn_id: String, + #[ts(type = "number")] + pub started_at_ms: i64, /// The command to be executed. pub command: Vec, /// The command's working directory. @@ -370,6 +378,8 @@ pub struct ApplyPatchApprovalRequestEvent { /// Uses `#[serde(default)]` for backwards compatibility with older senders. #[serde(default)] pub turn_id: String, + #[ts(type = "number")] + pub started_at_ms: i64, pub changes: HashMap, /// Optional explanatory reason (e.g. request for extra write access). #[serde(skip_serializing_if = "Option::is_none")] diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 5a0fafad94..92ad4db6f3 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -335,21 +335,6 @@ pub struct ActivePermissionProfile { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub extends: Option, - - /// Bounded user-requested modifications applied on top of the named - /// profile, if any. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub modifications: Vec, -} - -#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, JsonSchema, TS)] -#[serde(tag = "type", rename_all = "snake_case")] -#[ts(tag = "type")] -pub enum ActivePermissionProfileModification { - /// Additional concrete directory that should be writable. - #[serde(rename_all = "snake_case")] - #[ts(rename_all = "snake_case")] - AdditionalWritableRoot { path: AbsolutePathBuf }, } impl ActivePermissionProfile { @@ -357,17 +342,8 @@ impl ActivePermissionProfile { Self { id: id.into(), extends: None, - modifications: Vec::new(), } } - - pub fn with_modifications( - mut self, - modifications: Vec, - ) -> Self { - self.modifications = modifications; - self - } } impl Default for PermissionProfile { @@ -539,6 +515,20 @@ impl PermissionProfile { self.network_sandbox_policy(), ) } + + pub fn materialize_project_roots_with_workspace_roots( + &self, + workspace_roots: &[AbsolutePathBuf], + ) -> Self { + let (file_system_sandbox_policy, network_sandbox_policy) = self.to_runtime_permissions(); + let file_system_sandbox_policy = file_system_sandbox_policy + .materialize_project_roots_with_workspace_roots(workspace_roots); + Self::from_runtime_permissions_with_enforcement( + self.enforcement(), + &file_system_sandbox_policy, + network_sandbox_policy, + ) + } } #[derive(Debug, Clone, Deserialize)] diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rs index c1f3d0724b..d5cfb6ef81 100644 --- a/codex-rs/protocol/src/permissions.rs +++ b/codex-rs/protocol/src/permissions.rs @@ -538,27 +538,16 @@ impl FileSystemSandboxPolicy { /// into split filesystem policy. pub fn from_legacy_sandbox_policy_for_cwd(sandbox_policy: &SandboxPolicy, cwd: &Path) -> Self { let mut file_system_policy = Self::from(sandbox_policy); - if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = sandbox_policy { - if let Ok(cwd_root) = AbsolutePathBuf::from_absolute_path(cwd) { - for protected_path in default_read_only_subpaths_for_writable_root( - &cwd_root, /*protect_missing_dot_codex*/ true, - ) { - append_default_read_only_path_if_no_explicit_rule( - &mut file_system_policy.entries, - protected_path, - ); - } - } - for writable_root in writable_roots { - for protected_path in default_read_only_subpaths_for_writable_root( - writable_root, - /*protect_missing_dot_codex*/ false, - ) { - append_default_read_only_path_if_no_explicit_rule( - &mut file_system_policy.entries, - protected_path, - ); - } + if let SandboxPolicy::WorkspaceWrite { .. } = sandbox_policy + && let Ok(cwd_root) = AbsolutePathBuf::from_absolute_path(cwd) + { + for protected_path in default_read_only_subpaths_for_writable_root( + &cwd_root, /*protect_missing_dot_codex*/ true, + ) { + append_default_read_only_path_if_no_explicit_rule( + &mut file_system_policy.entries, + protected_path, + ); } } @@ -679,6 +668,38 @@ impl FileSystemSandboxPolicy { self } + /// Replaces symbolic `:project_roots` entries with concrete entries for + /// each workspace root. + pub fn materialize_project_roots_with_workspace_roots( + mut self, + workspace_roots: &[AbsolutePathBuf], + ) -> Self { + let mut entries = Vec::with_capacity(self.entries.len()); + for entry in self.entries { + let FileSystemPath::Special { + value: FileSystemSpecialPath::ProjectRoots { subpath }, + } = &entry.path + else { + entries.push(entry); + continue; + }; + + entries.extend(workspace_roots.iter().map(|root| FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: match subpath.as_ref() { + Some(subpath) => { + AbsolutePathBuf::resolve_path_against_base(subpath, root.as_path()) + } + None => root.clone(), + }, + }, + access: entry.access, + })); + } + self.entries = entries; + self + } + pub fn with_additional_readable_roots( mut self, cwd: &Path, @@ -994,10 +1015,10 @@ impl FileSystemSandboxPolicy { let cwd_absolute = AbsolutePathBuf::from_absolute_path(cwd).ok(); let has_full_disk_write_access = self.has_full_disk_write_access(); let mut workspace_root_writable = false; - let mut writable_roots = Vec::new(); let mut tmpdir_writable = false; let mut slash_tmp_writable = false; let mut unbridgeable_root_write = false; + let mut unbridgeable_external_write = false; for entry in &self.entries { match &entry.path { @@ -1007,7 +1028,7 @@ impl FileSystemSandboxPolicy { if cwd_absolute.as_ref().is_some_and(|cwd| cwd == path) { workspace_root_writable = true; } else { - writable_roots.push(path.clone()); + unbridgeable_external_write = true; } } } @@ -1023,11 +1044,8 @@ impl FileSystemSandboxPolicy { FileSystemSpecialPath::ProjectRoots { subpath } => { if subpath.is_none() && entry.access.can_write() { workspace_root_writable = true; - } else if let Some(path) = - resolve_file_system_special_path(value, cwd_absolute.as_ref()) - && entry.access.can_write() - { - writable_roots.push(path); + } else if entry.access.can_write() { + unbridgeable_external_write = true; } } FileSystemSpecialPath::Tmpdir => { @@ -1057,16 +1075,12 @@ impl FileSystemSandboxPolicy { if workspace_root_writable { SandboxPolicy::WorkspaceWrite { - writable_roots: dedup_absolute_paths( - writable_roots, - /*normalize_effective_paths*/ false, - ), network_access: network_policy.is_enabled(), exclude_tmpdir_env_var: !tmpdir_writable, exclude_slash_tmp: !slash_tmp_writable, } } else if unbridgeable_root_write - || !writable_roots.is_empty() + || unbridgeable_external_write || tmpdir_writable || slash_tmp_writable { @@ -1135,12 +1149,11 @@ impl From<&SandboxPolicy> for FileSystemSandboxPolicy { }]) } SandboxPolicy::WorkspaceWrite { - writable_roots, exclude_tmpdir_env_var, exclude_slash_tmp, .. } => FileSystemSandboxPolicy::workspace_write( - writable_roots, + &[], *exclude_tmpdir_env_var, *exclude_slash_tmp, ), @@ -1447,7 +1460,6 @@ fn legacy_runtime_file_system_policy_for_cwd( cwd: &Path, ) -> FileSystemSandboxPolicy { let SandboxPolicy::WorkspaceWrite { - writable_roots, exclude_tmpdir_env_var, exclude_slash_tmp, .. @@ -1487,16 +1499,6 @@ fn legacy_runtime_file_system_policy_for_cwd( access: FileSystemAccessMode::Write, }); } - entries.extend( - writable_roots - .iter() - .cloned() - .map(|path| FileSystemSandboxEntry { - path: FileSystemPath::Path { path }, - access: FileSystemAccessMode::Write, - }), - ); - if let Ok(cwd_root) = AbsolutePathBuf::from_absolute_path(cwd) { for protected_path in default_read_only_subpaths_for_writable_root( &cwd_root, /*protect_missing_dot_codex*/ true, @@ -1504,14 +1506,6 @@ fn legacy_runtime_file_system_policy_for_cwd( append_default_read_only_path_if_no_explicit_rule(&mut entries, protected_path); } } - for writable_root in writable_roots { - for protected_path in default_read_only_subpaths_for_writable_root( - writable_root, - /*protect_missing_dot_codex*/ false, - ) { - append_default_read_only_path_if_no_explicit_rule(&mut entries, protected_path); - } - } FileSystemSandboxPolicy::restricted(entries) } @@ -1800,7 +1794,6 @@ mod tests { #[test] fn legacy_workspace_write_projection_preserves_symbolic_project_root() { let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -1956,7 +1949,6 @@ mod tests { ) .expect("absolute root"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -2472,7 +2464,6 @@ mod tests { fn legacy_projection_runtime_enforcement_ignores_entry_order() { let cwd = TempDir::new().expect("tempdir"); let legacy_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -2499,7 +2490,6 @@ mod tests { fn missing_symbolic_metadata_carveouts_need_direct_runtime_enforcement() { let cwd = TempDir::new().expect("tempdir"); let legacy_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 30e33abe43..8419b8950e 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -462,6 +462,10 @@ pub enum Op { #[serde(skip_serializing_if = "Option::is_none")] cwd: Option, + /// Updated workspace roots for sandbox/tool calls. + #[serde(skip_serializing_if = "Option::is_none")] + workspace_roots: Option>, + /// Updated command approval policy. #[serde(skip_serializing_if = "Option::is_none")] approval_policy: Option, @@ -1004,14 +1008,9 @@ pub enum SandboxPolicy { }, /// Same as `ReadOnly` but additionally grants write access to the current - /// working directory ("workspace"). + /// thread workspace roots. #[serde(rename = "workspace-write")] WorkspaceWrite { - /// Additional folders (beyond cwd and possibly TMPDIR) that should be - /// writable from within the sandbox. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - writable_roots: Vec, - /// When set to `true`, outbound network access is allowed. `false` by /// default. #[serde(default)] @@ -1121,7 +1120,6 @@ impl SandboxPolicy { /// not allow network access. pub fn new_workspace_write_policy() -> Self { SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -1159,13 +1157,11 @@ impl SandboxPolicy { SandboxPolicy::ExternalSandbox { .. } => Vec::new(), SandboxPolicy::ReadOnly { .. } => Vec::new(), SandboxPolicy::WorkspaceWrite { - writable_roots, exclude_tmpdir_env_var, exclude_slash_tmp, network_access: _, } => { - // Start from explicitly configured writable roots. - let mut roots: Vec = writable_roots.clone(); + let mut roots: Vec = Vec::new(); // Always include defaults: cwd, /tmp (if present on Unix), and // on macOS, the per-user TMPDIR unless explicitly excluded. @@ -2707,6 +2703,8 @@ pub struct SessionMeta { pub forked_from_id: Option, pub timestamp: String, pub cwd: PathBuf, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub workspace_roots: Vec, pub originator: String, pub cli_version: String, #[serde(default)] @@ -2741,6 +2739,7 @@ impl Default for SessionMeta { forked_from_id: None, timestamp: String::new(), cwd: PathBuf::new(), + workspace_roots: Vec::new(), originator: String::new(), cli_version: String::new(), source: SessionSource::default(), @@ -2811,6 +2810,8 @@ pub struct TurnContextItem { #[serde(default, skip_serializing_if = "Option::is_none")] pub trace_id: Option, pub cwd: PathBuf, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub workspace_roots: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub current_date: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -3451,6 +3452,10 @@ pub struct SessionConfiguredEvent { /// session. pub cwd: AbsolutePathBuf, + /// Workspace roots used to realize symbolic `:project_roots` entries. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub workspace_roots: Vec, + /// The effort the model is putting into reasoning about the user's request. #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, @@ -3499,6 +3504,8 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent { #[serde(default)] active_permission_profile: Option, cwd: AbsolutePathBuf, + #[serde(default)] + workspace_roots: Vec, reasoning_effort: Option, initial_messages: Option>, network_proxy: Option, @@ -3516,6 +3523,11 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent { return Err(serde::de::Error::missing_field("permission_profile")); } }; + let workspace_roots = if wire.workspace_roots.is_empty() { + vec![wire.cwd.clone()] + } else { + wire.workspace_roots + }; Ok(Self { session_id: wire.session_id, @@ -3531,6 +3543,7 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent { permission_profile, active_permission_profile: wire.active_permission_profile, cwd: wire.cwd, + workspace_roots, reasoning_effort: wire.reasoning_effort, initial_messages: wire.initial_messages, network_proxy: wire.network_proxy, @@ -4480,7 +4493,6 @@ mod tests { #[test] fn legacy_sandbox_policy_semantics_survive_split_bridge() { let cwd = TempDir::new().expect("tempdir"); - let writable_root = AbsolutePathBuf::resolve_path_against_base("writable", cwd.path()); let policies = [ SandboxPolicy::DangerFullAccess, SandboxPolicy::ExternalSandbox { @@ -4493,13 +4505,11 @@ mod tests { network_access: false, }, SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, }, SandboxPolicy::WorkspaceWrite { - writable_roots: vec![writable_root], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: true, @@ -5183,6 +5193,7 @@ mod tests { turn_id: None, trace_id: None, cwd: test_path_buf("/tmp"), + workspace_roots: Vec::new(), current_date: None, timezone: None, approval_policy: AskForApproval::Never, @@ -5260,6 +5271,7 @@ mod tests { permission_profile: permission_profile.clone(), active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), + workspace_roots: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), initial_messages: None, network_proxy: None, diff --git a/codex-rs/protocol/src/request_permissions.rs b/codex-rs/protocol/src/request_permissions.rs index 6c7b699daf..be6b88ef52 100644 --- a/codex-rs/protocol/src/request_permissions.rs +++ b/codex-rs/protocol/src/request_permissions.rs @@ -71,6 +71,8 @@ pub struct RequestPermissionsEvent { /// Uses `#[serde(default)]` for backwards compatibility. #[serde(default)] pub turn_id: String, + #[ts(type = "number")] + pub started_at_ms: i64, #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, pub permissions: RequestPermissionProfile, diff --git a/codex-rs/realtime-webrtc/Cargo.toml b/codex-rs/realtime-webrtc/Cargo.toml index 4a20e2fec8..da468bf64d 100644 --- a/codex-rs/realtime-webrtc/Cargo.toml +++ b/codex-rs/realtime-webrtc/Cargo.toml @@ -7,6 +7,8 @@ license.workspace = true [lib] name = "codex_realtime_webrtc" path = "src/lib.rs" +test = false +doctest = false [dependencies] thiserror = { workspace = true } diff --git a/codex-rs/responses-api-proxy/Cargo.toml b/codex-rs/responses-api-proxy/Cargo.toml index 504588fe25..05d638843f 100644 --- a/codex-rs/responses-api-proxy/Cargo.toml +++ b/codex-rs/responses-api-proxy/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_responses_api_proxy" path = "src/lib.rs" +doctest = false [[bin]] name = "codex-responses-api-proxy" diff --git a/codex-rs/rmcp-client/Cargo.toml b/codex-rs/rmcp-client/Cargo.toml index c0c32c4b97..9be90e277a 100644 --- a/codex-rs/rmcp-client/Cargo.toml +++ b/codex-rs/rmcp-client/Cargo.toml @@ -78,3 +78,6 @@ keyring = { workspace = true, features = ["windows-native"] } [target.'cfg(any(target_os = "freebsd", target_os = "openbsd"))'.dependencies] keyring = { workspace = true, features = ["sync-secret-service"] } + +[lib] +doctest = false diff --git a/codex-rs/rollout/Cargo.toml b/codex-rs/rollout/Cargo.toml index ef5a8dc22a..166cc804b0 100644 --- a/codex-rs/rollout/Cargo.toml +++ b/codex-rs/rollout/Cargo.toml @@ -22,6 +22,7 @@ codex-login = { workspace = true } codex-otel = { workspace = true } codex-protocol = { workspace = true } codex-state = { workspace = true } +codex-utils-absolute-path = { workspace = true } codex-utils-path = { workspace = true } codex-utils-string = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/codex-rs/rollout/src/config.rs b/codex-rs/rollout/src/config.rs index 420949bfbd..873553ae91 100644 --- a/codex-rs/rollout/src/config.rs +++ b/codex-rs/rollout/src/config.rs @@ -2,10 +2,13 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use codex_utils_absolute_path::AbsolutePathBuf; + pub trait RolloutConfigView { fn codex_home(&self) -> &Path; fn sqlite_home(&self) -> &Path; fn cwd(&self) -> &Path; + fn workspace_roots(&self) -> &[AbsolutePathBuf]; fn model_provider_id(&self) -> &str; fn generate_memories(&self) -> bool; } @@ -15,6 +18,7 @@ pub struct RolloutConfig { pub codex_home: PathBuf, pub sqlite_home: PathBuf, pub cwd: PathBuf, + pub workspace_roots: Vec, pub model_provider_id: String, pub generate_memories: bool, } @@ -27,6 +31,7 @@ impl RolloutConfig { codex_home: view.codex_home().to_path_buf(), sqlite_home: view.sqlite_home().to_path_buf(), cwd: view.cwd().to_path_buf(), + workspace_roots: view.workspace_roots().to_vec(), model_provider_id: view.model_provider_id().to_string(), generate_memories: view.generate_memories(), } @@ -46,6 +51,10 @@ impl RolloutConfigView for RolloutConfig { self.cwd.as_path() } + fn workspace_roots(&self) -> &[AbsolutePathBuf] { + &self.workspace_roots + } + fn model_provider_id(&self) -> &str { self.model_provider_id.as_str() } @@ -68,6 +77,10 @@ impl RolloutConfigView for &T { (*self).cwd() } + fn workspace_roots(&self) -> &[AbsolutePathBuf] { + (*self).workspace_roots() + } + fn model_provider_id(&self) -> &str { (*self).model_provider_id() } @@ -90,6 +103,10 @@ impl RolloutConfigView for Arc { self.as_ref().cwd() } + fn workspace_roots(&self) -> &[AbsolutePathBuf] { + self.as_ref().workspace_roots() + } + fn model_provider_id(&self) -> &str { self.as_ref().model_provider_id() } diff --git a/codex-rs/rollout/src/metadata_tests.rs b/codex-rs/rollout/src/metadata_tests.rs index 45db758c65..c253f4db81 100644 --- a/codex-rs/rollout/src/metadata_tests.rs +++ b/codex-rs/rollout/src/metadata_tests.rs @@ -37,6 +37,7 @@ async fn extract_metadata_from_rollout_uses_session_meta() { forked_from_id: None, timestamp: "2026-01-27T12:34:56Z".to_string(), cwd: dir.path().to_path_buf(), + workspace_roots: Vec::new(), originator: "cli".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::default(), @@ -89,6 +90,7 @@ async fn extract_metadata_from_rollout_returns_latest_memory_mode() { forked_from_id: None, timestamp: "2026-01-27T12:34:56Z".to_string(), cwd: dir.path().to_path_buf(), + workspace_roots: Vec::new(), originator: "cli".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::default(), @@ -349,6 +351,7 @@ fn write_rollout_in_sessions_with_cwd( forked_from_id: None, timestamp: event_ts.to_string(), cwd, + workspace_roots: Vec::new(), originator: "cli".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::default(), diff --git a/codex-rs/rollout/src/recorder.rs b/codex-rs/rollout/src/recorder.rs index 6b549b745c..4c3dc1c264 100644 --- a/codex-rs/rollout/src/recorder.rs +++ b/codex-rs/rollout/src/recorder.rs @@ -697,6 +697,7 @@ impl RolloutRecorder { forked_from_id, timestamp, cwd: config.cwd().to_path_buf(), + workspace_roots: config.workspace_roots().to_vec(), originator: originator().value, cli_version: env!("CARGO_PKG_VERSION").to_string(), agent_nickname: source.get_nickname(), diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rs index 505cd59929..5784b1dfce 100644 --- a/codex-rs/rollout/src/recorder_tests.rs +++ b/codex-rs/rollout/src/recorder_tests.rs @@ -32,6 +32,7 @@ fn test_config(codex_home: &Path) -> RolloutConfig { codex_home: codex_home.to_path_buf(), sqlite_home: codex_home.to_path_buf(), cwd: codex_home.to_path_buf(), + workspace_roots: Vec::new(), model_provider_id: "test-provider".to_string(), generate_memories: true, } @@ -88,6 +89,7 @@ async fn state_db_init_backfills_before_returning() -> anyhow::Result<()> { forked_from_id: None, timestamp: "2026-01-27T12:34:56Z".to_string(), cwd: home.path().to_path_buf(), + workspace_roots: Vec::new(), originator: "test".to_string(), cli_version: "test".to_string(), source: SessionSource::Cli, @@ -216,6 +218,68 @@ async fn load_rollout_items_skips_legacy_ghost_snapshot_lines() -> std::io::Resu Ok(()) } +#[tokio::test] +async fn load_rollout_items_preserves_legacy_guardian_assessment_lines() -> std::io::Result<()> { + let home = TempDir::new().expect("temp dir"); + let rollout_path = home.path().join("rollout.jsonl"); + let mut file = File::create(&rollout_path)?; + let thread_id = ThreadId::new(); + let ts = "2025-01-03T12:00:00Z"; + + writeln!( + file, + "{}", + serde_json::json!({ + "timestamp": ts, + "type": "session_meta", + "payload": { + "id": thread_id, + "timestamp": ts, + "cwd": ".", + "originator": "test_originator", + "cli_version": "test_version", + "source": "cli", + "model_provider": "test-provider", + }, + }) + )?; + writeln!( + file, + "{}", + serde_json::json!({ + "timestamp": ts, + "type": "event_msg", + "payload": { + "type": "guardian_assessment", + "id": "guardian-1", + "turn_id": "turn-1", + "status": "in_progress", + "action": { + "type": "command", + "source": "shell", + "command": "rm -rf /tmp/guardian", + "cwd": if cfg!(windows) { r"C:\tmp" } else { "/tmp" }, + }, + }, + }) + )?; + + let (items, loaded_thread_id, parse_errors) = + RolloutRecorder::load_rollout_items(&rollout_path).await?; + + assert_eq!(loaded_thread_id, Some(thread_id)); + assert_eq!(parse_errors, 0); + assert_eq!(items.len(), 2); + let RolloutItem::EventMsg(EventMsg::GuardianAssessment(assessment)) = &items[1] else { + panic!("expected guardian assessment rollout item"); + }; + assert_eq!(assessment.id, "guardian-1"); + assert_eq!(assessment.turn_id, "turn-1"); + assert_eq!(assessment.started_at_ms, 0); + + Ok(()) +} + #[tokio::test] async fn load_rollout_items_filters_legacy_ghost_snapshots_from_compaction_history() -> std::io::Result<()> { @@ -586,70 +650,48 @@ async fn shutdown_flushes_pending_metadata_irrelevant_updated_at() -> std::io::R .expect("backfill should be complete"); let thread_id = ThreadId::new(); - let recorder = RolloutRecorder::new( - &config, - RolloutRecorderParams::new( - thread_id, - /*forked_from_id*/ None, - SessionSource::Cli, - /*thread_source*/ None, - BaseInstructions::default(), - Vec::new(), - EventPersistenceMode::Limited, - ), - Some(state_db.clone()), - /*state_builder*/ None, - ) - .await?; - - recorder - .record_items(&[RolloutItem::EventMsg(EventMsg::UserMessage( - UserMessageEvent { - message: "first-user-message".to_string(), - images: None, - local_images: Vec::new(), - text_elements: Vec::new(), - }, - ))]) - .await?; - recorder.persist().await?; - recorder.flush().await?; - let initial_updated_at = state_db - .get_thread(thread_id) + let rollout_path = home.path().join("rollout.jsonl"); + let initial_updated_at = Utc.with_ymd_and_hms(2026, 5, 7, 7, 37, 8).unwrap(); + let builder = ThreadMetadataBuilder::new( + thread_id, + rollout_path.clone(), + initial_updated_at, + SessionSource::Cli, + ); + state_db + .upsert_thread(&builder.build(config.model_provider_id.as_str())) .await - .expect("thread should load") - .expect("thread should exist") - .updated_at; + .expect("thread should be inserted"); + + File::create(&rollout_path)?; + let rollout_file = std::fs::OpenOptions::new() + .append(true) + .open(&rollout_path)?; + let mut state = RolloutWriterState::new( + Some(tokio::fs::File::from_std(rollout_file)), + /*deferred_log_file_info*/ None, + /*meta*/ None, + home.path().to_path_buf(), + rollout_path, + Some(state_db.clone()), + Some(builder), + config.model_provider_id.clone(), + config.generate_memories, + ); + let pending_updated_at = initial_updated_at + chrono::Duration::seconds(1); + state.thread_updated_at_touch.pending_touch = Some((thread_id, pending_updated_at)); + + state.shutdown().await?; - recorder - .record_items(&[RolloutItem::EventMsg(EventMsg::AgentMessage( - AgentMessageEvent { - message: "assistant text".to_string(), - phase: None, - memory_citation: None, - }, - ))]) - .await?; - recorder.flush().await?; assert_eq!( state_db .get_thread(thread_id) .await - .expect("thread should load before shutdown") + .expect("thread should load after shutdown") .expect("thread should still exist") .updated_at, - initial_updated_at + pending_updated_at ); - - recorder.shutdown().await?; - - let shutdown_updated_at = state_db - .get_thread(thread_id) - .await - .expect("thread should load after shutdown") - .expect("thread should still exist") - .updated_at; - assert!(shutdown_updated_at > initial_updated_at); Ok(()) } @@ -1300,6 +1342,7 @@ async fn resume_candidate_matches_cwd_reads_latest_turn_context() -> std::io::Re turn_id: Some("turn-1".to_string()), trace_id: None, cwd: latest_cwd.clone(), + workspace_roots: Vec::new(), current_date: None, timezone: None, approval_policy: AskForApproval::Never, diff --git a/codex-rs/rollout/src/session_index_tests.rs b/codex-rs/rollout/src/session_index_tests.rs index 757b08b4d4..c9a5d501b0 100644 --- a/codex-rs/rollout/src/session_index_tests.rs +++ b/codex-rs/rollout/src/session_index_tests.rs @@ -29,6 +29,7 @@ fn write_rollout_with_metadata(path: &Path, thread_id: ThreadId) -> std::io::Res forked_from_id: None, timestamp, cwd: ".".into(), + workspace_roots: Vec::new(), originator: "test_originator".into(), cli_version: "test_version".into(), source: SessionSource::Cli, diff --git a/codex-rs/rollout/src/tests.rs b/codex-rs/rollout/src/tests.rs index fdfed3dadc..dfcde35058 100644 --- a/codex-rs/rollout/src/tests.rs +++ b/codex-rs/rollout/src/tests.rs @@ -1211,6 +1211,7 @@ async fn test_updated_at_uses_file_mtime() -> Result<()> { forked_from_id: None, timestamp: ts.to_string(), cwd: ".".into(), + workspace_roots: Vec::new(), originator: "test_originator".into(), cli_version: "test_version".into(), source: SessionSource::VSCode, diff --git a/codex-rs/sandboxing/Cargo.toml b/codex-rs/sandboxing/Cargo.toml index 49fd33e01d..858219e9fc 100644 --- a/codex-rs/sandboxing/Cargo.toml +++ b/codex-rs/sandboxing/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_sandboxing" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/sandboxing/src/manager.rs b/codex-rs/sandboxing/src/manager.rs index 82c49f7908..8b13daab65 100644 --- a/codex-rs/sandboxing/src/manager.rs +++ b/codex-rs/sandboxing/src/manager.rs @@ -97,6 +97,7 @@ pub struct SandboxTransformRequest<'a> { // to make shared ownership explicit across runtime/sandbox plumbing. pub network: Option<&'a NetworkProxy>, pub sandbox_policy_cwd: &'a Path, + pub workspace_roots: &'a [AbsolutePathBuf], pub codex_linux_sandbox_exe: Option<&'a Path>, pub use_legacy_landlock: bool, pub windows_sandbox_level: WindowsSandboxLevel, @@ -176,6 +177,7 @@ impl SandboxManager { enforce_managed_network, network, sandbox_policy_cwd, + workspace_roots, codex_linux_sandbox_exe, use_legacy_landlock, windows_sandbox_level, @@ -183,7 +185,8 @@ impl SandboxManager { } = request; let additional_permissions = command.additional_permissions.take(); let effective_permission_profile = - effective_permission_profile(permissions, additional_permissions.as_ref()); + effective_permission_profile(permissions, additional_permissions.as_ref()) + .materialize_project_roots_with_workspace_roots(workspace_roots); let (effective_file_system_policy, effective_network_policy) = effective_permission_profile.to_runtime_permissions(); let mut argv = Vec::with_capacity(1 + command.args.len()); @@ -278,13 +281,6 @@ fn compatibility_workspace_write_policy( network_policy: NetworkSandboxPolicy, cwd: &Path, ) -> SandboxPolicy { - let cwd_abs = AbsolutePathBuf::from_absolute_path(cwd).ok(); - let writable_roots = file_system_policy - .get_writable_roots_with_cwd(cwd) - .into_iter() - .map(|root| root.root) - .filter(|root| cwd_abs.as_ref() != Some(root)) - .collect(); let tmpdir_writable = std::env::var_os("TMPDIR") .filter(|tmpdir| !tmpdir.is_empty()) .and_then(|tmpdir| { @@ -297,7 +293,6 @@ fn compatibility_workspace_write_policy( && file_system_policy.can_write_path_with_cwd(slash_tmp, cwd); SandboxPolicy::WorkspaceWrite { - writable_roots, network_access: network_policy.is_enabled(), exclude_tmpdir_env_var: !tmpdir_writable, exclude_slash_tmp: !slash_tmp_writable, diff --git a/codex-rs/sandboxing/src/manager_tests.rs b/codex-rs/sandboxing/src/manager_tests.rs index 31f74b9c0a..43ea6655ae 100644 --- a/codex-rs/sandboxing/src/manager_tests.rs +++ b/codex-rs/sandboxing/src/manager_tests.rs @@ -91,6 +91,7 @@ fn transform_preserves_unrestricted_file_system_policy_for_restricted_network() enforce_managed_network: false, network: None, sandbox_policy_cwd: cwd.as_path(), + workspace_roots: std::slice::from_ref(&cwd), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, @@ -142,6 +143,7 @@ fn transform_additional_permissions_enable_network_for_external_sandbox() { enforce_managed_network: false, network: None, sandbox_policy_cwd: cwd.as_path(), + workspace_roots: std::slice::from_ref(&cwd), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, @@ -210,6 +212,7 @@ fn transform_additional_permissions_preserves_denied_entries() { enforce_managed_network: false, network: None, sandbox_policy_cwd: cwd.as_path(), + workspace_roots: std::slice::from_ref(&cwd), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, @@ -263,6 +266,7 @@ fn transform_linux_seccomp_request( enforce_managed_network: false, network: None, sandbox_policy_cwd: cwd.as_path(), + workspace_roots: std::slice::from_ref(&cwd), codex_linux_sandbox_exe: Some(codex_linux_sandbox_exe), use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, diff --git a/codex-rs/sandboxing/src/seatbelt_tests.rs b/codex-rs/sandboxing/src/seatbelt_tests.rs index a8f14fc26a..ef5deefe38 100644 --- a/codex-rs/sandboxing/src/seatbelt_tests.rs +++ b/codex-rs/sandboxing/src/seatbelt_tests.rs @@ -415,7 +415,6 @@ fn create_seatbelt_args_allows_local_binding_when_explicitly_enabled() { fn dynamic_network_policy_preserves_restricted_policy_when_proxy_config_without_ports() { let policy = dynamic_network_policy( &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -451,7 +450,6 @@ fn dynamic_network_policy_preserves_restricted_policy_when_proxy_config_without_ fn dynamic_network_policy_blocks_dns_when_local_binding_has_no_proxy_ports() { let policy = dynamic_network_policy( &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -479,7 +477,6 @@ fn dynamic_network_policy_blocks_dns_when_local_binding_has_no_proxy_ports() { fn dynamic_network_policy_preserves_restricted_policy_for_managed_network_without_proxy_config() { let policy = dynamic_network_policy( &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -769,7 +766,6 @@ fn create_seatbelt_args_allows_all_unix_sockets_when_enabled() { fn create_seatbelt_args_full_network_with_proxy_is_still_proxy_only() { let policy = dynamic_network_policy( &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -816,15 +812,15 @@ fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() { // Build a policy that only includes the two test roots as writable and // does not automatically include defaults TMPDIR or /tmp. - let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![vulnerable_root, empty_root] - .into_iter() - .map(|p| p.try_into().unwrap()) - .collect(), - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; + let writable_roots = vec![vulnerable_root, empty_root] + .into_iter() + .map(|path| AbsolutePathBuf::from_absolute_path(path).expect("absolute writable root")) + .collect::>(); + let file_system_sandbox_policy = FileSystemSandboxPolicy::workspace_write( + &writable_roots, + /*exclude_tmpdir_env_var*/ true, + /*exclude_slash_tmp*/ true, + ); // Create the Seatbelt command to wrap a shell command that tries to // write to .codex/config.toml in the vulnerable root. @@ -841,13 +837,15 @@ fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() { .iter() .map(std::string::ToString::to_string) .collect(); - let args = create_seatbelt_command_args_for_legacy_policy( - shell_command.clone(), - &policy, - &cwd, - /*enforce_managed_network*/ false, - /*network*/ None, - ); + let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams { + command: shell_command.clone(), + file_system_sandbox_policy: &file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: &cwd, + enforce_managed_network: false, + network: None, + extra_allow_unix_sockets: &[], + }); let policy_text = seatbelt_policy_arg(&args); assert!( @@ -988,13 +986,15 @@ fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() { .iter() .map(std::string::ToString::to_string) .collect(); - let write_hooks_file_args = create_seatbelt_command_args_for_legacy_policy( - shell_command_git, - &policy, - &cwd, - /*enforce_managed_network*/ false, - /*network*/ None, - ); + let write_hooks_file_args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams { + command: shell_command_git, + file_system_sandbox_policy: &file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: &cwd, + enforce_managed_network: false, + network: None, + extra_allow_unix_sockets: &[], + }); let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) .args(&write_hooks_file_args) .current_dir(&cwd) @@ -1024,13 +1024,15 @@ fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() { .iter() .map(std::string::ToString::to_string) .collect(); - let write_allowed_file_args = create_seatbelt_command_args_for_legacy_policy( - shell_command_allowed, - &policy, - &cwd, - /*enforce_managed_network*/ false, - /*network*/ None, - ); + let write_allowed_file_args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams { + command: shell_command_allowed, + file_system_sandbox_policy: &file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: &cwd, + enforce_managed_network: false, + network: None, + extra_allow_unix_sockets: &[], + }); let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) .args(&write_allowed_file_args) .current_dir(&cwd) @@ -1071,7 +1073,6 @@ fn create_seatbelt_args_block_first_time_dot_codex_creation_with_metadata_name_r let dot_codex = repo_root.join(".codex"); let config_toml = dot_codex.join("config.toml"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![repo_root.as_path().try_into().expect("absolute repo root")], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -1123,12 +1124,13 @@ fn create_seatbelt_args_with_read_only_git_pointer_file() { let cwd = tmp.path().join("cwd"); fs::create_dir_all(&cwd).expect("create cwd"); - let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![worktree_root.try_into().expect("worktree_root is absolute")], - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; + let worktree_root = + AbsolutePathBuf::from_absolute_path(worktree_root).expect("worktree_root is absolute"); + let file_system_sandbox_policy = FileSystemSandboxPolicy::workspace_write( + std::slice::from_ref(&worktree_root), + /*exclude_tmpdir_env_var*/ true, + /*exclude_slash_tmp*/ true, + ); let shell_command: Vec = [ "bash", @@ -1140,13 +1142,15 @@ fn create_seatbelt_args_with_read_only_git_pointer_file() { .iter() .map(std::string::ToString::to_string) .collect(); - let args = create_seatbelt_command_args_for_legacy_policy( - shell_command, - &policy, - &cwd, - /*enforce_managed_network*/ false, - /*network*/ None, - ); + let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams { + command: shell_command, + file_system_sandbox_policy: &file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: &cwd, + enforce_managed_network: false, + network: None, + extra_allow_unix_sockets: &[], + }); let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) .args(&args) @@ -1176,13 +1180,15 @@ fn create_seatbelt_args_with_read_only_git_pointer_file() { .iter() .map(std::string::ToString::to_string) .collect(); - let gitdir_args = create_seatbelt_command_args_for_legacy_policy( - shell_command_gitdir, - &policy, - &cwd, - /*enforce_managed_network*/ false, - /*network*/ None, - ); + let gitdir_args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams { + command: shell_command_gitdir, + file_system_sandbox_policy: &file_system_sandbox_policy, + network_sandbox_policy: NetworkSandboxPolicy::Restricted, + sandbox_policy_cwd: &cwd, + enforce_managed_network: false, + network: None, + extra_allow_unix_sockets: &[], + }); let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE) .args(&gitdir_args) .current_dir(&cwd) @@ -1220,7 +1226,6 @@ fn create_seatbelt_args_for_cwd_as_git_repo() { // use the default ones (cwd and TMPDIR) and verifies the protected // metadata checks are done properly for cwd. let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/secrets/Cargo.toml b/codex-rs/secrets/Cargo.toml index 7ca634b251..2a294ee391 100644 --- a/codex-rs/secrets/Cargo.toml +++ b/codex-rs/secrets/Cargo.toml @@ -25,3 +25,6 @@ tracing = { workspace = true } keyring = { workspace = true } pretty_assertions = { workspace = true } tempfile = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/shell-command/Cargo.toml b/codex-rs/shell-command/Cargo.toml index 2df9843f02..cc33d3621c 100644 --- a/codex-rs/shell-command/Cargo.toml +++ b/codex-rs/shell-command/Cargo.toml @@ -24,3 +24,6 @@ which = { workspace = true } [dev-dependencies] anyhow = { workspace = true } pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/shell-escalation/Cargo.toml b/codex-rs/shell-escalation/Cargo.toml index 1f6ded3e40..a57db3ce53 100644 --- a/codex-rs/shell-escalation/Cargo.toml +++ b/codex-rs/shell-escalation/Cargo.toml @@ -37,3 +37,6 @@ tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] } [dev-dependencies] pretty_assertions = { workspace = true } tempfile = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 723c5084eb..f0aaf66116 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -247,6 +247,7 @@ mod tests { ), timestamp: "2026-02-26T00:00:00.000Z".to_string(), cwd: PathBuf::from("/child/worktree"), + workspace_roots: Vec::new(), originator: "codex_cli_rs".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::Cli, @@ -269,6 +270,7 @@ mod tests { turn_id: Some("turn-1".to_string()), trace_id: None, cwd: PathBuf::from("/parent/workspace"), + workspace_roots: Vec::new(), current_date: None, timezone: None, approval_policy: AskForApproval::Never, @@ -309,6 +311,7 @@ mod tests { turn_id: Some("turn-1".to_string()), trace_id: None, cwd: PathBuf::from("/fallback/workspace"), + workspace_roots: Vec::new(), current_date: None, timezone: None, approval_policy: AskForApproval::OnRequest, @@ -343,6 +346,7 @@ mod tests { turn_id: Some("turn-1".to_string()), trace_id: None, cwd: PathBuf::from("/fallback/workspace"), + workspace_roots: Vec::new(), current_date: None, timezone: None, approval_policy: AskForApproval::OnRequest, @@ -381,6 +385,7 @@ mod tests { forked_from_id: None, timestamp: "2026-02-26T00:00:00.000Z".to_string(), cwd: PathBuf::from("/workspace"), + workspace_roots: Vec::new(), originator: "codex_cli_rs".to_string(), cli_version: "0.0.0".to_string(), source: SessionSource::Cli, diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs index 1795a864d8..87cb09d907 100644 --- a/codex-rs/state/src/runtime/threads.rs +++ b/codex-rs/state/src/runtime/threads.rs @@ -1373,6 +1373,7 @@ mod tests { forked_from_id: None, timestamp: metadata.created_at.to_rfc3339(), cwd: PathBuf::new(), + workspace_roots: Vec::new(), originator: String::new(), cli_version: String::new(), source: SessionSource::Cli, @@ -1432,6 +1433,7 @@ mod tests { forked_from_id: None, timestamp: created_at, cwd: PathBuf::new(), + workspace_roots: Vec::new(), originator: String::new(), cli_version: String::new(), source: SessionSource::Cli, diff --git a/codex-rs/stdio-to-uds/Cargo.toml b/codex-rs/stdio-to-uds/Cargo.toml index 76d2176927..6b5c037d75 100644 --- a/codex-rs/stdio-to-uds/Cargo.toml +++ b/codex-rs/stdio-to-uds/Cargo.toml @@ -11,6 +11,8 @@ path = "src/main.rs" [lib] name = "codex_stdio_to_uds" path = "src/lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/terminal-detection/Cargo.toml b/codex-rs/terminal-detection/Cargo.toml index f75e649d36..9b1bf3a516 100644 --- a/codex-rs/terminal-detection/Cargo.toml +++ b/codex-rs/terminal-detection/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_terminal_detection" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/test-binary-support/Cargo.toml b/codex-rs/test-binary-support/Cargo.toml index e604f8c0a0..12d995b972 100644 --- a/codex-rs/test-binary-support/Cargo.toml +++ b/codex-rs/test-binary-support/Cargo.toml @@ -6,6 +6,8 @@ license.workspace = true [lib] path = "lib.rs" +test = false +doctest = false [lints] workspace = true diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index 6817f677e6..6c7bf40207 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -207,6 +207,7 @@ fn new_config(model: Option, arg0_paths: Arg0DispatchPaths) -> anyhow::R tui_session_picker_view: SessionPickerViewMode::Dense, tui_vim_mode_default: false, cwd, + workspace_roots: Vec::new(), cli_auth_credentials_store_mode: AuthCredentialsStoreMode::File, mcp_servers: Constrained::allow_any(HashMap::new()), mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode::File, diff --git a/codex-rs/thread-store/Cargo.toml b/codex-rs/thread-store/Cargo.toml index 3a0428f20e..765db63098 100644 --- a/codex-rs/thread-store/Cargo.toml +++ b/codex-rs/thread-store/Cargo.toml @@ -7,10 +7,7 @@ version.workspace = true [lib] name = "codex_thread_store" path = "src/lib.rs" - -[[example]] -name = "generate-proto" -path = "examples/generate-proto.rs" +doctest = false [lints] workspace = true @@ -22,20 +19,15 @@ codex-git-utils = { workspace = true } codex-protocol = { workspace = true } codex-rollout = { workspace = true } codex-state = { workspace = true } -prost = "0.14.3" +codex-utils-absolute-path = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } -tonic = { workspace = true } -tonic-prost = { workspace = true } tracing = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } -tokio-stream = { workspace = true, features = ["net"] } -tonic = { workspace = true, features = ["router", "transport"] } -tonic-prost-build = { version = "=0.14.3", default-features = false, features = ["transport"] } uuid = { workspace = true } diff --git a/codex-rs/thread-store/examples/generate-proto.rs b/codex-rs/thread-store/examples/generate-proto.rs deleted file mode 100644 index 0b4afb54f9..0000000000 --- a/codex-rs/thread-store/examples/generate-proto.rs +++ /dev/null @@ -1,19 +0,0 @@ -use std::path::PathBuf; - -fn main() -> Result<(), Box> { - let Some(proto_dir_arg) = std::env::args().nth(1) else { - eprintln!("Usage: generate-proto "); - std::process::exit(1); - }; - - let proto_dir = PathBuf::from(proto_dir_arg); - let proto_file = proto_dir.join("codex.thread_store.v1.proto"); - - tonic_prost_build::configure() - .build_client(true) - .build_server(true) - .out_dir(&proto_dir) - .compile_protos(&[proto_file], &[proto_dir])?; - - Ok(()) -} diff --git a/codex-rs/thread-store/scripts/generate-proto.sh b/codex-rs/thread-store/scripts/generate-proto.sh deleted file mode 100755 index 4045467cac..0000000000 --- a/codex-rs/thread-store/scripts/generate-proto.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -repo_root="$(cd "$script_dir/../../.." && pwd)" -proto_dir="$repo_root/codex-rs/thread-store/src/remote/proto" -generated="$proto_dir/codex.thread_store.v1.rs" -tmpdir="$(mktemp -d)" - -cleanup() { - rm -rf "$tmpdir" -} -trap cleanup EXIT - -( - cd "$repo_root/codex-rs" - CARGO_TARGET_DIR="$tmpdir/target" cargo run \ - -p codex-thread-store \ - --example generate-proto \ - -- "$proto_dir" -) - -if ! sed -n '2p' "$generated" | grep -q 'clippy::trivially_copy_pass_by_ref'; then - { - sed -n '1p' "$generated" - printf '#![allow(clippy::trivially_copy_pass_by_ref)]\n' - sed '1d' "$generated" - } > "$tmpdir/generated.rs" - mv "$tmpdir/generated.rs" "$generated" -fi - -rustfmt --edition 2024 "$generated" - -awk ' - NR == 3 && previous ~ /clippy::trivially_copy_pass_by_ref/ && $0 != "" { print "" } - { print; previous = $0 } -' "$generated" > "$tmpdir/formatted.rs" -mv "$tmpdir/formatted.rs" "$generated" diff --git a/codex-rs/thread-store/src/error.rs b/codex-rs/thread-store/src/error.rs index c5cee9a8b8..2244c93185 100644 --- a/codex-rs/thread-store/src/error.rs +++ b/codex-rs/thread-store/src/error.rs @@ -27,6 +27,13 @@ pub enum ThreadStoreError { message: String, }, + /// The store implementation does not support this operation yet. + #[error("thread-store unsupported operation: {operation}")] + Unsupported { + /// Stable operation name for callers that need to map unsupported operations. + operation: &'static str, + }, + /// Catch-all for implementation failures that do not fit a more specific category. #[error("thread-store internal error: {message}")] Internal { diff --git a/codex-rs/thread-store/src/in_memory.rs b/codex-rs/thread-store/src/in_memory.rs index 77739260b8..1483906267 100644 --- a/codex-rs/thread-store/src/in_memory.rs +++ b/codex-rs/thread-store/src/in_memory.rs @@ -35,6 +35,57 @@ fn stores() -> &'static Mutex>> { IN_MEMORY_THREAD_STORES.get_or_init(|| Mutex::new(HashMap::new())) } +#[cfg(test)] +mod tests { + use super::*; + use crate::ListItemsParams; + use crate::ListTurnsParams; + use crate::SortDirection; + use crate::StoredTurnItemsView; + + #[tokio::test] + async fn default_turn_pagination_methods_return_unsupported() { + let store = InMemoryThreadStore::default(); + let thread_id = ThreadId::default(); + + let turns_err = store + .list_turns(ListTurnsParams { + thread_id, + include_archived: true, + cursor: None, + page_size: 10, + sort_direction: SortDirection::Asc, + items_view: StoredTurnItemsView::Summary, + }) + .await + .expect_err("default list_turns should be unsupported"); + assert!(matches!( + turns_err, + ThreadStoreError::Unsupported { + operation: "list_turns" + } + )); + + let items_err = store + .list_items(ListItemsParams { + thread_id, + turn_id: "turn_1".to_string(), + include_archived: true, + cursor: None, + page_size: 10, + sort_direction: SortDirection::Asc, + }) + .await + .expect_err("default list_items should be unsupported"); + assert!(matches!( + items_err, + ThreadStoreError::Unsupported { + operation: "list_items" + } + )); + } +} + fn stores_guard() -> MutexGuard<'static, HashMap>> { match stores().lock() { Ok(guard) => guard, diff --git a/codex-rs/thread-store/src/lib.rs b/codex-rs/thread-store/src/lib.rs index 52b7f5ea1f..c7f6b4eaed 100644 --- a/codex-rs/thread-store/src/lib.rs +++ b/codex-rs/thread-store/src/lib.rs @@ -8,7 +8,6 @@ mod error; mod in_memory; mod live_thread; mod local; -mod remote; mod store; mod types; @@ -20,13 +19,15 @@ pub use live_thread::LiveThread; pub use live_thread::LiveThreadInitGuard; pub use local::LocalThreadStore; pub use local::LocalThreadStoreConfig; -pub use remote::RemoteThreadStore; pub use store::ThreadStore; pub use types::AppendThreadItemsParams; pub use types::ArchiveThreadParams; pub use types::CreateThreadParams; pub use types::GitInfoPatch; +pub use types::ItemPage; +pub use types::ListItemsParams; pub use types::ListThreadsParams; +pub use types::ListTurnsParams; pub use types::LoadThreadHistoryParams; pub use types::OptionalStringPatch; pub use types::ReadThreadByRolloutPathParams; @@ -35,9 +36,14 @@ pub use types::ResumeThreadParams; pub use types::SortDirection; pub use types::StoredThread; pub use types::StoredThreadHistory; +pub use types::StoredTurn; +pub use types::StoredTurnError; +pub use types::StoredTurnItemsView; +pub use types::StoredTurnStatus; pub use types::ThreadEventPersistenceMode; pub use types::ThreadMetadataPatch; pub use types::ThreadPage; pub use types::ThreadPersistenceMetadata; pub use types::ThreadSortKey; +pub use types::TurnPage; pub use types::UpdateThreadMetadataParams; diff --git a/codex-rs/thread-store/src/local/create_thread.rs b/codex-rs/thread-store/src/local/create_thread.rs index d181149406..0f9f761c5c 100644 --- a/codex-rs/thread-store/src/local/create_thread.rs +++ b/codex-rs/thread-store/src/local/create_thread.rs @@ -24,6 +24,7 @@ pub(super) async fn create_thread( codex_home: store.config.codex_home.clone(), sqlite_home: store.config.sqlite_home.clone(), cwd, + workspace_roots: params.metadata.workspace_roots, model_provider_id: params.metadata.model_provider.clone(), generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled), }; diff --git a/codex-rs/thread-store/src/local/list_threads.rs b/codex-rs/thread-store/src/local/list_threads.rs index e470ad2be9..e22df477f4 100644 --- a/codex-rs/thread-store/src/local/list_threads.rs +++ b/codex-rs/thread-store/src/local/list_threads.rs @@ -44,6 +44,7 @@ pub(super) async fn list_threads( codex_home: store.config.codex_home.clone(), sqlite_home: store.config.sqlite_home.clone(), cwd: store.config.codex_home.clone(), + workspace_roots: Vec::new(), model_provider_id: store.config.default_model_provider_id.clone(), generate_memories: false, }; diff --git a/codex-rs/thread-store/src/local/live_writer.rs b/codex-rs/thread-store/src/local/live_writer.rs index 643207b59d..2d7ae64397 100644 --- a/codex-rs/thread-store/src/local/live_writer.rs +++ b/codex-rs/thread-store/src/local/live_writer.rs @@ -68,6 +68,7 @@ pub(super) async fn resume_thread( codex_home: store.config.codex_home.clone(), sqlite_home: store.config.sqlite_home.clone(), cwd, + workspace_roots: params.metadata.workspace_roots, model_provider_id: params.metadata.model_provider.clone(), generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled), }; diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index 07aa5e925f..355c32f8d5 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -519,6 +519,7 @@ mod tests { include_archived: true, metadata: ThreadPersistenceMetadata { cwd: None, + workspace_roots: Vec::new(), model_provider: "test-provider".to_string(), memory_mode: ThreadMemoryMode::Enabled, }, @@ -749,6 +750,7 @@ mod tests { fn thread_metadata() -> ThreadPersistenceMetadata { ThreadPersistenceMetadata { cwd: Some(std::env::current_dir().expect("cwd")), + workspace_roots: Vec::new(), model_provider: "test-provider".to_string(), memory_mode: ThreadMemoryMode::Enabled, } diff --git a/codex-rs/thread-store/src/local/update_thread_metadata.rs b/codex-rs/thread-store/src/local/update_thread_metadata.rs index ef69cfa8b8..853cf51272 100644 --- a/codex-rs/thread-store/src/local/update_thread_metadata.rs +++ b/codex-rs/thread-store/src/local/update_thread_metadata.rs @@ -1019,6 +1019,7 @@ mod tests { fn test_thread_metadata() -> ThreadPersistenceMetadata { ThreadPersistenceMetadata { cwd: Some(std::env::current_dir().expect("cwd")), + workspace_roots: Vec::new(), model_provider: "test-provider".to_string(), memory_mode: ThreadMemoryMode::Enabled, } diff --git a/codex-rs/thread-store/src/remote/AGENTS.md b/codex-rs/thread-store/src/remote/AGENTS.md deleted file mode 100644 index b2b2b6417b..0000000000 --- a/codex-rs/thread-store/src/remote/AGENTS.md +++ /dev/null @@ -1,13 +0,0 @@ -# Remote Thread Store - -- The Rust protobuf output in `proto/codex.thread_store.v1.rs` is checked in. -- Do not add build-time protobuf generation to `codex-thread-store` unless the Bazel/Cargo story is intentionally changed. -- When `proto/codex.thread_store.v1.proto` changes, regenerate the Rust file manually and include both files in the same commit. - -Run this from the repository root: - -```sh -./codex-rs/thread-store/scripts/generate-proto.sh -``` - -The command requires `protoc` to be available on `PATH`. diff --git a/codex-rs/thread-store/src/remote/helpers.rs b/codex-rs/thread-store/src/remote/helpers.rs deleted file mode 100644 index 3322ecd142..0000000000 --- a/codex-rs/thread-store/src/remote/helpers.rs +++ /dev/null @@ -1,457 +0,0 @@ -use std::path::PathBuf; -use std::str::FromStr; - -use chrono::DateTime; -use chrono::Utc; -use codex_git_utils::GitSha; -use codex_protocol::AgentPath; -use codex_protocol::ThreadId; -use codex_protocol::dynamic_tools::DynamicToolSpec; -use codex_protocol::models::BaseInstructions; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::GitInfo; -use codex_protocol::protocol::RolloutItem; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::ThreadMemoryMode; -use codex_protocol::protocol::ThreadSource; - -use super::proto; -use crate::GitInfoPatch; -use crate::OptionalStringPatch; -use crate::SortDirection; -use crate::StoredThread; -use crate::StoredThreadHistory; -use crate::ThreadEventPersistenceMode; -use crate::ThreadMetadataPatch; -use crate::ThreadPersistenceMetadata; -use crate::ThreadSortKey; -use crate::ThreadStoreError; -use crate::ThreadStoreResult; - -pub(super) fn remote_status_to_error(status: tonic::Status) -> ThreadStoreError { - match status.code() { - tonic::Code::InvalidArgument => ThreadStoreError::InvalidRequest { - message: status.message().to_string(), - }, - tonic::Code::AlreadyExists | tonic::Code::FailedPrecondition | tonic::Code::Aborted => { - ThreadStoreError::Conflict { - message: status.message().to_string(), - } - } - _ => ThreadStoreError::Internal { - message: format!("remote thread store request failed: {status}"), - }, - } -} - -pub(super) fn remote_status_to_thread_error( - status: tonic::Status, - thread_id: ThreadId, -) -> ThreadStoreError { - if status.code() == tonic::Code::NotFound { - return ThreadStoreError::ThreadNotFound { thread_id }; - } - remote_status_to_error(status) -} - -pub(super) fn proto_thread_id_request(thread_id: ThreadId) -> proto::ThreadIdRequest { - proto::ThreadIdRequest { - thread_id: thread_id.to_string(), - } -} - -pub(super) fn proto_sort_key(sort_key: ThreadSortKey) -> proto::ThreadSortKey { - match sort_key { - ThreadSortKey::CreatedAt => proto::ThreadSortKey::CreatedAt, - ThreadSortKey::UpdatedAt => proto::ThreadSortKey::UpdatedAt, - } -} - -pub(super) fn proto_sort_direction(sort_direction: SortDirection) -> proto::SortDirection { - match sort_direction { - SortDirection::Asc => proto::SortDirection::Asc, - SortDirection::Desc => proto::SortDirection::Desc, - } -} - -pub(super) fn proto_event_persistence_mode( - mode: ThreadEventPersistenceMode, -) -> proto::ThreadEventPersistenceMode { - match mode { - ThreadEventPersistenceMode::Limited => proto::ThreadEventPersistenceMode::Limited, - ThreadEventPersistenceMode::Extended => proto::ThreadEventPersistenceMode::Extended, - } -} - -pub(super) fn proto_session_source(source: &SessionSource) -> proto::SessionSource { - match source { - SessionSource::Cli => proto_source(proto::SessionSourceKind::Cli), - SessionSource::VSCode => proto_source(proto::SessionSourceKind::Vscode), - SessionSource::Exec => proto_source(proto::SessionSourceKind::Exec), - SessionSource::Mcp => proto_source(proto::SessionSourceKind::AppServer), - SessionSource::Custom(custom) => proto::SessionSource { - kind: proto::SessionSourceKind::Custom.into(), - custom: Some(custom.clone()), - ..Default::default() - }, - SessionSource::SubAgent(SubAgentSource::Review) => { - proto_source(proto::SessionSourceKind::SubAgentReview) - } - SessionSource::SubAgent(SubAgentSource::Compact) => { - proto_source(proto::SessionSourceKind::SubAgentCompact) - } - SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id, - depth, - agent_path, - agent_nickname, - agent_role, - }) => proto::SessionSource { - kind: proto::SessionSourceKind::SubAgentThreadSpawn.into(), - sub_agent_parent_thread_id: Some(parent_thread_id.to_string()), - sub_agent_depth: Some(*depth), - sub_agent_path: agent_path.as_ref().map(|path| path.as_str().to_string()), - sub_agent_nickname: agent_nickname.clone(), - sub_agent_role: agent_role.clone(), - ..Default::default() - }, - SessionSource::SubAgent(SubAgentSource::MemoryConsolidation) => { - proto_source(proto::SessionSourceKind::SubAgentMemoryConsolidation) - } - SessionSource::SubAgent(SubAgentSource::Other(other)) => proto::SessionSource { - kind: proto::SessionSourceKind::SubAgentOther.into(), - sub_agent_other: Some(other.clone()), - ..Default::default() - }, - SessionSource::Internal(_) => proto_source(proto::SessionSourceKind::Unknown), - SessionSource::Unknown => proto_source(proto::SessionSourceKind::Unknown), - } -} - -fn proto_source(kind: proto::SessionSourceKind) -> proto::SessionSource { - proto::SessionSource { - kind: kind.into(), - ..Default::default() - } -} - -pub(super) fn serialize_json( - value: &T, - field_name: &str, -) -> ThreadStoreResult { - serde_json::to_string(value).map_err(|err| ThreadStoreError::InvalidRequest { - message: format!("failed to serialize {field_name} for remote thread store: {err}"), - }) -} - -fn deserialize_json( - json: &str, - field_name: &str, -) -> ThreadStoreResult { - serde_json::from_str(json).map_err(|err| ThreadStoreError::InvalidRequest { - message: format!("remote thread store returned invalid {field_name}: {err}"), - }) -} - -pub(super) fn serialize_json_vec( - values: &[T], - field_name: &str, -) -> ThreadStoreResult> { - values - .iter() - .map(|value| serialize_json(value, field_name)) - .collect() -} - -fn deserialize_json_vec( - values: &[String], - field_name: &str, -) -> ThreadStoreResult> { - values - .iter() - .map(|value| deserialize_json(value, field_name)) - .collect() -} - -pub(super) fn base_instructions_json( - base_instructions: &BaseInstructions, -) -> ThreadStoreResult { - serialize_json(base_instructions, "base_instructions") -} - -pub(super) fn dynamic_tools_json( - dynamic_tools: &[DynamicToolSpec], -) -> ThreadStoreResult> { - serialize_json_vec(dynamic_tools, "dynamic_tool") -} - -pub(super) fn thread_persistence_metadata_json( - metadata: &ThreadPersistenceMetadata, -) -> ThreadStoreResult { - serialize_json(metadata, "thread_persistence_metadata") -} - -pub(super) fn rollout_items_json(items: &[RolloutItem]) -> ThreadStoreResult> { - serialize_json_vec(items, "rollout_item") -} - -pub(super) fn stored_thread_history_from_proto( - history: proto::StoredThreadHistory, -) -> ThreadStoreResult { - let thread_id = ThreadId::from_string(&history.thread_id).map_err(|err| { - ThreadStoreError::InvalidRequest { - message: format!("remote thread store returned invalid history thread_id: {err}"), - } - })?; - Ok(StoredThreadHistory { - thread_id, - items: deserialize_json_vec(&history.items_json, "rollout_item")?, - }) -} - -pub(super) fn proto_metadata_patch(patch: ThreadMetadataPatch) -> proto::ThreadMetadataPatch { - proto::ThreadMetadataPatch { - name: patch.name, - memory_mode: patch.memory_mode.map(proto_memory_mode).map(Into::into), - git_info: patch.git_info.map(proto_git_info_patch), - } -} - -fn proto_memory_mode(memory_mode: ThreadMemoryMode) -> proto::ThreadMemoryMode { - match memory_mode { - ThreadMemoryMode::Enabled => proto::ThreadMemoryMode::Enabled, - ThreadMemoryMode::Disabled => proto::ThreadMemoryMode::Disabled, - } -} - -fn proto_git_info_patch(patch: GitInfoPatch) -> proto::GitInfoPatch { - proto::GitInfoPatch { - sha: Some(proto_optional_string_patch(patch.sha)), - branch: Some(proto_optional_string_patch(patch.branch)), - origin_url: Some(proto_optional_string_patch(patch.origin_url)), - } -} - -fn proto_optional_string_patch(patch: OptionalStringPatch) -> proto::OptionalStringPatch { - match patch { - None => proto::OptionalStringPatch { - kind: proto::OptionalStringPatchKind::Unset.into(), - value: None, - }, - Some(None) => proto::OptionalStringPatch { - kind: proto::OptionalStringPatchKind::Clear.into(), - value: None, - }, - Some(Some(value)) => proto::OptionalStringPatch { - kind: proto::OptionalStringPatchKind::Set.into(), - value: Some(value), - }, - } -} - -pub(super) fn stored_thread_from_proto( - thread: proto::StoredThread, -) -> ThreadStoreResult { - // Keep this mapping boring: the proto mirrors StoredThread for remote-readable - // summary fields, except for Rust domain types that cross gRPC as stable scalar - // values. Local-only fields such as rollout_path intentionally stay local. - let source = thread - .source - .as_ref() - .map(session_source_from_proto) - .transpose()? - .unwrap_or(SessionSource::Unknown); - let thread_id = ThreadId::from_string(&thread.thread_id).map_err(|err| { - ThreadStoreError::InvalidRequest { - message: format!("remote thread store returned invalid thread_id: {err}"), - } - })?; - let forked_from_id = thread - .forked_from_id - .as_deref() - .map(ThreadId::from_string) - .transpose() - .map_err(|err| ThreadStoreError::InvalidRequest { - message: format!("remote thread store returned invalid forked_from_id: {err}"), - })?; - - Ok(StoredThread { - thread_id, - rollout_path: thread.rollout_path.map(PathBuf::from), - forked_from_id, - preview: thread.preview, - name: thread.name, - model_provider: thread.model_provider, - model: thread.model, - reasoning_effort: thread - .reasoning_effort - .as_deref() - .map(parse_reasoning_effort) - .transpose()?, - created_at: datetime_from_unix(thread.created_at)?, - updated_at: datetime_from_unix(thread.updated_at)?, - archived_at: thread.archived_at.map(datetime_from_unix).transpose()?, - cwd: PathBuf::from(thread.cwd), - cli_version: thread.cli_version, - source, - thread_source: thread - .thread_source - .map(|thread_source| thread_source.parse::()) - .transpose() - .map_err(|error| ThreadStoreError::Internal { message: error })?, - agent_nickname: thread.agent_nickname, - agent_role: thread.agent_role, - agent_path: thread.agent_path, - git_info: thread.git_info.map(git_info_from_proto), - approval_mode: thread - .approval_mode_json - .as_deref() - .map(|json| deserialize_json(json, "approval_mode")) - .transpose()? - .unwrap_or(AskForApproval::OnRequest), - sandbox_policy: thread - .sandbox_policy_json - .as_deref() - .map(|json| deserialize_json(json, "sandbox_policy")) - .transpose()? - .unwrap_or_else(SandboxPolicy::new_read_only_policy), - token_usage: thread - .token_usage_json - .as_deref() - .map(|json| deserialize_json(json, "token_usage")) - .transpose()?, - first_user_message: thread.first_user_message, - history: thread - .history - .map(stored_thread_history_from_proto) - .transpose()?, - }) -} - -#[cfg(test)] -pub(super) fn stored_thread_to_proto(thread: StoredThread) -> proto::StoredThread { - proto::StoredThread { - thread_id: thread.thread_id.to_string(), - forked_from_id: thread.forked_from_id.map(|thread_id| thread_id.to_string()), - preview: thread.preview, - name: thread.name, - model_provider: thread.model_provider, - model: thread.model, - created_at: thread.created_at.timestamp(), - updated_at: thread.updated_at.timestamp(), - archived_at: thread.archived_at.map(|timestamp| timestamp.timestamp()), - cwd: thread.cwd.to_string_lossy().into_owned(), - cli_version: thread.cli_version, - source: Some(proto_session_source(&thread.source)), - thread_source: thread.thread_source.map(|source| source.to_string()), - git_info: thread.git_info.map(git_info_to_proto), - agent_nickname: thread.agent_nickname, - agent_role: thread.agent_role, - agent_path: thread.agent_path, - reasoning_effort: thread.reasoning_effort.map(|effort| effort.to_string()), - first_user_message: thread.first_user_message, - rollout_path: thread - .rollout_path - .map(|path| path.to_string_lossy().into_owned()), - approval_mode_json: Some(serialize_json(&thread.approval_mode, "approval_mode").unwrap()), - sandbox_policy_json: Some( - serialize_json(&thread.sandbox_policy, "sandbox_policy").unwrap(), - ), - token_usage_json: thread - .token_usage - .as_ref() - .map(|usage| serialize_json(usage, "token_usage").unwrap()), - history: thread.history.map(stored_thread_history_to_proto), - } -} - -#[cfg(test)] -fn stored_thread_history_to_proto(history: StoredThreadHistory) -> proto::StoredThreadHistory { - proto::StoredThreadHistory { - thread_id: history.thread_id.to_string(), - items_json: rollout_items_json(&history.items).unwrap(), - } -} - -fn datetime_from_unix(timestamp: i64) -> ThreadStoreResult> { - DateTime::from_timestamp(timestamp, 0).ok_or_else(|| ThreadStoreError::InvalidRequest { - message: format!("remote thread store returned invalid timestamp: {timestamp}"), - }) -} - -fn session_source_from_proto(source: &proto::SessionSource) -> ThreadStoreResult { - let kind = proto::SessionSourceKind::try_from(source.kind).unwrap_or_default(); - Ok(match kind { - proto::SessionSourceKind::Unknown => SessionSource::Unknown, - proto::SessionSourceKind::Cli => SessionSource::Cli, - proto::SessionSourceKind::Vscode => SessionSource::VSCode, - proto::SessionSourceKind::Exec => SessionSource::Exec, - proto::SessionSourceKind::AppServer => SessionSource::Mcp, - proto::SessionSourceKind::Custom => { - SessionSource::Custom(source.custom.clone().unwrap_or_default()) - } - proto::SessionSourceKind::SubAgentReview => SessionSource::SubAgent(SubAgentSource::Review), - proto::SessionSourceKind::SubAgentCompact => { - SessionSource::SubAgent(SubAgentSource::Compact) - } - proto::SessionSourceKind::SubAgentThreadSpawn => { - let parent_thread_id = source - .sub_agent_parent_thread_id - .as_deref() - .map(ThreadId::from_string) - .transpose() - .map_err(|err| ThreadStoreError::InvalidRequest { - message: format!( - "remote thread store returned invalid sub-agent parent thread id: {err}" - ), - })? - .ok_or_else(|| ThreadStoreError::InvalidRequest { - message: "remote thread store omitted sub-agent parent thread id".to_string(), - })?; - SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id, - depth: source.sub_agent_depth.unwrap_or_default(), - agent_path: source - .sub_agent_path - .clone() - .map(AgentPath::from_string) - .transpose() - .map_err(|message| ThreadStoreError::InvalidRequest { message })?, - agent_nickname: source.sub_agent_nickname.clone(), - agent_role: source.sub_agent_role.clone(), - }) - } - proto::SessionSourceKind::SubAgentMemoryConsolidation => { - SessionSource::SubAgent(SubAgentSource::MemoryConsolidation) - } - proto::SessionSourceKind::SubAgentOther => SessionSource::SubAgent(SubAgentSource::Other( - source.sub_agent_other.clone().unwrap_or_default(), - )), - }) -} - -fn git_info_from_proto(info: proto::GitInfo) -> GitInfo { - GitInfo { - commit_hash: info.sha.as_deref().map(GitSha::new), - branch: info.branch, - repository_url: info.origin_url, - } -} - -#[cfg(test)] -fn git_info_to_proto(info: GitInfo) -> proto::GitInfo { - proto::GitInfo { - sha: info.commit_hash.map(|sha| sha.0), - branch: info.branch, - origin_url: info.repository_url, - } -} - -fn parse_reasoning_effort(value: &str) -> ThreadStoreResult { - ReasoningEffort::from_str(value).map_err(|message| ThreadStoreError::InvalidRequest { - message: format!("remote thread store returned {message}"), - }) -} diff --git a/codex-rs/thread-store/src/remote/list_threads.rs b/codex-rs/thread-store/src/remote/list_threads.rs deleted file mode 100644 index cf562497f4..0000000000 --- a/codex-rs/thread-store/src/remote/list_threads.rs +++ /dev/null @@ -1,282 +0,0 @@ -use super::RemoteThreadStore; -use super::helpers::proto_session_source; -use super::helpers::proto_sort_direction; -use super::helpers::proto_sort_key; -use super::helpers::remote_status_to_error; -use super::helpers::stored_thread_from_proto; -use super::proto; -use crate::ListThreadsParams; -use crate::ThreadPage; -use crate::ThreadStoreError; -use crate::ThreadStoreResult; - -pub(super) async fn list_threads( - store: &RemoteThreadStore, - params: ListThreadsParams, -) -> ThreadStoreResult { - let request = proto::ListThreadsRequest { - page_size: params - .page_size - .try_into() - .map_err(|_| ThreadStoreError::InvalidRequest { - message: format!("page_size is too large: {}", params.page_size), - })?, - cursor: params.cursor, - sort_key: proto_sort_key(params.sort_key).into(), - sort_direction: proto_sort_direction(params.sort_direction).into(), - allowed_sources: params - .allowed_sources - .iter() - .map(proto_session_source) - .collect(), - model_provider_filter: params - .model_providers - .map(|values| proto::ModelProviderFilter { values }), - cwd_filter: params.cwd_filters.map(|values| proto::CwdFilter { - values: values - .into_iter() - .map(|cwd| cwd.display().to_string()) - .collect(), - }), - archived: params.archived, - search_term: params.search_term, - use_state_db_only: params.use_state_db_only, - }; - - let response = store - .client() - .await? - .list_threads(request) - .await - .map_err(remote_status_to_error)? - .into_inner(); - - let items = response - .threads - .into_iter() - .map(stored_thread_from_proto) - .collect::>>()?; - - Ok(ThreadPage { - items, - next_cursor: response.next_cursor, - }) -} - -#[cfg(test)] -mod tests { - use std::path::PathBuf; - - use codex_protocol::openai_models::ReasoningEffort; - use codex_protocol::protocol::SessionSource; - use pretty_assertions::assert_eq; - use tonic::Request; - use tonic::Response; - use tonic::Status; - use tonic::transport::Server; - - use super::super::helpers::stored_thread_to_proto; - use super::super::proto::thread_store_server; - use super::super::proto::thread_store_server::ThreadStoreServer; - use super::*; - use crate::ThreadSortKey; - use crate::ThreadStore; - - #[derive(Default)] - struct TestServer; - - #[tonic::async_trait] - impl thread_store_server::ThreadStore for TestServer { - async fn list_threads( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - assert_eq!(request.page_size, 2); - assert_eq!(request.cursor.as_deref(), Some("cursor-1")); - assert_eq!( - proto::ThreadSortKey::try_from(request.sort_key), - Ok(proto::ThreadSortKey::UpdatedAt) - ); - assert_eq!( - proto::SortDirection::try_from(request.sort_direction), - Ok(proto::SortDirection::Desc) - ); - assert_eq!(request.archived, true); - assert_eq!(request.search_term.as_deref(), Some("needle")); - assert!(request.use_state_db_only); - assert_eq!( - request.model_provider_filter, - Some(proto::ModelProviderFilter { - values: vec!["openai".to_string()], - }) - ); - assert_eq!( - request.cwd_filter, - Some(proto::CwdFilter { - values: vec!["/workspace".to_string()], - }) - ); - assert_eq!(request.allowed_sources.len(), 1); - assert_eq!( - proto::SessionSourceKind::try_from(request.allowed_sources[0].kind), - Ok(proto::SessionSourceKind::Cli) - ); - - Ok(Response::new(proto::ListThreadsResponse { - threads: vec![proto::StoredThread { - thread_id: "11111111-1111-1111-1111-111111111111".to_string(), - forked_from_id: None, - preview: "hello".to_string(), - name: Some("named thread".to_string()), - model_provider: "openai".to_string(), - model: Some("gpt-5".to_string()), - created_at: 100, - updated_at: 200, - archived_at: Some(300), - cwd: "/workspace".to_string(), - cli_version: "1.2.3".to_string(), - source: Some(proto::SessionSource { - kind: proto::SessionSourceKind::Cli.into(), - ..Default::default() - }), - thread_source: Some("user".to_string()), - git_info: Some(proto::GitInfo { - sha: Some("abc123".to_string()), - branch: Some("main".to_string()), - origin_url: Some("https://example.test/repo.git".to_string()), - }), - agent_nickname: None, - agent_role: None, - agent_path: None, - reasoning_effort: Some("medium".to_string()), - first_user_message: Some("hello".to_string()), - rollout_path: None, - approval_mode_json: None, - sandbox_policy_json: None, - token_usage_json: None, - history: None, - }], - next_cursor: Some("cursor-2".to_string()), - })) - } - } - - #[tokio::test] - async fn list_threads_calls_remote_service() { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind test server"); - let addr = listener.local_addr().expect("test server addr"); - let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - Server::builder() - .add_service(ThreadStoreServer::new(TestServer)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = shutdown_rx.await; - }, - ) - .await - }); - - let store = RemoteThreadStore::new(format!("http://{addr}")); - let page = store - .list_threads(ListThreadsParams { - page_size: 2, - cursor: Some("cursor-1".to_string()), - sort_key: ThreadSortKey::UpdatedAt, - sort_direction: crate::SortDirection::Desc, - allowed_sources: vec![SessionSource::Cli], - model_providers: Some(vec!["openai".to_string()]), - cwd_filters: Some(vec![PathBuf::from("/workspace")]), - archived: true, - search_term: Some("needle".to_string()), - use_state_db_only: true, - }) - .await - .expect("list threads"); - - assert_eq!(page.next_cursor.as_deref(), Some("cursor-2")); - assert_eq!(page.items.len(), 1); - let item = &page.items[0]; - assert_eq!( - item.thread_id.to_string(), - "11111111-1111-1111-1111-111111111111" - ); - assert_eq!(item.name.as_deref(), Some("named thread")); - assert_eq!(item.preview, "hello"); - assert_eq!(item.first_user_message.as_deref(), Some("hello")); - assert_eq!(item.model_provider, "openai"); - assert_eq!(item.model.as_deref(), Some("gpt-5")); - assert_eq!(item.created_at.timestamp(), 100); - assert_eq!(item.updated_at.timestamp(), 200); - assert_eq!(item.archived_at.map(|ts| ts.timestamp()), Some(300)); - assert_eq!(item.cwd, PathBuf::from("/workspace")); - assert_eq!(item.cli_version, "1.2.3"); - assert_eq!(item.source, SessionSource::Cli); - assert_eq!(item.reasoning_effort, Some(ReasoningEffort::Medium)); - assert_eq!( - item.git_info.as_ref().and_then(|git| git.branch.as_deref()), - Some("main") - ); - - let _ = shutdown_tx.send(()); - server.await.expect("join server").expect("server"); - } - - #[test] - fn stored_thread_proto_roundtrips_through_domain_type() { - let thread = proto::StoredThread { - thread_id: "11111111-1111-1111-1111-111111111111".to_string(), - forked_from_id: Some("22222222-2222-2222-2222-222222222222".to_string()), - preview: "preview text".to_string(), - name: Some("named thread".to_string()), - model_provider: "openai".to_string(), - model: Some("gpt-5".to_string()), - created_at: 100, - updated_at: 200, - archived_at: Some(300), - cwd: "/workspace/project".to_string(), - cli_version: "1.2.3".to_string(), - source: Some(proto::SessionSource { - kind: proto::SessionSourceKind::SubAgentThreadSpawn.into(), - sub_agent_parent_thread_id: Some( - "33333333-3333-3333-3333-333333333333".to_string(), - ), - sub_agent_depth: Some(2), - sub_agent_path: Some("/root/review/backend".to_string()), - sub_agent_nickname: Some("Navigator".to_string()), - sub_agent_role: Some("explorer".to_string()), - ..Default::default() - }), - thread_source: Some("subagent".to_string()), - git_info: Some(proto::GitInfo { - sha: Some("abc123".to_string()), - branch: Some("main".to_string()), - origin_url: Some("https://example.test/repo.git".to_string()), - }), - agent_nickname: Some("Navigator".to_string()), - agent_role: Some("explorer".to_string()), - agent_path: Some("/root/review/backend".to_string()), - reasoning_effort: Some("high".to_string()), - first_user_message: Some("first message".to_string()), - rollout_path: None, - approval_mode_json: None, - sandbox_policy_json: None, - token_usage_json: None, - history: None, - }; - - let stored = stored_thread_from_proto(thread.clone()).expect("proto to stored thread"); - - assert_eq!(stored.rollout_path, None); - assert!(stored.history.is_none()); - let roundtripped = stored_thread_to_proto(stored); - assert_eq!(roundtripped.thread_id, thread.thread_id); - assert_eq!(roundtripped.forked_from_id, thread.forked_from_id); - assert_eq!(roundtripped.source, thread.source); - assert_eq!(roundtripped.git_info, thread.git_info); - } -} diff --git a/codex-rs/thread-store/src/remote/mod.rs b/codex-rs/thread-store/src/remote/mod.rs deleted file mode 100644 index 013b74c933..0000000000 --- a/codex-rs/thread-store/src/remote/mod.rs +++ /dev/null @@ -1,410 +0,0 @@ -mod helpers; -mod list_threads; - -use async_trait::async_trait; -use codex_protocol::ThreadId; - -use crate::AppendThreadItemsParams; -use crate::ArchiveThreadParams; -use crate::CreateThreadParams; -use crate::ListThreadsParams; -use crate::LoadThreadHistoryParams; -use crate::ReadThreadByRolloutPathParams; -use crate::ReadThreadParams; -use crate::ResumeThreadParams; -use crate::StoredThread; -use crate::StoredThreadHistory; -use crate::ThreadPage; -use crate::ThreadStore; -use crate::ThreadStoreError; -use crate::ThreadStoreResult; -use crate::UpdateThreadMetadataParams; -use proto::thread_store_client::ThreadStoreClient; - -#[path = "proto/codex.thread_store.v1.rs"] -mod proto; - -/// gRPC-backed [`ThreadStore`] implementation for deployments whose durable thread data lives -/// outside the app-server process. -/// -/// This store is still a work in progress: app-server code should call the generic -/// [`ThreadStore`] methods, and unsupported remote operations will return explicit -/// `not_implemented` errors until the remote API catches up. -#[derive(Clone, Debug)] -pub struct RemoteThreadStore { - endpoint: String, -} - -impl RemoteThreadStore { - pub fn new(endpoint: impl Into) -> Self { - Self { - endpoint: endpoint.into(), - } - } - - async fn client(&self) -> ThreadStoreResult> { - ThreadStoreClient::connect(self.endpoint.clone()) - .await - .map_err(|err| ThreadStoreError::Internal { - message: format!("failed to connect to remote thread store: {err}"), - }) - } -} - -#[async_trait] -impl ThreadStore for RemoteThreadStore { - fn as_any(&self) -> &dyn std::any::Any { - self - } - - async fn create_thread(&self, params: CreateThreadParams) -> ThreadStoreResult<()> { - let thread_id = params.thread_id; - let request = proto::CreateThreadRequest { - thread_id: thread_id.to_string(), - forked_from_id: params.forked_from_id.map(|thread_id| thread_id.to_string()), - source: Some(helpers::proto_session_source(¶ms.source)), - base_instructions_json: helpers::base_instructions_json(¶ms.base_instructions)?, - dynamic_tools_json: helpers::dynamic_tools_json(¶ms.dynamic_tools)?, - event_persistence_mode: helpers::proto_event_persistence_mode( - params.event_persistence_mode, - ) - .into(), - metadata_json: helpers::thread_persistence_metadata_json(¶ms.metadata)?, - }; - self.client() - .await? - .create_thread(request) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn resume_thread(&self, params: ResumeThreadParams) -> ThreadStoreResult<()> { - let thread_id = params.thread_id; - let (has_history, history_json) = match params.history { - Some(history) => (true, helpers::rollout_items_json(&history)?), - None => (false, Vec::new()), - }; - let request = proto::ResumeThreadRequest { - thread_id: thread_id.to_string(), - rollout_path: params - .rollout_path - .map(|path| path.to_string_lossy().into_owned()), - history_json, - has_history, - include_archived: params.include_archived, - event_persistence_mode: helpers::proto_event_persistence_mode( - params.event_persistence_mode, - ) - .into(), - metadata_json: helpers::thread_persistence_metadata_json(¶ms.metadata)?, - }; - self.client() - .await? - .resume_thread(request) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn append_items(&self, params: AppendThreadItemsParams) -> ThreadStoreResult<()> { - let thread_id = params.thread_id; - let request = proto::AppendThreadItemsRequest { - thread_id: thread_id.to_string(), - items_json: helpers::rollout_items_json(¶ms.items)?, - }; - self.client() - .await? - .append_items(request) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn persist_thread(&self, thread_id: ThreadId) -> ThreadStoreResult<()> { - self.client() - .await? - .persist_thread(helpers::proto_thread_id_request(thread_id)) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn flush_thread(&self, thread_id: ThreadId) -> ThreadStoreResult<()> { - self.client() - .await? - .flush_thread(helpers::proto_thread_id_request(thread_id)) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn shutdown_thread(&self, thread_id: ThreadId) -> ThreadStoreResult<()> { - self.client() - .await? - .shutdown_thread(helpers::proto_thread_id_request(thread_id)) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn discard_thread(&self, thread_id: ThreadId) -> ThreadStoreResult<()> { - self.client() - .await? - .discard_thread(helpers::proto_thread_id_request(thread_id)) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn load_history( - &self, - params: LoadThreadHistoryParams, - ) -> ThreadStoreResult { - let thread_id = params.thread_id; - let response = self - .client() - .await? - .load_history(proto::LoadThreadHistoryRequest { - thread_id: thread_id.to_string(), - include_archived: params.include_archived, - }) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))? - .into_inner(); - helpers::stored_thread_history_from_proto(response) - } - - async fn read_thread(&self, params: ReadThreadParams) -> ThreadStoreResult { - let thread_id = params.thread_id; - let response = self - .client() - .await? - .read_thread(proto::ReadThreadRequest { - thread_id: thread_id.to_string(), - include_archived: params.include_archived, - include_history: params.include_history, - }) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))? - .into_inner(); - let thread = response.thread.ok_or_else(|| ThreadStoreError::Internal { - message: "remote thread store omitted read_thread response thread".to_string(), - })?; - helpers::stored_thread_from_proto(thread) - } - - async fn read_thread_by_rollout_path( - &self, - _params: ReadThreadByRolloutPathParams, - ) -> ThreadStoreResult { - Err(ThreadStoreError::Internal { - message: "remote thread store does not support read_thread_by_rollout_path".to_string(), - }) - } - - async fn list_threads(&self, params: ListThreadsParams) -> ThreadStoreResult { - list_threads::list_threads(self, params).await - } - - async fn update_thread_metadata( - &self, - params: UpdateThreadMetadataParams, - ) -> ThreadStoreResult { - let thread_id = params.thread_id; - let response = self - .client() - .await? - .update_thread_metadata(proto::UpdateThreadMetadataRequest { - thread_id: thread_id.to_string(), - patch: Some(helpers::proto_metadata_patch(params.patch)), - include_archived: params.include_archived, - }) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))? - .into_inner(); - let thread = response.thread.ok_or_else(|| ThreadStoreError::Internal { - message: "remote thread store omitted update_thread_metadata response thread" - .to_string(), - })?; - helpers::stored_thread_from_proto(thread) - } - - async fn archive_thread(&self, params: ArchiveThreadParams) -> ThreadStoreResult<()> { - let thread_id = params.thread_id; - self.client() - .await? - .archive_thread(proto::ArchiveThreadRequest { - thread_id: thread_id.to_string(), - }) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))?; - Ok(()) - } - - async fn unarchive_thread( - &self, - params: ArchiveThreadParams, - ) -> ThreadStoreResult { - let thread_id = params.thread_id; - let response = self - .client() - .await? - .unarchive_thread(proto::ArchiveThreadRequest { - thread_id: thread_id.to_string(), - }) - .await - .map_err(|status| helpers::remote_status_to_thread_error(status, thread_id))? - .into_inner(); - let thread = response.thread.ok_or_else(|| ThreadStoreError::Internal { - message: "remote thread store omitted unarchive_thread response thread".to_string(), - })?; - helpers::stored_thread_from_proto(thread) - } -} - -#[cfg(test)] -mod tests { - use std::path::PathBuf; - - use codex_protocol::ThreadId; - use codex_protocol::models::BaseInstructions; - use codex_protocol::protocol::SessionSource; - use codex_protocol::protocol::ThreadMemoryMode; - use pretty_assertions::assert_eq; - use tokio::sync::mpsc; - use tonic::Request; - use tonic::Response; - use tonic::Status; - use tonic::transport::Server; - - use super::*; - use crate::ThreadEventPersistenceMode; - use crate::ThreadPersistenceMetadata; - use proto::thread_store_server; - use proto::thread_store_server::ThreadStoreServer; - - enum RecordedRequest { - Create(proto::CreateThreadRequest), - Resume(proto::ResumeThreadRequest), - } - - struct TestServer { - requests_tx: mpsc::UnboundedSender, - } - - #[tonic::async_trait] - impl thread_store_server::ThreadStore for TestServer { - async fn create_thread( - &self, - request: Request, - ) -> Result, Status> { - self.requests_tx - .send(RecordedRequest::Create(request.into_inner())) - .expect("record create request"); - Ok(Response::new(proto::Empty {})) - } - - async fn resume_thread( - &self, - request: Request, - ) -> Result, Status> { - self.requests_tx - .send(RecordedRequest::Resume(request.into_inner())) - .expect("record resume request"); - Ok(Response::new(proto::Empty {})) - } - - async fn list_threads( - &self, - _request: Request, - ) -> Result, Status> { - Err(Status::unimplemented("not implemented")) - } - } - - async fn test_store() -> (RemoteThreadStore, mpsc::UnboundedReceiver) { - let (requests_tx, requests_rx) = mpsc::unbounded_channel(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind test server"); - let addr = listener.local_addr().expect("test server addr"); - - tokio::spawn(async move { - Server::builder() - .add_service(ThreadStoreServer::new(TestServer { requests_tx })) - .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)) - .await - .expect("test server"); - }); - - ( - RemoteThreadStore::new(format!("http://{addr}")), - requests_rx, - ) - } - - #[tokio::test] - async fn create_thread_forwards_metadata() { - let (store, mut requests_rx) = test_store().await; - let metadata = ThreadPersistenceMetadata { - cwd: Some(PathBuf::from("/workspace")), - model_provider: "test-provider".to_string(), - memory_mode: ThreadMemoryMode::Enabled, - }; - - store - .create_thread(CreateThreadParams { - thread_id: ThreadId::new(), - forked_from_id: None, - source: SessionSource::Exec, - thread_source: None, - base_instructions: BaseInstructions::default(), - dynamic_tools: Vec::new(), - metadata: metadata.clone(), - event_persistence_mode: ThreadEventPersistenceMode::Limited, - }) - .await - .expect("create thread"); - - let Some(RecordedRequest::Create(request)) = requests_rx.recv().await else { - panic!("expected create request"); - }; - assert_eq!( - serde_json::from_str::(&request.metadata_json) - .expect("metadata json"), - metadata - ); - } - - #[tokio::test] - async fn resume_thread_forwards_metadata() { - let (store, mut requests_rx) = test_store().await; - let metadata = ThreadPersistenceMetadata { - cwd: Some(PathBuf::from("/workspace")), - model_provider: "test-provider".to_string(), - memory_mode: ThreadMemoryMode::Disabled, - }; - - store - .resume_thread(ResumeThreadParams { - thread_id: ThreadId::new(), - rollout_path: None, - history: None, - include_archived: false, - metadata: metadata.clone(), - event_persistence_mode: ThreadEventPersistenceMode::Limited, - }) - .await - .expect("resume thread"); - - let Some(RecordedRequest::Resume(request)) = requests_rx.recv().await else { - panic!("expected resume request"); - }; - assert_eq!( - serde_json::from_str::(&request.metadata_json) - .expect("metadata json"), - metadata - ); - } -} diff --git a/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.proto b/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.proto deleted file mode 100644 index a5755afee0..0000000000 --- a/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.proto +++ /dev/null @@ -1,210 +0,0 @@ -syntax = "proto3"; - -package codex.thread_store.v1; - -service ThreadStore { - rpc CreateThread(CreateThreadRequest) returns (Empty); - rpc ResumeThread(ResumeThreadRequest) returns (Empty); - rpc AppendItems(AppendThreadItemsRequest) returns (Empty); - rpc PersistThread(ThreadIdRequest) returns (Empty); - rpc FlushThread(ThreadIdRequest) returns (Empty); - rpc ShutdownThread(ThreadIdRequest) returns (Empty); - rpc DiscardThread(ThreadIdRequest) returns (Empty); - rpc LoadHistory(LoadThreadHistoryRequest) returns (StoredThreadHistory); - rpc ReadThread(ReadThreadRequest) returns (StoredThreadResponse); - rpc ListThreads(ListThreadsRequest) returns (ListThreadsResponse); - rpc UpdateThreadMetadata(UpdateThreadMetadataRequest) returns (StoredThreadResponse); - rpc ArchiveThread(ArchiveThreadRequest) returns (Empty); - rpc UnarchiveThread(ArchiveThreadRequest) returns (StoredThreadResponse); -} - -message Empty {} - -message ThreadIdRequest { - string thread_id = 1; -} - -message CreateThreadRequest { - string thread_id = 1; - optional string forked_from_id = 2; - SessionSource source = 3; - string base_instructions_json = 4; - repeated string dynamic_tools_json = 5; - ThreadEventPersistenceMode event_persistence_mode = 6; - string metadata_json = 7; -} - -message ResumeThreadRequest { - string thread_id = 1; - optional string rollout_path = 2; - repeated string history_json = 3; - bool has_history = 4; - bool include_archived = 5; - ThreadEventPersistenceMode event_persistence_mode = 6; - string metadata_json = 7; -} - -message AppendThreadItemsRequest { - string thread_id = 1; - repeated string items_json = 2; -} - -message LoadThreadHistoryRequest { - string thread_id = 1; - bool include_archived = 2; -} - -message ReadThreadRequest { - string thread_id = 1; - bool include_archived = 2; - bool include_history = 3; -} - -message ListThreadsRequest { - uint32 page_size = 1; - optional string cursor = 2; - ThreadSortKey sort_key = 3; - repeated SessionSource allowed_sources = 4; - optional ModelProviderFilter model_provider_filter = 5; - bool archived = 6; - optional string search_term = 7; - optional CwdFilter cwd_filter = 8; - bool use_state_db_only = 9; - SortDirection sort_direction = 10; -} - -message ModelProviderFilter { - repeated string values = 1; -} - -message CwdFilter { - repeated string values = 1; -} - -enum ThreadSortKey { - THREAD_SORT_KEY_CREATED_AT = 0; - THREAD_SORT_KEY_UPDATED_AT = 1; -} - -enum SortDirection { - SORT_DIRECTION_ASC = 0; - SORT_DIRECTION_DESC = 1; -} - -message ListThreadsResponse { - repeated StoredThread threads = 1; - optional string next_cursor = 2; -} - -message StoredThreadResponse { - StoredThread thread = 1; -} - -message StoredThreadHistory { - string thread_id = 1; - repeated string items_json = 2; -} - -message StoredThread { - // Mirrors Rust's StoredThread. Domain types that are not protobuf-native, - // such as ThreadId, DateTime, and PathBuf, are represented as their - // stable scalar forms on the wire. - string thread_id = 1; - optional string forked_from_id = 2; - string preview = 3; - optional string name = 4; - string model_provider = 5; - optional string model = 6; - int64 created_at = 7; - int64 updated_at = 8; - optional int64 archived_at = 9; - string cwd = 10; - string cli_version = 11; - SessionSource source = 12; - optional GitInfo git_info = 13; - optional string agent_nickname = 14; - optional string agent_role = 15; - optional string agent_path = 16; - optional string reasoning_effort = 17; - optional string first_user_message = 18; - optional string rollout_path = 19; - optional string approval_mode_json = 20; - optional string sandbox_policy_json = 21; - optional string token_usage_json = 22; - optional StoredThreadHistory history = 23; - optional string thread_source = 24; -} - -message SessionSource { - SessionSourceKind kind = 1; - optional string custom = 2; - optional string sub_agent_parent_thread_id = 3; - optional int32 sub_agent_depth = 4; - optional string sub_agent_other = 5; - optional string sub_agent_path = 6; - optional string sub_agent_nickname = 7; - optional string sub_agent_role = 8; -} - -enum SessionSourceKind { - SESSION_SOURCE_KIND_UNKNOWN = 0; - SESSION_SOURCE_KIND_CLI = 1; - SESSION_SOURCE_KIND_VSCODE = 2; - SESSION_SOURCE_KIND_EXEC = 3; - SESSION_SOURCE_KIND_APP_SERVER = 4; - SESSION_SOURCE_KIND_CUSTOM = 5; - SESSION_SOURCE_KIND_SUB_AGENT_REVIEW = 6; - SESSION_SOURCE_KIND_SUB_AGENT_COMPACT = 7; - SESSION_SOURCE_KIND_SUB_AGENT_THREAD_SPAWN = 8; - SESSION_SOURCE_KIND_SUB_AGENT_MEMORY_CONSOLIDATION = 9; - SESSION_SOURCE_KIND_SUB_AGENT_OTHER = 10; -} - -message GitInfo { - optional string sha = 1; - optional string branch = 2; - optional string origin_url = 3; -} - -message UpdateThreadMetadataRequest { - string thread_id = 1; - ThreadMetadataPatch patch = 2; - bool include_archived = 3; -} - -message ThreadMetadataPatch { - optional string name = 1; - optional ThreadMemoryMode memory_mode = 2; - optional GitInfoPatch git_info = 3; -} - -enum ThreadMemoryMode { - THREAD_MEMORY_MODE_ENABLED = 0; - THREAD_MEMORY_MODE_DISABLED = 1; -} - -message GitInfoPatch { - OptionalStringPatch sha = 1; - OptionalStringPatch branch = 2; - OptionalStringPatch origin_url = 3; -} - -message OptionalStringPatch { - OptionalStringPatchKind kind = 1; - optional string value = 2; -} - -enum OptionalStringPatchKind { - OPTIONAL_STRING_PATCH_KIND_UNSET = 0; - OPTIONAL_STRING_PATCH_KIND_CLEAR = 1; - OPTIONAL_STRING_PATCH_KIND_SET = 2; -} - -message ArchiveThreadRequest { - string thread_id = 1; -} - -enum ThreadEventPersistenceMode { - THREAD_EVENT_PERSISTENCE_MODE_LIMITED = 0; - THREAD_EVENT_PERSISTENCE_MODE_EXTENDED = 1; -} diff --git a/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.rs b/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.rs deleted file mode 100644 index c5b8fdc1d6..0000000000 --- a/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.rs +++ /dev/null @@ -1,1122 +0,0 @@ -// This file is @generated by prost-build. -#![allow(clippy::trivially_copy_pass_by_ref)] - -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct Empty {} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct ThreadIdRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct CreateThreadRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(string, optional, tag = "2")] - pub forked_from_id: ::core::option::Option<::prost::alloc::string::String>, - #[prost(message, optional, tag = "3")] - pub source: ::core::option::Option, - #[prost(string, tag = "4")] - pub base_instructions_json: ::prost::alloc::string::String, - #[prost(string, repeated, tag = "5")] - pub dynamic_tools_json: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, - #[prost(enumeration = "ThreadEventPersistenceMode", tag = "6")] - pub event_persistence_mode: i32, - #[prost(string, tag = "7")] - pub metadata_json: ::prost::alloc::string::String, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct ResumeThreadRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(string, optional, tag = "2")] - pub rollout_path: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, repeated, tag = "3")] - pub history_json: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, - #[prost(bool, tag = "4")] - pub has_history: bool, - #[prost(bool, tag = "5")] - pub include_archived: bool, - #[prost(enumeration = "ThreadEventPersistenceMode", tag = "6")] - pub event_persistence_mode: i32, - #[prost(string, tag = "7")] - pub metadata_json: ::prost::alloc::string::String, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct AppendThreadItemsRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(string, repeated, tag = "2")] - pub items_json: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct LoadThreadHistoryRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(bool, tag = "2")] - pub include_archived: bool, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct ReadThreadRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(bool, tag = "2")] - pub include_archived: bool, - #[prost(bool, tag = "3")] - pub include_history: bool, -} -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct ListThreadsRequest { - #[prost(uint32, tag = "1")] - pub page_size: u32, - #[prost(string, optional, tag = "2")] - pub cursor: ::core::option::Option<::prost::alloc::string::String>, - #[prost(enumeration = "ThreadSortKey", tag = "3")] - pub sort_key: i32, - #[prost(message, repeated, tag = "4")] - pub allowed_sources: ::prost::alloc::vec::Vec, - #[prost(message, optional, tag = "5")] - pub model_provider_filter: ::core::option::Option, - #[prost(bool, tag = "6")] - pub archived: bool, - #[prost(string, optional, tag = "7")] - pub search_term: ::core::option::Option<::prost::alloc::string::String>, - #[prost(message, optional, tag = "8")] - pub cwd_filter: ::core::option::Option, - #[prost(bool, tag = "9")] - pub use_state_db_only: bool, - #[prost(enumeration = "SortDirection", tag = "10")] - pub sort_direction: i32, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct ModelProviderFilter { - #[prost(string, repeated, tag = "1")] - pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct CwdFilter { - #[prost(string, repeated, tag = "1")] - pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct ListThreadsResponse { - #[prost(message, repeated, tag = "1")] - pub threads: ::prost::alloc::vec::Vec, - #[prost(string, optional, tag = "2")] - pub next_cursor: ::core::option::Option<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct StoredThreadResponse { - #[prost(message, optional, tag = "1")] - pub thread: ::core::option::Option, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct StoredThreadHistory { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(string, repeated, tag = "2")] - pub items_json: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct StoredThread { - /// Mirrors Rust's StoredThread. Domain types that are not protobuf-native, - /// such as ThreadId, DateTime, and PathBuf, are represented as their - /// stable scalar forms on the wire. - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(string, optional, tag = "2")] - pub forked_from_id: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, tag = "3")] - pub preview: ::prost::alloc::string::String, - #[prost(string, optional, tag = "4")] - pub name: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, tag = "5")] - pub model_provider: ::prost::alloc::string::String, - #[prost(string, optional, tag = "6")] - pub model: ::core::option::Option<::prost::alloc::string::String>, - #[prost(int64, tag = "7")] - pub created_at: i64, - #[prost(int64, tag = "8")] - pub updated_at: i64, - #[prost(int64, optional, tag = "9")] - pub archived_at: ::core::option::Option, - #[prost(string, tag = "10")] - pub cwd: ::prost::alloc::string::String, - #[prost(string, tag = "11")] - pub cli_version: ::prost::alloc::string::String, - #[prost(message, optional, tag = "12")] - pub source: ::core::option::Option, - #[prost(message, optional, tag = "13")] - pub git_info: ::core::option::Option, - #[prost(string, optional, tag = "14")] - pub agent_nickname: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "15")] - pub agent_role: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "16")] - pub agent_path: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "17")] - pub reasoning_effort: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "18")] - pub first_user_message: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "19")] - pub rollout_path: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "20")] - pub approval_mode_json: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "21")] - pub sandbox_policy_json: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "22")] - pub token_usage_json: ::core::option::Option<::prost::alloc::string::String>, - #[prost(message, optional, tag = "23")] - pub history: ::core::option::Option, - #[prost(string, optional, tag = "24")] - pub thread_source: ::core::option::Option<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct SessionSource { - #[prost(enumeration = "SessionSourceKind", tag = "1")] - pub kind: i32, - #[prost(string, optional, tag = "2")] - pub custom: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "3")] - pub sub_agent_parent_thread_id: ::core::option::Option<::prost::alloc::string::String>, - #[prost(int32, optional, tag = "4")] - pub sub_agent_depth: ::core::option::Option, - #[prost(string, optional, tag = "5")] - pub sub_agent_other: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "6")] - pub sub_agent_path: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "7")] - pub sub_agent_nickname: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "8")] - pub sub_agent_role: ::core::option::Option<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct GitInfo { - #[prost(string, optional, tag = "1")] - pub sha: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "2")] - pub branch: ::core::option::Option<::prost::alloc::string::String>, - #[prost(string, optional, tag = "3")] - pub origin_url: ::core::option::Option<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct UpdateThreadMetadataRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, - #[prost(message, optional, tag = "2")] - pub patch: ::core::option::Option, - #[prost(bool, tag = "3")] - pub include_archived: bool, -} -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct ThreadMetadataPatch { - #[prost(string, optional, tag = "1")] - pub name: ::core::option::Option<::prost::alloc::string::String>, - #[prost(enumeration = "ThreadMemoryMode", optional, tag = "2")] - pub memory_mode: ::core::option::Option, - #[prost(message, optional, tag = "3")] - pub git_info: ::core::option::Option, -} -#[derive(Clone, PartialEq, ::prost::Message)] -pub struct GitInfoPatch { - #[prost(message, optional, tag = "1")] - pub sha: ::core::option::Option, - #[prost(message, optional, tag = "2")] - pub branch: ::core::option::Option, - #[prost(message, optional, tag = "3")] - pub origin_url: ::core::option::Option, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct OptionalStringPatch { - #[prost(enumeration = "OptionalStringPatchKind", tag = "1")] - pub kind: i32, - #[prost(string, optional, tag = "2")] - pub value: ::core::option::Option<::prost::alloc::string::String>, -} -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] -pub struct ArchiveThreadRequest { - #[prost(string, tag = "1")] - pub thread_id: ::prost::alloc::string::String, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] -#[repr(i32)] -pub enum ThreadSortKey { - CreatedAt = 0, - UpdatedAt = 1, -} -impl ThreadSortKey { - /// String value of the enum field names used in the ProtoBuf definition. - /// - /// The values are not transformed in any way and thus are considered stable - /// (if the ProtoBuf definition does not change) and safe for programmatic use. - pub fn as_str_name(&self) -> &'static str { - match self { - Self::CreatedAt => "THREAD_SORT_KEY_CREATED_AT", - Self::UpdatedAt => "THREAD_SORT_KEY_UPDATED_AT", - } - } - /// Creates an enum from field names used in the ProtoBuf definition. - pub fn from_str_name(value: &str) -> ::core::option::Option { - match value { - "THREAD_SORT_KEY_CREATED_AT" => Some(Self::CreatedAt), - "THREAD_SORT_KEY_UPDATED_AT" => Some(Self::UpdatedAt), - _ => None, - } - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] -#[repr(i32)] -pub enum SortDirection { - Asc = 0, - Desc = 1, -} -impl SortDirection { - /// String value of the enum field names used in the ProtoBuf definition. - /// - /// The values are not transformed in any way and thus are considered stable - /// (if the ProtoBuf definition does not change) and safe for programmatic use. - pub fn as_str_name(&self) -> &'static str { - match self { - Self::Asc => "SORT_DIRECTION_ASC", - Self::Desc => "SORT_DIRECTION_DESC", - } - } - /// Creates an enum from field names used in the ProtoBuf definition. - pub fn from_str_name(value: &str) -> ::core::option::Option { - match value { - "SORT_DIRECTION_ASC" => Some(Self::Asc), - "SORT_DIRECTION_DESC" => Some(Self::Desc), - _ => None, - } - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] -#[repr(i32)] -pub enum SessionSourceKind { - Unknown = 0, - Cli = 1, - Vscode = 2, - Exec = 3, - AppServer = 4, - Custom = 5, - SubAgentReview = 6, - SubAgentCompact = 7, - SubAgentThreadSpawn = 8, - SubAgentMemoryConsolidation = 9, - SubAgentOther = 10, -} -impl SessionSourceKind { - /// String value of the enum field names used in the ProtoBuf definition. - /// - /// The values are not transformed in any way and thus are considered stable - /// (if the ProtoBuf definition does not change) and safe for programmatic use. - pub fn as_str_name(&self) -> &'static str { - match self { - Self::Unknown => "SESSION_SOURCE_KIND_UNKNOWN", - Self::Cli => "SESSION_SOURCE_KIND_CLI", - Self::Vscode => "SESSION_SOURCE_KIND_VSCODE", - Self::Exec => "SESSION_SOURCE_KIND_EXEC", - Self::AppServer => "SESSION_SOURCE_KIND_APP_SERVER", - Self::Custom => "SESSION_SOURCE_KIND_CUSTOM", - Self::SubAgentReview => "SESSION_SOURCE_KIND_SUB_AGENT_REVIEW", - Self::SubAgentCompact => "SESSION_SOURCE_KIND_SUB_AGENT_COMPACT", - Self::SubAgentThreadSpawn => "SESSION_SOURCE_KIND_SUB_AGENT_THREAD_SPAWN", - Self::SubAgentMemoryConsolidation => { - "SESSION_SOURCE_KIND_SUB_AGENT_MEMORY_CONSOLIDATION" - } - Self::SubAgentOther => "SESSION_SOURCE_KIND_SUB_AGENT_OTHER", - } - } - /// Creates an enum from field names used in the ProtoBuf definition. - pub fn from_str_name(value: &str) -> ::core::option::Option { - match value { - "SESSION_SOURCE_KIND_UNKNOWN" => Some(Self::Unknown), - "SESSION_SOURCE_KIND_CLI" => Some(Self::Cli), - "SESSION_SOURCE_KIND_VSCODE" => Some(Self::Vscode), - "SESSION_SOURCE_KIND_EXEC" => Some(Self::Exec), - "SESSION_SOURCE_KIND_APP_SERVER" => Some(Self::AppServer), - "SESSION_SOURCE_KIND_CUSTOM" => Some(Self::Custom), - "SESSION_SOURCE_KIND_SUB_AGENT_REVIEW" => Some(Self::SubAgentReview), - "SESSION_SOURCE_KIND_SUB_AGENT_COMPACT" => Some(Self::SubAgentCompact), - "SESSION_SOURCE_KIND_SUB_AGENT_THREAD_SPAWN" => Some(Self::SubAgentThreadSpawn), - "SESSION_SOURCE_KIND_SUB_AGENT_MEMORY_CONSOLIDATION" => { - Some(Self::SubAgentMemoryConsolidation) - } - "SESSION_SOURCE_KIND_SUB_AGENT_OTHER" => Some(Self::SubAgentOther), - _ => None, - } - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] -#[repr(i32)] -pub enum ThreadMemoryMode { - Enabled = 0, - Disabled = 1, -} -impl ThreadMemoryMode { - /// String value of the enum field names used in the ProtoBuf definition. - /// - /// The values are not transformed in any way and thus are considered stable - /// (if the ProtoBuf definition does not change) and safe for programmatic use. - pub fn as_str_name(&self) -> &'static str { - match self { - Self::Enabled => "THREAD_MEMORY_MODE_ENABLED", - Self::Disabled => "THREAD_MEMORY_MODE_DISABLED", - } - } - /// Creates an enum from field names used in the ProtoBuf definition. - pub fn from_str_name(value: &str) -> ::core::option::Option { - match value { - "THREAD_MEMORY_MODE_ENABLED" => Some(Self::Enabled), - "THREAD_MEMORY_MODE_DISABLED" => Some(Self::Disabled), - _ => None, - } - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] -#[repr(i32)] -pub enum OptionalStringPatchKind { - Unset = 0, - Clear = 1, - Set = 2, -} -impl OptionalStringPatchKind { - /// String value of the enum field names used in the ProtoBuf definition. - /// - /// The values are not transformed in any way and thus are considered stable - /// (if the ProtoBuf definition does not change) and safe for programmatic use. - pub fn as_str_name(&self) -> &'static str { - match self { - Self::Unset => "OPTIONAL_STRING_PATCH_KIND_UNSET", - Self::Clear => "OPTIONAL_STRING_PATCH_KIND_CLEAR", - Self::Set => "OPTIONAL_STRING_PATCH_KIND_SET", - } - } - /// Creates an enum from field names used in the ProtoBuf definition. - pub fn from_str_name(value: &str) -> ::core::option::Option { - match value { - "OPTIONAL_STRING_PATCH_KIND_UNSET" => Some(Self::Unset), - "OPTIONAL_STRING_PATCH_KIND_CLEAR" => Some(Self::Clear), - "OPTIONAL_STRING_PATCH_KIND_SET" => Some(Self::Set), - _ => None, - } - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] -#[repr(i32)] -pub enum ThreadEventPersistenceMode { - Limited = 0, - Extended = 1, -} -impl ThreadEventPersistenceMode { - /// String value of the enum field names used in the ProtoBuf definition. - /// - /// The values are not transformed in any way and thus are considered stable - /// (if the ProtoBuf definition does not change) and safe for programmatic use. - pub fn as_str_name(&self) -> &'static str { - match self { - Self::Limited => "THREAD_EVENT_PERSISTENCE_MODE_LIMITED", - Self::Extended => "THREAD_EVENT_PERSISTENCE_MODE_EXTENDED", - } - } - /// Creates an enum from field names used in the ProtoBuf definition. - pub fn from_str_name(value: &str) -> ::core::option::Option { - match value { - "THREAD_EVENT_PERSISTENCE_MODE_LIMITED" => Some(Self::Limited), - "THREAD_EVENT_PERSISTENCE_MODE_EXTENDED" => Some(Self::Extended), - _ => None, - } - } -} -/// Generated client implementations. -pub mod thread_store_client { - #![allow( - unused_variables, - dead_code, - missing_docs, - clippy::wildcard_imports, - clippy::let_unit_value - )] - use tonic::codegen::http::Uri; - use tonic::codegen::*; - #[derive(Debug, Clone)] - pub struct ThreadStoreClient { - inner: tonic::client::Grpc, - } - impl ThreadStoreClient { - /// Attempt to create a new client by connecting to a given endpoint. - pub async fn connect(dst: D) -> Result - where - D: TryInto, - D::Error: Into, - { - let conn = tonic::transport::Endpoint::new(dst)?.connect().await?; - Ok(Self::new(conn)) - } - } - impl ThreadStoreClient - where - T: tonic::client::GrpcService, - T::Error: Into, - T::ResponseBody: Body + std::marker::Send + 'static, - ::Error: Into + std::marker::Send, - { - pub fn new(inner: T) -> Self { - let inner = tonic::client::Grpc::new(inner); - Self { inner } - } - pub fn with_origin(inner: T, origin: Uri) -> Self { - let inner = tonic::client::Grpc::with_origin(inner, origin); - Self { inner } - } - pub fn with_interceptor( - inner: T, - interceptor: F, - ) -> ThreadStoreClient> - where - F: tonic::service::Interceptor, - T::ResponseBody: Default, - T: tonic::codegen::Service< - http::Request, - Response = http::Response< - >::ResponseBody, - >, - >, - >>::Error: - Into + std::marker::Send + std::marker::Sync, - { - ThreadStoreClient::new(InterceptedService::new(inner, interceptor)) - } - /// Compress requests with the given encoding. - /// - /// This requires the server to support it otherwise it might respond with an - /// error. - #[must_use] - pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { - self.inner = self.inner.send_compressed(encoding); - self - } - /// Enable decompressing responses. - #[must_use] - pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { - self.inner = self.inner.accept_compressed(encoding); - self - } - /// Limits the maximum size of a decoded message. - /// - /// Default: `4MB` - #[must_use] - pub fn max_decoding_message_size(mut self, limit: usize) -> Self { - self.inner = self.inner.max_decoding_message_size(limit); - self - } - /// Limits the maximum size of an encoded message. - /// - /// Default: `usize::MAX` - #[must_use] - pub fn max_encoding_message_size(mut self, limit: usize) -> Self { - self.inner = self.inner.max_encoding_message_size(limit); - self - } - pub async fn create_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/CreateThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "CreateThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn resume_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/ResumeThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "ResumeThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn append_items( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/AppendItems", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "AppendItems", - )); - self.inner.unary(req, path, codec).await - } - pub async fn persist_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/PersistThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "PersistThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn flush_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/FlushThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "FlushThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn shutdown_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/ShutdownThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "ShutdownThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn discard_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/DiscardThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "DiscardThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn load_history( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> - { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/LoadHistory", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "LoadHistory", - )); - self.inner.unary(req, path, codec).await - } - pub async fn read_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> - { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/ReadThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "ReadThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn list_threads( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> - { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/ListThreads", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "ListThreads", - )); - self.inner.unary(req, path, codec).await - } - pub async fn update_thread_metadata( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> - { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/UpdateThreadMetadata", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "UpdateThreadMetadata", - )); - self.inner.unary(req, path, codec).await - } - pub async fn archive_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/ArchiveThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "ArchiveThread", - )); - self.inner.unary(req, path, codec).await - } - pub async fn unarchive_thread( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> - { - self.inner.ready().await.map_err(|e| { - tonic::Status::unknown(format!("Service was not ready: {}", e.into())) - })?; - let codec = tonic_prost::ProstCodec::default(); - let path = http::uri::PathAndQuery::from_static( - "/codex.thread_store.v1.ThreadStore/UnarchiveThread", - ); - let mut req = request.into_request(); - req.extensions_mut().insert(GrpcMethod::new( - "codex.thread_store.v1.ThreadStore", - "UnarchiveThread", - )); - self.inner.unary(req, path, codec).await - } - } -} -/// Generated server implementations. -pub mod thread_store_server { - #![allow( - unused_variables, - dead_code, - missing_docs, - clippy::wildcard_imports, - clippy::let_unit_value - )] - use tonic::codegen::*; - /// Generated trait containing gRPC methods that should be implemented for use with ThreadStoreServer. - #[async_trait] - pub trait ThreadStore: std::marker::Send + std::marker::Sync + 'static { - async fn create_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn resume_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn append_items( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn persist_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn flush_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn shutdown_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn discard_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn load_history( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> - { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn read_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> - { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn list_threads( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status>; - async fn update_thread_metadata( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> - { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn archive_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - async fn unarchive_thread( - &self, - request: tonic::Request, - ) -> std::result::Result, tonic::Status> - { - let _ = request; - Err(tonic::Status::unimplemented("not implemented")) - } - } - #[derive(Debug)] - pub struct ThreadStoreServer { - inner: Arc, - accept_compression_encodings: EnabledCompressionEncodings, - send_compression_encodings: EnabledCompressionEncodings, - max_decoding_message_size: Option, - max_encoding_message_size: Option, - } - impl ThreadStoreServer { - pub fn new(inner: T) -> Self { - Self::from_arc(Arc::new(inner)) - } - pub fn from_arc(inner: Arc) -> Self { - Self { - inner, - accept_compression_encodings: Default::default(), - send_compression_encodings: Default::default(), - max_decoding_message_size: None, - max_encoding_message_size: None, - } - } - pub fn with_interceptor(inner: T, interceptor: F) -> InterceptedService - where - F: tonic::service::Interceptor, - { - InterceptedService::new(Self::new(inner), interceptor) - } - /// Enable decompressing requests with the given encoding. - #[must_use] - pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self { - self.accept_compression_encodings.enable(encoding); - self - } - /// Compress responses with the given encoding, if the client supports it. - #[must_use] - pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self { - self.send_compression_encodings.enable(encoding); - self - } - /// Limits the maximum size of a decoded message. - /// - /// Default: `4MB` - #[must_use] - pub fn max_decoding_message_size(mut self, limit: usize) -> Self { - self.max_decoding_message_size = Some(limit); - self - } - /// Limits the maximum size of an encoded message. - /// - /// Default: `usize::MAX` - #[must_use] - pub fn max_encoding_message_size(mut self, limit: usize) -> Self { - self.max_encoding_message_size = Some(limit); - self - } - } - impl tonic::codegen::Service> for ThreadStoreServer - where - T: ThreadStore, - B: Body + std::marker::Send + 'static, - B::Error: Into + std::marker::Send + 'static, - { - type Response = http::Response; - type Error = std::convert::Infallible; - type Future = BoxFuture; - fn poll_ready( - &mut self, - _cx: &mut Context<'_>, - ) -> Poll> { - Poll::Ready(Ok(())) - } - fn call(&mut self, req: http::Request) -> Self::Future { - macro_rules! unary_service { - ($svc:ident, $request:ty, $response:ty, $method:ident) => {{ - #[allow(non_camel_case_types)] - struct $svc(pub Arc); - impl tonic::server::UnaryService<$request> for $svc { - type Response = $response; - type Future = BoxFuture, tonic::Status>; - fn call(&mut self, request: tonic::Request<$request>) -> Self::Future { - let inner = Arc::clone(&self.0); - let fut = - async move { ::$method(&inner, request).await }; - Box::pin(fut) - } - } - let accept_compression_encodings = self.accept_compression_encodings; - let send_compression_encodings = self.send_compression_encodings; - let max_decoding_message_size = self.max_decoding_message_size; - let max_encoding_message_size = self.max_encoding_message_size; - let inner = self.inner.clone(); - let fut = async move { - let method = $svc(inner); - let codec = tonic_prost::ProstCodec::default(); - let mut grpc = tonic::server::Grpc::new(codec) - .apply_compression_config( - accept_compression_encodings, - send_compression_encodings, - ) - .apply_max_message_size_config( - max_decoding_message_size, - max_encoding_message_size, - ); - let res = grpc.unary(method, req).await; - Ok(res) - }; - Box::pin(fut) - }}; - } - match req.uri().path() { - "/codex.thread_store.v1.ThreadStore/CreateThread" => unary_service!( - CreateThreadSvc, - super::CreateThreadRequest, - super::Empty, - create_thread - ), - "/codex.thread_store.v1.ThreadStore/ResumeThread" => unary_service!( - ResumeThreadSvc, - super::ResumeThreadRequest, - super::Empty, - resume_thread - ), - "/codex.thread_store.v1.ThreadStore/AppendItems" => unary_service!( - AppendItemsSvc, - super::AppendThreadItemsRequest, - super::Empty, - append_items - ), - "/codex.thread_store.v1.ThreadStore/PersistThread" => unary_service!( - PersistThreadSvc, - super::ThreadIdRequest, - super::Empty, - persist_thread - ), - "/codex.thread_store.v1.ThreadStore/FlushThread" => unary_service!( - FlushThreadSvc, - super::ThreadIdRequest, - super::Empty, - flush_thread - ), - "/codex.thread_store.v1.ThreadStore/ShutdownThread" => unary_service!( - ShutdownThreadSvc, - super::ThreadIdRequest, - super::Empty, - shutdown_thread - ), - "/codex.thread_store.v1.ThreadStore/DiscardThread" => unary_service!( - DiscardThreadSvc, - super::ThreadIdRequest, - super::Empty, - discard_thread - ), - "/codex.thread_store.v1.ThreadStore/LoadHistory" => unary_service!( - LoadHistorySvc, - super::LoadThreadHistoryRequest, - super::StoredThreadHistory, - load_history - ), - "/codex.thread_store.v1.ThreadStore/ReadThread" => unary_service!( - ReadThreadSvc, - super::ReadThreadRequest, - super::StoredThreadResponse, - read_thread - ), - "/codex.thread_store.v1.ThreadStore/ListThreads" => { - #[allow(non_camel_case_types)] - struct ListThreadsSvc(pub Arc); - impl tonic::server::UnaryService for ListThreadsSvc { - type Response = super::ListThreadsResponse; - type Future = BoxFuture, tonic::Status>; - fn call( - &mut self, - request: tonic::Request, - ) -> Self::Future { - let inner = Arc::clone(&self.0); - let fut = async move { - ::list_threads(&inner, request).await - }; - Box::pin(fut) - } - } - let accept_compression_encodings = self.accept_compression_encodings; - let send_compression_encodings = self.send_compression_encodings; - let max_decoding_message_size = self.max_decoding_message_size; - let max_encoding_message_size = self.max_encoding_message_size; - let inner = self.inner.clone(); - let fut = async move { - let method = ListThreadsSvc(inner); - let codec = tonic_prost::ProstCodec::default(); - let mut grpc = tonic::server::Grpc::new(codec) - .apply_compression_config( - accept_compression_encodings, - send_compression_encodings, - ) - .apply_max_message_size_config( - max_decoding_message_size, - max_encoding_message_size, - ); - let res = grpc.unary(method, req).await; - Ok(res) - }; - Box::pin(fut) - } - "/codex.thread_store.v1.ThreadStore/UpdateThreadMetadata" => unary_service!( - UpdateThreadMetadataSvc, - super::UpdateThreadMetadataRequest, - super::StoredThreadResponse, - update_thread_metadata - ), - "/codex.thread_store.v1.ThreadStore/ArchiveThread" => unary_service!( - ArchiveThreadSvc, - super::ArchiveThreadRequest, - super::Empty, - archive_thread - ), - "/codex.thread_store.v1.ThreadStore/UnarchiveThread" => unary_service!( - UnarchiveThreadSvc, - super::ArchiveThreadRequest, - super::StoredThreadResponse, - unarchive_thread - ), - _ => Box::pin(async move { - let mut response = http::Response::new(tonic::body::Body::default()); - let headers = response.headers_mut(); - headers.insert( - tonic::Status::GRPC_STATUS, - (tonic::Code::Unimplemented as i32).into(), - ); - headers.insert( - http::header::CONTENT_TYPE, - tonic::metadata::GRPC_CONTENT_TYPE, - ); - Ok(response) - }), - } - } - } - impl Clone for ThreadStoreServer { - fn clone(&self) -> Self { - let inner = self.inner.clone(); - Self { - inner, - accept_compression_encodings: self.accept_compression_encodings, - send_compression_encodings: self.send_compression_encodings, - max_decoding_message_size: self.max_decoding_message_size, - max_encoding_message_size: self.max_encoding_message_size, - } - } - } - /// Generated gRPC service name - pub const SERVICE_NAME: &str = "codex.thread_store.v1.ThreadStore"; - impl tonic::server::NamedService for ThreadStoreServer { - const NAME: &'static str = SERVICE_NAME; - } -} diff --git a/codex-rs/thread-store/src/store.rs b/codex-rs/thread-store/src/store.rs index 238e56aa92..bd5e3e7d3d 100644 --- a/codex-rs/thread-store/src/store.rs +++ b/codex-rs/thread-store/src/store.rs @@ -5,7 +5,10 @@ use std::any::Any; use crate::AppendThreadItemsParams; use crate::ArchiveThreadParams; use crate::CreateThreadParams; +use crate::ItemPage; +use crate::ListItemsParams; use crate::ListThreadsParams; +use crate::ListTurnsParams; use crate::LoadThreadHistoryParams; use crate::ReadThreadByRolloutPathParams; use crate::ReadThreadParams; @@ -13,7 +16,9 @@ use crate::ResumeThreadParams; use crate::StoredThread; use crate::StoredThreadHistory; use crate::ThreadPage; +use crate::ThreadStoreError; use crate::ThreadStoreResult; +use crate::TurnPage; use crate::UpdateThreadMetadataParams; /// Storage-neutral thread persistence boundary. @@ -67,6 +72,20 @@ pub trait ThreadStore: Any + Send + Sync { /// Lists stored threads matching the supplied filters. async fn list_threads(&self, params: ListThreadsParams) -> ThreadStoreResult; + /// Lists turns within a stored thread. + async fn list_turns(&self, _params: ListTurnsParams) -> ThreadStoreResult { + Err(ThreadStoreError::Unsupported { + operation: "list_turns", + }) + } + + /// Lists persisted items within a stored turn. + async fn list_items(&self, _params: ListItemsParams) -> ThreadStoreResult { + Err(ThreadStoreError::Unsupported { + operation: "list_items", + }) + } + /// Applies a mutable metadata patch and returns the updated thread. async fn update_thread_metadata( &self, diff --git a/codex-rs/thread-store/src/types.rs b/codex-rs/thread-store/src/types.rs index 06aa2998c9..2ad9280215 100644 --- a/codex-rs/thread-store/src/types.rs +++ b/codex-rs/thread-store/src/types.rs @@ -14,6 +14,7 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::ThreadMemoryMode as MemoryMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TokenUsage; +use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde::Serialize; @@ -34,6 +35,9 @@ pub struct ThreadPersistenceMetadata { /// /// `None` means the thread has no filesystem/environment context. pub cwd: Option, + /// Thread-scoped workspace roots used to materialize permission profiles. + #[serde(default)] + pub workspace_roots: Vec, /// Model provider associated with the thread. pub model_provider: String, /// Memory mode associated with the live thread. @@ -183,6 +187,117 @@ pub struct ThreadPage { pub next_cursor: Option, } +/// Requested amount of item detail for stored turns. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum StoredTurnItemsView { + /// Return turn metadata only. + NotLoaded, + /// Return display summary items for each turn. + #[default] + Summary, + /// Return every persisted item available for each turn. + Full, +} + +/// Store-owned status for a persisted turn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum StoredTurnStatus { + /// The turn completed normally. + Completed, + /// The turn was interrupted before normal completion. + Interrupted, + /// The turn failed. + Failed, + /// The turn is still in progress. + InProgress, +} + +/// Store-owned error details for a failed persisted turn. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredTurnError { + /// User-visible error message. + pub message: String, + /// Optional additional detail for clients that expose expanded error context. + pub additional_details: Option, +} + +/// Parameters for listing turns within a stored thread. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ListTurnsParams { + /// Thread id to read. + pub thread_id: ThreadId, + /// Whether archived threads are eligible. + pub include_archived: bool, + /// Opaque cursor returned by a previous list call. + pub cursor: Option, + /// Maximum number of turns to return. + pub page_size: usize, + /// Sort direction requested by the caller. + pub sort_direction: SortDirection, + /// Requested amount of item detail for each returned turn. + pub items_view: StoredTurnItemsView, +} + +/// Store-owned turn representation used by turn pagination APIs. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StoredTurn { + /// Turn id. + pub turn_id: String, + /// Persisted rollout items associated with this turn, according to `items_view`. + pub items: Vec, + /// Amount of item detail included in `items`. + pub items_view: StoredTurnItemsView, + /// Store-owned status for API layer projection. + pub status: StoredTurnStatus, + /// Error message when the turn failed. + pub error: Option, + /// Unix timestamp (seconds) when the turn started. + pub started_at: Option, + /// Unix timestamp (seconds) when the turn completed. + pub completed_at: Option, + /// Duration between turn start and completion in milliseconds, if known. + pub duration_ms: Option, +} + +/// A page of stored turns. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TurnPage { + /// Turns returned for this page. + pub turns: Vec, + /// Opaque cursor to continue listing. + pub next_cursor: Option, + /// Opaque cursor for fetching in the opposite direction. + pub backwards_cursor: Option, +} + +/// Parameters for listing persisted items within a single turn. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ListItemsParams { + /// Thread id to read. + pub thread_id: ThreadId, + /// Turn id to hydrate. + pub turn_id: String, + /// Whether archived threads are eligible. + pub include_archived: bool, + /// Opaque cursor returned by a previous list call. + pub cursor: Option, + /// Maximum number of items to return. + pub page_size: usize, + /// Sort direction requested by the caller. + pub sort_direction: SortDirection, +} + +/// A page of persisted rollout items within a turn. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ItemPage { + /// Items returned for this page. + pub items: Vec, + /// Opaque cursor to continue listing. + pub next_cursor: Option, + /// Opaque cursor for fetching in the opposite direction. + pub backwards_cursor: Option, +} + /// Store-owned thread metadata used by list/read/resume responses. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StoredThread { diff --git a/codex-rs/tools/Cargo.toml b/codex-rs/tools/Cargo.toml index 179681003c..0029352d4b 100644 --- a/codex-rs/tools/Cargo.toml +++ b/codex-rs/tools/Cargo.toml @@ -26,3 +26,6 @@ tracing = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/tools/src/tool_config.rs b/codex-rs/tools/src/tool_config.rs index 0bb4b8b156..2ebf0540f7 100644 --- a/codex-rs/tools/src/tool_config.rs +++ b/codex-rs/tools/src/tool_config.rs @@ -222,7 +222,7 @@ impl ToolsConfig { let apply_patch_tool_type = match model_info.apply_patch_tool_type { Some(ApplyPatchToolType::Freeform) => Some(ApplyPatchToolType::Freeform), Some(ApplyPatchToolType::Function) => Some(ApplyPatchToolType::Function), - None => include_apply_patch_tool.then_some(ApplyPatchToolType::Freeform), + None => include_apply_patch_tool.then_some(ApplyPatchToolType::Function), }; let agent_jobs_worker_tools = include_agent_jobs diff --git a/codex-rs/tools/src/tool_config_tests.rs b/codex-rs/tools/src/tool_config_tests.rs index 34c871cac3..3d1829c4e5 100644 --- a/codex-rs/tools/src/tool_config_tests.rs +++ b/codex-rs/tools/src/tool_config_tests.rs @@ -4,6 +4,7 @@ use codex_features::Features; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::PermissionProfile; +use codex_protocol::openai_models::ApplyPatchToolType; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelInfo; @@ -154,6 +155,29 @@ fn shell_zsh_fork_prefers_shell_command_over_unified_exec() { ); } +#[test] +fn fallback_apply_patch_models_use_function_tool_by_default() { + let model_info = model_info(); + let features = Features::with_defaults(); + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + image_generation_tool_auth_allowed: true, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + permission_profile: &PermissionProfile::Disabled, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + assert_eq!( + tools_config.apply_patch_tool_type, + Some(ApplyPatchToolType::Function) + ); +} + #[test] fn subagents_keep_request_user_input_config_and_agent_jobs_workers_opt_in_by_label() { let model_info = model_info(); diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 5ef87bd9b9..d3d28461b6 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -16,6 +16,7 @@ path = "src/bin/md-events.rs" [lib] name = "codex_tui" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/tui/src/app/app_server_requests.rs b/codex-rs/tui/src/app/app_server_requests.rs index 4b587b0fc8..dce87f367e 100644 --- a/codex-rs/tui/src/app/app_server_requests.rs +++ b/codex-rs/tui/src/app/app_server_requests.rs @@ -429,6 +429,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "call-1".to_string(), + started_at_ms: 0, approval_id: Some("approval-1".to_string()), reason: None, network_approval_context: None, @@ -481,6 +482,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "perm-1".to_string(), + started_at_ms: 0, cwd: absolute_path(if cfg!(windows) { r"C:\tmp" } else { "/tmp" }), reason: None, permissions: serde_json::from_value(json!({ @@ -686,6 +688,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "patch-1".to_string(), + started_at_ms: 0, reason: None, grant_root: None, }, @@ -715,6 +718,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "call-1".to_string(), + started_at_ms: 0, approval_id: Some("approval-1".to_string()), reason: None, network_approval_context: None, diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index 82cbd9f301..83819349b4 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -648,7 +648,6 @@ pub(super) async fn fetch_skills_list( params: SkillsListParams { cwds: vec![cwd], force_reload: true, - per_cwd_extra_user_roots: None, }, }) .await diff --git a/codex-rs/tui/src/app/pending_interactive_replay.rs b/codex-rs/tui/src/app/pending_interactive_replay.rs index 671e41461c..1a21d4df50 100644 --- a/codex-rs/tui/src/app/pending_interactive_replay.rs +++ b/codex-rs/tui/src/app/pending_interactive_replay.rs @@ -612,6 +612,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: turn_id.to_string(), item_id: call_id.to_string(), + started_at_ms: 0, approval_id: approval_id.map(str::to_string), reason: None, network_approval_context: None, @@ -633,6 +634,7 @@ mod tests { thread_id: "thread-1".to_string(), turn_id: turn_id.to_string(), item_id: call_id.to_string(), + started_at_ms: 0, reason: None, grant_root: None, }, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 5ab85887a7..eacb6d5053 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -2659,6 +2659,7 @@ async fn inactive_thread_file_change_approval_recovers_buffered_changes() { thread_id: thread_id.to_string(), turn_id: "turn-approval".to_string(), item_id: "patch-approval".to_string(), + started_at_ms: 0, reason: Some("command failed; retry without sandbox?".to_string()), grant_root: None, }, @@ -2709,6 +2710,7 @@ async fn inactive_thread_permissions_approval_preserves_file_system_permissions( thread_id: thread_id.to_string(), turn_id: "turn-approval".to_string(), item_id: "call-approval".to_string(), + started_at_ms: 0, cwd: test_absolute_path("/tmp"), reason: Some("Need access to .git".to_string()), permissions: codex_app_server_protocol::RequestPermissionProfile { @@ -4259,6 +4261,7 @@ fn exec_approval_request( thread_id: thread_id.to_string(), turn_id: turn_id.to_string(), item_id: item_id.to_string(), + started_at_ms: 0, approval_id: approval_id.map(str::to_string), reason: Some("needs approval".to_string()), network_approval_context: None, diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs index 56477c18cf..431bf5f804 100644 --- a/codex-rs/tui/src/app/thread_events.rs +++ b/codex-rs/tui/src/app/thread_events.rs @@ -465,6 +465,7 @@ mod tests { thread_id: thread_id.to_string(), turn_id: turn_id.to_string(), item_id: item_id.to_string(), + started_at_ms: 0, approval_id: approval_id.map(str::to_string), reason: Some("needs approval".to_string()), network_approval_context: None, diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 1a7986ad31..9a76b54168 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -621,7 +621,6 @@ impl App { .skills_list(codex_app_server_protocol::SkillsListParams { cwds: cwds.clone(), force_reload: *force_reload, - per_cwd_extra_user_roots: None, }) .await, "failed to refresh skills", diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 9f1e0f8101..485e969bb9 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -34,7 +34,6 @@ use codex_app_server_protocol::MemoryResetResponse; use codex_app_server_protocol::Model as ApiModel; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; -use codex_app_server_protocol::PermissionProfileModificationParams; use codex_app_server_protocol::PermissionProfileSelectionParams; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RequestId; @@ -105,7 +104,6 @@ use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; use codex_protocol::approvals::GuardianAssessmentEvent; use codex_protocol::models::ActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification; use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelAvailabilityNux; @@ -551,6 +549,7 @@ impl AppServerSession { responsesapi_client_metadata: None, environments: None, cwd: Some(cwd), + workspace_roots: None, approval_policy: Some(approval_policy), approvals_reviewer: Some(approvals_reviewer.into()), sandbox_policy, @@ -1112,19 +1111,7 @@ fn sandbox_mode_from_permission_profile( fn permissions_selection_from_active_profile( active: ActivePermissionProfile, ) -> PermissionProfileSelectionParams { - let modifications = active - .modifications - .into_iter() - .map(|modification| match modification { - ActivePermissionProfileModification::AdditionalWritableRoot { path } => { - PermissionProfileModificationParams::AdditionalWritableRoot { path } - } - }) - .collect::>(); - PermissionProfileSelectionParams::Profile { - id: active.id, - modifications: (!modifications.is_empty()).then_some(modifications), - } + PermissionProfileSelectionParams::Profile { id: active.id } } fn turn_permissions_overrides( @@ -1189,6 +1176,7 @@ fn thread_start_params_from_config( model: config.model.clone(), model_provider: thread_params_mode.model_provider_from_config(config), cwd: thread_cwd_from_config(config, thread_params_mode, remote_cwd_override), + workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(config), sandbox, @@ -1223,6 +1211,7 @@ fn thread_resume_params_from_config( model: config.model.clone(), model_provider: thread_params_mode.model_provider_from_config(&config), cwd: thread_cwd_from_config(&config, thread_params_mode, remote_cwd_override), + workspace_roots: Some(config.workspace_roots.clone()), approval_policy: Some(config.permissions.approval_policy.value().into()), approvals_reviewer: approvals_reviewer_override_from_config(&config), sandbox, @@ -1870,6 +1859,7 @@ mod tests { model_provider: "openai".to_string(), service_tier: None, cwd: test_path_buf("/tmp/project").abs(), + workspace_roots: Vec::new(), instruction_sources: vec![test_path_buf("/tmp/project/AGENTS.md").abs()], approval_policy: codex_app_server_protocol::AskForApproval::Never, approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::User, diff --git a/codex-rs/tui/src/auto_review_denials.rs b/codex-rs/tui/src/auto_review_denials.rs index e51e071e21..149a60f049 100644 --- a/codex-rs/tui/src/auto_review_denials.rs +++ b/codex-rs/tui/src/auto_review_denials.rs @@ -88,6 +88,8 @@ mod tests { id: format!("review-{id}"), target_item_id: None, turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::Denied, risk_level: None, user_authorization: None, diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap index 7dadf02b35..598fa418a1 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__title_setup__tests__terminal_title_setup_basic.snap @@ -11,7 +11,7 @@ expression: "render_lines(&view, 84)" β€Ί [x] project-name Project name (falls back to current directory name) [x] activity Spinner while working, action-required message while blo… [x] run-state Compact session run-state text (Ready, Working, Thinking) - [x] thread-title Current thread title (omitted when unavailable) + [x] thread-title Current thread title, or thread identifier when unnamed [ ] app-name Codex app name [ ] current-dir Current working directory [ ] git-branch Current Git branch (omitted when unavailable) diff --git a/codex-rs/tui/src/bottom_pane/status_line_setup.rs b/codex-rs/tui/src/bottom_pane/status_line_setup.rs index db789a11ff..d96bc286a3 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_setup.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_setup.rs @@ -12,9 +12,11 @@ //! - Model information (name, reasoning level) //! - Directory paths (current dir, project root) //! - Git information (branch name) +//! - Permissions profile +//! - Approval mode //! - Context usage (remaining %, used %, window size) //! - Usage limits (5-hour, weekly) -//! - Session info (thread title, ID, tokens used) +//! - Session info (thread title, thread ID, tokens used) //! - Application version use ratatui::buffer::Buffer; @@ -46,7 +48,7 @@ const STATUS_LINE_USE_THEME_COLORS_ITEM_ID: &str = "status-line-use-theme-colors /// Some items are conditionally displayed based on availability: /// - Git-related items only show when in a git repository /// - Context/limit items only show when data is available from the API -/// - Session ID only shows after a session has started +/// - Thread ID only shows after a session has started #[derive(EnumIter, EnumString, Display, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] #[strum(serialize_all = "kebab_case")] pub(crate) enum StatusLineItem { @@ -81,6 +83,13 @@ pub(crate) enum StatusLineItem { #[strum(to_string = "run-state", serialize = "status")] Status, + /// Active permission profile or sandbox summary. + Permissions, + + /// Active command approval mode. + #[strum(to_string = "approval-mode", serialize = "approval")] + ApprovalMode, + /// Percentage of context window remaining. ContextRemaining, @@ -111,7 +120,8 @@ pub(crate) enum StatusLineItem { /// Total output tokens generated. TotalOutputTokens, - /// Full session UUID. + /// Full thread UUID. + #[strum(to_string = "thread-id", serialize = "session-id")] SessionId, /// Whether Fast mode is currently active. @@ -143,6 +153,8 @@ impl StatusLineItem { "Committed branch changes against the default branch (omitted when unavailable)" } StatusLineItem::Status => "Compact session run-state text (Ready, Working, Thinking)", + StatusLineItem::Permissions => "Active permission profile or sandbox mode", + StatusLineItem::ApprovalMode => "Active command approval mode", StatusLineItem::ContextRemaining => { "Percentage of context window remaining (omitted when unknown)" } @@ -162,12 +174,12 @@ impl StatusLineItem { StatusLineItem::UsedTokens => "Total tokens used in session (omitted when zero)", StatusLineItem::TotalInputTokens => "Total input tokens used in session", StatusLineItem::TotalOutputTokens => "Total output tokens used in session", - StatusLineItem::SessionId => { - "Current session identifier (omitted until session starts)" - } + StatusLineItem::SessionId => "Current thread identifier (omitted until thread starts)", StatusLineItem::FastMode => "Whether Fast mode is currently active", StatusLineItem::RawOutput => "Whether raw scrollback mode is active", - StatusLineItem::ThreadTitle => "Current thread title (omitted when unavailable)", + StatusLineItem::ThreadTitle => { + "Current thread title, or thread identifier when unnamed" + } StatusLineItem::TaskProgress => { "Latest task progress from update_plan (omitted until available)" } @@ -184,6 +196,8 @@ impl StatusLineItem { StatusLineItem::PullRequestNumber => StatusSurfacePreviewItem::PullRequestNumber, StatusLineItem::BranchChanges => StatusSurfacePreviewItem::BranchChanges, StatusLineItem::Status => StatusSurfacePreviewItem::Status, + StatusLineItem::Permissions => StatusSurfacePreviewItem::Permissions, + StatusLineItem::ApprovalMode => StatusSurfacePreviewItem::ApprovalMode, StatusLineItem::ContextRemaining => StatusSurfacePreviewItem::ContextRemaining, StatusLineItem::ContextUsed => StatusSurfacePreviewItem::ContextUsed, StatusLineItem::FiveHourLimit => StatusSurfacePreviewItem::FiveHourLimit, diff --git a/codex-rs/tui/src/bottom_pane/status_line_style.rs b/codex-rs/tui/src/bottom_pane/status_line_style.rs index 07018bff0e..ffb2a289e9 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_style.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_style.rs @@ -45,6 +45,8 @@ impl StatusLineAccent { StatusLineItem::FiveHourLimit | StatusLineItem::WeeklyLimit => Self::Limit, StatusLineItem::CodexVersion | StatusLineItem::SessionId => Self::Metadata, StatusLineItem::FastMode | StatusLineItem::RawOutput => Self::Mode, + StatusLineItem::Permissions => Self::Mode, + StatusLineItem::ApprovalMode => Self::Mode, StatusLineItem::ThreadTitle => Self::Thread, StatusLineItem::TaskProgress => Self::Progress, } diff --git a/codex-rs/tui/src/bottom_pane/status_surface_preview.rs b/codex-rs/tui/src/bottom_pane/status_surface_preview.rs index 1f23742a55..9f0f8ed5fb 100644 --- a/codex-rs/tui/src/bottom_pane/status_surface_preview.rs +++ b/codex-rs/tui/src/bottom_pane/status_surface_preview.rs @@ -16,6 +16,8 @@ pub(crate) enum StatusSurfacePreviewItem { GitBranch, PullRequestNumber, BranchChanges, + Permissions, + ApprovalMode, ContextRemaining, ContextUsed, FiveHourLimit, @@ -45,6 +47,8 @@ impl StatusSurfacePreviewItem { StatusSurfacePreviewItem::GitBranch => "feat/awesome-feature", StatusSurfacePreviewItem::PullRequestNumber => "PR #123", StatusSurfacePreviewItem::BranchChanges => "+12 -3", + StatusSurfacePreviewItem::Permissions => "Workspace", + StatusSurfacePreviewItem::ApprovalMode => "on-request", StatusSurfacePreviewItem::ContextRemaining => "Context 0% left", StatusSurfacePreviewItem::ContextUsed => "Context 0% used", StatusSurfacePreviewItem::FiveHourLimit => "5h 0%", @@ -74,6 +78,8 @@ impl StatusSurfacePreviewItem { Self::GitBranch, Self::PullRequestNumber, Self::BranchChanges, + Self::Permissions, + Self::ApprovalMode, Self::ContextRemaining, Self::ContextUsed, Self::FiveHourLimit, diff --git a/codex-rs/tui/src/bottom_pane/title_setup.rs b/codex-rs/tui/src/bottom_pane/title_setup.rs index 8b46d059c4..ae3c56ca3b 100644 --- a/codex-rs/tui/src/bottom_pane/title_setup.rs +++ b/codex-rs/tui/src/bottom_pane/title_setup.rs @@ -71,7 +71,8 @@ pub(crate) enum TerminalTitleItem { TotalInputTokens, /// Total output tokens generated. TotalOutputTokens, - /// Full session UUID. + /// Full thread UUID. + #[strum(to_string = "thread-id", serialize = "session-id")] SessionId, /// Whether Fast mode is currently active. FastMode, @@ -96,7 +97,7 @@ impl TerminalTitleItem { TerminalTitleItem::Status => { "Compact session run-state text (Ready, Working, Thinking)" } - TerminalTitleItem::Thread => "Current thread title (omitted when unavailable)", + TerminalTitleItem::Thread => "Current thread title, or thread identifier when unnamed", TerminalTitleItem::GitBranch => "Current Git branch (omitted when unavailable)", TerminalTitleItem::ContextRemaining => { "Percentage of context window remaining (omitted when unknown)" @@ -115,7 +116,7 @@ impl TerminalTitleItem { TerminalTitleItem::TotalInputTokens => "Total input tokens used in session", TerminalTitleItem::TotalOutputTokens => "Total output tokens used in session", TerminalTitleItem::SessionId => { - "Current session identifier (omitted until session starts)" + "Current thread identifier (omitted until thread starts)" } TerminalTitleItem::FastMode => "Whether Fast mode is currently active", TerminalTitleItem::Model => "Current model name", diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index adaba76b24..b65f8b1c4d 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1637,6 +1637,7 @@ fn request_permissions_from_params( RequestPermissionsEvent { turn_id: params.turn_id, call_id: params.item_id, + started_at_ms: params.started_at_ms, reason: params.reason, permissions: params.permissions.into(), cwd: Some(params.cwd), @@ -6374,8 +6375,9 @@ impl ChatWidget { self.on_guardian_review_notification( notification.review_id, notification.turn_id, + notification.started_at_ms, notification.review, - /*decision_source*/ None, + /*completion*/ None, notification.action, ); } @@ -6383,8 +6385,9 @@ impl ChatWidget { self.on_guardian_review_notification( notification.review_id, notification.turn_id, + notification.started_at_ms, notification.review, - Some(notification.decision_source), + Some((notification.completed_at_ms, notification.decision_source)), notification.action, ); } @@ -6567,14 +6570,24 @@ impl ChatWidget { &mut self, id: String, turn_id: String, + started_at_ms: i64, review: codex_app_server_protocol::GuardianApprovalReview, - decision_source: Option, + completion: Option<(i64, codex_app_server_protocol::AutoReviewDecisionSource)>, action: GuardianApprovalReviewAction, ) { + let (completed_at_ms, decision_source) = match completion { + Some((completed_at_ms, decision_source)) => { + (Some(completed_at_ms), Some(decision_source)) + } + None => (None, None), + }; + self.on_guardian_assessment(GuardianAssessmentEvent { id, target_item_id: None, turn_id, + started_at_ms, + completed_at_ms, status: match review.status { codex_app_server_protocol::GuardianApprovalReviewStatus::InProgress => { GuardianAssessmentStatus::InProgress @@ -9128,6 +9141,8 @@ impl ChatWidget { .set(policy.to_core()) { tracing::warn!(%err, "failed to set approval_policy on chat config"); + } else { + self.refresh_status_surfaces(); } } @@ -9137,7 +9152,9 @@ impl ChatWidget { &mut self, profile: PermissionProfile, ) -> ConstraintResult<()> { - self.config.permissions.set_permission_profile(profile) + self.config.permissions.set_permission_profile(profile)?; + self.refresh_status_surfaces(); + Ok(()) } #[cfg_attr(not(target_os = "windows"), allow(dead_code))] @@ -9218,6 +9235,7 @@ impl ChatWidget { pub(crate) fn set_approvals_reviewer(&mut self, policy: ApprovalsReviewer) { self.config.approvals_reviewer = policy; + self.refresh_status_surfaces(); } pub(crate) fn set_full_access_warning_acknowledged(&mut self, acknowledged: bool) { diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap index e527c14623..27c7d061ee 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap @@ -4,10 +4,9 @@ expression: popup --- Select Reasoning Level for gpt-5.4 - 1. Low Fast responses with lighter reasoning - 2. Medium Balances speed and reasoning depth for everyday - tasks -β€Ί 3. High (current) Greater reasoning depth for complex problems - 4. Extra high (default) Extra high reasoning depth for complex problems + 1. Low Fast responses with lighter reasoning + 2. Medium (default) Balances speed and reasoning depth for everyday tasks +β€Ί 3. High (current) Greater reasoning depth for complex problems + 4. Extra high Extra high reasoning depth for complex problems Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap index b3c909647d..652c914adf 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_hardcoded_only.snap @@ -11,7 +11,7 @@ expression: status_line_popup_snapshot(&mut chat) ─────────────────────── [x] project-name Project name (omitted when unavailable) [x] git-branch Current Git branch (omitted when unavailable) - [x] thread-title Current thread title (omitted when unavailable) + [x] thread-title Current thread title, or thread identifier when unnamed [ ] model Current model name [ ] model-with-reasoning Current model name with reasoning level [ ] current-dir Current working directory diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap index e1b7e0e777..fc713c4cdc 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_live_only.snap @@ -11,7 +11,7 @@ expression: status_line_popup_snapshot(&mut chat) ─────────────────────── [x] project-name Project name (omitted when unavailable) [x] git-branch Current Git branch (omitted when unavailable) - [x] thread-title Current thread title (omitted when unavailable) + [x] thread-title Current thread title, or thread identifier when unnamed [ ] model Current model name [ ] model-with-reasoning Current model name with reasoning level [ ] current-dir Current working directory diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap index b76ba0dc4e..547f70daa8 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_mixed.snap @@ -11,7 +11,7 @@ expression: status_line_popup_snapshot(&mut chat) ─────────────────────── [x] project-name Project name (omitted when unavailable) [x] git-branch Current Git branch (omitted when unavailable) - [x] thread-title Current thread title (omitted when unavailable) + [x] thread-title Current thread title, or thread identifier when unnamed [ ] model Current model name [ ] model-with-reasoning Current model name with reasoning level [ ] current-dir Current working directory diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap index abf3df3c26..250d56ff48 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap @@ -2,5 +2,5 @@ source: tui/src/chatwidget/tests/status_surface_previews.rs expression: snapshot --- -status line: my-project Β· feat/awesome-feature Β· thread title +status line: my-project Β· feat/awesome-feature Β· thread title Β· Read Only Β· on-request terminal title: thread title | feat/awesome-feature | Tasks 0/0 diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap index 9ab8659a37..cf2248ffdd 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_hardcoded_only.snap @@ -7,7 +7,7 @@ expression: terminal_title_popup_snapshot(&mut chat) Type to search > -β€Ί [x] thread-title Current thread title (omitted when unavailable) +β€Ί [x] thread-title Current thread title, or thread identifier when unnamed [x] git-branch Current Git branch (omitted when unavailable) [x] task-progress Latest task progress from update_plan (omitted until available) [ ] app-name Codex app name diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap index 6ede93244b..c22a70f714 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_live_only.snap @@ -8,7 +8,7 @@ expression: terminal_title_popup_snapshot(&mut chat) Type to search > β€Ί [x] project-name Project name (falls back to current directory name) - [x] thread-title Current thread title (omitted when unavailable) + [x] thread-title Current thread title, or thread identifier when unnamed [x] git-branch Current Git branch (omitted when unavailable) [x] task-progress Latest task progress from update_plan (omitted until available) [ ] app-name Codex app name diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap index 842938ca0b..06b988811e 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_mixed.snap @@ -8,7 +8,7 @@ expression: terminal_title_popup_snapshot(&mut chat) Type to search > β€Ί [x] project-name Project name (falls back to current directory name) - [x] thread-title Current thread title (omitted when unavailable) + [x] thread-title Current thread title, or thread identifier when unnamed [x] task-progress Latest task progress from update_plan (omitted until available) [ ] app-name Codex app name [ ] current-dir Current working directory diff --git a/codex-rs/tui/src/chatwidget/status_surfaces.rs b/codex-rs/tui/src/chatwidget/status_surfaces.rs index 3095556fd0..9d4b7103d0 100644 --- a/codex-rs/tui/src/chatwidget/status_surfaces.rs +++ b/codex-rs/tui/src/chatwidget/status_surfaces.rs @@ -6,7 +6,12 @@ use super::*; use crate::bottom_pane::status_line_from_segments; use crate::branch_summary; +use crate::legacy_core::config::Config; use crate::status::format_tokens_compact; +use codex_app_server_protocol::AskForApproval; +use codex_protocol::config_types::ApprovalsReviewer; +use codex_protocol::models::PermissionProfile; +use codex_utils_sandbox_summary::summarize_permission_profile; /// Items shown in the terminal title when the user has not configured a /// custom selection. Intentionally minimal: activity indicator + project name. @@ -590,9 +595,11 @@ impl ChatWidget { } }), StatusLineItem::Status => Some(self.run_state_status_text()), + StatusLineItem::Permissions => Some(permissions_display(&self.config)), + StatusLineItem::ApprovalMode => Some(approval_mode_display(&self.config)), StatusLineItem::UsedTokens => { let usage = self.status_line_total_usage(); - let total = usage.tokens_in_context_window(); + let total = usage.blended_total(); if total <= 0 { None } else { @@ -648,10 +655,17 @@ impl ChatWidget { }, ), StatusLineItem::RawOutput => self.raw_output_mode().then(|| "raw output".to_string()), - StatusLineItem::ThreadTitle => self.thread_name.as_ref().and_then(|name| { - let trimmed = name.trim(); - (!trimmed.is_empty()).then(|| trimmed.to_string()) - }), + StatusLineItem::ThreadTitle => self.thread_name.as_ref().map_or_else( + || self.thread_id.map(|id| id.to_string()), + |name| { + let trimmed = name.trim(); + if trimmed.is_empty() { + self.thread_id.map(|id| id.to_string()) + } else { + Some(trimmed.to_string()) + } + }, + ), StatusLineItem::TaskProgress => self.terminal_title_task_progress(), } } @@ -678,6 +692,8 @@ impl ChatWidget { StatusSurfacePreviewItem::GitBranch => StatusLineItem::GitBranch, StatusSurfacePreviewItem::PullRequestNumber => StatusLineItem::PullRequestNumber, StatusSurfacePreviewItem::BranchChanges => StatusLineItem::BranchChanges, + StatusSurfacePreviewItem::Permissions => StatusLineItem::Permissions, + StatusSurfacePreviewItem::ApprovalMode => StatusLineItem::ApprovalMode, StatusSurfacePreviewItem::ContextRemaining => StatusLineItem::ContextRemaining, StatusSurfacePreviewItem::ContextUsed => StatusLineItem::ContextUsed, StatusSurfacePreviewItem::FiveHourLimit => StatusLineItem::FiveHourLimit, @@ -713,17 +729,9 @@ impl ChatWidget { )), TerminalTitleItem::Spinner => self.terminal_title_spinner_text_at(now), TerminalTitleItem::Status => Some(self.run_state_status_text()), - TerminalTitleItem::Thread => self.thread_name.as_ref().and_then(|name| { - let trimmed = name.trim(); - if trimmed.is_empty() { - None - } else { - Some(Self::truncate_terminal_title_part( - trimmed.to_string(), - /*max_chars*/ 48, - )) - } - }), + TerminalTitleItem::Thread => self + .status_line_value_for_item(StatusLineItem::ThreadTitle) + .map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 48)), TerminalTitleItem::GitBranch => self.status_line_branch.as_ref().map(|branch| { Self::truncate_terminal_title_part(branch.clone(), /*max_chars*/ 32) }), @@ -890,6 +898,44 @@ impl ChatWidget { } } +fn permissions_display(config: &Config) -> String { + let active_permission_profile = config.permissions.active_permission_profile(); + if let Some(active_permission_profile) = active_permission_profile.as_ref() + && !active_permission_profile.id.starts_with(':') + { + return active_permission_profile.id.clone(); + } + + let permission_profile = config.permissions.permission_profile(); + let summary = summarize_permission_profile(&permission_profile, config.cwd.as_path()); + if let Some(details) = summary.strip_prefix("read-only") + && !details.contains("(network access enabled)") + { + return "Read Only".to_string(); + } + if let Some(details) = summary.strip_prefix("workspace-write") + && !details.contains("(network access enabled)") + { + return "Workspace".to_string(); + } + if permission_profile == PermissionProfile::Disabled { + return "Full Access".to_string(); + } + + "Custom permissions".to_string() +} + +fn approval_mode_display(config: &Config) -> String { + let approval_policy = AskForApproval::from(config.permissions.approval_policy.value()); + if approval_policy == AskForApproval::OnRequest + && config.approvals_reviewer == ApprovalsReviewer::AutoReview + { + "auto-review".to_string() + } else { + config.permissions.approval_policy.value().to_string() + } +} + fn parse_items_with_invalids(ids: impl IntoIterator) -> (Vec, Vec) where T: std::str::FromStr, diff --git a/codex-rs/tui/src/chatwidget/tests/approval_requests.rs b/codex-rs/tui/src/chatwidget/tests/approval_requests.rs index 93e2a38c13..85c8fc6c03 100644 --- a/codex-rs/tui/src/chatwidget/tests/approval_requests.rs +++ b/codex-rs/tui/src/chatwidget/tests/approval_requests.rs @@ -55,6 +55,7 @@ fn app_server_exec_approval_request_splits_shell_wrapped_command() { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "item-1".to_string(), + started_at_ms: 0, approval_id: Some("approval-1".to_string()), reason: None, network_approval_context: None, @@ -93,6 +94,7 @@ fn app_server_exec_approval_request_preserves_permissions_context() { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "item-1".to_string(), + started_at_ms: 0, approval_id: Some("approval-1".to_string()), reason: None, network_approval_context: Some(codex_app_server_protocol::NetworkApprovalContext { @@ -156,6 +158,7 @@ fn app_server_request_permissions_preserves_file_system_permissions() { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "item-1".to_string(), + started_at_ms: 0, cwd: cwd.clone(), reason: Some("Select a workspace root".to_string()), permissions: codex_app_server_protocol::RequestPermissionProfile { diff --git a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs index b1949d7809..0045e7d126 100644 --- a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs +++ b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs @@ -54,6 +54,7 @@ fn app_server_exec_approval_request_splits_shell_wrapped_command() { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), item_id: "item-1".to_string(), + started_at_ms: 0, approval_id: Some("approval-1".to_string()), reason: None, network_approval_context: None, diff --git a/codex-rs/tui/src/chatwidget/tests/guardian.rs b/codex-rs/tui/src/chatwidget/tests/guardian.rs index c51b3f6687..7cdc9f760b 100644 --- a/codex-rs/tui/src/chatwidget/tests/guardian.rs +++ b/codex-rs/tui/src/chatwidget/tests/guardian.rs @@ -6,6 +6,8 @@ fn auto_review_denial_event() -> GuardianAssessmentEvent { id: "auto-review-recent-1".into(), target_item_id: Some("target-auto-review-recent-1".into()), turn_id: "turn-recent-1".into(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::Denied, risk_level: Some(GuardianRiskLevel::High), user_authorization: Some(GuardianUserAuthorization::Low), @@ -73,6 +75,8 @@ async fn guardian_denied_exec_renders_warning_and_denied_request() { id: "guardian-1".into(), target_item_id: Some("guardian-target-1".into()), turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -85,6 +89,8 @@ async fn guardian_denied_exec_renders_warning_and_denied_request() { id: "guardian-1".into(), target_item_id: Some("guardian-target-1".into()), turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::Denied, risk_level: Some(GuardianRiskLevel::High), user_authorization: Some(GuardianUserAuthorization::Low), @@ -127,6 +133,8 @@ async fn guardian_approved_exec_renders_approved_request() { id: "thread:child-thread:guardian-1".into(), target_item_id: Some("guardian-approved-target".into()), turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::Approved, risk_level: Some(GuardianRiskLevel::Low), user_authorization: Some(GuardianUserAuthorization::High), @@ -183,6 +191,8 @@ async fn guardian_approved_request_permissions_renders_request_summary() { id: "guardian-request-permissions".into(), target_item_id: None, turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -205,6 +215,8 @@ async fn guardian_approved_request_permissions_renders_request_summary() { id: "guardian-request-permissions".into(), target_item_id: None, turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::Approved, risk_level: Some(GuardianRiskLevel::Low), user_authorization: Some(GuardianUserAuthorization::High), @@ -253,6 +265,8 @@ async fn guardian_timed_out_exec_renders_warning_and_timed_out_request() { id: "guardian-1".into(), target_item_id: Some("guardian-target-1".into()), turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -265,6 +279,8 @@ async fn guardian_timed_out_exec_renders_warning_and_timed_out_request() { id: "guardian-1".into(), target_item_id: Some("guardian-target-1".into()), turn_id: "turn-1".into(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::TimedOut, risk_level: None, user_authorization: None, @@ -315,6 +331,7 @@ async fn app_server_guardian_review_started_sets_review_status() { ItemGuardianApprovalReviewStartedNotification { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), + started_at_ms: 0, review_id: "guardian-1".to_string(), target_item_id: Some("guardian-target-1".to_string()), review: GuardianApprovalReview { @@ -356,6 +373,7 @@ async fn app_server_guardian_review_denied_renders_denied_request_snapshot() { ItemGuardianApprovalReviewStartedNotification { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), + started_at_ms: 0, review_id: "guardian-1".to_string(), target_item_id: Some("guardian-target-1".to_string()), review: GuardianApprovalReview { @@ -375,6 +393,8 @@ async fn app_server_guardian_review_denied_renders_denied_request_snapshot() { ItemGuardianApprovalReviewCompletedNotification { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: 1, review_id: "guardian-1".to_string(), target_item_id: Some("guardian-target-1".to_string()), decision_source: AppServerGuardianApprovalReviewDecisionSource::Agent, @@ -431,6 +451,7 @@ async fn app_server_guardian_review_timed_out_renders_timed_out_request_snapshot ItemGuardianApprovalReviewStartedNotification { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), + started_at_ms: 0, review_id: "guardian-1".to_string(), target_item_id: Some("guardian-target-1".to_string()), review: GuardianApprovalReview { @@ -450,6 +471,8 @@ async fn app_server_guardian_review_timed_out_renders_timed_out_request_snapshot ItemGuardianApprovalReviewCompletedNotification { thread_id: "thread-1".to_string(), turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: 1, review_id: "guardian-1".to_string(), target_item_id: Some("guardian-target-1".to_string()), decision_source: AppServerGuardianApprovalReviewDecisionSource::Agent, @@ -506,6 +529,8 @@ async fn guardian_parallel_reviews_render_aggregate_status_snapshot() { id: id.to_string(), target_item_id: Some(format!("{id}-target")), turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -535,6 +560,8 @@ async fn guardian_parallel_reviews_keep_remaining_review_visible_after_denial() id: "guardian-1".to_string(), target_item_id: Some("guardian-1-target".to_string()), turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -550,6 +577,8 @@ async fn guardian_parallel_reviews_keep_remaining_review_visible_after_denial() id: "guardian-2".to_string(), target_item_id: Some("guardian-2-target".to_string()), turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: None, status: GuardianAssessmentStatus::InProgress, risk_level: None, user_authorization: None, @@ -565,6 +594,8 @@ async fn guardian_parallel_reviews_keep_remaining_review_visible_after_denial() id: "guardian-1".to_string(), target_item_id: Some("guardian-1-target".to_string()), turn_id: "turn-1".to_string(), + started_at_ms: 0, + completed_at_ms: Some(1), status: GuardianAssessmentStatus::Denied, risk_level: Some(GuardianRiskLevel::High), user_authorization: Some(GuardianUserAuthorization::Low), diff --git a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs index fff328d190..c206313549 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs @@ -90,7 +90,7 @@ async fn status_command_uses_catalog_default_reasoning_when_config_empty() { other => panic!("expected status output, got {other:?}"), }; assert!( - rendered.contains("gpt-5.4 (reasoning xhigh, summaries auto)"), + rendered.contains("gpt-5.4 (reasoning medium, summaries auto)"), "expected /status to render the catalog default reasoning effort, got: {rendered}" ); } diff --git a/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs b/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs index 4b080794b1..c11d016751 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs @@ -112,6 +112,8 @@ async fn status_surface_preview_lines_hardcoded_only_snapshot() { StatusLineItem::ProjectRoot, StatusLineItem::GitBranch, StatusLineItem::ThreadTitle, + StatusLineItem::Permissions, + StatusLineItem::ApprovalMode, ], &[ TerminalTitleItem::Thread, @@ -123,6 +125,22 @@ async fn status_surface_preview_lines_hardcoded_only_snapshot() { assert_chatwidget_snapshot!("status_surface_previews_hardcoded_only", snapshot); } +#[tokio::test] +async fn thread_title_falls_back_to_thread_id_when_unnamed() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + let thread_id = ThreadId::new(); + chat.thread_id = Some(thread_id); + + assert_eq!( + status_preview_line(&mut chat, &[StatusLineItem::ThreadTitle]), + thread_id.to_string() + ); + assert_eq!( + title_preview_line(&mut chat, &[TerminalTitleItem::Thread]), + thread_id.to_string() + ); +} + #[tokio::test] async fn status_line_setup_popup_hardcoded_only_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index aa98a20bc4..5fe65c9fcc 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -15,7 +15,6 @@ use codex_protocol::ThreadId; use codex_protocol::account::PlanType; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::models::ActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; use codex_utils_sandbox_summary::summarize_permission_profile; @@ -567,25 +566,6 @@ fn status_permissions_label( approval: &str, ) -> String { let active_id = active_permission_profile.map(|active| active.id.as_str()); - let writable_root_modifications = active_permission_profile - .map(|active| { - active - .modifications - .iter() - .filter(|modification| { - matches!( - modification, - ActivePermissionProfileModification::AdditionalWritableRoot { .. } - ) - }) - .count() - }) - .unwrap_or(0); - let modification_suffix = match writable_root_modifications { - 0 => String::new(), - 1 => " + 1 writable root".to_string(), - count => format!(" + {count} writable roots"), - }; match active_id { Some(":read-only") => { let label = if sandbox == "read-only with network access" { @@ -593,12 +573,12 @@ fn status_permissions_label( } else { "Read Only" }; - return format!("{label}{modification_suffix} ({approval})"); + return format!("{label} ({approval})"); } Some(":workspace") => match sandbox { - "workspace" => return format!("Workspace{modification_suffix} ({approval})"), + "workspace" => return format!("Workspace ({approval})"), "workspace with network access" => { - return format!("Workspace with network access{modification_suffix} ({approval})"); + return format!("Workspace with network access ({approval})"); } _ => {} }, @@ -609,7 +589,7 @@ fn status_permissions_label( format!("No Sandbox ({approval})") }; } - Some(id) => return format!("Profile {id}{modification_suffix} ({sandbox}, {approval})"), + Some(id) => return format!("Profile {id} ({sandbox}, {approval})"), None => {} } diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index b511957d84..30aa65f0e2 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -30,7 +30,6 @@ use codex_protocol::ThreadId; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::ActivePermissionProfile; -use codex_protocol::models::ActivePermissionProfileModification; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::permissions::NetworkSandboxPolicy; @@ -307,7 +306,7 @@ async fn status_permissions_named_read_only_profile_shows_builtin_label() { } #[tokio::test] -async fn status_permissions_read_only_profile_shows_additional_writable_roots() { +async fn status_permissions_read_only_profile_ignores_workspace_root_metadata() { let temp_home = TempDir::new().expect("temp home"); let mut config = test_config(&temp_home).await; config @@ -326,19 +325,13 @@ async fn status_permissions_read_only_profile_shows_additional_writable_roots() &file_system_policy, NetworkSandboxPolicy::Restricted, ), - Some( - ActivePermissionProfile::new(":read-only").with_modifications(vec![ - ActivePermissionProfileModification::AdditionalWritableRoot { - path: extra_root, - }, - ]), - ), + Some(ActivePermissionProfile::new(":read-only")), ) .expect("set permission profile"); assert_eq!( permissions_text_for(&config).as_deref(), - Some("Read Only + 1 writable root (on-request)") + Some("Read Only (on-request)") ); } @@ -390,7 +383,7 @@ async fn status_permissions_workspace_auto_review_shows_reviewer_label() { } #[tokio::test] -async fn status_permissions_named_profile_shows_additional_writable_roots() { +async fn status_permissions_named_workspace_profile_uses_builtin_label() { let temp_home = TempDir::new().expect("temp home"); let mut config = test_config(&temp_home).await; config @@ -408,19 +401,13 @@ async fn status_permissions_named_profile_shows_additional_writable_roots() { /*exclude_tmpdir_env_var*/ false, /*exclude_slash_tmp*/ false, ), - Some( - ActivePermissionProfile::new(":workspace").with_modifications(vec![ - ActivePermissionProfileModification::AdditionalWritableRoot { - path: extra_root, - }, - ]), - ), + Some(ActivePermissionProfile::new(":workspace")), ) .expect("set permission profile"); assert_eq!( permissions_text_for(&config).as_deref(), - Some("Workspace + 1 writable root (on-request)") + Some("Workspace (on-request)") ); } diff --git a/codex-rs/tui/src/token_usage.rs b/codex-rs/tui/src/token_usage.rs index 14d3d78c6c..ac9a20be9a 100644 --- a/codex-rs/tui/src/token_usage.rs +++ b/codex-rs/tui/src/token_usage.rs @@ -34,6 +34,8 @@ impl TokenUsage { (self.non_cached_input() + self.output_tokens.max(0)).max(0) } + /// Returns the raw `total_tokens` value. For `last_token_usage`, this is the latest active + /// context size; for `total_token_usage`, this is the accumulated session total. pub(crate) fn tokens_in_context_window(&self) -> i64 { self.total_tokens } diff --git a/codex-rs/tui/tests/suite/model_availability_nux.rs b/codex-rs/tui/tests/suite/model_availability_nux.rs index 04a03a09f9..5a384e8280 100644 --- a/codex-rs/tui/tests/suite/model_availability_nux.rs +++ b/codex-rs/tui/tests/suite/model_availability_nux.rs @@ -177,15 +177,24 @@ trust_level = "trusted" } }; let output_text = String::from_utf8_lossy(&output); - let interrupt_only_output = { - let trimmed_output = output_text.trim(); - !trimmed_output.is_empty() - && trimmed_output + let rendered_output = { + let mut parser = vt100::Parser::new( + /*rows*/ 24, /*cols*/ 80, /*scrollback_len*/ 0, + ); + parser.process(&output); + parser.screen().contents() + }; + let interrupted_during_terminal_startup = { + let trimmed_output = rendered_output.trim(); + trimmed_output.is_empty() + || trimmed_output .chars() .all(|character| character == '^' || character == 'C' || character.is_whitespace()) }; anyhow::ensure!( - exit_code == 0 || exit_code == 130 || (exit_code == 1 && interrupt_only_output), + exit_code == 0 + || exit_code == 130 + || (exit_code == 1 && interrupted_during_terminal_startup), "unexpected exit code from codex resume: {exit_code}; output: {output_text}", ); diff --git a/codex-rs/uds/Cargo.toml b/codex-rs/uds/Cargo.toml index bc36708919..3477924772 100644 --- a/codex-rs/uds/Cargo.toml +++ b/codex-rs/uds/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_uds" path = "src/lib.rs" +doctest = false [lints] workspace = true diff --git a/codex-rs/utils/absolute-path/Cargo.toml b/codex-rs/utils/absolute-path/Cargo.toml index 1d35198ed4..7c5b4840d1 100644 --- a/codex-rs/utils/absolute-path/Cargo.toml +++ b/codex-rs/utils/absolute-path/Cargo.toml @@ -22,3 +22,6 @@ ts-rs = { workspace = true, features = [ pretty_assertions = { workspace = true } serde_json = { workspace = true } tempfile = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/approval-presets/Cargo.toml b/codex-rs/utils/approval-presets/Cargo.toml index 0e387f07a8..6efd2c482b 100644 --- a/codex-rs/utils/approval-presets/Cargo.toml +++ b/codex-rs/utils/approval-presets/Cargo.toml @@ -9,3 +9,7 @@ workspace = true [dependencies] codex-protocol = { workspace = true } + +[lib] +test = false +doctest = false diff --git a/codex-rs/utils/cache/Cargo.toml b/codex-rs/utils/cache/Cargo.toml index c034ad1346..3c120c032e 100644 --- a/codex-rs/utils/cache/Cargo.toml +++ b/codex-rs/utils/cache/Cargo.toml @@ -14,3 +14,6 @@ tokio = { workspace = true, features = ["sync", "rt", "rt-multi-thread"] } [dev-dependencies] tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread"] } + +[lib] +doctest = false diff --git a/codex-rs/utils/cargo-bin/Cargo.toml b/codex-rs/utils/cargo-bin/Cargo.toml index 6cbe923f97..a56e575830 100644 --- a/codex-rs/utils/cargo-bin/Cargo.toml +++ b/codex-rs/utils/cargo-bin/Cargo.toml @@ -11,3 +11,7 @@ workspace = true assert_cmd = { workspace = true } runfiles = { workspace = true } thiserror = { workspace = true } + +[lib] +test = false +doctest = false diff --git a/codex-rs/utils/cli/Cargo.toml b/codex-rs/utils/cli/Cargo.toml index d9adf42b3f..1ade005e3b 100644 --- a/codex-rs/utils/cli/Cargo.toml +++ b/codex-rs/utils/cli/Cargo.toml @@ -15,3 +15,6 @@ toml = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/elapsed/Cargo.toml b/codex-rs/utils/elapsed/Cargo.toml index a29d36995f..7ba5e6ae66 100644 --- a/codex-rs/utils/elapsed/Cargo.toml +++ b/codex-rs/utils/elapsed/Cargo.toml @@ -6,3 +6,6 @@ license.workspace = true [lints] workspace = true + +[lib] +doctest = false diff --git a/codex-rs/utils/fuzzy-match/Cargo.toml b/codex-rs/utils/fuzzy-match/Cargo.toml index 4788faba15..704386e74f 100644 --- a/codex-rs/utils/fuzzy-match/Cargo.toml +++ b/codex-rs/utils/fuzzy-match/Cargo.toml @@ -6,3 +6,6 @@ license.workspace = true [lints] workspace = true + +[lib] +doctest = false diff --git a/codex-rs/utils/home-dir/Cargo.toml b/codex-rs/utils/home-dir/Cargo.toml index 79f64e7490..2d2de0230e 100644 --- a/codex-rs/utils/home-dir/Cargo.toml +++ b/codex-rs/utils/home-dir/Cargo.toml @@ -14,3 +14,6 @@ dirs = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } tempfile = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/image/Cargo.toml b/codex-rs/utils/image/Cargo.toml index 9fcd3166bf..5ac187caaa 100644 --- a/codex-rs/utils/image/Cargo.toml +++ b/codex-rs/utils/image/Cargo.toml @@ -17,3 +17,6 @@ tokio = { workspace = true, features = ["fs", "rt", "rt-multi-thread", "macros"] [dev-dependencies] image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] } + +[lib] +doctest = false diff --git a/codex-rs/utils/json-to-toml/Cargo.toml b/codex-rs/utils/json-to-toml/Cargo.toml index 36e848d7de..57a28696c8 100644 --- a/codex-rs/utils/json-to-toml/Cargo.toml +++ b/codex-rs/utils/json-to-toml/Cargo.toml @@ -13,3 +13,6 @@ pretty_assertions = { workspace = true } [lints] workspace = true + +[lib] +doctest = false diff --git a/codex-rs/utils/oss/Cargo.toml b/codex-rs/utils/oss/Cargo.toml index d02202b69e..78cc0cb2f8 100644 --- a/codex-rs/utils/oss/Cargo.toml +++ b/codex-rs/utils/oss/Cargo.toml @@ -12,3 +12,6 @@ codex-core = { workspace = true } codex-lmstudio = { workspace = true } codex-model-provider-info = { workspace = true } codex-ollama = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/output-truncation/Cargo.toml b/codex-rs/utils/output-truncation/Cargo.toml index 7ad0ccfd46..17176c9f56 100644 --- a/codex-rs/utils/output-truncation/Cargo.toml +++ b/codex-rs/utils/output-truncation/Cargo.toml @@ -13,3 +13,6 @@ codex-utils-string = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/path-utils/Cargo.toml b/codex-rs/utils/path-utils/Cargo.toml index 0d1693361f..d1503fd060 100644 --- a/codex-rs/utils/path-utils/Cargo.toml +++ b/codex-rs/utils/path-utils/Cargo.toml @@ -15,3 +15,6 @@ tempfile = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } tempfile = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/pty/Cargo.toml b/codex-rs/utils/pty/Cargo.toml index 7196cf5312..f38e8f7a63 100644 --- a/codex-rs/utils/pty/Cargo.toml +++ b/codex-rs/utils/pty/Cargo.toml @@ -32,3 +32,6 @@ winapi = { version = "0.3.9", features = [ ] } [target.'cfg(unix)'.dependencies] libc = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/readiness/Cargo.toml b/codex-rs/utils/readiness/Cargo.toml index 12519d4adb..2a6dfaeb54 100644 --- a/codex-rs/utils/readiness/Cargo.toml +++ b/codex-rs/utils/readiness/Cargo.toml @@ -16,3 +16,6 @@ tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread"] } [lints] workspace = true + +[lib] +doctest = false diff --git a/codex-rs/utils/rustls-provider/Cargo.toml b/codex-rs/utils/rustls-provider/Cargo.toml index c9077df780..af79eff692 100644 --- a/codex-rs/utils/rustls-provider/Cargo.toml +++ b/codex-rs/utils/rustls-provider/Cargo.toml @@ -9,3 +9,7 @@ workspace = true [dependencies] rustls = { workspace = true } + +[lib] +test = false +doctest = false diff --git a/codex-rs/utils/sandbox-summary/Cargo.toml b/codex-rs/utils/sandbox-summary/Cargo.toml index ade36985c0..d8cf3d575b 100644 --- a/codex-rs/utils/sandbox-summary/Cargo.toml +++ b/codex-rs/utils/sandbox-summary/Cargo.toml @@ -13,5 +13,7 @@ codex-model-provider-info = { workspace = true } codex-protocol = { workspace = true } [dev-dependencies] -codex-utils-absolute-path = { workspace = true } pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs b/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs index 0719773aad..8fa9080dd9 100644 --- a/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs +++ b/codex-rs/utils/sandbox-summary/src/sandbox_summary.rs @@ -21,7 +21,6 @@ pub fn summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String { summary } SandboxPolicy::WorkspaceWrite { - writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, @@ -36,11 +35,6 @@ pub fn summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String { if !*exclude_tmpdir_env_var { writable_entries.push("$TMPDIR".to_string()); } - writable_entries.extend( - writable_roots - .iter() - .map(|p| p.to_string_lossy().to_string()), - ); summary.push_str(&format!(" [{}]", writable_entries.join(", "))); if *network_access { @@ -67,7 +61,6 @@ pub fn summarize_permission_profile(permission_profile: &PermissionProfile, cwd: #[cfg(test)] mod tests { use super::*; - use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; #[test] @@ -96,20 +89,14 @@ mod tests { #[test] fn workspace_write_summary_still_includes_network_access() { - let root = if cfg!(windows) { "C:\\repo" } else { "/repo" }; - let writable_root = AbsolutePathBuf::try_from(root).unwrap(); let summary = summarize_sandbox_policy(&SandboxPolicy::WorkspaceWrite { - writable_roots: vec![writable_root.clone()], network_access: true, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, }); assert_eq!( summary, - format!( - "workspace-write [workdir, {}] (network access enabled)", - writable_root.to_string_lossy() - ) + "workspace-write [workdir] (network access enabled)" ); } } diff --git a/codex-rs/utils/sleep-inhibitor/Cargo.toml b/codex-rs/utils/sleep-inhibitor/Cargo.toml index 888705a770..f2abb6df21 100644 --- a/codex-rs/utils/sleep-inhibitor/Cargo.toml +++ b/codex-rs/utils/sleep-inhibitor/Cargo.toml @@ -23,3 +23,6 @@ windows-sys = { version = "0.61.2", features = [ "Win32_System_SystemServices", "Win32_System_Threading", ] } + +[lib] +doctest = false diff --git a/codex-rs/utils/stream-parser/Cargo.toml b/codex-rs/utils/stream-parser/Cargo.toml index faba53e1fe..6eb5fb9a87 100644 --- a/codex-rs/utils/stream-parser/Cargo.toml +++ b/codex-rs/utils/stream-parser/Cargo.toml @@ -9,3 +9,6 @@ workspace = true [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/string/Cargo.toml b/codex-rs/utils/string/Cargo.toml index a81760e5ef..8710cffe46 100644 --- a/codex-rs/utils/string/Cargo.toml +++ b/codex-rs/utils/string/Cargo.toml @@ -14,3 +14,6 @@ serde_json = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/utils/template/Cargo.toml b/codex-rs/utils/template/Cargo.toml index 60a0c5b984..f24caec190 100644 --- a/codex-rs/utils/template/Cargo.toml +++ b/codex-rs/utils/template/Cargo.toml @@ -9,3 +9,6 @@ workspace = true [dev-dependencies] pretty_assertions = { workspace = true } + +[lib] +doctest = false diff --git a/codex-rs/v8-poc/Cargo.toml b/codex-rs/v8-poc/Cargo.toml index cbcb7ca404..9615ab977f 100644 --- a/codex-rs/v8-poc/Cargo.toml +++ b/codex-rs/v8-poc/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [lib] name = "codex_v8_poc" path = "src/lib.rs" +doctest = false [features] sandbox = ["v8/v8_enable_sandbox"] diff --git a/codex-rs/windows-sandbox-rs/Cargo.toml b/codex-rs/windows-sandbox-rs/Cargo.toml index e45509a960..4a71a952e7 100644 --- a/codex-rs/windows-sandbox-rs/Cargo.toml +++ b/codex-rs/windows-sandbox-rs/Cargo.toml @@ -8,6 +8,7 @@ version.workspace = true [lib] name = "codex_windows_sandbox" path = "src/lib.rs" +doctest = false [[bin]] name = "codex-windows-sandbox-setup" diff --git a/codex-rs/windows-sandbox-rs/src/allow.rs b/codex-rs/windows-sandbox-rs/src/allow.rs index 273dc8c4f2..1ac0fcc7a2 100644 --- a/codex-rs/windows-sandbox-rs/src/allow.rs +++ b/codex-rs/windows-sandbox-rs/src/allow.rs @@ -66,17 +66,6 @@ pub fn compute_allow_paths( &mut add_allow_path, &mut add_deny_path, ); - - if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = policy { - for root in writable_roots { - add_writable_root( - root.clone().into(), - policy_cwd, - &mut add_allow_path, - &mut add_deny_path, - ); - } - } } if include_tmp_env_vars { for key in ["TEMP", "TMP"] { @@ -95,21 +84,16 @@ pub fn compute_allow_paths( #[cfg(test)] mod tests { use super::*; - use codex_protocol::protocol::SandboxPolicy; - use codex_utils_absolute_path::AbsolutePathBuf; use std::fs; use tempfile::TempDir; #[test] - fn includes_additional_writable_roots() { + fn includes_command_cwd_as_writable_root() { let tmp = TempDir::new().expect("tempdir"); let command_cwd = tmp.path().join("workspace"); - let extra_root = tmp.path().join("extra"); let _ = fs::create_dir_all(&command_cwd); - let _ = fs::create_dir_all(&extra_root); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![AbsolutePathBuf::try_from(extra_root.as_path()).unwrap()], network_access: false, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, @@ -120,9 +104,6 @@ mod tests { assert!(paths .allow .contains(&dunce::canonicalize(&command_cwd).unwrap())); - assert!(paths - .allow - .contains(&dunce::canonicalize(&extra_root).unwrap())); assert!(paths.deny.is_empty(), "no deny paths expected"); } @@ -135,7 +116,6 @@ mod tests { let _ = fs::create_dir_all(&temp_dir); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: false, @@ -162,7 +142,6 @@ mod tests { let _ = fs::create_dir_all(&git_dir); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: false, @@ -189,7 +168,6 @@ mod tests { let _ = fs::write(&git_file, "gitdir: .git/worktrees/example"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: false, @@ -217,7 +195,6 @@ mod tests { let _ = fs::create_dir_all(&agents_dir); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: false, @@ -245,7 +222,6 @@ mod tests { let _ = fs::create_dir_all(&command_cwd); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: false, diff --git a/codex-rs/windows-sandbox-rs/src/audit.rs b/codex-rs/windows-sandbox-rs/src/audit.rs index 9ee371ce68..a15bc36315 100644 --- a/codex-rs/windows-sandbox-rs/src/audit.rs +++ b/codex-rs/windows-sandbox-rs/src/audit.rs @@ -250,15 +250,10 @@ pub fn apply_capability_denies_for_world_writable( let caps = load_or_create_cap_sids(codex_home)?; std::fs::write(&cap_path, serde_json::to_string(&caps)?)?; let (active_sid, workspace_roots): (*mut c_void, Vec) = match sandbox_policy { - SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + SandboxPolicy::WorkspaceWrite { .. } => { let sid = unsafe { convert_string_sid_to_sid(&caps.workspace) } .ok_or_else(|| anyhow!("ConvertStringSidToSidW failed for workspace capability"))?; - let mut roots: Vec = - vec![dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf())]; - for root in writable_roots { - let candidate = root.as_path(); - roots.push(dunce::canonicalize(candidate).unwrap_or_else(|_| root.to_path_buf())); - } + let roots = vec![dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf())]; (sid, roots) } SandboxPolicy::ReadOnly { .. } => ( diff --git a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs index be9f1cfb98..98745b7655 100644 --- a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs +++ b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs @@ -194,7 +194,6 @@ mod windows_impl { fn workspace_policy(network_access: bool) -> SandboxPolicy { SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index 522f8926d5..fd1f99394e 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -656,7 +656,6 @@ mod windows_impl { fn workspace_policy(network_access: bool) -> SandboxPolicy { SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs b/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs index ef952a4e03..2b3693845e 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_orchestrator.rs @@ -368,11 +368,6 @@ fn gather_legacy_full_read_roots( roots.extend(profile_read_roots(Path::new(&up))); } roots.push(command_cwd.to_path_buf()); - if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = policy { - for root in writable_roots { - roots.push(root.to_path_buf()); - } - } canonical_existing(&roots) } @@ -1276,26 +1271,19 @@ mod tests { } #[test] - fn workspace_write_roots_remain_readable() { + fn workspace_write_cwd_remains_readable() { let tmp = TempDir::new().expect("tempdir"); let codex_home = tmp.path().join("codex-home"); let command_cwd = tmp.path().join("workspace"); - let writable_root = tmp.path().join("extra-write-root"); fs::create_dir_all(&command_cwd).expect("create workspace"); - fs::create_dir_all(&writable_root).expect("create writable root"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![ - AbsolutePathBuf::from_absolute_path(&writable_root) - .expect("absolute writable root"), - ], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, }; let roots = gather_read_roots(&command_cwd, &policy, &codex_home); - let expected_writable = - dunce::canonicalize(&writable_root).expect("canonical writable root"); + let expected_writable = dunce::canonicalize(&command_cwd).expect("canonical command cwd"); assert!(roots.contains(&expected_writable)); } @@ -1406,10 +1394,6 @@ mod tests { fs::create_dir_all(&command_git).expect("create command .git"); fs::create_dir_all(&extra_codex).expect("create extra .codex"); let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![ - AbsolutePathBuf::from_absolute_path(&extra_write_root) - .expect("absolute writable root"), - ], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, diff --git a/codex-rs/windows-sandbox-rs/src/spawn_prep.rs b/codex-rs/windows-sandbox-rs/src/spawn_prep.rs index 1b3704d6a2..8c275d5430 100644 --- a/codex-rs/windows-sandbox-rs/src/spawn_prep.rs +++ b/codex-rs/windows-sandbox-rs/src/spawn_prep.rs @@ -350,7 +350,6 @@ mod tests { fn no_network_env_rewrite_skips_when_network_access_is_allowed() { assert!(!should_apply_network_block( &SandboxPolicy::WorkspaceWrite { - writable_roots: Vec::new(), network_access: true, exclude_tmpdir_env_var: false, exclude_slash_tmp: false, diff --git a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs index bfcc2c069b..89d29118c2 100644 --- a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs +++ b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs @@ -5,6 +5,7 @@ use codex_otel::OtelExporter; use codex_otel::OtelProvider; use codex_otel::OtelSettings; use codex_otel::StatsigMetricsSettings; +use std::collections::BTreeMap; use std::path::Path; const WFP_SETUP_SERVICE_NAME: &str = "codex-windows-sandbox-setup"; @@ -54,6 +55,8 @@ fn build_wfp_metrics_provider( trace_exporter: OtelExporter::None, metrics_exporter: OtelExporter::Statsig, runtime_metrics: false, + span_attributes: BTreeMap::new(), + tracestate: BTreeMap::new(), }) .map_err(|err| anyhow::anyhow!("failed to initialize WFP setup metrics provider: {err}")) } diff --git a/docs/config.md b/docs/config.md index e0a0c5fc2f..759d6b94b8 100644 --- a/docs/config.md +++ b/docs/config.md @@ -26,3 +26,24 @@ When enabled, Codex appends a `Co-authored-by:` trailer using the configured attribution value. If `commit_attribution` is omitted, Codex uses `Codex `. Set `commit_attribution = ""` to disable the trailer while leaving the feature flag enabled. + +## OpenTelemetry Trace Metadata + +Codex can add static OpenTelemetry span attributes to exported trace spans and +static W3C tracestate fields to propagated trace context: + +```toml +[otel.span_attributes] +"example.trace_attr" = "enabled" + +[otel.tracestate.example] +alpha = "one" +beta = "two" +``` + +Nested `otel.tracestate` tables are encoded as semicolon-separated `key:value` +fields inside the named tracestate member. If propagated trace context already +has the named member, Codex upserts configured fields and preserves other fields +in that member. This config shape does not support setting opaque tracestate +member values. Invalid trace metadata entries are ignored during config load and +reported as startup warnings. diff --git a/docs/install.md b/docs/install.md index b7d4f0711a..0991e7d16c 100644 --- a/docs/install.md +++ b/docs/install.md @@ -25,7 +25,7 @@ source "$HOME/.cargo/env" rustup component add rustfmt rustup component add clippy # Install helper tools used by the workspace justfile: -cargo install just +cargo install --locked just # Optional: install nextest for the `just test` helper cargo install --locked cargo-nextest diff --git a/justfile b/justfile index ca74c2e5c6..71eed89a35 100644 --- a/justfile +++ b/justfile @@ -47,7 +47,7 @@ install: # Run `cargo nextest` since it's faster than `cargo test`, though including # --no-fail-fast is important to ensure all tests are run. # -# Run `cargo install cargo-nextest` if you don't have it installed. +# Run `cargo install --locked cargo-nextest` if you don't have it installed. # Prefer this for routine local runs. Workspace crate features are banned, so # there should be no need to add `--all-features`. test: diff --git a/tools/argument-comment-lint/README.md b/tools/argument-comment-lint/README.md index 1b4895e325..7270c48867 100644 --- a/tools/argument-comment-lint/README.md +++ b/tools/argument-comment-lint/README.md @@ -54,7 +54,7 @@ create_openai_url(None, 3); Install the required tooling once: ```bash -cargo install cargo-dylint dylint-link +cargo install --locked cargo-dylint dylint-link rustup toolchain install nightly-2025-09-18 \ --component llvm-tools-preview \ --component rustc-dev \