diff --git a/.codex/skills/code-review-context/SKILL.md b/.codex/skills/code-review-context/SKILL.md index 3d33192ec5..7faf3d7cd2 100644 --- a/.codex/skills/code-review-context/SKILL.md +++ b/.codex/skills/code-review-context/SKILL.md @@ -10,3 +10,4 @@ Codex maintains a context (history of messages) that is sent to the model in inf 3. No unbounded items - everything injected in the model context must have a bounded size and a hard cap. 4. No items larger than 10K tokens. 5. Highlight new individual items that can cross >1k tokens as P0. These need an additional manual review. +6. All injected fragments must be defined as structs in `core/context` and implement ContextualUserFragment trait \ No newline at end of file diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 1dbc873796..f5ad018c03 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -667,6 +667,7 @@ "axum_0.7.9": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.67\"},{\"name\":\"axum-core\",\"req\":\"^0.4.5\"},{\"name\":\"axum-macros\",\"optional\":true,\"req\":\"^0.4.2\"},{\"features\":[\"__private\"],\"kind\":\"dev\",\"name\":\"axum-macros\",\"req\":\"^0.4.1\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22.1\"},{\"name\":\"bytes\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1.0.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"optional\":true,\"req\":\"^1.1.0\"},{\"features\":[\"tokio\",\"server\",\"service\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1.3\"},{\"name\":\"itoa\",\"req\":\"^1.0.5\"},{\"name\":\"matchit\",\"req\":\"^0.7\"},{\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"mime\",\"req\":\"^0.3.16\"},{\"name\":\"multer\",\"optional\":true,\"req\":\"^3.0.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"name\":\"rustversion\",\"req\":\"^1.0.9\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"raw_value\"],\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"serde_path_to_error\",\"optional\":true,\"req\":\"^0.1.8\"},{\"name\":\"serde_urlencoded\",\"optional\":true,\"req\":\"^0.7\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0.0\"},{\"features\":[\"serde-human-readable\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3\"},{\"features\":[\"time\"],\"name\":\"tokio\",\"optional\":true,\"package\":\"tokio\",\"req\":\"^1.25.0\"},{\"features\":[\"macros\",\"rt\",\"rt-multi-thread\",\"net\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"package\":\"tokio\",\"req\":\"^1.25.0\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"name\":\"tokio-tungstenite\",\"optional\":true,\"req\":\"^0.24.0\"},{\"kind\":\"dev\",\"name\":\"tokio-tungstenite\",\"req\":\"^0.24.0\"},{\"default_features\":false,\"features\":[\"util\"],\"name\":\"tower\",\"req\":\"^0.5.1\"},{\"features\":[\"util\",\"timeout\",\"limit\",\"load-shed\",\"steer\",\"filter\"],\"kind\":\"dev\",\"name\":\"tower\",\"package\":\"tower\",\"req\":\"^0.5.1\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"name\":\"tower-http\",\"optional\":true,\"req\":\"^0.6.0\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"kind\":\"dev\",\"name\":\"tower-http\",\"req\":\"^0.6.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3.2\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"json\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"features\":[\"serde\",\"v4\"],\"kind\":\"dev\",\"name\":\"uuid\",\"req\":\"^1.0\"}],\"features\":{\"__private_docs\":[\"axum-core/__private_docs\",\"tower/full\",\"dep:tower-http\"],\"default\":[\"form\",\"http1\",\"json\",\"matched-path\",\"original-uri\",\"query\",\"tokio\",\"tower-log\",\"tracing\"],\"form\":[\"dep:serde_urlencoded\"],\"http1\":[\"dep:hyper\",\"hyper?/http1\",\"hyper-util?/http1\"],\"http2\":[\"dep:hyper\",\"hyper?/http2\",\"hyper-util?/http2\"],\"json\":[\"dep:serde_json\",\"dep:serde_path_to_error\"],\"macros\":[\"dep:axum-macros\"],\"matched-path\":[],\"multipart\":[\"dep:multer\"],\"original-uri\":[],\"query\":[\"dep:serde_urlencoded\"],\"tokio\":[\"dep:hyper-util\",\"dep:tokio\",\"tokio/net\",\"tokio/rt\",\"tower/make\",\"tokio/macros\"],\"tower-log\":[\"tower/log\"],\"tracing\":[\"dep:tracing\",\"axum-core/tracing\"],\"ws\":[\"dep:hyper\",\"tokio\",\"dep:tokio-tungstenite\",\"dep:sha1\",\"dep:base64\"]}}", "axum_0.8.8": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"axum-core\",\"req\":\"^0.5.5\"},{\"name\":\"axum-macros\",\"optional\":true,\"req\":\"^0.5.0\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22.1\"},{\"name\":\"bytes\",\"req\":\"^1.0\"},{\"name\":\"form_urlencoded\",\"optional\":true,\"req\":\"^1.1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"http\",\"req\":\"^1.0.0\"},{\"name\":\"http-body\",\"req\":\"^1.0.0\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.0\"},{\"name\":\"hyper\",\"optional\":true,\"req\":\"^1.1.0\"},{\"features\":[\"client\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1.0\"},{\"features\":[\"tokio\",\"server\",\"service\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1.3\"},{\"name\":\"itoa\",\"req\":\"^1.0.5\"},{\"name\":\"matchit\",\"req\":\"=0.8.4\"},{\"name\":\"memchr\",\"req\":\"^2.4.1\"},{\"name\":\"mime\",\"req\":\"^0.3.16\"},{\"name\":\"multer\",\"optional\":true,\"req\":\"^3.0.0\"},{\"name\":\"percent-encoding\",\"req\":\"^2.1\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.7\"},{\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"quickcheck_macros\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"default_features\":false,\"features\":[\"json\",\"stream\",\"multipart\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.211\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.221\"},{\"name\":\"serde_core\",\"req\":\"^1.0.221\"},{\"features\":[\"raw_value\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"raw_value\"],\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"serde_path_to_error\",\"optional\":true,\"req\":\"^0.1.8\"},{\"name\":\"serde_urlencoded\",\"optional\":true,\"req\":\"^0.7\"},{\"name\":\"sha1\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"sync_wrapper\",\"req\":\"^1.0.0\"},{\"features\":[\"serde-human-readable\"],\"kind\":\"dev\",\"name\":\"time\",\"req\":\"^0.3\"},{\"features\":[\"time\"],\"name\":\"tokio\",\"optional\":true,\"package\":\"tokio\",\"req\":\"^1.44\"},{\"features\":[\"macros\",\"rt\",\"rt-multi-thread\",\"net\",\"test-util\"],\"kind\":\"dev\",\"name\":\"tokio\",\"package\":\"tokio\",\"req\":\"^1.44.2\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"name\":\"tokio-tungstenite\",\"optional\":true,\"req\":\"^0.28.0\"},{\"kind\":\"dev\",\"name\":\"tokio-tungstenite\",\"req\":\"^0.28.0\"},{\"default_features\":false,\"features\":[\"util\"],\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"features\":[\"util\",\"timeout\",\"limit\",\"load-shed\",\"steer\",\"filter\"],\"kind\":\"dev\",\"name\":\"tower\",\"package\":\"tower\",\"req\":\"^0.5.2\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"name\":\"tower-http\",\"optional\":true,\"req\":\"^0.6.0\"},{\"features\":[\"add-extension\",\"auth\",\"catch-panic\",\"compression-br\",\"compression-deflate\",\"compression-gzip\",\"cors\",\"decompression-br\",\"decompression-deflate\",\"decompression-gzip\",\"follow-redirect\",\"fs\",\"limit\",\"map-request-body\",\"map-response-body\",\"metrics\",\"normalize-path\",\"propagate-header\",\"redirect\",\"request-id\",\"sensitive-headers\",\"set-header\",\"set-status\",\"timeout\",\"trace\",\"util\",\"validate-request\"],\"kind\":\"dev\",\"name\":\"tower-http\",\"req\":\"^0.6.0\"},{\"name\":\"tower-layer\",\"req\":\"^0.3.2\"},{\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"tracing\",\"optional\":true,\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"json\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"features\":[\"serde\",\"v4\"],\"kind\":\"dev\",\"name\":\"uuid\",\"req\":\"^1.0\"}],\"features\":{\"__private\":[\"tokio\",\"http1\",\"dep:reqwest\"],\"__private_docs\":[\"axum-core/__private_docs\",\"tower/full\",\"dep:serde\",\"dep:tower-http\"],\"default\":[\"form\",\"http1\",\"json\",\"matched-path\",\"original-uri\",\"query\",\"tokio\",\"tower-log\",\"tracing\"],\"form\":[\"dep:form_urlencoded\",\"dep:serde_urlencoded\",\"dep:serde_path_to_error\"],\"http1\":[\"dep:hyper\",\"hyper?/http1\",\"hyper-util?/http1\"],\"http2\":[\"dep:hyper\",\"hyper?/http2\",\"hyper-util?/http2\"],\"json\":[\"dep:serde_json\",\"dep:serde_path_to_error\"],\"macros\":[\"dep:axum-macros\"],\"matched-path\":[],\"multipart\":[\"dep:multer\"],\"original-uri\":[],\"query\":[\"dep:form_urlencoded\",\"dep:serde_urlencoded\",\"dep:serde_path_to_error\"],\"tokio\":[\"dep:hyper-util\",\"dep:tokio\",\"tokio/net\",\"tokio/rt\",\"tower/make\",\"tokio/macros\"],\"tower-log\":[\"tower/log\"],\"tracing\":[\"dep:tracing\",\"axum-core/tracing\"],\"ws\":[\"dep:hyper\",\"tokio\",\"dep:tokio-tungstenite\",\"dep:sha1\",\"dep:base64\"]}}", "backtrace_0.3.76": "{\"dependencies\":[{\"default_features\":false,\"name\":\"addr2line\",\"req\":\"^0.25.0\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"cpp_demangle\",\"optional\":true,\"req\":\"^0.5.0\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.156\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"kind\":\"dev\",\"name\":\"libloading\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"miniz_oxide\",\"req\":\"^0.8\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"default_features\":false,\"features\":[\"read_core\",\"elf\",\"macho\",\"pe\",\"xcoff\",\"unaligned\",\"archive\"],\"name\":\"object\",\"req\":\"^0.37.0\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"name\":\"rustc-demangle\",\"req\":\"^0.1.24\"},{\"default_features\":false,\"name\":\"ruzstd\",\"optional\":true,\"req\":\"^0.8.1\",\"target\":\"cfg(not(all(windows, target_env = \\\"msvc\\\", not(target_vendor = \\\"uwp\\\"))))\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"windows-link\",\"req\":\"^0.2\",\"target\":\"cfg(any(windows, target_os = \\\"cygwin\\\"))\"}],\"features\":{\"coresymbolication\":[],\"dbghelp\":[],\"default\":[\"std\"],\"dl_iterate_phdr\":[],\"dladdr\":[],\"kernel32\":[],\"libunwind\":[],\"ruzstd\":[\"dep:ruzstd\"],\"serialize-serde\":[\"serde\"],\"std\":[],\"unix-backtrace\":[]}}", + "base16ct_0.2.0": "{\"dependencies\":[],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", "base64_0.21.7": "{\"dependencies\":[{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^3.2.25\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"kind\":\"dev\",\"name\":\"rstest\",\"req\":\"^0.13.0\"},{\"kind\":\"dev\",\"name\":\"rstest_reuse\",\"req\":\"^0.6.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"strum\",\"req\":\"^0.25\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "base64_0.22.1": "{\"dependencies\":[{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"clap\",\"req\":\"^3.2.25\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4.0\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"kind\":\"dev\",\"name\":\"rstest\",\"req\":\"^0.13.0\"},{\"kind\":\"dev\",\"name\":\"rstest_reuse\",\"req\":\"^0.6.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"strum\",\"req\":\"^0.25\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", "base64ct_1.8.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"base64\",\"req\":\"^0.22\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.6\"}],\"features\":{\"alloc\":[],\"std\":[\"alloc\"]}}", @@ -680,7 +681,6 @@ "bitflags_1.3.2": "{\"dependencies\":[{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.2\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3\"}],\"features\":{\"default\":[],\"example_generated\":[],\"rustc-dep-of-std\":[\"core\",\"compiler_builtins\"]}}", "bitflags_2.10.0": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"arbitrary\",\"req\":\"^1.0\"},{\"name\":\"bytemuck\",\"optional\":true,\"req\":\"^1.12\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"bytemuck\",\"req\":\"^1.12.2\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.228\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde_lib\",\"package\":\"serde\",\"req\":\"^1.0.103\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0.19\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.18\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"zerocopy\",\"req\":\"^0.8\"}],\"features\":{\"example_generated\":[],\"serde\":[\"serde_core\"],\"std\":[]}}", "bitflags_2.11.0": "{\"dependencies\":[{\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"arbitrary\",\"req\":\"^1.0\"},{\"name\":\"bytemuck\",\"optional\":true,\"req\":\"^1.12\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"bytemuck\",\"req\":\"^1.12.2\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.228\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde_lib\",\"package\":\"serde\",\"req\":\"^1.0.103\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0.19\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.18\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"zerocopy\",\"req\":\"^0.8\"}],\"features\":{\"example_generated\":[],\"serde\":[\"serde_core\"],\"std\":[]}}", - "blake2_0.10.6": "{\"dependencies\":[{\"features\":[\"mac\"],\"name\":\"digest\",\"req\":\"^0.10.3\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"digest\",\"req\":\"^0.10.3\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.2.2\"}],\"features\":{\"default\":[\"std\"],\"reset\":[],\"simd\":[],\"simd_asm\":[\"simd_opt\"],\"simd_opt\":[\"simd\"],\"size_opt\":[],\"std\":[\"digest/std\"]}}", "block-buffer_0.10.4": "{\"dependencies\":[{\"name\":\"generic-array\",\"req\":\"^0.14\"}],\"features\":{}}", "block-padding_0.3.3": "{\"dependencies\":[{\"name\":\"generic-array\",\"req\":\"^0.14\"}],\"features\":{\"std\":[]}}", "block2_0.6.2": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"std\"],\"name\":\"objc2\",\"req\":\">=0.6.2, <0.8.0\"}],\"features\":{\"alloc\":[],\"compiler-rt\":[\"objc2/unstable-compiler-rt\"],\"default\":[\"std\"],\"gnustep-1-7\":[\"objc2/gnustep-1-7\"],\"gnustep-1-8\":[\"gnustep-1-7\",\"objc2/gnustep-1-8\"],\"gnustep-1-9\":[\"gnustep-1-8\",\"objc2/gnustep-1-9\"],\"gnustep-2-0\":[\"gnustep-1-9\",\"objc2/gnustep-2-0\"],\"gnustep-2-1\":[\"gnustep-2-0\",\"objc2/gnustep-2-1\"],\"std\":[\"alloc\"],\"unstable-coerce-pointee\":[],\"unstable-objfw\":[],\"unstable-private\":[],\"unstable-winobjc\":[\"gnustep-1-8\"]}}", @@ -755,6 +755,8 @@ "convert_case_0.10.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"unicode-segmentation\",\"req\":\"^1.9.0\"}],\"features\":{}}", "convert_case_0.6.0": "{\"dependencies\":[{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"strum\",\"req\":\"^0.18.0\"},{\"kind\":\"dev\",\"name\":\"strum_macros\",\"req\":\"^0.18.0\"},{\"name\":\"unicode-segmentation\",\"req\":\"^1.9.0\"}],\"features\":{\"random\":[\"rand\"]}}", "cookie-factory_0.3.3": "{\"dependencies\":[{\"features\":[\"attributes\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.9.0\"},{\"name\":\"futures\",\"optional\":true,\"req\":\"^0.3.16\"},{\"kind\":\"dev\",\"name\":\"maplit\",\"req\":\"^1.0\"}],\"features\":{\"async\":[\"futures\"],\"default\":[\"std\",\"async\"],\"std\":[]}}", + "cookie_0.18.1": "{\"dependencies\":[{\"name\":\"aes-gcm\",\"optional\":true,\"req\":\"^0.10.0\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"hkdf\",\"optional\":true,\"req\":\"^0.12.0\"},{\"name\":\"hmac\",\"optional\":true,\"req\":\"^0.12.0\"},{\"name\":\"percent-encoding\",\"optional\":true,\"req\":\"^2.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10.0\"},{\"name\":\"subtle\",\"optional\":true,\"req\":\"^2.3\"},{\"default_features\":false,\"features\":[\"std\",\"parsing\",\"formatting\",\"macros\"],\"name\":\"time\",\"req\":\"^0.3\"},{\"kind\":\"build\",\"name\":\"version_check\",\"req\":\"^0.9.4\"}],\"features\":{\"key-expansion\":[\"sha2\",\"hkdf\"],\"percent-encode\":[\"percent-encoding\"],\"private\":[\"aes-gcm\",\"base64\",\"rand\",\"subtle\"],\"secure\":[\"private\",\"signed\",\"key-expansion\"],\"signed\":[\"hmac\",\"sha2\",\"base64\",\"rand\",\"subtle\"]}}", + "cookie_store_0.22.1": "{\"dependencies\":[{\"features\":[\"percent-encode\"],\"name\":\"cookie\",\"req\":\"^0.18.0\"},{\"name\":\"document-features\",\"req\":\"^0.2.10\"},{\"name\":\"idna\",\"req\":\"^1.0\"},{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.6.0\"},{\"name\":\"log\",\"req\":\"^0.4.17\"},{\"name\":\"publicsuffix\",\"optional\":true,\"req\":\"^2.2.3\"},{\"name\":\"ron\",\"optional\":true,\"req\":\"^0.10.1\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.147\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0.147\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.87\"},{\"name\":\"time\",\"req\":\"^0.3.47\"},{\"name\":\"url\",\"req\":\"^2.3.1\"}],\"features\":{\"default\":[\"public_suffix\",\"serde_json\"],\"log_secure_cookie_values\":[],\"preserve_order\":[\"dep:indexmap\"],\"public_suffix\":[\"dep:publicsuffix\"],\"serde\":[\"dep:serde\",\"dep:serde_derive\"],\"serde_json\":[\"serde\",\"dep:serde_json\"],\"serde_ron\":[\"serde\",\"dep:ron\"],\"wasm-bindgen\":[\"time/wasm-bindgen\"]}}", "core-foundation-sys_0.8.7": "{\"dependencies\":[],\"features\":{\"default\":[\"link\"],\"link\":[],\"mac_os_10_7_support\":[],\"mac_os_10_8_features\":[]}}", "core-foundation_0.10.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"core-foundation-sys\",\"req\":\"^0.8\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"default\":[\"link\"],\"link\":[\"core-foundation-sys/link\"],\"mac_os_10_7_support\":[\"core-foundation-sys/mac_os_10_7_support\"],\"mac_os_10_8_features\":[\"core-foundation-sys/mac_os_10_8_features\"],\"with-uuid\":[\"dep:uuid\"]}}", "core-foundation_0.9.4": "{\"dependencies\":[{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"core-foundation-sys\",\"req\":\"^0.8.6\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"uuid\",\"optional\":true,\"req\":\"^0.5\"}],\"features\":{\"default\":[\"link\"],\"link\":[\"core-foundation-sys/link\"],\"mac_os_10_7_support\":[\"core-foundation-sys/mac_os_10_7_support\"],\"mac_os_10_8_features\":[\"core-foundation-sys/mac_os_10_8_features\"],\"with-chrono\":[\"chrono\"],\"with-uuid\":[\"uuid\"]}}", @@ -774,9 +776,8 @@ "crossbeam-utils_0.8.21": "{\"dependencies\":[{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7.1\",\"target\":\"cfg(crossbeam_loom)\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"}],\"features\":{\"default\":[\"std\"],\"nightly\":[],\"std\":[]}}", "crossterm_winapi_0.9.1": "{\"dependencies\":[{\"features\":[\"winbase\",\"consoleapi\",\"processenv\",\"handleapi\",\"synchapi\",\"impl-default\"],\"name\":\"winapi\",\"req\":\"^0.3.8\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "crunchy_0.2.4": "{\"dependencies\":[],\"features\":{\"default\":[\"limit_128\"],\"limit_1024\":[],\"limit_128\":[],\"limit_2048\":[],\"limit_256\":[],\"limit_512\":[],\"limit_64\":[],\"std\":[]}}", + "crypto-bigint_0.5.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1\"},{\"features\":[\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"der\",\"optional\":true,\"req\":\"^0.7\"},{\"name\":\"generic-array\",\"optional\":true,\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"num-bigint\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"num-integer\",\"req\":\"^0.1\"},{\"kind\":\"dev\",\"name\":\"num-traits\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"rand_chacha\",\"req\":\"^0.3\"},{\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6.4\"},{\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"name\":\"rlp\",\"optional\":true,\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.4\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"serdect?/alloc\"],\"default\":[\"rand\"],\"extra-sizes\":[],\"rand\":[\"rand_core/std\"],\"serde\":[\"dep:serdect\"]}}", "crypto-common_0.1.7": "{\"dependencies\":[{\"features\":[\"more_lengths\"],\"name\":\"generic-array\",\"req\":\"=0.14.7\"},{\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6\"},{\"name\":\"typenum\",\"req\":\"^1.14\"}],\"features\":{\"getrandom\":[\"rand_core/getrandom\"],\"std\":[]}}", - "crypto_box_0.9.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aead\",\"req\":\"^0.5.2\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"blake2\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"chacha20\",\"optional\":true,\"req\":\"^0.9\"},{\"default_features\":false,\"name\":\"crypto_secretbox\",\"req\":\"^0.1.1\"},{\"default_features\":false,\"features\":[\"zeroize\"],\"name\":\"curve25519-dalek\",\"req\":\"^4\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rmp-serde\",\"req\":\"^1\"},{\"name\":\"salsa20\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"zeroize\",\"req\":\"^1\"}],\"features\":{\"alloc\":[\"aead/alloc\"],\"chacha20\":[\"dep:chacha20\",\"crypto_secretbox/chacha20\"],\"default\":[\"alloc\",\"getrandom\",\"salsa20\"],\"getrandom\":[\"aead/getrandom\",\"rand_core\"],\"heapless\":[\"aead/heapless\"],\"rand_core\":[\"aead/rand_core\"],\"salsa20\":[\"dep:salsa20\",\"crypto_secretbox/salsa20\"],\"seal\":[\"dep:blake2\",\"alloc\"],\"serde\":[\"dep:serdect\"],\"std\":[\"aead/std\"]}}", - "crypto_secretbox_0.1.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"aead\",\"req\":\"^0.5\"},{\"features\":[\"zeroize\"],\"name\":\"chacha20\",\"optional\":true,\"req\":\"^0.9\"},{\"default_features\":false,\"name\":\"cipher\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"zeroize\"],\"name\":\"generic-array\",\"req\":\"^0.14.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"name\":\"poly1305\",\"req\":\"^0.8\"},{\"features\":[\"zeroize\"],\"name\":\"salsa20\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"zeroize\",\"req\":\"^1\"}],\"features\":{\"alloc\":[\"aead/alloc\"],\"default\":[\"alloc\",\"getrandom\",\"salsa20\"],\"getrandom\":[\"aead/getrandom\",\"rand_core\"],\"heapless\":[\"aead/heapless\"],\"rand_core\":[\"aead/rand_core\"],\"std\":[\"aead/std\",\"alloc\"],\"stream\":[\"aead/stream\"]}}", "csv-core_0.1.13": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"arrayvec\",\"req\":\"^0.5\"},{\"default_features\":false,\"name\":\"memchr\",\"req\":\"^2\"}],\"features\":{\"default\":[],\"libc\":[\"memchr/libc\"]}}", "csv_1.4.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\",\"serde\"],\"kind\":\"dev\",\"name\":\"bstr\",\"req\":\"^1.7.0\"},{\"name\":\"csv-core\",\"req\":\"^0.1.11\"},{\"name\":\"itoa\",\"req\":\"^1\"},{\"name\":\"ryu\",\"req\":\"^1\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.221\"},{\"name\":\"serde_core\",\"req\":\"^1.0.221\"}],\"features\":{}}", "ctor-proc-macro_0.0.7": "{\"dependencies\":[],\"features\":{\"default\":[]}}", @@ -834,6 +835,7 @@ "display_container_0.9.0": "{\"dependencies\":[{\"name\":\"either\",\"req\":\"^1.8\"},{\"name\":\"indenter\",\"req\":\"^0.3.3\"}],\"features\":{}}", "displaydoc_0.2.5": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^0.6.1\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"},{\"name\":\"syn\",\"req\":\"^2.0\"},{\"kind\":\"dev\",\"name\":\"thiserror\",\"req\":\"^1.0.24\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "dns-lookup_3.0.1": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"name\":\"socket2\",\"req\":\"^0.6.0\"},{\"features\":[\"Win32_Networking_WinSock\",\"Win32_Foundation\"],\"name\":\"windows-sys\",\"req\":\"^0.60\",\"target\":\"cfg(windows)\"}],\"features\":{}}", + "document-features_0.2.12": "{\"dependencies\":[{\"name\":\"litrs\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[],\"self-test\":[]}}", "dotenvy_0.15.7": "{\"dependencies\":[{\"name\":\"clap\",\"optional\":true,\"req\":\"^3.2\"},{\"kind\":\"dev\",\"name\":\"once_cell\",\"req\":\"^1.16.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.3.0\"}],\"features\":{\"cli\":[\"clap\"]}}", "downcast-rs_1.2.1": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "dtor-proc-macro_0.0.6": "{\"dependencies\":[],\"features\":{\"default\":[]}}", @@ -846,9 +848,9 @@ "dylint_linting_5.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert_cmd\",\"req\":\"^2.0\"},{\"name\":\"cargo_metadata\",\"req\":\"^0.23\"},{\"features\":[\"config\"],\"name\":\"dylint_internal\",\"req\":\"=5.0.0\"},{\"name\":\"paste\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"rustc_version\",\"req\":\"^0.4\"},{\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.23\"},{\"name\":\"thiserror\",\"req\":\"^2.0\"},{\"name\":\"toml\",\"req\":\"^0.9\"},{\"kind\":\"build\",\"name\":\"toml\",\"req\":\"^0.9\"}],\"features\":{\"constituent\":[]}}", "dylint_testing_5.0.0": "{\"dependencies\":[{\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"cargo_metadata\",\"req\":\"^0.23\"},{\"name\":\"compiletest_rs\",\"req\":\"^0.11\"},{\"name\":\"dylint\",\"req\":\"=5.0.0\"},{\"name\":\"dylint_internal\",\"req\":\"=5.0.0\"},{\"name\":\"env_logger\",\"req\":\"^0.11\"},{\"name\":\"once_cell\",\"req\":\"^1.21\"},{\"name\":\"regex\",\"req\":\"^1.11\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"tempfile\",\"req\":\"^3.23\"}],\"features\":{\"default\":[],\"deny_warnings\":[]}}", "dyn-clone_1.0.20": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"rustversion\",\"req\":\"^1.0\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.66\"}],\"features\":{}}", - "ed25519-dalek_2.2.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"blake2\",\"req\":\"^0.10\"},{\"features\":[\"html_reports\"],\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"default_features\":false,\"features\":[\"digest\"],\"name\":\"curve25519-dalek\",\"req\":\"^4\"},{\"default_features\":false,\"features\":[\"digest\",\"rand_core\"],\"kind\":\"dev\",\"name\":\"curve25519-dalek\",\"req\":\"^4\"},{\"default_features\":false,\"name\":\"ed25519\",\"req\":\">=2.2, <2.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"merlin\",\"optional\":true,\"req\":\"^3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"rand_core\",\"optional\":true,\"req\":\"^0.6.4\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6.4\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha3\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"signature\",\"optional\":true,\"req\":\">=2.0, <2.3\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.3.0\"},{\"kind\":\"dev\",\"name\":\"toml\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"static_secrets\"],\"kind\":\"dev\",\"name\":\"x25519-dalek\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.5\"}],\"features\":{\"alloc\":[\"curve25519-dalek/alloc\",\"ed25519/alloc\",\"serde?/alloc\",\"zeroize/alloc\"],\"asm\":[\"sha2/asm\"],\"batch\":[\"alloc\",\"merlin\",\"rand_core\"],\"default\":[\"fast\",\"std\",\"zeroize\"],\"digest\":[\"signature/digest\"],\"fast\":[\"curve25519-dalek/precomputed-tables\"],\"hazmat\":[],\"legacy_compatibility\":[\"curve25519-dalek/legacy_compatibility\"],\"pem\":[\"alloc\",\"ed25519/pem\",\"pkcs8\"],\"pkcs8\":[\"ed25519/pkcs8\"],\"rand_core\":[\"dep:rand_core\"],\"serde\":[\"dep:serde\",\"ed25519/serde\"],\"std\":[\"alloc\",\"ed25519/std\",\"serde?/std\",\"sha2/std\"],\"zeroize\":[\"dep:zeroize\",\"curve25519-dalek/zeroize\"]}}", - "ed25519_2.2.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1\"},{\"features\":[\"rand_core\"],\"kind\":\"dev\",\"name\":\"ed25519-dalek\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"name\":\"pkcs8\",\"optional\":true,\"req\":\"^0.10\"},{\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"signature\"],\"kind\":\"dev\",\"name\":\"ring-compat\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"serde_bytes\",\"optional\":true,\"req\":\"^0.11\"},{\"default_features\":false,\"name\":\"signature\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"pkcs8?/alloc\"],\"default\":[\"std\"],\"pem\":[\"alloc\",\"pkcs8/pem\"],\"serde_bytes\":[\"serde\",\"dep:serde_bytes\"],\"std\":[\"pkcs8?/std\",\"signature/std\"]}}", + "ecdsa_0.16.9": "{\"dependencies\":[{\"name\":\"der\",\"optional\":true,\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"oid\"],\"name\":\"digest\",\"optional\":true,\"req\":\"^0.10.7\"},{\"default_features\":false,\"features\":[\"digest\",\"sec1\"],\"name\":\"elliptic-curve\",\"req\":\"^0.13.6\"},{\"default_features\":false,\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"elliptic-curve\",\"req\":\"^0.13\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"name\":\"rfc6979\",\"optional\":true,\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"oid\"],\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"signature\",\"req\":\"^2.0, <2.3\"},{\"default_features\":false,\"name\":\"spki\",\"optional\":true,\"req\":\"^0.7.2\"}],\"features\":{\"alloc\":[\"elliptic-curve/alloc\",\"signature/alloc\",\"spki/alloc\"],\"arithmetic\":[\"elliptic-curve/arithmetic\"],\"default\":[\"digest\"],\"dev\":[\"arithmetic\",\"digest\",\"elliptic-curve/dev\",\"hazmat\"],\"digest\":[\"dep:digest\",\"signature/digest\"],\"hazmat\":[],\"pem\":[\"elliptic-curve/pem\",\"pkcs8\"],\"pkcs8\":[\"digest\",\"elliptic-curve/pkcs8\",\"der\"],\"serde\":[\"elliptic-curve/serde\",\"serdect\"],\"signing\":[\"arithmetic\",\"digest\",\"hazmat\",\"rfc6979\"],\"std\":[\"alloc\",\"elliptic-curve/std\",\"signature/std\"],\"verifying\":[\"arithmetic\",\"digest\",\"hazmat\"]}}", "either_1.15.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\",\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.95\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[\"std\"],\"std\":[],\"use_std\":[\"std\"]}}", + "elliptic-curve_0.13.8": "{\"dependencies\":[{\"name\":\"base16ct\",\"req\":\"^0.2\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"base64ct\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"rand_core\",\"generic-array\",\"zeroize\"],\"name\":\"crypto-bigint\",\"req\":\"^0.5\"},{\"name\":\"digest\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"ff\",\"optional\":true,\"req\":\"^0.13\"},{\"default_features\":false,\"features\":[\"zeroize\"],\"name\":\"generic-array\",\"req\":\"^0.14.6\"},{\"default_features\":false,\"name\":\"group\",\"optional\":true,\"req\":\"^0.13\"},{\"name\":\"hex-literal\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"hkdf\",\"optional\":true,\"req\":\"^0.12.1\"},{\"features\":[\"alloc\"],\"name\":\"pem-rfc7468\",\"optional\":true,\"req\":\"^0.7\"},{\"default_features\":false,\"name\":\"pkcs8\",\"optional\":true,\"req\":\"^0.10.2\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6.4\"},{\"features\":[\"subtle\",\"zeroize\"],\"name\":\"sec1\",\"optional\":true,\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.47\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"kind\":\"dev\",\"name\":\"sha3\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"tap\",\"optional\":true,\"req\":\"^1.0.1\"},{\"default_features\":false,\"name\":\"zeroize\",\"req\":\"^1.7\"}],\"features\":{\"alloc\":[\"base16ct/alloc\",\"ff?/alloc\",\"group?/alloc\",\"pkcs8?/alloc\",\"sec1?/alloc\",\"zeroize/alloc\"],\"arithmetic\":[\"group\"],\"bits\":[\"arithmetic\",\"ff/bits\",\"dep:tap\"],\"default\":[\"arithmetic\"],\"dev\":[\"arithmetic\",\"dep:hex-literal\",\"pem\",\"pkcs8\"],\"ecdh\":[\"arithmetic\",\"digest\",\"dep:hkdf\"],\"group\":[\"dep:group\",\"ff\"],\"hash2curve\":[\"arithmetic\",\"digest\"],\"hazmat\":[],\"jwk\":[\"dep:base64ct\",\"dep:serde_json\",\"alloc\",\"serde\",\"zeroize/alloc\"],\"pem\":[\"dep:pem-rfc7468\",\"alloc\",\"arithmetic\",\"pkcs8\",\"sec1/pem\"],\"pkcs8\":[\"dep:pkcs8\",\"sec1\"],\"serde\":[\"dep:serdect\",\"alloc\",\"pkcs8\",\"sec1/serde\"],\"std\":[\"alloc\",\"rand_core/std\",\"pkcs8?/std\",\"sec1?/std\"],\"voprf\":[\"digest\"]}}", "ena_0.14.3": "{\"dependencies\":[{\"name\":\"dogged\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"log\",\"req\":\"^0.4\"}],\"features\":{\"bench\":[],\"persistent\":[\"dogged\"]}}", "encode_unicode_1.0.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ascii\",\"optional\":true,\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.0\",\"target\":\"cfg(unix)\"},{\"features\":[\"https-native\"],\"kind\":\"dev\",\"name\":\"minreq\",\"req\":\"^2.6\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "encoding_rs_0.8.35": "{\"dependencies\":[{\"name\":\"any_all_workaround\",\"optional\":true,\"req\":\"^0.1.0\"},{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.0\"},{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\"],\"fast-big5-hanzi-encode\":[],\"fast-gb-hanzi-encode\":[],\"fast-hangul-encode\":[],\"fast-hanja-encode\":[],\"fast-kanji-encode\":[],\"fast-legacy-encode\":[\"fast-hangul-encode\",\"fast-hanja-encode\",\"fast-kanji-encode\",\"fast-gb-hanzi-encode\",\"fast-big5-hanzi-encode\"],\"less-slow-big5-hanzi-encode\":[],\"less-slow-gb-hanzi-encode\":[],\"less-slow-kanji-encode\":[],\"simd-accel\":[\"any_all_workaround\"]}}", @@ -879,6 +881,7 @@ "fax_derive_0.2.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "fd-lock_4.0.4": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"features\":[\"fs\"],\"name\":\"rustix\",\"req\":\"^1.0.0\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3.0.8\"},{\"features\":[\"Win32_Foundation\",\"Win32_Storage_FileSystem\",\"Win32_System_IO\"],\"name\":\"windows-sys\",\"req\":\">=0.52.0, <0.60.0\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "fdeflate_0.3.7": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"miniz_oxide\",\"req\":\"^0.7.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"name\":\"simd-adler32\",\"req\":\"^0.3.4\"}],\"features\":{}}", + "ff_0.13.1": "{\"dependencies\":[{\"default_features\":false,\"name\":\"bitvec\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"blake2b_simd\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"byteorder\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"ff_derive\",\"optional\":true,\"req\":\"^0.13.1\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"features\":[\"i128\"],\"name\":\"subtle\",\"req\":\"^2.2.1\"}],\"features\":{\"alloc\":[],\"bits\":[\"bitvec\"],\"default\":[\"bits\",\"std\"],\"derive\":[\"byteorder\",\"ff_derive\"],\"derive_bits\":[\"bits\",\"ff_derive/bits\"],\"std\":[\"alloc\"]}}", "fiat-crypto_0.2.9": "{\"dependencies\":[],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "filedescriptor_0.8.3": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^1.0\"},{\"features\":[\"winuser\",\"handleapi\",\"fileapi\",\"namedpipeapi\",\"processthreadsapi\",\"winsock2\",\"processenv\"],\"name\":\"winapi\",\"req\":\"^0.3\",\"target\":\"cfg(windows)\"}],\"features\":{}}", "filetime_0.2.27": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"libc\",\"req\":\"^0.2.27\",\"target\":\"cfg(unix)\"},{\"name\":\"libredox\",\"req\":\"^0.1.0\",\"target\":\"cfg(target_os = \\\"redox\\\")\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{}}", @@ -1006,6 +1009,7 @@ "glob_0.3.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tempdir\",\"req\":\"^0.3\"}],\"features\":{}}", "globset_0.4.18": "{\"dependencies\":[{\"name\":\"aho-corasick\",\"req\":\"^1.1.1\"},{\"features\":[\"derive\"],\"name\":\"arbitrary\",\"optional\":true,\"req\":\"^1.3.2\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"bstr\",\"req\":\"^1.6.2\"},{\"kind\":\"dev\",\"name\":\"glob\",\"req\":\"^0.3.1\"},{\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.20\"},{\"default_features\":false,\"features\":[\"std\",\"perf\",\"syntax\",\"meta\",\"nfa\",\"hybrid\"],\"name\":\"regex-automata\",\"req\":\"^0.4.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"regex-syntax\",\"req\":\"^0.8.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.188\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.107\"}],\"features\":{\"arbitrary\":[\"dep:arbitrary\"],\"default\":[\"log\"],\"serde1\":[\"serde\"],\"simd-accel\":[]}}", "gobject-sys_0.21.5": "{\"dependencies\":[{\"name\":\"glib-sys\",\"req\":\"^0.21\"},{\"name\":\"libc\",\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"shell-words\",\"req\":\"^1.0.0\"},{\"kind\":\"build\",\"name\":\"system-deps\",\"req\":\"^7\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"}],\"features\":{\"v2_58\":[],\"v2_62\":[\"v2_58\"],\"v2_66\":[\"v2_62\"],\"v2_68\":[\"v2_66\"],\"v2_70\":[\"v2_68\"],\"v2_72\":[\"v2_70\"],\"v2_74\":[\"v2_72\"],\"v2_76\":[\"v2_74\"],\"v2_78\":[\"v2_74\"],\"v2_80\":[\"v2_78\"],\"v2_82\":[\"v2_80\"],\"v2_84\":[\"v2_82\"],\"v2_86\":[\"v2_84\"]}}", + "group_0.13.0": "{\"dependencies\":[{\"default_features\":false,\"name\":\"ff\",\"req\":\"^0.13\"},{\"name\":\"memuse\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"rand\",\"optional\":true,\"req\":\"^0.8\"},{\"default_features\":false,\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"name\":\"rand_xorshift\",\"optional\":true,\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2.2.1\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\"],\"tests\":[\"alloc\",\"rand\",\"rand_xorshift\"],\"wnaf-memuse\":[\"alloc\",\"memuse\"]}}", "gzip-header_1.0.0": "{\"dependencies\":[{\"name\":\"crc32fast\",\"req\":\"^1.2.1\"}],\"features\":{}}", "h2_0.4.13": "{\"dependencies\":[{\"name\":\"atomic-waker\",\"req\":\"^1.0.0\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"http\",\"req\":\"^1\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"name\":\"slab\",\"req\":\"^0.4.2\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^1\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", "h2_0.4.6": "{\"dependencies\":[{\"name\":\"atomic-waker\",\"req\":\"^1.0.0\"},{\"name\":\"bytes\",\"req\":\"^1\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\"},{\"name\":\"fnv\",\"req\":\"^1.0.5\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3\"},{\"default_features\":false,\"name\":\"futures-sink\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"hex\",\"req\":\"^0.4.3\"},{\"name\":\"http\",\"req\":\"^1\"},{\"features\":[\"std\"],\"name\":\"indexmap\",\"req\":\"^2\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quickcheck\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.4\"},{\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.0\"},{\"name\":\"slab\",\"req\":\"^0.4.2\"},{\"features\":[\"io-util\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"rt-multi-thread\",\"macros\",\"sync\",\"net\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-rustls\",\"req\":\"^0.26\"},{\"features\":[\"codec\",\"io\"],\"name\":\"tokio-util\",\"req\":\"^0.7.1\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"tracing\",\"req\":\"^0.1.35\"},{\"kind\":\"dev\",\"name\":\"walkdir\",\"req\":\"^2.3.2\"},{\"kind\":\"dev\",\"name\":\"webpki-roots\",\"req\":\"^0.26\"}],\"features\":{\"stream\":[],\"unstable\":[]}}", @@ -1139,6 +1143,7 @@ "linux-raw-sys_0.12.1": "{\"dependencies\":[{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.100\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"}],\"features\":{\"auxvec\":[],\"bootparam\":[],\"btrfs\":[],\"default\":[\"std\",\"general\",\"errno\"],\"elf\":[],\"elf_uapi\":[],\"errno\":[],\"general\":[],\"if_arp\":[],\"if_ether\":[],\"if_packet\":[],\"if_tun\":[],\"image\":[],\"io_uring\":[],\"ioctl\":[],\"landlock\":[],\"loop_device\":[],\"mempolicy\":[],\"net\":[],\"netlink\":[],\"no_std\":[],\"prctl\":[],\"ptrace\":[],\"rustc-dep-of-std\":[\"core\",\"no_std\"],\"std\":[],\"system\":[],\"vm_sockets\":[],\"xdp\":[]}}", "linux-raw-sys_0.4.15": "{\"dependencies\":[{\"name\":\"compiler_builtins\",\"optional\":true,\"req\":\"^0.1.49\"},{\"name\":\"core\",\"optional\":true,\"package\":\"rustc-std-workspace-core\",\"req\":\"^1.0.0\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.100\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1.0\"}],\"features\":{\"bootparam\":[],\"btrfs\":[],\"default\":[\"std\",\"general\",\"errno\"],\"elf\":[],\"elf_uapi\":[],\"errno\":[],\"general\":[],\"if_arp\":[],\"if_ether\":[],\"if_packet\":[],\"io_uring\":[],\"ioctl\":[],\"landlock\":[],\"loop_device\":[],\"mempolicy\":[],\"net\":[],\"netlink\":[],\"no_std\":[],\"prctl\":[],\"ptrace\":[],\"rustc-dep-of-std\":[\"core\",\"compiler_builtins\",\"no_std\"],\"std\":[],\"system\":[],\"xdp\":[]}}", "litemap_0.8.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"databake\",\"optional\":true,\"req\":\"^0.2.0\"},{\"default_features\":false,\"features\":[\"use-std\"],\"kind\":\"dev\",\"name\":\"postcard\",\"req\":\"^1.0.3\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.9\"},{\"features\":[\"validation\"],\"kind\":\"dev\",\"name\":\"rkyv\",\"req\":\"^0.7\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0.220\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"serde_core\",\"req\":\"^1.0.220\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.45\"},{\"default_features\":false,\"features\":[\"derive\"],\"name\":\"yoke\",\"optional\":true,\"req\":\"^0.8.0\"}],\"features\":{\"alloc\":[],\"databake\":[\"dep:databake\"],\"default\":[\"alloc\"],\"serde\":[\"dep:serde_core\",\"alloc\"],\"testing\":[\"alloc\"],\"yoke\":[\"dep:yoke\"]}}", + "litrs_1.0.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"optional\":true,\"req\":\"^1.0.63\"},{\"name\":\"unicode-xid\",\"optional\":true,\"req\":\"^0.2.4\"}],\"features\":{\"check_suffix\":[\"unicode-xid\"]}}", "local-waker_0.1.4": "{\"dependencies\":[],\"features\":{}}", "lock_api_0.4.14": "{\"dependencies\":[{\"name\":\"owning_ref\",\"optional\":true,\"req\":\"^0.4.1\"},{\"default_features\":false,\"name\":\"scopeguard\",\"req\":\"^1.1.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.126\"}],\"features\":{\"arc_lock\":[],\"atomic_usize\":[],\"default\":[\"atomic_usize\"],\"nightly\":[]}}", "log_0.4.29": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"dev\",\"name\":\"proc-macro2\",\"req\":\"^1.0.63\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_core\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"sval\",\"optional\":true,\"req\":\"^2.16\"},{\"kind\":\"dev\",\"name\":\"sval\",\"req\":\"^2.16\"},{\"kind\":\"dev\",\"name\":\"sval_derive\",\"req\":\"^2.16\"},{\"default_features\":false,\"name\":\"sval_ref\",\"optional\":true,\"req\":\"^2.16\"},{\"default_features\":false,\"features\":[\"inline-i128\"],\"name\":\"value-bag\",\"optional\":true,\"req\":\"^1.12\"},{\"features\":[\"test\"],\"kind\":\"dev\",\"name\":\"value-bag\",\"req\":\"^1.12\"}],\"features\":{\"kv\":[],\"kv_serde\":[\"kv_std\",\"value-bag/serde\",\"serde\"],\"kv_std\":[\"std\",\"kv\",\"value-bag/error\"],\"kv_sval\":[\"kv\",\"value-bag/sval\",\"sval\",\"sval_ref\"],\"kv_unstable\":[\"kv\",\"value-bag\"],\"kv_unstable_serde\":[\"kv_serde\",\"kv_unstable_std\"],\"kv_unstable_std\":[\"kv_std\",\"kv_unstable\"],\"kv_unstable_sval\":[\"kv_sval\",\"kv_unstable\"],\"max_level_debug\":[],\"max_level_error\":[],\"max_level_info\":[],\"max_level_off\":[],\"max_level_trace\":[],\"max_level_warn\":[],\"release_max_level_debug\":[],\"release_max_level_error\":[],\"release_max_level_info\":[],\"release_max_level_off\":[],\"release_max_level_trace\":[],\"release_max_level_warn\":[],\"serde\":[\"serde_core\"],\"std\":[]}}", @@ -1249,6 +1254,7 @@ "os_info_3.14.0": "{\"dependencies\":[{\"name\":\"android_system_properties\",\"req\":\"^0.1\",\"target\":\"cfg(target_os = \\\"android\\\")\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"features\":[\"feature\"],\"name\":\"nix\",\"req\":\"^0.30\",\"target\":\"cfg(any(target_os = \\\"aix\\\", target_os = \\\"dragonfly\\\", target_os = \\\"freebsd\\\", target_os = \\\"illumos\\\", target_os = \\\"linux\\\", target_os = \\\"macos\\\", target_os = \\\"netbsd\\\", target_os = \\\"openbsd\\\", target_os = \\\"cygwin\\\"))\"},{\"name\":\"objc2\",\"req\":\"^0.6\",\"target\":\"cfg(target_os = \\\"ios\\\")\"},{\"features\":[\"NSString\"],\"name\":\"objc2-foundation\",\"req\":\"^0.3\",\"target\":\"cfg(target_os = \\\"ios\\\")\"},{\"features\":[\"NSData\",\"NSError\",\"NSEnumerator\",\"NSString\"],\"name\":\"objc2-foundation\",\"req\":\"^0.3\",\"target\":\"cfg(target_os = \\\"macos\\\")\"},{\"name\":\"objc2-ui-kit\",\"req\":\"^0.3\",\"target\":\"cfg(target_os = \\\"ios\\\")\"},{\"kind\":\"dev\",\"name\":\"pretty_assertions\",\"req\":\"^1\"},{\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0.3\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_LibraryLoader\",\"Win32_System_Registry\",\"Win32_System_SystemInformation\",\"Win32_System_SystemServices\",\"Win32_System_Threading\",\"Win32_UI_WindowsAndMessaging\"],\"name\":\"windows-sys\",\"req\":\"^0.61\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"serde\"]}}", "os_pipe_1.2.3": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.62\",\"target\":\"cfg(not(windows))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Pipes\",\"Win32_Security\"],\"name\":\"windows-sys\",\"req\":\">=0.28, <=0.61\",\"target\":\"cfg(windows)\"}],\"features\":{\"io_safety\":[]}}", "owo-colors_4.3.0": "{\"dependencies\":[{\"name\":\"supports-color\",\"optional\":true,\"req\":\"^3.0.0\"},{\"name\":\"supports-color-2\",\"optional\":true,\"package\":\"supports-color\",\"req\":\"^2.0\"}],\"features\":{\"alloc\":[],\"supports-colors\":[\"dep:supports-color-2\",\"supports-color\"]}}", + "p256_0.13.2": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"blobby\",\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"der\"],\"name\":\"ecdsa-core\",\"optional\":true,\"package\":\"ecdsa\",\"req\":\"^0.16\"},{\"default_features\":false,\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"ecdsa-core\",\"package\":\"ecdsa\",\"req\":\"^0.16\"},{\"default_features\":false,\"features\":[\"hazmat\",\"sec1\"],\"name\":\"elliptic-curve\",\"req\":\"^0.13.1\"},{\"name\":\"hex-literal\",\"optional\":true,\"req\":\"^0.4\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"name\":\"primeorder\",\"optional\":true,\"req\":\"^0.13\"},{\"features\":[\"dev\"],\"kind\":\"dev\",\"name\":\"primeorder\",\"req\":\"^0.13\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1\"},{\"features\":[\"getrandom\"],\"kind\":\"dev\",\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10\"}],\"features\":{\"alloc\":[\"ecdsa-core?/alloc\",\"elliptic-curve/alloc\"],\"arithmetic\":[\"dep:primeorder\",\"elliptic-curve/arithmetic\"],\"bits\":[\"arithmetic\",\"elliptic-curve/bits\"],\"default\":[\"arithmetic\",\"ecdsa\",\"pem\",\"std\"],\"digest\":[\"ecdsa-core/digest\",\"ecdsa-core/hazmat\"],\"ecdh\":[\"arithmetic\",\"elliptic-curve/ecdh\"],\"ecdsa\":[\"arithmetic\",\"ecdsa-core/signing\",\"ecdsa-core/verifying\",\"sha256\"],\"expose-field\":[\"arithmetic\"],\"hash2curve\":[\"arithmetic\",\"elliptic-curve/hash2curve\"],\"jwk\":[\"elliptic-curve/jwk\"],\"pem\":[\"elliptic-curve/pem\",\"ecdsa-core/pem\",\"pkcs8\"],\"pkcs8\":[\"ecdsa-core?/pkcs8\",\"elliptic-curve/pkcs8\"],\"serde\":[\"ecdsa-core?/serde\",\"elliptic-curve/serde\",\"primeorder?/serde\",\"serdect\"],\"sha256\":[\"digest\",\"sha2\"],\"std\":[\"alloc\",\"ecdsa-core?/std\",\"elliptic-curve/std\"],\"test-vectors\":[\"dep:hex-literal\"],\"voprf\":[\"elliptic-curve/voprf\",\"sha2\"]}}", "parking_2.2.1": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"easy-parallel\",\"req\":\"^3.0.0\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\",\"target\":\"cfg(loom)\"}],\"features\":{}}", "parking_lot_0.12.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.3\"},{\"name\":\"lock_api\",\"req\":\"^0.4.14\"},{\"name\":\"parking_lot_core\",\"req\":\"^0.9.12\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.3\"}],\"features\":{\"arc_lock\":[\"lock_api/arc_lock\"],\"deadlock_detection\":[\"parking_lot_core/deadlock_detection\"],\"default\":[],\"hardware-lock-elision\":[],\"nightly\":[\"parking_lot_core/nightly\",\"lock_api/nightly\"],\"owning_ref\":[\"lock_api/owning_ref\"],\"send_guard\":[],\"serde\":[\"lock_api/serde\"]}}", "parking_lot_core_0.9.12": "{\"dependencies\":[{\"name\":\"backtrace\",\"optional\":true,\"req\":\"^0.3.60\"},{\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"libc\",\"req\":\"^0.2.95\",\"target\":\"cfg(unix)\"},{\"name\":\"petgraph\",\"optional\":true,\"req\":\"^0.6.0\"},{\"name\":\"redox_syscall\",\"req\":\"^0.5\",\"target\":\"cfg(target_os = \\\"redox\\\")\"},{\"name\":\"smallvec\",\"req\":\"^1.6.1\"},{\"name\":\"windows-link\",\"req\":\"^0.2.0\",\"target\":\"cfg(windows)\"}],\"features\":{\"deadlock_detection\":[\"petgraph\",\"backtrace\"],\"nightly\":[]}}", @@ -1298,6 +1304,7 @@ "predicates_3.1.3": "{\"dependencies\":[{\"name\":\"anstyle\",\"req\":\"^1.0.0\"},{\"name\":\"difflib\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"float-cmp\",\"optional\":true,\"req\":\"^0.10\"},{\"name\":\"normalize-line-endings\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"predicates-core\",\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"predicates-tree\",\"req\":\"^1.0\"},{\"name\":\"regex\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"color\":[],\"default\":[\"diff\",\"regex\",\"float-cmp\",\"normalize-line-endings\",\"color\"],\"diff\":[\"dep:difflib\"],\"unstable\":[]}}", "pretty_assertions_1.4.1": "{\"dependencies\":[{\"name\":\"diff\",\"req\":\"^0.1.12\"},{\"name\":\"yansi\",\"req\":\"^1.0.1\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[],\"unstable\":[]}}", "prettyplease_0.2.37": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"indoc\",\"req\":\"^2\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1.0.80\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"proc-macro2\",\"req\":\"^1.0.80\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"quote\",\"req\":\"^1.0.35\"},{\"default_features\":false,\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0.105\"},{\"default_features\":false,\"features\":[\"clone-impls\",\"extra-traits\",\"parsing\",\"printing\",\"visit-mut\"],\"kind\":\"dev\",\"name\":\"syn\",\"req\":\"^2.0.105\"}],\"features\":{\"verbatim\":[\"syn/parsing\"]}}", + "primeorder_0.13.6": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"arithmetic\",\"sec1\"],\"name\":\"elliptic-curve\",\"req\":\"^0.13.7\"},{\"default_features\":false,\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"}],\"features\":{\"alloc\":[\"elliptic-curve/alloc\"],\"dev\":[],\"serde\":[\"elliptic-curve/serde\",\"serdect\"],\"std\":[\"alloc\",\"elliptic-curve/std\"]}}", "proc-macro-crate_3.4.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"proc-macro2\",\"req\":\"^1.0.94\"},{\"kind\":\"dev\",\"name\":\"quote\",\"req\":\"^1.0.39\"},{\"kind\":\"dev\",\"name\":\"syn\",\"req\":\"^2.0.99\"},{\"default_features\":false,\"features\":[\"parse\"],\"name\":\"toml_edit\",\"req\":\"^0.23.2\"}],\"features\":{}}", "proc-macro-error-attr2_2.0.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"}],\"features\":{}}", "proc-macro-error2_2.0.1": "{\"dependencies\":[{\"name\":\"proc-macro-error-attr2\",\"req\":\"=2.0.0\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"syn\",\"optional\":true,\"req\":\"^2\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"syn\",\"req\":\"^2\"},{\"features\":[\"diff\"],\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0.99\"}],\"features\":{\"default\":[\"syn-error\"],\"nightly\":[],\"syn-error\":[\"dep:syn\"]}}", @@ -1321,6 +1328,7 @@ "protoc-gen-tonic_0.4.1": "{\"dependencies\":[{\"name\":\"heck\",\"req\":\"^0.5.0\"},{\"name\":\"prettyplease\",\"req\":\"^0.2.9\"},{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"prost\",\"req\":\"^0.13.1\"},{\"default_features\":false,\"name\":\"prost-build\",\"req\":\"^0.13.1\"},{\"default_features\":false,\"name\":\"prost-types\",\"req\":\"^0.13.1\"},{\"name\":\"protoc-gen-prost\",\"req\":\"^0.4.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"regex\",\"req\":\"^1.5.5\"},{\"features\":[\"parsing\",\"full\"],\"name\":\"syn\",\"req\":\"^2.0.22\"},{\"name\":\"tonic-build\",\"req\":\"^0.12.0\"}],\"features\":{}}", "psl-types_2.0.11": "{\"dependencies\":[],\"features\":{}}", "psl_2.1.184": "{\"dependencies\":[{\"name\":\"psl-types\",\"req\":\"^2.0.11\"},{\"kind\":\"dev\",\"name\":\"rspec\",\"req\":\"^1.0.0\"}],\"features\":{\"default\":[\"helpers\"],\"helpers\":[]}}", + "publicsuffix_2.3.0": "{\"dependencies\":[{\"features\":[\"inline-more\"],\"name\":\"hashbrown\",\"optional\":true,\"req\":\"^0.15.1\"},{\"name\":\"idna\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"psl-types\",\"req\":\"^2.0.11\"},{\"kind\":\"dev\",\"name\":\"rspec\",\"req\":\"^1.0.0\"},{\"default_features\":false,\"name\":\"unicase\",\"optional\":true,\"req\":\"^2.6.0\"}],\"features\":{\"anycase\":[\"unicase\"],\"default\":[\"punycode\"],\"punycode\":[\"idna\"],\"std\":[]}}", "pulldown-cmark-escape_0.10.1": "{\"dependencies\":[],\"features\":{\"simd\":[]}}", "pulldown-cmark_0.10.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bincode\",\"req\":\"^1.3.1\"},{\"name\":\"bitflags\",\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5\"},{\"name\":\"getopts\",\"optional\":true,\"req\":\"^0.2\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1.4\"},{\"name\":\"memchr\",\"req\":\"^2.5\"},{\"name\":\"pulldown-cmark-escape\",\"optional\":true,\"req\":\"^0.10.0\"},{\"kind\":\"dev\",\"name\":\"regex\",\"req\":\"^1.6\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0.61\"},{\"name\":\"unicase\",\"req\":\"^2.6\"}],\"features\":{\"default\":[\"getopts\",\"html\"],\"gen-tests\":[],\"html\":[\"pulldown-cmark-escape\"],\"simd\":[\"pulldown-cmark-escape?/simd\"]}}", "pxfm_0.1.27": "{\"dependencies\":[{\"name\":\"num-traits\",\"req\":\"^0.2.3\"}],\"features\":{}}", @@ -1379,6 +1387,7 @@ "reqwest_0.12.28": "{\"dependencies\":[{\"name\":\"base64\",\"req\":\"^0.22\"},{\"kind\":\"dev\",\"name\":\"brotli_crate\",\"package\":\"brotli\",\"req\":\"^8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"bytes\",\"req\":\"^1.2\"},{\"name\":\"cookie_crate\",\"optional\":true,\"package\":\"cookie\",\"req\":\"^0.18.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"cookie_store\",\"optional\":true,\"req\":\"^0.22.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"encoding_rs\",\"optional\":true,\"req\":\"^0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"env_logger\",\"req\":\"^0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"flate2\",\"req\":\"^1.0.13\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"futures-channel\",\"optional\":true,\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"futures-core\",\"req\":\"^0.3.28\"},{\"default_features\":false,\"name\":\"futures-util\",\"optional\":true,\"req\":\"^0.3.28\"},{\"default_features\":false,\"features\":[\"std\",\"alloc\"],\"kind\":\"dev\",\"name\":\"futures-util\",\"req\":\"^0.3.28\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h2\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3\",\"optional\":true,\"req\":\"^0.0.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"h3-quinn\",\"optional\":true,\"req\":\"^0.0.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"tokio\"],\"name\":\"hickory-resolver\",\"optional\":true,\"req\":\"^0.25\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http\",\"req\":\"^1.1\"},{\"name\":\"http-body\",\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"http-body-util\",\"req\":\"^0.1.2\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"client\"],\"name\":\"hyper\",\"req\":\"^1.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"http1\",\"http2\",\"client\",\"server\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1.1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"http1\",\"tls12\"],\"name\":\"hyper-rustls\",\"optional\":true,\"req\":\"^0.27.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"hyper-tls\",\"optional\":true,\"req\":\"^0.6\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"client\",\"client-legacy\",\"client-proxy\",\"tokio\"],\"name\":\"hyper-util\",\"req\":\"^0.1.12\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"http1\",\"http2\",\"client\",\"client-legacy\",\"server-auto\",\"server-graceful\",\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1.12\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"js-sys\",\"req\":\"^0.3.77\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0\"},{\"name\":\"log\",\"req\":\"^0.4.17\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"mime\",\"optional\":true,\"req\":\"^0.3.16\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0\"},{\"name\":\"native-tls-crate\",\"optional\":true,\"package\":\"native-tls\",\"req\":\"^0.2.10\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"num_cpus\",\"req\":\"^1.0\"},{\"name\":\"once_cell\",\"optional\":true,\"req\":\"^1.18\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"percent-encoding\",\"req\":\"^2.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2.11\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"rustls\",\"runtime-tokio\"],\"name\":\"quinn\",\"optional\":true,\"req\":\"^0.11.1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"std\",\"tls12\"],\"name\":\"rustls\",\"optional\":true,\"req\":\"^0.23.4\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"rustls-native-certs\",\"optional\":true,\"req\":\"^0.8.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"features\":[\"std\"],\"name\":\"rustls-pki-types\",\"optional\":true,\"req\":\"^1.9.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde\",\"req\":\"^1.0\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"serde_json\",\"req\":\"^1.0\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_urlencoded\",\"req\":\"^0.7.1\"},{\"features\":[\"futures\"],\"name\":\"sync_wrapper\",\"req\":\"^1.0\"},{\"default_features\":false,\"features\":[\"net\",\"time\"],\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tokio-native-tls\",\"optional\":true,\"req\":\"^0.3.0\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"tls12\"],\"name\":\"tokio-rustls\",\"optional\":true,\"req\":\"^0.26\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"io\"],\"name\":\"tokio-util\",\"optional\":true,\"req\":\"^0.7.9\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"retry\",\"timeout\",\"util\"],\"name\":\"tower\",\"req\":\"^0.5.2\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"default_features\":false,\"features\":[\"limit\"],\"kind\":\"dev\",\"name\":\"tower\",\"req\":\"^0.5.2\"},{\"default_features\":false,\"features\":[\"follow-redirect\"],\"name\":\"tower-http\",\"req\":\"^0.6.8\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"tower-service\",\"req\":\"^0.3\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"name\":\"url\",\"req\":\"^2.4\"},{\"name\":\"wasm-bindgen\",\"req\":\"^0.2.89\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"serde-serialize\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen\",\"req\":\"^0.2.89\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-bindgen-futures\",\"req\":\"^0.4.18\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"wasm-streams\",\"optional\":true,\"req\":\"^0.4\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"features\":[\"AbortController\",\"AbortSignal\",\"Headers\",\"Request\",\"RequestInit\",\"RequestMode\",\"Response\",\"Window\",\"FormData\",\"Blob\",\"BlobPropertyBag\",\"ServiceWorkerGlobalScope\",\"RequestCredentials\",\"File\",\"ReadableStream\",\"RequestCache\"],\"name\":\"web-sys\",\"req\":\"^0.3.28\",\"target\":\"cfg(target_arch = \\\"wasm32\\\")\"},{\"name\":\"webpki-roots\",\"optional\":true,\"req\":\"^1\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"},{\"kind\":\"dev\",\"name\":\"zstd_crate\",\"package\":\"zstd\",\"req\":\"^0.13\",\"target\":\"cfg(not(target_arch = \\\"wasm32\\\"))\"}],\"features\":{\"__rustls\":[\"dep:hyper-rustls\",\"dep:tokio-rustls\",\"dep:rustls\",\"__tls\"],\"__rustls-ring\":[\"hyper-rustls?/ring\",\"tokio-rustls?/ring\",\"rustls?/ring\",\"quinn?/ring\"],\"__tls\":[\"dep:rustls-pki-types\",\"tokio/io-util\"],\"blocking\":[\"dep:futures-channel\",\"futures-channel?/sink\",\"dep:futures-util\",\"futures-util?/io\",\"futures-util?/sink\",\"tokio/sync\"],\"brotli\":[\"tower-http/decompression-br\"],\"charset\":[\"dep:encoding_rs\",\"dep:mime\"],\"cookies\":[\"dep:cookie_crate\",\"dep:cookie_store\"],\"default\":[\"default-tls\",\"charset\",\"http2\",\"system-proxy\"],\"default-tls\":[\"dep:hyper-tls\",\"dep:native-tls-crate\",\"__tls\",\"dep:tokio-native-tls\"],\"deflate\":[\"tower-http/decompression-deflate\"],\"gzip\":[\"tower-http/decompression-gzip\"],\"hickory-dns\":[\"dep:hickory-resolver\",\"dep:once_cell\"],\"http2\":[\"h2\",\"hyper/http2\",\"hyper-util/http2\",\"hyper-rustls?/http2\"],\"http3\":[\"rustls-tls-manual-roots\",\"dep:h3\",\"dep:h3-quinn\",\"dep:quinn\",\"tokio/macros\"],\"json\":[\"dep:serde_json\"],\"macos-system-configuration\":[\"system-proxy\"],\"multipart\":[\"dep:mime_guess\",\"dep:futures-util\"],\"native-tls\":[\"default-tls\"],\"native-tls-alpn\":[\"native-tls\",\"native-tls-crate?/alpn\",\"hyper-tls?/alpn\"],\"native-tls-vendored\":[\"native-tls\",\"native-tls-crate?/vendored\"],\"rustls-tls\":[\"rustls-tls-webpki-roots\"],\"rustls-tls-manual-roots\":[\"rustls-tls-manual-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-manual-roots-no-provider\":[\"__rustls\"],\"rustls-tls-native-roots\":[\"rustls-tls-native-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-native-roots-no-provider\":[\"dep:rustls-native-certs\",\"hyper-rustls?/native-tokio\",\"__rustls\"],\"rustls-tls-no-provider\":[\"rustls-tls-manual-roots-no-provider\"],\"rustls-tls-webpki-roots\":[\"rustls-tls-webpki-roots-no-provider\",\"__rustls-ring\"],\"rustls-tls-webpki-roots-no-provider\":[\"dep:webpki-roots\",\"hyper-rustls?/webpki-tokio\",\"__rustls\"],\"socks\":[],\"stream\":[\"tokio/fs\",\"dep:futures-util\",\"dep:tokio-util\",\"dep:wasm-streams\"],\"system-proxy\":[\"hyper-util/client-proxy-system\"],\"trust-dns\":[],\"zstd\":[\"tower-http/decompression-zstd\"]}}", "resb_0.1.1": "{\"dependencies\":[{\"name\":\"indexmap\",\"optional\":true,\"req\":\"^2.0.0\"},{\"default_features\":false,\"name\":\"log\",\"optional\":true,\"req\":\"^0.4.17\"},{\"name\":\"nom\",\"optional\":true,\"req\":\"^7.0.0\"},{\"default_features\":false,\"name\":\"potential_utf\",\"req\":\"^0.1.3\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde_core\",\"req\":\"^1.0.220\"}],\"features\":{\"default\":[],\"logging\":[\"dep:log\"],\"serialize\":[\"std\"],\"std\":[],\"text\":[\"dep:indexmap\",\"dep:nom\",\"std\"]}}", "resolv-conf_0.7.6": "{\"dependencies\":[],\"features\":{\"system\":[]}}", + "rfc6979_0.4.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"reset\"],\"name\":\"hmac\",\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"}],\"features\":{}}", "ring_0.17.14": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.8\"},{\"default_features\":false,\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"getrandom\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(all(any(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), all(target_arch = \\\"arm\\\", target_endian = \\\"little\\\")), any(target_os = \\\"android\\\", target_os = \\\"linux\\\")))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_vendor = \\\"apple\\\", any(target_os = \\\"ios\\\", target_os = \\\"macos\\\", target_os = \\\"tvos\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\")))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_os = \\\"windows\\\"))\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\",\"dev_urandom_fallback\"],\"dev_urandom_fallback\":[],\"less-safe-getrandom-custom-or-rdrand\":[],\"less-safe-getrandom-espidf\":[],\"slow_tests\":[],\"std\":[\"alloc\"],\"test_logging\":[],\"unstable-testing-arm-no-hw\":[],\"unstable-testing-arm-no-neon\":[],\"wasm32_unknown_unknown_js\":[\"getrandom/js\"]}}", "rmcp-macros_0.15.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{}}", "rmcp_0.15.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"name\":\"axum\",\"optional\":true,\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"serde\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"reqwest\"],\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.12\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^0.15.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[\"dep:url\"],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls-tls\"],\"reqwest-native-tls\":[\"__reqwest\",\"reqwest?/native-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-tls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\",\"dep:pastey\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"dep:axum\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"__reqwest\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"]}}", @@ -1421,6 +1430,7 @@ "scratch_1.0.9": "{\"dependencies\":[],\"features\":{}}", "scrypt_0.11.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"password-hash\",\"optional\":true,\"req\":\"^0.5\"},{\"features\":[\"rand_core\"],\"kind\":\"dev\",\"name\":\"password-hash\",\"req\":\"^0.5\"},{\"name\":\"pbkdf2\",\"req\":\"^0.12\"},{\"default_features\":false,\"name\":\"salsa20\",\"req\":\"^0.10.2\"},{\"default_features\":false,\"name\":\"sha2\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"simple\",\"std\"],\"simple\":[\"password-hash\"],\"std\":[\"password-hash/std\"]}}", "sdd_3.0.10": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.6\"},{\"name\":\"loom\",\"optional\":true,\"req\":\"^0.7\"},{\"kind\":\"dev\",\"name\":\"static_assertions\",\"req\":\"^1.1\"}],\"features\":{}}", + "sec1_0.7.3": "{\"dependencies\":[{\"default_features\":false,\"name\":\"base16ct\",\"optional\":true,\"req\":\"^0.2\"},{\"features\":[\"oid\"],\"name\":\"der\",\"optional\":true,\"req\":\"^0.7\"},{\"default_features\":false,\"name\":\"generic-array\",\"optional\":true,\"req\":\"^0.14.7\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"name\":\"pkcs8\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serdect\",\"optional\":true,\"req\":\"^0.2\"},{\"default_features\":false,\"name\":\"subtle\",\"optional\":true,\"req\":\"^2\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1\"}],\"features\":{\"alloc\":[\"der?/alloc\",\"pkcs8?/alloc\",\"zeroize?/alloc\"],\"default\":[\"der\",\"point\"],\"der\":[\"dep:der\",\"zeroize\"],\"pem\":[\"alloc\",\"der/pem\",\"pkcs8/pem\"],\"point\":[\"dep:base16ct\",\"dep:generic-array\"],\"serde\":[\"dep:serdect\"],\"std\":[\"alloc\",\"der?/std\"],\"zeroize\":[\"dep:zeroize\",\"der?/zeroize\"]}}", "seccompiler_0.5.0": "{\"dependencies\":[{\"name\":\"libc\",\"req\":\"^0.2.153\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.27\"},{\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0.9\"}],\"features\":{\"json\":[\"serde\",\"serde_json\"]}}", "secrecy_0.10.3": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"alloc\"],\"name\":\"zeroize\",\"req\":\"^1.6\"}],\"features\":{}}", "secret-service_4.0.0": "{\"dependencies\":[{\"name\":\"aes\",\"optional\":true,\"req\":\"^0.8\"},{\"features\":[\"block-padding\",\"alloc\"],\"name\":\"cbc\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"futures-util\",\"req\":\"^0.3\"},{\"name\":\"generic-array\",\"req\":\"^0.14\"},{\"name\":\"hkdf\",\"optional\":true,\"req\":\"^0.12.0\"},{\"name\":\"num\",\"req\":\"^0.4.0\"},{\"name\":\"once_cell\",\"req\":\"^1\"},{\"name\":\"openssl\",\"optional\":true,\"req\":\"^0.10.40\"},{\"name\":\"rand\",\"req\":\"^0.8.1\"},{\"features\":[\"derive\"],\"name\":\"serde\",\"req\":\"^1.0.103\"},{\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10.0\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"test-with\",\"req\":\"^0.8\"},{\"features\":[\"rt\",\"macros\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"zbus\",\"req\":\"^4\"}],\"features\":{\"crypto-openssl\":[\"dep:openssl\"],\"crypto-rust\":[\"dep:aes\",\"dep:cbc\",\"dep:sha2\",\"dep:hkdf\"],\"rt-async-io-crypto-openssl\":[\"zbus/async-io\",\"crypto-openssl\"],\"rt-async-io-crypto-rust\":[\"zbus/async-io\",\"crypto-rust\"],\"rt-tokio-crypto-openssl\":[\"zbus/tokio\",\"crypto-openssl\"],\"rt-tokio-crypto-rust\":[\"zbus/tokio\",\"crypto-rust\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 18c26e6a14..de908f05fc 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -842,6 +842,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.21.7" @@ -940,15 +946,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -1466,6 +1463,7 @@ dependencies = [ "codex-config", "codex-core", "codex-core-plugins", + "codex-device-key", "codex-exec-server", "codex-features", "codex-feedback", @@ -1508,11 +1506,13 @@ dependencies = [ "sha2", "shlex", "tempfile", + "thiserror 2.0.18", "time", "tokio", "tokio-tungstenite", "tokio-util", "toml 0.9.11+spec-1.1.0", + "toml_edit 0.24.0+spec-1.1.0", "tracing", "tracing-opentelemetry", "tracing-subscriber", @@ -1937,7 +1937,6 @@ dependencies = [ "codex-api", "codex-app-server-protocol", "codex-apply-patch", - "codex-arg0", "codex-async-utils", "codex-code-mode", "codex-config", @@ -1987,12 +1986,10 @@ dependencies = [ "codex-windows-sandbox", "core-foundation 0.9.4", "core_test_support", - "crypto_box", "csv", "ctor 0.6.3", "dirs", "dunce", - "ed25519-dalek", "env-flags", "eventsource-stream", "futures", @@ -2018,7 +2015,6 @@ dependencies = [ "serde_json", "serial_test", "sha1", - "sha2", "shlex", "similar", "tempfile", @@ -2115,6 +2111,20 @@ dependencies = [ "serde_json", ] +[[package]] +name = "codex-device-key" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "p256", + "pretty_assertions", + "rand 0.9.3", + "serde", + "serde_json", + "thiserror 2.0.18", + "url", +] + [[package]] name = "codex-exec" version = "0.0.0" @@ -2394,8 +2404,6 @@ dependencies = [ "codex-terminal-detection", "codex-utils-template", "core_test_support", - "crypto_box", - "ed25519-dalek", "keyring", "once_cell", "os_info", @@ -2780,6 +2788,18 @@ dependencies = [ "uuid", ] +[[package]] +name = "codex-rollout-trace" +version = "0.0.0" +dependencies = [ + "anyhow", + "codex-protocol", + "pretty_assertions", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "codex-sandboxing" version = "0.0.0" @@ -3473,6 +3493,17 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -3482,6 +3513,24 @@ dependencies = [ "futures", ] +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -3711,6 +3760,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -3718,40 +3779,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] -[[package]] -name = "crypto_box" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16182b4f39a82ec8a6851155cc4c0cda3065bb1db33651726a29e1951de0f009" -dependencies = [ - "aead", - "blake2", - "crypto_secretbox", - "curve25519-dalek", - "salsa20", - "subtle", - "zeroize", -] - -[[package]] -name = "crypto_secretbox" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1" -dependencies = [ - "aead", - "cipher", - "generic-array", - "poly1305", - "salsa20", - "subtle", - "zeroize", -] - [[package]] name = "csv" version = "1.4.0" @@ -3808,7 +3838,6 @@ dependencies = [ "cfg-if", "cpufeatures", "curve25519-dalek-derive", - "digest", "fiat-crypto", "rustc_version", "subtle", @@ -4356,6 +4385,15 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "dotenvy" version = "0.15.7" @@ -4416,27 +4454,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] -name = "ed25519" -version = "2.2.3" +name = "ecdsa" +version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "pkcs8", + "der", + "digest", + "elliptic-curve", + "rfc6979", "signature", -] - -[[package]] -name = "ed25519-dalek" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" -dependencies = [ - "curve25519-dalek", - "ed25519", - "serde", - "sha2", - "subtle", - "zeroize", + "spki", ] [[package]] @@ -4448,6 +4476,26 @@ dependencies = [ "serde", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "ena" version = "0.14.3" @@ -4701,6 +4749,16 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -6095,6 +6153,17 @@ dependencies = [ "system-deps", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "gzip-header" version = "1.0.0" @@ -7413,6 +7482,12 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + [[package]] name = "livekit-protocol" version = "0.7.1" @@ -8571,6 +8646,18 @@ dependencies = [ "supports-color 3.0.2", ] +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + [[package]] name = "parking" version = "2.2.1" @@ -9000,6 +9087,15 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro-crate" version = "3.4.0" @@ -9197,6 +9293,16 @@ version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + [[package]] name = "pulldown-cmark" version = "0.10.3" @@ -9881,6 +9987,8 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "cookie", + "cookie_store", "encoding_rs", "futures-channel", "futures-core", @@ -9938,6 +10046,16 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -10397,6 +10515,20 @@ version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "seccompiler" version = "0.5.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 75e54abfba..d70af322a1 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -24,6 +24,7 @@ members = [ "collaboration-mode-templates", "connectors", "config", + "device-key", "shell-command", "shell-escalation", "skills", @@ -51,6 +52,7 @@ members = [ "protocol", "realtime-webrtc", "rollout", + "rollout-trace", "rmcp-client", "responses-api-proxy", "response-debug-context", @@ -132,6 +134,7 @@ codex-connectors = { path = "connectors" } codex-core = { path = "core" } codex-core-plugins = { path = "core-plugins" } codex-core-skills = { path = "core-skills" } +codex-device-key = { path = "device-key" } codex-exec = { path = "exec" } codex-exec-server = { path = "exec-server" } codex-execpolicy = { path = "execpolicy" } @@ -227,7 +230,6 @@ color-eyre = "0.6.3" constant_time_eq = "0.3.1" crossbeam-channel = "0.5.15" crossterm = "0.28.1" -crypto_box = { version = "0.9.1", features = ["seal"] } csv = "1.3.1" ctor = "0.6.3" deno_core_icudata = "0.77.0" @@ -237,7 +239,6 @@ dirs = "6" dns-lookup = "3.0.1" dotenvy = "0.15.7" dunce = "1.0.4" -ed25519-dalek = { version = "2.2.0", features = ["pkcs8"] } encoding_rs = "0.8.35" env-flags = "0.1.1" env_logger = "0.11.9" @@ -283,6 +284,7 @@ os_info = "3.12.0" owo-colors = "4.3.0" path-absolutize = "3.1.1" pathdiff = "0.2" +p256 = "0.13.2" portable-pty = "0.9.0" predicates = "3" pretty_assertions = "1.4.1" @@ -293,7 +295,7 @@ ratatui = "0.29.0" ratatui-macros = "0.6.0" regex = "1.12.3" regex-lite = "0.1.8" -reqwest = "0.12" +reqwest = { version = "0.12", features = ["cookies"] } rmcp = { version = "0.15.0", default-features = false } runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" } rustls = { version = "0.23", default-features = false, features = [ diff --git a/codex-rs/analytics/src/client.rs b/codex-rs/analytics/src/client.rs index 25ab40953f..1a4b5defe9 100644 --- a/codex-rs/analytics/src/client.rs +++ b/codex-rs/analytics/src/client.rs @@ -297,7 +297,7 @@ impl AnalyticsEventsClient { } async fn send_track_events( - auth_manager: &Arc, + auth_manager: &AuthManager, base_url: &str, events: Vec, ) { @@ -310,11 +310,9 @@ async fn send_track_events( if !auth.is_chatgpt_auth() { return; } - let Some(authorization_header_value) = auth_manager - .chatgpt_authorization_header_for_auth(&auth) - .await - else { - return; + let access_token = match auth.get_token() { + Ok(token) => token, + Err(_) => return, }; let Some(account_id) = auth.get_account_id() else { return; @@ -324,17 +322,15 @@ async fn send_track_events( let url = format!("{base_url}/codex/analytics-events/events"); let payload = TrackEventsRequest { events }; - let mut request = create_client() + let response = create_client() .post(&url) .timeout(ANALYTICS_EVENTS_TIMEOUT) - .header("authorization", authorization_header_value) + .bearer_auth(&access_token) .header("chatgpt-account-id", &account_id) .header("Content-Type", "application/json") - .json(&payload); - if auth.is_fedramp_account() { - request = request.header("X-OpenAI-Fedramp", "true"); - } - let response = request.send().await; + .json(&payload) + .send() + .await; match response { Ok(response) if response.status().is_success() => {} diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 43871d74a0..352cf02113 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -521,6 +521,200 @@ } ] }, + "DeviceKeyCreateParams": { + "description": "Create a controller-local device key with a random key id.", + "properties": { + "accountUserId": { + "type": "string" + }, + "clientId": { + "type": "string" + }, + "protectionPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/DeviceKeyProtectionPolicy" + }, + { + "type": "null" + } + ], + "description": "Defaults to `hardware_only` when omitted." + } + }, + "required": [ + "accountUserId", + "clientId" + ], + "type": "object" + }, + "DeviceKeyProtectionPolicy": { + "description": "Protection policy for creating or loading a controller-local device key.", + "enum": [ + "hardware_only", + "allow_os_protected_nonextractable" + ], + "type": "string" + }, + "DeviceKeyPublicParams": { + "description": "Fetch a controller-local device key public key by id.", + "properties": { + "keyId": { + "type": "string" + } + }, + "required": [ + "keyId" + ], + "type": "object" + }, + "DeviceKeySignParams": { + "description": "Sign an accepted structured payload with a controller-local device key.", + "properties": { + "keyId": { + "type": "string" + }, + "payload": { + "$ref": "#/definitions/DeviceKeySignPayload" + } + }, + "required": [ + "keyId", + "payload" + ], + "type": "object" + }, + "DeviceKeySignPayload": { + "description": "Structured payloads accepted by `device/key/sign`.", + "oneOf": [ + { + "description": "Payload bound to one remote-control controller websocket `/client` connection challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/RemoteControlClientConnectionAudience" + }, + "clientId": { + "type": "string" + }, + "nonce": { + "type": "string" + }, + "scopes": { + "description": "Must contain exactly `remote_control_controller_websocket`.", + "items": { + "type": "string" + }, + "type": "array" + }, + "sessionId": { + "description": "Backend-issued websocket session id that this proof authorizes.", + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "Websocket route path that this proof authorizes.", + "type": "string" + }, + "tokenExpiresAt": { + "description": "Remote-control token expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "tokenSha256Base64url": { + "description": "SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientConnection" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "clientId", + "nonce", + "scopes", + "sessionId", + "targetOrigin", + "targetPath", + "tokenExpiresAt", + "tokenSha256Base64url", + "type" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayload", + "type": "object" + }, + { + "description": "Payload bound to a remote-control client `/client/enroll` ownership challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/RemoteControlClientEnrollmentAudience" + }, + "challengeExpiresAt": { + "description": "Enrollment challenge expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "challengeId": { + "description": "Backend-issued enrollment challenge id that this proof authorizes.", + "type": "string" + }, + "clientId": { + "type": "string" + }, + "deviceIdentitySha256Base64url": { + "description": "SHA-256 of the requested device identity operation, encoded as unpadded base64url.", + "type": "string" + }, + "nonce": { + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "HTTP route path that this proof authorizes.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientEnrollment" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "challengeExpiresAt", + "challengeId", + "clientId", + "deviceIdentitySha256Base64url", + "nonce", + "targetOrigin", + "targetPath", + "type" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayload", + "type": "object" + } + ] + }, "DynamicToolSpec": { "properties": { "deferLoading": { @@ -1747,6 +1941,20 @@ } ] }, + "RemoteControlClientConnectionAudience": { + "description": "Audience for a remote-control client connection device-key proof.", + "enum": [ + "remote_control_client_websocket" + ], + "type": "string" + }, + "RemoteControlClientEnrollmentAudience": { + "description": "Audience for a remote-control client enrollment device-key proof.", + "enum": [ + "remote_control_client_enrollment" + ], + "type": "string" + }, "RequestId": { "anyOf": [ { @@ -4360,6 +4568,78 @@ "title": "App/listRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "device/key/create" + ], + "title": "Device/key/createRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeviceKeyCreateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/createRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "device/key/public" + ], + "title": "Device/key/publicRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeviceKeyPublicParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/publicRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "device/key/sign" + ], + "title": "Device/key/signRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeviceKeySignParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/signRequest", + "type": "object" + }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json b/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json index 0aa8b9c571..991733da66 100644 --- a/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json +++ b/codex-rs/app-server-protocol/schema/json/DynamicToolCallParams.json @@ -30,4 +30,4 @@ ], "title": "DynamicToolCallParams", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json index e389983bfa..c2e26c5532 100644 --- a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json @@ -295,6 +295,9 @@ } }, "properties": { + "cwd": { + "$ref": "#/definitions/AbsolutePathBuf" + }, "itemId": { "type": "string" }, @@ -315,6 +318,7 @@ } }, "required": [ + "cwd", "itemId", "permissions", "threadId", diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index 6bd386b6a1..016dbe3415 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -1584,6 +1584,9 @@ }, "PermissionsRequestApprovalParams": { "properties": { + "cwd": { + "$ref": "#/definitions/AbsolutePathBuf" + }, "itemId": { "type": "string" }, @@ -1604,6 +1607,7 @@ } }, "required": [ + "cwd", "itemId", "permissions", "threadId", 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 2cb5fb84df..d1518ce28f 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 @@ -737,6 +737,78 @@ "title": "App/listRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "device/key/create" + ], + "title": "Device/key/createRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/DeviceKeyCreateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/createRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "device/key/public" + ], + "title": "Device/key/publicRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/DeviceKeyPublicParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/publicRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "device/key/sign" + ], + "title": "Device/key/signRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/DeviceKeySignParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/signRequest", + "type": "object" + }, { "properties": { "id": { @@ -3360,6 +3432,9 @@ "PermissionsRequestApprovalParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "cwd": { + "$ref": "#/definitions/v2/AbsolutePathBuf" + }, "itemId": { "type": "string" }, @@ -3380,6 +3455,7 @@ } }, "required": [ + "cwd", "itemId", "permissions", "threadId", @@ -7324,6 +7400,300 @@ "title": "DeprecationNoticeNotification", "type": "object" }, + "DeviceKeyAlgorithm": { + "description": "Device-key algorithm reported at enrollment and signing boundaries.", + "enum": [ + "ecdsa_p256_sha256" + ], + "type": "string" + }, + "DeviceKeyCreateParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Create a controller-local device key with a random key id.", + "properties": { + "accountUserId": { + "type": "string" + }, + "clientId": { + "type": "string" + }, + "protectionPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/v2/DeviceKeyProtectionPolicy" + }, + { + "type": "null" + } + ], + "description": "Defaults to `hardware_only` when omitted." + } + }, + "required": [ + "accountUserId", + "clientId" + ], + "title": "DeviceKeyCreateParams", + "type": "object" + }, + "DeviceKeyCreateResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Device-key metadata and public key returned by create/public APIs.", + "properties": { + "algorithm": { + "$ref": "#/definitions/v2/DeviceKeyAlgorithm" + }, + "keyId": { + "type": "string" + }, + "protectionClass": { + "$ref": "#/definitions/v2/DeviceKeyProtectionClass" + }, + "publicKeySpkiDerBase64": { + "description": "SubjectPublicKeyInfo DER encoded as base64.", + "type": "string" + } + }, + "required": [ + "algorithm", + "keyId", + "protectionClass", + "publicKeySpkiDerBase64" + ], + "title": "DeviceKeyCreateResponse", + "type": "object" + }, + "DeviceKeyProtectionClass": { + "description": "Platform protection class for a controller-local device key.", + "enum": [ + "hardware_secure_enclave", + "hardware_tpm", + "os_protected_nonextractable" + ], + "type": "string" + }, + "DeviceKeyProtectionPolicy": { + "description": "Protection policy for creating or loading a controller-local device key.", + "enum": [ + "hardware_only", + "allow_os_protected_nonextractable" + ], + "type": "string" + }, + "DeviceKeyPublicParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Fetch a controller-local device key public key by id.", + "properties": { + "keyId": { + "type": "string" + } + }, + "required": [ + "keyId" + ], + "title": "DeviceKeyPublicParams", + "type": "object" + }, + "DeviceKeyPublicResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Device-key public metadata returned by `device/key/public`.", + "properties": { + "algorithm": { + "$ref": "#/definitions/v2/DeviceKeyAlgorithm" + }, + "keyId": { + "type": "string" + }, + "protectionClass": { + "$ref": "#/definitions/v2/DeviceKeyProtectionClass" + }, + "publicKeySpkiDerBase64": { + "description": "SubjectPublicKeyInfo DER encoded as base64.", + "type": "string" + } + }, + "required": [ + "algorithm", + "keyId", + "protectionClass", + "publicKeySpkiDerBase64" + ], + "title": "DeviceKeyPublicResponse", + "type": "object" + }, + "DeviceKeySignParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Sign an accepted structured payload with a controller-local device key.", + "properties": { + "keyId": { + "type": "string" + }, + "payload": { + "$ref": "#/definitions/v2/DeviceKeySignPayload" + } + }, + "required": [ + "keyId", + "payload" + ], + "title": "DeviceKeySignParams", + "type": "object" + }, + "DeviceKeySignPayload": { + "description": "Structured payloads accepted by `device/key/sign`.", + "oneOf": [ + { + "description": "Payload bound to one remote-control controller websocket `/client` connection challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/v2/RemoteControlClientConnectionAudience" + }, + "clientId": { + "type": "string" + }, + "nonce": { + "type": "string" + }, + "scopes": { + "description": "Must contain exactly `remote_control_controller_websocket`.", + "items": { + "type": "string" + }, + "type": "array" + }, + "sessionId": { + "description": "Backend-issued websocket session id that this proof authorizes.", + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "Websocket route path that this proof authorizes.", + "type": "string" + }, + "tokenExpiresAt": { + "description": "Remote-control token expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "tokenSha256Base64url": { + "description": "SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientConnection" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "clientId", + "nonce", + "scopes", + "sessionId", + "targetOrigin", + "targetPath", + "tokenExpiresAt", + "tokenSha256Base64url", + "type" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayload", + "type": "object" + }, + { + "description": "Payload bound to a remote-control client `/client/enroll` ownership challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/v2/RemoteControlClientEnrollmentAudience" + }, + "challengeExpiresAt": { + "description": "Enrollment challenge expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "challengeId": { + "description": "Backend-issued enrollment challenge id that this proof authorizes.", + "type": "string" + }, + "clientId": { + "type": "string" + }, + "deviceIdentitySha256Base64url": { + "description": "SHA-256 of the requested device identity operation, encoded as unpadded base64url.", + "type": "string" + }, + "nonce": { + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "HTTP route path that this proof authorizes.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientEnrollment" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "challengeExpiresAt", + "challengeId", + "clientId", + "deviceIdentitySha256Base64url", + "nonce", + "targetOrigin", + "targetPath", + "type" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayload", + "type": "object" + } + ] + }, + "DeviceKeySignResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "ASN.1 DER signature returned by `device/key/sign`.", + "properties": { + "algorithm": { + "$ref": "#/definitions/v2/DeviceKeyAlgorithm" + }, + "signatureDerBase64": { + "description": "ECDSA signature DER encoded as base64.", + "type": "string" + }, + "signedPayloadBase64": { + "description": "Exact bytes signed by the device key, encoded as base64. Verifiers must verify this byte string directly and must not reserialize `payload`.", + "type": "string" + } + }, + "required": [ + "algorithm", + "signatureDerBase64", + "signedPayloadBase64" + ], + "title": "DeviceKeySignResponse", + "type": "object" + }, "DynamicToolCallOutputContentItem": { "oneOf": [ { @@ -11642,6 +12012,20 @@ "title": "ReasoningTextDeltaNotification", "type": "object" }, + "RemoteControlClientConnectionAudience": { + "description": "Audience for a remote-control client connection device-key proof.", + "enum": [ + "remote_control_client_websocket" + ], + "type": "string" + }, + "RemoteControlClientEnrollmentAudience": { + "description": "Audience for a remote-control client enrollment device-key proof.", + "enum": [ + "remote_control_client_enrollment" + ], + "type": "string" + }, "RequestId": { "anyOf": [ { @@ -14099,8 +14483,8 @@ }, "namespace": { "type": [ - "null", - "string" + "string", + "null" ] }, "status": { @@ -16612,4 +16996,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 4ff918e642..82c990533a 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 @@ -1418,6 +1418,78 @@ "title": "App/listRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "device/key/create" + ], + "title": "Device/key/createRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeviceKeyCreateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/createRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "device/key/public" + ], + "title": "Device/key/publicRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeviceKeyPublicParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/publicRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "device/key/sign" + ], + "title": "Device/key/signRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/DeviceKeySignParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Device/key/signRequest", + "type": "object" + }, { "properties": { "id": { @@ -3935,6 +4007,300 @@ "title": "DeprecationNoticeNotification", "type": "object" }, + "DeviceKeyAlgorithm": { + "description": "Device-key algorithm reported at enrollment and signing boundaries.", + "enum": [ + "ecdsa_p256_sha256" + ], + "type": "string" + }, + "DeviceKeyCreateParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Create a controller-local device key with a random key id.", + "properties": { + "accountUserId": { + "type": "string" + }, + "clientId": { + "type": "string" + }, + "protectionPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/DeviceKeyProtectionPolicy" + }, + { + "type": "null" + } + ], + "description": "Defaults to `hardware_only` when omitted." + } + }, + "required": [ + "accountUserId", + "clientId" + ], + "title": "DeviceKeyCreateParams", + "type": "object" + }, + "DeviceKeyCreateResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Device-key metadata and public key returned by create/public APIs.", + "properties": { + "algorithm": { + "$ref": "#/definitions/DeviceKeyAlgorithm" + }, + "keyId": { + "type": "string" + }, + "protectionClass": { + "$ref": "#/definitions/DeviceKeyProtectionClass" + }, + "publicKeySpkiDerBase64": { + "description": "SubjectPublicKeyInfo DER encoded as base64.", + "type": "string" + } + }, + "required": [ + "algorithm", + "keyId", + "protectionClass", + "publicKeySpkiDerBase64" + ], + "title": "DeviceKeyCreateResponse", + "type": "object" + }, + "DeviceKeyProtectionClass": { + "description": "Platform protection class for a controller-local device key.", + "enum": [ + "hardware_secure_enclave", + "hardware_tpm", + "os_protected_nonextractable" + ], + "type": "string" + }, + "DeviceKeyProtectionPolicy": { + "description": "Protection policy for creating or loading a controller-local device key.", + "enum": [ + "hardware_only", + "allow_os_protected_nonextractable" + ], + "type": "string" + }, + "DeviceKeyPublicParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Fetch a controller-local device key public key by id.", + "properties": { + "keyId": { + "type": "string" + } + }, + "required": [ + "keyId" + ], + "title": "DeviceKeyPublicParams", + "type": "object" + }, + "DeviceKeyPublicResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Device-key public metadata returned by `device/key/public`.", + "properties": { + "algorithm": { + "$ref": "#/definitions/DeviceKeyAlgorithm" + }, + "keyId": { + "type": "string" + }, + "protectionClass": { + "$ref": "#/definitions/DeviceKeyProtectionClass" + }, + "publicKeySpkiDerBase64": { + "description": "SubjectPublicKeyInfo DER encoded as base64.", + "type": "string" + } + }, + "required": [ + "algorithm", + "keyId", + "protectionClass", + "publicKeySpkiDerBase64" + ], + "title": "DeviceKeyPublicResponse", + "type": "object" + }, + "DeviceKeySignParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Sign an accepted structured payload with a controller-local device key.", + "properties": { + "keyId": { + "type": "string" + }, + "payload": { + "$ref": "#/definitions/DeviceKeySignPayload" + } + }, + "required": [ + "keyId", + "payload" + ], + "title": "DeviceKeySignParams", + "type": "object" + }, + "DeviceKeySignPayload": { + "description": "Structured payloads accepted by `device/key/sign`.", + "oneOf": [ + { + "description": "Payload bound to one remote-control controller websocket `/client` connection challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/RemoteControlClientConnectionAudience" + }, + "clientId": { + "type": "string" + }, + "nonce": { + "type": "string" + }, + "scopes": { + "description": "Must contain exactly `remote_control_controller_websocket`.", + "items": { + "type": "string" + }, + "type": "array" + }, + "sessionId": { + "description": "Backend-issued websocket session id that this proof authorizes.", + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "Websocket route path that this proof authorizes.", + "type": "string" + }, + "tokenExpiresAt": { + "description": "Remote-control token expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "tokenSha256Base64url": { + "description": "SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientConnection" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "clientId", + "nonce", + "scopes", + "sessionId", + "targetOrigin", + "targetPath", + "tokenExpiresAt", + "tokenSha256Base64url", + "type" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayload", + "type": "object" + }, + { + "description": "Payload bound to a remote-control client `/client/enroll` ownership challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/RemoteControlClientEnrollmentAudience" + }, + "challengeExpiresAt": { + "description": "Enrollment challenge expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "challengeId": { + "description": "Backend-issued enrollment challenge id that this proof authorizes.", + "type": "string" + }, + "clientId": { + "type": "string" + }, + "deviceIdentitySha256Base64url": { + "description": "SHA-256 of the requested device identity operation, encoded as unpadded base64url.", + "type": "string" + }, + "nonce": { + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "HTTP route path that this proof authorizes.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientEnrollment" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "challengeExpiresAt", + "challengeId", + "clientId", + "deviceIdentitySha256Base64url", + "nonce", + "targetOrigin", + "targetPath", + "type" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayload", + "type": "object" + } + ] + }, + "DeviceKeySignResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "ASN.1 DER signature returned by `device/key/sign`.", + "properties": { + "algorithm": { + "$ref": "#/definitions/DeviceKeyAlgorithm" + }, + "signatureDerBase64": { + "description": "ECDSA signature DER encoded as base64.", + "type": "string" + }, + "signedPayloadBase64": { + "description": "Exact bytes signed by the device key, encoded as base64. Verifiers must verify this byte string directly and must not reserialize `payload`.", + "type": "string" + } + }, + "required": [ + "algorithm", + "signatureDerBase64", + "signedPayloadBase64" + ], + "title": "DeviceKeySignResponse", + "type": "object" + }, "DynamicToolCallOutputContentItem": { "oneOf": [ { @@ -8408,6 +8774,20 @@ "title": "ReasoningTextDeltaNotification", "type": "object" }, + "RemoteControlClientConnectionAudience": { + "description": "Audience for a remote-control client connection device-key proof.", + "enum": [ + "remote_control_client_websocket" + ], + "type": "string" + }, + "RemoteControlClientEnrollmentAudience": { + "description": "Audience for a remote-control client enrollment device-key proof.", + "enum": [ + "remote_control_client_enrollment" + ], + "type": "string" + }, "RequestId": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyCreateParams.json b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyCreateParams.json new file mode 100644 index 0000000000..fe2c0f0895 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyCreateParams.json @@ -0,0 +1,39 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "DeviceKeyProtectionPolicy": { + "description": "Protection policy for creating or loading a controller-local device key.", + "enum": [ + "hardware_only", + "allow_os_protected_nonextractable" + ], + "type": "string" + } + }, + "description": "Create a controller-local device key with a random key id.", + "properties": { + "accountUserId": { + "type": "string" + }, + "clientId": { + "type": "string" + }, + "protectionPolicy": { + "anyOf": [ + { + "$ref": "#/definitions/DeviceKeyProtectionPolicy" + }, + { + "type": "null" + } + ], + "description": "Defaults to `hardware_only` when omitted." + } + }, + "required": [ + "accountUserId", + "clientId" + ], + "title": "DeviceKeyCreateParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyCreateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyCreateResponse.json new file mode 100644 index 0000000000..12072588a9 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyCreateResponse.json @@ -0,0 +1,45 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "DeviceKeyAlgorithm": { + "description": "Device-key algorithm reported at enrollment and signing boundaries.", + "enum": [ + "ecdsa_p256_sha256" + ], + "type": "string" + }, + "DeviceKeyProtectionClass": { + "description": "Platform protection class for a controller-local device key.", + "enum": [ + "hardware_secure_enclave", + "hardware_tpm", + "os_protected_nonextractable" + ], + "type": "string" + } + }, + "description": "Device-key metadata and public key returned by create/public APIs.", + "properties": { + "algorithm": { + "$ref": "#/definitions/DeviceKeyAlgorithm" + }, + "keyId": { + "type": "string" + }, + "protectionClass": { + "$ref": "#/definitions/DeviceKeyProtectionClass" + }, + "publicKeySpkiDerBase64": { + "description": "SubjectPublicKeyInfo DER encoded as base64.", + "type": "string" + } + }, + "required": [ + "algorithm", + "keyId", + "protectionClass", + "publicKeySpkiDerBase64" + ], + "title": "DeviceKeyCreateResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyPublicParams.json b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyPublicParams.json new file mode 100644 index 0000000000..37cc5fbe2c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyPublicParams.json @@ -0,0 +1,14 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Fetch a controller-local device key public key by id.", + "properties": { + "keyId": { + "type": "string" + } + }, + "required": [ + "keyId" + ], + "title": "DeviceKeyPublicParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyPublicResponse.json b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyPublicResponse.json new file mode 100644 index 0000000000..39f98b7623 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeyPublicResponse.json @@ -0,0 +1,45 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "DeviceKeyAlgorithm": { + "description": "Device-key algorithm reported at enrollment and signing boundaries.", + "enum": [ + "ecdsa_p256_sha256" + ], + "type": "string" + }, + "DeviceKeyProtectionClass": { + "description": "Platform protection class for a controller-local device key.", + "enum": [ + "hardware_secure_enclave", + "hardware_tpm", + "os_protected_nonextractable" + ], + "type": "string" + } + }, + "description": "Device-key public metadata returned by `device/key/public`.", + "properties": { + "algorithm": { + "$ref": "#/definitions/DeviceKeyAlgorithm" + }, + "keyId": { + "type": "string" + }, + "protectionClass": { + "$ref": "#/definitions/DeviceKeyProtectionClass" + }, + "publicKeySpkiDerBase64": { + "description": "SubjectPublicKeyInfo DER encoded as base64.", + "type": "string" + } + }, + "required": [ + "algorithm", + "keyId", + "protectionClass", + "publicKeySpkiDerBase64" + ], + "title": "DeviceKeyPublicResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/DeviceKeySignParams.json b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeySignParams.json new file mode 100644 index 0000000000..054765b297 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeySignParams.json @@ -0,0 +1,165 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "DeviceKeySignPayload": { + "description": "Structured payloads accepted by `device/key/sign`.", + "oneOf": [ + { + "description": "Payload bound to one remote-control controller websocket `/client` connection challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/RemoteControlClientConnectionAudience" + }, + "clientId": { + "type": "string" + }, + "nonce": { + "type": "string" + }, + "scopes": { + "description": "Must contain exactly `remote_control_controller_websocket`.", + "items": { + "type": "string" + }, + "type": "array" + }, + "sessionId": { + "description": "Backend-issued websocket session id that this proof authorizes.", + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "Websocket route path that this proof authorizes.", + "type": "string" + }, + "tokenExpiresAt": { + "description": "Remote-control token expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "tokenSha256Base64url": { + "description": "SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientConnection" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "clientId", + "nonce", + "scopes", + "sessionId", + "targetOrigin", + "targetPath", + "tokenExpiresAt", + "tokenSha256Base64url", + "type" + ], + "title": "RemoteControlClientConnectionDeviceKeySignPayload", + "type": "object" + }, + { + "description": "Payload bound to a remote-control client `/client/enroll` ownership challenge.", + "properties": { + "accountUserId": { + "type": "string" + }, + "audience": { + "$ref": "#/definitions/RemoteControlClientEnrollmentAudience" + }, + "challengeExpiresAt": { + "description": "Enrollment challenge expiration as Unix seconds.", + "format": "int64", + "type": "integer" + }, + "challengeId": { + "description": "Backend-issued enrollment challenge id that this proof authorizes.", + "type": "string" + }, + "clientId": { + "type": "string" + }, + "deviceIdentitySha256Base64url": { + "description": "SHA-256 of the requested device identity operation, encoded as unpadded base64url.", + "type": "string" + }, + "nonce": { + "type": "string" + }, + "targetOrigin": { + "description": "Origin of the backend endpoint that issued the challenge and will verify this proof.", + "type": "string" + }, + "targetPath": { + "description": "HTTP route path that this proof authorizes.", + "type": "string" + }, + "type": { + "enum": [ + "remoteControlClientEnrollment" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayloadType", + "type": "string" + } + }, + "required": [ + "accountUserId", + "audience", + "challengeExpiresAt", + "challengeId", + "clientId", + "deviceIdentitySha256Base64url", + "nonce", + "targetOrigin", + "targetPath", + "type" + ], + "title": "RemoteControlClientEnrollmentDeviceKeySignPayload", + "type": "object" + } + ] + }, + "RemoteControlClientConnectionAudience": { + "description": "Audience for a remote-control client connection device-key proof.", + "enum": [ + "remote_control_client_websocket" + ], + "type": "string" + }, + "RemoteControlClientEnrollmentAudience": { + "description": "Audience for a remote-control client enrollment device-key proof.", + "enum": [ + "remote_control_client_enrollment" + ], + "type": "string" + } + }, + "description": "Sign an accepted structured payload with a controller-local device key.", + "properties": { + "keyId": { + "type": "string" + }, + "payload": { + "$ref": "#/definitions/DeviceKeySignPayload" + } + }, + "required": [ + "keyId", + "payload" + ], + "title": "DeviceKeySignParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/DeviceKeySignResponse.json b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeySignResponse.json new file mode 100644 index 0000000000..83fec90330 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/DeviceKeySignResponse.json @@ -0,0 +1,33 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "DeviceKeyAlgorithm": { + "description": "Device-key algorithm reported at enrollment and signing boundaries.", + "enum": [ + "ecdsa_p256_sha256" + ], + "type": "string" + } + }, + "description": "ASN.1 DER signature returned by `device/key/sign`.", + "properties": { + "algorithm": { + "$ref": "#/definitions/DeviceKeyAlgorithm" + }, + "signatureDerBase64": { + "description": "ECDSA signature DER encoded as base64.", + "type": "string" + }, + "signedPayloadBase64": { + "description": "Exact bytes signed by the device key, encoded as base64. Verifiers must verify this byte string directly and must not reserialize `payload`.", + "type": "string" + } + }, + "required": [ + "algorithm", + "signatureDerBase64", + "signedPayloadBase64" + ], + "title": "DeviceKeySignResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index c26ff9161f..fdb934ed53 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -16,6 +16,9 @@ import type { CommandExecWriteParams } from "./v2/CommandExecWriteParams"; import type { ConfigBatchWriteParams } from "./v2/ConfigBatchWriteParams"; import type { ConfigReadParams } from "./v2/ConfigReadParams"; import type { ConfigValueWriteParams } from "./v2/ConfigValueWriteParams"; +import type { DeviceKeyCreateParams } from "./v2/DeviceKeyCreateParams"; +import type { DeviceKeyPublicParams } from "./v2/DeviceKeyPublicParams"; +import type { DeviceKeySignParams } from "./v2/DeviceKeySignParams"; import type { ExperimentalFeatureEnablementSetParams } from "./v2/ExperimentalFeatureEnablementSetParams"; import type { ExperimentalFeatureListParams } from "./v2/ExperimentalFeatureListParams"; import type { ExternalAgentConfigDetectParams } from "./v2/ExternalAgentConfigDetectParams"; @@ -71,4 +74,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/turns/list", id: RequestId, params: ThreadTurnsListParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/turns/list", id: RequestId, params: ThreadTurnsListParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "device/key/create", id: RequestId, params: DeviceKeyCreateParams, } | { "method": "device/key/public", id: RequestId, params: DeviceKeyPublicParams, } | { "method": "device/key/sign", id: RequestId, params: DeviceKeySignParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyAlgorithm.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyAlgorithm.ts new file mode 100644 index 0000000000..6809c41eb5 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyAlgorithm.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Device-key algorithm reported at enrollment and signing boundaries. + */ +export type DeviceKeyAlgorithm = "ecdsa_p256_sha256"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyCreateParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyCreateParams.ts new file mode 100644 index 0000000000..7ffd9b5fa3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyCreateParams.ts @@ -0,0 +1,13 @@ +// 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 { DeviceKeyProtectionPolicy } from "./DeviceKeyProtectionPolicy"; + +/** + * Create a controller-local device key with a random key id. + */ +export type DeviceKeyCreateParams = { +/** + * Defaults to `hardware_only` when omitted. + */ +protectionPolicy?: DeviceKeyProtectionPolicy | null, accountUserId: string, clientId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyCreateResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyCreateResponse.ts new file mode 100644 index 0000000000..6ace37934a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyCreateResponse.ts @@ -0,0 +1,14 @@ +// 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 { DeviceKeyAlgorithm } from "./DeviceKeyAlgorithm"; +import type { DeviceKeyProtectionClass } from "./DeviceKeyProtectionClass"; + +/** + * Device-key metadata and public key returned by create/public APIs. + */ +export type DeviceKeyCreateResponse = { keyId: string, +/** + * SubjectPublicKeyInfo DER encoded as base64. + */ +publicKeySpkiDerBase64: string, algorithm: DeviceKeyAlgorithm, protectionClass: DeviceKeyProtectionClass, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyProtectionClass.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyProtectionClass.ts new file mode 100644 index 0000000000..ba7ff311ad --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyProtectionClass.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Platform protection class for a controller-local device key. + */ +export type DeviceKeyProtectionClass = "hardware_secure_enclave" | "hardware_tpm" | "os_protected_nonextractable"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyProtectionPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyProtectionPolicy.ts new file mode 100644 index 0000000000..66fceafb51 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyProtectionPolicy.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Protection policy for creating or loading a controller-local device key. + */ +export type DeviceKeyProtectionPolicy = "hardware_only" | "allow_os_protected_nonextractable"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyPublicParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyPublicParams.ts new file mode 100644 index 0000000000..5a5b77899d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyPublicParams.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Fetch a controller-local device key public key by id. + */ +export type DeviceKeyPublicParams = { keyId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyPublicResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyPublicResponse.ts new file mode 100644 index 0000000000..9967c0936e --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeyPublicResponse.ts @@ -0,0 +1,14 @@ +// 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 { DeviceKeyAlgorithm } from "./DeviceKeyAlgorithm"; +import type { DeviceKeyProtectionClass } from "./DeviceKeyProtectionClass"; + +/** + * Device-key public metadata returned by `device/key/public`. + */ +export type DeviceKeyPublicResponse = { keyId: string, +/** + * SubjectPublicKeyInfo DER encoded as base64. + */ +publicKeySpkiDerBase64: string, algorithm: DeviceKeyAlgorithm, protectionClass: DeviceKeyProtectionClass, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignParams.ts new file mode 100644 index 0000000000..0886e45d93 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignParams.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DeviceKeySignPayload } from "./DeviceKeySignPayload"; + +/** + * Sign an accepted structured payload with a controller-local device key. + */ +export type DeviceKeySignParams = { keyId: string, payload: DeviceKeySignPayload, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignPayload.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignPayload.ts new file mode 100644 index 0000000000..8596445490 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignPayload.ts @@ -0,0 +1,54 @@ +// 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 { RemoteControlClientConnectionAudience } from "./RemoteControlClientConnectionAudience"; +import type { RemoteControlClientEnrollmentAudience } from "./RemoteControlClientEnrollmentAudience"; + +/** + * Structured payloads accepted by `device/key/sign`. + */ +export type DeviceKeySignPayload = { "type": "remoteControlClientConnection", nonce: string, audience: RemoteControlClientConnectionAudience, +/** + * Backend-issued websocket session id that this proof authorizes. + */ +sessionId: string, +/** + * Origin of the backend endpoint that issued the challenge and will verify this proof. + */ +targetOrigin: string, +/** + * Websocket route path that this proof authorizes. + */ +targetPath: string, accountUserId: string, clientId: string, +/** + * Remote-control token expiration as Unix seconds. + */ +tokenExpiresAt: number, +/** + * SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url. + */ +tokenSha256Base64url: string, +/** + * Must contain exactly `remote_control_controller_websocket`. + */ +scopes: Array, } | { "type": "remoteControlClientEnrollment", nonce: string, audience: RemoteControlClientEnrollmentAudience, +/** + * Backend-issued enrollment challenge id that this proof authorizes. + */ +challengeId: string, +/** + * Origin of the backend endpoint that issued the challenge and will verify this proof. + */ +targetOrigin: string, +/** + * HTTP route path that this proof authorizes. + */ +targetPath: string, accountUserId: string, clientId: string, +/** + * SHA-256 of the requested device identity operation, encoded as unpadded base64url. + */ +deviceIdentitySha256Base64url: string, +/** + * Enrollment challenge expiration as Unix seconds. + */ +challengeExpiresAt: number, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignResponse.ts new file mode 100644 index 0000000000..cf77fae27f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/DeviceKeySignResponse.ts @@ -0,0 +1,18 @@ +// 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 { DeviceKeyAlgorithm } from "./DeviceKeyAlgorithm"; + +/** + * ASN.1 DER signature returned by `device/key/sign`. + */ +export type DeviceKeySignResponse = { +/** + * ECDSA signature DER encoded as base64. + */ +signatureDerBase64: string, +/** + * Exact bytes signed by the device key, encoded as base64. Verifiers must verify this byte + * string directly and must not reserialize `payload`. + */ +signedPayloadBase64: string, algorithm: DeviceKeyAlgorithm, }; 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 efdefead79..308670a809 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PermissionsRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PermissionsRequestApprovalParams.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 { AbsolutePathBuf } from "../AbsolutePathBuf"; import type { RequestPermissionProfile } from "./RequestPermissionProfile"; -export type PermissionsRequestApprovalParams = { threadId: string, turnId: string, itemId: string, reason: string | null, permissions: RequestPermissionProfile, }; +export type PermissionsRequestApprovalParams = { threadId: string, turnId: string, itemId: string, cwd: AbsolutePathBuf, reason: string | null, permissions: RequestPermissionProfile, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/RemoteControlClientConnectionAudience.ts b/codex-rs/app-server-protocol/schema/typescript/v2/RemoteControlClientConnectionAudience.ts new file mode 100644 index 0000000000..e4d41ff4c2 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/RemoteControlClientConnectionAudience.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Audience for a remote-control client connection device-key proof. + */ +export type RemoteControlClientConnectionAudience = "remote_control_client_websocket"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/RemoteControlClientEnrollmentAudience.ts b/codex-rs/app-server-protocol/schema/typescript/v2/RemoteControlClientEnrollmentAudience.ts new file mode 100644 index 0000000000..b65fb3d11b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/RemoteControlClientEnrollmentAudience.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Audience for a remote-control client enrollment device-key proof. + */ +export type RemoteControlClientEnrollmentAudience = "remote_control_client_enrollment"; 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 e37759112a..7bddd0f9d6 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -74,6 +74,16 @@ export type { ConfigWriteResponse } from "./ConfigWriteResponse"; export type { ContextCompactedNotification } from "./ContextCompactedNotification"; export type { CreditsSnapshot } from "./CreditsSnapshot"; export type { DeprecationNoticeNotification } from "./DeprecationNoticeNotification"; +export type { DeviceKeyAlgorithm } from "./DeviceKeyAlgorithm"; +export type { DeviceKeyCreateParams } from "./DeviceKeyCreateParams"; +export type { DeviceKeyCreateResponse } from "./DeviceKeyCreateResponse"; +export type { DeviceKeyProtectionClass } from "./DeviceKeyProtectionClass"; +export type { DeviceKeyProtectionPolicy } from "./DeviceKeyProtectionPolicy"; +export type { DeviceKeyPublicParams } from "./DeviceKeyPublicParams"; +export type { DeviceKeyPublicResponse } from "./DeviceKeyPublicResponse"; +export type { DeviceKeySignParams } from "./DeviceKeySignParams"; +export type { DeviceKeySignPayload } from "./DeviceKeySignPayload"; +export type { DeviceKeySignResponse } from "./DeviceKeySignResponse"; export type { DynamicToolCallOutputContentItem } from "./DynamicToolCallOutputContentItem"; export type { DynamicToolCallParams } from "./DynamicToolCallParams"; export type { DynamicToolCallResponse } from "./DynamicToolCallResponse"; @@ -259,6 +269,8 @@ export type { ReasoningEffortOption } from "./ReasoningEffortOption"; export type { ReasoningSummaryPartAddedNotification } from "./ReasoningSummaryPartAddedNotification"; export type { ReasoningSummaryTextDeltaNotification } from "./ReasoningSummaryTextDeltaNotification"; export type { ReasoningTextDeltaNotification } from "./ReasoningTextDeltaNotification"; +export type { RemoteControlClientConnectionAudience } from "./RemoteControlClientConnectionAudience"; +export type { RemoteControlClientEnrollmentAudience } from "./RemoteControlClientEnrollmentAudience"; export type { RequestPermissionProfile } from "./RequestPermissionProfile"; export type { ResidencyRequirement } from "./ResidencyRequirement"; export type { ReviewDelivery } from "./ReviewDelivery"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index aa3ff8331c..4179e18b55 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -360,6 +360,18 @@ client_request_definitions! { params: v2::AppsListParams, response: v2::AppsListResponse, }, + DeviceKeyCreate => "device/key/create" { + params: v2::DeviceKeyCreateParams, + response: v2::DeviceKeyCreateResponse, + }, + DeviceKeyPublic => "device/key/public" { + params: v2::DeviceKeyPublicParams, + response: v2::DeviceKeyPublicResponse, + }, + DeviceKeySign => "device/key/sign" { + params: v2::DeviceKeySignParams, + response: v2::DeviceKeySignResponse, + }, FsReadFile => "fs/readFile" { params: v2::FsReadFileParams, response: v2::FsReadFileResponse, 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 bd3911d0d2..f7973a45de 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -232,9 +232,7 @@ impl ThreadHistoryBuilder { RolloutItem::EventMsg(event) => self.handle_event(event), RolloutItem::Compacted(payload) => self.handle_compacted(payload), RolloutItem::ResponseItem(item) => self.handle_response_item(item), - RolloutItem::TurnContext(_) - | RolloutItem::SessionMeta(_) - | RolloutItem::SessionState(_) => {} + RolloutItem::TurnContext(_) | RolloutItem::SessionMeta(_) => {} } } diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 8ac6651ae9..b7162eb4de 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -2494,6 +2494,164 @@ pub struct FeedbackUploadResponse { pub thread_id: String, } +/// Device-key algorithm reported at enrollment and signing boundaries. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(rename_all = "snake_case", export_to = "v2/")] +pub enum DeviceKeyAlgorithm { + EcdsaP256Sha256, +} + +/// Platform protection class for a controller-local device key. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(rename_all = "snake_case", export_to = "v2/")] +pub enum DeviceKeyProtectionClass { + HardwareSecureEnclave, + HardwareTpm, + OsProtectedNonextractable, +} + +/// Protection policy for creating or loading a controller-local device key. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(rename_all = "snake_case", export_to = "v2/")] +pub enum DeviceKeyProtectionPolicy { + HardwareOnly, + AllowOsProtectedNonextractable, +} + +/// Create a controller-local device key with a random key id. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct DeviceKeyCreateParams { + /// Defaults to `hardware_only` when omitted. + #[ts(optional = nullable)] + pub protection_policy: Option, + pub account_user_id: String, + pub client_id: String, +} + +/// Device-key metadata and public key returned by create/public APIs. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct DeviceKeyCreateResponse { + pub key_id: String, + /// SubjectPublicKeyInfo DER encoded as base64. + pub public_key_spki_der_base64: String, + pub algorithm: DeviceKeyAlgorithm, + pub protection_class: DeviceKeyProtectionClass, +} + +/// Fetch a controller-local device key public key by id. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct DeviceKeyPublicParams { + pub key_id: String, +} + +/// Device-key public metadata returned by `device/key/public`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct DeviceKeyPublicResponse { + pub key_id: String, + /// SubjectPublicKeyInfo DER encoded as base64. + pub public_key_spki_der_base64: String, + pub algorithm: DeviceKeyAlgorithm, + pub protection_class: DeviceKeyProtectionClass, +} + +/// Audience for a remote-control client connection device-key proof. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(rename_all = "snake_case", export_to = "v2/")] +pub enum RemoteControlClientConnectionAudience { + RemoteControlClientWebsocket, +} + +/// Audience for a remote-control client enrollment device-key proof. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(rename_all = "snake_case", export_to = "v2/")] +pub enum RemoteControlClientEnrollmentAudience { + RemoteControlClientEnrollment, +} + +/// Structured payloads accepted by `device/key/sign`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(tag = "type", rename_all = "camelCase")] +#[ts(tag = "type", export_to = "v2/")] +pub enum DeviceKeySignPayload { + /// Payload bound to one remote-control controller websocket `/client` connection challenge. + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] + RemoteControlClientConnection { + nonce: String, + audience: RemoteControlClientConnectionAudience, + /// Backend-issued websocket session id that this proof authorizes. + session_id: String, + /// Origin of the backend endpoint that issued the challenge and will verify this proof. + target_origin: String, + /// Websocket route path that this proof authorizes. + target_path: String, + account_user_id: String, + client_id: String, + /// Remote-control token expiration as Unix seconds. + #[ts(type = "number")] + token_expires_at: i64, + /// SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url. + token_sha256_base64url: String, + /// Must contain exactly `remote_control_controller_websocket`. + scopes: Vec, + }, + /// Payload bound to a remote-control client `/client/enroll` ownership challenge. + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] + RemoteControlClientEnrollment { + nonce: String, + audience: RemoteControlClientEnrollmentAudience, + /// Backend-issued enrollment challenge id that this proof authorizes. + challenge_id: String, + /// Origin of the backend endpoint that issued the challenge and will verify this proof. + target_origin: String, + /// HTTP route path that this proof authorizes. + target_path: String, + account_user_id: String, + client_id: String, + /// SHA-256 of the requested device identity operation, encoded as unpadded base64url. + device_identity_sha256_base64url: String, + /// Enrollment challenge expiration as Unix seconds. + #[ts(type = "number")] + challenge_expires_at: i64, + }, +} + +/// Sign an accepted structured payload with a controller-local device key. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct DeviceKeySignParams { + pub key_id: String, + pub payload: DeviceKeySignPayload, +} + +/// ASN.1 DER signature returned by `device/key/sign`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct DeviceKeySignResponse { + /// ECDSA signature DER encoded as base64. + pub signature_der_base64: String, + /// Exact bytes signed by the device key, encoded as base64. Verifiers must verify this byte + /// string directly and must not reserialize `payload`. + pub signed_payload_base64: String, + pub algorithm: DeviceKeyAlgorithm, +} + /// Read a file from the host filesystem. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] @@ -6668,6 +6826,7 @@ pub struct PermissionsRequestApprovalParams { pub thread_id: String, pub turn_id: String, pub item_id: String, + pub cwd: AbsolutePathBuf, pub reason: Option, pub permissions: RequestPermissionProfile, } @@ -7102,6 +7261,7 @@ mod tests { "threadId": "thr_123", "turnId": "turn_123", "itemId": "call_123", + "cwd": absolute_path_string("repo"), "reason": "Select a workspace root", "permissions": { "network": { @@ -7115,6 +7275,7 @@ mod tests { })) .expect("permissions request should deserialize"); + assert_eq!(params.cwd, absolute_path("repo")); assert_eq!( params.permissions, RequestPermissionProfile { @@ -7162,6 +7323,7 @@ mod tests { "threadId": "thr_123", "turnId": "turn_123", "itemId": "call_123", + "cwd": absolute_path_string("repo"), "reason": "Select a workspace root", "permissions": { "network": null, @@ -7386,6 +7548,181 @@ mod tests { assert_eq!(decoded, params); } + #[test] + fn device_key_create_params_round_trip_uses_protection_policy() { + let params = DeviceKeyCreateParams { + protection_policy: None, + account_user_id: "account-user-1".to_string(), + client_id: "cli_123".to_string(), + }; + + let value = serde_json::to_value(¶ms).expect("serialize device/key/create params"); + assert_eq!( + value, + json!({ + "accountUserId": "account-user-1", + "clientId": "cli_123", + "protectionPolicy": null, + }) + ); + + let decoded = serde_json::from_value::(value) + .expect("deserialize device/key/create params"); + assert_eq!(decoded, params); + + let params = DeviceKeyCreateParams { + protection_policy: Some(DeviceKeyProtectionPolicy::AllowOsProtectedNonextractable), + account_user_id: "account-user-1".to_string(), + client_id: "cli_123".to_string(), + }; + let value = serde_json::to_value(¶ms) + .expect("serialize device/key/create params with protection policy"); + assert_eq!( + value, + json!({ + "accountUserId": "account-user-1", + "clientId": "cli_123", + "protectionPolicy": "allow_os_protected_nonextractable", + }) + ); + } + + #[test] + fn device_key_create_response_round_trips_protection_class() { + let response = DeviceKeyCreateResponse { + key_id: "dk_123".to_string(), + public_key_spki_der_base64: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE".to_string(), + algorithm: DeviceKeyAlgorithm::EcdsaP256Sha256, + protection_class: DeviceKeyProtectionClass::OsProtectedNonextractable, + }; + + let value = serde_json::to_value(&response).expect("serialize device/key/create response"); + assert_eq!( + value, + json!({ + "keyId": "dk_123", + "publicKeySpkiDerBase64": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE", + "algorithm": "ecdsa_p256_sha256", + "protectionClass": "os_protected_nonextractable", + }) + ); + + let decoded = serde_json::from_value::(value) + .expect("deserialize device/key/create response"); + assert_eq!(decoded, response); + } + + #[test] + fn device_key_sign_params_round_trip_uses_accepted_payload_enum() { + let params = DeviceKeySignParams { + key_id: "dk_123".to_string(), + payload: DeviceKeySignPayload::RemoteControlClientConnection { + nonce: "nonce-1".to_string(), + audience: RemoteControlClientConnectionAudience::RemoteControlClientWebsocket, + session_id: "wssess_123".to_string(), + target_origin: "https://chatgpt.com".to_string(), + target_path: "/api/codex/remote/control/client".to_string(), + account_user_id: "account-user-1".to_string(), + client_id: "cli_123".to_string(), + token_sha256_base64url: "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU".to_string(), + token_expires_at: 1_700_000_000, + scopes: vec!["remote_control_controller_websocket".to_string()], + }, + }; + + let value = serde_json::to_value(¶ms).expect("serialize device/key/sign params"); + assert_eq!( + value, + json!({ + "keyId": "dk_123", + "payload": { + "type": "remoteControlClientConnection", + "nonce": "nonce-1", + "audience": "remote_control_client_websocket", + "sessionId": "wssess_123", + "targetOrigin": "https://chatgpt.com", + "targetPath": "/api/codex/remote/control/client", + "accountUserId": "account-user-1", + "clientId": "cli_123", + "tokenSha256Base64url": "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU", + "tokenExpiresAt": 1_700_000_000, + "scopes": ["remote_control_controller_websocket"], + }, + }) + ); + + let decoded = serde_json::from_value::(value) + .expect("deserialize device/key/sign params"); + assert_eq!(decoded, params); + } + + #[test] + fn device_key_sign_params_round_trip_uses_enrollment_payload() { + let params = DeviceKeySignParams { + key_id: "dk_123".to_string(), + payload: DeviceKeySignPayload::RemoteControlClientEnrollment { + nonce: "nonce-1".to_string(), + audience: RemoteControlClientEnrollmentAudience::RemoteControlClientEnrollment, + challenge_id: "rch_123".to_string(), + target_origin: "https://chatgpt.com".to_string(), + target_path: "/wham/remote/control/client/enroll".to_string(), + account_user_id: "account-user-1".to_string(), + client_id: "cli_123".to_string(), + device_identity_sha256_base64url: "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU" + .to_string(), + challenge_expires_at: 1_700_000_000, + }, + }; + + let value = serde_json::to_value(¶ms) + .expect("serialize device/key/sign params with enrollment payload"); + assert_eq!( + value, + json!({ + "keyId": "dk_123", + "payload": { + "type": "remoteControlClientEnrollment", + "nonce": "nonce-1", + "audience": "remote_control_client_enrollment", + "challengeId": "rch_123", + "targetOrigin": "https://chatgpt.com", + "targetPath": "/wham/remote/control/client/enroll", + "accountUserId": "account-user-1", + "clientId": "cli_123", + "deviceIdentitySha256Base64url": "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU", + "challengeExpiresAt": 1_700_000_000, + }, + }) + ); + + let decoded = serde_json::from_value::(value) + .expect("deserialize device/key/sign params with enrollment payload"); + assert_eq!(decoded, params); + } + + #[test] + fn device_key_sign_response_returns_signed_payload_bytes() { + let response = DeviceKeySignResponse { + signature_der_base64: "MEUCIQD".to_string(), + signed_payload_base64: "eyJkb21haW4iOiJjb2RleA".to_string(), + algorithm: DeviceKeyAlgorithm::EcdsaP256Sha256, + }; + + let value = serde_json::to_value(&response).expect("serialize device/key/sign response"); + assert_eq!( + value, + json!({ + "signatureDerBase64": "MEUCIQD", + "signedPayloadBase64": "eyJkb21haW4iOiJjb2RleA", + "algorithm": "ecdsa_p256_sha256", + }) + ); + + let decoded = serde_json::from_value::(value) + .expect("deserialize device/key/sign response"); + assert_eq!(decoded, response); + } + #[test] fn fs_create_directory_params_round_trip_with_default_recursive() { let params = FsCreateDirectoryParams { diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index f354539640..bec863eb6a 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -35,6 +35,7 @@ codex-cloud-requirements = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-core-plugins = { workspace = true } +codex-device-key = { workspace = true } codex-exec-server = { workspace = true } codex-features = { workspace = true } codex-git-utils = { workspace = true } @@ -72,8 +73,10 @@ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } sha2 = { workspace = true } tempfile = { workspace = true } +thiserror = { workspace = true } time = { workspace = true } toml = { workspace = true } +toml_edit = { workspace = true } tokio = { workspace = true, features = [ "io-std", "macros", diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 57cb6c173b..7e23cc24a7 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -190,6 +190,9 @@ Example with notification opt-out: - `plugin/read` — read one plugin by `marketplacePath` plus `pluginName`, returning marketplace info, a list-style `summary`, manifest descriptions/interface metadata, and bundled skills/apps/MCP server names. Returned plugin skills include their current `enabled` state after local config filtering. Plugin app summaries also include `needsAuth` when the server can determine connector accessibility (**under development; do not call from production clients yet**). - `skills/changed` — notification emitted when watched local skill files change. - `app/list` — list available apps. +- `device/key/create` — create or load a controller-local device signing key for an account/client binding. This local-key API is available only over local transports such as stdio and in-process; remote transports reject it. Hardware-backed providers are the target protection class; an OS-protected non-extractable fallback is allowed only with `protectionPolicy: "allow_os_protected_nonextractable"` and returns the reported `protectionClass`. +- `device/key/public` — return a device key's SPKI DER public key as base64 plus its `algorithm` and `protectionClass`. +- `device/key/sign` — sign one of the accepted structured payload variants with a controller-local device key. The only accepted payload today is `remoteControlClientConnection`, which binds a server-issued `/client` websocket challenge to the enrolled controller device without signing the bearer token itself; this is intentionally not an arbitrary-byte signing API. - `skills/config/write` — write user-level skill config by name or absolute path. - `plugin/install` — install a plugin from a discovered marketplace entry, rejecting marketplace entries marked unavailable for install, install MCPs if any, and return the effective plugin auth policy plus any apps that still need auth (**under development; do not call from production clients yet**). - `plugin/uninstall` — uninstall a plugin by id by removing its cached files and clearing its user-level config entry (**under development; do not call from production clients yet**). @@ -1148,7 +1151,7 @@ the client can offer session-scoped and/or persistent approval choices. ### Permission requests -The built-in `request_permissions` tool sends an `item/permissions/requestApproval` JSON-RPC request to the client with the requested permission profile. This v2 payload mirrors the command-execution `additionalPermissions` shape: it can request network access and additional filesystem access. +The built-in `request_permissions` tool sends an `item/permissions/requestApproval` JSON-RPC request to the client with the requested permission profile. This v2 payload mirrors the command-execution `additionalPermissions` shape: it can request network access and additional filesystem access. The `cwd` field identifies the directory used to resolve cwd-relative permissions such as `:cwd`, `:project_roots`, and relative deny globs. ```json { @@ -1158,6 +1161,7 @@ The built-in `request_permissions` tool sends an `item/permissions/requestApprov "threadId": "thr_123", "turnId": "turn_123", "itemId": "call_123", + "cwd": "/Users/me/project", "reason": "Select a workspace root", "permissions": { "fileSystem": { diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index d2b435ef93..a2ea77900a 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -120,6 +120,7 @@ use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem; use codex_protocol::dynamic_tools::DynamicToolResponse as CoreDynamicToolResponse; use codex_protocol::items::parse_hook_prompt_message; +use codex_protocol::models::PermissionProfile as CorePermissionProfile; use codex_protocol::plan_tool::UpdatePlanArgs; use codex_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo; use codex_protocol::protocol::Event; @@ -908,27 +909,32 @@ pub(crate) async fn apply_bespoke_event_handling( .note_permission_requested(&conversation_id.to_string()) .await; let requested_permissions = request.permissions.clone(); + let request_cwd = match request.cwd.clone() { + Some(cwd) => cwd, + None => conversation.config_snapshot().await.cwd, + }; let params = PermissionsRequestApprovalParams { thread_id: conversation_id.to_string(), turn_id: request.turn_id.clone(), item_id: request.call_id.clone(), + cwd: request_cwd.clone(), reason: request.reason, permissions: request.permissions.into(), }; let (pending_request_id, rx) = outgoing .send_request(ServerRequestPayload::PermissionsRequestApproval(params)) .await; + let pending_response = PendingRequestPermissionsResponse { + call_id: request.call_id, + requested_permissions, + request_cwd, + pending_request_id, + receiver: rx, + request_permissions_guard: permission_guard, + }; tokio::spawn(async move { - on_request_permissions_response( - request.call_id, - requested_permissions, - pending_request_id, - rx, - conversation, - thread_state, - permission_guard, - ) - .await; + on_request_permissions_response(pending_response, conversation, thread_state) + .await; }); } else { error!( @@ -2590,20 +2596,26 @@ fn mcp_server_elicitation_response_from_client_result( } async fn on_request_permissions_response( - call_id: String, - requested_permissions: CoreRequestPermissionProfile, - pending_request_id: RequestId, - receiver: oneshot::Receiver, + pending_response: PendingRequestPermissionsResponse, conversation: Arc, thread_state: Arc>, - request_permissions_guard: ThreadWatchActiveGuard, ) { + let PendingRequestPermissionsResponse { + call_id, + requested_permissions, + request_cwd, + pending_request_id, + receiver, + request_permissions_guard, + } = pending_response; let response = receiver.await; resolve_server_request_on_thread_listener(&thread_state, pending_request_id).await; drop(request_permissions_guard); - let Some(response) = - request_permissions_response_from_client_result(requested_permissions, response) - else { + let Some(response) = request_permissions_response_from_client_result( + requested_permissions, + response, + request_cwd.as_path(), + ) else { return; }; @@ -2618,9 +2630,19 @@ async fn on_request_permissions_response( } } +struct PendingRequestPermissionsResponse { + call_id: String, + requested_permissions: CoreRequestPermissionProfile, + request_cwd: AbsolutePathBuf, + pending_request_id: RequestId, + receiver: oneshot::Receiver, + request_permissions_guard: ThreadWatchActiveGuard, +} + fn request_permissions_response_from_client_result( requested_permissions: CoreRequestPermissionProfile, response: std::result::Result, + cwd: &std::path::Path, ) -> Option { let value = match response { Ok(Ok(value)) => value, @@ -2649,12 +2671,14 @@ fn request_permissions_response_from_client_result( scope: codex_app_server_protocol::PermissionGrantScope::Turn, } }); + let granted_permissions: CorePermissionProfile = response.permissions.into(); + let permissions = if granted_permissions.is_empty() { + CoreRequestPermissionProfile::default() + } else { + intersect_permission_profiles(requested_permissions.into(), granted_permissions, cwd).into() + }; Some(CoreRequestPermissionsResponse { - permissions: intersect_permission_profiles( - requested_permissions.into(), - response.permissions.into(), - ) - .into(), + permissions, scope: response.scope.to_core(), }) } @@ -3027,6 +3051,10 @@ mod tests { use codex_protocol::mcp::CallToolResult; use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions; use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions; + use codex_protocol::permissions::FileSystemAccessMode; + use codex_protocol::permissions::FileSystemPath; + use codex_protocol::permissions::FileSystemSandboxEntry; + use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::plan_tool::PlanItemArg; use codex_protocol::plan_tool::StepStatus; use codex_protocol::protocol::CollabResumeBeginEvent; @@ -3711,6 +3739,7 @@ mod tests { let response = request_permissions_response_from_client_result( CoreRequestPermissionProfile::default(), Ok(Err(error)), + std::env::current_dir().expect("current dir").as_path(), ); assert_eq!(response, None); @@ -3797,12 +3826,14 @@ mod tests { ), ]; + let cwd = std::env::current_dir().expect("current dir"); for (granted_permissions, expected_permissions) in cases { let response = request_permissions_response_from_client_result( requested_permissions.clone(), Ok(Ok(serde_json::json!({ "permissions": granted_permissions, }))), + cwd.as_path(), ) .expect("response should be accepted"); @@ -3824,6 +3855,7 @@ mod tests { "scope": "session", "permissions": {}, }))), + std::env::current_dir().expect("current dir").as_path(), ) .expect("response should be accepted"); @@ -3836,6 +3868,129 @@ mod tests { ); } + #[test] + fn request_permissions_response_accepts_explicit_child_grant_for_requested_cwd_scope() { + let temp_dir = TempDir::new().expect("temp dir"); + let cwd = AbsolutePathBuf::from_absolute_path(temp_dir.path()).expect("absolute cwd"); + let child = cwd.join("child"); + let requested_permissions = CoreRequestPermissionProfile { + file_system: Some(CoreFileSystemPermissions { + entries: vec![FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::CurrentWorkingDirectory, + }, + access: FileSystemAccessMode::Write, + }], + glob_scan_max_depth: None, + }), + ..Default::default() + }; + + let response = request_permissions_response_from_client_result( + requested_permissions, + Ok(Ok(serde_json::json!({ + "permissions": { + "fileSystem": { + "write": [child], + }, + }, + }))), + cwd.as_path(), + ) + .expect("response should be accepted"); + + assert_eq!( + response.permissions, + CoreRequestPermissionProfile { + file_system: Some(CoreFileSystemPermissions::from_read_write_roots( + /*read*/ None, + Some(vec![child]), + )), + ..Default::default() + } + ); + } + + #[test] + fn request_permissions_response_rejects_child_grant_outside_requested_cwd_scope() { + let temp_dir = TempDir::new().expect("temp dir"); + let request_cwd = AbsolutePathBuf::from_absolute_path(temp_dir.path().join("request-cwd")) + .expect("absolute request cwd"); + let later_cwd = AbsolutePathBuf::from_absolute_path(temp_dir.path().join("later-cwd")) + .expect("absolute later cwd"); + let later_child = later_cwd.join("child"); + let requested_permissions = CoreRequestPermissionProfile { + file_system: Some(CoreFileSystemPermissions { + entries: vec![FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::CurrentWorkingDirectory, + }, + access: FileSystemAccessMode::Write, + }], + glob_scan_max_depth: None, + }), + ..Default::default() + }; + + let response = request_permissions_response_from_client_result( + requested_permissions, + Ok(Ok(serde_json::json!({ + "permissions": { + "fileSystem": { + "write": [later_child], + }, + }, + }))), + request_cwd.as_path(), + ) + .expect("response should be accepted"); + + assert_eq!( + response.permissions, + CoreRequestPermissionProfile::default() + ); + } + + #[test] + fn request_permissions_response_ignores_broader_cwd_grant_for_requested_child_path() { + let temp_dir = TempDir::new().expect("temp dir"); + let cwd = AbsolutePathBuf::from_absolute_path(temp_dir.path()).expect("absolute cwd"); + let child = cwd.join("child"); + let requested_permissions = CoreRequestPermissionProfile { + file_system: Some(CoreFileSystemPermissions::from_read_write_roots( + /*read*/ None, + Some(vec![child]), + )), + ..Default::default() + }; + + let response = request_permissions_response_from_client_result( + requested_permissions, + Ok(Ok(serde_json::json!({ + "permissions": { + "fileSystem": { + "entries": [{ + "path": { + "type": "special", + "value": { + "kind": "current_working_directory" + } + }, + "access": "write" + }], + }, + }, + }))), + cwd.as_path(), + ) + .expect("response should be accepted"); + + assert_eq!( + response.permissions, + CoreRequestPermissionProfile::default() + ); + } + #[test] fn collab_resume_begin_maps_to_item_started_resume_agent() { let event = CollabResumeBeginEvent { diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 7a2ada0765..4669c0cb1a 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -2,7 +2,7 @@ use crate::bespoke_event_handling::apply_bespoke_event_handling; use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed; use crate::command_exec::CommandExecManager; use crate::command_exec::StartCommandExecParams; -use crate::config_api::apply_runtime_feature_enablement; +use crate::config_manager::ConfigManager; use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_PARAMS_ERROR_CODE; @@ -212,8 +212,6 @@ use codex_arg0::Arg0DispatchPaths; use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType; use codex_backend_client::Client as BackendClient; use codex_chatgpt::connectors; -use codex_cloud_requirements::cloud_requirements_loader; -use codex_config::ThreadConfigLoader; use codex_config::types::McpServerTransportConfig; use codex_core::CodexThread; use codex_core::ForkSnapshot; @@ -231,9 +229,6 @@ use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config_loader::CloudRequirementsLoadError; use codex_core::config_loader::CloudRequirementsLoadErrorCode; -use codex_core::config_loader::CloudRequirementsLoader; -use codex_core::config_loader::LoaderOverrides; -use codex_core::config_loader::load_config_layers_state; use codex_core::config_loader::project_trust_key; use codex_core::exec::ExecCapturePolicy; use codex_core::exec::ExecExpiration; @@ -280,16 +275,15 @@ use codex_login::ServerOptions as LoginServerOptions; use codex_login::ShutdownHandle; use codex_login::auth::login_with_chatgpt_auth_tokens; use codex_login::complete_device_code_login; -use codex_login::default_client::set_default_client_residency_requirement; use codex_login::login_with_api_key; use codex_login::request_device_code; use codex_login::run_login_server; use codex_mcp::McpRuntimeEnvironment; use codex_mcp::McpServerStatusSnapshot; use codex_mcp::McpSnapshotDetail; -use codex_mcp::collect_mcp_server_status_snapshot_with_detail_and_authorization_header; +use codex_mcp::collect_mcp_server_status_snapshot_with_detail; use codex_mcp::discover_supported_scopes; -use codex_mcp::effective_mcp_servers_with_authorization_header; +use codex_mcp::effective_mcp_servers; use codex_mcp::read_mcp_resource as read_mcp_resource_without_thread; use codex_mcp::resolve_oauth_scopes; use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig; @@ -348,16 +342,13 @@ use codex_thread_store::ThreadStore; use codex_thread_store::ThreadStoreError; use codex_thread_store::UpdateThreadMetadataParams as StoreUpdateThreadMetadataParams; use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_json_to_toml::json_to_toml; use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP; -use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::io::Error as IoError; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; -use std::sync::RwLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; @@ -478,10 +469,7 @@ pub(crate) struct CodexMessageProcessor { arg0_paths: Arg0DispatchPaths, config: Arc, thread_store: Arc, - cli_overrides: Arc>>, - runtime_feature_enablement: Arc>>, - cloud_requirements: Arc>, - thread_config_loader: Arc, + config_manager: ConfigManager, active_login: Arc>>, pending_thread_unloads: Arc>>, thread_state_manager: ThreadStateManager, @@ -638,11 +626,10 @@ pub(crate) struct CodexMessageProcessorArgs { pub(crate) outgoing: Arc, pub(crate) analytics_events_client: AnalyticsEventsClient, pub(crate) arg0_paths: Arg0DispatchPaths, + /// Startup config used as the process baseline. Fresh effective config loads + /// go through `config_manager`. pub(crate) config: Arc, - pub(crate) cli_overrides: Arc>>, - pub(crate) runtime_feature_enablement: Arc>>, - pub(crate) cloud_requirements: Arc>, - pub(crate) thread_config_loader: Arc, + pub(crate) config_manager: ConfigManager, pub(crate) feedback: CodexFeedback, pub(crate) log_db: Option, } @@ -727,10 +714,7 @@ impl CodexMessageProcessor { analytics_events_client, arg0_paths, config, - cli_overrides, - runtime_feature_enablement, - cloud_requirements, - thread_config_loader, + config_manager, feedback, log_db, } = args; @@ -742,10 +726,7 @@ impl CodexMessageProcessor { arg0_paths, thread_store: configured_thread_store(&config), config, - cli_overrides, - runtime_feature_enablement, - cloud_requirements, - thread_config_loader, + config_manager, active_login: Arc::new(Mutex::new(None)), pending_thread_unloads: Arc::new(Mutex::new(HashSet::new())), thread_state_manager: ThreadStateManager::new(), @@ -763,44 +744,14 @@ impl CodexMessageProcessor { &self, fallback_cwd: Option, ) -> Result { - let cloud_requirements = self.current_cloud_requirements(); - let mut config = codex_core::config::ConfigBuilder::default() - .cli_overrides(self.current_cli_overrides()) - .fallback_cwd(fallback_cwd) - .cloud_requirements(cloud_requirements) - .build() + self.config_manager + .load_latest_config(fallback_cwd) .await .map_err(|err| JSONRPCErrorError { code: INTERNAL_ERROR_CODE, message: format!("failed to reload config: {err}"), data: None, - })?; - apply_runtime_feature_enablement(&mut config, &self.current_runtime_feature_enablement()); - config.codex_self_exe = self.arg0_paths.codex_self_exe.clone(); - config.codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone(); - config.main_execve_wrapper_exe = self.arg0_paths.main_execve_wrapper_exe.clone(); - Ok(config) - } - - fn current_cloud_requirements(&self) -> CloudRequirementsLoader { - self.cloud_requirements - .read() - .map(|guard| guard.clone()) - .unwrap_or_default() - } - - fn current_cli_overrides(&self) -> Vec<(String, TomlValue)> { - self.cli_overrides - .read() - .map(|guard| guard.clone()) - .unwrap_or_default() - } - - fn current_runtime_feature_enablement(&self) -> BTreeMap { - self.runtime_feature_enablement - .read() - .map(|guard| guard.clone()) - .unwrap_or_default() + }) } /// If a client sends `developer_instructions: null` during a mode switch, @@ -1186,6 +1137,11 @@ impl CodexMessageProcessor { self.command_exec_terminate(to_connection_request_id(request_id), params) .await; } + ClientRequest::DeviceKeyCreate { .. } + | ClientRequest::DeviceKeyPublic { .. } + | ClientRequest::DeviceKeySign { .. } => { + warn!("Device key request reached CodexMessageProcessor unexpectedly"); + } ClientRequest::ConfigRead { .. } | ClientRequest::ConfigValueWrite { .. } | ClientRequest::ConfigBatchWrite { .. } @@ -1419,10 +1375,8 @@ impl CodexMessageProcessor { let outgoing_clone = self.outgoing.clone(); let active_login = self.active_login.clone(); let auth_manager = self.auth_manager.clone(); - let cloud_requirements = self.cloud_requirements.clone(); + let config_manager = self.config_manager.clone(); let chatgpt_base_url = self.config.chatgpt_base_url.clone(); - let codex_home = self.config.codex_home.to_path_buf(); - let cli_overrides = self.current_cli_overrides(); let auth_url = server.auth_url.clone(); tokio::spawn(async move { let (success, error_msg) = match tokio::time::timeout( @@ -1452,17 +1406,13 @@ impl CodexMessageProcessor { if success { auth_manager.reload(); - replace_cloud_requirements_loader( - cloud_requirements.as_ref(), + config_manager.replace_cloud_requirements_loader( auth_manager.clone(), chatgpt_base_url, - codex_home, ); - sync_default_client_residency_requirement( - &cli_overrides, - cloud_requirements.as_ref(), - ) - .await; + config_manager + .sync_default_client_residency_requirement() + .await; // Notify clients with the actual current auth mode. let auth = auth_manager.auth_cached(); @@ -1536,10 +1486,8 @@ impl CodexMessageProcessor { let outgoing_clone = self.outgoing.clone(); let active_login = self.active_login.clone(); let auth_manager = self.auth_manager.clone(); - let cloud_requirements = self.cloud_requirements.clone(); + let config_manager = self.config_manager.clone(); let chatgpt_base_url = self.config.chatgpt_base_url.clone(); - let codex_home = self.config.codex_home.to_path_buf(); - let cli_overrides = self.current_cli_overrides(); tokio::spawn(async move { let (success, error_msg) = tokio::select! { _ = cancel.cancelled() => { @@ -1566,17 +1514,13 @@ impl CodexMessageProcessor { if success { auth_manager.reload(); - replace_cloud_requirements_loader( - cloud_requirements.as_ref(), + config_manager.replace_cloud_requirements_loader( auth_manager.clone(), chatgpt_base_url, - codex_home, ); - sync_default_client_residency_requirement( - &cli_overrides, - cloud_requirements.as_ref(), - ) - .await; + config_manager + .sync_default_client_residency_requirement() + .await; let auth = auth_manager.auth_cached(); let payload_v2 = AccountUpdatedNotification { @@ -1706,14 +1650,12 @@ impl CodexMessageProcessor { return; } self.auth_manager.reload(); - replace_cloud_requirements_loader( - self.cloud_requirements.as_ref(), + self.config_manager.replace_cloud_requirements_loader( self.auth_manager.clone(), self.config.chatgpt_base_url.clone(), - self.config.codex_home.to_path_buf(), ); - let cli_overrides = self.current_cli_overrides(); - sync_default_client_residency_requirement(&cli_overrides, self.cloud_requirements.as_ref()) + self.config_manager + .sync_default_client_residency_requirement() .await; self.outgoing @@ -2028,28 +1970,12 @@ impl CodexMessageProcessor { }); } - let authorization_header_value = self - .auth_manager - .chatgpt_authorization_header_for_auth(&auth) - .await; - let mut client = BackendClient::new(self.config.chatgpt_base_url.clone()) - .map(|client| { - client.with_user_agent(codex_login::default_client::get_codex_user_agent()) - }) + let client = BackendClient::from_auth(self.config.chatgpt_base_url.clone(), &auth) .map_err(|err| JSONRPCErrorError { code: INTERNAL_ERROR_CODE, message: format!("failed to construct backend client: {err}"), data: None, })?; - if let Some(authorization_header_value) = authorization_header_value { - client = client.with_authorization_header_value(authorization_header_value); - } - if let Some(account_id) = auth.get_account_id() { - client = client.with_chatgpt_account_id(account_id); - } - if auth.is_fedramp_account() { - client = client.with_fedramp_routing_header(); - } let snapshots = client .get_rate_limits_many() @@ -2424,8 +2350,6 @@ impl CodexMessageProcessor { personality, ); typesafe_overrides.ephemeral = ephemeral; - let cloud_requirements = self.current_cloud_requirements(); - let cli_overrides = self.current_cli_overrides(); let listener_task_context = ListenerTaskContext { thread_manager: Arc::clone(&self.thread_manager), thread_state_manager: self.thread_state_manager.clone(), @@ -2438,15 +2362,11 @@ impl CodexMessageProcessor { codex_home: self.config.codex_home.to_path_buf(), }; let request_trace = request_context.request_trace(); - let runtime_feature_enablement = self.current_runtime_feature_enablement(); - let thread_config_loader = Arc::clone(&self.thread_config_loader); + let config_manager = self.config_manager.clone(); let thread_start_task = async move { Self::thread_start_task( listener_task_context, - cli_overrides, - runtime_feature_enablement, - cloud_requirements, - thread_config_loader, + config_manager, request_id, app_server_client_name, app_server_client_version, @@ -2520,10 +2440,7 @@ impl CodexMessageProcessor { #[allow(clippy::too_many_arguments)] async fn thread_start_task( listener_task_context: ListenerTaskContext, - cli_overrides: Vec<(String, TomlValue)>, - runtime_feature_enablement: BTreeMap, - cloud_requirements: CloudRequirementsLoader, - thread_config_loader: Arc, + config_manager: ConfigManager, request_id: ConnectionRequestId, app_server_client_name: Option, app_server_client_version: Option, @@ -2537,16 +2454,9 @@ impl CodexMessageProcessor { request_trace: Option, ) { let requested_cwd = typesafe_overrides.cwd.clone(); - let mut config = match derive_config_from_params( - &cli_overrides, - config_overrides.clone(), - typesafe_overrides.clone(), - Arc::clone(&thread_config_loader), - &cloud_requirements, - &listener_task_context.codex_home, - &runtime_feature_enablement, - ) - .await + let mut config = match config_manager + .load_with_overrides(config_overrides.clone(), typesafe_overrides.clone()) + .await { Ok(config) => config, Err(err) => { @@ -2585,6 +2495,7 @@ impl CodexMessageProcessor { let trust_target = resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &config.cwd) .await .unwrap_or_else(|| config.cwd.clone()); + let current_cli_overrides = config_manager.current_cli_overrides(); let cli_overrides_with_trust; let cli_overrides_for_reload = if let Err(err) = codex_core::config::set_project_trust_level( @@ -2606,7 +2517,7 @@ impl CodexMessageProcessor { project_trust_key(trust_target.as_path()), TomlValue::Table(project), ); - cli_overrides_with_trust = cli_overrides + cli_overrides_with_trust = current_cli_overrides .iter() .cloned() .chain(std::iter::once(( @@ -2616,19 +2527,17 @@ impl CodexMessageProcessor { .collect::>(); cli_overrides_with_trust.as_slice() } else { - &cli_overrides + current_cli_overrides.as_slice() }; - config = match derive_config_from_params( - cli_overrides_for_reload, - config_overrides, - typesafe_overrides, - thread_config_loader, - &cloud_requirements, - &listener_task_context.codex_home, - &runtime_feature_enablement, - ) - .await + config = match config_manager + .load_with_cli_overrides( + cli_overrides_for_reload, + config_overrides, + typesafe_overrides, + /*fallback_cwd*/ None, + ) + .await { Ok(config) => config, Err(err) => { @@ -4412,19 +4321,10 @@ impl CodexMessageProcessor { .await; // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let cloud_requirements = self.current_cloud_requirements(); - let cli_overrides = self.current_cli_overrides(); - let runtime_feature_enablement = self.current_runtime_feature_enablement(); - let config = match derive_config_for_cwd( - &cli_overrides, - request_overrides, - typesafe_overrides, - history_cwd, - &cloud_requirements, - &self.config.codex_home, - &runtime_feature_enablement, - ) - .await + let config = match self + .config_manager + .load_for_cwd(request_overrides, typesafe_overrides, history_cwd) + .await { Ok(config) => config, Err(err) => { @@ -4992,19 +4892,10 @@ impl CodexMessageProcessor { ); typesafe_overrides.ephemeral = ephemeral.then_some(true); // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let cloud_requirements = self.current_cloud_requirements(); - let cli_overrides = self.current_cli_overrides(); - let runtime_feature_enablement = self.current_runtime_feature_enablement(); - let config = match derive_config_for_cwd( - &cli_overrides, - request_overrides, - typesafe_overrides, - history_cwd, - &cloud_requirements, - &self.config.codex_home, - &runtime_feature_enablement, - ) - .await + let config = match self + .config_manager + .load_for_cwd(request_overrides, typesafe_overrides, history_cwd) + .await { Ok(config) => config, Err(err) => { @@ -5785,8 +5676,7 @@ impl CodexMessageProcessor { let mcp_config = config .to_mcp_config(self.thread_manager.plugins_manager().as_ref()) .await; - let auth_manager = Arc::clone(&self.auth_manager); - let auth = auth_manager.auth().await; + let auth = self.auth_manager.auth().await; let runtime_environment = match self.thread_manager.environment_manager().current().await { Ok(Some(environment)) => { // Status listing has no turn cwd. This fallback is used only @@ -5811,113 +5701,122 @@ impl CodexMessageProcessor { }; tokio::spawn(async move { - let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) { - McpServerStatusDetail::Full => McpSnapshotDetail::Full, - McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly, - }; - - let background_authorization_header_value = if let Some(auth) = auth.as_ref() { - auth_manager - .chatgpt_authorization_header_for_auth(auth) - .await - } else { - None - }; - let snapshot = collect_mcp_server_status_snapshot_with_detail_and_authorization_header( - &mcp_config, - auth.as_ref(), - request.request_id.to_string(), + Self::list_mcp_server_status_task( + outgoing, + request, + params, + config, + mcp_config, + auth, runtime_environment, - detail, - background_authorization_header_value.as_deref(), ) .await; - - let effective_servers = effective_mcp_servers_with_authorization_header( - &mcp_config, - auth.as_ref(), - background_authorization_header_value.as_deref(), - ); - let McpServerStatusSnapshot { - tools_by_server, - resources, - resource_templates, - auth_statuses, - } = snapshot; - - let mut server_names: Vec = config - .mcp_servers - .keys() - .cloned() - // Include built-in/plugin MCP servers that are present in the - // effective runtime config even when they are not user-declared in - // `config.mcp_servers`. - .chain(effective_servers.keys().cloned()) - .chain(auth_statuses.keys().cloned()) - .chain(resources.keys().cloned()) - .chain(resource_templates.keys().cloned()) - .collect(); - server_names.sort(); - server_names.dedup(); - - let total = server_names.len(); - let limit = params.limit.unwrap_or(total as u32).max(1) as usize; - let effective_limit = limit.min(total); - let start = match params.cursor { - Some(cursor) => match cursor.parse::() { - Ok(idx) => idx, - Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid cursor: {cursor}"), - data: None, - }; - outgoing.send_error(request, error).await; - return; - } - }, - None => 0, - }; - - if start > total { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("cursor {start} exceeds total MCP servers {total}"), - data: None, - }; - outgoing.send_error(request, error).await; - return; - } - - let end = start.saturating_add(effective_limit).min(total); - - let data: Vec = server_names[start..end] - .iter() - .map(|name| McpServerStatus { - name: name.clone(), - tools: tools_by_server.get(name).cloned().unwrap_or_default(), - resources: resources.get(name).cloned().unwrap_or_default(), - resource_templates: resource_templates.get(name).cloned().unwrap_or_default(), - auth_status: auth_statuses - .get(name) - .cloned() - .unwrap_or(CoreMcpAuthStatus::Unsupported) - .into(), - }) - .collect(); - - let next_cursor = if end < total { - Some(end.to_string()) - } else { - None - }; - - let response = ListMcpServerStatusResponse { data, next_cursor }; - - outgoing.send_response(request, response).await; }); } + async fn list_mcp_server_status_task( + outgoing: Arc, + request_id: ConnectionRequestId, + params: ListMcpServerStatusParams, + config: Config, + mcp_config: codex_mcp::McpConfig, + auth: Option, + runtime_environment: McpRuntimeEnvironment, + ) { + let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) { + McpServerStatusDetail::Full => McpSnapshotDetail::Full, + McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly, + }; + + let snapshot = collect_mcp_server_status_snapshot_with_detail( + &mcp_config, + auth.as_ref(), + request_id.request_id.to_string(), + runtime_environment, + detail, + ) + .await; + + let effective_servers = effective_mcp_servers(&mcp_config, auth.as_ref()); + let McpServerStatusSnapshot { + tools_by_server, + resources, + resource_templates, + auth_statuses, + } = snapshot; + + let mut server_names: Vec = config + .mcp_servers + .keys() + .cloned() + // Include built-in/plugin MCP servers that are present in the + // effective runtime config even when they are not user-declared in + // `config.mcp_servers`. + .chain(effective_servers.keys().cloned()) + .chain(auth_statuses.keys().cloned()) + .chain(resources.keys().cloned()) + .chain(resource_templates.keys().cloned()) + .collect(); + server_names.sort(); + server_names.dedup(); + + let total = server_names.len(); + let limit = params.limit.unwrap_or(total as u32).max(1) as usize; + let effective_limit = limit.min(total); + let start = match params.cursor { + Some(cursor) => match cursor.parse::() { + Ok(idx) => idx, + Err(_) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("invalid cursor: {cursor}"), + data: None, + }; + outgoing.send_error(request_id, error).await; + return; + } + }, + None => 0, + }; + + if start > total { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("cursor {start} exceeds total MCP servers {total}"), + data: None, + }; + outgoing.send_error(request_id, error).await; + return; + } + + let end = start.saturating_add(effective_limit).min(total); + + let data: Vec = server_names[start..end] + .iter() + .map(|name| McpServerStatus { + name: name.clone(), + tools: tools_by_server.get(name).cloned().unwrap_or_default(), + resources: resources.get(name).cloned().unwrap_or_default(), + resource_templates: resource_templates.get(name).cloned().unwrap_or_default(), + auth_status: auth_statuses + .get(name) + .cloned() + .unwrap_or(CoreMcpAuthStatus::Unsupported) + .into(), + }) + .collect(); + + let next_cursor = if end < total { + Some(end.to_string()) + } else { + None + }; + + let response = ListMcpServerStatusResponse { data, next_cursor }; + + outgoing.send_response(request_id, response).await; + } + async fn read_mcp_resource( &self, request_id: ConnectionRequestId, @@ -6041,17 +5940,19 @@ impl CodexMessageProcessor { params: McpServerToolCallParams, ) { let outgoing = Arc::clone(&self.outgoing); - let (_, thread) = match self.load_thread(¶ms.thread_id).await { + let thread_id = params.thread_id.clone(); + let (_, thread) = match self.load_thread(&thread_id).await { Ok(thread) => thread, Err(error) => { self.outgoing.send_error(request_id, error).await; return; } }; + let meta = with_mcp_tool_call_thread_id_meta(params.meta, &thread_id); tokio::spawn(async move { let result = thread - .call_mcp_tool(¶ms.server, ¶ms.tool, params.arguments, params.meta) + .call_mcp_tool(¶ms.server, ¶ms.tool, params.arguments, meta) .await; match result { Ok(result) => { @@ -6577,8 +6478,6 @@ impl CodexMessageProcessor { return; } }; - let cli_overrides = self.current_cli_overrides(); - let host_name = codex_config::host_name(); let mut data = Vec::new(); for cwd in cwds { let extra_roots = extra_roots_by_cwd @@ -6599,17 +6498,10 @@ impl CodexMessageProcessor { continue; } }; - let config_layer_stack = match load_config_layers_state( - LOCAL_FS.as_ref(), - &self.config.codex_home, - Some(cwd_abs.clone()), - &cli_overrides, - LoaderOverrides::default(), - CloudRequirementsLoader::default(), - self.thread_config_loader.as_ref(), - host_name.as_deref(), - ) - .await + let config_layer_stack = match self + .config_manager + .load_config_layers_for_cwd(cwd_abs.clone()) + .await { Ok(config_layer_stack) => config_layer_stack, Err(err) => { @@ -8765,30 +8657,25 @@ impl CodexMessageProcessor { WindowsSandboxSetupMode::Unelevated => CoreWindowsSandboxSetupMode::Unelevated, }; let config = Arc::clone(&self.config); - let cloud_requirements = self.current_cloud_requirements(); + let config_manager = self.config_manager.clone(); let command_cwd = params .cwd .map(PathBuf::from) .unwrap_or_else(|| config.cwd.to_path_buf()); - let cli_overrides = self.current_cli_overrides(); - let runtime_feature_enablement = self.current_runtime_feature_enablement(); let outgoing = Arc::clone(&self.outgoing); let connection_id = request_id.connection_id; tokio::spawn(async move { - let derived_config = derive_config_for_cwd( - &cli_overrides, - /*request_overrides*/ None, - ConfigOverrides { - cwd: Some(command_cwd.clone()), - ..Default::default() - }, - Some(command_cwd.clone()), - &cloud_requirements, - &config.codex_home, - &runtime_feature_enablement, - ) - .await; + let derived_config = config_manager + .load_for_cwd( + /*request_overrides*/ None, + ConfigOverrides { + cwd: Some(command_cwd.clone()), + ..Default::default() + }, + Some(command_cwd.clone()), + ) + .await; let setup_result = match derived_config { Ok(config) => { let setup_request = WindowsSandboxSetupRequest { @@ -9518,116 +9405,6 @@ fn validate_dynamic_tools(tools: &[ApiDynamicToolSpec]) -> Result<(), String> { Ok(()) } -fn replace_cloud_requirements_loader( - cloud_requirements: &RwLock, - auth_manager: Arc, - chatgpt_base_url: String, - codex_home: PathBuf, -) { - let loader = cloud_requirements_loader(auth_manager, chatgpt_base_url, codex_home); - if let Ok(mut guard) = cloud_requirements.write() { - *guard = loader; - } else { - warn!("failed to update cloud requirements loader"); - } -} - -async fn sync_default_client_residency_requirement( - cli_overrides: &[(String, TomlValue)], - cloud_requirements: &RwLock, -) { - let loader = cloud_requirements - .read() - .map(|guard| guard.clone()) - .unwrap_or_default(); - match codex_core::config::ConfigBuilder::default() - .cli_overrides(cli_overrides.to_vec()) - .cloud_requirements(loader) - .build() - .await - { - Ok(config) => set_default_client_residency_requirement(config.enforce_residency.value()), - Err(err) => warn!( - error = %err, - "failed to sync default client residency requirement after auth refresh" - ), - } -} - -/// Derive the effective [`Config`] by layering three override sources. -/// -/// Precedence (lowest to highest): -/// - `cli_overrides`: process-wide startup `--config` flags. -/// - `request_overrides`: per-request dotted-path overrides (`params.config`), converted JSON->TOML. -/// - `typesafe_overrides`: Request objects such as `NewThreadParams` and -/// `ThreadStartParams` support a limited set of _explicit_ config overrides, so -/// `typesafe_overrides` is a `ConfigOverrides` derived from the respective request object. -/// Because the overrides are defined explicitly in the `*Params`, this takes priority over -/// the more general "bag of config options" provided by `cli_overrides` and `request_overrides`. -async fn derive_config_from_params( - cli_overrides: &[(String, TomlValue)], - request_overrides: Option>, - typesafe_overrides: ConfigOverrides, - thread_config_loader: Arc, - cloud_requirements: &CloudRequirementsLoader, - codex_home: &Path, - runtime_feature_enablement: &BTreeMap, -) -> std::io::Result { - let merged_cli_overrides = cli_overrides - .iter() - .cloned() - .chain( - request_overrides - .unwrap_or_default() - .into_iter() - .map(|(k, v)| (k, json_to_toml(v))), - ) - .collect::>(); - - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(codex_home.to_path_buf()) - .cli_overrides(merged_cli_overrides) - .harness_overrides(typesafe_overrides) - .cloud_requirements(cloud_requirements.clone()) - .thread_config_loader(thread_config_loader) - .build() - .await?; - apply_runtime_feature_enablement(&mut config, runtime_feature_enablement); - Ok(config) -} - -async fn derive_config_for_cwd( - cli_overrides: &[(String, TomlValue)], - request_overrides: Option>, - typesafe_overrides: ConfigOverrides, - cwd: Option, - cloud_requirements: &CloudRequirementsLoader, - codex_home: &Path, - runtime_feature_enablement: &BTreeMap, -) -> std::io::Result { - let merged_cli_overrides = cli_overrides - .iter() - .cloned() - .chain( - request_overrides - .unwrap_or_default() - .into_iter() - .map(|(k, v)| (k, json_to_toml(v))), - ) - .collect::>(); - - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(codex_home.to_path_buf()) - .cli_overrides(merged_cli_overrides) - .harness_overrides(typesafe_overrides) - .fallback_cwd(cwd) - .cloud_requirements(cloud_requirements.clone()) - .build() - .await?; - apply_runtime_feature_enablement(&mut config, runtime_feature_enablement); - Ok(config) -} - async fn read_history_cwd_from_state_db( config: &Config, thread_id: Option, @@ -9891,6 +9668,32 @@ fn thread_store_archive_error(operation: &str, err: ThreadStoreError) -> JSONRPC } } +const MCP_TOOL_THREAD_ID_META_KEY: &str = "threadId"; + +fn with_mcp_tool_call_thread_id_meta( + meta: Option, + thread_id: &str, +) -> Option { + match meta { + Some(serde_json::Value::Object(mut map)) => { + map.insert( + MCP_TOOL_THREAD_ID_META_KEY.to_string(), + serde_json::Value::String(thread_id.to_string()), + ); + Some(serde_json::Value::Object(map)) + } + None => { + let mut map = serde_json::Map::new(); + map.insert( + MCP_TOOL_THREAD_ID_META_KEY.to_string(), + serde_json::Value::String(thread_id.to_string()), + ); + Some(serde_json::Value::Object(map)) + } + other => other, + } +} + fn summary_from_stored_thread( thread: StoredThread, fallback_provider: &str, @@ -10523,6 +10326,8 @@ mod tests { use codex_config::SessionThreadConfig; use codex_config::StaticThreadConfigLoader; use codex_config::ThreadConfigSource; + use codex_core::config_loader::CloudRequirementsLoader; + use codex_core::config_loader::LoaderOverrides; use codex_model_provider_info::ModelProviderInfo; use codex_model_provider_info::WireApi; use codex_protocol::ThreadId; @@ -10536,6 +10341,7 @@ mod tests { use codex_utils_absolute_path::test_support::test_path_buf; use pretty_assertions::assert_eq; use serde_json::json; + use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Arc; use tempfile::TempDir; @@ -10811,21 +10617,12 @@ mod tests { requires_openai_auth: false, supports_websockets: true, }; - let config = derive_config_from_params( - &[], - Some(HashMap::from([ - ("model_provider".to_string(), json!("request")), - ("features.plugins".to_string(), json!(true)), - ( - "model_providers.session".to_string(), - json!({ - "name": "request", - "base_url": "http://127.0.0.1:9999/api/codex", - "wire_api": "responses", - }), - ), - ])), - ConfigOverrides::default(), + let config_manager = ConfigManager::new( + temp_dir.path().to_path_buf(), + Vec::new(), + LoaderOverrides::default(), + CloudRequirementsLoader::default(), + Arg0DispatchPaths::default(), Arc::new(StaticThreadConfigLoader::new(vec![ ThreadConfigSource::Session(SessionThreadConfig { model_provider: Some("session".to_string()), @@ -10836,11 +10633,24 @@ mod tests { features: BTreeMap::from([("plugins".to_string(), false)]), }), ])), - &CloudRequirementsLoader::default(), - temp_dir.path(), - &BTreeMap::new(), - ) - .await?; + ); + let config = config_manager + .load_with_overrides( + Some(HashMap::from([ + ("model_provider".to_string(), json!("request")), + ("features.plugins".to_string(), json!(true)), + ( + "model_providers.session".to_string(), + json!({ + "name": "request", + "base_url": "http://127.0.0.1:9999/api/codex", + "wire_api": "responses", + }), + ), + ])), + ConfigOverrides::default(), + ) + .await?; assert_eq!(config.model_provider_id, "session"); assert_eq!(config.model_provider, session_provider); diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index c57d3893c1..5fac8d8386 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -1,3 +1,5 @@ +use crate::config_manager::ConfigManager; +use crate::config_manager_service::ConfigManagerError; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use async_trait::async_trait; @@ -19,11 +21,7 @@ use codex_app_server_protocol::NetworkUnixSocketPermission; use codex_app_server_protocol::SandboxMode; use codex_core::ThreadManager; use codex_core::config::Config; -use codex_core::config::ConfigService; -use codex_core::config::ConfigServiceError; -use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::ConfigRequirementsToml; -use codex_core::config_loader::LoaderOverrides; use codex_core::config_loader::ResidencyRequirement as CoreResidencyRequirement; use codex_core::config_loader::SandboxModeRequirement as CoreSandboxModeRequirement; use codex_core::plugins::PluginId; @@ -34,12 +32,8 @@ use codex_features::feature_for_key; use codex_protocol::config_types::WebSearchMode; use codex_protocol::protocol::Op; use serde_json::json; -use std::collections::BTreeMap; -use std::collections::BTreeSet; use std::path::PathBuf; use std::sync::Arc; -use std::sync::RwLock; -use toml::Value as TomlValue; use tracing::warn; const SUPPORTED_EXPERIMENTAL_FEATURE_ENABLEMENT: &[&str] = &[ @@ -72,86 +66,36 @@ impl UserConfigReloader for ThreadManager { #[derive(Clone)] pub(crate) struct ConfigApi { - codex_home: PathBuf, - cli_overrides: Arc>>, - runtime_feature_enablement: Arc>>, - loader_overrides: LoaderOverrides, - cloud_requirements: Arc>, + config_manager: ConfigManager, user_config_reloader: Arc, analytics_events_client: AnalyticsEventsClient, } impl ConfigApi { pub(crate) fn new( - codex_home: PathBuf, - cli_overrides: Arc>>, - runtime_feature_enablement: Arc>>, - loader_overrides: LoaderOverrides, - cloud_requirements: Arc>, + config_manager: ConfigManager, user_config_reloader: Arc, analytics_events_client: AnalyticsEventsClient, ) -> Self { Self { - codex_home, - cli_overrides, - runtime_feature_enablement, - loader_overrides, - cloud_requirements, + config_manager, user_config_reloader, analytics_events_client, } } - fn config_service(&self) -> ConfigService { - ConfigService::new( - self.codex_home.clone(), - self.current_cli_overrides(), - self.loader_overrides.clone(), - self.current_cloud_requirements(), - codex_config::host_name(), - ) - } - - fn current_cli_overrides(&self) -> Vec<(String, TomlValue)> { - self.cli_overrides - .read() - .map(|guard| guard.clone()) - .unwrap_or_default() - } - - fn current_runtime_feature_enablement(&self) -> BTreeMap { - self.runtime_feature_enablement - .read() - .map(|guard| guard.clone()) - .unwrap_or_default() - } - - fn current_cloud_requirements(&self) -> CloudRequirementsLoader { - self.cloud_requirements - .read() - .map(|guard| guard.clone()) - .unwrap_or_default() - } - pub(crate) async fn load_latest_config( &self, fallback_cwd: Option, ) -> Result { - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(self.codex_home.clone()) - .cli_overrides(self.current_cli_overrides()) - .loader_overrides(self.loader_overrides.clone()) - .fallback_cwd(fallback_cwd) - .cloud_requirements(self.current_cloud_requirements()) - .build() + self.config_manager + .load_latest_config(fallback_cwd) .await .map_err(|err| JSONRPCErrorError { code: INTERNAL_ERROR_CODE, message: format!("failed to resolve feature override precedence: {err}"), data: None, - })?; - apply_runtime_feature_enablement(&mut config, &self.current_runtime_feature_enablement()); - Ok(config) + }) } pub(crate) async fn read( @@ -159,11 +103,7 @@ impl ConfigApi { params: ConfigReadParams, ) -> Result { let fallback_cwd = params.cwd.as_ref().map(PathBuf::from); - let mut response = self - .config_service() - .read(params) - .await - .map_err(map_error)?; + let mut response = self.config_manager.read(params).await.map_err(map_error)?; let config = self.load_latest_config(fallback_cwd).await?; for feature_key in SUPPORTED_EXPERIMENTAL_FEATURE_ENABLEMENT { let Some(feature) = feature_for_key(feature_key) else { @@ -191,7 +131,7 @@ impl ConfigApi { &self, ) -> Result { let requirements = self - .config_service() + .config_manager .read_requirements() .await .map_err(map_error)? @@ -207,7 +147,7 @@ impl ConfigApi { let pending_changes = collect_plugin_enabled_candidates([(¶ms.key_path, ¶ms.value)].into_iter()); let response = self - .config_service() + .config_manager .write_value(params) .await .map_err(map_error)?; @@ -227,7 +167,7 @@ impl ConfigApi { .map(|edit| (&edit.key_path, &edit.value)), ); let response = self - .config_service() + .config_manager .batch_write(params) .await .map_err(map_error)?; @@ -278,21 +218,17 @@ impl ConfigApi { return Ok(ExperimentalFeatureEnablementSetResponse { enablement }); } - { - let mut runtime_feature_enablement = - self.runtime_feature_enablement - .write() - .map_err(|_| JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "failed to update feature enablement".to_string(), - data: None, - })?; - runtime_feature_enablement.extend( + self.config_manager + .extend_runtime_feature_enablement( enablement .iter() .map(|(name, enabled)| (name.clone(), *enabled)), - ); - } + ) + .map_err(|_| JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: "failed to update feature enablement".to_string(), + data: None, + })?; self.load_latest_config(/*fallback_cwd*/ None).await?; self.user_config_reloader.reload_user_config().await; @@ -309,7 +245,8 @@ impl ConfigApi { continue; }; let metadata = - installed_plugin_telemetry_metadata(self.codex_home.as_path(), &plugin_id).await; + installed_plugin_telemetry_metadata(self.config_manager.codex_home(), &plugin_id) + .await; if enabled { self.analytics_events_client.track_plugin_enabled(metadata); } else { @@ -319,49 +256,6 @@ impl ConfigApi { } } -pub(crate) fn protected_feature_keys( - config_layer_stack: &codex_core::config_loader::ConfigLayerStack, -) -> BTreeSet { - let mut protected_features = config_layer_stack - .effective_config() - .get("features") - .and_then(toml::Value::as_table) - .map(|features| features.keys().cloned().collect::>()) - .unwrap_or_default(); - - if let Some(feature_requirements) = config_layer_stack - .requirements_toml() - .feature_requirements - .as_ref() - { - protected_features.extend(feature_requirements.entries.keys().cloned()); - } - - protected_features -} - -pub(crate) fn apply_runtime_feature_enablement( - config: &mut Config, - runtime_feature_enablement: &BTreeMap, -) { - let protected_features = protected_feature_keys(&config.config_layer_stack); - for (name, enabled) in runtime_feature_enablement { - if protected_features.contains(name) { - continue; - } - let Some(feature) = feature_for_key(name) else { - continue; - }; - if let Err(err) = config.features.set_enabled(feature, *enabled) { - warn!( - feature = name, - error = %err, - "failed to apply runtime feature enablement" - ); - } - } -} - fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigRequirements { ConfigRequirements { allowed_approval_policies: requirements.allowed_approval_policies.map(|policies| { @@ -495,7 +389,7 @@ fn map_network_unix_socket_permission_to_api( } } -fn map_error(err: ConfigServiceError) -> JSONRPCErrorError { +fn map_error(err: ConfigManagerError) -> JSONRPCErrorError { if let Some(code) = err.write_error_code() { return config_write_error(code, err.to_string()); } @@ -520,7 +414,11 @@ fn config_write_error(code: ConfigWriteErrorCode, message: impl Into) -> #[cfg(test)] mod tests { use super::*; + use crate::config_manager::apply_runtime_feature_enablement; use codex_analytics::AnalyticsEventsClient; + use codex_arg0::Arg0DispatchPaths; + use codex_core::config_loader::CloudRequirementsLoader; + use codex_core::config_loader::LoaderOverrides; use codex_core::config_loader::NetworkDomainPermissionToml as CoreNetworkDomainPermissionToml; use codex_core::config_loader::NetworkDomainPermissionsToml as CoreNetworkDomainPermissionsToml; use codex_core::config_loader::NetworkRequirementsToml as CoreNetworkRequirementsToml; @@ -533,9 +431,11 @@ mod tests { use codex_protocol::protocol::AskForApproval as CoreAskForApproval; use pretty_assertions::assert_eq; use serde_json::json; + use std::collections::BTreeMap; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use tempfile::TempDir; + use toml::Value as TomlValue; #[derive(Default)] struct RecordingUserConfigReloader { @@ -830,11 +730,14 @@ mod tests { ); let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test")); let config_api = ConfigApi::new( - codex_home.path().to_path_buf(), - Arc::new(RwLock::new(Vec::new())), - Arc::new(RwLock::new(BTreeMap::new())), - LoaderOverrides::default(), - Arc::new(RwLock::new(CloudRequirementsLoader::default())), + ConfigManager::new( + codex_home.path().to_path_buf(), + Vec::new(), + LoaderOverrides::default(), + CloudRequirementsLoader::default(), + Arg0DispatchPaths::default(), + Arc::new(codex_config::NoopThreadConfigLoader), + ), reloader.clone(), AnalyticsEventsClient::new( auth_manager, diff --git a/codex-rs/app-server/src/config_manager.rs b/codex-rs/app-server/src/config_manager.rs new file mode 100644 index 0000000000..69b819c152 --- /dev/null +++ b/codex-rs/app-server/src/config_manager.rs @@ -0,0 +1,333 @@ +use codex_arg0::Arg0DispatchPaths; +use codex_cloud_requirements::cloud_requirements_loader; +use codex_config::ThreadConfigLoader; +use codex_core::config::Config; +use codex_core::config::ConfigOverrides; +use codex_core::config_loader::CloudRequirementsLoader; +use codex_core::config_loader::ConfigLayerStack; +use codex_core::config_loader::LoaderOverrides; +use codex_core::config_loader::load_config_layers_state; +use codex_exec_server::LOCAL_FS; +use codex_features::feature_for_key; +use codex_login::AuthManager; +use codex_login::default_client::set_default_client_residency_requirement; +use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_json_to_toml::json_to_toml; +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::RwLock; +use toml::Value as TomlValue; +use tracing::warn; + +/// Shared app-server entry point for loading effective Codex configuration. +#[derive(Clone)] +pub(crate) struct ConfigManager { + codex_home: PathBuf, + cli_overrides: Arc>>, + runtime_feature_enablement: Arc>>, + loader_overrides: LoaderOverrides, + cloud_requirements: Arc>, + arg0_paths: Arg0DispatchPaths, + thread_config_loader: Arc, + host_name: Option, +} + +impl ConfigManager { + pub(crate) fn new( + codex_home: PathBuf, + cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, + cloud_requirements: CloudRequirementsLoader, + arg0_paths: Arg0DispatchPaths, + thread_config_loader: Arc, + ) -> Self { + Self::new_with_host_name( + codex_home, + cli_overrides, + loader_overrides, + cloud_requirements, + arg0_paths, + thread_config_loader, + codex_config::host_name(), + ) + } + + #[allow(clippy::too_many_arguments)] + fn new_with_host_name( + codex_home: PathBuf, + cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, + cloud_requirements: CloudRequirementsLoader, + arg0_paths: Arg0DispatchPaths, + thread_config_loader: Arc, + host_name: Option, + ) -> Self { + Self { + codex_home, + cli_overrides: Arc::new(RwLock::new(cli_overrides)), + runtime_feature_enablement: Arc::new(RwLock::new(BTreeMap::new())), + loader_overrides, + cloud_requirements: Arc::new(RwLock::new(cloud_requirements)), + arg0_paths, + thread_config_loader, + host_name, + } + } + + pub(crate) fn codex_home(&self) -> &Path { + self.codex_home.as_path() + } + + pub(crate) fn current_cli_overrides(&self) -> Vec<(String, TomlValue)> { + self.cli_overrides + .read() + .map(|guard| guard.clone()) + .unwrap_or_default() + } + + pub(crate) fn current_cloud_requirements(&self) -> CloudRequirementsLoader { + self.cloud_requirements + .read() + .map(|guard| guard.clone()) + .unwrap_or_default() + } + + pub(crate) fn extend_runtime_feature_enablement(&self, enablement: I) -> Result<(), ()> + where + I: IntoIterator, + { + let mut runtime_feature_enablement = + self.runtime_feature_enablement.write().map_err(|_| ())?; + runtime_feature_enablement.extend(enablement); + Ok(()) + } + + pub(crate) fn replace_cloud_requirements_loader( + &self, + auth_manager: Arc, + chatgpt_base_url: String, + ) { + let loader = + cloud_requirements_loader(auth_manager, chatgpt_base_url, self.codex_home.clone()); + if let Ok(mut guard) = self.cloud_requirements.write() { + *guard = loader; + } else { + warn!("failed to update cloud requirements loader"); + } + } + + pub(crate) async fn sync_default_client_residency_requirement(&self) { + match self.load_latest_config(/*fallback_cwd*/ None).await { + Ok(config) => { + set_default_client_residency_requirement(config.enforce_residency.value()); + } + Err(err) => warn!( + error = %err, + "failed to sync default client residency requirement after auth refresh" + ), + } + } + + pub(crate) async fn load_latest_config( + &self, + fallback_cwd: Option, + ) -> std::io::Result { + self.load_with_cli_overrides( + &self.current_cli_overrides(), + /*request_overrides*/ None, + ConfigOverrides::default(), + fallback_cwd, + ) + .await + } + + pub(crate) async fn load_default_config(&self) -> std::io::Result { + let mut config = Config::load_default_with_cli_overrides_for_codex_home( + self.codex_home.clone(), + self.current_cli_overrides(), + ) + .await?; + self.apply_runtime_feature_enablement(&mut config); + self.apply_arg0_paths(&mut config); + Ok(config) + } + + pub(crate) async fn load_with_overrides( + &self, + request_overrides: Option>, + typesafe_overrides: ConfigOverrides, + ) -> std::io::Result { + self.load_with_cli_overrides( + &self.current_cli_overrides(), + request_overrides, + typesafe_overrides, + /*fallback_cwd*/ None, + ) + .await + } + + pub(crate) async fn load_for_cwd( + &self, + request_overrides: Option>, + typesafe_overrides: ConfigOverrides, + cwd: Option, + ) -> std::io::Result { + self.load_with_cli_overrides( + &self.current_cli_overrides(), + request_overrides, + typesafe_overrides, + cwd, + ) + .await + } + + pub(crate) async fn load_with_cli_overrides( + &self, + cli_overrides: &[(String, TomlValue)], + request_overrides: Option>, + typesafe_overrides: ConfigOverrides, + fallback_cwd: Option, + ) -> std::io::Result { + let merged_cli_overrides = cli_overrides + .iter() + .cloned() + .chain( + request_overrides + .unwrap_or_default() + .into_iter() + .map(|(key, value)| (key, json_to_toml(value))), + ) + .collect::>(); + + let mut config = codex_core::config::ConfigBuilder::default() + .codex_home(self.codex_home.clone()) + .cli_overrides(merged_cli_overrides) + .loader_overrides(self.loader_overrides.clone()) + .harness_overrides(typesafe_overrides) + .fallback_cwd(fallback_cwd) + .cloud_requirements(self.current_cloud_requirements()) + .thread_config_loader(Arc::clone(&self.thread_config_loader)) + .host_name(self.host_name.clone()) + .build() + .await?; + self.apply_runtime_feature_enablement(&mut config); + self.apply_arg0_paths(&mut config); + Ok(config) + } + + pub(crate) async fn load_config_layers_for_cwd( + &self, + cwd: AbsolutePathBuf, + ) -> std::io::Result { + self.load_config_layers(Some(cwd)).await + } + + pub(crate) async fn load_config_layers( + &self, + cwd: Option, + ) -> std::io::Result { + load_config_layers_state( + LOCAL_FS.as_ref(), + &self.codex_home, + cwd, + &self.current_cli_overrides(), + self.loader_overrides.clone(), + self.current_cloud_requirements(), + self.thread_config_loader.as_ref(), + self.host_name.as_deref(), + ) + .await + } + + fn apply_runtime_feature_enablement(&self, config: &mut Config) { + apply_runtime_feature_enablement(config, &self.current_runtime_feature_enablement()); + } + + fn current_runtime_feature_enablement(&self) -> BTreeMap { + self.runtime_feature_enablement + .read() + .map(|guard| guard.clone()) + .unwrap_or_default() + } + + fn apply_arg0_paths(&self, config: &mut Config) { + config.codex_self_exe = self.arg0_paths.codex_self_exe.clone(); + config.codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone(); + config.main_execve_wrapper_exe = self.arg0_paths.main_execve_wrapper_exe.clone(); + } + + #[cfg(test)] + pub(crate) fn new_for_tests( + codex_home: PathBuf, + cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, + cloud_requirements: CloudRequirementsLoader, + host_name: Option, + ) -> Self { + Self::new_with_host_name( + codex_home, + cli_overrides, + loader_overrides, + cloud_requirements, + Arg0DispatchPaths::default(), + Arc::new(codex_config::NoopThreadConfigLoader), + host_name, + ) + } + + #[cfg(test)] + pub(crate) fn without_managed_config_for_tests(codex_home: PathBuf) -> Self { + Self::new_for_tests( + codex_home, + Vec::new(), + LoaderOverrides::without_managed_config_for_tests(), + CloudRequirementsLoader::default(), + /*host_name*/ None, + ) + } +} + +pub(crate) fn protected_feature_keys(config_layer_stack: &ConfigLayerStack) -> BTreeSet { + let mut protected_features = config_layer_stack + .effective_config() + .get("features") + .and_then(toml::Value::as_table) + .map(|features| features.keys().cloned().collect::>()) + .unwrap_or_default(); + + if let Some(feature_requirements) = config_layer_stack + .requirements_toml() + .feature_requirements + .as_ref() + { + protected_features.extend(feature_requirements.entries.keys().cloned()); + } + + protected_features +} + +pub(crate) fn apply_runtime_feature_enablement( + config: &mut Config, + runtime_feature_enablement: &BTreeMap, +) { + let protected_features = protected_feature_keys(&config.config_layer_stack); + for (name, enabled) in runtime_feature_enablement { + if protected_features.contains(name) { + continue; + } + let Some(feature) = feature_for_key(name) else { + continue; + }; + if let Err(err) = config.features.set_enabled(feature, *enabled) { + warn!( + feature = name, + error = %err, + "failed to apply runtime feature enablement" + ); + } + } +} diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/app-server/src/config_manager_service.rs similarity index 74% rename from codex-rs/core/src/config/service.rs rename to codex-rs/app-server/src/config_manager_service.rs index e9546ef4db..0104429a4b 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/app-server/src/config_manager_service.rs @@ -1,20 +1,4 @@ -use super::deserialize_config_toml_with_base; -use crate::config::edit::ConfigEdit; -use crate::config::edit::ConfigEditsBuilder; -use crate::config::managed_features::validate_explicit_feature_settings_in_config_toml; -use crate::config::managed_features::validate_feature_requirements_in_config_toml; -use crate::config_loader::CloudRequirementsLoader; -use crate::config_loader::ConfigLayerEntry; -use crate::config_loader::ConfigLayerStack; -use crate::config_loader::ConfigLayerStackOrdering; -use crate::config_loader::ConfigRequirementsToml; -use crate::config_loader::LoaderOverrides; -use crate::config_loader::load_config_layers_state; -use crate::config_loader::merge_toml_values; -use crate::path_utils; -use crate::path_utils::SymlinkWritePaths; -use crate::path_utils::resolve_symlink_write_paths; -use crate::path_utils::write_atomically; +use crate::config_manager::ConfigManager; use codex_app_server_protocol::Config as ApiConfig; use codex_app_server_protocol::ConfigBatchWriteParams; use codex_app_server_protocol::ConfigLayerMetadata; @@ -29,7 +13,19 @@ use codex_app_server_protocol::OverriddenMetadata; use codex_app_server_protocol::WriteStatus; use codex_config::CONFIG_TOML_FILE; use codex_config::config_toml::ConfigToml; -use codex_exec_server::LOCAL_FS; +use codex_core::config::deserialize_config_toml_with_base; +use codex_core::config::edit::ConfigEdit; +use codex_core::config::edit::ConfigEditsBuilder; +use codex_core::config::validate_feature_requirements_for_config_toml; +use codex_core::config_loader::ConfigLayerEntry; +use codex_core::config_loader::ConfigLayerStack; +use codex_core::config_loader::ConfigLayerStackOrdering; +use codex_core::config_loader::ConfigRequirementsToml; +use codex_core::config_loader::merge_toml_values; +use codex_core::path_utils; +use codex_core::path_utils::SymlinkWritePaths; +use codex_core::path_utils::resolve_symlink_write_paths; +use codex_core::path_utils::write_atomically; use codex_utils_absolute_path::AbsolutePathBuf; use serde_json::Value as JsonValue; use std::borrow::Cow; @@ -41,7 +37,7 @@ use toml::Value as TomlValue; use toml_edit::Item as TomlItem; #[derive(Debug, Error)] -pub enum ConfigServiceError { +pub(crate) enum ConfigManagerError { #[error("{message}")] Write { code: ConfigWriteErrorCode, @@ -77,7 +73,7 @@ pub enum ConfigServiceError { }, } -impl ConfigServiceError { +impl ConfigManagerError { fn write(code: ConfigWriteErrorCode, message: impl Into) -> Self { Self::Write { code, @@ -101,7 +97,7 @@ impl ConfigServiceError { Self::Anyhow { context, source } } - pub fn write_error_code(&self) -> Option { + pub(crate) fn write_error_code(&self) -> Option { match self { Self::Write { code, .. } => Some(code.clone()), _ => None, @@ -109,78 +105,22 @@ impl ConfigServiceError { } } -#[derive(Clone)] -pub struct ConfigService { - codex_home: PathBuf, - cli_overrides: Vec<(String, TomlValue)>, - loader_overrides: LoaderOverrides, - cloud_requirements: CloudRequirementsLoader, - host_name: Option, -} - -impl ConfigService { - pub fn new( - codex_home: PathBuf, - cli_overrides: Vec<(String, TomlValue)>, - loader_overrides: LoaderOverrides, - cloud_requirements: CloudRequirementsLoader, - host_name: Option, - ) -> Self { - Self { - codex_home, - cli_overrides, - loader_overrides, - cloud_requirements, - host_name, - } - } - - pub fn new_with_defaults(codex_home: PathBuf) -> Self { - Self { - codex_home, - cli_overrides: Vec::new(), - loader_overrides: LoaderOverrides::default(), - cloud_requirements: CloudRequirementsLoader::default(), - host_name: codex_config::host_name(), - } - } - - #[cfg(test)] - pub(crate) fn without_managed_config_for_tests(codex_home: PathBuf) -> Self { - Self::new( - codex_home, - Vec::new(), - LoaderOverrides::without_managed_config_for_tests(), - CloudRequirementsLoader::default(), - /*host_name*/ None, - ) - } - - pub async fn read( +impl ConfigManager { + pub(crate) async fn read( &self, params: ConfigReadParams, - ) -> Result { + ) -> Result { let layers = match params.cwd.as_deref() { Some(cwd) => { let cwd = AbsolutePathBuf::try_from(PathBuf::from(cwd)).map_err(|err| { - ConfigServiceError::io("failed to resolve config cwd to an absolute path", err) + ConfigManagerError::io("failed to resolve config cwd to an absolute path", err) })?; - crate::config::ConfigBuilder::default() - .codex_home(self.codex_home.clone()) - .cli_overrides(self.cli_overrides.clone()) - .loader_overrides(self.loader_overrides.clone()) - .fallback_cwd(Some(cwd.to_path_buf())) - .cloud_requirements(self.cloud_requirements.clone()) - .host_name(self.host_name.clone()) - .build() - .await - .map_err(|err| { - ConfigServiceError::io("failed to read configuration layers", err) - })? - .config_layer_stack + self.load_config_layers(Some(cwd)).await.map_err(|err| { + ConfigManagerError::io("failed to read configuration layers", err) + })? } None => self.load_thread_agnostic_config().await.map_err(|err| { - ConfigServiceError::io("failed to read configuration layers", err) + ConfigManagerError::io("failed to read configuration layers", err) })?, }; @@ -188,12 +128,12 @@ impl ConfigService { let effective_config_toml: ConfigToml = effective .try_into() - .map_err(|err| ConfigServiceError::toml("invalid configuration", err))?; + .map_err(|err| ConfigManagerError::toml("invalid configuration", err))?; let json_value = serde_json::to_value(&effective_config_toml) - .map_err(|err| ConfigServiceError::json("failed to serialize configuration", err))?; + .map_err(|err| ConfigManagerError::json("failed to serialize configuration", err))?; let config: ApiConfig = serde_json::from_value(json_value) - .map_err(|err| ConfigServiceError::json("failed to deserialize configuration", err))?; + .map_err(|err| ConfigManagerError::json("failed to deserialize configuration", err))?; Ok(ConfigReadResponse { config, @@ -211,13 +151,13 @@ impl ConfigService { }) } - pub async fn read_requirements( + pub(crate) async fn read_requirements( &self, - ) -> Result, ConfigServiceError> { + ) -> Result, ConfigManagerError> { let layers = self .load_thread_agnostic_config() .await - .map_err(|err| ConfigServiceError::io("failed to read configuration layers", err))?; + .map_err(|err| ConfigManagerError::io("failed to read configuration layers", err))?; let requirements = layers.requirements_toml().clone(); if requirements.is_empty() { @@ -227,19 +167,19 @@ impl ConfigService { } } - pub async fn write_value( + pub(crate) async fn write_value( &self, params: ConfigValueWriteParams, - ) -> Result { + ) -> Result { let edits = vec![(params.key_path, params.value, params.merge_strategy)]; self.apply_edits(params.file_path, params.expected_version, edits) .await } - pub async fn batch_write( + pub(crate) async fn batch_write( &self, params: ConfigBatchWriteParams, - ) -> Result { + ) -> Result { let edits = params .edits .into_iter() @@ -250,37 +190,22 @@ impl ConfigService { .await } - pub async fn load_user_saved_config( - &self, - ) -> Result { - let layers = self - .load_thread_agnostic_config() - .await - .map_err(|err| ConfigServiceError::io("failed to load configuration", err))?; - - let toml_value = layers.effective_config(); - let cfg: ConfigToml = toml_value - .try_into() - .map_err(|err| ConfigServiceError::toml("failed to parse config.toml", err))?; - Ok(cfg.into()) - } - async fn apply_edits( &self, file_path: Option, expected_version: Option, edits: Vec<(String, JsonValue, MergeStrategy)>, - ) -> Result { + ) -> Result { let allowed_path = - AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, &self.codex_home); + AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, self.codex_home()); let provided_path = match file_path { Some(path) => AbsolutePathBuf::from_absolute_path(PathBuf::from(path)) - .map_err(|err| ConfigServiceError::io("failed to resolve user config path", err))?, + .map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?, None => allowed_path.clone(), }; if !paths_match(&allowed_path, &provided_path) { - return Err(ConfigServiceError::write( + return Err(ConfigManagerError::write( ConfigWriteErrorCode::ConfigLayerReadonly, "Only writes to the user config are allowed", )); @@ -289,7 +214,7 @@ impl ConfigService { let layers = self .load_thread_agnostic_config() .await - .map_err(|err| ConfigServiceError::io("failed to load configuration", err))?; + .map_err(|err| ConfigManagerError::io("failed to load configuration", err))?; let user_layer = match layers.get_user_layer() { Some(layer) => Cow::Borrowed(layer), None => Cow::Owned(create_empty_user_layer(&allowed_path).await?), @@ -298,7 +223,7 @@ impl ConfigService { if let Some(expected) = expected_version.as_deref() && expected != user_layer.version { - return Err(ConfigServiceError::write( + return Err(ConfigManagerError::write( ConfigWriteErrorCode::ConfigVersionConflict, "Configuration was modified since last read. Fetch latest version and retry.", )); @@ -310,20 +235,20 @@ impl ConfigService { for (key_path, value, strategy) in edits.into_iter() { let segments = parse_key_path(&key_path).map_err(|message| { - ConfigServiceError::write(ConfigWriteErrorCode::ConfigValidationError, message) + ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message) })?; let original_value = value_at_path(&user_config, &segments).cloned(); let parsed_value = parse_value(value).map_err(|message| { - ConfigServiceError::write(ConfigWriteErrorCode::ConfigValidationError, message) + ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message) })?; apply_merge(&mut user_config, &segments, parsed_value.as_ref(), strategy).map_err( |err| match err { - MergeError::PathNotFound => ConfigServiceError::write( + MergeError::PathNotFound => ConfigManagerError::write( ConfigWriteErrorCode::ConfigPathNotFound, "Path not found", ), - MergeError::Validation(message) => ConfigServiceError::write( + MergeError::Validation(message) => ConfigManagerError::write( ConfigWriteErrorCode::ConfigValidationError, message, ), @@ -336,7 +261,7 @@ impl ConfigService { Some(value) => ConfigEdit::SetPath { segments: segments.clone(), value: toml_value_to_item(&value).map_err(|err| { - ConfigServiceError::anyhow("failed to build config edits", err) + ConfigManagerError::anyhow("failed to build config edits", err) })?, }, None => ConfigEdit::ClearPath { @@ -350,56 +275,45 @@ impl ConfigService { } validate_config(&user_config).map_err(|err| { - ConfigServiceError::write( + ConfigManagerError::write( ConfigWriteErrorCode::ConfigValidationError, format!("Invalid configuration: {err}"), ) })?; let user_config_toml = - deserialize_config_toml_with_base(user_config.clone(), &self.codex_home).map_err( + deserialize_config_toml_with_base(user_config.clone(), self.codex_home()).map_err( |err| { - ConfigServiceError::write( + ConfigManagerError::write( ConfigWriteErrorCode::ConfigValidationError, format!("Invalid configuration: {err}"), ) }, )?; - validate_explicit_feature_settings_in_config_toml( + validate_feature_requirements_for_config_toml( &user_config_toml, layers.requirements().feature_requirements.as_ref(), ) .map_err(|err| { - ConfigServiceError::write( + ConfigManagerError::write( ConfigWriteErrorCode::ConfigValidationError, format!("Invalid configuration: {err}"), ) })?; - validate_feature_requirements_in_config_toml( - &user_config_toml, - layers.requirements().feature_requirements.as_ref(), - ) - .map_err(|err| { - ConfigServiceError::write( - ConfigWriteErrorCode::ConfigValidationError, - format!("Invalid configuration: {err}"), - ) - })?; - let updated_layers = layers.with_user_config(&provided_path, user_config.clone()); let effective = updated_layers.effective_config(); validate_config(&effective).map_err(|err| { - ConfigServiceError::write( + ConfigManagerError::write( ConfigWriteErrorCode::ConfigValidationError, format!("Invalid configuration: {err}"), ) })?; if !config_edits.is_empty() { - ConfigEditsBuilder::new(&self.codex_home) + ConfigEditsBuilder::new(self.codex_home()) .with_edits(config_edits) .apply() .await - .map_err(|err| ConfigServiceError::anyhow("failed to persist config.toml", err))?; + .map_err(|err| ConfigManagerError::anyhow("failed to persist config.toml", err))?; } let overridden = first_overridden_edit(&updated_layers, &effective, &parsed_segments); @@ -413,7 +327,7 @@ impl ConfigService { version: updated_layers .get_user_layer() .ok_or_else(|| { - ConfigServiceError::write( + ConfigManagerError::write( ConfigWriteErrorCode::UserLayerNotFound, "user layer not found in updated layers", ) @@ -429,40 +343,29 @@ impl ConfigService { /// include any in-repo .codex/ folders because there is no cwd/project root /// associated with this query. async fn load_thread_agnostic_config(&self) -> std::io::Result { - let cwd: Option = None; - load_config_layers_state( - LOCAL_FS.as_ref(), - &self.codex_home, - cwd, - &self.cli_overrides, - self.loader_overrides.clone(), - self.cloud_requirements.clone(), - &codex_config::NoopThreadConfigLoader, - self.host_name.as_deref(), - ) - .await + self.load_config_layers(/*cwd*/ None).await } } async fn create_empty_user_layer( config_toml: &AbsolutePathBuf, -) -> Result { +) -> Result { let SymlinkWritePaths { read_path, write_path, } = resolve_symlink_write_paths(config_toml.as_path()) - .map_err(|err| ConfigServiceError::io("failed to resolve user config path", err))?; + .map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?; let toml_value = match read_path { Some(path) => match tokio::fs::read_to_string(&path).await { Ok(contents) => toml::from_str(&contents).map_err(|e| { - ConfigServiceError::toml("failed to parse existing user config.toml", e) + ConfigManagerError::toml("failed to parse existing user config.toml", e) })?, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { write_empty_user_config(write_path.clone()).await?; TomlValue::Table(toml::map::Map::new()) } Err(err) => { - return Err(ConfigServiceError::io( + return Err(ConfigManagerError::io( "failed to read user config.toml", err, )); @@ -481,11 +384,11 @@ async fn create_empty_user_layer( )) } -async fn write_empty_user_config(write_path: PathBuf) -> Result<(), ConfigServiceError> { +async fn write_empty_user_config(write_path: PathBuf) -> Result<(), ConfigManagerError> { task::spawn_blocking(move || write_atomically(&write_path, "")) .await - .map_err(|err| ConfigServiceError::anyhow("config persistence task panicked", err.into()))? - .map_err(|err| ConfigServiceError::io("failed to create empty user config.toml", err)) + .map_err(|err| ConfigManagerError::anyhow("config persistence task panicked", err.into()))? + .map_err(|err| ConfigManagerError::io("failed to create empty user config.toml", err)) } fn parse_value(value: JsonValue) -> Result, String> { @@ -746,5 +649,5 @@ fn find_effective_layer( } #[cfg(test)] -#[path = "service_tests.rs"] +#[path = "config_manager_service_tests.rs"] mod tests; diff --git a/codex-rs/core/src/config/service_tests.rs b/codex-rs/app-server/src/config_manager_service_tests.rs similarity index 95% rename from codex-rs/core/src/config/service_tests.rs rename to codex-rs/app-server/src/config_manager_service_tests.rs index ceb801c456..a871d8e43f 100644 --- a/codex-rs/core/src/config/service_tests.rs +++ b/codex-rs/app-server/src/config_manager_service_tests.rs @@ -4,6 +4,9 @@ use codex_app_server_protocol::AppConfig; use codex_app_server_protocol::AppToolApproval; use codex_app_server_protocol::AppsConfig; use codex_app_server_protocol::AskForApproval; +use codex_core::config_loader::CloudRequirementsLoader; +use codex_core::config_loader::FeatureRequirementsToml; +use codex_core::config_loader::LoaderOverrides; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use std::collections::BTreeMap; @@ -74,7 +77,7 @@ unified_exec = true "#; std::fs::write(tmp.path().join(CONFIG_TOML_FILE), original)?; - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -108,7 +111,7 @@ async fn write_value_supports_nested_app_paths() -> Result<()> { let tmp = tempdir().expect("tempdir"); std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "")?; - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -172,7 +175,7 @@ async fn write_value_supports_custom_mcp_server_default_tool_approval_mode() -> "[mcp_servers.docs]\ncommand = \"docs-server\"\n", )?; - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -218,7 +221,7 @@ async fn read_includes_origins_and_layers() { std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file"); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()), @@ -297,7 +300,7 @@ writable_roots = ["~/code"] ), ); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], loader_overrides, @@ -338,7 +341,7 @@ async fn write_value_reports_override() { std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file"); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()), @@ -388,7 +391,7 @@ async fn version_conflict_rejected() { let user_path = tmp.path().join(CONFIG_TOML_FILE); std::fs::write(&user_path, "model = \"user\"").unwrap(); - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); let error = service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -411,7 +414,7 @@ async fn write_value_defaults_to_user_config_path() { let tmp = tempdir().expect("tempdir"); std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: None, @@ -438,7 +441,7 @@ async fn invalid_user_value_rejected_even_if_overridden_by_managed() { let managed_path = tmp.path().join("managed_config.toml"); std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()), @@ -471,7 +474,7 @@ async fn reserved_builtin_provider_override_rejected() { let tmp = tempdir().expect("tempdir"); std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "model = \"user\"\n").unwrap(); - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); let error = service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -499,13 +502,13 @@ async fn write_value_rejects_feature_requirement_conflict() { let tmp = tempdir().expect("tempdir"); std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], LoaderOverrides::without_managed_config_for_tests(), CloudRequirementsLoader::new(async { Ok(Some(ConfigRequirementsToml { - feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + feature_requirements: Some(FeatureRequirementsToml { entries: BTreeMap::from([("personality".to_string(), true)]), }), ..Default::default() @@ -546,13 +549,13 @@ async fn write_value_rejects_profile_feature_requirement_conflict() { let tmp = tempdir().expect("tempdir"); std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], LoaderOverrides::without_managed_config_for_tests(), CloudRequirementsLoader::new(async { Ok(Some(ConfigRequirementsToml { - feature_requirements: Some(crate::config_loader::FeatureRequirementsToml { + feature_requirements: Some(FeatureRequirementsToml { entries: BTreeMap::from([("personality".to_string(), true)]), }), ..Default::default() @@ -604,7 +607,7 @@ async fn read_reports_managed_overrides_user_and_session_flags() { TomlValue::String("session".to_string()), )]; - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), cli_overrides, LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()), @@ -658,7 +661,7 @@ async fn write_value_reports_managed_override() { std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file"); - let service = ConfigService::new( + let service = ConfigManager::new_for_tests( tmp.path().to_path_buf(), vec![], LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()), @@ -714,7 +717,7 @@ alpha = "a" std::fs::write(&path, base)?; - let service = ConfigService::without_managed_config_for_tests(tmp.path().to_path_buf()); + let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: Some(path.display().to_string()), diff --git a/codex-rs/app-server/src/device_key_api.rs b/codex-rs/app-server/src/device_key_api.rs new file mode 100644 index 0000000000..beead123b0 --- /dev/null +++ b/codex-rs/app-server/src/device_key_api.rs @@ -0,0 +1,226 @@ +use crate::error_code::INTERNAL_ERROR_CODE; +use crate::error_code::INVALID_REQUEST_ERROR_CODE; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use codex_app_server_protocol::DeviceKeyAlgorithm; +use codex_app_server_protocol::DeviceKeyCreateParams; +use codex_app_server_protocol::DeviceKeyCreateResponse; +use codex_app_server_protocol::DeviceKeyProtectionClass; +use codex_app_server_protocol::DeviceKeyPublicParams; +use codex_app_server_protocol::DeviceKeyPublicResponse; +use codex_app_server_protocol::DeviceKeySignParams; +use codex_app_server_protocol::DeviceKeySignPayload; +use codex_app_server_protocol::DeviceKeySignResponse; +use codex_app_server_protocol::JSONRPCErrorError; +use codex_device_key::DeviceKeyBinding; +use codex_device_key::DeviceKeyCreateRequest; +use codex_device_key::DeviceKeyError; +use codex_device_key::DeviceKeyGetPublicRequest; +use codex_device_key::DeviceKeyInfo; +use codex_device_key::DeviceKeyProtectionPolicy; +use codex_device_key::DeviceKeySignRequest; +use codex_device_key::DeviceKeyStore; +use codex_device_key::RemoteControlClientConnectionAudience; +use codex_device_key::RemoteControlClientConnectionSignPayload; +use codex_device_key::RemoteControlClientEnrollmentAudience; +use codex_device_key::RemoteControlClientEnrollmentSignPayload; + +#[derive(Clone, Default)] +pub(crate) struct DeviceKeyApi { + store: DeviceKeyStore, +} + +impl DeviceKeyApi { + pub(crate) fn create( + &self, + params: DeviceKeyCreateParams, + ) -> Result { + let info = self + .store + .create(DeviceKeyCreateRequest { + protection_policy: protection_policy_from_params(params.protection_policy), + binding: DeviceKeyBinding { + account_user_id: params.account_user_id, + client_id: params.client_id, + }, + }) + .map_err(map_device_key_error)?; + Ok(create_response_from_info(info)) + } + + pub(crate) fn public( + &self, + params: DeviceKeyPublicParams, + ) -> Result { + let info = self + .store + .get_public(DeviceKeyGetPublicRequest { + key_id: params.key_id, + }) + .map_err(map_device_key_error)?; + Ok(public_response_from_info(info)) + } + + pub(crate) fn sign( + &self, + params: DeviceKeySignParams, + ) -> Result { + let signature = self + .store + .sign(DeviceKeySignRequest { + key_id: params.key_id, + payload: payload_from_params(params.payload), + }) + .map_err(map_device_key_error)?; + Ok(DeviceKeySignResponse { + signature_der_base64: STANDARD.encode(signature.signature_der), + signed_payload_base64: STANDARD.encode(signature.signed_payload), + algorithm: algorithm_from_store(signature.algorithm), + }) + } +} + +fn create_response_from_info(info: DeviceKeyInfo) -> DeviceKeyCreateResponse { + DeviceKeyCreateResponse { + key_id: info.key_id, + public_key_spki_der_base64: STANDARD.encode(info.public_key_spki_der), + algorithm: algorithm_from_store(info.algorithm), + protection_class: protection_class_from_store(info.protection_class), + } +} + +fn public_response_from_info(info: DeviceKeyInfo) -> DeviceKeyPublicResponse { + DeviceKeyPublicResponse { + key_id: info.key_id, + public_key_spki_der_base64: STANDARD.encode(info.public_key_spki_der), + algorithm: algorithm_from_store(info.algorithm), + protection_class: protection_class_from_store(info.protection_class), + } +} + +fn protection_policy_from_params( + protection_policy: Option, +) -> DeviceKeyProtectionPolicy { + match protection_policy + .unwrap_or(codex_app_server_protocol::DeviceKeyProtectionPolicy::HardwareOnly) + { + codex_app_server_protocol::DeviceKeyProtectionPolicy::HardwareOnly => { + DeviceKeyProtectionPolicy::HardwareOnly + } + codex_app_server_protocol::DeviceKeyProtectionPolicy::AllowOsProtectedNonextractable => { + DeviceKeyProtectionPolicy::AllowOsProtectedNonextractable + } + } +} + +fn payload_from_params(payload: DeviceKeySignPayload) -> codex_device_key::DeviceKeySignPayload { + match payload { + DeviceKeySignPayload::RemoteControlClientConnection { + nonce, + audience, + session_id, + target_origin, + target_path, + account_user_id, + client_id, + token_sha256_base64url, + token_expires_at, + scopes, + } => codex_device_key::DeviceKeySignPayload::RemoteControlClientConnection( + RemoteControlClientConnectionSignPayload { + nonce, + audience: remote_control_client_connection_audience_from_protocol(audience), + session_id, + target_origin, + target_path, + account_user_id, + client_id, + token_sha256_base64url, + token_expires_at, + scopes, + }, + ), + DeviceKeySignPayload::RemoteControlClientEnrollment { + nonce, + audience, + challenge_id, + target_origin, + target_path, + account_user_id, + client_id, + device_identity_sha256_base64url, + challenge_expires_at, + } => codex_device_key::DeviceKeySignPayload::RemoteControlClientEnrollment( + RemoteControlClientEnrollmentSignPayload { + nonce, + audience: remote_control_client_enrollment_audience_from_protocol(audience), + challenge_id, + target_origin, + target_path, + account_user_id, + client_id, + device_identity_sha256_base64url, + challenge_expires_at, + }, + ), + } +} + +fn remote_control_client_connection_audience_from_protocol( + audience: codex_app_server_protocol::RemoteControlClientConnectionAudience, +) -> RemoteControlClientConnectionAudience { + match audience { + codex_app_server_protocol::RemoteControlClientConnectionAudience::RemoteControlClientWebsocket => { + RemoteControlClientConnectionAudience::RemoteControlClientWebsocket + } + } +} + +fn remote_control_client_enrollment_audience_from_protocol( + audience: codex_app_server_protocol::RemoteControlClientEnrollmentAudience, +) -> RemoteControlClientEnrollmentAudience { + match audience { + codex_app_server_protocol::RemoteControlClientEnrollmentAudience::RemoteControlClientEnrollment => { + RemoteControlClientEnrollmentAudience::RemoteControlClientEnrollment + } + } +} + +fn algorithm_from_store(algorithm: codex_device_key::DeviceKeyAlgorithm) -> DeviceKeyAlgorithm { + match algorithm { + codex_device_key::DeviceKeyAlgorithm::EcdsaP256Sha256 => { + DeviceKeyAlgorithm::EcdsaP256Sha256 + } + } +} + +fn protection_class_from_store( + protection_class: codex_device_key::DeviceKeyProtectionClass, +) -> DeviceKeyProtectionClass { + match protection_class { + codex_device_key::DeviceKeyProtectionClass::HardwareSecureEnclave => { + DeviceKeyProtectionClass::HardwareSecureEnclave + } + codex_device_key::DeviceKeyProtectionClass::HardwareTpm => { + DeviceKeyProtectionClass::HardwareTpm + } + codex_device_key::DeviceKeyProtectionClass::OsProtectedNonextractable => { + DeviceKeyProtectionClass::OsProtectedNonextractable + } + } +} + +fn map_device_key_error(error: DeviceKeyError) -> JSONRPCErrorError { + let code = match error { + DeviceKeyError::DegradedProtectionNotAllowed { .. } + | DeviceKeyError::HardwareBackedKeysUnavailable + | DeviceKeyError::KeyNotFound + | DeviceKeyError::InvalidPayload(_) => INVALID_REQUEST_ERROR_CODE, + DeviceKeyError::Platform(_) | DeviceKeyError::Crypto(_) => INTERNAL_ERROR_CODE, + }; + JSONRPCErrorError { + code, + message: error.to_string(), + data: None, + } +} diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index e73124c0d3..4fe88fa277 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -50,6 +50,7 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; +use crate::config_manager::ConfigManager; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::error_code::OVERLOADED_ERROR_CODE; @@ -62,6 +63,7 @@ use crate::outgoing_message::OutgoingMessage; use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::QueuedOutgoingMessage; use crate::transport::CHANNEL_CAPACITY; +use crate::transport::ConnectionOrigin; use crate::transport::OutboundConnectionState; use crate::transport::route_outgoing_envelope; use codex_analytics::AppServerRpcTransport; @@ -390,17 +392,22 @@ fn start_uninitialized(args: InProcessStartArgs) -> InProcessClientHandle { let processor_outgoing = Arc::clone(&outgoing_message_sender); let auth_manager = AuthManager::shared_from_config(args.config.as_ref(), args.enable_codex_api_key_env); + let config_manager = ConfigManager::new( + args.config.codex_home.to_path_buf(), + args.cli_overrides, + args.loader_overrides, + args.cloud_requirements, + args.arg0_paths.clone(), + args.thread_config_loader, + ); let (processor_tx, mut processor_rx) = mpsc::channel::(channel_capacity); let mut processor_handle = tokio::spawn(async move { let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { outgoing: Arc::clone(&processor_outgoing), arg0_paths: args.arg0_paths, config: args.config, + config_manager, environment_manager: args.environment_manager, - cli_overrides: args.cli_overrides, - loader_overrides: args.loader_overrides, - cloud_requirements: args.cloud_requirements, - thread_config_loader: args.thread_config_loader, feedback: args.feedback, log_db: args.log_db, config_warnings: args.config_warnings, @@ -410,7 +417,7 @@ fn start_uninitialized(args: InProcessStartArgs) -> InProcessClientHandle { remote_control_handle: None, })); let mut thread_created_rx = processor.thread_created_receiver(); - let session = Arc::new(ConnectionSessionState::default()); + let session = Arc::new(ConnectionSessionState::new(ConnectionOrigin::InProcess)); let mut listen_for_threads = true; loop { @@ -707,6 +714,11 @@ mod tests { use super::*; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ConfigRequirementsReadResponse; + use codex_app_server_protocol::DeviceKeyPublicParams; + use codex_app_server_protocol::DeviceKeySignParams; + use codex_app_server_protocol::DeviceKeySignPayload; + use codex_app_server_protocol::RemoteControlClientConnectionAudience; + use codex_app_server_protocol::RemoteControlClientEnrollmentAudience; use codex_app_server_protocol::SessionSource as ApiSessionSource; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; @@ -780,6 +792,87 @@ mod tests { .expect("in-process runtime should shutdown cleanly"); } + #[tokio::test] + async fn in_process_allows_device_key_requests_to_reach_device_key_api() { + let client = start_test_client(SessionSource::Cli).await; + const MALFORMED_KEY_ID_MESSAGE: &str = concat!( + "invalid device key payload: keyId must be dk_hse_, dk_tpm_, or dk_osn_ ", + "followed by unpadded base64url-encoded 32 bytes" + ); + let requests = [ + ( + ClientRequest::DeviceKeyPublic { + request_id: RequestId::Integer(11), + params: DeviceKeyPublicParams { + key_id: String::new(), + }, + }, + MALFORMED_KEY_ID_MESSAGE, + ), + ( + ClientRequest::DeviceKeySign { + request_id: RequestId::Integer(12), + params: DeviceKeySignParams { + key_id: String::new(), + payload: DeviceKeySignPayload::RemoteControlClientConnection { + nonce: "nonce-123".to_string(), + audience: + RemoteControlClientConnectionAudience::RemoteControlClientWebsocket, + session_id: "wssess_123".to_string(), + target_origin: "https://chatgpt.com".to_string(), + target_path: "/api/codex/remote/control/client".to_string(), + account_user_id: "acct_123".to_string(), + client_id: "cli_123".to_string(), + token_expires_at: 4_102_444_800, + token_sha256_base64url: "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU" + .to_string(), + scopes: vec!["remote_control_controller_websocket".to_string()], + }, + }, + }, + MALFORMED_KEY_ID_MESSAGE, + ), + ( + ClientRequest::DeviceKeySign { + request_id: RequestId::Integer(13), + params: DeviceKeySignParams { + key_id: String::new(), + payload: DeviceKeySignPayload::RemoteControlClientEnrollment { + nonce: "nonce-123".to_string(), + audience: + RemoteControlClientEnrollmentAudience::RemoteControlClientEnrollment, + challenge_id: "rch_123".to_string(), + target_origin: "https://chatgpt.com".to_string(), + target_path: "/wham/remote/control/client/enroll".to_string(), + account_user_id: "acct_123".to_string(), + client_id: "cli_123".to_string(), + device_identity_sha256_base64url: + "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU".to_string(), + challenge_expires_at: 4_102_444_800, + }, + }, + }, + MALFORMED_KEY_ID_MESSAGE, + ), + ]; + + for (request, expected_message) in requests { + let error = client + .request(request) + .await + .expect("request transport should work") + .expect_err("request should be rejected"); + + assert_eq!(error.code, INVALID_REQUEST_ERROR_CODE); + assert_eq!(error.message, expected_message); + } + + client + .shutdown() + .await + .expect("in-process runtime should shutdown cleanly"); + } + #[tokio::test] async fn in_process_start_uses_requested_session_source_for_thread_start() { for (requested_source, expected_source) in [ diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 0eac54df2a..ca80ad2c99 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -1,11 +1,9 @@ #![deny(clippy::print_stdout, clippy::print_stderr)] use codex_arg0::Arg0DispatchPaths; -use codex_cloud_requirements::cloud_requirements_loader; use codex_config::NoopThreadConfigLoader; +use codex_config::ThreadConfigLoader; use codex_core::config::Config; -use codex_core::config::ConfigBuilder; -use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::ConfigLayerStackOrdering; use codex_core::config_loader::LoaderOverrides; use codex_features::Feature; @@ -19,6 +17,7 @@ use std::sync::Arc; use std::sync::RwLock; use std::sync::atomic::AtomicBool; +use crate::config_manager::ConfigManager; use crate::message_processor::MessageProcessor; use crate::message_processor::MessageProcessorArgs; use crate::outgoing_message::ConnectionId; @@ -28,11 +27,10 @@ use crate::outgoing_message::QueuedOutgoingMessage; use crate::transport::CHANNEL_CAPACITY; use crate::transport::ConnectionState; use crate::transport::OutboundConnectionState; -use crate::transport::RemoteControlStartOptions; use crate::transport::TransportEvent; use crate::transport::auth::policy_from_settings; use crate::transport::route_outgoing_envelope; -use crate::transport::start_remote_control_with_options; +use crate::transport::start_remote_control; use crate::transport::start_stdio_connection; use crate::transport::start_websocket_acceptor; use codex_analytics::AppServerRpcTransport; @@ -43,6 +41,7 @@ use codex_app_server_protocol::TextPosition as AppTextPosition; use codex_app_server_protocol::TextRange as AppTextRange; use codex_core::ExecPolicyError; use codex_core::check_execpolicy_for_warnings; +use codex_core::config::find_codex_home; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::TextRange as CoreTextRange; use codex_exec_server::EnvironmentManager; @@ -54,7 +53,6 @@ use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; -use toml::Value as TomlValue; use tracing::Level; use tracing::error; use tracing::info; @@ -72,6 +70,9 @@ mod codex_message_processor; mod command_exec; mod config; mod config_api; +mod config_manager; +mod config_manager_service; +mod device_key_api; mod dynamic_tools; mod error_code; mod external_agent_config_api; @@ -379,10 +380,18 @@ pub async fn run_main_with_transport( format!("error parsing -c overrides: {e}"), ) })?; - let cloud_requirements = match ConfigBuilder::default() - .cli_overrides(cli_kv_overrides.clone()) - .loader_overrides(loader_overrides.clone()) - .build() + let codex_home = find_codex_home()?; + let thread_config_loader: Arc = Arc::new(NoopThreadConfigLoader); + let config_manager = ConfigManager::new( + codex_home.to_path_buf(), + cli_kv_overrides.clone(), + loader_overrides, + Default::default(), + arg0_paths.clone(), + thread_config_loader.clone(), + ); + match config_manager + .load_latest_config(/*fallback_cwd*/ None) .await { Ok(config) => { @@ -405,40 +414,28 @@ pub async fn run_main_with_transport( let auth_manager = AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); - cloud_requirements_loader( - auth_manager, - config.chatgpt_base_url, - config.codex_home.to_path_buf(), - ) + config_manager.replace_cloud_requirements_loader(auth_manager, config.chatgpt_base_url); } Err(err) => { warn!(error = %err, "Failed to preload config for cloud requirements"); // TODO(gt): Make cloud requirements preload failures blocking once we can fail-closed. - CloudRequirementsLoader::default() } }; - let loader_overrides_for_config_api = loader_overrides.clone(); - let thread_config_loader = Arc::new(NoopThreadConfigLoader); let mut config_warnings = Vec::new(); - let config = match ConfigBuilder::default() - .cli_overrides(cli_kv_overrides.clone()) - .loader_overrides(loader_overrides) - .cloud_requirements(cloud_requirements.clone()) - .build() + let config = match config_manager + .load_latest_config(/*fallback_cwd*/ None) .await { Ok(config) => config, Err(err) => { let message = config_warning_from_error("Invalid configuration; using defaults.", &err); config_warnings.push(message); - Config::load_default_with_cli_overrides(cli_kv_overrides.clone()) - .await - .map_err(|e| { - std::io::Error::new( - ErrorKind::InvalidData, - format!("error loading default config after config error: {e}"), - ) - })? + config_manager.load_default_config().await.map_err(|e| { + std::io::Error::new( + ErrorKind::InvalidData, + format!("error loading default config after config error: {e}"), + ) + })? } }; @@ -579,17 +576,16 @@ pub async fn run_main_with_transport( )); } - let (remote_control_accept_handle, remote_control_handle) = - start_remote_control_with_options(RemoteControlStartOptions { - remote_control_url: config.chatgpt_base_url.clone(), - state_db: state_db.clone(), - auth_manager: auth_manager.clone(), - transport_event_tx: transport_event_tx.clone(), - shutdown_token: transport_shutdown_token.clone(), - app_server_client_name_rx, - initial_enabled: remote_control_enabled, - }) - .await?; + let (remote_control_accept_handle, remote_control_handle) = start_remote_control( + config.chatgpt_base_url.clone(), + state_db.clone(), + auth_manager.clone(), + transport_event_tx.clone(), + transport_shutdown_token.clone(), + app_server_client_name_rx, + remote_control_enabled, + ) + .await?; transport_accept_handles.push(remote_control_accept_handle); let outbound_handle = tokio::spawn(async move { @@ -652,17 +648,12 @@ pub async fn run_main_with_transport( let outbound_control_tx = outbound_control_tx; let auth_manager = AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); - let cli_overrides: Vec<(String, TomlValue)> = cli_kv_overrides.clone(); - let loader_overrides = loader_overrides_for_config_api; let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { outgoing: outgoing_message_sender, arg0_paths, config: Arc::new(config), + config_manager, environment_manager, - cli_overrides, - loader_overrides, - cloud_requirements: cloud_requirements.clone(), - thread_config_loader, feedback: feedback.clone(), log_db, config_warnings, @@ -714,6 +705,7 @@ pub async fn run_main_with_transport( match event { TransportEvent::ConnectionOpened { connection_id, + origin, writer, disconnect_sender, } => { @@ -743,6 +735,7 @@ pub async fn run_main_with_transport( connections.insert( connection_id, ConnectionState::new( + origin, outbound_initialized, outbound_experimental_api_enabled, outbound_opted_out_notification_methods, diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 2032eb61cd..2b7097c262 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -1,15 +1,15 @@ -use std::collections::BTreeMap; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; use std::sync::OnceLock; -use std::sync::RwLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use crate::codex_message_processor::CodexMessageProcessor; use crate::codex_message_processor::CodexMessageProcessorArgs; use crate::config_api::ConfigApi; +use crate::config_manager::ConfigManager; +use crate::device_key_api::DeviceKeyApi; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::external_agent_config_api::ExternalAgentConfigApi; use crate::fs_api::FsApi; @@ -19,6 +19,7 @@ use crate::outgoing_message::ConnectionRequestId; use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::RequestContext; use crate::transport::AppServerTransport; +use crate::transport::ConnectionOrigin; use crate::transport::RemoteControlHandle; use async_trait::async_trait; use axum::http::HeaderValue; @@ -36,6 +37,9 @@ use codex_app_server_protocol::ConfigBatchWriteParams; use codex_app_server_protocol::ConfigReadParams; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::ConfigWarningNotification; +use codex_app_server_protocol::DeviceKeyCreateParams; +use codex_app_server_protocol::DeviceKeyPublicParams; +use codex_app_server_protocol::DeviceKeySignParams; use codex_app_server_protocol::ExperimentalApi; use codex_app_server_protocol::ExperimentalFeatureEnablementSetParams; use codex_app_server_protocol::ExternalAgentConfigDetectParams; @@ -63,11 +67,8 @@ use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::experimental_required_message; use codex_arg0::Arg0DispatchPaths; use codex_chatgpt::connectors; -use codex_config::ThreadConfigLoader; use codex_core::ThreadManager; use codex_core::config::Config; -use codex_core::config_loader::CloudRequirementsLoader; -use codex_core::config_loader::LoaderOverrides; use codex_exec_server::EnvironmentManager; use codex_features::Feature; use codex_feedback::CodexFeedback; @@ -91,7 +92,6 @@ use tokio::sync::broadcast; use tokio::sync::watch; use tokio::time::Duration; use tokio::time::timeout; -use toml::Value as TomlValue; use tracing::Instrument; const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10); @@ -169,6 +169,7 @@ pub(crate) struct MessageProcessor { codex_message_processor: CodexMessageProcessor, thread_manager: Arc, config_api: ConfigApi, + device_key_api: DeviceKeyApi, external_agent_config_api: ExternalAgentConfigApi, fs_api: FsApi, auth_manager: Arc, @@ -180,8 +181,9 @@ pub(crate) struct MessageProcessor { remote_control_handle: Option, } -#[derive(Debug, Default)] +#[derive(Debug)] pub(crate) struct ConnectionSessionState { + origin: ConnectionOrigin, initialized: OnceLock, } @@ -193,11 +195,28 @@ struct InitializedConnectionSessionState { client_version: String, } +impl Default for ConnectionSessionState { + fn default() -> Self { + Self::new(ConnectionOrigin::WebSocket) + } +} + impl ConnectionSessionState { + pub(crate) fn new(origin: ConnectionOrigin) -> Self { + Self { + origin, + initialized: OnceLock::new(), + } + } + pub(crate) fn initialized(&self) -> bool { self.initialized.get().is_some() } + fn allows_device_key_requests(&self) -> bool { + self.origin.allows_device_key_requests() + } + pub(crate) fn experimental_api_enabled(&self) -> bool { self.initialized .get() @@ -232,11 +251,8 @@ pub(crate) struct MessageProcessorArgs { pub(crate) outgoing: Arc, pub(crate) arg0_paths: Arg0DispatchPaths, pub(crate) config: Arc, + pub(crate) config_manager: ConfigManager, pub(crate) environment_manager: Arc, - pub(crate) cli_overrides: Vec<(String, TomlValue)>, - pub(crate) loader_overrides: LoaderOverrides, - pub(crate) cloud_requirements: CloudRequirementsLoader, - pub(crate) thread_config_loader: Arc, pub(crate) feedback: CodexFeedback, pub(crate) log_db: Option, pub(crate) config_warnings: Vec, @@ -254,11 +270,8 @@ impl MessageProcessor { outgoing, arg0_paths, config, + config_manager, environment_manager, - cli_overrides, - loader_overrides, - cloud_requirements, - thread_config_loader, feedback, log_db, config_warnings, @@ -291,9 +304,6 @@ impl MessageProcessor { .plugins_manager() .set_analytics_events_client(analytics_events_client.clone()); - let cli_overrides = Arc::new(RwLock::new(cli_overrides)); - let runtime_feature_enablement = Arc::new(RwLock::new(BTreeMap::new())); - let cloud_requirements = Arc::new(RwLock::new(cloud_requirements)); let codex_message_processor = CodexMessageProcessor::new(CodexMessageProcessorArgs { auth_manager: auth_manager.clone(), thread_manager: Arc::clone(&thread_manager), @@ -301,10 +311,7 @@ impl MessageProcessor { analytics_events_client: analytics_events_client.clone(), arg0_paths, config: Arc::clone(&config), - cli_overrides: cli_overrides.clone(), - runtime_feature_enablement: runtime_feature_enablement.clone(), - cloud_requirements: cloud_requirements.clone(), - thread_config_loader, + config_manager: config_manager.clone(), feedback, log_db, }); @@ -314,14 +321,11 @@ impl MessageProcessor { .plugins_manager() .maybe_start_plugin_startup_tasks_for_config(&config, auth_manager.clone()); let config_api = ConfigApi::new( - config.codex_home.to_path_buf(), - cli_overrides, - runtime_feature_enablement, - loader_overrides, - cloud_requirements, + config_manager, thread_manager.clone(), analytics_events_client.clone(), ); + let device_key_api = DeviceKeyApi::default(); let external_agent_config_api = ExternalAgentConfigApi::new(config.codex_home.to_path_buf()); let fs_api = FsApi::default(); @@ -332,6 +336,7 @@ impl MessageProcessor { codex_message_processor, thread_manager: Arc::clone(&thread_manager), config_api, + device_key_api, external_agent_config_api, fs_api, auth_manager, @@ -769,6 +774,7 @@ impl MessageProcessor { let app_server_client_name = session.app_server_client_name().map(str::to_string); let client_version = session.client_version().map(str::to_string); + let device_key_requests_allowed = session.allows_device_key_requests(); Arc::clone(self) .handle_initialized_client_request( connection_request_id, @@ -776,6 +782,7 @@ impl MessageProcessor { request_context, app_server_client_name, client_version, + device_key_requests_allowed, ) .await; } @@ -787,6 +794,7 @@ impl MessageProcessor { request_context: RequestContext, app_server_client_name: Option, client_version: Option, + device_key_requests_allowed: bool, ) { let connection_id = connection_request_id.connection_id; @@ -861,6 +869,39 @@ impl MessageProcessor { }) .await; } + ClientRequest::DeviceKeyCreate { request_id, params } => { + self.handle_device_key_create( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + device_key_requests_allowed, + ) + .await; + } + ClientRequest::DeviceKeyPublic { request_id, params } => { + self.handle_device_key_public( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + device_key_requests_allowed, + ) + .await; + } + ClientRequest::DeviceKeySign { request_id, params } => { + self.handle_device_key_sign( + ConnectionRequestId { + connection_id, + request_id, + }, + params, + device_key_requests_allowed, + ) + .await; + } ClientRequest::FsReadFile { request_id, params } => { self.handle_fs_read_file( ConnectionRequestId { @@ -1124,6 +1165,98 @@ impl MessageProcessor { } } + async fn handle_device_key_create( + &self, + request_id: ConnectionRequestId, + params: DeviceKeyCreateParams, + device_key_requests_allowed: bool, + ) { + if self + .reject_device_key_request_over_remote_transport( + request_id.clone(), + "device/key/create", + device_key_requests_allowed, + ) + .await + { + return; + } + + match self.device_key_api.create(params) { + Ok(response) => self.outgoing.send_response(request_id, response).await, + Err(error) => self.outgoing.send_error(request_id, error).await, + } + } + + async fn handle_device_key_public( + &self, + request_id: ConnectionRequestId, + params: DeviceKeyPublicParams, + device_key_requests_allowed: bool, + ) { + if self + .reject_device_key_request_over_remote_transport( + request_id.clone(), + "device/key/public", + device_key_requests_allowed, + ) + .await + { + return; + } + + match self.device_key_api.public(params) { + Ok(response) => self.outgoing.send_response(request_id, response).await, + Err(error) => self.outgoing.send_error(request_id, error).await, + } + } + + async fn handle_device_key_sign( + &self, + request_id: ConnectionRequestId, + params: DeviceKeySignParams, + device_key_requests_allowed: bool, + ) { + if self + .reject_device_key_request_over_remote_transport( + request_id.clone(), + "device/key/sign", + device_key_requests_allowed, + ) + .await + { + return; + } + + match self.device_key_api.sign(params) { + Ok(response) => self.outgoing.send_response(request_id, response).await, + Err(error) => self.outgoing.send_error(request_id, error).await, + } + } + + async fn reject_device_key_request_over_remote_transport( + &self, + request_id: ConnectionRequestId, + method: &str, + device_key_requests_allowed: bool, + ) -> bool { + if device_key_requests_allowed { + return false; + } + + self.outgoing + .send_error( + request_id, + JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("{method} is not available over remote transports"), + data: None, + }, + ) + .await; + true + } + async fn handle_external_agent_config_detect( &self, request_id: ConnectionRequestId, 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 83f8bc98d7..bf5986f6de 100644 --- a/codex-rs/app-server/src/message_processor/tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor/tracing_tests.rs @@ -1,19 +1,25 @@ use super::ConnectionSessionState; use super::MessageProcessor; use super::MessageProcessorArgs; +use crate::config_manager::ConfigManager; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::OutgoingMessageSender; use crate::transport::AppServerTransport; +use crate::transport::ConnectionOrigin; use anyhow::Result; use app_test_support::create_mock_responses_server_repeating_assistant; use app_test_support::write_mock_responses_config_toml; use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::DeviceKeySignParams; +use codex_app_server_protocol::DeviceKeySignPayload; use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::InitializeParams; use codex_app_server_protocol::InitializeResponse; +use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::JSONRPCRequest; +use codex_app_server_protocol::RemoteControlClientConnectionAudience; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; @@ -40,6 +46,7 @@ use opentelemetry_sdk::trace::InMemorySpanExporter; use opentelemetry_sdk::trace::SdkTracerProvider; use opentelemetry_sdk::trace::SpanData; use pretty_assertions::assert_eq; +use serial_test::serial; use std::collections::BTreeMap; use std::path::Path; use std::sync::Arc; @@ -101,11 +108,6 @@ fn request_from_client_request(request: ClientRequest) -> JSONRPCRequest { .expect("client request should convert to JSON-RPC") } -fn tracing_test_guard() -> &'static tokio::sync::Mutex<()> { - static GUARD: OnceLock> = OnceLock::new(); - GUARD.get_or_init(|| tokio::sync::Mutex::new(())) -} - struct TracingHarness { _server: MockServer, _codex_home: TempDir, @@ -117,6 +119,10 @@ struct TracingHarness { impl TracingHarness { async fn new() -> Result { + Self::new_with_origin(ConnectionOrigin::WebSocket).await + } + + async fn new_with_origin(origin: ConnectionOrigin) -> Result { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; let config = Arc::new(build_test_config(codex_home.path(), &server.uri()).await?); @@ -129,7 +135,7 @@ impl TracingHarness { _codex_home: codex_home, processor, outgoing_rx, - session: Arc::new(ConnectionSessionState::default()), + session: Arc::new(ConnectionSessionState::new(origin)), tracing, }; @@ -188,6 +194,29 @@ impl TracingHarness { read_response(&mut self.outgoing_rx, request_id).await } + async fn request_error( + &mut self, + request: ClientRequest, + trace: Option, + ) -> JSONRPCErrorError { + let request_id = match request.id() { + RequestId::Integer(request_id) => *request_id, + request_id => panic!("expected integer request id in test harness, got {request_id:?}"), + }; + let mut request = request_from_client_request(request); + request.trace = trace; + + self.processor + .process_request( + TEST_CONNECTION_ID, + request, + AppServerTransport::Stdio, + Arc::clone(&self.session), + ) + .await; + read_error(&mut self.outgoing_rx, request_id).await + } + async fn start_thread( &mut self, request_id: i64, @@ -237,15 +266,20 @@ fn build_test_processor( let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let auth_manager = AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false); + let config_manager = ConfigManager::new( + config.codex_home.to_path_buf(), + Vec::new(), + LoaderOverrides::default(), + CloudRequirementsLoader::default(), + Arg0DispatchPaths::default(), + Arc::new(codex_config::NoopThreadConfigLoader), + ); let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { outgoing, arg0_paths: Arg0DispatchPaths::default(), config, + config_manager, environment_manager: Arc::new(EnvironmentManager::new(/*exec_server_url*/ None)), - cli_overrides: Vec::new(), - loader_overrides: LoaderOverrides::default(), - cloud_requirements: CloudRequirementsLoader::default(), - thread_config_loader: Arc::new(codex_config::NoopThreadConfigLoader), feedback: CodexFeedback::new(), log_db: None, config_warnings: Vec::new(), @@ -418,6 +452,36 @@ async fn read_response( } } +async fn read_error( + outgoing_rx: &mut mpsc::Receiver, + request_id: i64, +) -> JSONRPCErrorError { + loop { + let envelope = tokio::time::timeout(std::time::Duration::from_secs(5), outgoing_rx.recv()) + .await + .expect("timed out waiting for error") + .expect("outgoing channel closed"); + let crate::outgoing_message::OutgoingEnvelope::ToConnection { + connection_id, + message, + .. + } = envelope + else { + continue; + }; + if connection_id != TEST_CONNECTION_ID { + continue; + } + let crate::outgoing_message::OutgoingMessage::Error(error) = message else { + continue; + }; + if error.id != RequestId::Integer(request_id) { + continue; + } + return error.error; + } +} + async fn read_thread_started_notification( outgoing_rx: &mut mpsc::Receiver, ) { @@ -505,12 +569,8 @@ where } #[tokio::test(flavor = "current_thread")] -#[expect( - clippy::await_holding_invalid_type, - reason = "test serializes access to global tracing state for its full duration" -)] +#[serial(app_server_tracing)] async fn thread_start_jsonrpc_span_exports_server_span_and_parents_children() -> Result<()> { - let _guard = tracing_test_guard().lock().await; let mut harness = TracingHarness::new().await?; let RemoteTrace { @@ -588,12 +648,49 @@ async fn thread_start_jsonrpc_span_exports_server_span_and_parents_children() -> } #[tokio::test(flavor = "current_thread")] -#[expect( - clippy::await_holding_invalid_type, - reason = "test serializes access to global tracing state for its full duration" -)] +#[serial(app_server_tracing)] +async fn remote_control_origin_rejects_device_key_requests() -> Result<()> { + let mut harness = TracingHarness::new_with_origin(ConnectionOrigin::RemoteControl).await?; + + let error = harness + .request_error( + ClientRequest::DeviceKeySign { + request_id: RequestId::Integer(20_004), + params: DeviceKeySignParams { + key_id: "dk_123".to_string(), + payload: DeviceKeySignPayload::RemoteControlClientConnection { + nonce: "nonce-123".to_string(), + audience: + RemoteControlClientConnectionAudience::RemoteControlClientWebsocket, + session_id: "wssess_123".to_string(), + target_origin: "https://chatgpt.com".to_string(), + target_path: "/api/codex/remote/control/client".to_string(), + account_user_id: "acct_123".to_string(), + client_id: "cli_123".to_string(), + token_expires_at: 4_102_444_800, + token_sha256_base64url: "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU" + .to_string(), + scopes: vec!["remote_control_controller_websocket".to_string()], + }, + }, + }, + /*trace*/ None, + ) + .await; + + assert_eq!(error.code, crate::error_code::INVALID_REQUEST_ERROR_CODE); + assert_eq!( + error.message, + "device/key/sign is not available over remote transports" + ); + + harness.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "current_thread")] +#[serial(app_server_tracing)] async fn turn_start_jsonrpc_span_parents_core_turn_spans() -> Result<()> { - let _guard = tracing_test_guard().lock().await; let mut harness = TracingHarness::new().await?; let thread_start_response = harness.start_thread(/*request_id*/ 2, /*trace*/ None).await; let thread_id = thread_start_response.thread.id.clone(); diff --git a/codex-rs/app-server/src/transport/mod.rs b/codex-rs/app-server/src/transport/mod.rs index a07bd44188..cb3510da77 100644 --- a/codex-rs/app-server/src/transport/mod.rs +++ b/codex-rs/app-server/src/transport/mod.rs @@ -34,8 +34,7 @@ mod stdio; mod websocket; pub(crate) use remote_control::RemoteControlHandle; -pub(crate) use remote_control::RemoteControlStartOptions; -pub(crate) use remote_control::start_remote_control_with_options; +pub(crate) use remote_control::start_remote_control; pub(crate) use stdio::start_stdio_connection; pub(crate) use websocket::start_websocket_acceptor; @@ -106,6 +105,7 @@ impl FromStr for AppServerTransport { pub(crate) enum TransportEvent { ConnectionOpened { connection_id: ConnectionId, + origin: ConnectionOrigin, writer: mpsc::Sender, disconnect_sender: Option, }, @@ -118,6 +118,22 @@ pub(crate) enum TransportEvent { }, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ConnectionOrigin { + Stdio, + InProcess, + WebSocket, + RemoteControl, +} + +impl ConnectionOrigin { + pub(crate) fn allows_device_key_requests(self) -> bool { + // Device-key endpoints are only for local connections that own the app-server instance. + // Do not include remote transports such as SSH or remote-control websocket connections. + matches!(self, Self::Stdio | Self::InProcess) + } +} + pub(crate) struct ConnectionState { pub(crate) outbound_initialized: Arc, pub(crate) outbound_experimental_api_enabled: Arc, @@ -127,6 +143,7 @@ pub(crate) struct ConnectionState { impl ConnectionState { pub(crate) fn new( + origin: ConnectionOrigin, outbound_initialized: Arc, outbound_experimental_api_enabled: Arc, outbound_opted_out_notification_methods: Arc>>, @@ -135,7 +152,7 @@ impl ConnectionState { outbound_initialized, outbound_experimental_api_enabled, outbound_opted_out_notification_methods, - session: Arc::new(ConnectionSessionState::default()), + session: Arc::new(ConnectionSessionState::new(origin)), } } } diff --git a/codex-rs/app-server/src/transport/remote_control/client_tracker.rs b/codex-rs/app-server/src/transport/remote_control/client_tracker.rs index fa9a208ade..cbd74c2fd9 100644 --- a/codex-rs/app-server/src/transport/remote_control/client_tracker.rs +++ b/codex-rs/app-server/src/transport/remote_control/client_tracker.rs @@ -9,6 +9,7 @@ use super::protocol::ServerEvent; use super::protocol::StreamId; use crate::outgoing_message::ConnectionId; use crate::outgoing_message::QueuedOutgoingMessage; +use crate::transport::ConnectionOrigin; use crate::transport::remote_control::QueuedServerEnvelope; use codex_app_server_protocol::JSONRPCMessage; use std::collections::HashMap; @@ -160,6 +161,7 @@ impl ClientTracker { let disconnect_token = self.shutdown_token.child_token(); self.send_transport_event(TransportEvent::ConnectionOpened { connection_id, + origin: ConnectionOrigin::RemoteControl, writer: writer_tx, disconnect_sender: Some(disconnect_token.clone()), }) diff --git a/codex-rs/app-server/src/transport/remote_control/enroll.rs b/codex-rs/app-server/src/transport/remote_control/enroll.rs index 4d9929818a..dbe18c8355 100644 --- a/codex-rs/app-server/src/transport/remote_control/enroll.rs +++ b/codex-rs/app-server/src/transport/remote_control/enroll.rs @@ -17,7 +17,6 @@ const REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES: usize = 4096; const REQUEST_ID_HEADER: &str = "x-request-id"; const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id"; const CF_RAY_HEADER: &str = "cf-ray"; -const REMOTE_CONTROL_FEDRAMP_HEADER: &str = "X-OpenAI-Fedramp"; pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id"; #[derive(Debug, Clone, PartialEq, Eq)] @@ -30,9 +29,8 @@ pub(super) struct RemoteControlEnrollment { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct RemoteControlConnectionAuth { - pub(super) authorization_header_value: String, + pub(super) bearer_token: String, pub(super) account_id: String, - pub(super) is_fedramp_account: bool, } pub(super) async fn load_persisted_remote_control_enrollment( @@ -201,15 +199,12 @@ pub(super) async fn enroll_remote_control_server( app_server_version: env!("CARGO_PKG_VERSION"), }; let client = build_reqwest_client(); - let mut http_request = client + let http_request = client .post(enroll_url) .timeout(REMOTE_CONTROL_ENROLL_TIMEOUT) - .header("authorization", &auth.authorization_header_value) - .header(REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id); - if auth.is_fedramp_account { - http_request = http_request.header(REMOTE_CONTROL_FEDRAMP_HEADER, "true"); - } - let http_request = http_request.json(&request); + .bearer_auth(&auth.bearer_token) + .header(REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id) + .json(&request); let response = http_request.send().await.map_err(|err| { io::Error::other(format!( @@ -450,9 +445,8 @@ mod tests { let err = enroll_remote_control_server( &remote_control_target, &RemoteControlConnectionAuth { - authorization_header_value: "Bearer Access Token".to_string(), + bearer_token: "Access Token".to_string(), account_id: "account_id".to_string(), - is_fedramp_account: false, }, ) .await diff --git a/codex-rs/app-server/src/transport/remote_control/mod.rs b/codex-rs/app-server/src/transport/remote_control/mod.rs index 8764928ea9..c014c7a2c9 100644 --- a/codex-rs/app-server/src/transport/remote_control/mod.rs +++ b/codex-rs/app-server/src/transport/remote_control/mod.rs @@ -4,7 +4,6 @@ mod protocol; mod websocket; use crate::transport::remote_control::websocket::RemoteControlWebsocket; -use crate::transport::remote_control::websocket::RemoteControlWebsocketOptions; pub use self::protocol::ClientId; use self::protocol::ServerEvent; @@ -45,17 +44,6 @@ impl RemoteControlHandle { } } -pub(crate) struct RemoteControlStartOptions { - pub(crate) remote_control_url: String, - pub(crate) state_db: Option>, - pub(crate) auth_manager: Arc, - pub(crate) transport_event_tx: mpsc::Sender, - pub(crate) shutdown_token: CancellationToken, - pub(crate) app_server_client_name_rx: Option>, - pub(crate) initial_enabled: bool, -} - -#[cfg(test)] pub(crate) async fn start_remote_control( remote_control_url: String, state_db: Option>, @@ -65,38 +53,15 @@ pub(crate) async fn start_remote_control( app_server_client_name_rx: Option>, initial_enabled: bool, ) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> { - start_remote_control_with_options(RemoteControlStartOptions { - remote_control_url, - state_db, - auth_manager, - transport_event_tx, - shutdown_token, - app_server_client_name_rx, - initial_enabled, - }) - .await -} - -pub(crate) async fn start_remote_control_with_options( - options: RemoteControlStartOptions, -) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> { - let RemoteControlStartOptions { - remote_control_url, - state_db, - auth_manager, - transport_event_tx, - shutdown_token, - app_server_client_name_rx, - initial_enabled, - } = options; let remote_control_target = if initial_enabled { Some(normalize_remote_control_url(&remote_control_url)?) } else { None }; + let (enabled_tx, enabled_rx) = watch::channel(initial_enabled); let join_handle = tokio::spawn(async move { - RemoteControlWebsocket::from_options(RemoteControlWebsocketOptions { + RemoteControlWebsocket::new( remote_control_url, remote_control_target, state_db, @@ -104,7 +69,7 @@ pub(crate) async fn start_remote_control_with_options( transport_event_tx, shutdown_token, enabled_rx, - }) + ) .run(app_server_client_name_rx) .await; }); diff --git a/codex-rs/app-server/src/transport/remote_control/protocol.rs b/codex-rs/app-server/src/transport/remote_control/protocol.rs index dcb79e5c35..f0db5ecacb 100644 --- a/codex-rs/app-server/src/transport/remote_control/protocol.rs +++ b/codex-rs/app-server/src/transport/remote_control/protocol.rs @@ -105,7 +105,7 @@ pub(crate) struct ServerEnvelope { pub(crate) seq_id: u64, } -fn is_allowed_chatgpt_host(host: &Option>) -> bool { +fn is_allowed_remote_control_chatgpt_host(host: &Option>) -> bool { let Some(Host::Domain(host)) = *host else { return false; }; @@ -156,7 +156,7 @@ pub(super) fn normalize_remote_control_url( .map_err(map_url_parse_error)?; let host = enroll_url.host(); match enroll_url.scheme() { - "https" if is_localhost(&host) || is_allowed_chatgpt_host(&host) => { + "https" if is_localhost(&host) || is_allowed_remote_control_chatgpt_host(&host) => { websocket_url.set_scheme("wss").map_err(map_scheme_error)?; } "http" if is_localhost(&host) => { @@ -232,6 +232,7 @@ mod tests { "http://chatgpt.com/backend-api", "http://example.com/backend-api", "https://example.com/backend-api", + "https://chat.openai.com/backend-api", "https://chatgpt.com.evil.com/backend-api", "https://evilchatgpt.com/backend-api", "https://foo.localhost/backend-api", diff --git a/codex-rs/app-server/src/transport/remote_control/tests.rs b/codex-rs/app-server/src/transport/remote_control/tests.rs index d702a99c2c..99946b4916 100644 --- a/codex-rs/app-server/src/transport/remote_control/tests.rs +++ b/codex-rs/app-server/src/transport/remote_control/tests.rs @@ -12,6 +12,7 @@ use super::*; use crate::outgoing_message::OutgoingMessage; use crate::outgoing_message::QueuedOutgoingMessage; use crate::transport::CHANNEL_CAPACITY; +use crate::transport::ConnectionOrigin; use crate::transport::TransportEvent; use base64::Engine; use codex_app_server_protocol::AuthMode; @@ -97,7 +98,6 @@ fn remote_control_auth_dot_json(account_id: Option<&str>) -> AuthDotJson { account_id: account_id.map(str::to_string), }), last_refresh: Some(chrono::Utc::now()), - agent_identity: None, } } @@ -226,9 +226,13 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages() { TransportEvent::ConnectionOpened { connection_id, + origin, writer, .. - } => (connection_id, writer), + } => { + assert_eq!(origin, ConnectionOrigin::RemoteControl); + (connection_id, writer) + } other => panic!("expected connection open event, got {other:?}"), }; diff --git a/codex-rs/app-server/src/transport/remote_control/websocket.rs b/codex-rs/app-server/src/transport/remote_control/websocket.rs index dee177d30e..b68c98e733 100644 --- a/codex-rs/app-server/src/transport/remote_control/websocket.rs +++ b/codex-rs/app-server/src/transport/remote_control/websocket.rs @@ -49,7 +49,6 @@ use tracing::warn; pub(super) const REMOTE_CONTROL_PROTOCOL_VERSION: &str = "2"; pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id"; -const REMOTE_CONTROL_FEDRAMP_HEADER: &str = "X-OpenAI-Fedramp"; const REMOTE_CONTROL_SUBSCRIBE_CURSOR_HEADER: &str = "x-codex-subscribe-cursor"; const REMOTE_CONTROL_WEBSOCKET_PING_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10); @@ -129,16 +128,6 @@ pub(crate) struct RemoteControlWebsocket { enabled_rx: watch::Receiver, } -pub(crate) struct RemoteControlWebsocketOptions { - pub(crate) remote_control_url: String, - pub(crate) remote_control_target: Option, - pub(crate) state_db: Option>, - pub(crate) auth_manager: Arc, - pub(crate) transport_event_tx: mpsc::Sender, - pub(crate) shutdown_token: CancellationToken, - pub(crate) enabled_rx: watch::Receiver, -} - enum ConnectOutcome { Connected(Box>>), Disabled, @@ -146,7 +135,6 @@ enum ConnectOutcome { } impl RemoteControlWebsocket { - #[cfg(test)] pub(crate) fn new( remote_control_url: String, remote_control_target: Option, @@ -156,27 +144,6 @@ impl RemoteControlWebsocket { shutdown_token: CancellationToken, enabled_rx: watch::Receiver, ) -> Self { - Self::from_options(RemoteControlWebsocketOptions { - remote_control_url, - remote_control_target, - state_db, - auth_manager, - transport_event_tx, - shutdown_token, - enabled_rx, - }) - } - - pub(crate) fn from_options(options: RemoteControlWebsocketOptions) -> Self { - let RemoteControlWebsocketOptions { - remote_control_url, - remote_control_target, - state_db, - auth_manager, - transport_event_tx, - shutdown_token, - enabled_rx, - } = options; let shutdown_token = shutdown_token.child_token(); let (server_event_tx, server_event_rx) = mpsc::channel(super::CHANNEL_CAPACITY); let client_tracker = @@ -308,16 +275,14 @@ impl RemoteControlWebsocket { } return ConnectOutcome::Disabled; } - connect_result = connect_remote_control_websocket_with_options( - ConnectRemoteControlWebsocketOptions { - remote_control_target: &remote_control_target, - state_db: self.state_db.as_deref(), - auth_manager: &self.auth_manager, - auth_recovery: &mut self.auth_recovery, - enrollment: &mut self.enrollment, - subscribe_cursor: subscribe_cursor.as_deref(), - app_server_client_name, - }, + connect_result = connect_remote_control_websocket( + &remote_control_target, + self.state_db.as_deref(), + &self.auth_manager, + &mut self.auth_recovery, + &mut self.enrollment, + subscribe_cursor.as_deref(), + app_server_client_name, ) => connect_result, }; @@ -715,11 +680,12 @@ fn build_remote_control_websocket_request( "x-codex-protocol-version", REMOTE_CONTROL_PROTOCOL_VERSION, )?; - set_remote_control_header(headers, "authorization", &auth.authorization_header_value)?; + set_remote_control_header( + headers, + "authorization", + &format!("Bearer {}", auth.bearer_token), + )?; set_remote_control_header(headers, REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id)?; - if auth.is_fedramp_account { - set_remote_control_header(headers, REMOTE_CONTROL_FEDRAMP_HEADER, "true")?; - } if let Some(subscribe_cursor) = subscribe_cursor { set_remote_control_header( headers, @@ -764,19 +730,8 @@ pub(crate) async fn load_remote_control_auth( )); } - let authorization_header_value = auth_manager - .chatgpt_authorization_header_for_auth(&auth) - .await - .ok_or_else(|| { - io::Error::new( - ErrorKind::PermissionDenied, - "remote control requires ChatGPT authentication", - ) - })?; - Ok(RemoteControlConnectionAuth { - authorization_header_value, - is_fedramp_account: auth.is_fedramp_account(), + bearer_token: auth.get_token().map_err(io::Error::other)?, account_id: auth.get_account_id().ok_or_else(|| { io::Error::new( ErrorKind::WouldBlock, @@ -786,7 +741,6 @@ pub(crate) async fn load_remote_control_auth( }) } -#[cfg(test)] pub(super) async fn connect_remote_control_websocket( remote_control_target: &RemoteControlTarget, state_db: Option<&StateRuntime>, @@ -799,44 +753,6 @@ pub(super) async fn connect_remote_control_websocket( WebSocketStream>, tungstenite::http::Response<()>, )> { - connect_remote_control_websocket_with_options(ConnectRemoteControlWebsocketOptions { - remote_control_target, - state_db, - auth_manager, - auth_recovery, - enrollment, - subscribe_cursor, - app_server_client_name, - }) - .await -} - -struct ConnectRemoteControlWebsocketOptions<'a> { - remote_control_target: &'a RemoteControlTarget, - state_db: Option<&'a StateRuntime>, - auth_manager: &'a Arc, - auth_recovery: &'a mut UnauthorizedRecovery, - enrollment: &'a mut Option, - subscribe_cursor: Option<&'a str>, - app_server_client_name: Option<&'a str>, -} - -async fn connect_remote_control_websocket_with_options( - options: ConnectRemoteControlWebsocketOptions<'_>, -) -> io::Result<( - WebSocketStream>, - tungstenite::http::Response<()>, -)> { - let ConnectRemoteControlWebsocketOptions { - remote_control_target, - state_db, - auth_manager, - auth_recovery, - enrollment, - subscribe_cursor, - app_server_client_name, - } = options; - ensure_rustls_crypto_provider(); let auth = load_remote_control_auth(auth_manager).await?; @@ -1095,38 +1011,9 @@ mod tests { account_id: Some("account_id".to_string()), }), last_refresh: Some(Utc::now()), - agent_identity: None, } } - #[test] - fn build_remote_control_websocket_request_includes_fedramp_header() { - let request = build_remote_control_websocket_request( - "ws://127.0.0.1/backend-api/wham/remote/control/server", - &RemoteControlEnrollment { - account_id: "account_id".to_string(), - environment_id: "env_test".to_string(), - server_id: "srv_e_test".to_string(), - server_name: "test-server".to_string(), - }, - &RemoteControlConnectionAuth { - authorization_header_value: "AgentAssertion assertion".to_string(), - account_id: "account_id".to_string(), - is_fedramp_account: true, - }, - /*subscribe_cursor*/ None, - ) - .expect("request should build"); - - assert_eq!( - request - .headers() - .get(REMOTE_CONTROL_FEDRAMP_HEADER) - .and_then(|value| value.to_str().ok()), - Some("true") - ); - } - #[tokio::test] async fn connect_remote_control_websocket_includes_http_error_details() { let listener = TcpListener::bind("127.0.0.1:0") diff --git a/codex-rs/app-server/src/transport/stdio.rs b/codex-rs/app-server/src/transport/stdio.rs index 20eab025fb..14466c86cc 100644 --- a/codex-rs/app-server/src/transport/stdio.rs +++ b/codex-rs/app-server/src/transport/stdio.rs @@ -1,4 +1,5 @@ use super::CHANNEL_CAPACITY; +use super::ConnectionOrigin; use super::TransportEvent; use super::forward_incoming_message; use super::next_connection_id; @@ -31,6 +32,7 @@ pub(crate) async fn start_stdio_connection( transport_event_tx .send(TransportEvent::ConnectionOpened { connection_id, + origin: ConnectionOrigin::Stdio, writer: writer_tx, disconnect_sender: None, }) diff --git a/codex-rs/app-server/src/transport/websocket.rs b/codex-rs/app-server/src/transport/websocket.rs index 41b138e216..2647d7c768 100644 --- a/codex-rs/app-server/src/transport/websocket.rs +++ b/codex-rs/app-server/src/transport/websocket.rs @@ -1,4 +1,5 @@ use super::CHANNEL_CAPACITY; +use super::ConnectionOrigin; use super::TransportEvent; use super::auth::WebsocketAuthPolicy; use super::auth::authorize_upgrade; @@ -172,6 +173,7 @@ async fn run_websocket_connection( if transport_event_tx .send(TransportEvent::ConnectionOpened { connection_id, + origin: ConnectionOrigin::WebSocket, writer: writer_tx, disconnect_sender: Some(disconnect_token.clone()), }) diff --git a/codex-rs/app-server/tests/common/auth_fixtures.rs b/codex-rs/app-server/tests/common/auth_fixtures.rs index 86f0fb456d..99334f0770 100644 --- a/codex-rs/app-server/tests/common/auth_fixtures.rs +++ b/codex-rs/app-server/tests/common/auth_fixtures.rs @@ -163,7 +163,6 @@ pub fn write_chatgpt_auth( openai_api_key: None, tokens: Some(tokens), last_refresh, - agent_identity: None, }; save_auth(codex_home, &auth, cli_auth_credentials_store_mode).context("write auth.json") diff --git a/codex-rs/app-server/tests/suite/auth.rs b/codex-rs/app-server/tests/suite/auth.rs index b35a6fcba1..1e60871012 100644 --- a/codex-rs/app-server/tests/suite/auth.rs +++ b/codex-rs/app-server/tests/suite/auth.rs @@ -351,8 +351,6 @@ async fn get_auth_status_omits_token_after_proactive_refresh_failure() -> Result )?; let server = MockServer::start().await; - // App-server startup may proactively read stale auth before this test sends - // getAuthStatus; require the refresh path without depending on that race. Mock::given(method("POST")) .and(path("/oauth/token")) .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({ @@ -360,7 +358,7 @@ async fn get_auth_status_omits_token_after_proactive_refresh_failure() -> Result "code": "refresh_token_reused" } }))) - .expect(1..=2) + .expect(2) .mount(&server) .await; @@ -420,8 +418,6 @@ async fn get_auth_status_returns_token_after_proactive_refresh_recovery() -> Res )?; let server = MockServer::start().await; - // App-server startup may proactively read stale auth before this test sends - // getAuthStatus; require the refresh path without depending on that race. Mock::given(method("POST")) .and(path("/oauth/token")) .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({ @@ -429,7 +425,7 @@ async fn get_auth_status_returns_token_after_proactive_refresh_recovery() -> Res "code": "refresh_token_reused" } }))) - .expect(1..=2) + .expect(2) .mount(&server) .await; diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index f798122635..3c88bcb7a4 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -45,9 +45,7 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -// Account tests spin up fresh app-server processes repeatedly, which can take -// longer on slower Bazel macOS runners once the suite is already warm. -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const LOGIN_ISSUER_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER"; // Helper to create a minimal config.toml for the app server diff --git a/codex-rs/app-server/tests/suite/v2/app_list.rs b/codex-rs/app-server/tests/suite/v2/app_list.rs index 78a915d178..7aa8034528 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -119,7 +119,6 @@ async fn list_apps_returns_empty_with_api_key_auth() -> Result<()> { openai_api_key: Some("test-api-key".to_string()), tokens: None, last_refresh: None, - agent_identity: None, }, AuthCredentialsStoreMode::File, )?; diff --git a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs index 0cc8b51e56..456ae1577a 100644 --- a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs +++ b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs @@ -777,7 +777,7 @@ pub(super) async fn read_response_and_notification_for_method( Ok((response, notification)) } -async fn read_error_for_id(stream: &mut WsClient, id: i64) -> Result { +pub(super) async fn read_error_for_id(stream: &mut WsClient, id: i64) -> Result { let target_id = RequestId::Integer(id); loop { let message = read_jsonrpc_message(stream).await?; diff --git a/codex-rs/app-server/tests/suite/v2/device_key.rs b/codex-rs/app-server/tests/suite/v2/device_key.rs new file mode 100644 index 0000000000..f8a4d0cf67 --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/device_key.rs @@ -0,0 +1,119 @@ +use super::connection_handling_websocket::connect_websocket; +use super::connection_handling_websocket::create_config_toml; +use super::connection_handling_websocket::read_error_for_id; +use super::connection_handling_websocket::read_response_for_id; +use super::connection_handling_websocket::send_initialize_request; +use super::connection_handling_websocket::send_request; +use super::connection_handling_websocket::spawn_websocket_server; +use anyhow::Result; +use app_test_support::McpProcess; +use app_test_support::create_mock_responses_server_sequence_unchecked; +use codex_app_server_protocol::RequestId; +use pretty_assertions::assert_eq; +use serde_json::json; +use tempfile::TempDir; +use tokio::time::Duration; +use tokio::time::timeout; + +#[cfg(any(target_os = "macos", windows))] +const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(60); +#[cfg(not(any(target_os = "macos", windows)))] +const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); + +async fn initialized_mcp(codex_home: &TempDir) -> Result { + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + Ok(mcp) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn device_key_create_rejects_empty_account_user_id() -> Result<()> { + let codex_home = TempDir::new()?; + let mut mcp = initialized_mcp(&codex_home).await?; + + let request_id = mcp + .send_raw_request( + "device/key/create", + Some(json!({ + "accountUserId": "", + "clientId": "cli_123", + })), + ) + .await?; + let error = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(error.error.code, -32600); + assert_eq!( + error.error.message, + "invalid device key payload: accountUserId must not be empty" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn device_key_methods_are_rejected_over_websocket() -> Result<()> { + let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri(), "never")?; + + let (mut process, bind_addr) = spawn_websocket_server(codex_home.path()).await?; + let mut ws = connect_websocket(bind_addr).await?; + send_initialize_request(&mut ws, /*id*/ 1, "device_key_ws_test").await?; + let initialize_response = read_response_for_id(&mut ws, /*id*/ 1).await?; + assert_eq!(initialize_response.id, RequestId::Integer(1)); + + let cases = [ + ( + "device/key/create", + json!({ + "accountUserId": "acct_123", + "clientId": "cli_123", + }), + ), + ( + "device/key/public", + json!({ + "keyId": "device-key-123", + }), + ), + ( + "device/key/sign", + json!({ + "keyId": "device-key-123", + "payload": { + "type": "remoteControlClientConnection", + "nonce": "nonce-123", + "audience": "remote_control_client_websocket", + "sessionId": "wssess_123", + "targetOrigin": "https://chatgpt.com", + "targetPath": "/api/codex/remote/control/client", + "accountUserId": "acct_123", + "clientId": "cli_123", + "tokenExpiresAt": 4_102_444_800i64, + "tokenSha256Base64url": "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU", + "scopes": ["remote_control_controller_websocket"], + }, + }), + ), + ]; + + for (index, (method, params)) in cases.into_iter().enumerate() { + let id = 2 + index as i64; + send_request(&mut ws, method, id, Some(params)).await?; + let error = read_error_for_id(&mut ws, id).await?; + + assert_eq!(error.error.code, -32600); + assert_eq!( + error.error.message, + format!("{method} is not available over remote transports") + ); + } + + process.kill().await?; + Ok(()) +} diff --git a/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs b/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs index 07bdd0bde1..3f7e6989f8 100644 --- a/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs +++ b/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs @@ -15,6 +15,7 @@ use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_core::config::ConfigBuilder; +use codex_core::config_loader::LoaderOverrides; use codex_features::FEATURES; use codex_features::Stage; use pretty_assertions::assert_eq; @@ -32,6 +33,9 @@ async fn experimental_feature_list_returns_feature_metadata_with_stage() -> Resu let config = ConfigBuilder::default() .codex_home(codex_home.path().to_path_buf()) .fallback_cwd(Some(codex_home.path().to_path_buf())) + .loader_overrides(LoaderOverrides::with_managed_config_path_for_tests( + codex_home.path().join("managed_config.toml"), + )) .build() .await?; let mut mcp = McpProcess::new(codex_home.path()).await?; diff --git a/codex-rs/app-server/tests/suite/v2/initialize.rs b/codex-rs/app-server/tests/suite/v2/initialize.rs index 4fe5f2fbe7..165160468f 100644 --- a/codex-rs/app-server/tests/suite/v2/initialize.rs +++ b/codex-rs/app-server/tests/suite/v2/initialize.rs @@ -24,9 +24,7 @@ use std::time::Duration; use tempfile::TempDir; use tokio::time::timeout; -// This covers debug app-server process startup before the first JSON-RPC response, -// not expected steady-state request latency. -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); #[tokio::test] async fn initialize_uses_client_info_name_as_originator() -> Result<()> { diff --git a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs index 87556c8364..8a323efcef 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs @@ -83,10 +83,11 @@ url = "{mcp_server_url}/mcp" ) .await??; let ThreadStartResponse { thread, .. } = to_response(thread_start_resp)?; + let thread_id = thread.id.clone(); let tool_call_request_id = mcp .send_mcp_server_tool_call_request(McpServerToolCallParams { - thread_id: thread.id, + thread_id: thread_id.clone(), server: TEST_SERVER_NAME.to_string(), tool: TEST_TOOL_NAME.to_string(), arguments: Some(json!({ @@ -114,6 +115,7 @@ url = "{mcp_server_url}/mcp" response.structured_content, Some(json!({ "echoed": "hello from app", + "threadId": thread_id, })) ); assert_eq!(response.is_error, Some(false)); @@ -203,7 +205,7 @@ impl ServerHandler for ToolAppsMcpServer { async fn call_tool( &self, request: CallToolRequestParams, - _context: RequestContext, + context: RequestContext, ) -> Result { assert_eq!(request.name.as_ref(), TEST_TOOL_NAME); let message = request @@ -212,12 +214,19 @@ impl ServerHandler for ToolAppsMcpServer { .and_then(|arguments| arguments.get("message")) .and_then(|value| value.as_str()) .unwrap_or_default(); + let thread_id = context + .meta + .0 + .get("threadId") + .and_then(|value| value.as_str()) + .unwrap_or_default(); let mut meta = Meta::new(); meta.0.insert("calledBy".to_string(), json!("mcp-app")); let mut result = CallToolResult::structured(json!({ "echoed": message, + "threadId": thread_id, })); result.content = vec![Content::text(format!("echo: {message}"))]; result.meta = Some(meta); diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index ea4f7cb5d1..4ab21ffc52 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -10,6 +10,7 @@ mod config_rpc; mod connection_handling_websocket; #[cfg(unix)] mod connection_handling_websocket_unix; +mod device_key; mod dynamic_tools; mod experimental_api; mod experimental_feature_list; diff --git a/codex-rs/app-server/tests/suite/v2/plugin_list.rs b/codex-rs/app-server/tests/suite/v2/plugin_list.rs index bf69df3c47..9718761e33 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_list.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_list.rs @@ -30,8 +30,7 @@ use wiremock::matchers::method; use wiremock::matchers::path; use wiremock::matchers::query_param; -// These tests start full app-server processes and can also run plugin startup warmers. -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; const STARTUP_REMOTE_PLUGIN_SYNC_MARKER_FILE: &str = ".tmp/app-server-remote-plugin-sync-v1"; const ALTERNATE_MARKETPLACE_RELATIVE_PATH: &str = ".claude-plugin/marketplace.json"; diff --git a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs index dfc3fea318..793efbe1e1 100644 --- a/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs +++ b/codex-rs/app-server/tests/suite/v2/realtime_conversation.rs @@ -72,7 +72,6 @@ use wiremock::matchers::path; use wiremock::matchers::path_regex; const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); -const DELEGATED_SHELL_TOOL_TIMEOUT_MS: u64 = 30_000; const STARTUP_CONTEXT_HEADER: &str = "Startup context from Codex."; const V2_STEERING_ACKNOWLEDGEMENT: &str = "This was sent to steer the previous background agent task."; @@ -1782,9 +1781,7 @@ async fn webrtc_v2_tool_call_delegated_turn_can_execute_shell_tool() -> Result<( create_shell_command_sse_response( realtime_tool_ok_command(), /*workdir*/ None, - // Windows CI can spend several seconds starting the nested PowerShell command. This - // test verifies delegated shell-tool plumbing, not timeout enforcement. - Some(DELEGATED_SHELL_TOOL_TIMEOUT_MS), + Some(5000), "shell_call", )?, create_final_assistant_message_sse_response("shell tool finished")?, diff --git a/codex-rs/app-server/tests/suite/v2/request_permissions.rs b/codex-rs/app-server/tests/suite/v2/request_permissions.rs index 295ac96a3b..4f7c398f98 100644 --- a/codex-rs/app-server/tests/suite/v2/request_permissions.rs +++ b/codex-rs/app-server/tests/suite/v2/request_permissions.rs @@ -76,6 +76,7 @@ async fn request_permissions_round_trip() -> Result<()> { assert_eq!(params.thread_id, thread.id); assert_eq!(params.turn_id, turn.id); assert_eq!(params.item_id, "call1"); + assert!(params.cwd.as_path().is_absolute()); assert_eq!(params.reason, Some("Select a workspace root".to_string())); let requested_writes = params .permissions diff --git a/codex-rs/backend-client/src/client.rs b/codex-rs/backend-client/src/client.rs index e6ea0253b8..b96395b015 100644 --- a/codex-rs/backend-client/src/client.rs +++ b/codex-rs/backend-client/src/client.rs @@ -6,6 +6,7 @@ use crate::types::RateLimitStatusPayload; use crate::types::TurnAttemptsSiblingTurnsResponse; use anyhow::Result; use codex_client::build_reqwest_client_with_custom_ca; +use codex_client::with_chatgpt_cloudflare_cookie_store; use codex_login::CodexAuth; use codex_login::default_client::get_codex_user_agent; use codex_protocol::account::PlanType as AccountPlanType; @@ -116,7 +117,7 @@ impl PathStyle { pub struct Client { base_url: String, http: reqwest::Client, - authorization_header_value: Option, + bearer_token: Option, user_agent: Option, chatgpt_account_id: Option, chatgpt_account_is_fedramp: bool, @@ -137,12 +138,14 @@ impl Client { { base_url = format!("{base_url}/backend-api"); } - let http = build_reqwest_client_with_custom_ca(reqwest::Client::builder())?; + let http = build_reqwest_client_with_custom_ca(with_chatgpt_cloudflare_cookie_store( + reqwest::Client::builder(), + ))?; let path_style = PathStyle::from_base_url(&base_url); Ok(Self { base_url, http, - authorization_header_value: None, + bearer_token: None, user_agent: None, chatgpt_account_id: None, chatgpt_account_is_fedramp: false, @@ -165,12 +168,7 @@ impl Client { } pub fn with_bearer_token(mut self, token: impl Into) -> Self { - self.authorization_header_value = Some(format!("Bearer {}", token.into())); - self - } - - pub fn with_authorization_header_value(mut self, value: impl Into) -> Self { - self.authorization_header_value = Some(value.into()); + self.bearer_token = Some(token.into()); self } @@ -203,10 +201,11 @@ impl Client { } else { h.insert(USER_AGENT, HeaderValue::from_static("codex-cli")); } - if let Some(value) = &self.authorization_header_value - && let Ok(hv) = HeaderValue::from_str(value) - { - h.insert(AUTHORIZATION, hv); + if let Some(token) = &self.bearer_token { + let value = format!("Bearer {token}"); + if let Ok(hv) = HeaderValue::from_str(&value) { + h.insert(AUTHORIZATION, hv); + } } if let Some(acc) = &self.chatgpt_account_id && let Ok(name) = HeaderName::from_bytes(b"ChatGPT-Account-Id") @@ -820,7 +819,7 @@ mod tests { let codex_client = Client { base_url: "https://example.test".to_string(), http: reqwest::Client::new(), - authorization_header_value: None, + bearer_token: None, user_agent: None, chatgpt_account_id: None, chatgpt_account_is_fedramp: false, @@ -834,7 +833,7 @@ mod tests { let chatgpt_client = Client { base_url: "https://chatgpt.com/backend-api".to_string(), http: reqwest::Client::new(), - authorization_header_value: None, + bearer_token: None, user_agent: None, chatgpt_account_id: None, chatgpt_account_is_fedramp: false, diff --git a/codex-rs/chatgpt/src/chatgpt_client.rs b/codex-rs/chatgpt/src/chatgpt_client.rs index 6bdb16347e..fa3a63dadb 100644 --- a/codex-rs/chatgpt/src/chatgpt_client.rs +++ b/codex-rs/chatgpt/src/chatgpt_client.rs @@ -1,5 +1,4 @@ use codex_core::config::Config; -use codex_login::AuthManager; use codex_login::default_client::create_client; use crate::chatgpt_token::get_chatgpt_token_data; @@ -32,32 +31,16 @@ pub(crate) async fn chatgpt_get_request_with_timeout( let token = get_chatgpt_token_data().ok_or_else(|| anyhow::anyhow!("ChatGPT token not available"))?; - let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); - let auth = auth_manager.auth().await; - let is_fedramp_account = auth - .as_ref() - .is_some_and(codex_login::CodexAuth::is_fedramp_account); - let authorization_header_value = match auth.as_ref() { - Some(auth) if auth.is_chatgpt_auth() => auth_manager - .chatgpt_authorization_header_for_auth(auth) - .await - .unwrap_or_else(|| format!("Bearer {}", token.access_token)), - _ => format!("Bearer {}", token.access_token), - }; let account_id = token.account_id.ok_or_else(|| { anyhow::anyhow!("ChatGPT account ID not available, please re-run `codex login`") - })?; + }); let mut request = client .get(&url) - .header("authorization", authorization_header_value) - .header("chatgpt-account-id", account_id) + .bearer_auth(&token.access_token) + .header("chatgpt-account-id", account_id?) .header("Content-Type", "application/json"); - if is_fedramp_account { - request = request.header("X-OpenAI-Fedramp", "true"); - } if let Some(timeout) = timeout { request = request.timeout(timeout); diff --git a/codex-rs/cli/tests/debug_clear_memories.rs b/codex-rs/cli/tests/debug_clear_memories.rs index a24f7ebdde..9d5e114dbf 100644 --- a/codex-rs/cli/tests/debug_clear_memories.rs +++ b/codex-rs/cli/tests/debug_clear_memories.rs @@ -105,7 +105,7 @@ INSERT INTO jobs ( let memory_root = codex_home.path().join("memories"); std::fs::create_dir_all(&memory_root)?; std::fs::write(memory_root.join("memory_summary.md"), "stale memory")?; - drop(pool); + pool.close().await; let mut cmd = codex_command(codex_home.path())?; cmd.args(["debug", "clear-memories"]) @@ -127,6 +127,7 @@ INSERT INTO jobs ( assert_eq!(memory_jobs_count, 0); assert!(memory_root.exists()); assert_eq!(std::fs::read_dir(memory_root)?.count(), 0); + pool.close().await; Ok(()) } diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index 23be6f410d..914958d2c7 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -195,15 +195,11 @@ trait RequirementsFetcher: Send + Sync { struct BackendRequirementsFetcher { base_url: String, - auth_manager: Arc, } impl BackendRequirementsFetcher { - fn new(auth_manager: Arc, base_url: String) -> Self { - Self { - base_url, - auth_manager, - } + fn new(base_url: String) -> Self { + Self { base_url } } } @@ -213,14 +209,7 @@ impl RequirementsFetcher for BackendRequirementsFetcher { &self, auth: &CodexAuth, ) -> Result, FetchAttemptError> { - let authorization_header_value = self - .auth_manager - .chatgpt_authorization_header_for_auth(auth) - .await; - let mut client = BackendClient::new(self.base_url.clone()) - .map(|client| { - client.with_user_agent(codex_login::default_client::get_codex_user_agent()) - }) + let client = BackendClient::from_auth(self.base_url.clone(), auth) .inspect_err(|err| { tracing::warn!( error = %err, @@ -228,15 +217,6 @@ impl RequirementsFetcher for BackendRequirementsFetcher { ); }) .map_err(|_| FetchAttemptError::Retryable(RetryableFailureKind::BackendClientInit))?; - if let Some(authorization_header_value) = authorization_header_value { - client = client.with_authorization_header_value(authorization_header_value); - } - if let Some(account_id) = auth.get_account_id() { - client = client.with_chatgpt_account_id(account_id); - } - if auth.is_fedramp_account() { - client = client.with_fedramp_routing_header(); - } let response = client .get_config_requirements_file() @@ -713,11 +693,8 @@ pub fn cloud_requirements_loader( codex_home: PathBuf, ) -> CloudRequirementsLoader { let service = CloudRequirementsService::new( - auth_manager.clone(), - Arc::new(BackendRequirementsFetcher::new( - auth_manager, - chatgpt_base_url, - )), + auth_manager, + Arc::new(BackendRequirementsFetcher::new(chatgpt_base_url)), codex_home, CLOUD_REQUIREMENTS_TIMEOUT, ); diff --git a/codex-rs/cloud-tasks-client/src/http.rs b/codex-rs/cloud-tasks-client/src/http.rs index 3ada702365..4ea0980227 100644 --- a/codex-rs/cloud-tasks-client/src/http.rs +++ b/codex-rs/cloud-tasks-client/src/http.rs @@ -37,11 +37,6 @@ impl HttpClient { self } - pub fn with_authorization_header_value(mut self, value: impl Into) -> Self { - self.backend = self.backend.clone().with_authorization_header_value(value); - self - } - pub fn with_user_agent(mut self, ua: impl Into) -> Self { self.backend = self.backend.clone().with_user_agent(ua); self @@ -52,11 +47,6 @@ impl HttpClient { self } - pub fn with_fedramp_routing_header(mut self) -> Self { - self.backend = self.backend.clone().with_fedramp_routing_header(); - self - } - fn tasks_api(&self) -> api::Tasks<'_> { api::Tasks::new(self) } diff --git a/codex-rs/cloud-tasks/src/lib.rs b/codex-rs/cloud-tasks/src/lib.rs index 155587003c..7006d52b92 100644 --- a/codex-rs/cloud-tasks/src/lib.rs +++ b/codex-rs/cloud-tasks/src/lib.rs @@ -68,45 +68,43 @@ async fn init_backend(user_agent_suffix: &str) -> anyhow::Result }; append_error_log(format!("startup: base_url={base_url} path_style={style}")); - let Some(auth_manager) = util::load_auth_manager(Some(base_url.clone())).await else { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); + let auth_manager = util::load_auth_manager().await; + let auth = match auth_manager.as_ref() { + Some(manager) => manager.auth().await, + None => None, }; - let Some(auth) = auth_manager.auth().await else { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); + let auth = match auth { + Some(auth) => auth, + None => { + eprintln!( + "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." + ); + std::process::exit(1); + } }; if let Some(acc) = auth.get_account_id() { append_error_log(format!("auth: mode=ChatGPT account_id={acc}")); } - let authorization_header_value = auth_manager - .chatgpt_authorization_header_for_auth(&auth) - .await; - let Some(authorization_header_value) = authorization_header_value else { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); + let token = match auth.get_token() { + Ok(t) if !t.is_empty() => t, + _ => { + eprintln!( + "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." + ); + std::process::exit(1); + } }; - http = http.with_authorization_header_value(authorization_header_value); - if let Some(acc) = auth.get_account_id().or_else(|| { - auth.get_token() - .ok() - .and_then(|token| util::extract_chatgpt_account_id(&token)) - }) { + http = http.with_bearer_token(token.clone()); + if let Some(acc) = auth + .get_account_id() + .or_else(|| util::extract_chatgpt_account_id(&token)) + { append_error_log(format!("auth: set ChatGPT-Account-Id header: {acc}")); http = http.with_chatgpt_account_id(acc); } - if auth.is_fedramp_account() { - http = http.with_fedramp_routing_header(); - } Ok(BackendContext { backend: Arc::new(http), diff --git a/codex-rs/cloud-tasks/src/util.rs b/codex-rs/cloud-tasks/src/util.rs index 693ff7839c..cbaed17bea 100644 --- a/codex-rs/cloud-tasks/src/util.rs +++ b/codex-rs/cloud-tasks/src/util.rs @@ -3,7 +3,6 @@ use chrono::DateTime; use chrono::Local; use chrono::Utc; use reqwest::header::HeaderMap; -use std::sync::Arc; use codex_core::config::Config; use codex_login::AuthManager; @@ -60,18 +59,18 @@ pub fn extract_chatgpt_account_id(token: &str) -> Option { .map(str::to_string) } -pub async fn load_auth_manager(chatgpt_base_url: Option) -> Option> { +pub async fn load_auth_manager() -> Option { // TODO: pass in cli overrides once cloud tasks properly support them. let config = Config::load_with_cli_overrides(Vec::new()).await.ok()?; - let auth_manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); - if let Some(chatgpt_base_url) = chatgpt_base_url { - auth_manager.set_chatgpt_backend_base_url(Some(chatgpt_base_url)); - } - Some(auth_manager) + Some(AuthManager::new( + config.codex_home.to_path_buf(), + /*enable_codex_api_key_env*/ false, + config.cli_auth_credentials_store_mode, + )) } -/// Build headers for ChatGPT-backed requests. +/// Build headers for ChatGPT-backed requests: `User-Agent`, optional `Authorization`, +/// and optional `ChatGPT-Account-Id`. pub async fn build_chatgpt_headers() -> HeaderMap { use reqwest::header::AUTHORIZATION; use reqwest::header::HeaderName; @@ -85,34 +84,23 @@ pub async fn build_chatgpt_headers() -> HeaderMap { USER_AGENT, HeaderValue::from_str(&ua).unwrap_or(HeaderValue::from_static("codex-cli")), ); - let base_url = normalize_base_url( - &std::env::var("CODEX_CLOUD_TASKS_BASE_URL") - .unwrap_or_else(|_| "https://chatgpt.com/backend-api".to_string()), - ); - if let Some(auth_manager) = load_auth_manager(Some(base_url)).await - && let Some(auth) = auth_manager.auth().await + if let Some(am) = load_auth_manager().await + && let Some(auth) = am.auth().await + && let Ok(tok) = auth.get_token() + && !tok.is_empty() { - if let Some(authorization_header_value) = auth_manager - .chatgpt_authorization_header_for_auth(&auth) - .await - && let Ok(hv) = HeaderValue::from_str(&authorization_header_value) - { + let v = format!("Bearer {tok}"); + if let Ok(hv) = HeaderValue::from_str(&v) { headers.insert(AUTHORIZATION, hv); } - if let Some(acc) = auth.get_account_id().or_else(|| { - auth.get_token() - .ok() - .and_then(|token| extract_chatgpt_account_id(&token)) - }) && let Ok(name) = HeaderName::from_bytes(b"ChatGPT-Account-Id") + if let Some(acc) = auth + .get_account_id() + .or_else(|| extract_chatgpt_account_id(&tok)) + && let Ok(name) = HeaderName::from_bytes(b"ChatGPT-Account-Id") && let Ok(hv) = HeaderValue::from_str(&acc) { headers.insert(name, hv); } - if auth.is_fedramp_account() - && let Ok(name) = HeaderName::from_bytes(b"X-OpenAI-Fedramp") - { - headers.insert(name, HeaderValue::from_static("true")); - } } headers } diff --git a/codex-rs/codex-api/src/files.rs b/codex-rs/codex-api/src/files.rs index a938242934..d1e2840066 100644 --- a/codex-rs/codex-api/src/files.rs +++ b/codex-rs/codex-api/src/files.rs @@ -308,18 +308,6 @@ mod tests { ChatGptTestAuth } - #[derive(Clone, Copy)] - struct AgentAssertionTestAuth; - - impl AuthProvider for AgentAssertionTestAuth { - fn add_auth_headers(&self, headers: &mut reqwest::header::HeaderMap) { - headers.insert( - reqwest::header::AUTHORIZATION, - HeaderValue::from_static("AgentAssertion test-assertion"), - ); - } - } - fn base_url_for(server: &MockServer) -> String { format!("{}/backend-api", server.uri()) } @@ -329,7 +317,6 @@ mod tests { let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/backend-api/files")) - .and(header("authorization", "Bearer token")) .and(header("chatgpt-account-id", "account_id")) .and(body_json(serde_json::json!({ "file_name": "hello.txt", @@ -390,52 +377,4 @@ mod tests { assert_eq!(uploaded.mime_type, Some("text/plain".to_string())); assert_eq!(finalize_attempts.load(Ordering::SeqCst), 2); } - - #[tokio::test] - async fn upload_local_file_uses_authorization_header_value() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("authorization", "AgentAssertion test-assertion")) - .and(body_json(serde_json::json!({ - "file_name": "hello.txt", - "file_size": 5, - "use_case": "codex", - }))) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({"file_id": "file_123", "upload_url": format!("{}/upload/file_123", server.uri())})), - ) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .and(header("content-length", "5")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_123/uploaded")) - .and(header("authorization", "AgentAssertion test-assertion")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_123", server.uri()), - "file_name": "hello.txt", - "mime_type": "text/plain", - "file_size_bytes": 5 - }))) - .mount(&server) - .await; - - let base_url = base_url_for(&server); - let dir = TempDir::new().expect("temp dir"); - let path = dir.path().join("hello.txt"); - tokio::fs::write(&path, b"hello").await.expect("write file"); - - let uploaded = upload_local_file(&base_url, &AgentAssertionTestAuth, &path) - .await - .expect("upload succeeds"); - - assert_eq!(uploaded.file_id, "file_123"); - } } diff --git a/codex-rs/codex-client/src/chatgpt_cloudflare_cookies.rs b/codex-rs/codex-client/src/chatgpt_cloudflare_cookies.rs new file mode 100644 index 0000000000..c5f4bbd4eb --- /dev/null +++ b/codex-rs/codex-client/src/chatgpt_cloudflare_cookies.rs @@ -0,0 +1,264 @@ +use std::sync::Arc; +use std::sync::LazyLock; + +use reqwest::cookie::CookieStore; +use reqwest::cookie::Jar; +use reqwest::header::HeaderValue; + +use crate::chatgpt_hosts::is_allowed_chatgpt_host; + +// WARNING: this store is process-global and may be shared across auth contexts. +// It must only ever contain Cloudflare infrastructure cookies. Never extend this +// store to persist ChatGPT account, session, auth, or other user-specific cookie +// data. +static SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE: LazyLock> = + LazyLock::new(|| Arc::new(ChatGptCloudflareCookieStore::default())); + +#[derive(Debug, Default)] +struct ChatGptCloudflareCookieStore { + jar: Jar, +} + +impl CookieStore for ChatGptCloudflareCookieStore { + fn set_cookies( + &self, + cookie_headers: &mut dyn Iterator, + url: &reqwest::Url, + ) { + if !is_chatgpt_cookie_url(url) { + return; + } + + let mut cloudflare_cookie_headers = + cookie_headers.filter(|header| is_allowed_cloudflare_set_cookie_header(header)); + self.jar.set_cookies(&mut cloudflare_cookie_headers, url); + } + + fn cookies(&self, url: &reqwest::Url) -> Option { + if is_chatgpt_cookie_url(url) { + self.jar.cookies(url).and_then(only_cloudflare_cookies) + } else { + None + } + } +} + +/// Adds the process-local ChatGPT Cloudflare cookie jar used by Codex HTTP clients. +/// +/// WARNING: this jar is global within the process. It is only acceptable because it hardcodes a +/// small allowlist of Cloudflare cookie names and refuses all other ChatGPT cookies. Do not store +/// ChatGPT account, session, auth, or other user-specific cookies here. If a future caller needs +/// those cookies, the store must be scoped to the auth/session owner instead of shared globally. +pub fn with_chatgpt_cloudflare_cookie_store( + builder: reqwest::ClientBuilder, +) -> reqwest::ClientBuilder { + builder.cookie_provider(Arc::clone(&SHARED_CHATGPT_CLOUDFLARE_COOKIE_STORE)) +} + +fn is_chatgpt_cookie_url(url: &reqwest::Url) -> bool { + match url.scheme() { + "https" => {} + _ => return false, + } + + let Some(host) = url.host_str() else { + return false; + }; + + is_allowed_chatgpt_host(host) +} + +fn is_allowed_cloudflare_set_cookie_header(header: &HeaderValue) -> bool { + header + .to_str() + .ok() + .and_then(set_cookie_name) + .is_some_and(is_allowed_cloudflare_cookie_name) +} + +fn set_cookie_name(header: &str) -> Option<&str> { + let (name, _) = header.split_once('=')?; + let name = name.trim(); + (!name.is_empty()).then_some(name) +} + +fn only_cloudflare_cookies(header: HeaderValue) -> Option { + let header = header.to_str().ok()?; + let cookies = header + .split(';') + .filter_map(|cookie| { + let cookie = cookie.trim(); + let name = cookie.split_once('=')?.0.trim(); + is_allowed_cloudflare_cookie_name(name).then_some(cookie) + }) + .collect::>() + .join("; "); + + if cookies.is_empty() { + None + } else { + HeaderValue::from_str(&cookies).ok() + } +} + +fn is_allowed_cloudflare_cookie_name(name: &str) -> bool { + // Keep this allowlist aligned with Cloudflare's documented service cookies: + // https://developers.cloudflare.com/fundamentals/reference/policies-compliances/cloudflare-cookies/ + matches!( + name, + "__cf_bm" + | "__cflb" + | "__cfruid" + | "__cfseq" + | "__cfwaitingroom" + | "_cfuvid" + | "cf_clearance" + | "cf_ob_info" + | "cf_use_ob" + ) || name.starts_with("cf_chl_") +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use reqwest::cookie::CookieStore; + + #[test] + fn stores_and_returns_cloudflare_cookies_for_chatgpt_hosts() { + let store = ChatGptCloudflareCookieStore::default(); + let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap(); + let cfuvid = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly"); + let clearance = + HeaderValue::from_static("cf_clearance=clearance; Path=/; Secure; HttpOnly"); + + store.set_cookies(&mut [&cfuvid, &clearance].into_iter(), &url); + + let mut cookies = store + .cookies(&url) + .and_then(|value| value.to_str().ok().map(str::to_string)) + .map(|header| { + header + .split("; ") + .map(str::to_string) + .collect::>() + }) + .unwrap_or_default(); + cookies.sort(); + assert_eq!( + cookies, + vec![ + "_cfuvid=visitor".to_string(), + "cf_clearance=clearance".to_string() + ] + ); + } + + #[test] + fn ignores_non_chatgpt_cookies() { + let store = ChatGptCloudflareCookieStore::default(); + let url = reqwest::Url::parse("https://api.openai.com/v1/responses").unwrap(); + let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly"); + + store.set_cookies(&mut std::iter::once(&set_cookie), &url); + + assert_eq!(store.cookies(&url), None); + } + + #[test] + fn ignores_non_cloudflare_cookies_for_chatgpt_hosts() { + let store = ChatGptCloudflareCookieStore::default(); + let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap(); + let set_cookie = HeaderValue::from_static( + "__Secure-next-auth.session-token=secret; Path=/; Secure; HttpOnly", + ); + + store.set_cookies(&mut std::iter::once(&set_cookie), &url); + + assert_eq!(store.cookies(&url), None); + } + + #[test] + fn ignores_mixed_non_cloudflare_cookies_for_chatgpt_hosts() { + let store = ChatGptCloudflareCookieStore::default(); + let url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap(); + let cfuvid = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly"); + let account_cookie = + HeaderValue::from_static("chatgpt_session=secret; Path=/; Secure; HttpOnly"); + + store.set_cookies(&mut [&cfuvid, &account_cookie].into_iter(), &url); + + assert_eq!( + store + .cookies(&url) + .and_then(|value| value.to_str().ok().map(str::to_string)), + Some("_cfuvid=visitor".to_string()) + ); + } + + #[test] + fn does_not_return_chatgpt_cloudflare_cookies_for_other_hosts() { + let store = ChatGptCloudflareCookieStore::default(); + let chatgpt_url = + reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap(); + let api_url = reqwest::Url::parse("https://api.openai.com/v1/responses").unwrap(); + let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly"); + + store.set_cookies(&mut std::iter::once(&set_cookie), &chatgpt_url); + + assert_eq!(store.cookies(&api_url), None); + } + + #[test] + fn rejects_plain_http_chatgpt_cookie_urls() { + let store = ChatGptCloudflareCookieStore::default(); + let http_url = reqwest::Url::parse("http://chatgpt.com/backend-api/codex/responses") + .expect("URL should parse"); + let https_url = reqwest::Url::parse("https://chatgpt.com/backend-api/codex/responses") + .expect("URL should parse"); + let set_cookie = HeaderValue::from_static("_cfuvid=visitor; Path=/; Secure; HttpOnly"); + + store.set_cookies(&mut std::iter::once(&set_cookie), &http_url); + + assert_eq!(store.cookies(&http_url), None); + assert_eq!(store.cookies(&https_url), None); + } + + #[test] + fn only_allows_https_urls() { + let url = reqwest::Url::parse("http://chatgpt.com/backend-api/codex/responses").unwrap(); + + assert!(!is_chatgpt_cookie_url(&url)); + + let url = reqwest::Url::parse("wss://chatgpt.com/backend-api/codex/responses").unwrap(); + + assert!(!is_chatgpt_cookie_url(&url)); + } + + #[test] + fn allows_only_known_cloudflare_cookie_names() { + for name in [ + "__cf_bm", + "__cflb", + "__cfruid", + "__cfseq", + "__cfwaitingroom", + "_cfuvid", + "cf_clearance", + "cf_ob_info", + "cf_use_ob", + "cf_chl_rc_i", + ] { + assert!(is_allowed_cloudflare_cookie_name(name)); + } + + for name in [ + "__Secure-next-auth.session-token", + "chatgpt_session", + "oai-auth-token", + "not_cf_clearance", + ] { + assert!(!is_allowed_cloudflare_cookie_name(name)); + } + } +} diff --git a/codex-rs/codex-client/src/chatgpt_hosts.rs b/codex-rs/codex-client/src/chatgpt_hosts.rs new file mode 100644 index 0000000000..dd0b99589c --- /dev/null +++ b/codex-rs/codex-client/src/chatgpt_hosts.rs @@ -0,0 +1,39 @@ +/// Returns whether `host` is one of the ChatGPT hosts Codex is allowed to treat +/// as first-party ChatGPT traffic. +pub fn is_allowed_chatgpt_host(host: &str) -> bool { + const EXACT_HOSTS: &[&str] = &["chatgpt.com", "chat.openai.com", "chatgpt-staging.com"]; + const SUBDOMAIN_SUFFIXES: &[&str] = &[".chatgpt.com", ".chatgpt-staging.com"]; + + EXACT_HOSTS.contains(&host) + || SUBDOMAIN_SUFFIXES + .iter() + .any(|suffix| host.ends_with(suffix)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognizes_chatgpt_hosts_without_suffix_tricks() { + for host in [ + "chatgpt.com", + "foo.chatgpt.com", + "staging.chatgpt.com", + "chat.openai.com", + "chatgpt-staging.com", + "api.chatgpt-staging.com", + ] { + assert!(is_allowed_chatgpt_host(host)); + } + + for host in [ + "evilchatgpt.com", + "chatgpt.com.evil.example", + "api.openai.com", + "foo.chat.openai.com", + ] { + assert!(!is_allowed_chatgpt_host(host)); + } + } +} diff --git a/codex-rs/codex-client/src/lib.rs b/codex-rs/codex-client/src/lib.rs index 7b1bf84753..acabec17a5 100644 --- a/codex-rs/codex-client/src/lib.rs +++ b/codex-rs/codex-client/src/lib.rs @@ -1,3 +1,5 @@ +mod chatgpt_cloudflare_cookies; +mod chatgpt_hosts; mod custom_ca; mod default_client; mod error; @@ -7,6 +9,8 @@ mod sse; mod telemetry; mod transport; +pub use crate::chatgpt_cloudflare_cookies::with_chatgpt_cloudflare_cookie_store; +pub use crate::chatgpt_hosts::is_allowed_chatgpt_host; pub use crate::custom_ca::BuildCustomCaTransportError; /// Test-only subprocess hook for custom CA coverage. /// diff --git a/codex-rs/codex-mcp/src/lib.rs b/codex-rs/codex-mcp/src/lib.rs index 760fc64cfd..8b77086e5e 100644 --- a/codex-rs/codex-mcp/src/lib.rs +++ b/codex-rs/codex-mcp/src/lib.rs @@ -16,18 +16,15 @@ pub use mcp::ToolPluginProvenance; pub use mcp::canonical_mcp_server_key; pub use mcp::collect_mcp_server_status_snapshot; pub use mcp::collect_mcp_server_status_snapshot_with_detail; -pub use mcp::collect_mcp_server_status_snapshot_with_detail_and_authorization_header; pub use mcp::collect_mcp_snapshot; pub use mcp::collect_mcp_snapshot_from_manager; pub use mcp::collect_mcp_snapshot_from_manager_with_detail; pub use mcp::collect_mcp_snapshot_with_detail; -pub use mcp::collect_mcp_snapshot_with_detail_and_authorization_header; pub use mcp::collect_missing_mcp_dependencies; pub use mcp::compute_auth_statuses; pub use mcp::configured_mcp_servers; pub use mcp::discover_supported_scopes; pub use mcp::effective_mcp_servers; -pub use mcp::effective_mcp_servers_with_authorization_header; pub use mcp::group_tools_by_server; pub use mcp::mcp_permission_prompt_is_auto_approved; pub use mcp::oauth_login_support; @@ -38,7 +35,6 @@ pub use mcp::should_retry_without_scopes; pub use mcp::split_qualified_tool_name; pub use mcp::tool_plugin_provenance; pub use mcp::with_codex_apps_mcp; -pub use mcp::with_codex_apps_mcp_with_authorization_header; pub use mcp_connection_manager::CodexAppsToolsCacheKey; pub use mcp_connection_manager::DEFAULT_STARTUP_TIMEOUT; pub use mcp_connection_manager::MCP_SANDBOX_STATE_META_CAPABILITY; diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index 3118c7c171..97053cbe53 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -215,25 +215,14 @@ fn codex_apps_mcp_bearer_token(auth: Option<&CodexAuth>) -> Option { } } -fn codex_apps_mcp_http_headers( - auth: Option<&CodexAuth>, - authorization_header_value: Option<&str>, -) -> Option> { +fn codex_apps_mcp_http_headers(auth: Option<&CodexAuth>) -> Option> { let mut headers = HashMap::new(); - if let Some(authorization_header_value) = authorization_header_value { - headers.insert( - "Authorization".to_string(), - authorization_header_value.to_string(), - ); - } else if let Some(token) = codex_apps_mcp_bearer_token(auth) { + if let Some(token) = codex_apps_mcp_bearer_token(auth) { headers.insert("Authorization".to_string(), format!("Bearer {token}")); } if let Some(account_id) = auth.and_then(CodexAuth::get_account_id) { headers.insert("ChatGPT-Account-ID".to_string(), account_id); } - if auth.is_some_and(CodexAuth::is_fedramp_account) { - headers.insert("X-OpenAI-Fedramp".to_string(), "true".to_string()); - } if headers.is_empty() { None } else { @@ -267,16 +256,12 @@ pub(crate) fn codex_apps_mcp_url(config: &McpConfig) -> String { codex_apps_mcp_url_for_base_url(&config.chatgpt_base_url) } -fn codex_apps_mcp_server_config( - config: &McpConfig, - auth: Option<&CodexAuth>, - authorization_header_value: Option<&str>, -) -> McpServerConfig { +fn codex_apps_mcp_server_config(config: &McpConfig, auth: Option<&CodexAuth>) -> McpServerConfig { let bearer_token_env_var = codex_apps_mcp_bearer_token_env_var(); let http_headers = if bearer_token_env_var.is_some() { None } else { - codex_apps_mcp_http_headers(auth, authorization_header_value) + codex_apps_mcp_http_headers(auth) }; let url = codex_apps_mcp_url(config); @@ -304,25 +289,14 @@ fn codex_apps_mcp_server_config( } pub fn with_codex_apps_mcp( - servers: HashMap, - auth: Option<&CodexAuth>, - config: &McpConfig, -) -> HashMap { - with_codex_apps_mcp_with_authorization_header( - servers, auth, config, /*authorization_header_value*/ None, - ) -} - -pub fn with_codex_apps_mcp_with_authorization_header( mut servers: HashMap, auth: Option<&CodexAuth>, config: &McpConfig, - authorization_header_value: Option<&str>, ) -> HashMap { if config.apps_enabled && auth.is_some_and(CodexAuth::is_chatgpt_auth) { servers.insert( CODEX_APPS_MCP_SERVER_NAME.to_string(), - codex_apps_mcp_server_config(config, auth, authorization_header_value), + codex_apps_mcp_server_config(config, auth), ); } else { servers.remove(CODEX_APPS_MCP_SERVER_NAME); @@ -337,19 +311,9 @@ pub fn configured_mcp_servers(config: &McpConfig) -> HashMap, -) -> HashMap { - effective_mcp_servers_with_authorization_header( - config, auth, /*authorization_header_value*/ None, - ) -} - -pub fn effective_mcp_servers_with_authorization_header( - config: &McpConfig, - auth: Option<&CodexAuth>, - authorization_header_value: Option<&str>, ) -> HashMap { let servers = configured_mcp_servers(config); - with_codex_apps_mcp_with_authorization_header(servers, auth, config, authorization_header_value) + with_codex_apps_mcp(servers, auth, config) } pub fn tool_plugin_provenance(config: &McpConfig) -> ToolPluginProvenance { @@ -420,27 +384,7 @@ pub async fn collect_mcp_snapshot_with_detail( runtime_environment: McpRuntimeEnvironment, detail: McpSnapshotDetail, ) -> McpListToolsResponseEvent { - collect_mcp_snapshot_with_detail_and_authorization_header( - config, - auth, - submit_id, - runtime_environment, - detail, - /*authorization_header_value*/ None, - ) - .await -} - -pub async fn collect_mcp_snapshot_with_detail_and_authorization_header( - config: &McpConfig, - auth: Option<&CodexAuth>, - submit_id: String, - runtime_environment: McpRuntimeEnvironment, - detail: McpSnapshotDetail, - authorization_header_value: Option<&str>, -) -> McpListToolsResponseEvent { - let mcp_servers = - effective_mcp_servers_with_authorization_header(config, auth, authorization_header_value); + let mcp_servers = effective_mcp_servers(config, auth); let tool_plugin_provenance = tool_plugin_provenance(config); if mcp_servers.is_empty() { return McpListToolsResponseEvent { @@ -515,27 +459,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail( runtime_environment: McpRuntimeEnvironment, detail: McpSnapshotDetail, ) -> McpServerStatusSnapshot { - collect_mcp_server_status_snapshot_with_detail_and_authorization_header( - config, - auth, - submit_id, - runtime_environment, - detail, - /*authorization_header_value*/ None, - ) - .await -} - -pub async fn collect_mcp_server_status_snapshot_with_detail_and_authorization_header( - config: &McpConfig, - auth: Option<&CodexAuth>, - submit_id: String, - runtime_environment: McpRuntimeEnvironment, - detail: McpSnapshotDetail, - authorization_header_value: Option<&str>, -) -> McpServerStatusSnapshot { - let mcp_servers = - effective_mcp_servers_with_authorization_header(config, auth, authorization_header_value); + let mcp_servers = effective_mcp_servers(config, auth); let tool_plugin_provenance = tool_plugin_provenance(config); if mcp_servers.is_empty() { return McpServerStatusSnapshot { diff --git a/codex-rs/core-skills/src/lib.rs b/codex-rs/core-skills/src/lib.rs index 6d3ac7a4fe..06ced0d5d4 100644 --- a/codex-rs/core-skills/src/lib.rs +++ b/codex-rs/core-skills/src/lib.rs @@ -22,8 +22,8 @@ pub use model::SkillLoadOutcome; pub use model::SkillMetadata; pub use model::SkillPolicy; pub use model::filter_skill_load_outcome_for_product; -pub use render::RenderedSkillsSection; +pub use render::AvailableSkills; pub use render::SkillMetadataBudget; pub use render::SkillRenderReport; +pub use render::build_available_skills; pub use render::default_skill_metadata_budget; -pub use render::render_skills_section; diff --git a/codex-rs/core-skills/src/remote.rs b/codex-rs/core-skills/src/remote.rs index c85c78ff8d..2dc620b864 100644 --- a/codex-rs/core-skills/src/remote.rs +++ b/codex-rs/core-skills/src/remote.rs @@ -6,9 +6,7 @@ use std::path::Path; use std::path::PathBuf; use std::time::Duration; -use codex_login::BackgroundAgentTaskAuthMode; use codex_login::CodexAuth; -use codex_login::cached_background_agent_task_authorization_header_value; use codex_login::default_client::build_reqwest_client; const REMOTE_SKILLS_API_TIMEOUT: Duration = Duration::from_secs(30); @@ -114,15 +112,13 @@ pub async fn list_remote_skills( .get(&url) .timeout(REMOTE_SKILLS_API_TIMEOUT) .query(&query_params); - let authorization_header_value = authorization_header_value_for_auth(auth) + let token = auth + .get_token() .context("Failed to read auth token for remote skills")?; - request = request.header("authorization", authorization_header_value); + request = request.bearer_auth(token); if let Some(account_id) = auth.get_account_id() { request = request.header("chatgpt-account-id", account_id); } - if auth.is_fedramp_account() { - request = request.header("X-OpenAI-Fedramp", "true"); - } let response = request .send() .await @@ -161,15 +157,13 @@ pub async fn export_remote_skill( let url = format!("{base_url}/hazelnuts/{skill_id}/export"); let mut request = client.get(&url).timeout(REMOTE_SKILLS_API_TIMEOUT); - let authorization_header_value = authorization_header_value_for_auth(auth) + let token = auth + .get_token() .context("Failed to read auth token for remote skills")?; - request = request.header("authorization", authorization_header_value); + request = request.bearer_auth(token); if let Some(account_id) = auth.get_account_id() { request = request.header("chatgpt-account-id", account_id); } - if auth.is_fedramp_account() { - request = request.header("X-OpenAI-Fedramp", "true"); - } let response = request .send() @@ -207,19 +201,6 @@ pub async fn export_remote_skill( }) } -fn authorization_header_value_for_auth(auth: &CodexAuth) -> std::io::Result { - if let Ok(Some(authorization_header_value)) = - cached_background_agent_task_authorization_header_value( - auth, - BackgroundAgentTaskAuthMode::Disabled, - ) - { - Ok(authorization_header_value) - } else { - auth.get_token().map(|token| format!("Bearer {token}")) - } -} - fn safe_join(base: &Path, name: &str) -> Result { let path = Path::new(name); for component in path.components() { diff --git a/codex-rs/core-skills/src/render.rs b/codex-rs/core-skills/src/render.rs index ad674fbffa..6bcd5e4e05 100644 --- a/codex-rs/core-skills/src/render.rs +++ b/codex-rs/core-skills/src/render.rs @@ -3,8 +3,6 @@ use codex_otel::SessionTelemetry; use codex_otel::THREAD_SKILLS_ENABLED_TOTAL_METRIC; use codex_otel::THREAD_SKILLS_KEPT_TOTAL_METRIC; use codex_otel::THREAD_SKILLS_TRUNCATED_METRIC; -use codex_protocol::protocol::SKILLS_INSTRUCTIONS_CLOSE_TAG; -use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG; use codex_protocol::protocol::SkillScope; use codex_utils_output_truncation::approx_token_count; @@ -48,8 +46,8 @@ pub enum SkillRenderSideEffects<'a> { } #[derive(Debug, Clone, PartialEq, Eq)] -pub struct RenderedSkillsSection { - pub text: String, +pub struct AvailableSkills { + pub skill_lines: Vec, pub report: SkillRenderReport, pub emit_warning: bool, } @@ -71,11 +69,11 @@ pub fn default_skill_metadata_budget(context_window: Option) -> SkillMetada )) } -pub fn render_skills_section( +pub fn build_available_skills( skills: &[SkillMetadata], budget: SkillMetadataBudget, side_effects: SkillRenderSideEffects<'_>, -) -> Option { +) -> Option { if skills.is_empty() { let _ = record_skill_render_side_effects( side_effects, @@ -93,39 +91,8 @@ pub fn render_skills_section( report.included_count, report.omitted_count > 0, ); - let mut lines: Vec = Vec::new(); - lines.push("## Skills".to_string()); - lines.push("A skill is a set of local instructions to follow that is stored in a `SKILL.md` file. Below is the list of skills that can be used. Each entry includes a name, description, and file path so you can open the source for full instructions when using a specific skill.".to_string()); - lines.push("### Available skills".to_string()); - if !skill_lines.is_empty() { - lines.extend(skill_lines); - } - - lines.push("### How to use skills".to_string()); - lines.push( - r###"- Discovery: The list above is the skills available in this session (name + description + file path). Skill bodies live on disk at the listed paths. -- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned. -- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback. -- How to use a skill (progressive disclosure): - 1) After deciding to use a skill, open its `SKILL.md`. Read only enough to follow the workflow. - 2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the skill directory listed above first, and only consider other paths if needed. - 3) If `SKILL.md` points to extra folders such as `references/`, load only the specific files needed for the request; don't bulk-load everything. - 4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks. - 5) If `assets/` or templates exist, reuse them instead of recreating from scratch. -- Coordination and sequencing: - - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them. - - Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why. -- Context hygiene: - - Keep context small: summarize long sections instead of pasting them; only load extra files when needed. - - Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked. - - When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice. -- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue."### - .to_string(), - ); - - let body = lines.join("\n"); - Some(RenderedSkillsSection { - text: format!("{SKILLS_INSTRUCTIONS_OPEN_TAG}\n{body}\n{SKILLS_INSTRUCTIONS_CLOSE_TAG}"), + Some(AvailableSkills { + skill_lines, report, emit_warning, }) @@ -274,7 +241,7 @@ mod tests { .cost(&format!("{}\n", render_skill_line(&admin))); let budget = SkillMetadataBudget::Characters(system_cost + admin_cost); - let rendered = render_skills_section( + let rendered = build_available_skills( &[system, user, repo, admin], budget, SkillRenderSideEffects::None, @@ -284,10 +251,11 @@ mod tests { assert_eq!(rendered.report.included_count, 2); assert_eq!(rendered.report.omitted_count, 2); assert!(!rendered.emit_warning); - assert!(rendered.text.contains("- system-skill:")); - assert!(rendered.text.contains("- admin-skill:")); - assert!(!rendered.text.contains("- repo-skill:")); - assert!(!rendered.text.contains("- user-skill:")); + let rendered_text = rendered.skill_lines.join("\n"); + assert!(rendered_text.contains("- system-skill:")); + assert!(rendered_text.contains("- admin-skill:")); + assert!(!rendered_text.contains("- repo-skill:")); + assert!(!rendered_text.contains("- user-skill:")); } #[test] @@ -300,13 +268,14 @@ mod tests { let budget = SkillMetadataBudget::Characters(repo_cost); let rendered = - render_skills_section(&[oversized, repo], budget, SkillRenderSideEffects::None) + build_available_skills(&[oversized, repo], budget, SkillRenderSideEffects::None) .expect("skills render"); assert_eq!(rendered.report.included_count, 1); assert_eq!(rendered.report.omitted_count, 1); assert!(!rendered.emit_warning); - assert!(!rendered.text.contains("- oversized-system-skill:")); - assert!(rendered.text.contains("- repo-skill:")); + let rendered_text = rendered.skill_lines.join("\n"); + assert!(!rendered_text.contains("- oversized-system-skill:")); + assert!(rendered_text.contains("- repo-skill:")); } } diff --git a/codex-rs/core/BUILD.bazel b/codex-rs/core/BUILD.bazel index dd52bce43d..df5f4da1fa 100644 --- a/codex-rs/core/BUILD.bazel +++ b/codex-rs/core/BUILD.bazel @@ -57,7 +57,6 @@ codex_rust_crate( "//codex-rs/linux-sandbox:codex-linux-sandbox", "//codex-rs/rmcp-client:test_stdio_server", "//codex-rs/rmcp-client:test_streamable_http_server", - "//codex-rs/responses-api-proxy:codex-responses-api-proxy", "//codex-rs/cli:codex", ], ) diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 6ef6741fd9..86d6f8b0f3 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -35,7 +35,6 @@ codex-connectors = { workspace = true } codex-config = { workspace = true } codex-core-plugins = { workspace = true } codex-core-skills = { workspace = true } -crypto_box = { workspace = true } codex-exec-server = { workspace = true } codex-features = { workspace = true } codex-feedback = { workspace = true } @@ -43,7 +42,6 @@ codex-login = { workspace = true } codex-mcp = { workspace = true } codex-model-provider-info = { workspace = true } codex-models-manager = { workspace = true } -ed25519-dalek = { workspace = true } codex-shell-command = { workspace = true } codex-execpolicy = { workspace = true } codex-git-utils = { workspace = true } @@ -100,11 +98,9 @@ rmcp = { workspace = true, default-features = false, features = [ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } sha1 = { workspace = true } -sha2 = { workspace = true } shlex = { workspace = true } similar = { workspace = true } tempfile = { workspace = true } -test-log = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = [ "io-std", @@ -148,7 +144,6 @@ codex-shell-escalation = { workspace = true } [dev-dependencies] assert_cmd = { workspace = true } assert_matches = { workspace = true } -codex-arg0 = { workspace = true } codex-otel = { workspace = true } codex-test-binary-support = { workspace = true } codex-utils-cargo-bin = { workspace = true } @@ -166,6 +161,7 @@ opentelemetry_sdk = { workspace = true, features = [ ] } serial_test = { workspace = true } tempfile = { workspace = true } +test-log = { workspace = true } tracing-opentelemetry = { workspace = true } tracing-subscriber = { workspace = true } tracing-test = { workspace = true, features = ["no-env-filter"] } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index b0faea2b56..3f97359917 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -521,9 +521,6 @@ "unified_exec": { "type": "boolean" }, - "use_agent_identity": { - "type": "boolean" - }, "use_legacy_landlock": { "type": "boolean" }, @@ -2520,9 +2517,6 @@ "unified_exec": { "type": "boolean" }, - "use_agent_identity": { - "type": "boolean" - }, "use_legacy_landlock": { "type": "boolean" }, diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 8004f6e6ed..1c30d613e0 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -116,11 +116,10 @@ fn keep_forked_rollout_item(item: &RolloutItem) -> bool { | ResponseItem::Compaction { .. } | ResponseItem::Other, ) => false, - RolloutItem::SessionState(_) => false, - RolloutItem::Compacted(_) - | RolloutItem::EventMsg(_) - | RolloutItem::SessionMeta(_) - | RolloutItem::TurnContext(_) => true, + // A forked child gets its own runtime config, including spawned-agent + // instructions, so it must establish a fresh context diff baseline. + RolloutItem::TurnContext(_) => false, + RolloutItem::Compacted(_) | RolloutItem::EventMsg(_) | RolloutItem::SessionMeta(_) => true, } } diff --git a/codex-rs/core/src/agent_identity.rs b/codex-rs/core/src/agent_identity.rs deleted file mode 100644 index 3a4c6787f2..0000000000 --- a/codex-rs/core/src/agent_identity.rs +++ /dev/null @@ -1,848 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use anyhow::Context; -use anyhow::Result; -use base64::Engine as _; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use chrono::SecondsFormat; -use chrono::Utc; -use codex_features::Feature; -use codex_login::AgentIdentityAuthRecord; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_login::default_client::create_client; -use codex_protocol::protocol::SessionSource; -use ed25519_dalek::SigningKey; -use ed25519_dalek::VerifyingKey; -use ed25519_dalek::pkcs8::DecodePrivateKey; -use ed25519_dalek::pkcs8::EncodePrivateKey; -use rand::TryRngCore; -use rand::rngs::OsRng; -use serde::Deserialize; -use serde::Serialize; -use tokio::sync::Semaphore; -use tracing::debug; -use tracing::info; -use tracing::warn; - -use crate::config::Config; - -mod task_registration; - -pub(crate) use task_registration::RegisteredAgentTask; - -const AGENT_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(15); -const AGENT_IDENTITY_BISCUIT_TIMEOUT: Duration = Duration::from_secs(15); - -#[derive(Clone)] -pub(crate) struct AgentIdentityManager { - auth_manager: Arc, - chatgpt_base_url: String, - feature_enabled: bool, - abom: AgentBillOfMaterials, - ensure_lock: Arc, -} - -impl std::fmt::Debug for AgentIdentityManager { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AgentIdentityManager") - .field("chatgpt_base_url", &self.chatgpt_base_url) - .field("feature_enabled", &self.feature_enabled) - .field("abom", &self.abom) - .finish_non_exhaustive() - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub(crate) struct StoredAgentIdentity { - pub(crate) binding_id: String, - pub(crate) chatgpt_account_id: String, - pub(crate) chatgpt_user_id: Option, - pub(crate) agent_runtime_id: String, - pub(crate) private_key_pkcs8_base64: String, - pub(crate) public_key_ssh: String, - pub(crate) registered_at: String, - pub(crate) abom: AgentBillOfMaterials, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub(crate) struct AgentBillOfMaterials { - pub(crate) agent_version: String, - pub(crate) agent_harness_id: String, - pub(crate) running_location: String, -} - -#[derive(Debug, Serialize)] -struct RegisterAgentRequest { - abom: AgentBillOfMaterials, - agent_public_key: String, - capabilities: Vec, -} - -#[derive(Debug, Deserialize)] -struct RegisterAgentResponse { - agent_runtime_id: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct AgentIdentityBinding { - binding_id: String, - chatgpt_account_id: String, - chatgpt_user_id: Option, - access_token: String, -} - -struct GeneratedAgentKeyMaterial { - private_key_pkcs8_base64: String, - public_key_ssh: String, -} - -impl AgentIdentityManager { - pub(crate) fn new( - config: &Config, - auth_manager: Arc, - session_source: SessionSource, - ) -> Self { - Self { - auth_manager, - chatgpt_base_url: config.chatgpt_base_url.clone(), - feature_enabled: config.features.enabled(Feature::UseAgentIdentity), - abom: build_abom(session_source), - ensure_lock: Arc::new(Semaphore::new(/*permits*/ 1)), - } - } - - pub(crate) fn is_enabled(&self) -> bool { - self.feature_enabled - } - - pub(crate) async fn ensure_registered_identity(&self) -> Result> { - if !self.feature_enabled { - return Ok(None); - } - - let Some((auth, binding)) = self.current_auth_binding().await else { - return Ok(None); - }; - - self.ensure_registered_identity_for_binding(&auth, &binding) - .await - .map(Some) - } - - async fn ensure_registered_identity_for_binding( - &self, - auth: &CodexAuth, - binding: &AgentIdentityBinding, - ) -> Result { - let _guard = self - .ensure_lock - .acquire() - .await - .map_err(|_| anyhow::anyhow!("agent identity ensure semaphore closed"))?; - - if let Some(stored_identity) = self.load_stored_identity(auth, binding)? { - info!( - agent_runtime_id = %stored_identity.agent_runtime_id, - binding_id = %binding.binding_id, - "reusing stored agent identity" - ); - return Ok(stored_identity); - } - - let stored_identity = self.register_agent_identity(binding).await?; - self.store_identity(auth, &stored_identity)?; - Ok(stored_identity) - } - - pub(crate) async fn task_matches_current_identity(&self, task: &RegisteredAgentTask) -> bool { - if !self.feature_enabled { - return false; - } - - self.current_stored_identity() - .await - .is_some_and(|stored_identity| { - stored_identity.agent_runtime_id == task.agent_runtime_id - }) - } - - async fn current_auth_binding(&self) -> Option<(CodexAuth, AgentIdentityBinding)> { - let Some(auth) = self.auth_manager.auth().await else { - debug!("skipping agent identity flow because no auth is available"); - return None; - }; - - let binding = - AgentIdentityBinding::from_auth(&auth, self.auth_manager.forced_chatgpt_workspace_id()); - if binding.is_none() { - debug!("skipping agent identity flow because ChatGPT auth is unavailable"); - } - binding.map(|binding| (auth, binding)) - } - - async fn current_stored_identity(&self) -> Option { - let (auth, binding) = self.current_auth_binding().await?; - self.load_stored_identity(&auth, &binding).ok().flatten() - } - - async fn register_agent_identity( - &self, - binding: &AgentIdentityBinding, - ) -> Result { - let key_material = generate_agent_key_material()?; - let request_body = RegisterAgentRequest { - abom: self.abom.clone(), - agent_public_key: key_material.public_key_ssh.clone(), - capabilities: Vec::new(), - }; - - let url = agent_registration_url(&self.chatgpt_base_url); - let human_biscuit = self.mint_human_biscuit(binding, "POST", &url).await?; - let client = create_client(); - let response = client - .post(&url) - .header("X-OpenAI-Authorization", human_biscuit) - .json(&request_body) - .timeout(AGENT_REGISTRATION_TIMEOUT) - .send() - .await - .with_context(|| { - format!("failed to send agent identity registration request to {url}") - })?; - - if response.status().is_success() { - let response_body = response - .json::() - .await - .with_context(|| format!("failed to parse agent identity response from {url}"))?; - let stored_identity = StoredAgentIdentity { - binding_id: binding.binding_id.clone(), - chatgpt_account_id: binding.chatgpt_account_id.clone(), - chatgpt_user_id: binding.chatgpt_user_id.clone(), - agent_runtime_id: response_body.agent_runtime_id, - private_key_pkcs8_base64: key_material.private_key_pkcs8_base64, - public_key_ssh: key_material.public_key_ssh, - registered_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), - abom: self.abom.clone(), - }; - info!( - agent_runtime_id = %stored_identity.agent_runtime_id, - binding_id = %binding.binding_id, - "registered agent identity" - ); - return Ok(stored_identity); - } - - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - anyhow::bail!("agent identity registration failed with status {status} from {url}: {body}") - } - - async fn mint_human_biscuit( - &self, - binding: &AgentIdentityBinding, - target_method: &str, - target_url: &str, - ) -> Result { - let url = agent_identity_biscuit_url(&self.chatgpt_base_url); - let request_id = agent_identity_request_id()?; - let client = create_client(); - let response = client - .get(&url) - .bearer_auth(&binding.access_token) - .header("X-Request-Id", request_id.clone()) - .header("X-Original-Method", target_method) - .header("X-Original-Url", target_url) - .timeout(AGENT_IDENTITY_BISCUIT_TIMEOUT) - .send() - .await - .with_context(|| format!("failed to send agent identity biscuit request to {url}"))?; - - if response.status().is_success() { - let human_biscuit = response - .headers() - .get("x-openai-authorization") - .context("agent identity biscuit response did not include x-openai-authorization")? - .to_str() - .context("agent identity biscuit response header was not valid UTF-8")? - .to_string(); - info!( - request_id = %request_id, - "minted human biscuit for agent identity registration" - ); - return Ok(human_biscuit); - } - - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - anyhow::bail!( - "agent identity biscuit minting failed with status {status} from {url}: {body}" - ) - } - - fn load_stored_identity( - &self, - auth: &CodexAuth, - binding: &AgentIdentityBinding, - ) -> Result> { - let Some(record) = auth.get_agent_identity(&binding.chatgpt_account_id) else { - return Ok(None); - }; - - let stored_identity = - match StoredAgentIdentity::from_auth_record(binding, record, self.abom.clone()) { - Ok(stored_identity) => stored_identity, - Err(error) => { - warn!( - binding_id = %binding.binding_id, - error = %error, - "stored agent identity is invalid; deleting cached value" - ); - auth.remove_agent_identity()?; - return Ok(None); - } - }; - - if !stored_identity.matches_binding(binding) { - warn!( - binding_id = %binding.binding_id, - "stored agent identity binding no longer matches current auth; deleting cached value" - ); - auth.remove_agent_identity()?; - return Ok(None); - } - - if let Err(error) = stored_identity.validate_key_material() { - warn!( - agent_runtime_id = %stored_identity.agent_runtime_id, - binding_id = %binding.binding_id, - error = %error, - "stored agent identity key material is invalid; deleting cached value" - ); - auth.remove_agent_identity()?; - return Ok(None); - } - - Ok(Some(stored_identity)) - } - - fn store_identity( - &self, - auth: &CodexAuth, - stored_identity: &StoredAgentIdentity, - ) -> Result<()> { - auth.set_agent_identity(stored_identity.to_auth_record())?; - Ok(()) - } - - #[cfg(test)] - pub(crate) fn new_for_tests( - auth_manager: Arc, - feature_enabled: bool, - chatgpt_base_url: String, - session_source: SessionSource, - ) -> Self { - Self { - auth_manager, - chatgpt_base_url, - feature_enabled, - abom: build_abom(session_source), - ensure_lock: Arc::new(Semaphore::new(/*permits*/ 1)), - } - } - - #[cfg(test)] - pub(crate) async fn seed_generated_identity_for_tests( - &self, - agent_runtime_id: &str, - ) -> Result { - let (auth, binding) = self - .current_auth_binding() - .await - .context("test agent identity requires ChatGPT auth")?; - let key_material = generate_agent_key_material()?; - let stored_identity = StoredAgentIdentity { - binding_id: binding.binding_id.clone(), - chatgpt_account_id: binding.chatgpt_account_id.clone(), - chatgpt_user_id: binding.chatgpt_user_id, - agent_runtime_id: agent_runtime_id.to_string(), - private_key_pkcs8_base64: key_material.private_key_pkcs8_base64, - public_key_ssh: key_material.public_key_ssh, - registered_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), - abom: self.abom.clone(), - }; - self.store_identity(&auth, &stored_identity)?; - Ok(stored_identity) - } -} - -impl StoredAgentIdentity { - fn from_auth_record( - binding: &AgentIdentityBinding, - record: AgentIdentityAuthRecord, - abom: AgentBillOfMaterials, - ) -> Result { - if record.workspace_id != binding.chatgpt_account_id { - anyhow::bail!( - "stored agent identity workspace {:?} does not match current workspace {:?}", - record.workspace_id, - binding.chatgpt_account_id - ); - } - let signing_key = signing_key_from_private_key_pkcs8_base64(&record.agent_private_key)?; - Ok(Self { - binding_id: binding.binding_id.clone(), - chatgpt_account_id: binding.chatgpt_account_id.clone(), - chatgpt_user_id: record.chatgpt_user_id, - agent_runtime_id: record.agent_runtime_id, - private_key_pkcs8_base64: record.agent_private_key, - public_key_ssh: encode_ssh_ed25519_public_key(&signing_key.verifying_key()), - registered_at: record.registered_at, - abom, - }) - } - - fn to_auth_record(&self) -> AgentIdentityAuthRecord { - AgentIdentityAuthRecord { - workspace_id: self.chatgpt_account_id.clone(), - chatgpt_user_id: self.chatgpt_user_id.clone(), - agent_runtime_id: self.agent_runtime_id.clone(), - agent_private_key: self.private_key_pkcs8_base64.clone(), - registered_at: self.registered_at.clone(), - background_task_id: None, - } - } - - fn matches_binding(&self, binding: &AgentIdentityBinding) -> bool { - binding.matches_parts( - &self.binding_id, - &self.chatgpt_account_id, - self.chatgpt_user_id.as_deref(), - ) - } - - fn validate_key_material(&self) -> Result<()> { - let signing_key = self.signing_key()?; - let derived_public_key = encode_ssh_ed25519_public_key(&signing_key.verifying_key()); - anyhow::ensure!( - self.public_key_ssh == derived_public_key, - "stored public key does not match the private key" - ); - Ok(()) - } - - pub(crate) fn signing_key(&self) -> Result { - signing_key_from_private_key_pkcs8_base64(&self.private_key_pkcs8_base64) - } -} - -impl AgentIdentityBinding { - fn matches_parts( - &self, - binding_id: &str, - chatgpt_account_id: &str, - chatgpt_user_id: Option<&str>, - ) -> bool { - binding_id == self.binding_id - && chatgpt_account_id == self.chatgpt_account_id - && match self.chatgpt_user_id.as_deref() { - Some(expected_user_id) => chatgpt_user_id == Some(expected_user_id), - None => true, - } - } - - fn from_auth(auth: &CodexAuth, forced_workspace_id: Option) -> Option { - if !auth.is_chatgpt_auth() { - return None; - } - - let token_data = auth.get_token_data().ok()?; - let resolved_account_id = - forced_workspace_id - .filter(|value| !value.is_empty()) - .or(token_data - .account_id - .clone() - .filter(|value| !value.is_empty()))?; - - Some(Self { - binding_id: format!("chatgpt-account-{resolved_account_id}"), - chatgpt_account_id: resolved_account_id, - chatgpt_user_id: token_data - .id_token - .chatgpt_user_id - .filter(|value| !value.is_empty()), - access_token: token_data.access_token, - }) - } -} - -fn build_abom(session_source: SessionSource) -> AgentBillOfMaterials { - AgentBillOfMaterials { - agent_version: env!("CARGO_PKG_VERSION").to_string(), - agent_harness_id: match &session_source { - SessionSource::VSCode => "codex-app".to_string(), - SessionSource::Cli - | SessionSource::Exec - | SessionSource::Mcp - | SessionSource::Custom(_) - | SessionSource::SubAgent(_) - | SessionSource::Unknown => "codex-cli".to_string(), - }, - running_location: format!("{}-{}", session_source, std::env::consts::OS), - } -} - -fn generate_agent_key_material() -> Result { - let mut secret_key_bytes = [0u8; 32]; - OsRng - .try_fill_bytes(&mut secret_key_bytes) - .context("failed to generate agent identity private key bytes")?; - let signing_key = SigningKey::from_bytes(&secret_key_bytes); - let private_key_pkcs8 = signing_key - .to_pkcs8_der() - .context("failed to encode agent identity private key as PKCS#8")?; - - Ok(GeneratedAgentKeyMaterial { - private_key_pkcs8_base64: BASE64_STANDARD.encode(private_key_pkcs8.as_bytes()), - public_key_ssh: encode_ssh_ed25519_public_key(&signing_key.verifying_key()), - }) -} - -fn encode_ssh_ed25519_public_key(verifying_key: &VerifyingKey) -> String { - let mut blob = Vec::with_capacity(4 + 11 + 4 + 32); - append_ssh_string(&mut blob, b"ssh-ed25519"); - append_ssh_string(&mut blob, verifying_key.as_bytes()); - format!("ssh-ed25519 {}", BASE64_STANDARD.encode(blob)) -} - -fn append_ssh_string(buf: &mut Vec, value: &[u8]) { - buf.extend_from_slice(&(value.len() as u32).to_be_bytes()); - buf.extend_from_slice(value); -} - -fn agent_registration_url(chatgpt_base_url: &str) -> String { - let trimmed = chatgpt_base_url.trim_end_matches('/'); - format!("{trimmed}/v1/agent/register") -} - -fn signing_key_from_private_key_pkcs8_base64(private_key_pkcs8_base64: &str) -> Result { - let private_key = BASE64_STANDARD - .decode(private_key_pkcs8_base64) - .context("stored agent identity private key is not valid base64")?; - SigningKey::from_pkcs8_der(&private_key) - .context("stored agent identity private key is not valid PKCS#8") -} - -fn agent_identity_biscuit_url(chatgpt_base_url: &str) -> String { - let trimmed = chatgpt_base_url.trim_end_matches('/'); - format!("{trimmed}/authenticate_app_v2") -} - -fn agent_identity_request_id() -> Result { - let mut request_id_bytes = [0u8; 16]; - OsRng - .try_fill_bytes(&mut request_id_bytes) - .context("failed to generate agent identity request id")?; - Ok(format!( - "codex-agent-identity-{}", - URL_SAFE_NO_PAD.encode(request_id_bytes) - )) -} - -#[cfg(test)] -mod tests { - use super::*; - - use base64::engine::general_purpose::URL_SAFE_NO_PAD; - use codex_app_server_protocol::AuthMode as ApiAuthMode; - use codex_login::AuthCredentialsStoreMode; - use codex_login::AuthDotJson; - use codex_login::save_auth; - use codex_login::token_data::IdTokenInfo; - use codex_login::token_data::TokenData; - use pretty_assertions::assert_eq; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::header; - use wiremock::matchers::method; - use wiremock::matchers::path; - - #[tokio::test] - async fn ensure_registered_identity_skips_when_feature_is_disabled() { - let auth_manager = - AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123"))); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ false, - "https://chatgpt.com/backend-api/".to_string(), - SessionSource::Cli, - ); - - assert_eq!(manager.ensure_registered_identity().await.unwrap(), None); - } - - #[tokio::test] - async fn ensure_registered_identity_skips_for_api_key_auth() { - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key")); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - "https://chatgpt.com/backend-api/".to_string(), - SessionSource::Cli, - ); - - assert_eq!(manager.ensure_registered_identity().await.unwrap(), None); - } - - #[tokio::test] - async fn ensure_registered_identity_registers_and_reuses_cached_identity() { - let server = MockServer::start().await; - let chatgpt_base_url = server.uri(); - mount_human_biscuit(&server, &chatgpt_base_url).await; - Mock::given(method("POST")) - .and(path("/v1/agent/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "agent_runtime_id": "agent-123", - }))) - .expect(1) - .mount(&server) - .await; - - let auth_manager = - AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123"))); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - - let first = manager - .ensure_registered_identity() - .await - .unwrap() - .expect("identity should be registered"); - let second = manager - .ensure_registered_identity() - .await - .unwrap() - .expect("identity should be reused"); - - assert_eq!(first.agent_runtime_id, "agent-123"); - assert_eq!(first, second); - assert_eq!(first.abom.agent_harness_id, "codex-cli"); - assert_eq!(first.chatgpt_account_id, "account-123"); - assert_eq!(first.chatgpt_user_id.as_deref(), Some("user-123")); - } - - #[tokio::test] - async fn ensure_registered_identity_deletes_invalid_cached_identity_and_reregisters() { - let server = MockServer::start().await; - let chatgpt_base_url = server.uri(); - mount_human_biscuit(&server, &chatgpt_base_url).await; - Mock::given(method("POST")) - .and(path("/v1/agent/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "agent_runtime_id": "agent-456", - }))) - .expect(1) - .mount(&server) - .await; - - let auth = make_chatgpt_auth("account-123", Some("user-123")); - let auth_manager = AuthManager::from_auth_for_testing(auth.clone()); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - - let binding = - AgentIdentityBinding::from_auth(&auth, /*forced_workspace_id*/ None).expect("binding"); - auth.set_agent_identity(AgentIdentityAuthRecord { - workspace_id: "account-123".to_string(), - chatgpt_user_id: Some("user-123".to_string()), - agent_runtime_id: "agent_invalid".to_string(), - agent_private_key: "not-valid-base64".to_string(), - registered_at: "2026-01-01T00:00:00Z".to_string(), - background_task_id: None, - }) - .expect("seed invalid identity"); - - let stored = manager - .ensure_registered_identity() - .await - .unwrap() - .expect("identity should be registered"); - - assert_eq!(stored.agent_runtime_id, "agent-456"); - let persisted = auth - .get_agent_identity(&binding.chatgpt_account_id) - .expect("stored identity"); - assert_eq!(persisted.agent_runtime_id, "agent-456"); - } - - #[tokio::test] - async fn ensure_registered_identity_deletes_different_user_identity_and_reregisters() { - let server = MockServer::start().await; - let chatgpt_base_url = server.uri(); - mount_human_biscuit(&server, &chatgpt_base_url).await; - Mock::given(method("POST")) - .and(path("/v1/agent/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "agent_runtime_id": "agent_new", - }))) - .expect(1) - .mount(&server) - .await; - - let auth = make_chatgpt_auth("account-123", Some("user-new")); - let stale_key = generate_agent_key_material().expect("key material"); - auth.set_agent_identity(AgentIdentityAuthRecord { - workspace_id: "account-123".to_string(), - chatgpt_user_id: Some("user-old".to_string()), - agent_runtime_id: "agent_old".to_string(), - agent_private_key: stale_key.private_key_pkcs8_base64, - registered_at: "2026-01-01T00:00:00Z".to_string(), - background_task_id: None, - }) - .expect("seed stale identity"); - - let auth_manager = AuthManager::from_auth_for_testing(auth.clone()); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - - let stored = manager - .ensure_registered_identity() - .await - .unwrap() - .expect("identity should be registered"); - - assert_eq!(stored.agent_runtime_id, "agent_new"); - assert_eq!(stored.chatgpt_user_id.as_deref(), Some("user-new")); - let persisted = auth - .get_agent_identity("account-123") - .expect("stored identity"); - assert_eq!(persisted.agent_runtime_id, "agent_new"); - assert_eq!(persisted.chatgpt_user_id.as_deref(), Some("user-new")); - } - - #[tokio::test] - async fn ensure_registered_identity_uses_chatgpt_base_url() { - let server = MockServer::start().await; - let chatgpt_base_url = format!("{}/backend-api", server.uri()); - mount_human_biscuit(&server, &chatgpt_base_url).await; - Mock::given(method("POST")) - .and(path("/backend-api/v1/agent/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "agent_runtime_id": "agent_canonical", - }))) - .expect(1) - .mount(&server) - .await; - - let auth_manager = - AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123"))); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - - let stored = manager - .ensure_registered_identity() - .await - .unwrap() - .expect("identity should be registered"); - assert_eq!(stored.agent_runtime_id, "agent_canonical"); - } - - async fn mount_human_biscuit(server: &MockServer, chatgpt_base_url: &str) { - let biscuit_url = agent_identity_biscuit_url(chatgpt_base_url); - let biscuit_path = reqwest::Url::parse(&biscuit_url) - .expect("biscuit URL parses") - .path() - .to_string(); - let target_url = agent_registration_url(chatgpt_base_url); - Mock::given(method("GET")) - .and(path(biscuit_path)) - .and(header("authorization", "Bearer access-token-account-123")) - .and(header("x-original-method", "POST")) - .and(header("x-original-url", target_url)) - .respond_with( - ResponseTemplate::new(200).insert_header("x-openai-authorization", "human-biscuit"), - ) - .expect(1) - .mount(server) - .await; - } - - #[test] - fn encode_ssh_ed25519_public_key_matches_expected_wire_shape() { - let key_material = generate_agent_key_material().expect("key material"); - let (_, encoded_blob) = key_material - .public_key_ssh - .split_once(' ') - .expect("public key contains scheme"); - let decoded = BASE64_STANDARD.decode(encoded_blob).expect("base64"); - - assert_eq!(&decoded[..4], 11u32.to_be_bytes().as_slice()); - assert_eq!(&decoded[4..15], b"ssh-ed25519"); - assert_eq!(&decoded[15..19], 32u32.to_be_bytes().as_slice()); - assert_eq!(decoded.len(), 51); - } - - fn make_chatgpt_auth(account_id: &str, user_id: Option<&str>) -> CodexAuth { - let tempdir = tempfile::tempdir().expect("tempdir"); - let auth_json = AuthDotJson { - auth_mode: Some(ApiAuthMode::Chatgpt), - openai_api_key: None, - tokens: Some(TokenData { - id_token: IdTokenInfo { - email: None, - chatgpt_plan_type: None, - chatgpt_user_id: user_id.map(ToOwned::to_owned), - chatgpt_account_id: Some(account_id.to_string()), - chatgpt_account_is_fedramp: false, - raw_jwt: fake_id_token(account_id, user_id), - }, - access_token: format!("access-token-{account_id}"), - refresh_token: "refresh-token".to_string(), - account_id: Some(account_id.to_string()), - }), - last_refresh: Some(Utc::now()), - agent_identity: None, - }; - save_auth(tempdir.path(), &auth_json, AuthCredentialsStoreMode::File).expect("save auth"); - CodexAuth::from_auth_storage(tempdir.path(), AuthCredentialsStoreMode::File) - .expect("load auth") - .expect("auth") - } - - fn fake_id_token(account_id: &str, user_id: Option<&str>) -> String { - let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"none","typ":"JWT"}"#); - let payload = serde_json::json!({ - "https://api.openai.com/auth": { - "chatgpt_user_id": user_id, - "chatgpt_account_id": account_id, - } - }); - let payload = URL_SAFE_NO_PAD.encode(payload.to_string()); - format!("{header}.{payload}.signature") - } -} diff --git a/codex-rs/core/src/agent_identity/task_registration.rs b/codex-rs/core/src/agent_identity/task_registration.rs deleted file mode 100644 index d00f7d25e4..0000000000 --- a/codex-rs/core/src/agent_identity/task_registration.rs +++ /dev/null @@ -1,466 +0,0 @@ -use std::time::Duration; - -use anyhow::Context; -use anyhow::Result; -use codex_login::AgentTaskAuthorizationTarget; -use codex_protocol::protocol::SessionAgentTask; -use crypto_box::SecretKey as Curve25519SecretKey; -use ed25519_dalek::Signer as _; -use serde::Deserialize; -use serde::Serialize; -use sha2::Digest as _; -use sha2::Sha512; -use tracing::info; - -use super::*; - -const AGENT_TASK_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(15); - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct RegisteredAgentTask { - pub(crate) agent_runtime_id: String, - pub(crate) task_id: String, - pub(crate) registered_at: String, -} - -#[derive(Debug, Serialize)] -struct RegisterTaskRequest { - signature: String, - timestamp: String, -} - -#[derive(Debug, Deserialize)] -struct RegisterTaskResponse { - encrypted_task_id: String, -} - -impl AgentIdentityManager { - pub(crate) async fn register_task(&self) -> Result> { - if !self.feature_enabled { - return Ok(None); - } - - let Some((auth, binding)) = self.current_auth_binding().await else { - return Ok(None); - }; - - self.register_task_for_binding(auth, binding).await - } - - async fn register_task_for_binding( - &self, - auth: CodexAuth, - binding: AgentIdentityBinding, - ) -> Result> { - let stored_identity = self - .ensure_registered_identity_for_binding(&auth, &binding) - .await?; - - let timestamp = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true); - let request_body = RegisterTaskRequest { - signature: sign_task_registration_payload(&stored_identity, ×tamp)?, - timestamp, - }; - - let client = create_client(); - let url = - agent_task_registration_url(&self.chatgpt_base_url, &stored_identity.agent_runtime_id); - let human_biscuit = self.mint_human_biscuit(&binding, "POST", &url).await?; - let response = client - .post(&url) - .header("X-OpenAI-Authorization", human_biscuit) - .json(&request_body) - .timeout(AGENT_TASK_REGISTRATION_TIMEOUT) - .send() - .await - .with_context(|| format!("failed to send agent task registration request to {url}"))?; - - if response.status().is_success() { - let response_body = response - .json::() - .await - .with_context(|| format!("failed to parse agent task response from {url}"))?; - let registered_task = RegisteredAgentTask { - agent_runtime_id: stored_identity.agent_runtime_id.clone(), - task_id: decrypt_task_id_response( - &stored_identity, - &response_body.encrypted_task_id, - )?, - registered_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), - }; - info!( - agent_runtime_id = %registered_task.agent_runtime_id, - task_id = %registered_task.task_id, - "registered agent task" - ); - return Ok(Some(registered_task)); - } - - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - anyhow::bail!("agent task registration failed with status {status} from {url}: {body}") - } -} - -impl RegisteredAgentTask { - pub(crate) fn authorization_target(&self) -> AgentTaskAuthorizationTarget<'_> { - AgentTaskAuthorizationTarget { - agent_runtime_id: &self.agent_runtime_id, - task_id: &self.task_id, - } - } - - pub(crate) fn to_session_agent_task(&self) -> SessionAgentTask { - SessionAgentTask { - agent_runtime_id: self.agent_runtime_id.clone(), - task_id: self.task_id.clone(), - registered_at: self.registered_at.clone(), - } - } - - pub(crate) fn from_session_agent_task(task: SessionAgentTask) -> Self { - Self { - agent_runtime_id: task.agent_runtime_id, - task_id: task.task_id, - registered_at: task.registered_at, - } - } -} - -fn sign_task_registration_payload( - stored_identity: &StoredAgentIdentity, - timestamp: &str, -) -> Result { - let signing_key = stored_identity.signing_key()?; - let payload = format!("{}:{timestamp}", stored_identity.agent_runtime_id); - Ok(BASE64_STANDARD.encode(signing_key.sign(payload.as_bytes()).to_bytes())) -} - -fn decrypt_task_id_response( - stored_identity: &StoredAgentIdentity, - encrypted_task_id: &str, -) -> Result { - let signing_key = stored_identity.signing_key()?; - let ciphertext = BASE64_STANDARD - .decode(encrypted_task_id) - .context("encrypted task id is not valid base64")?; - let plaintext = curve25519_secret_key_from_signing_key(&signing_key) - .unseal(&ciphertext) - .map_err(|_| anyhow::anyhow!("failed to decrypt encrypted task id"))?; - String::from_utf8(plaintext).context("decrypted task id is not valid UTF-8") -} - -fn curve25519_secret_key_from_signing_key(signing_key: &SigningKey) -> Curve25519SecretKey { - let digest = Sha512::digest(signing_key.to_bytes()); - let mut secret_key = [0u8; 32]; - secret_key.copy_from_slice(&digest[..32]); - secret_key[0] &= 248; - secret_key[31] &= 127; - secret_key[31] |= 64; - Curve25519SecretKey::from(secret_key) -} - -fn agent_task_registration_url(chatgpt_base_url: &str, agent_runtime_id: &str) -> String { - let trimmed = chatgpt_base_url.trim_end_matches('/'); - format!("{trimmed}/v1/agent/{agent_runtime_id}/task/register") -} - -#[cfg(test)] -mod tests { - use base64::engine::general_purpose::URL_SAFE_NO_PAD; - use codex_app_server_protocol::AuthMode as ApiAuthMode; - use codex_login::AuthCredentialsStoreMode; - use codex_login::AuthDotJson; - use codex_login::save_auth; - use codex_login::token_data::IdTokenInfo; - use codex_login::token_data::TokenData; - use pretty_assertions::assert_eq; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::header; - use wiremock::matchers::method; - use wiremock::matchers::path; - - use super::*; - - #[tokio::test] - async fn register_task_skips_when_feature_is_disabled() { - let auth_manager = - AuthManager::from_auth_for_testing(make_chatgpt_auth("account-123", Some("user-123"))); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ false, - "https://chatgpt.com/backend-api/".to_string(), - SessionSource::Cli, - ); - - assert_eq!(manager.register_task().await.unwrap(), None); - } - - #[tokio::test] - async fn register_task_skips_for_api_key_auth() { - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key")); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - "https://chatgpt.com/backend-api/".to_string(), - SessionSource::Cli, - ); - - assert_eq!(manager.register_task().await.unwrap(), None); - } - - #[tokio::test] - async fn register_task_registers_and_decrypts_plaintext_task_id() { - let server = MockServer::start().await; - let chatgpt_base_url = server.uri(); - mount_human_biscuit(&server, &chatgpt_base_url, "agent-123").await; - let auth = make_chatgpt_auth("account-123", Some("user-123")); - let auth_manager = AuthManager::from_auth_for_testing(auth.clone()); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - let stored_identity = seed_stored_identity(&manager, &auth, "agent-123", "account-123"); - let encrypted_task_id = - encrypt_task_id_for_identity(&stored_identity, "task_123").expect("task ciphertext"); - - Mock::given(method("POST")) - .and(path("/v1/agent/agent-123/task/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "encrypted_task_id": encrypted_task_id, - }))) - .expect(1) - .mount(&server) - .await; - - let task = manager - .register_task() - .await - .unwrap() - .expect("task should be registered"); - - assert_eq!( - task, - RegisteredAgentTask { - agent_runtime_id: "agent-123".to_string(), - task_id: "task_123".to_string(), - registered_at: task.registered_at.clone(), - } - ); - } - - #[tokio::test] - async fn register_task_uses_chatgpt_base_url() { - let server = MockServer::start().await; - let chatgpt_base_url = format!("{}/backend-api", server.uri()); - mount_human_biscuit(&server, &chatgpt_base_url, "agent-fallback").await; - let auth = make_chatgpt_auth("account-123", Some("user-123")); - let auth_manager = AuthManager::from_auth_for_testing(auth.clone()); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - let stored_identity = - seed_stored_identity(&manager, &auth, "agent-fallback", "account-123"); - let encrypted_task_id = encrypt_task_id_for_identity(&stored_identity, "task_fallback") - .expect("task ciphertext"); - - Mock::given(method("POST")) - .and(path("/backend-api/v1/agent/agent-fallback/task/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "encrypted_task_id": encrypted_task_id, - }))) - .expect(1) - .mount(&server) - .await; - - let task = manager - .register_task() - .await - .unwrap() - .expect("task should be registered"); - - assert_eq!(task.agent_runtime_id, "agent-fallback"); - assert_eq!(task.task_id, "task_fallback"); - } - - #[tokio::test] - async fn register_task_for_binding_keeps_one_auth_snapshot() { - let server = MockServer::start().await; - let chatgpt_base_url = server.uri(); - mount_human_biscuit(&server, &chatgpt_base_url, "agent-123").await; - let binding_auth = make_chatgpt_auth("account-123", Some("user-123")); - let auth_manager = - AuthManager::from_auth_for_testing(make_chatgpt_auth("account-456", Some("user-456"))); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Cli, - ); - let stored_identity = - seed_stored_identity(&manager, &binding_auth, "agent-123", "account-123"); - let encrypted_task_id = - encrypt_task_id_for_identity(&stored_identity, "task_123").expect("task ciphertext"); - let binding = - AgentIdentityBinding::from_auth(&binding_auth, /*forced_workspace_id*/ None) - .expect("binding"); - - Mock::given(method("POST")) - .and(path("/v1/agent/agent-123/task/register")) - .and(header("x-openai-authorization", "human-biscuit")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "encrypted_task_id": encrypted_task_id, - }))) - .expect(1) - .mount(&server) - .await; - - let task = manager - .register_task_for_binding(binding_auth, binding) - .await - .unwrap() - .expect("task should be registered"); - - assert_eq!( - task, - RegisteredAgentTask { - agent_runtime_id: "agent-123".to_string(), - task_id: "task_123".to_string(), - registered_at: task.registered_at.clone(), - } - ); - } - - #[tokio::test] - async fn task_matches_current_identity_rejects_stale_registered_identity() { - let auth_manager = - AuthManager::from_auth_for_testing(make_chatgpt_auth("account-456", Some("user-456"))); - let manager = AgentIdentityManager::new_for_tests( - auth_manager, - /*feature_enabled*/ true, - "https://chatgpt.com/backend-api/".to_string(), - SessionSource::Cli, - ); - let task = RegisteredAgentTask { - agent_runtime_id: "agent-123".to_string(), - task_id: "task_123".to_string(), - registered_at: "2026-03-23T12:00:00Z".to_string(), - }; - - assert!(!manager.task_matches_current_identity(&task).await); - } - - async fn mount_human_biscuit( - server: &MockServer, - chatgpt_base_url: &str, - agent_runtime_id: &str, - ) { - let biscuit_url = agent_identity_biscuit_url(chatgpt_base_url); - let biscuit_path = reqwest::Url::parse(&biscuit_url) - .expect("biscuit URL parses") - .path() - .to_string(); - let target_url = agent_task_registration_url(chatgpt_base_url, agent_runtime_id); - Mock::given(method("GET")) - .and(path(biscuit_path)) - .and(header("authorization", "Bearer access-token-account-123")) - .and(header("x-original-method", "POST")) - .and(header("x-original-url", target_url)) - .respond_with( - ResponseTemplate::new(200).insert_header("x-openai-authorization", "human-biscuit"), - ) - .expect(1) - .mount(server) - .await; - } - - fn seed_stored_identity( - manager: &AgentIdentityManager, - auth: &CodexAuth, - agent_runtime_id: &str, - account_id: &str, - ) -> StoredAgentIdentity { - let key_material = generate_agent_key_material().expect("key material"); - let binding = - AgentIdentityBinding::from_auth(auth, /*forced_workspace_id*/ None).expect("binding"); - let stored_identity = StoredAgentIdentity { - binding_id: binding.binding_id, - chatgpt_account_id: account_id.to_string(), - chatgpt_user_id: Some("user-123".to_string()), - agent_runtime_id: agent_runtime_id.to_string(), - private_key_pkcs8_base64: key_material.private_key_pkcs8_base64, - public_key_ssh: key_material.public_key_ssh, - registered_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), - abom: manager.abom.clone(), - }; - manager - .store_identity(auth, &stored_identity) - .expect("store identity"); - let persisted = auth - .get_agent_identity(account_id) - .expect("persisted identity"); - assert_eq!(persisted.agent_runtime_id, agent_runtime_id); - stored_identity - } - - fn encrypt_task_id_for_identity( - stored_identity: &StoredAgentIdentity, - task_id: &str, - ) -> Result { - let mut rng = crypto_box::aead::OsRng; - let public_key = - curve25519_secret_key_from_signing_key(&stored_identity.signing_key()?).public_key(); - let ciphertext = public_key - .seal(&mut rng, task_id.as_bytes()) - .map_err(|_| anyhow::anyhow!("failed to encrypt test task id"))?; - Ok(BASE64_STANDARD.encode(ciphertext)) - } - - fn make_chatgpt_auth(account_id: &str, user_id: Option<&str>) -> CodexAuth { - let tempdir = tempfile::tempdir().expect("tempdir"); - let auth_json = AuthDotJson { - auth_mode: Some(ApiAuthMode::Chatgpt), - openai_api_key: None, - tokens: Some(TokenData { - id_token: IdTokenInfo { - email: None, - chatgpt_plan_type: None, - chatgpt_user_id: user_id.map(ToOwned::to_owned), - chatgpt_account_id: Some(account_id.to_string()), - chatgpt_account_is_fedramp: false, - raw_jwt: fake_id_token(account_id, user_id), - }, - access_token: format!("access-token-{account_id}"), - refresh_token: "refresh-token".to_string(), - account_id: Some(account_id.to_string()), - }), - last_refresh: Some(Utc::now()), - agent_identity: None, - }; - save_auth(tempdir.path(), &auth_json, AuthCredentialsStoreMode::File).expect("save auth"); - CodexAuth::from_auth_storage(tempdir.path(), AuthCredentialsStoreMode::File) - .expect("load auth") - .expect("auth") - } - - fn fake_id_token(account_id: &str, user_id: Option<&str>) -> String { - let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"none","typ":"JWT"}"#); - let payload = serde_json::json!({ - "https://api.openai.com/auth": { - "chatgpt_user_id": user_id, - "chatgpt_account_id": account_id, - } - }); - let payload = URL_SAFE_NO_PAD.encode(payload.to_string()); - format!("{header}.{payload}.signature") - } -} diff --git a/codex-rs/core/src/apps/mod.rs b/codex-rs/core/src/apps/mod.rs index dcb5c4c20a..5a58d22204 100644 --- a/codex-rs/core/src/apps/mod.rs +++ b/codex-rs/core/src/apps/mod.rs @@ -1,3 +1,2 @@ +#[cfg(test)] mod render; - -pub(crate) use render::render_apps_section; diff --git a/codex-rs/core/src/apps/render.rs b/codex-rs/core/src/apps/render.rs index fe23a09f8d..3793231e10 100644 --- a/codex-rs/core/src/apps/render.rs +++ b/codex-rs/core/src/apps/render.rs @@ -1,22 +1,11 @@ +use crate::context::AppsInstructions; +use crate::context::ContextualUserFragment; use codex_app_server_protocol::AppInfo; -use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_protocol::protocol::APPS_INSTRUCTIONS_CLOSE_TAG; use codex_protocol::protocol::APPS_INSTRUCTIONS_OPEN_TAG; pub(crate) fn render_apps_section(connectors: &[AppInfo]) -> Option { - if !connectors - .iter() - .any(|connector| connector.is_accessible && connector.is_enabled) - { - return None; - } - - let body = format!( - "## Apps (Connectors)\nApps (Connectors) can be explicitly triggered in user messages in the format `[$app-name](app://{{connector_id}})`. Apps can also be implicitly triggered as long as the context suggests usage of available apps.\nAn app is equivalent to a set of MCP tools within the `{CODEX_APPS_MCP_SERVER_NAME}` MCP.\nAn installed app's MCP tools are either provided to you already, or can be lazy-loaded through the `tool_search` tool. If `tool_search` is available, the apps that are searchable by `tools_search` will be listed by it.\nDo not additionally call list_mcp_resources or list_mcp_resource_templates for apps." - ); - Some(format!( - "{APPS_INSTRUCTIONS_OPEN_TAG}\n{body}\n{APPS_INSTRUCTIONS_CLOSE_TAG}" - )) + AppsInstructions::from_connectors(connectors).map(|instructions| instructions.render()) } #[cfg(test)] diff --git a/codex-rs/core/src/arc_monitor.rs b/codex-rs/core/src/arc_monitor.rs index 99767872d5..ecd7f39666 100644 --- a/codex-rs/core/src/arc_monitor.rs +++ b/codex-rs/core/src/arc_monitor.rs @@ -13,7 +13,6 @@ use codex_login::CodexAuth; use codex_login::default_client::build_reqwest_client; use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; -use reqwest::header::AUTHORIZATION; const ARC_MONITOR_TIMEOUT: Duration = Duration::from_secs(30); const CODEX_ARC_MONITOR_ENDPOINT_OVERRIDE: &str = "CODEX_ARC_MONITOR_ENDPOINT_OVERRIDE"; @@ -110,31 +109,13 @@ pub(crate) async fn monitor_action( }, None => None, }; - let (authorization_header_value, account_id) = if let Some(token) = - read_non_empty_env_var(CODEX_ARC_MONITOR_TOKEN) - { - ( - format!("Bearer {token}"), - auth.as_ref().and_then(CodexAuth::get_account_id), - ) - } else if let Some(authorization_header_value) = - match sess.authorization_header_for_current_agent_task().await { - Ok(authorization_header_value) => authorization_header_value, - Err(err) => { - warn!( - error = %err, - "skipping safety monitor because agent assertion authorization is unavailable" - ); - return ArcMonitorOutcome::Ok; - } - } - { - (authorization_header_value, None) + let token = if let Some(token) = read_non_empty_env_var(CODEX_ARC_MONITOR_TOKEN) { + token } else { let Some(auth) = auth.as_ref() else { return ArcMonitorOutcome::Ok; }; - let token = match auth.get_token() { + match auth.get_token() { Ok(token) => token, Err(err) => { warn!( @@ -143,8 +124,7 @@ pub(crate) async fn monitor_action( ); return ArcMonitorOutcome::Ok; } - }; - (format!("Bearer {token}"), auth.get_account_id()) + } }; let url = read_non_empty_env_var(CODEX_ARC_MONITOR_ENDPOINT_OVERRIDE).unwrap_or_else(|| { @@ -167,8 +147,8 @@ pub(crate) async fn monitor_action( .post(&url) .timeout(ARC_MONITOR_TIMEOUT) .json(&body) - .header(AUTHORIZATION, authorization_header_value); - if let Some(account_id) = account_id { + .bearer_auth(token); + if let Some(account_id) = auth.as_ref().and_then(CodexAuth::get_account_id) { request = request.header("chatgpt-account-id", account_id); } diff --git a/codex-rs/core/src/arc_monitor_tests.rs b/codex-rs/core/src/arc_monitor_tests.rs index 5fd691b930..1cb29ce08c 100644 --- a/codex-rs/core/src/arc_monitor_tests.rs +++ b/codex-rs/core/src/arc_monitor_tests.rs @@ -10,38 +10,18 @@ use wiremock::MockServer; use wiremock::ResponseTemplate; use wiremock::matchers::body_json; use wiremock::matchers::header; -use wiremock::matchers::header_regex; use wiremock::matchers::method; use wiremock::matchers::path; use super::*; -use crate::agent_identity::AgentIdentityManager; -use crate::agent_identity::RegisteredAgentTask; use crate::context::ContextualUserFragment; use crate::session::tests::make_session_and_context; -use chrono::Utc; -use codex_login::AuthCredentialsStoreMode; -use codex_login::AuthDotJson; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_login::save_auth; -use codex_login::token_data::IdTokenInfo; -use codex_login::token_data::TokenData; use codex_protocol::models::ContentItem; use codex_protocol::models::LocalShellAction; use codex_protocol::models::LocalShellExecAction; use codex_protocol::models::LocalShellStatus; use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::SessionSource; -use tempfile::tempdir; - -const TEST_ID_TOKEN: &str = concat!( - "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.", - "eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lk", - "IjpudWxsLCJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2NvdW50X2lkIn19.", - "c2ln", -); struct EnvVarGuard { key: &'static str, @@ -71,58 +51,6 @@ impl Drop for EnvVarGuard { } } -async fn install_cached_agent_task_auth( - session: &mut Session, - turn_context: &mut TurnContext, - chatgpt_base_url: String, -) { - let auth_dir = tempdir().expect("temp auth dir"); - let auth_json = AuthDotJson { - auth_mode: Some(codex_app_server_protocol::AuthMode::Chatgpt), - openai_api_key: None, - tokens: Some(TokenData { - id_token: IdTokenInfo { - email: None, - chatgpt_plan_type: None, - chatgpt_user_id: None, - chatgpt_account_id: Some("account_id".to_string()), - chatgpt_account_is_fedramp: false, - raw_jwt: TEST_ID_TOKEN.to_string(), - }, - access_token: "Access Token".to_string(), - refresh_token: "test".to_string(), - account_id: Some("account_id".to_string()), - }), - last_refresh: Some(Utc::now()), - agent_identity: None, - }; - save_auth(auth_dir.path(), &auth_json, AuthCredentialsStoreMode::File).expect("save test auth"); - let auth = CodexAuth::from_auth_storage(auth_dir.path(), AuthCredentialsStoreMode::File) - .expect("load test auth") - .expect("test auth"); - let auth_manager = AuthManager::from_auth_for_testing(auth); - let agent_identity_manager = Arc::new(AgentIdentityManager::new_for_tests( - Arc::clone(&auth_manager), - /*feature_enabled*/ true, - chatgpt_base_url, - SessionSource::Exec, - )); - let stored_identity = agent_identity_manager - .seed_generated_identity_for_tests("agent-123") - .await - .expect("seed test identity"); - session.services.auth_manager = Arc::clone(&auth_manager); - session.services.agent_identity_manager = agent_identity_manager; - turn_context.auth_manager = Some(auth_manager); - session - .cache_agent_task_for_tests(RegisteredAgentTask { - agent_runtime_id: stored_identity.agent_runtime_id, - task_id: "task-123".to_string(), - registered_at: "2026-04-15T00:00:00Z".to_string(), - }) - .await; -} - #[tokio::test] async fn build_arc_monitor_request_includes_relevant_history_and_null_policies() { let (session, mut turn_context) = make_session_and_context().await; @@ -326,80 +254,6 @@ async fn build_arc_monitor_request_includes_relevant_history_and_null_policies() ); } -#[tokio::test] -#[serial(arc_monitor_env)] -async fn monitor_action_uses_agent_assertion_for_cached_task() { - let server = MockServer::start().await; - let (mut session, mut turn_context) = make_session_and_context().await; - install_cached_agent_task_auth(&mut session, &mut turn_context, server.uri()).await; - - let mut config = (*turn_context.config).clone(); - config.chatgpt_base_url = server.uri(); - turn_context.config = Arc::new(config); - - session - .record_into_history( - &[ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "please run the tool".to_string(), - }], - end_turn: None, - phase: None, - }], - &turn_context, - ) - .await; - - Mock::given(method("POST")) - .and(path("/codex/safety/arc")) - .and(header_regex("authorization", r"^AgentAssertion .+")) - .and(body_json(serde_json::json!({ - "metadata": { - "codex_thread_id": session.conversation_id.to_string(), - "codex_turn_id": turn_context.sub_id.clone(), - "conversation_id": session.conversation_id.to_string(), - "protection_client_callsite": "normal", - }, - "messages": [{ - "role": "user", - "content": [{ - "type": "input_text", - "text": "please run the tool", - }], - }], - "policies": { - "developer": null, - "user": null, - }, - "action": { - "tool": "mcp_tool_call", - }, - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "outcome": "ok", - "short_reason": "", - "rationale": "", - "risk_score": 1, - "risk_level": "low", - "evidence": [], - }))) - .expect(1) - .mount(&server) - .await; - - let outcome = monitor_action( - &session, - &turn_context, - serde_json::json!({ "tool": "mcp_tool_call" }), - "normal", - ) - .await; - - assert_eq!(outcome, ArcMonitorOutcome::Ok); -} - #[tokio::test] #[serial(arc_monitor_env)] async fn monitor_action_posts_expected_arc_request() { diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 50f9dd295e..601b8106df 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -31,7 +31,6 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; -use crate::agent_identity::RegisteredAgentTask; use codex_api::ApiError; use codex_api::AuthProvider; use codex_api::CompactClient as ApiCompactClient; @@ -96,7 +95,6 @@ use tokio::sync::oneshot; use tokio::sync::oneshot::error::TryRecvError; use tokio_tungstenite::tungstenite::Error; use tokio_tungstenite::tungstenite::Message; -use tracing::debug; use tracing::instrument; use tracing::trace; use tracing::warn; @@ -111,7 +109,6 @@ use codex_feedback::FeedbackRequestTags; use codex_feedback::emit_feedback_request_tags_with_auth_env; use codex_login::auth_env_telemetry::AuthEnvTelemetry; use codex_login::auth_env_telemetry::collect_auth_env_telemetry; -use codex_model_provider::AuthorizationHeaderAuthProvider; use codex_model_provider::SharedModelProvider; use codex_model_provider::create_model_provider; #[cfg(test)] @@ -216,8 +213,6 @@ pub struct ModelClient { pub struct ModelClientSession { client: ModelClient, websocket_session: WebsocketSession, - agent_task: Option, - cache_websocket_session_on_drop: bool, /// Turn state for sticky routing. /// /// This is an `OnceLock` that stores the turn state value received from the server @@ -335,25 +330,9 @@ impl ModelClient { /// This constructor does not perform network I/O itself; the session opens a websocket lazily /// when the first stream request is issued. pub fn new_session(&self) -> ModelClientSession { - self.new_session_with_agent_task(/*agent_task*/ None) - } - - pub(crate) fn new_session_with_agent_task( - &self, - agent_task: Option, - ) -> ModelClientSession { - let cache_websocket_session_on_drop = agent_task.is_none(); - let websocket_session = if agent_task.is_some() { - drop(self.take_cached_websocket_session()); - WebsocketSession::default() - } else { - self.take_cached_websocket_session() - }; ModelClientSession { client: self.clone(), - websocket_session, - agent_task, - cache_websocket_session_on_drop, + websocket_session: self.take_cached_websocket_session(), turn_state: Arc::new(OnceLock::new()), } } @@ -436,7 +415,7 @@ impl ModelClient { if prompt.input.is_empty() { return Ok(Vec::new()); } - let client_setup = self.current_client_setup(/*agent_task*/ None).await?; + let client_setup = self.current_client_setup().await?; let transport = ReqwestTransport::new(build_reqwest_client()); let request_telemetry = Self::build_request_telemetry( session_telemetry, @@ -500,7 +479,7 @@ impl ModelClient { ) -> Result { // Create the media call over HTTP first, then retain matching auth so realtime can attach // the server-side control WebSocket to the call id from that HTTP response. - let client_setup = self.current_client_setup(/*agent_task*/ None).await?; + let client_setup = self.current_client_setup().await?; let mut sideband_headers = extra_headers.clone(); sideband_headers.extend(sideband_websocket_auth_headers( client_setup.api_auth.as_ref(), @@ -535,7 +514,7 @@ impl ModelClient { return Ok(Vec::new()); } - let client_setup = self.current_client_setup(/*agent_task*/ None).await?; + let client_setup = self.current_client_setup().await?; let transport = ReqwestTransport::new(build_reqwest_client()); let request_telemetry = Self::build_request_telemetry( session_telemetry, @@ -685,46 +664,10 @@ impl ModelClient { /// /// This centralizes setup used by both prewarm and normal request paths so they stay in /// lockstep when auth/provider resolution changes. - async fn current_client_setup( - &self, - agent_task: Option<&RegisteredAgentTask>, - ) -> Result { + async fn current_client_setup(&self) -> Result { let auth = self.state.provider.auth().await; let api_provider = self.state.provider.api_provider().await?; - let auth_manager = self.state.provider.auth_manager(); - let api_auth = match (agent_task, auth_manager.as_ref(), auth.as_ref()) { - (Some(agent_task), Some(auth_manager), Some(auth)) => { - if let Some(authorization_header_value) = auth_manager - .chatgpt_agent_task_authorization_header_for_auth( - auth, - agent_task.authorization_target(), - ) - .map_err(|err| { - CodexErr::Stream( - format!("failed to build agent assertion authorization: {err}"), - None, - ) - })? - { - debug!( - agent_runtime_id = %agent_task.agent_runtime_id, - task_id = %agent_task.task_id, - "using agent assertion authorization for downstream request" - ); - let mut auth_provider = AuthorizationHeaderAuthProvider::new( - Some(authorization_header_value), - /*account_id*/ None, - ); - if auth.is_fedramp_account() { - auth_provider = auth_provider.with_fedramp_routing_header(); - } - Arc::new(auth_provider) - } else { - self.state.provider.api_auth().await? - } - } - _ => self.state.provider.api_auth().await?, - }; + let api_auth = self.state.provider.api_auth().await?; Ok(CurrentClientSetup { auth, api_provider, @@ -858,18 +801,12 @@ impl ModelClient { impl Drop for ModelClientSession { fn drop(&mut self) { let websocket_session = std::mem::take(&mut self.websocket_session); - if self.cache_websocket_session_on_drop { - self.client - .store_cached_websocket_session(websocket_session); - } + self.client + .store_cached_websocket_session(websocket_session); } } impl ModelClientSession { - pub(crate) fn disable_cached_websocket_session_on_drop(&mut self) { - self.cache_websocket_session_on_drop = false; - } - pub(crate) fn reset_websocket_session(&mut self) { self.websocket_session.connection = None; self.websocket_session.last_request = None; @@ -1071,15 +1008,11 @@ impl ModelClientSession { return Ok(()); } - let client_setup = self - .client - .current_client_setup(self.agent_task.as_ref()) - .await - .map_err(|err| { - ApiError::Stream(format!( - "failed to build websocket prewarm client setup: {err}" - )) - })?; + let client_setup = self.client.current_client_setup().await.map_err(|err| { + ApiError::Stream(format!( + "failed to build websocket prewarm client setup: {err}" + )) + })?; let auth_context = AuthRequestTelemetryContext::new( client_setup.auth.as_ref().map(CodexAuth::auth_mode), client_setup.api_auth.as_ref(), @@ -1233,10 +1166,7 @@ impl ModelClientSession { .map(AuthManager::unauthorized_recovery); let mut pending_retry = PendingUnauthorizedRetry::default(); loop { - let client_setup = self - .client - .current_client_setup(self.agent_task.as_ref()) - .await?; + let client_setup = self.client.current_client_setup().await?; let transport = ReqwestTransport::new(build_reqwest_client()); let request_auth_context = AuthRequestTelemetryContext::new( client_setup.auth.as_ref().map(CodexAuth::auth_mode), @@ -1325,10 +1255,7 @@ impl ModelClientSession { .map(AuthManager::unauthorized_recovery); let mut pending_retry = PendingUnauthorizedRetry::default(); loop { - let client_setup = self - .client - .current_client_setup(self.agent_task.as_ref()) - .await?; + let client_setup = self.client.current_client_setup().await?; let request_auth_context = AuthRequestTelemetryContext::new( client_setup.auth.as_ref().map(CodexAuth::auth_mode), client_setup.api_auth.as_ref(), diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index 357a892264..f4575b26a0 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use super::AuthRequestTelemetryContext; use super::ModelClient; use super::PendingUnauthorizedRetry; @@ -9,36 +7,17 @@ use super::X_CODEX_PARENT_THREAD_ID_HEADER; use super::X_CODEX_TURN_METADATA_HEADER; use super::X_CODEX_WINDOW_ID_HEADER; use super::X_OPENAI_SUBAGENT_HEADER; -use crate::Prompt; -use crate::ResponseEvent; -use crate::agent_identity::AgentIdentityManager; -use crate::agent_identity::RegisteredAgentTask; -use crate::agent_identity::StoredAgentIdentity; -use base64::Engine as _; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; use codex_app_server_protocol::AuthMode; -use codex_login::AuthManager; -use codex_login::CodexAuth; use codex_model_provider::BearerAuthProvider; -use codex_model_provider_info::ModelProviderInfo; use codex_model_provider_info::WireApi; use codex_model_provider_info::create_oss_provider_with_base_url; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::models::ContentItem; -use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; -use core_test_support::responses; -use ed25519_dalek::Signature; -use ed25519_dalek::Verifier as _; -use futures::StreamExt; use pretty_assertions::assert_eq; -use serde::Deserialize; use serde_json::json; -use tempfile::TempDir; fn test_model_client(session_source: SessionSource) -> ModelClient { let provider = create_oss_provider_with_base_url("https://example.com/v1", WireApi::Responses); @@ -100,118 +79,6 @@ fn test_session_telemetry() -> SessionTelemetry { ) } -fn test_prompt(text: &str) -> Prompt { - Prompt { - input: vec![ResponseItem::Message { - id: None, - role: "user".into(), - content: vec![ContentItem::InputText { - text: text.to_string(), - }], - end_turn: None, - phase: None, - }], - ..Prompt::default() - } -} - -async fn drain_stream_to_completion(stream: &mut crate::ResponseStream) -> anyhow::Result<()> { - while let Some(event) = stream.next().await { - if matches!(event?, ResponseEvent::Completed { .. }) { - break; - } - } - Ok(()) -} - -async fn model_client_with_agent_task( - provider: ModelProviderInfo, -) -> ( - TempDir, - ModelClient, - RegisteredAgentTask, - StoredAgentIdentity, -) { - let codex_home = tempfile::tempdir().expect("tempdir"); - let auth_manager = - AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let agent_identity_manager = Arc::new(AgentIdentityManager::new_for_tests( - Arc::clone(&auth_manager), - /*feature_enabled*/ true, - "https://chatgpt.com/backend-api/".to_string(), - SessionSource::Cli, - )); - let stored_identity = agent_identity_manager - .seed_generated_identity_for_tests("agent-123") - .await - .expect("seed test identity"); - let agent_task = RegisteredAgentTask { - agent_runtime_id: stored_identity.agent_runtime_id.clone(), - task_id: "task-123".to_string(), - registered_at: "2026-03-23T12:00:00Z".to_string(), - }; - let client = ModelClient::new( - Some(auth_manager), - ThreadId::new(), - /*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(), - provider, - SessionSource::Cli, - /*model_verbosity*/ None, - /*enable_request_compression*/ false, - /*include_timing_metrics*/ false, - /*beta_features_header*/ None, - ); - (codex_home, client, agent_task, stored_identity) -} - -#[derive(Debug, Deserialize)] -struct AgentAssertionEnvelope { - agent_runtime_id: String, - task_id: String, - timestamp: String, - signature: String, -} - -fn assert_agent_assertion_header( - authorization_header: &str, - stored_identity: &StoredAgentIdentity, - expected_agent_runtime_id: &str, - expected_task_id: &str, -) { - let token = authorization_header - .strip_prefix("AgentAssertion ") - .expect("agent assertion authorization scheme"); - let envelope: AgentAssertionEnvelope = serde_json::from_slice( - &URL_SAFE_NO_PAD - .decode(token) - .expect("base64url-encoded agent assertion"), - ) - .expect("valid agent assertion envelope"); - - assert_eq!(envelope.agent_runtime_id, expected_agent_runtime_id); - assert_eq!(envelope.task_id, expected_task_id); - - let signature = Signature::from_slice( - &base64::engine::general_purpose::STANDARD - .decode(&envelope.signature) - .expect("base64 signature"), - ) - .expect("signature bytes"); - stored_identity - .signing_key() - .expect("signing key") - .verifying_key() - .verify( - format!( - "{}:{}:{}", - envelope.agent_runtime_id, envelope.task_id, envelope.timestamp - ) - .as_bytes(), - &signature, - ) - .expect("signature should verify"); -} - #[test] fn build_subagent_headers_sets_other_subagent_label() { let client = test_model_client(SessionSource::SubAgent(SubAgentSource::Other( @@ -302,130 +169,3 @@ fn auth_request_telemetry_context_tracks_attached_auth_and_retry_phase() { assert_eq!(auth_context.recovery_mode, Some("managed")); assert_eq!(auth_context.recovery_phase, Some("refresh_token")); } - -#[tokio::test] -async fn responses_http_uses_agent_assertion_when_agent_task_is_present() { - core_test_support::skip_if_no_network!(); - - let server = responses::start_mock_server().await; - let request_recorder = responses::mount_sse_once( - &server, - responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_completed("resp-1"), - ]), - ) - .await; - let provider = - create_oss_provider_with_base_url(&format!("{}/v1", server.uri()), WireApi::Responses); - let (_codex_home, client, agent_task, stored_identity) = - model_client_with_agent_task(provider).await; - let model_info = test_model_info(); - let session_telemetry = test_session_telemetry(); - let mut client_session = client.new_session_with_agent_task(Some(agent_task.clone())); - - let mut stream = client_session - .stream( - &test_prompt("hello"), - &model_info, - &session_telemetry, - /*effort*/ None, - ReasoningSummary::Auto, - /*service_tier*/ None, - /*turn_metadata_header*/ None, - ) - .await - .expect("stream request should succeed"); - drain_stream_to_completion(&mut stream) - .await - .expect("stream should complete"); - - let request = request_recorder.single_request(); - let authorization = request - .header("authorization") - .expect("authorization header should be present"); - assert_agent_assertion_header( - &authorization, - &stored_identity, - &agent_task.agent_runtime_id, - &agent_task.task_id, - ); - assert_eq!(request.header("chatgpt-account-id"), None); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn websocket_agent_task_bypasses_cached_bearer_prewarm() { - core_test_support::skip_if_no_network!(); - - let server = responses::start_websocket_server(vec![ - vec![vec![ - responses::ev_response_created("resp-prewarm"), - responses::ev_completed("resp-prewarm"), - ]], - vec![vec![ - responses::ev_response_created("resp-1"), - responses::ev_completed("resp-1"), - ]], - ]) - .await; - let mut provider = - create_oss_provider_with_base_url(&format!("{}/v1", server.uri()), WireApi::Responses); - provider.supports_websockets = true; - provider.websocket_connect_timeout_ms = Some(5_000); - let (_codex_home, client, agent_task, stored_identity) = - model_client_with_agent_task(provider).await; - let model_info = test_model_info(); - let session_telemetry = test_session_telemetry(); - let prompt = test_prompt("hello"); - - let mut prewarm_session = client.new_session(); - prewarm_session - .prewarm_websocket( - &prompt, - &model_info, - &session_telemetry, - /*effort*/ None, - ReasoningSummary::Auto, - /*service_tier*/ None, - /*turn_metadata_header*/ None, - ) - .await - .expect("bearer prewarm should succeed"); - drop(prewarm_session); - - let mut agent_task_session = client.new_session_with_agent_task(Some(agent_task.clone())); - let mut stream = agent_task_session - .stream( - &prompt, - &model_info, - &session_telemetry, - /*effort*/ None, - ReasoningSummary::Auto, - /*service_tier*/ None, - /*turn_metadata_header*/ None, - ) - .await - .expect("agent task stream should succeed"); - drain_stream_to_completion(&mut stream) - .await - .expect("agent task websocket stream should complete"); - - let handshakes = server.handshakes(); - assert_eq!(handshakes.len(), 2); - assert_eq!( - handshakes[0].header("authorization"), - Some("Bearer Access Token".to_string()) - ); - let agent_authorization = handshakes[1] - .header("authorization") - .expect("agent handshake should include authorization"); - assert_agent_assertion_header( - &agent_authorization, - &stored_identity, - &agent_task.agent_runtime_id, - &agent_task.task_id, - ); - assert_eq!(handshakes[1].header("chatgpt-account-id"), None); - - server.shutdown().await; -} diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index be021fe6aa..7247c601f4 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -741,8 +741,14 @@ async fn handle_request_permissions( reason: event.reason, permissions: event.permissions, }; - let response_fut = - parent_session.request_permissions(parent_ctx, call_id.clone(), args, cancel_token.clone()); + let cwd = event.cwd.unwrap_or_else(|| parent_ctx.cwd.clone()); + let response_fut = parent_session.request_permissions_for_cwd( + parent_ctx, + call_id.clone(), + args, + cwd, + cancel_token.clone(), + ); let response = await_request_permissions_with_cancel(response_fut, parent_session, &call_id, cancel_token) .await; diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index d26460a255..3e685d92e9 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -180,8 +180,10 @@ async fn handle_request_permissions_uses_tool_call_id_for_round_trip() { }, scope: PermissionGrantScope::Turn, }; + let delegated_cwd = parent_ctx.cwd.join("delegated-cwd"); let cancel_token = CancellationToken::new(); let request_call_id = call_id.clone(); + let request_cwd = delegated_cwd.clone(); let handle = tokio::spawn({ let codex = Arc::clone(&codex); @@ -203,6 +205,7 @@ async fn handle_request_permissions_uses_tool_call_id_for_round_trip() { }), ..RequestPermissionProfile::default() }, + cwd: Some(request_cwd), }, &cancel_token, ) @@ -218,6 +221,7 @@ async fn handle_request_permissions_uses_tool_call_id_for_round_trip() { panic!("expected RequestPermissions event"); }; assert_eq!(request.call_id, call_id.clone()); + assert_eq!(request.cwd, Some(delegated_cwd)); parent_session .notify_request_permissions_response(&call_id, expected_response.clone()) diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index a6240fdcb3..995c2008c5 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -7,6 +7,7 @@ use crate::config_loader::ConfigLayerStackOrdering; use crate::config_loader::ConfigRequirements; use crate::config_loader::ConfigRequirementsToml; use crate::config_loader::ConstrainedWithSource; +use crate::config_loader::FeatureRequirementsToml; use crate::config_loader::LoaderOverrides; use crate::config_loader::McpServerIdentity; use crate::config_loader::McpServerRequirement; @@ -50,7 +51,7 @@ use codex_config::types::UriBasedFileOpener; use codex_config::types::WindowsSandboxModeToml; use codex_exec_server::ExecutorFileSystem; use codex_exec_server::LOCAL_FS; -pub use codex_features::Feature; +use codex_features::Feature; use codex_features::FeatureConfigSource; use codex_features::FeatureOverrides; use codex_features::FeatureToml; @@ -59,7 +60,6 @@ use codex_features::FeaturesToml; use codex_features::MultiAgentV2ConfigToml; use codex_git_utils::resolve_root_git_project_for_trust; use codex_login::AuthManagerConfig; -use codex_login::BackgroundAgentTaskAuthMode; use codex_mcp::McpConfig; use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID; use codex_model_provider_info::ModelProviderInfo; @@ -108,7 +108,6 @@ mod network_proxy_spec; mod permissions; #[cfg(test)] mod schema; -pub(crate) mod service; pub use codex_config::Constrained; pub use codex_config::ConstraintError; pub use codex_config::ConstraintResult; @@ -118,8 +117,6 @@ pub use managed_features::ManagedFeatures; pub use network_proxy_spec::NetworkProxySpec; pub use network_proxy_spec::StartedNetworkProxy; pub(crate) use permissions::resolve_permission_profile; -pub use service::ConfigService; -pub use service::ConfigServiceError; pub use codex_git_utils::GhostSnapshotConfig; @@ -637,16 +634,6 @@ impl AuthManagerConfig for Config { fn forced_chatgpt_workspace_id(&self) -> Option { self.forced_chatgpt_workspace_id.clone() } - - fn chatgpt_base_url(&self) -> Option { - Some(self.chatgpt_base_url.clone()) - } - - fn background_agent_task_auth_mode(&self) -> BackgroundAgentTaskAuthMode { - BackgroundAgentTaskAuthMode::from_feature_enabled( - self.features.enabled(Feature::UseAgentIdentity), - ) - } } #[derive(Clone)] @@ -947,7 +934,7 @@ pub async fn load_config_as_toml_with_cli_and_loader_overrides( Ok(cfg) } -pub(crate) fn deserialize_config_toml_with_base( +pub fn deserialize_config_toml_with_base( root_value: TomlValue, config_base_dir: &Path, ) -> std::io::Result { @@ -959,6 +946,15 @@ pub(crate) fn deserialize_config_toml_with_base( .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } +/// Validate user-visible feature settings against managed feature requirements. +pub fn validate_feature_requirements_for_config_toml( + cfg: &ConfigToml, + feature_requirements: Option<&Sourced>, +) -> std::io::Result<()> { + managed_features::validate_explicit_feature_settings_in_config_toml(cfg, feature_requirements)?; + managed_features::validate_feature_requirements_in_config_toml(cfg, feature_requirements) +} + fn load_catalog_json(path: &AbsolutePathBuf) -> std::io::Result { let file_contents = std::fs::read_to_string(path)?; let catalog = serde_json::from_str::(&file_contents).map_err(|err| { diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 965521ae3d..933ce0ac76 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -43,7 +43,7 @@ use codex_mcp::ToolInfo; use codex_mcp::ToolPluginProvenance; use codex_mcp::codex_apps_tools_cache_key; use codex_mcp::compute_auth_statuses; -use codex_mcp::with_codex_apps_mcp_with_authorization_header; +use codex_mcp::with_codex_apps_mcp; const CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS: Duration = Duration::from_secs(30); const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60); @@ -220,20 +220,8 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_options_and_status( }); } - let background_authorization_header_value = if let Some(auth) = auth.as_ref() { - auth_manager - .chatgpt_authorization_header_for_auth(auth) - .await - } else { - None - }; let mcp_config = config.to_mcp_config(plugins_manager.as_ref()).await; - let mcp_servers = with_codex_apps_mcp_with_authorization_header( - HashMap::new(), - auth.as_ref(), - &mcp_config, - background_authorization_header_value.as_deref(), - ); + let mcp_servers = with_codex_apps_mcp(HashMap::new(), auth.as_ref(), &mcp_config); if mcp_servers.is_empty() { return Ok(AccessibleConnectorsStatus { connectors: Vec::new(), @@ -435,18 +423,6 @@ async fn list_directory_connectors_for_tool_suggest_with_auth( }; let access_token = token_data.access_token.clone(); let account_id = account_id.to_string(); - let is_fedramp_account = token_data.id_token.is_fedramp_account(); - let authorization_header_value = { - let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); - match auth { - Some(auth) if auth.is_chatgpt_auth() => auth_manager - .chatgpt_authorization_header_for_auth(auth) - .await - .unwrap_or_else(|| format!("Bearer {access_token}")), - _ => format!("Bearer {access_token}"), - } - }; let is_workspace_account = token_data.id_token.is_workspace_account(); let cache_key = AllConnectorsCacheKey::new( config.chatgpt_base_url.clone(), @@ -460,15 +436,14 @@ async fn list_directory_connectors_for_tool_suggest_with_auth( is_workspace_account, /*force_refetch*/ false, |path| { - let authorization_header_value = authorization_header_value.clone(); + let access_token = access_token.clone(); let account_id = account_id.clone(); async move { - chatgpt_get_request_with_authorization_header::( + chatgpt_get_request_with_token::( config, path, - authorization_header_value.as_str(), + access_token.as_str(), account_id.as_str(), - is_fedramp_account, ) .await } @@ -477,25 +452,23 @@ async fn list_directory_connectors_for_tool_suggest_with_auth( .await } -async fn chatgpt_get_request_with_authorization_header( +async fn chatgpt_get_request_with_token( config: &Config, path: String, - authorization_header_value: &str, + access_token: &str, account_id: &str, - is_fedramp_account: bool, ) -> anyhow::Result { let client = create_client(); let url = format!("{}{}", config.chatgpt_base_url, path); - let mut request = client + let response = client .get(&url) - .header("authorization", authorization_header_value) + .bearer_auth(access_token) .header("chatgpt-account-id", account_id) .header("Content-Type", "application/json") - .timeout(DIRECTORY_CONNECTORS_TIMEOUT); - if is_fedramp_account { - request = request.header("X-OpenAI-Fedramp", "true"); - } - let response = request.send().await.context("failed to send request")?; + .timeout(DIRECTORY_CONNECTORS_TIMEOUT) + .send() + .await + .context("failed to send request")?; if response.status().is_success() { response diff --git a/codex-rs/core/src/context/approved_command_prefix_saved.rs b/codex-rs/core/src/context/approved_command_prefix_saved.rs new file mode 100644 index 0000000000..3aac17712a --- /dev/null +++ b/codex-rs/core/src/context/approved_command_prefix_saved.rs @@ -0,0 +1,24 @@ +use super::ContextualUserFragment; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ApprovedCommandPrefixSaved { + prefixes: String, +} + +impl ApprovedCommandPrefixSaved { + pub(crate) fn new(prefixes: impl Into) -> Self { + Self { + prefixes: prefixes.into(), + } + } +} + +impl ContextualUserFragment for ApprovedCommandPrefixSaved { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = ""; + const END_MARKER: &'static str = ""; + + fn body(&self) -> String { + format!("Approved command prefix saved:\n{}", self.prefixes) + } +} diff --git a/codex-rs/core/src/context/apps_instructions.rs b/codex-rs/core/src/context/apps_instructions.rs new file mode 100644 index 0000000000..55865b429a --- /dev/null +++ b/codex-rs/core/src/context/apps_instructions.rs @@ -0,0 +1,30 @@ +use codex_app_server_protocol::AppInfo; +use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_protocol::protocol::APPS_INSTRUCTIONS_CLOSE_TAG; +use codex_protocol::protocol::APPS_INSTRUCTIONS_OPEN_TAG; + +use super::ContextualUserFragment; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct AppsInstructions; + +impl AppsInstructions { + pub(crate) fn from_connectors(connectors: &[AppInfo]) -> Option { + connectors + .iter() + .any(|connector| connector.is_accessible && connector.is_enabled) + .then_some(Self) + } +} + +impl ContextualUserFragment for AppsInstructions { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = APPS_INSTRUCTIONS_OPEN_TAG; + const END_MARKER: &'static str = APPS_INSTRUCTIONS_CLOSE_TAG; + + fn body(&self) -> String { + format!( + "\n## Apps (Connectors)\nApps (Connectors) can be explicitly triggered in user messages in the format `[$app-name](app://{{connector_id}})`. Apps can also be implicitly triggered as long as the context suggests usage of available apps.\nAn app is equivalent to a set of MCP tools within the `{CODEX_APPS_MCP_SERVER_NAME}` MCP.\nAn installed app's MCP tools are either provided to you already, or can be lazy-loaded through the `tool_search` tool. If `tool_search` is available, the apps that are searchable by `tools_search` will be listed by it.\nDo not additionally call list_mcp_resources or list_mcp_resource_templates for apps.\n" + ) + } +} diff --git a/codex-rs/core/src/context/available_plugins_instructions.rs b/codex-rs/core/src/context/available_plugins_instructions.rs new file mode 100644 index 0000000000..52f9c8df48 --- /dev/null +++ b/codex-rs/core/src/context/available_plugins_instructions.rs @@ -0,0 +1,58 @@ +use codex_plugin::PluginCapabilitySummary; +use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_CLOSE_TAG; +use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG; + +use super::ContextualUserFragment; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct AvailablePluginsInstructions { + plugins: Vec, +} + +impl AvailablePluginsInstructions { + pub(crate) fn from_plugins(plugins: &[PluginCapabilitySummary]) -> Option { + if plugins.is_empty() { + return None; + } + + Some(Self { + plugins: plugins.to_vec(), + }) + } +} + +impl ContextualUserFragment for AvailablePluginsInstructions { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = PLUGINS_INSTRUCTIONS_OPEN_TAG; + const END_MARKER: &'static str = PLUGINS_INSTRUCTIONS_CLOSE_TAG; + + fn body(&self) -> String { + let mut lines = vec![ + "## Plugins".to_string(), + "A plugin is a local bundle of skills, MCP servers, and apps. Below is the list of plugins that are enabled and available in this session.".to_string(), + "### Available plugins".to_string(), + ]; + + lines.extend( + self.plugins + .iter() + .map(|plugin| match plugin.description.as_deref() { + Some(description) => format!("- `{}`: {description}", plugin.display_name), + None => format!("- `{}`", plugin.display_name), + }), + ); + + lines.push("### How to use plugins".to_string()); + lines.push( + r###"- Discovery: The list above is the plugins available in this session. +- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list. +- Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn. +- Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task. +- Preference: When a relevant plugin is available, prefer using capabilities associated with that plugin over standalone capabilities that provide similar functionality. +- Missing/blocked: If the user requests a plugin that is not listed above, or the plugin does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback."### + .to_string(), + ); + + format!("\n{}\n", lines.join("\n")) + } +} diff --git a/codex-rs/core/src/context/available_skills_instructions.rs b/codex-rs/core/src/context/available_skills_instructions.rs new file mode 100644 index 0000000000..aba4b20135 --- /dev/null +++ b/codex-rs/core/src/context/available_skills_instructions.rs @@ -0,0 +1,56 @@ +use codex_core_skills::AvailableSkills; +use codex_protocol::protocol::SKILLS_INSTRUCTIONS_CLOSE_TAG; +use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG; + +use super::ContextualUserFragment; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct AvailableSkillsInstructions { + skill_lines: Vec, +} + +impl From for AvailableSkillsInstructions { + fn from(available_skills: AvailableSkills) -> Self { + Self { + skill_lines: available_skills.skill_lines, + } + } +} + +impl ContextualUserFragment for AvailableSkillsInstructions { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = SKILLS_INSTRUCTIONS_OPEN_TAG; + const END_MARKER: &'static str = SKILLS_INSTRUCTIONS_CLOSE_TAG; + + fn body(&self) -> String { + let mut lines: Vec = Vec::new(); + lines.push("## Skills".to_string()); + lines.push("A skill is a set of local instructions to follow that is stored in a `SKILL.md` file. Below is the list of skills that can be used. Each entry includes a name, description, and file path so you can open the source for full instructions when using a specific skill.".to_string()); + lines.push("### Available skills".to_string()); + lines.extend(self.skill_lines.iter().cloned()); + + lines.push("### How to use skills".to_string()); + lines.push( + r###"- Discovery: The list above is the skills available in this session (name + description + file path). Skill bodies live on disk at the listed paths. +- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned. +- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback. +- How to use a skill (progressive disclosure): + 1) After deciding to use a skill, open its `SKILL.md`. Read only enough to follow the workflow. + 2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the skill directory listed above first, and only consider other paths if needed. + 3) If `SKILL.md` points to extra folders such as `references/`, load only the specific files needed for the request; don't bulk-load everything. + 4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks. + 5) If `assets/` or templates exist, reuse them instead of recreating from scratch. +- Coordination and sequencing: + - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them. + - Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why. +- Context hygiene: + - Keep context small: summarize long sections instead of pasting them; only load extra files when needed. + - Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked. + - When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice. +- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue."### + .to_string(), + ); + + format!("\n{}\n", lines.join("\n")) + } +} diff --git a/codex-rs/core/src/context/collaboration_mode_instructions.rs b/codex-rs/core/src/context/collaboration_mode_instructions.rs new file mode 100644 index 0000000000..dcf3bac1de --- /dev/null +++ b/codex-rs/core/src/context/collaboration_mode_instructions.rs @@ -0,0 +1,32 @@ +use super::ContextualUserFragment; +use codex_protocol::config_types::CollaborationMode; +use codex_protocol::protocol::COLLABORATION_MODE_CLOSE_TAG; +use codex_protocol::protocol::COLLABORATION_MODE_OPEN_TAG; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct CollaborationModeInstructions { + instructions: String, +} + +impl CollaborationModeInstructions { + pub(crate) fn from_collaboration_mode(collaboration_mode: &CollaborationMode) -> Option { + collaboration_mode + .settings + .developer_instructions + .as_ref() + .filter(|instructions| !instructions.is_empty()) + .map(|instructions| Self { + instructions: instructions.clone(), + }) + } +} + +impl ContextualUserFragment for CollaborationModeInstructions { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = COLLABORATION_MODE_OPEN_TAG; + const END_MARKER: &'static str = COLLABORATION_MODE_CLOSE_TAG; + + fn body(&self) -> String { + self.instructions.clone() + } +} diff --git a/codex-rs/core/src/context/environment_context.rs b/codex-rs/core/src/context/environment_context.rs index 7ce71111f0..b9fb9dffb2 100644 --- a/codex-rs/core/src/context/environment_context.rs +++ b/codex-rs/core/src/context/environment_context.rs @@ -216,7 +216,7 @@ impl ContextualUserFragment for EnvironmentContext { lines.extend(subagents.lines().map(|line| format!(" {line}"))); lines.push(" ".to_string()); } - format!("\n{}", lines.join("\n")) + format!("\n{}\n", lines.join("\n")) } } diff --git a/codex-rs/core/src/context/fragment.rs b/codex-rs/core/src/context/fragment.rs index e0e6d03303..34f4a7c367 100644 --- a/codex-rs/core/src/context/fragment.rs +++ b/codex-rs/core/src/context/fragment.rs @@ -28,13 +28,16 @@ impl FragmentRegistration for FragmentRegistrationPro } } -/// Context payload that is injected as a user-authored message fragment. +/// Context payload that is injected as a message fragment. /// -/// Implementations own the response role, start/end markers used to recognize -/// the fragment, and provide the fragment body appended directly after the -/// start marker. The default helpers wrap that body and convert it into the -/// response item shape expected by model input assembly. -pub(crate) trait ContextualUserFragment { +/// Implementations own the response role and provide the exact fragment body. +/// Marked fragments also provide start/end markers used to recognize injected +/// context later. `render()` concatenates markers and body without adding +/// separators, so implementations should include any whitespace they need +/// between tags in `body()`. Unmarked fragments should leave both markers empty, +/// in which case the default helpers render only the body and never match +/// arbitrary text. +pub trait ContextualUserFragment { const ROLE: &'static str; const START_MARKER: &'static str; const END_MARKER: &'static str; @@ -45,6 +48,10 @@ pub(crate) trait ContextualUserFragment { where Self: Sized, { + if Self::START_MARKER.is_empty() || Self::END_MARKER.is_empty() { + return false; + } + let trimmed = text.trim_start(); let starts_with_marker = trimmed .get(..Self::START_MARKER.len()) @@ -57,12 +64,11 @@ pub(crate) trait ContextualUserFragment { } fn render(&self) -> String { - format!( - "{}{}\n{}", - Self::START_MARKER, - self.body(), - Self::END_MARKER - ) + if Self::START_MARKER.is_empty() && Self::END_MARKER.is_empty() { + return self.body(); + } + + format!("{}{}{}", Self::START_MARKER, self.body(), Self::END_MARKER) } fn into(self) -> ResponseItem diff --git a/codex-rs/core/src/context/guardian_followup_review_reminder.rs b/codex-rs/core/src/context/guardian_followup_review_reminder.rs new file mode 100644 index 0000000000..972355ba95 --- /dev/null +++ b/codex-rs/core/src/context/guardian_followup_review_reminder.rs @@ -0,0 +1,21 @@ +use super::ContextualUserFragment; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct GuardianFollowupReviewReminder; + +impl ContextualUserFragment for GuardianFollowupReviewReminder { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = ""; + const END_MARKER: &'static str = ""; + + fn body(&self) -> String { + concat!( + "Use prior reviews as context, not binding precedent. ", + "Follow the Workspace Policy. ", + "If the user explicitly approves a previously rejected action after being informed of the ", + "concrete risks, set outcome to \"allow\" unless the policy explicitly disallows user ", + "overwrites in such cases." + ) + .to_string() + } +} diff --git a/codex-rs/core/src/context/hook_additional_context.rs b/codex-rs/core/src/context/hook_additional_context.rs new file mode 100644 index 0000000000..01c95a6524 --- /dev/null +++ b/codex-rs/core/src/context/hook_additional_context.rs @@ -0,0 +1,22 @@ +use super::ContextualUserFragment; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct HookAdditionalContext { + text: String, +} + +impl HookAdditionalContext { + pub(crate) fn new(text: impl Into) -> Self { + Self { text: text.into() } + } +} + +impl ContextualUserFragment for HookAdditionalContext { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = ""; + const END_MARKER: &'static str = ""; + + fn body(&self) -> String { + self.text.clone() + } +} diff --git a/codex-rs/core/src/context/image_generation_instructions.rs b/codex-rs/core/src/context/image_generation_instructions.rs new file mode 100644 index 0000000000..01abee9096 --- /dev/null +++ b/codex-rs/core/src/context/image_generation_instructions.rs @@ -0,0 +1,30 @@ +use super::ContextualUserFragment; +use std::fmt::Display; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ImageGenerationInstructions { + image_output_dir: String, + image_output_path: String, +} + +impl ImageGenerationInstructions { + pub(crate) fn new(image_output_dir: impl Display, image_output_path: impl Display) -> Self { + Self { + image_output_dir: image_output_dir.to_string(), + image_output_path: image_output_path.to_string(), + } + } +} + +impl ContextualUserFragment for ImageGenerationInstructions { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = ""; + const END_MARKER: &'static str = ""; + + fn body(&self) -> String { + format!( + "Generated images are saved to {} as {} by default.\nIf you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it.", + self.image_output_dir, self.image_output_path + ) + } +} diff --git a/codex-rs/core/src/context/mod.rs b/codex-rs/core/src/context/mod.rs index 94c5849f9d..bbc5bcacf1 100644 --- a/codex-rs/core/src/context/mod.rs +++ b/codex-rs/core/src/context/mod.rs @@ -1,20 +1,56 @@ +//! Context fragments injected into model input. + +mod approved_command_prefix_saved; +mod apps_instructions; +mod available_plugins_instructions; +mod available_skills_instructions; +mod collaboration_mode_instructions; mod contextual_user_message; mod environment_context; mod fragment; +mod guardian_followup_review_reminder; +mod hook_additional_context; +mod image_generation_instructions; +mod model_switch_instructions; +mod network_rule_saved; +mod permissions_instructions; +mod personality_spec_instructions; +mod plugin_instructions; +mod realtime_end_instructions; +mod realtime_start_instructions; +mod realtime_start_with_instructions; mod skill_instructions; +mod spawn_agent_instructions; mod subagent_notification; mod turn_aborted; mod user_instructions; mod user_shell_command; +pub(crate) use approved_command_prefix_saved::ApprovedCommandPrefixSaved; +pub(crate) use apps_instructions::AppsInstructions; +pub(crate) use available_plugins_instructions::AvailablePluginsInstructions; +pub(crate) use available_skills_instructions::AvailableSkillsInstructions; +pub(crate) use collaboration_mode_instructions::CollaborationModeInstructions; pub(crate) use contextual_user_message::is_contextual_user_fragment; pub(crate) use contextual_user_message::is_memory_excluded_contextual_user_fragment; pub(crate) use contextual_user_message::parse_visible_hook_prompt_message; pub(crate) use environment_context::EnvironmentContext; -pub(crate) use fragment::ContextualUserFragment; +pub use fragment::ContextualUserFragment; pub(crate) use fragment::FragmentRegistration; pub(crate) use fragment::FragmentRegistrationProxy; +pub(crate) use guardian_followup_review_reminder::GuardianFollowupReviewReminder; +pub(crate) use hook_additional_context::HookAdditionalContext; +pub(crate) use image_generation_instructions::ImageGenerationInstructions; +pub(crate) use model_switch_instructions::ModelSwitchInstructions; +pub(crate) use network_rule_saved::NetworkRuleSaved; +pub use permissions_instructions::PermissionsInstructions; +pub(crate) use personality_spec_instructions::PersonalitySpecInstructions; +pub(crate) use plugin_instructions::PluginInstructions; +pub(crate) use realtime_end_instructions::RealtimeEndInstructions; +pub(crate) use realtime_start_instructions::RealtimeStartInstructions; +pub(crate) use realtime_start_with_instructions::RealtimeStartWithInstructions; pub(crate) use skill_instructions::SkillInstructions; +pub(crate) use spawn_agent_instructions::SpawnAgentInstructions; pub(crate) use subagent_notification::SubagentNotification; pub(crate) use turn_aborted::TurnAborted; pub(crate) use user_instructions::UserInstructions; diff --git a/codex-rs/core/src/context/model_switch_instructions.rs b/codex-rs/core/src/context/model_switch_instructions.rs new file mode 100644 index 0000000000..0b75afb61a --- /dev/null +++ b/codex-rs/core/src/context/model_switch_instructions.rs @@ -0,0 +1,27 @@ +use super::ContextualUserFragment; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ModelSwitchInstructions { + model_instructions: String, +} + +impl ModelSwitchInstructions { + pub(crate) fn new(model_instructions: impl Into) -> Self { + Self { + model_instructions: model_instructions.into(), + } + } +} + +impl ContextualUserFragment for ModelSwitchInstructions { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = ""; + const END_MARKER: &'static str = ""; + + fn body(&self) -> String { + format!( + "\nThe user was previously using a different model. Please continue the conversation according to the following instructions:\n\n{}\n", + self.model_instructions + ) + } +} diff --git a/codex-rs/core/src/context/network_rule_saved.rs b/codex-rs/core/src/context/network_rule_saved.rs new file mode 100644 index 0000000000..8162e6bda2 --- /dev/null +++ b/codex-rs/core/src/context/network_rule_saved.rs @@ -0,0 +1,35 @@ +use super::ContextualUserFragment; +use codex_protocol::approvals::NetworkPolicyAmendment; +use codex_protocol::approvals::NetworkPolicyRuleAction; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct NetworkRuleSaved { + action: NetworkPolicyRuleAction, + host: String, +} + +impl NetworkRuleSaved { + pub(crate) fn new(amendment: &NetworkPolicyAmendment) -> Self { + Self { + action: amendment.action, + host: amendment.host.clone(), + } + } +} + +impl ContextualUserFragment for NetworkRuleSaved { + const ROLE: &'static str = "developer"; + const START_MARKER: &'static str = ""; + const END_MARKER: &'static str = ""; + + fn body(&self) -> String { + let (action, list_name) = match self.action { + NetworkPolicyRuleAction::Allow => ("Allowed", "allowlist"), + NetworkPolicyRuleAction::Deny => ("Denied", "denylist"), + }; + format!( + "{action} network rule saved in execpolicy ({list_name}): {}", + self.host + ) + } +} diff --git a/codex-rs/core/src/context/permissions_instructions.rs b/codex-rs/core/src/context/permissions_instructions.rs new file mode 100644 index 0000000000..db420f7464 --- /dev/null +++ b/codex-rs/core/src/context/permissions_instructions.rs @@ -0,0 +1,316 @@ +use super::ContextualUserFragment; +use codex_execpolicy::Policy; +use codex_protocol::config_types::ApprovalsReviewer; +use codex_protocol::config_types::SandboxMode; +use codex_protocol::models::format_allow_prefixes; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::GranularApprovalConfig; +use codex_protocol::protocol::NetworkAccess; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::WritableRoot; +use codex_utils_template::Template; +use std::path::Path; +use std::sync::LazyLock; + +const APPROVAL_POLICY_NEVER: &str = include_str!("prompts/permissions/approval_policy/never.md"); +const APPROVAL_POLICY_UNLESS_TRUSTED: &str = + include_str!("prompts/permissions/approval_policy/unless_trusted.md"); +const APPROVAL_POLICY_ON_FAILURE: &str = + include_str!("prompts/permissions/approval_policy/on_failure.md"); +const APPROVAL_POLICY_ON_REQUEST_RULE: &str = + include_str!("prompts/permissions/approval_policy/on_request.md"); +const APPROVAL_POLICY_ON_REQUEST_RULE_REQUEST_PERMISSION: &str = + include_str!("prompts/permissions/approval_policy/on_request_rule_request_permission.md"); +const AUTO_REVIEW_APPROVAL_SUFFIX: &str = "`approvals_reviewer` is `auto_review`: Sandbox escalations with require_escalated will be reviewed for compliance with the policy. If a rejection happens, you should proceed only with a materially safer alternative, or inform the user of the risk and send a final message to ask for approval."; + +const SANDBOX_MODE_DANGER_FULL_ACCESS: &str = + include_str!("prompts/permissions/sandbox_mode/danger_full_access.md"); +const SANDBOX_MODE_WORKSPACE_WRITE: &str = + include_str!("prompts/permissions/sandbox_mode/workspace_write.md"); +const SANDBOX_MODE_READ_ONLY: &str = include_str!("prompts/permissions/sandbox_mode/read_only.md"); + +static SANDBOX_MODE_DANGER_FULL_ACCESS_TEMPLATE: LazyLock