diff --git a/.github/actions/setup-bazel-ci/action.yml b/.github/actions/setup-bazel-ci/action.yml index 881209fd81..bb757aab91 100644 --- a/.github/actions/setup-bazel-ci/action.yml +++ b/.github/actions/setup-bazel-ci/action.yml @@ -33,7 +33,7 @@ runs: run: Copy-Item (Get-Command dotslash).Source -Destination "$env:LOCALAPPDATA\Microsoft\WindowsApps\dotslash.exe" - name: Set up Bazel - uses: bazelbuild/setup-bazelisk@b39c379c82683a5f25d34f0d062761f62693e0b2 # v3 + uses: bazel-contrib/setup-bazel@c5acdfb288317d0b5c0bbd7a396a3dc868bb0f86 # 0.19.0 - name: Configure Bazel repository cache id: configure_bazel_repository_cache diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 45322e4ffa..4ea424c435 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,6 +1,6 @@ # External (non-OpenAI) Pull Request Requirements -Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: +External code contributions are by invitation only. Please read the dedicated "Contributing" markdown file for details: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c745106cb..bb5ed5b5bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,11 +45,16 @@ jobs: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - # Use a rust-release version that includes all native binaries. - CODEX_VERSION=0.115.0 + # Use a recent successful rust-release run that published the full + # cross-platform native payload required by the npm package layout. + # Passing the workflow URL directly avoids relying on old rust-v* + # branches remaining discoverable via `gh run list --branch ...`. + CODEX_VERSION=0.125.0 + WORKFLOW_URL="https://github.com/openai/codex/actions/runs/24901475298" OUTPUT_DIR="${RUNNER_TEMP}" python3 ./scripts/stage_npm_packages.py \ --release-version "$CODEX_VERSION" \ + --workflow-url "$WORKFLOW_URL" \ --package codex \ --output-dir "$OUTPUT_DIR" PACK_OUTPUT="${OUTPUT_DIR}/codex-npm-${CODEX_VERSION}.tgz" diff --git a/.github/workflows/rusty-v8-release.yml b/.github/workflows/rusty-v8-release.yml index 29e7b3b1ae..ee92eff4fa 100644 --- a/.github/workflows/rusty-v8-release.yml +++ b/.github/workflows/rusty-v8-release.yml @@ -78,7 +78,9 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - name: Set up Bazel - uses: bazelbuild/setup-bazelisk@b39c379c82683a5f25d34f0d062761f62693e0b2 # v3 + uses: ./.github/actions/setup-bazel-ci + with: + target: ${{ matrix.target }} - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6 diff --git a/.github/workflows/v8-canary.yml b/.github/workflows/v8-canary.yml index f5aa1d7c67..119d042275 100644 --- a/.github/workflows/v8-canary.yml +++ b/.github/workflows/v8-canary.yml @@ -3,6 +3,7 @@ name: v8-canary on: pull_request: paths: + - ".github/actions/setup-bazel-ci/**" - ".github/scripts/rusty_v8_bazel.py" - ".github/workflows/rusty-v8-release.yml" - ".github/workflows/v8-canary.yml" @@ -16,6 +17,7 @@ on: branches: - main paths: + - ".github/actions/setup-bazel-ci/**" - ".github/scripts/rusty_v8_bazel.py" - ".github/workflows/rusty-v8-release.yml" - ".github/workflows/v8-canary.yml" @@ -75,7 +77,9 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - name: Set up Bazel - uses: bazelbuild/setup-bazelisk@b39c379c82683a5f25d34f0d062761f62693e0b2 # v3 + uses: ./.github/actions/setup-bazel-ci + with: + target: ${{ matrix.target }} - name: Set up Python uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6 diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 7c0b30feba..e079e3af0e 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1560,6 +1560,7 @@ "system-deps_7.0.7": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"assert_matches\",\"req\":\"^1.5\"},{\"features\":[\"targets\"],\"name\":\"cfg-expr\",\"req\":\">=0.17, <0.21\"},{\"name\":\"heck\",\"req\":\"^0.5\"},{\"kind\":\"dev\",\"name\":\"itertools\",\"req\":\"^0.14\"},{\"kind\":\"dev\",\"name\":\"lazy_static\",\"req\":\"^1\"},{\"name\":\"pkg-config\",\"req\":\"^0.3.25\"},{\"default_features\":false,\"features\":[\"parse\",\"std\"],\"name\":\"toml\",\"req\":\"^0.9\"},{\"name\":\"version-compare\",\"req\":\"^0.2\"}],\"features\":{}}", "tagptr_0.2.0": "{\"dependencies\":[],\"features\":{}}", "tar_0.4.44": "{\"dependencies\":[{\"name\":\"filetime\",\"req\":\"^0.2.8\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"},{\"name\":\"xattr\",\"optional\":true,\"req\":\"^1.1.3\",\"target\":\"cfg(unix)\"}],\"features\":{\"default\":[\"xattr\"]}}", + "tar_0.4.45": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"astral-tokio-tar\",\"req\":\"^0.5\"},{\"name\":\"filetime\",\"req\":\"^0.2.8\"},{\"name\":\"libc\",\"req\":\"^0.2\",\"target\":\"cfg(unix)\"},{\"features\":[\"small_rng\"],\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"^3\"},{\"features\":[\"macros\",\"rt\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tokio-stream\",\"req\":\"^0.1\"},{\"name\":\"xattr\",\"optional\":true,\"req\":\"^1.1.3\",\"target\":\"cfg(unix)\"}],\"features\":{\"default\":[\"xattr\"]}}", "target-lexicon_0.13.3": "{\"dependencies\":[{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_json\",\"req\":\"^1.0\"}],\"features\":{\"arch_z80\":[],\"arch_zkasm\":[],\"default\":[],\"serde_support\":[\"serde\",\"std\"],\"std\":[]}}", "tempfile_3.27.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3\"},{\"name\":\"fastrand\",\"req\":\"^2.1.1\"},{\"default_features\":false,\"name\":\"getrandom\",\"optional\":true,\"req\":\">=0.3.0, <0.5\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"once_cell\",\"req\":\"^1.19.0\"},{\"features\":[\"fs\"],\"name\":\"rustix\",\"req\":\"^1.1.4\",\"target\":\"cfg(any(unix, target_os = \\\"wasi\\\"))\"},{\"features\":[\"Win32_Storage_FileSystem\",\"Win32_Foundation\"],\"name\":\"windows-sys\",\"req\":\">=0.52, <0.62\",\"target\":\"cfg(windows)\"}],\"features\":{\"default\":[\"getrandom\"],\"nightly\":[]}}", "temporal_capi_0.1.2": "{\"dependencies\":[{\"default_features\":false,\"name\":\"diplomat\",\"req\":\"^0.14.0\"},{\"default_features\":false,\"name\":\"diplomat-runtime\",\"req\":\"^0.14.0\"},{\"default_features\":false,\"features\":[\"unstable\"],\"name\":\"icu_calendar\",\"req\":\"^2.1.0\"},{\"name\":\"icu_locale\",\"req\":\"^2.1.0\"},{\"default_features\":false,\"name\":\"num-traits\",\"req\":\"^0.2.19\"},{\"default_features\":false,\"name\":\"temporal_rs\",\"req\":\"^0.1.2\"},{\"name\":\"timezone_provider\",\"req\":\"^0.1.2\"},{\"name\":\"writeable\",\"req\":\"^0.6.0\"},{\"name\":\"zoneinfo64\",\"optional\":true,\"req\":\"^0.2.0\"}],\"features\":{\"compiled_data\":[\"temporal_rs/compiled_data\"],\"zoneinfo64\":[\"dep:zoneinfo64\",\"timezone_provider/zoneinfo64\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index fbab962cbc..164e8a0857 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1859,6 +1859,7 @@ dependencies = [ "codex-git-utils", "codex-login", "codex-mcp", + "codex-memories-write", "codex-model-provider", "codex-model-provider-info", "codex-models-manager", @@ -1880,6 +1881,7 @@ dependencies = [ "codex-utils-rustls-provider", "constant_time_eq 0.3.1", "core_test_support", + "flate2", "futures", "gethostname", "hmac", @@ -1895,6 +1897,7 @@ dependencies = [ "serial_test", "sha2", "shlex", + "tar", "tempfile", "thiserror 2.0.18", "time", @@ -2116,6 +2119,7 @@ dependencies = [ "codex-login", "codex-mcp", "codex-mcp-server", + "codex-memories-write", "codex-models-manager", "codex-protocol", "codex-responses-api-proxy", @@ -2288,9 +2292,9 @@ dependencies = [ "async-trait", "base64 0.22.1", "codex-app-server-protocol", - "codex-exec-server", "codex-execpolicy", "codex-features", + "codex-file-system", "codex-git-utils", "codex-model-provider-info", "codex-network-proxy", @@ -2370,6 +2374,7 @@ dependencies = [ "codex-hooks", "codex-login", "codex-mcp", + "codex-memories-read", "codex-model-provider", "codex-model-provider-info", "codex-models-manager", @@ -2382,7 +2387,6 @@ dependencies = [ "codex-rollout", "codex-rollout-trace", "codex-sandboxing", - "codex-secrets", "codex-shell-command", "codex-shell-escalation", "codex-state", @@ -2477,11 +2481,13 @@ dependencies = [ "codex-utils-absolute-path", "codex-utils-plugins", "dirs", + "flate2", "libc", "pretty_assertions", "reqwest", "serde", "serde_json", + "tar", "tempfile", "thiserror 2.0.18", "tokio", @@ -2607,6 +2613,7 @@ dependencies = [ "bytes", "codex-app-server-protocol", "codex-client", + "codex-file-system", "codex-protocol", "codex-sandboxing", "codex-test-binary-support", @@ -2717,14 +2724,23 @@ dependencies = [ "tokio", ] +[[package]] +name = "codex-file-system" +version = "0.0.0" +dependencies = [ + "async-trait", + "codex-protocol", + "codex-utils-absolute-path", + "serde", +] + [[package]] name = "codex-git-utils" version = "0.0.0" dependencies = [ "anyhow", - "assert_matches", "chrono", - "codex-exec-server", + "codex-file-system", "codex-protocol", "codex-utils-absolute-path", "futures", @@ -2921,6 +2937,54 @@ dependencies = [ "wiremock", ] +[[package]] +name = "codex-memories-read" +version = "0.0.0" +dependencies = [ + "codex-protocol", + "codex-shell-command", + "codex-utils-absolute-path", + "codex-utils-output-truncation", + "codex-utils-template", + "pretty_assertions", + "tempfile", + "tokio", +] + +[[package]] +name = "codex-memories-write" +version = "0.0.0" +dependencies = [ + "anyhow", + "chrono", + "codex-config", + "codex-core", + "codex-features", + "codex-git-utils", + "codex-login", + "codex-models-manager", + "codex-otel", + "codex-protocol", + "codex-rollout", + "codex-rollout-trace", + "codex-secrets", + "codex-state", + "codex-terminal-detection", + "codex-utils-absolute-path", + "codex-utils-output-truncation", + "codex-utils-template", + "core_test_support", + "futures", + "pretty_assertions", + "serde", + "serde_json", + "tempfile", + "tokio", + "tracing", + "uuid", + "wiremock", +] + [[package]] name = "codex-model-provider" version = "0.0.0" @@ -12232,6 +12296,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tar" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22692a6476a21fa75fdfc11d452fda482af402c008cdbaf3476414e122040973" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "target-lexicon" version = "0.13.3" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 648c184ec8..d39651fedd 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -36,6 +36,7 @@ members = [ "hooks", "secrets", "exec", + "file-system", "exec-server", "execpolicy", "execpolicy-legacy", @@ -46,6 +47,8 @@ members = [ "login", "codex-mcp", "mcp-server", + "memories/read", + "memories/write", "model-provider-info", "models-manager", "network-proxy", @@ -140,6 +143,7 @@ codex-core-plugins = { path = "core-plugins" } codex-core-skills = { path = "core-skills" } codex-device-key = { path = "device-key" } codex-exec = { path = "exec" } +codex-file-system = { path = "file-system" } codex-exec-server = { path = "exec-server" } codex-execpolicy = { path = "execpolicy" } codex-experimental-api-macros = { path = "codex-experimental-api-macros" } @@ -153,6 +157,8 @@ codex-keyring-store = { path = "keyring-store" } codex-linux-sandbox = { path = "linux-sandbox" } codex-lmstudio = { path = "lmstudio" } codex-login = { path = "login" } +codex-memories-read = { path = "memories/read" } +codex-memories-write = { path = "memories/write" } codex-mcp = { path = "codex-mcp" } codex-mcp-server = { path = "mcp-server" } codex-model-provider-info = { path = "model-provider-info" } @@ -254,6 +260,7 @@ encoding_rs = "0.8.35" env-flags = "0.1.1" env_logger = "0.11.9" eventsource-stream = "0.2.3" +flate2 = "1.1.8" futures = { version = "0.3", default-features = false } gethostname = "1.1.0" gix = { version = "0.81.0", default-features = false, features = ["sha1"] } @@ -346,6 +353,7 @@ strum_macros = "0.28.0" supports-color = "3.0.2" syntect = "5" sys-locale = "0.3.2" +tar = { version = "=0.4.45", default-features = false } tempfile = "3.23.0" test-log = "0.2.19" textwrap = "0.16.2" diff --git a/codex-rs/agent-identity/src/lib.rs b/codex-rs/agent-identity/src/lib.rs index bf139f7870..69801f6fc2 100644 --- a/codex-rs/agent-identity/src/lib.rs +++ b/codex-rs/agent-identity/src/lib.rs @@ -322,6 +322,7 @@ pub fn build_abom(session_source: SessionSource) -> AgentBillOfMaterials { | SessionSource::Exec | SessionSource::Mcp | SessionSource::Custom(_) + | SessionSource::Internal(_) | SessionSource::SubAgent(_) | SessionSource::Unknown => "codex-cli".to_string(), }, diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs index 0445975dd6..290dbe28d3 100644 --- a/codex-rs/analytics/src/reducer.rs +++ b/codex-rs/analytics/src/reducer.rs @@ -106,6 +106,7 @@ impl ThreadMetadataState { | SessionSource::Exec | SessionSource::Mcp | SessionSource::Custom(_) + | SessionSource::Internal(_) | SessionSource::Unknown => (None, None), }; Self { diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index e1614c32db..1e7a84efe7 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -1396,6 +1396,55 @@ mod tests { client.shutdown().await.expect("shutdown should complete"); } + #[tokio::test] + async fn remote_typed_request_accepts_large_single_frame_response() { + let padding = "x".repeat((17 << 20) + 1024); + let websocket_url = start_test_remote_server(move |mut websocket| async move { + expect_remote_initialize(&mut websocket).await; + let JSONRPCMessage::Request(request) = read_websocket_message(&mut websocket).await + else { + panic!("expected account/read request"); + }; + assert_eq!(request.method, "account/read"); + write_websocket_message( + &mut websocket, + JSONRPCMessage::Response(JSONRPCResponse { + id: request.id, + result: serde_json::json!({ + "account": null, + "requiresOpenaiAuth": false, + "padding": padding, + }), + }), + ) + .await; + websocket.close(None).await.expect("close should succeed"); + }) + .await; + let client = RemoteAppServerClient::connect(test_remote_connect_args(websocket_url)) + .await + .expect("remote client should connect"); + + let response: GetAccountResponse = client + .request_typed(ClientRequest::GetAccount { + request_id: RequestId::Integer(1), + params: codex_app_server_protocol::GetAccountParams { + refresh_token: false, + }, + }) + .await + .expect("large typed request should succeed"); + assert_eq!( + response, + GetAccountResponse { + account: None, + requires_openai_auth: false, + } + ); + + client.shutdown().await.expect("shutdown should complete"); + } + #[tokio::test] async fn remote_connect_includes_auth_header_when_configured() { let auth_token = "remote-bearer-token".to_string(); diff --git a/codex-rs/app-server-client/src/remote.rs b/codex-rs/app-server-client/src/remote.rs index 4fb54184aa..d75534c160 100644 --- a/codex-rs/app-server-client/src/remote.rs +++ b/codex-rs/app-server-client/src/remote.rs @@ -45,16 +45,18 @@ use tokio::sync::oneshot; use tokio::time::timeout; use tokio_tungstenite::MaybeTlsStream; use tokio_tungstenite::WebSocketStream; -use tokio_tungstenite::connect_async; +use tokio_tungstenite::connect_async_with_config; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tokio_tungstenite::tungstenite::http::HeaderValue; use tokio_tungstenite::tungstenite::http::header::AUTHORIZATION; +use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; use tracing::warn; use url::Url; const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(10); +const REMOTE_APP_SERVER_MAX_WEBSOCKET_MESSAGE_SIZE: usize = 128 << 20; #[derive(Debug, Clone)] pub struct RemoteAppServerConnectArgs { @@ -170,20 +172,32 @@ impl RemoteAppServerClient { request.headers_mut().insert(AUTHORIZATION, header_value); } ensure_rustls_crypto_provider(); - let stream = timeout(CONNECT_TIMEOUT, connect_async(request)) - .await - .map_err(|_| { - IoError::new( - ErrorKind::TimedOut, - format!("timed out connecting to remote app server at `{websocket_url}`"), - ) - })? - .map(|(stream, _response)| stream) - .map_err(|err| { - IoError::other(format!( - "failed to connect to remote app server at `{websocket_url}`: {err}" - )) - })?; + // Remote resume responses can legitimately carry large thread histories. + // Keep a bounded cap, but raise it above tungstenite's 16 MiB frame default. + let websocket_config = WebSocketConfig::default() + .max_frame_size(Some(REMOTE_APP_SERVER_MAX_WEBSOCKET_MESSAGE_SIZE)) + .max_message_size(Some(REMOTE_APP_SERVER_MAX_WEBSOCKET_MESSAGE_SIZE)); + let stream = timeout( + CONNECT_TIMEOUT, + connect_async_with_config( + request, + Some(websocket_config), + /*disable_nagle*/ false, + ), + ) + .await + .map_err(|_| { + IoError::new( + ErrorKind::TimedOut, + format!("timed out connecting to remote app server at `{websocket_url}`"), + ) + })? + .map(|(stream, _response)| stream) + .map_err(|err| { + IoError::other(format!( + "failed to connect to remote app server at `{websocket_url}`: {err}" + )) + })?; let mut stream = stream; let pending_events = initialize_remote_connection( &mut stream, @@ -198,6 +212,7 @@ impl RemoteAppServerClient { let worker_handle = tokio::spawn(async move { let mut pending_requests = HashMap::>>::new(); + let mut worker_exit_error: Option<(ErrorKind, String)> = None; loop { tokio::select! { command = command_rx.recv() => { @@ -224,17 +239,19 @@ impl RemoteAppServerClient { .await { let err_message = err.to_string(); + let message = format!( + "remote app server at `{websocket_url}` write failed: {err_message}" + ); if let Some(response_tx) = pending_requests.remove(&request_id) { let _ = response_tx.send(Err(err)); } let _ = deliver_event( &event_tx, AppServerEvent::Disconnected { - message: format!( - "remote app server at `{websocket_url}` write failed: {err_message}" - ), + message: message.clone(), }, ); + worker_exit_error = Some((ErrorKind::BrokenPipe, message)); break; } } @@ -351,28 +368,34 @@ impl RemoteAppServerClient { .await { let err_message = reject_err.to_string(); + let message = format!( + "remote app server at `{websocket_url}` write failed: {err_message}" + ); let _ = deliver_event( &event_tx, AppServerEvent::Disconnected { - message: format!( - "remote app server at `{websocket_url}` write failed: {err_message}" - ), + message: message.clone(), }, ); + worker_exit_error = + Some((ErrorKind::BrokenPipe, message)); break; } } } } Err(err) => { + let message = format!( + "remote app server at `{websocket_url}` sent invalid JSON-RPC: {err}" + ); let _ = deliver_event( &event_tx, AppServerEvent::Disconnected { - message: format!( - "remote app server at `{websocket_url}` sent invalid JSON-RPC: {err}" - ), + message: message.clone(), }, ); + worker_exit_error = + Some((ErrorKind::InvalidData, message)); break; } } @@ -383,14 +406,19 @@ impl RemoteAppServerClient { .map(|frame| frame.reason.to_string()) .filter(|reason| !reason.is_empty()) .unwrap_or_else(|| "connection closed".to_string()); + let message = format!( + "remote app server at `{websocket_url}` disconnected: {reason}" + ); let _ = deliver_event( &event_tx, AppServerEvent::Disconnected { - message: format!( - "remote app server at `{websocket_url}` disconnected: {reason}" - ), + message: message.clone(), }, ); + worker_exit_error = Some(( + ErrorKind::ConnectionAborted, + message, + )); break; } Some(Ok(Message::Binary(_))) @@ -398,25 +426,29 @@ impl RemoteAppServerClient { | Some(Ok(Message::Pong(_))) | Some(Ok(Message::Frame(_))) => {} Some(Err(err)) => { + let message = format!( + "remote app server at `{websocket_url}` transport failed: {err}" + ); let _ = deliver_event( &event_tx, AppServerEvent::Disconnected { - message: format!( - "remote app server at `{websocket_url}` transport failed: {err}" - ), + message: message.clone(), }, ); + worker_exit_error = Some((ErrorKind::InvalidData, message)); break; } None => { + let message = format!( + "remote app server at `{websocket_url}` closed the connection" + ); let _ = deliver_event( &event_tx, AppServerEvent::Disconnected { - message: format!( - "remote app server at `{websocket_url}` closed the connection" - ), + message: message.clone(), }, ); + worker_exit_error = Some((ErrorKind::UnexpectedEof, message)); break; } } @@ -424,12 +456,14 @@ impl RemoteAppServerClient { } } - let err = IoError::new( - ErrorKind::BrokenPipe, - "remote app-server worker channel is closed", - ); + let (err_kind, err_message) = worker_exit_error.unwrap_or_else(|| { + ( + ErrorKind::BrokenPipe, + "remote app-server worker channel is closed".to_string(), + ) + }); for (_, response_tx) in pending_requests { - let _ = response_tx.send(Err(IoError::new(err.kind(), err.to_string()))); + let _ = response_tx.send(Err(IoError::new(err_kind, err_message.clone()))); } }); diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index cf665f4a5c..31cfd542b7 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -218,17 +218,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Optional full permissions profile for this command.\n\nDefaults to the user's configured permissions when omitted. Cannot be combined with `sandboxPolicy`." - }, "processId": { "description": "Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", "type": [ @@ -1028,21 +1017,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -1415,38 +1389,6 @@ }, "type": "object" }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, "ImageDetail": { "enum": [ "auto", @@ -2691,26 +2633,6 @@ "title": "ImageGenerationCallResponseItem", "type": "object" }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, { "properties": { "encrypted_content": { @@ -3338,17 +3260,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the forked thread. Cannot be combined with `sandbox`." - }, "sandbox": { "anyOf": [ { @@ -3754,17 +3665,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the resumed thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -3948,17 +3848,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for this thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -4170,17 +4059,6 @@ "outputSchema": { "description": "Optional JSON Schema used to constrain the final assistant message for this turn." }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Override the full permissions profile for this turn and subsequent turns. Cannot be combined with `sandboxPolicy`." - }, "personality": { "anyOf": [ { @@ -6124,4 +6002,4 @@ } ], "title": "ClientRequest" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json index 76d265c591..ce587a7f10 100644 --- a/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/CommandExecutionRequestApprovalParams.json @@ -392,21 +392,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { diff --git a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json index ef268908f9..adb50dee43 100644 --- a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json +++ b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalParams.json @@ -177,21 +177,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { diff --git a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalResponse.json b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalResponse.json index f49165296a..3e775a3da9 100644 --- a/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalResponse.json +++ b/codex-rs/app-server-protocol/schema/json/PermissionsRequestApprovalResponse.json @@ -177,21 +177,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 629c0b97fa..aa5c944d9c 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1199,21 +1199,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerRequest.json b/codex-rs/app-server-protocol/schema/json/ServerRequest.json index 50510adf98..51cab50810 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ServerRequest.json @@ -731,21 +731,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { 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 47c6680ad0..1c0ace7fd8 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 @@ -6536,17 +6536,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Optional full permissions profile for this command.\n\nDefaults to the user's configured permissions when omitted. Cannot be combined with `sandboxPolicy`." - }, "processId": { "description": "Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", "type": [ @@ -8573,21 +8562,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -9198,38 +9172,6 @@ "title": "GetAccountResponse", "type": "object" }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, "GitInfo": { "properties": { "branch": { @@ -13138,26 +13080,6 @@ "title": "ImageGenerationCallResponseItem", "type": "object" }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/v2/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, { "properties": { "encrypted_content": { @@ -14510,17 +14432,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the forked thread. Cannot be combined with `sandbox`." - }, "sandbox": { "anyOf": [ { @@ -14589,18 +14500,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { @@ -16034,17 +15933,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the resumed thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -16123,18 +16011,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { @@ -16351,17 +16227,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for this thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -16450,18 +16315,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { @@ -17167,17 +17020,6 @@ "outputSchema": { "description": "Optional JSON Schema used to constrain the final assistant message for this turn." }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/v2/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Override the full permissions profile for this turn and subsequent turns. Cannot be combined with `sandboxPolicy`." - }, "personality": { "anyOf": [ { @@ -17752,4 +17594,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 455d9f16f4..cf721d82af 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 @@ -3055,17 +3055,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Optional full permissions profile for this command.\n\nDefaults to the user's configured permissions when omitted. Cannot be combined with `sandboxPolicy`." - }, "processId": { "description": "Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", "type": [ @@ -5092,21 +5081,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -5828,38 +5802,6 @@ "title": "GetAccountResponse", "type": "object" }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, "GitInfo": { "properties": { "branch": { @@ -9812,26 +9754,6 @@ "title": "ImageGenerationCallResponseItem", "type": "object" }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, { "properties": { "encrypted_content": { @@ -12396,17 +12318,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the forked thread. Cannot be combined with `sandbox`." - }, "sandbox": { "anyOf": [ { @@ -12475,18 +12386,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { @@ -13920,17 +13819,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the resumed thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -14009,18 +13897,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { @@ -14237,17 +14113,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for this thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -14336,18 +14201,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { @@ -15053,17 +14906,6 @@ "outputSchema": { "description": "Optional JSON Schema used to constrain the final assistant message for this turn." }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Override the full permissions profile for this turn and subsequent turns. Cannot be combined with `sandboxPolicy`." - }, "personality": { "anyOf": [ { @@ -15637,4 +15479,4 @@ }, "title": "CodexAppServerProtocolV2", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json b/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json index b85a0e7911..f29483862c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/CommandExecParams.json @@ -146,21 +146,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -520,17 +505,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Optional full permissions profile for this command.\n\nDefaults to the user's configured permissions when omitted. Cannot be combined with `sandboxPolicy`." - }, "processId": { "description": "Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json index e4a278330c..98f44e50a2 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewCompletedNotification.json @@ -184,21 +184,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json index b4ad6af44b..16e47c2d72 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemGuardianApprovalReviewStartedNotification.json @@ -177,21 +177,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json index 34e4086c59..92117cf36d 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/RawResponseItemCompletedNotification.json @@ -143,38 +143,6 @@ } ] }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, "ImageDetail": { "enum": [ "auto", @@ -744,26 +712,6 @@ "title": "ImageGenerationCallResponseItem", "type": "object" }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, { "properties": { "encrypted_content": { @@ -922,4 +870,4 @@ ], "title": "RawResponseItemCompletedNotification", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json index d120fc8b5d..eb8f3bdb4f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkParams.json @@ -183,21 +183,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -488,17 +473,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the forked thread. Cannot be combined with `sandbox`." - }, "sandbox": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index a2f2490a0b..b5d6b139b2 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -569,21 +569,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -2500,18 +2485,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json index 872a3eb324..425fc52a48 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -257,21 +257,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -417,38 +402,6 @@ } ] }, - "GhostCommit": { - "description": "Details of a ghost commit created from a repository state.", - "properties": { - "id": { - "type": "string" - }, - "parent": { - "type": [ - "string", - "null" - ] - }, - "preexisting_untracked_dirs": { - "items": { - "type": "string" - }, - "type": "array" - }, - "preexisting_untracked_files": { - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "id", - "preexisting_untracked_dirs", - "preexisting_untracked_files" - ], - "type": "object" - }, "ImageDetail": { "enum": [ "auto", @@ -1155,26 +1108,6 @@ "title": "ImageGenerationCallResponseItem", "type": "object" }, - { - "properties": { - "ghost_commit": { - "$ref": "#/definitions/GhostCommit" - }, - "type": { - "enum": [ - "ghost_snapshot" - ], - "title": "GhostSnapshotResponseItemType", - "type": "string" - } - }, - "required": [ - "ghost_commit", - "type" - ], - "title": "GhostSnapshotResponseItem", - "type": "object" - }, { "properties": { "encrypted_content": { @@ -1395,17 +1328,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for the resumed thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { @@ -1452,4 +1374,4 @@ ], "title": "ThreadResumeParams", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 516627576e..7135a53174 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -569,21 +569,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -2500,18 +2485,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json index 5a59e280ea..d5e76f05e3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -209,21 +209,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -541,17 +526,6 @@ "null" ] }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Full permissions override for this thread. Cannot be combined with `sandbox`." - }, "personality": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index f773c0be69..5deca9f699 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -569,21 +569,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -2500,18 +2485,6 @@ "modelProvider": { "type": "string" }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Canonical active permissions view for this thread." - }, "reasoningEffort": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json index 559698100f..719a1bedc8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -218,21 +218,6 @@ "title": "MinimalFileSystemSpecialPath", "type": "object" }, - { - "properties": { - "kind": { - "enum": [ - "current_working_directory" - ], - "type": "string" - } - }, - "required": [ - "kind" - ], - "title": "CurrentWorkingDirectoryFileSystemSpecialPath", - "type": "object" - }, { "properties": { "kind": { @@ -844,17 +829,6 @@ "outputSchema": { "description": "Optional JSON Schema used to constrain the final assistant message for this turn." }, - "permissionProfile": { - "anyOf": [ - { - "$ref": "#/definitions/PermissionProfile" - }, - { - "type": "null" - } - ], - "description": "Override the full permissions profile for this turn and subsequent turns. Cannot be combined with `sandboxPolicy`." - }, "personality": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/typescript/GhostCommit.ts b/codex-rs/app-server-protocol/schema/typescript/GhostCommit.ts deleted file mode 100644 index d7b927492b..0000000000 --- a/codex-rs/app-server-protocol/schema/typescript/GhostCommit.ts +++ /dev/null @@ -1,8 +0,0 @@ -// GENERATED CODE! DO NOT MODIFY BY HAND! - -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. - -/** - * Details of a ghost commit created from a repository state. - */ -export type GhostCommit = { id: string, parent: string | null, preexisting_untracked_files: Array, preexisting_untracked_dirs: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/InternalSessionSource.ts b/codex-rs/app-server-protocol/schema/typescript/InternalSessionSource.ts new file mode 100644 index 0000000000..47417c5167 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/InternalSessionSource.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type InternalSessionSource = "memory_consolidation"; diff --git a/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts b/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts index eed78b1fc0..382c89db7d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ResponseItem.ts @@ -3,7 +3,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ContentItem } from "./ContentItem"; import type { FunctionCallOutputBody } from "./FunctionCallOutputBody"; -import type { GhostCommit } from "./GhostCommit"; import type { LocalShellAction } from "./LocalShellAction"; import type { LocalShellStatus } from "./LocalShellStatus"; import type { MessagePhase } from "./MessagePhase"; @@ -15,4 +14,4 @@ export type ResponseItem = { "type": "message", role: string, content: Array, -/** +command: Array, /** * Optional client-supplied, connection-scoped process id. * * Required for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up @@ -26,81 +23,63 @@ command: Array, * `command/exec/terminate` calls. When omitted, buffered execution gets an * internal id that is not exposed to the client. */ -processId?: string | null, -/** +processId?: string | null, /** * Enable PTY mode. * * This implies `streamStdin` and `streamStdoutStderr`. */ -tty?: boolean, -/** +tty?: boolean, /** * Allow follow-up `command/exec/write` requests to write stdin bytes. * * Requires a client-supplied `processId`. */ -streamStdin?: boolean, -/** +streamStdin?: boolean, /** * Stream stdout/stderr via `command/exec/outputDelta` notifications. * * Streamed bytes are not duplicated into the final response and require a * client-supplied `processId`. */ -streamStdoutStderr?: boolean, -/** +streamStdoutStderr?: boolean, /** * Optional per-stream stdout/stderr capture cap in bytes. * * When omitted, the server default applies. Cannot be combined with * `disableOutputCap`. */ -outputBytesCap?: number | null, -/** +outputBytesCap?: number | null, /** * Disable stdout/stderr capture truncation for this request. * * Cannot be combined with `outputBytesCap`. */ -disableOutputCap?: boolean, -/** +disableOutputCap?: boolean, /** * Disable the timeout entirely for this request. * * Cannot be combined with `timeoutMs`. */ -disableTimeout?: boolean, -/** +disableTimeout?: boolean, /** * Optional timeout in milliseconds. * * When omitted, the server default applies. Cannot be combined with * `disableTimeout`. */ -timeoutMs?: number | null, -/** +timeoutMs?: number | null, /** * Optional working directory. Defaults to the server cwd. */ -cwd?: string | null, -/** +cwd?: string | null, /** * Optional environment overrides merged into the server-computed * environment. * * Matching names override inherited values. Set a key to `null` to unset * an inherited variable. */ -env?: { [key in string]?: string | null } | null, -/** +env?: { [key in string]?: string | null } | null, /** * Optional initial PTY size in character cells. Only valid when `tty` is * true. */ -size?: CommandExecTerminalSize | null, -/** +size?: CommandExecTerminalSize | null, /** * Optional sandbox policy for this command. * * Uses the same shape as thread/turn execution sandbox configuration and * defaults to the user's configured policy when omitted. Cannot be * combined with `permissionProfile`. */ -sandboxPolicy?: SandboxPolicy | null, -/** - * Optional full permissions profile for this command. - * - * Defaults to the user's configured permissions when omitted. Cannot be - * combined with `sandboxPolicy`. - */ -permissionProfile?: PermissionProfile | null, }; +sandboxPolicy?: SandboxPolicy | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts index 59da1de945..ca2d0b0aa0 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/CommandExecutionRequestApprovalParams.ts @@ -2,15 +2,12 @@ // 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 { AdditionalPermissionProfile } from "./AdditionalPermissionProfile"; import type { CommandAction } from "./CommandAction"; -import type { CommandExecutionApprovalDecision } from "./CommandExecutionApprovalDecision"; import type { ExecPolicyAmendment } from "./ExecPolicyAmendment"; import type { NetworkApprovalContext } from "./NetworkApprovalContext"; import type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; -export type CommandExecutionRequestApprovalParams = { threadId: string, turnId: string, itemId: string, -/** +export type CommandExecutionRequestApprovalParams = {threadId: string, turnId: string, itemId: string, /** * Unique identifier for this specific approval callback. * * For regular shell/unified_exec approvals, this is null. @@ -19,40 +16,25 @@ export type CommandExecutionRequestApprovalParams = { threadId: string, turnId: * one parent `itemId`, so `approvalId` is a distinct opaque callback id * (a UUID) used to disambiguate routing. */ -approvalId?: string | null, -/** +approvalId?: string | null, /** * Optional explanatory reason (e.g. request for network access). */ -reason?: string | null, -/** +reason?: string | null, /** * Optional context for a managed-network approval prompt. */ -networkApprovalContext?: NetworkApprovalContext | null, -/** +networkApprovalContext?: NetworkApprovalContext | null, /** * The command to be executed. */ -command?: string | null, -/** +command?: string | null, /** * The command's working directory. */ -cwd?: AbsolutePathBuf | null, -/** +cwd?: AbsolutePathBuf | null, /** * Best-effort parsed command actions for friendly display. */ -commandActions?: Array | null, -/** - * Optional additional permissions requested for this command. - */ -additionalPermissions?: AdditionalPermissionProfile | null, -/** +commandActions?: Array | null, /** * Optional proposed execpolicy amendment to allow similar commands without prompting. */ -proposedExecpolicyAmendment?: ExecPolicyAmendment | null, -/** +proposedExecpolicyAmendment?: ExecPolicyAmendment | null, /** * Optional proposed network policy amendments (allow/deny host) for future requests. */ -proposedNetworkPolicyAmendments?: Array | null, -/** - * Ordered list of decisions the client may present for this prompt. - */ -availableDecisions?: Array | null, }; +proposedNetworkPolicyAmendments?: Array | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/FileSystemSpecialPath.ts b/codex-rs/app-server-protocol/schema/typescript/v2/FileSystemSpecialPath.ts index bf27547ee7..f4dc2b01e6 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/FileSystemSpecialPath.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/FileSystemSpecialPath.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type FileSystemSpecialPath = { "kind": "root" } | { "kind": "minimal" } | { "kind": "current_working_directory" } | { "kind": "project_roots", subpath: string | null, } | { "kind": "tmpdir" } | { "kind": "slash_tmp" } | { "kind": "unknown", path: string, subpath: string | null, }; +export type FileSystemSpecialPath = { "kind": "root" } | { "kind": "minimal" } | { "kind": "project_roots", subpath: string | null, } | { "kind": "tmpdir" } | { "kind": "slash_tmp" } | { "kind": "unknown", path: string, subpath: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts index f5f3f1878c..a40e406df9 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkParams.ts @@ -5,7 +5,6 @@ import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxMode } from "./SandboxMode"; /** @@ -18,27 +17,15 @@ import type { SandboxMode } from "./SandboxMode"; * Prefer using thread_id whenever possible. */ export type ThreadForkParams = {threadId: string, /** - * [UNSTABLE] Specify the rollout path to fork from. - * If specified, the thread_id param will be ignored. - */ -path?: string | null, /** * Configuration overrides for the forked thread, if any. */ model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /** * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, /** - * Full permissions override for the forked thread. Cannot be combined - * with `sandbox`. - */ -permissionProfile?: PermissionProfile | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, ephemeral?: boolean, /** +approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, ephemeral?: boolean, /** * When true, return only thread metadata and live fork state without * populating `thread.turns`. This is useful when the client plans to call * `thread/turns/list` immediately after forking. */ -excludeTurns?: boolean, /** - * If true, persist additional rollout EventMsg variants required to - * reconstruct a richer thread history on subsequent resume/fork/read. - */ -persistExtendedHistory: boolean}; +excludeTurns?: boolean}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts index b69f1da012..1207002514 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadForkResponse.ts @@ -6,26 +6,18 @@ import type { ReasoningEffort } from "../ReasoningEffort"; import type { ServiceTier } from "../ServiceTier"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { Thread } from "./Thread"; -export type ThreadForkResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: AbsolutePathBuf, -/** +export type ThreadForkResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: AbsolutePathBuf, /** * Instruction source files currently loaded for this thread. */ -instructionSources: Array, approvalPolicy: AskForApproval, -/** +instructionSources: Array, approvalPolicy: AskForApproval, /** * Reviewer currently used for approval requests on this thread. */ -approvalsReviewer: ApprovalsReviewer, -/** +approvalsReviewer: ApprovalsReviewer, /** * Legacy sandbox policy retained for compatibility. New clients should use * `permissionProfile` when present as the canonical active permissions * view. */ -sandbox: SandboxPolicy, -/** - * Canonical active permissions view for this thread. - */ -permissionProfile: PermissionProfile | null, reasoningEffort: ReasoningEffort | null, }; +sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts index 452126be46..f9821585fb 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeParams.ts @@ -2,12 +2,10 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { Personality } from "../Personality"; -import type { ResponseItem } from "../ResponseItem"; import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxMode } from "./SandboxMode"; /** @@ -22,32 +20,15 @@ import type { SandboxMode } from "./SandboxMode"; * Prefer using thread_id whenever possible. */ export type ThreadResumeParams = {threadId: string, /** - * [UNSTABLE] FOR CODEX CLOUD - DO NOT USE. - * If specified, the thread will be resumed with the provided history - * instead of loaded from disk. - */ -history?: Array | null, /** - * [UNSTABLE] Specify the rollout path to resume from. - * If specified, the thread_id param will be ignored. - */ -path?: string | null, /** * Configuration overrides for the resumed thread, if any. */ model?: string | null, modelProvider?: string | null, serviceTier?: ServiceTier | null | null, cwd?: string | null, approvalPolicy?: AskForApproval | null, /** * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, /** - * Full permissions override for the resumed thread. Cannot be combined - * with `sandbox`. - */ -permissionProfile?: PermissionProfile | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, /** +approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, /** * When true, return only thread metadata and live-resume state without * populating `thread.turns`. This is useful when the client plans to call * `thread/turns/list` immediately after resuming. */ -excludeTurns?: boolean, /** - * If true, persist additional rollout EventMsg variants required to - * reconstruct a richer thread history on subsequent resume/fork/read. - */ -persistExtendedHistory: boolean}; +excludeTurns?: boolean}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts index 5ceec7f3fe..20f91b3e91 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeResponse.ts @@ -6,26 +6,18 @@ import type { ReasoningEffort } from "../ReasoningEffort"; import type { ServiceTier } from "../ServiceTier"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { Thread } from "./Thread"; -export type ThreadResumeResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: AbsolutePathBuf, -/** +export type ThreadResumeResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: AbsolutePathBuf, /** * Instruction source files currently loaded for this thread. */ -instructionSources: Array, approvalPolicy: AskForApproval, -/** +instructionSources: Array, approvalPolicy: AskForApproval, /** * Reviewer currently used for approval requests on this thread. */ -approvalsReviewer: ApprovalsReviewer, -/** +approvalsReviewer: ApprovalsReviewer, /** * Legacy sandbox policy retained for compatibility. New clients should use * `permissionProfile` when present as the canonical active permissions * view. */ -sandbox: SandboxPolicy, -/** - * Canonical active permissions view for this thread. - */ -permissionProfile: PermissionProfile | null, reasoningEffort: ReasoningEffort | null, }; +sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts index 8b9dafec9f..374ac2e681 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartParams.ts @@ -6,7 +6,6 @@ import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxMode } from "./SandboxMode"; import type { ThreadStartSource } from "./ThreadStartSource"; @@ -14,16 +13,4 @@ export type ThreadStartParams = {model?: string | null, modelProvider?: string | * Override where approval requests are routed for review on this thread * and subsequent turns. */ -approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, /** - * Full permissions override for this thread. Cannot be combined with - * `sandbox`. - */ -permissionProfile?: PermissionProfile | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, sessionStartSource?: ThreadStartSource | null, /** - * If true, opt into emitting raw Responses API items on the event stream. - * This is for internal use only (e.g. Codex Cloud). - */ -experimentalRawEvents: boolean, /** - * If true, persist additional rollout EventMsg variants required to - * reconstruct a richer thread history on resume/fork/read. - */ -persistExtendedHistory: boolean}; +approvalsReviewer?: ApprovalsReviewer | null, sandbox?: SandboxMode | null, config?: { [key in string]?: JsonValue } | null, serviceName?: string | null, baseInstructions?: string | null, developerInstructions?: string | null, personality?: Personality | null, ephemeral?: boolean | null, sessionStartSource?: ThreadStartSource | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts index 61d268afe8..87e15411a2 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadStartResponse.ts @@ -6,26 +6,18 @@ import type { ReasoningEffort } from "../ReasoningEffort"; import type { ServiceTier } from "../ServiceTier"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { Thread } from "./Thread"; -export type ThreadStartResponse = { thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: AbsolutePathBuf, -/** +export type ThreadStartResponse = {thread: Thread, model: string, modelProvider: string, serviceTier: ServiceTier | null, cwd: AbsolutePathBuf, /** * Instruction source files currently loaded for this thread. */ -instructionSources: Array, approvalPolicy: AskForApproval, -/** +instructionSources: Array, approvalPolicy: AskForApproval, /** * Reviewer currently used for approval requests on this thread. */ -approvalsReviewer: ApprovalsReviewer, -/** +approvalsReviewer: ApprovalsReviewer, /** * Legacy sandbox policy retained for compatibility. New clients should use * `permissionProfile` when present as the canonical active permissions * view. */ -sandbox: SandboxPolicy, -/** - * Canonical active permissions view for this thread. - */ -permissionProfile: PermissionProfile | null, reasoningEffort: ReasoningEffort | null, }; +sandbox: SandboxPolicy, reasoningEffort: ReasoningEffort | null}; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts index 3d12e6001c..4af17115c8 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts @@ -1,7 +1,6 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { CollaborationMode } from "../CollaborationMode"; import type { Personality } from "../Personality"; import type { ReasoningEffort } from "../ReasoningEffort"; import type { ReasoningSummary } from "../ReasoningSummary"; @@ -9,7 +8,6 @@ import type { ServiceTier } from "../ServiceTier"; import type { JsonValue } from "../serde_json/JsonValue"; import type { ApprovalsReviewer } from "./ApprovalsReviewer"; import type { AskForApproval } from "./AskForApproval"; -import type { PermissionProfile } from "./PermissionProfile"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { UserInput } from "./UserInput"; @@ -27,10 +25,6 @@ approvalsReviewer?: ApprovalsReviewer | null, /** * Override the sandbox policy for this turn and subsequent turns. */ sandboxPolicy?: SandboxPolicy | null, /** - * Override the full permissions profile for this turn and subsequent - * turns. Cannot be combined with `sandboxPolicy`. - */ -permissionProfile?: PermissionProfile | null, /** * Override the model for this turn and subsequent turns. */ model?: string | null, /** @@ -49,11 +43,4 @@ personality?: Personality | null, /** * Optional JSON Schema used to constrain the final assistant message for * this turn. */ -outputSchema?: JsonValue | null, /** - * EXPERIMENTAL - Set a pre-set collaboration mode. - * Takes precedence over model, reasoning_effort, and developer instructions if set. - * - * For `collaboration_mode.settings.developer_instructions`, `null` means - * "use the built-in instructions for the selected mode". - */ -collaborationMode?: CollaborationMode | null}; +outputSchema?: JsonValue | null}; diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 96bb8d17a9..0f9b33671b 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -736,11 +736,11 @@ fn find_top_level_brace_span(input: &str) -> Option<(usize, usize)> { let mut state = ScanState::default(); let mut open_index = None; for (index, ch) in input.char_indices() { - if !state.in_string() && ch == '{' && state.depth.is_top_level() { + if !state.in_ignored_syntax() && ch == '{' && state.depth.is_top_level() { open_index = Some(index); } state.observe(ch); - if !state.in_string() + if !state.in_ignored_syntax() && ch == '}' && state.depth.is_top_level() && let Some(open) = open_index @@ -760,7 +760,7 @@ fn split_top_level_multi(input: &str, delimiters: &[char]) -> Vec { let mut start = 0usize; let mut parts = Vec::new(); for (index, ch) in input.char_indices() { - if !state.in_string() && state.depth.is_top_level() && delimiters.contains(&ch) { + if !state.in_ignored_syntax() && state.depth.is_top_level() && delimiters.contains(&ch) { let part = input[start..index].trim(); if !part.is_empty() { parts.push(part.to_string()); @@ -882,22 +882,58 @@ struct ScanState { depth: Depth, string_delim: Option, escape: bool, + block_comment: bool, + line_comment: bool, + previous_char: Option, } impl ScanState { fn observe(&mut self, ch: char) { + if self.line_comment { + if ch == '\n' { + self.line_comment = false; + } + self.previous_char = Some(ch); + return; + } + + if self.block_comment { + if self.previous_char == Some('*') && ch == '/' { + self.block_comment = false; + self.previous_char = None; + } else { + self.previous_char = Some(ch); + } + return; + } + if let Some(delim) = self.string_delim { if self.escape { self.escape = false; + self.previous_char = Some(ch); return; } if ch == '\\' { self.escape = true; + self.previous_char = Some(ch); return; } if ch == delim { self.string_delim = None; } + self.previous_char = Some(ch); + return; + } + + if self.previous_char == Some('/') && ch == '/' { + self.line_comment = true; + self.previous_char = Some(ch); + return; + } + + if self.previous_char == Some('/') && ch == '*' { + self.block_comment = true; + self.previous_char = Some(ch); return; } @@ -919,10 +955,11 @@ impl ScanState { } _ => {} } + self.previous_char = Some(ch); } - fn in_string(&self) -> bool { - self.string_delim.is_some() + fn in_ignored_syntax(&self) -> bool { + self.string_delim.is_some() || self.block_comment || self.line_comment } } @@ -2694,6 +2731,79 @@ export type Config = { stableField: Keep, unstableField: string | null } & ({ [k Ok(()) } + #[test] + fn experimental_type_fields_ts_filter_handles_generated_command_params_shape() -> Result<()> { + let output_dir = std::env::temp_dir().join(format!("codex_ts_filter_{}", Uuid::now_v7())); + fs::create_dir_all(&output_dir)?; + + struct TempDirGuard(PathBuf); + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + let _guard = TempDirGuard(output_dir.clone()); + let path = output_dir.join("CommandExecParams.ts"); + let content = r#"import type { CommandExecTerminalSize } from "./CommandExecTerminalSize"; +import type { PermissionProfile } from "./PermissionProfile"; +import type { SandboxPolicy } from "./SandboxPolicy"; + +export type CommandExecParams = {/** + * Command argv vector. Empty arrays are rejected. + */ +command: Array, /** + * Optional environment overrides merged into the server-computed + * environment. + */ +env?: { [key in string]?: string | null } | null, /** + * Optional initial PTY size in character cells. Only valid when `tty` is + * true. + */ +size?: CommandExecTerminalSize | null, /** + * Optional sandbox policy for this command. + * + * Uses the same shape as thread/turn execution sandbox configuration and + * defaults to the user's configured policy when omitted. Cannot be + * combined with `permissionProfile`. + */ +sandboxPolicy?: SandboxPolicy | null, +/** + * Optional full permissions profile for this command. + * + * Defaults to the user's configured permissions when omitted. Cannot be + * combined with `sandboxPolicy`. + */ +permissionProfile?: PermissionProfile | null}; +"#; + fs::write(&path, content)?; + + static CUSTOM_FIELD: crate::experimental_api::ExperimentalField = + crate::experimental_api::ExperimentalField { + type_name: "CommandExecParams", + field_name: "permissionProfile", + reason: "command/exec.permissionProfile", + }; + filter_experimental_type_fields_ts(&output_dir, &[&CUSTOM_FIELD])?; + + let filtered = fs::read_to_string(&path)?; + assert_eq!( + filtered.contains("permissionProfile?: PermissionProfile"), + false + ); + assert_eq!( + filtered.contains(r#"import type { PermissionProfile } from "./PermissionProfile";"#), + false + ); + assert_eq!(filtered.contains("sandboxPolicy?: SandboxPolicy"), true); + assert_eq!( + filtered.contains(r#"import type { SandboxPolicy } from "./SandboxPolicy";"#), + true + ); + Ok(()) + } + #[test] fn stable_schema_filter_removes_mock_experimental_method() -> Result<()> { let output_dir = std::env::temp_dir().join(format!("codex_schema_{}", Uuid::now_v7())); diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 016d6e16b8..167435ac88 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -581,6 +581,7 @@ client_request_definitions! { /// Execute a standalone command (argv vector) under the server's sandbox. OneOffCommandExec => "command/exec" { params: v2::CommandExecParams, + inspect_params: true, response: v2::CommandExecResponse, }, /// Write stdin bytes to a running `command/exec` session or close stdin. @@ -2049,6 +2050,33 @@ mod tests { let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); assert_eq!(reason, Some("mock/experimentalMethod")); } + + #[test] + fn command_exec_permission_profile_is_marked_experimental() { + let request = ClientRequest::OneOffCommandExec { + request_id: RequestId::Integer(1), + params: v2::CommandExecParams { + command: vec!["pwd".to_string()], + process_id: None, + tty: false, + stream_stdin: false, + stream_stdout_stderr: false, + output_bytes_cap: None, + disable_output_cap: false, + disable_timeout: false, + timeout_ms: None, + cwd: None, + env: None, + size: None, + sandbox_policy: None, + permission_profile: Some(v2::PermissionProfile::Disabled), + }, + }; + + let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request); + assert_eq!(reason, Some("command/exec.permissionProfile")); + } + #[test] fn thread_realtime_start_is_marked_experimental() { let request = ClientRequest::ThreadRealtimeStart { diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index b7dccc8613..64f16d1625 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1434,7 +1434,7 @@ v2_enum_from_core!( pub enum FileSystemSpecialPath { Root, Minimal, - CurrentWorkingDirectory, + #[serde(alias = "current_working_directory")] ProjectRoots { subpath: Option, }, @@ -1451,7 +1451,6 @@ impl From for FileSystemSpecialPath { match value { CoreFileSystemSpecialPath::Root => Self::Root, CoreFileSystemSpecialPath::Minimal => Self::Minimal, - CoreFileSystemSpecialPath::CurrentWorkingDirectory => Self::CurrentWorkingDirectory, CoreFileSystemSpecialPath::ProjectRoots { subpath } => Self::ProjectRoots { subpath }, CoreFileSystemSpecialPath::Tmpdir => Self::Tmpdir, CoreFileSystemSpecialPath::SlashTmp => Self::SlashTmp, @@ -1465,7 +1464,6 @@ impl From for CoreFileSystemSpecialPath { match value { FileSystemSpecialPath::Root => Self::Root, FileSystemSpecialPath::Minimal => Self::Minimal, - FileSystemSpecialPath::CurrentWorkingDirectory => Self::CurrentWorkingDirectory, FileSystemSpecialPath::ProjectRoots { subpath } => Self::ProjectRoots { subpath }, FileSystemSpecialPath::Tmpdir => Self::Tmpdir, FileSystemSpecialPath::SlashTmp => Self::SlashTmp, @@ -1998,6 +1996,8 @@ impl From for SessionSource { CoreSessionSource::Exec => SessionSource::Exec, CoreSessionSource::Mcp => SessionSource::AppServer, CoreSessionSource::Custom(source) => SessionSource::Custom(source), + // We do not want to render those at the app-server level. + CoreSessionSource::Internal(_) => SessionSource::Unknown, CoreSessionSource::SubAgent(sub) => SessionSource::SubAgent(sub), CoreSessionSource::Unknown => SessionSource::Unknown, } @@ -3165,7 +3165,7 @@ pub struct CommandExecTerminalSize { /// The final `command/exec` response is deferred until the process exits and is /// sent only after all `command/exec/outputDelta` notifications for that /// connection have been emitted. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] pub struct CommandExecParams { @@ -3244,6 +3244,7 @@ pub struct CommandExecParams { /// /// Defaults to the user's configured permissions when omitted. Cannot be /// combined with `sandboxPolicy`. + #[experimental("command/exec.permissionProfile")] #[ts(optional = nullable)] pub permission_profile: Option, } @@ -3366,6 +3367,7 @@ pub struct ThreadStartParams { pub sandbox: Option, /// Full permissions override for this thread. Cannot be combined with /// `sandbox`. + #[experimental("thread/start.permissionProfile")] #[ts(optional = nullable)] pub permission_profile: Option, #[ts(optional = nullable)] @@ -3449,6 +3451,7 @@ pub struct ThreadStartResponse { /// view. pub sandbox: SandboxPolicy, /// Canonical active permissions view for this thread. + #[experimental("thread/start.permissionProfile")] #[serde(default)] pub permission_profile: Option, pub reasoning_effort: Option, @@ -3510,6 +3513,7 @@ pub struct ThreadResumeParams { pub sandbox: Option, /// Full permissions override for the resumed thread. Cannot be combined /// with `sandbox`. + #[experimental("thread/resume.permissionProfile")] #[ts(optional = nullable)] pub permission_profile: Option, #[ts(optional = nullable)] @@ -3553,6 +3557,7 @@ pub struct ThreadResumeResponse { /// view. pub sandbox: SandboxPolicy, /// Canonical active permissions view for this thread. + #[experimental("thread/resume.permissionProfile")] #[serde(default)] pub permission_profile: Option, pub reasoning_effort: Option, @@ -3605,6 +3610,7 @@ pub struct ThreadForkParams { pub sandbox: Option, /// Full permissions override for the forked thread. Cannot be combined /// with `sandbox`. + #[experimental("thread/fork.permissionProfile")] #[ts(optional = nullable)] pub permission_profile: Option, #[ts(optional = nullable)] @@ -3648,6 +3654,7 @@ pub struct ThreadForkResponse { /// view. pub sandbox: SandboxPolicy, /// Canonical active permissions view for this thread. + #[experimental("thread/fork.permissionProfile")] #[serde(default)] pub permission_profile: Option, pub reasoning_effort: Option, @@ -5186,6 +5193,7 @@ pub struct TurnStartParams { pub sandbox_policy: Option, /// Override the full permissions profile for this turn and subsequent /// turns. Cannot be combined with `sandboxPolicy`. + #[experimental("turn/start.permissionProfile")] #[ts(optional = nullable)] pub permission_profile: Option, /// Override the model for this turn and subsequent turns. @@ -8111,6 +8119,26 @@ mod tests { .expect_err("zero glob scan depth should fail deserialization"); } + #[test] + fn legacy_current_working_directory_special_path_deserializes_as_project_roots() { + let special_path = serde_json::from_value::(json!({ + "kind": "current_working_directory", + })) + .expect("legacy cwd special path should deserialize"); + + assert_eq!( + special_path, + FileSystemSpecialPath::ProjectRoots { subpath: None } + ); + assert_eq!( + serde_json::to_value(&special_path).expect("serialize special path"), + json!({ + "kind": "project_roots", + "subpath": null, + }) + ); + } + #[test] fn permissions_request_approval_response_uses_granted_permission_profile_without_macos() { let read_only_path = if cfg!(windows) { @@ -10279,6 +10307,27 @@ mod tests { plugin_id: "gmail@openai-curated".to_string(), }, ); + + assert_eq!( + serde_json::to_value(PluginUninstallParams { + plugin_id: "plugins~Plugin_gmail".to_string(), + }) + .unwrap(), + json!({ + "pluginId": "plugins~Plugin_gmail", + }), + ); + + assert_eq!( + serde_json::from_value::(json!({ + "pluginId": "plugins~Plugin_gmail", + "forceRemoteSync": true, + })) + .unwrap(), + PluginUninstallParams { + plugin_id: "plugins~Plugin_gmail".to_string(), + }, + ); } #[test] diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 06ed624c37..d1721c99d1 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -48,6 +48,7 @@ codex-backend-client = { workspace = true } codex-file-search = { workspace = true } codex-chatgpt = { workspace = true } codex-login = { workspace = true } +codex-memories-write = { workspace = true } codex-mcp = { workspace = true } codex-model-provider = { workspace = true } codex-models-manager = { workspace = true } @@ -105,6 +106,7 @@ axum = { workspace = true, default-features = false, features = [ core_test_support = { workspace = true } codex-model-provider-info = { workspace = true } codex-utils-cargo-bin = { workspace = true } +flate2 = { workspace = true } opentelemetry = { workspace = true } opentelemetry_sdk = { workspace = true } pretty_assertions = { workspace = true } @@ -115,6 +117,7 @@ rmcp = { workspace = true, default-features = false, features = [ "transport-streamable-http-server", ] } serial_test = { workspace = true } +tar = { workspace = true } tokio-tungstenite = { workspace = true } tracing-opentelemetry = { workspace = true } wiremock = { workspace = true } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 35df7016c4..2f968789e4 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -207,7 +207,7 @@ Example with notification opt-out: - `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**). +- `plugin/uninstall` — uninstall a local plugin by `pluginId` in `@` form by removing its cached files and clearing its user-level config entry, or uninstall a remote ChatGPT plugin by backend `pluginId` by forwarding the uninstall to the ChatGPT plugin backend and removing any downloaded remote-plugin cache (**under development; do not call from production clients yet**). - `mcpServer/oauth/login` — start an OAuth login for a configured MCP server; returns an `authorization_url` and later emits `mcpServer/oauthLogin/completed` once the browser flow finishes. - `tool/requestUserInput` — prompt the user with 1–3 short questions for a tool call and return their answers (experimental). - `config/mcpServer/reload` — reload MCP server config from disk and queue a refresh for loaded threads (applied on each thread's next active turn); returns `{}`. Use this after editing `config.toml` without restarting the server. @@ -909,7 +909,7 @@ Run a standalone command (argv vector) in the server’s sandbox without creatin "type": "managed", "fileSystem": { "type": "restricted", "entries": [ { "path": { "type": "special", "value": { "kind": "root" } }, "access": "read" }, - { "path": { "type": "special", "value": { "kind": "current_working_directory" } }, "access": "write" } + { "path": { "type": "special", "value": { "kind": "project_roots", "subpath": null } }, "access": "write" } ] }, "network": { "enabled": false } }, @@ -1255,7 +1255,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 `cwd` field identifies the directory used to resolve cwd-relative permissions such as `:cwd`, `:project_roots`, and relative deny globs. +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 project-root permissions and relative deny globs. ```json { diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index a1eba990c6..04de06f469 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -2,8 +2,8 @@ use crate::codex_message_processor::ApiVersion; use crate::codex_message_processor::read_rollout_items_from_rollout; use crate::codex_message_processor::read_summary_from_rollout; use crate::codex_message_processor::summary_to_thread; -use crate::error_code::INTERNAL_ERROR_CODE; -use crate::error_code::INVALID_REQUEST_ERROR_CODE; +use crate::error_code::internal_error; +use crate::error_code::invalid_request; use crate::outgoing_message::ClientRequestResult; use crate::outgoing_message::ThreadScopedOutgoingMessageSender; use crate::server_request_error::is_turn_transition_server_request_error; @@ -51,7 +51,6 @@ use codex_app_server_protocol::HookStartedNotification; use codex_app_server_protocol::InterruptConversationResponse; use codex_app_server_protocol::ItemCompletedNotification; use codex_app_server_protocol::ItemStartedNotification; -use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::McpServerElicitationAction; use codex_app_server_protocol::McpServerElicitationRequestParams; use codex_app_server_protocol::McpServerElicitationRequestResponse; @@ -1876,12 +1875,12 @@ pub(crate) async fn apply_bespoke_event_handling( if let Some(request_id) = pending { let Some(rollout_path) = conversation.rollout_path() else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "thread has no persisted rollout".to_string(), - data: None, - }; - outgoing.send_error(request_id, error).await; + outgoing + .send_error( + request_id, + invalid_request("thread has no persisted rollout"), + ) + .await; return; }; let response = match read_summary_from_rollout( @@ -1912,29 +1911,29 @@ pub(crate) async fn apply_bespoke_event_handling( ThreadRollbackResponse { thread } } Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to load rollout `{}`: {err}", - rollout_path.display() - ), - data: None, - }; - outgoing.send_error(request_id.clone(), error).await; + outgoing + .send_error( + request_id.clone(), + internal_error(format!( + "failed to load rollout `{}`: {err}", + rollout_path.display() + )), + ) + .await; return; } } } Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to load rollout `{}`: {err}", - rollout_path.display() - ), - data: None, - }; - outgoing.send_error(request_id.clone(), error).await; + outgoing + .send_error( + request_id.clone(), + internal_error(format!( + "failed to load rollout `{}`: {err}", + rollout_path.display() + )), + ) + .await; return; } }; @@ -2332,14 +2331,7 @@ async fn handle_thread_rollback_failed( if let Some(request_id) = pending_rollback { outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: message.clone(), - data: None, - }, - ) + .send_error(request_id, invalid_request(message)) .await; } } @@ -4008,7 +4000,7 @@ mod tests { file_system: Some(CoreFileSystemPermissions { entries: vec![FileSystemSandboxEntry { path: FileSystemPath::Special { - value: FileSystemSpecialPath::CurrentWorkingDirectory, + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), }, access: FileSystemAccessMode::Write, }], @@ -4054,7 +4046,7 @@ mod tests { file_system: Some(CoreFileSystemPermissions { entries: vec![FileSystemSandboxEntry { path: FileSystemPath::Special { - value: FileSystemSpecialPath::CurrentWorkingDirectory, + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), }, access: FileSystemAccessMode::Write, }], @@ -4104,7 +4096,8 @@ mod tests { "path": { "type": "special", "value": { - "kind": "current_working_directory" + "kind": "project_roots", + "subpath": null } }, "access": "write" diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index c86d414359..519ea50fd1 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -7,6 +7,7 @@ use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_PARAMS_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; +use crate::error_code::invalid_params; use crate::fuzzy_file_search::FuzzyFileSearchSession; use crate::fuzzy_file_search::run_fuzzy_file_search; use crate::fuzzy_file_search::start_fuzzy_file_search_session; @@ -240,11 +241,10 @@ use codex_core::ForkSnapshot; use codex_core::NewThread; use codex_core::RolloutRecorder; use codex_core::SessionMeta; -use codex_core::StartThreadWithToolsOptions; +use codex_core::StartThreadOptions; use codex_core::SteerInputError; use codex_core::ThreadConfigSnapshot; use codex_core::ThreadManager; -use codex_core::clear_memory_roots_contents; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; @@ -314,6 +314,7 @@ use codex_mcp::discover_supported_scopes; 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_memories_write::clear_memory_roots_contents; use codex_model_provider::ProviderAccountError; use codex_model_provider::create_model_provider; use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig; @@ -495,6 +496,13 @@ enum ThreadReadViewError { mod thread_goal_handlers; use self::thread_goal_handlers::api_thread_goal_from_state; +fn thread_read_view_error(err: ThreadReadViewError) -> JSONRPCErrorError { + match err { + ThreadReadViewError::InvalidRequest(message) => invalid_request(message), + ThreadReadViewError::Internal(message) => internal_error(message), + } +} + impl Drop for ActiveLogin { fn drop(&mut self) { self.cancel(); @@ -534,12 +542,12 @@ pub(crate) enum ApiVersion { #[derive(Clone)] struct ListenerTaskContext { + auth_manager: Arc, thread_manager: Arc, thread_state_manager: ThreadStateManager, outgoing: Arc, pending_thread_unloads: Arc>>, analytics_events_client: AnalyticsEventsClient, - general_analytics_enabled: bool, thread_watch_manager: ThreadWatchManager, fallback_model_provider: String, codex_home: PathBuf, @@ -726,14 +734,12 @@ impl CodexMessageProcessor { error: &JSONRPCErrorError, error_type: Option, ) { - if self.config.features.enabled(Feature::GeneralAnalytics) { - self.analytics_events_client.track_error_response( - request_id.connection_id.0, - request_id.request_id.clone(), - error.clone(), - error_type, - ); - } + self.analytics_events_client.track_error_response( + request_id.connection_id.0, + request_id.request_id.clone(), + error.clone(), + error_type, + ); } async fn load_thread( @@ -1353,7 +1359,7 @@ impl CodexMessageProcessor { self.config.cli_auth_credentials_store_mode, ) { Ok(()) => { - self.auth_manager.reload(); + self.auth_manager.reload().await; Ok(()) } Err(err) => Err(JSONRPCErrorError { @@ -1365,31 +1371,16 @@ impl CodexMessageProcessor { } async fn login_api_key_v2(&self, request_id: ConnectionRequestId, params: LoginApiKeyParams) { - match self.login_api_key_common(¶ms).await { - Ok(()) => { - let response = codex_app_server_protocol::LoginAccountResponse::ApiKey {}; - self.outgoing.send_response(request_id, response).await; + let result = self + .login_api_key_common(¶ms) + .await + .map(|()| LoginAccountResponse::ApiKey {}); + let logged_in = result.is_ok(); + self.outgoing.send_result(request_id, result).await; - let payload_login_completed = AccountLoginCompletedNotification { - login_id: None, - success: true, - error: None, - }; - self.outgoing - .send_server_notification(ServerNotification::AccountLoginCompleted( - payload_login_completed, - )) - .await; - - self.outgoing - .send_server_notification(ServerNotification::AccountUpdated( - self.current_account_updated_notification(), - )) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } + if logged_in { + self.send_login_success_notifications(/*login_id*/ None) + .await; } } @@ -1452,202 +1443,143 @@ impl CodexMessageProcessor { } async fn login_chatgpt_v2(&self, request_id: ConnectionRequestId) { - match self.login_chatgpt_common().await { - Ok(opts) => match run_login_server(opts) { - Ok(server) => { - let login_id = Uuid::new_v4(); - let shutdown_handle = server.cancel_handle(); + let result = self.login_chatgpt_response().await; + self.outgoing.send_result(request_id, result).await; + } - // Replace active login if present. - { - let mut guard = self.active_login.lock().await; - if let Some(existing) = guard.take() { - drop(existing); - } - *guard = Some(ActiveLogin::Browser { - shutdown_handle: shutdown_handle.clone(), - login_id, - }); - } + async fn login_chatgpt_response(&self) -> Result { + let opts = self.login_chatgpt_common().await?; + let server = run_login_server(opts) + .map_err(|err| internal_error(format!("failed to start login server: {err}")))?; + let login_id = Uuid::new_v4(); + let shutdown_handle = server.cancel_handle(); - // Spawn background task to monitor completion. - let outgoing_clone = self.outgoing.clone(); - let active_login = self.active_login.clone(); - let auth_manager = self.auth_manager.clone(); - let config_manager = self.config_manager.clone(); - let chatgpt_base_url = self.config.chatgpt_base_url.clone(); - let auth_url = server.auth_url.clone(); - tokio::spawn(async move { - let (success, error_msg) = match tokio::time::timeout( - LOGIN_CHATGPT_TIMEOUT, - server.block_until_done(), - ) - .await - { - Ok(Ok(())) => (true, None), - Ok(Err(err)) => (false, Some(format!("Login server error: {err}"))), - Err(_elapsed) => { - shutdown_handle.shutdown(); - (false, Some("Login timed out".to_string())) - } - }; - - let payload_v2 = AccountLoginCompletedNotification { - login_id: Some(login_id.to_string()), - success, - error: error_msg, - }; - outgoing_clone - .send_server_notification(ServerNotification::AccountLoginCompleted( - payload_v2, - )) - .await; - - if success { - auth_manager.reload(); - config_manager.replace_cloud_requirements_loader( - auth_manager.clone(), - chatgpt_base_url, - ); - config_manager - .sync_default_client_residency_requirement() - .await; - - // Notify clients with the actual current auth mode. - let auth = auth_manager.auth_cached(); - let payload_v2 = AccountUpdatedNotification { - auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), - plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), - }; - outgoing_clone - .send_server_notification(ServerNotification::AccountUpdated( - payload_v2, - )) - .await; - } - - // Clear the active login if it matches this attempt. It may have been replaced or cancelled. - let mut guard = active_login.lock().await; - if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) { - *guard = None; - } - }); - - let response = codex_app_server_protocol::LoginAccountResponse::Chatgpt { - login_id: login_id.to_string(), - auth_url, - }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to start login server: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - }, - Err(err) => { - self.outgoing.send_error(request_id, err).await; + // Replace active login if present. + { + let mut guard = self.active_login.lock().await; + if let Some(existing) = guard.take() { + drop(existing); } + *guard = Some(ActiveLogin::Browser { + shutdown_handle: shutdown_handle.clone(), + login_id, + }); } + + let outgoing_clone = self.outgoing.clone(); + let active_login = self.active_login.clone(); + let auth_manager = self.auth_manager.clone(); + let config_manager = self.config_manager.clone(); + let chatgpt_base_url = self.config.chatgpt_base_url.clone(); + let auth_url = server.auth_url.clone(); + tokio::spawn(async move { + let (success, error_msg) = match tokio::time::timeout( + LOGIN_CHATGPT_TIMEOUT, + server.block_until_done(), + ) + .await + { + Ok(Ok(())) => (true, None), + Ok(Err(err)) => (false, Some(format!("Login server error: {err}"))), + Err(_elapsed) => { + shutdown_handle.shutdown(); + (false, Some("Login timed out".to_string())) + } + }; + + Self::send_chatgpt_login_completion_notifications( + &outgoing_clone, + auth_manager, + config_manager, + chatgpt_base_url, + login_id, + success, + error_msg, + ) + .await; + + // Clear the active login if it matches this attempt. It may have been replaced or cancelled. + let mut guard = active_login.lock().await; + if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) { + *guard = None; + } + }); + + Ok(LoginAccountResponse::Chatgpt { + login_id: login_id.to_string(), + auth_url, + }) } async fn login_chatgpt_device_code_v2(&self, request_id: ConnectionRequestId) { - match self.login_chatgpt_common().await { - Ok(opts) => match request_device_code(&opts).await { - Ok(device_code) => { - let login_id = Uuid::new_v4(); - let cancel = CancellationToken::new(); + let result = self.login_chatgpt_device_code_response().await; + self.outgoing.send_result(request_id, result).await; + } - { - let mut guard = self.active_login.lock().await; - if let Some(existing) = guard.take() { - drop(existing); - } - *guard = Some(ActiveLogin::DeviceCode { - cancel: cancel.clone(), - login_id, - }); - } + async fn login_chatgpt_device_code_response( + &self, + ) -> Result { + let opts = self.login_chatgpt_common().await?; + let device_code = request_device_code(&opts) + .await + .map_err(Self::login_chatgpt_device_code_start_error)?; + let login_id = Uuid::new_v4(); + let cancel = CancellationToken::new(); - let verification_url = device_code.verification_url.clone(); - let user_code = device_code.user_code.clone(); - let response = - codex_app_server_protocol::LoginAccountResponse::ChatgptDeviceCode { - login_id: login_id.to_string(), - verification_url, - user_code, - }; - self.outgoing.send_response(request_id, response).await; - - let outgoing_clone = self.outgoing.clone(); - let active_login = self.active_login.clone(); - let auth_manager = self.auth_manager.clone(); - let config_manager = self.config_manager.clone(); - let chatgpt_base_url = self.config.chatgpt_base_url.clone(); - tokio::spawn(async move { - let (success, error_msg) = tokio::select! { - _ = cancel.cancelled() => { - (false, Some("Login was not completed".to_string())) - } - r = complete_device_code_login(opts, device_code) => { - match r { - Ok(()) => (true, None), - Err(err) => (false, Some(err.to_string())), - } - } - }; - - let payload_v2 = AccountLoginCompletedNotification { - login_id: Some(login_id.to_string()), - success, - error: error_msg, - }; - outgoing_clone - .send_server_notification(ServerNotification::AccountLoginCompleted( - payload_v2, - )) - .await; - - if success { - auth_manager.reload(); - config_manager.replace_cloud_requirements_loader( - auth_manager.clone(), - chatgpt_base_url, - ); - config_manager - .sync_default_client_residency_requirement() - .await; - - let auth = auth_manager.auth_cached(); - let payload_v2 = AccountUpdatedNotification { - auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), - plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), - }; - outgoing_clone - .send_server_notification(ServerNotification::AccountUpdated( - payload_v2, - )) - .await; - } - - let mut guard = active_login.lock().await; - if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) { - *guard = None; - } - }); - } - Err(err) => { - let error = Self::login_chatgpt_device_code_start_error(err); - self.outgoing.send_error(request_id, error).await; - } - }, - Err(err) => { - self.outgoing.send_error(request_id, err).await; + { + let mut guard = self.active_login.lock().await; + if let Some(existing) = guard.take() { + drop(existing); } + *guard = Some(ActiveLogin::DeviceCode { + cancel: cancel.clone(), + login_id, + }); } + + let verification_url = device_code.verification_url.clone(); + let user_code = device_code.user_code.clone(); + + let outgoing_clone = self.outgoing.clone(); + let active_login = self.active_login.clone(); + let auth_manager = self.auth_manager.clone(); + let config_manager = self.config_manager.clone(); + let chatgpt_base_url = self.config.chatgpt_base_url.clone(); + tokio::spawn(async move { + let (success, error_msg) = tokio::select! { + _ = cancel.cancelled() => { + (false, Some("Login was not completed".to_string())) + } + r = complete_device_code_login(opts, device_code) => { + match r { + Ok(()) => (true, None), + Err(err) => (false, Some(err.to_string())), + } + } + }; + + Self::send_chatgpt_login_completion_notifications( + &outgoing_clone, + auth_manager, + config_manager, + chatgpt_base_url, + login_id, + success, + error_msg, + ) + .await; + + let mut guard = active_login.lock().await; + if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) { + *guard = None; + } + }); + + Ok(LoginAccountResponse::ChatgptDeviceCode { + login_id: login_id.to_string(), + verification_url, + user_code, + }) } async fn cancel_login_chatgpt_common( @@ -1670,25 +1602,22 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: CancelLoginAccountParams, ) { + let result = self.cancel_login_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn cancel_login_response( + &self, + params: CancelLoginAccountParams, + ) -> Result { let login_id = params.login_id; - match Uuid::parse_str(&login_id) { - Ok(uuid) => { - let status = match self.cancel_login_chatgpt_common(uuid).await { - Ok(()) => CancelLoginAccountStatus::Canceled, - Err(CancelLoginError::NotFound) => CancelLoginAccountStatus::NotFound, - }; - let response = CancelLoginAccountResponse { status }; - self.outgoing.send_response(request_id, response).await; - } - Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid login id: {login_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } + let uuid = Uuid::parse_str(&login_id) + .map_err(|_| invalid_request(format!("invalid login id: {login_id}")))?; + let status = match self.cancel_login_chatgpt_common(uuid).await { + Ok(()) => CancelLoginAccountStatus::Canceled, + Err(CancelLoginError::NotFound) => CancelLoginAccountStatus::NotFound, + }; + Ok(CancelLoginAccountResponse { status }) } async fn login_chatgpt_auth_tokens( @@ -1698,18 +1627,31 @@ impl CodexMessageProcessor { chatgpt_account_id: String, chatgpt_plan_type: Option, ) { + let result = self + .login_chatgpt_auth_tokens_response(access_token, chatgpt_account_id, chatgpt_plan_type) + .await; + let logged_in = result.is_ok(); + self.outgoing.send_result(request_id, result).await; + + if logged_in { + self.send_login_success_notifications(/*login_id*/ None) + .await; + } + } + + async fn login_chatgpt_auth_tokens_response( + &self, + access_token: String, + chatgpt_account_id: String, + chatgpt_plan_type: Option, + ) -> Result { if matches!( self.config.forced_login_method, Some(ForcedLoginMethod::Api) ) { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "External ChatGPT auth is disabled. Use API key login instead." - .to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request( + "External ChatGPT auth is disabled. Use API key login instead.", + )); } // Cancel any active login attempt to avoid persisting managed auth state. @@ -1723,32 +1665,19 @@ impl CodexMessageProcessor { if let Some(expected_workspace) = self.config.forced_chatgpt_workspace_id.as_deref() && chatgpt_account_id != expected_workspace { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!( - "External auth must use workspace {expected_workspace}, but received {chatgpt_account_id:?}." - ), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request(format!( + "External auth must use workspace {expected_workspace}, but received {chatgpt_account_id:?}." + ))); } - if let Err(err) = login_with_chatgpt_auth_tokens( + login_with_chatgpt_auth_tokens( &self.config.codex_home, &access_token, &chatgpt_account_id, chatgpt_plan_type.as_deref(), - ) { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to set external auth: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - self.auth_manager.reload(); + ) + .map_err(|err| internal_error(format!("failed to set external auth: {err}")))?; + self.auth_manager.reload().await; self.config_manager.replace_cloud_requirements_loader( self.auth_manager.clone(), self.config.chatgpt_base_url.clone(), @@ -1757,12 +1686,12 @@ impl CodexMessageProcessor { .sync_default_client_residency_requirement() .await; - self.outgoing - .send_response(request_id, LoginAccountResponse::ChatgptAuthTokens {}) - .await; + Ok(LoginAccountResponse::ChatgptAuthTokens {}) + } + async fn send_login_success_notifications(&self, login_id: Option) { let payload_login_completed = AccountLoginCompletedNotification { - login_id: None, + login_id: login_id.map(|id| id.to_string()), success: true, error: None, }; @@ -1779,6 +1708,43 @@ impl CodexMessageProcessor { .await; } + async fn send_chatgpt_login_completion_notifications( + outgoing: &OutgoingMessageSender, + auth_manager: Arc, + config_manager: ConfigManager, + chatgpt_base_url: String, + login_id: Uuid, + success: bool, + error_msg: Option, + ) { + let payload_v2 = AccountLoginCompletedNotification { + login_id: Some(login_id.to_string()), + success, + error: error_msg, + }; + outgoing + .send_server_notification(ServerNotification::AccountLoginCompleted(payload_v2)) + .await; + + if success { + auth_manager.reload().await; + config_manager + .replace_cloud_requirements_loader(auth_manager.clone(), chatgpt_base_url); + config_manager + .sync_default_client_residency_requirement() + .await; + + let auth = auth_manager.auth_cached(); + let payload_v2 = AccountUpdatedNotification { + auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), + plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), + }; + outgoing + .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) + .await; + } + } + async fn logout_common(&self) -> std::result::Result, JSONRPCErrorError> { // Cancel any active login attempt. { @@ -1808,23 +1774,24 @@ impl CodexMessageProcessor { } async fn logout_v2(&self, request_id: ConnectionRequestId) { - match self.logout_common().await { - Ok(current_auth_method) => { - self.outgoing - .send_response(request_id, LogoutAccountResponse {}) - .await; - - let payload_v2 = AccountUpdatedNotification { - auth_mode: current_auth_method, + let result = self.logout_common().await; + let account_updated = + result + .as_ref() + .ok() + .cloned() + .map(|auth_mode| AccountUpdatedNotification { + auth_mode, plan_type: None, - }; - self.outgoing - .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } + }); + self.outgoing + .send_result(request_id, result.map(|_| LogoutAccountResponse {})) + .await; + + if let Some(payload) = account_updated { + self.outgoing + .send_server_notification(ServerNotification::AccountUpdated(payload)) + .await; } } @@ -1907,6 +1874,14 @@ impl CodexMessageProcessor { } async fn get_account(&self, request_id: ConnectionRequestId, params: GetAccountParams) { + let result = self.get_account_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn get_account_response( + &self, + params: GetAccountParams, + ) -> Result { let do_refresh = params.refresh_token; self.refresh_token_if_requested(do_refresh).await; @@ -1918,43 +1893,35 @@ impl CodexMessageProcessor { let account_state = match provider.account_state() { Ok(account_state) => account_state, Err(ProviderAccountError::MissingChatgptAccountDetails) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "email and plan type are required for chatgpt authentication" - .to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request( + "email and plan type are required for chatgpt authentication", + )); } }; let account = account_state.account.map(Account::from); - let response = GetAccountResponse { + Ok(GetAccountResponse { account, requires_openai_auth: account_state.requires_openai_auth, - }; - self.outgoing.send_response(request_id, response).await; + }) } async fn get_account_rate_limits(&self, request_id: ConnectionRequestId) { - match self.fetch_account_rate_limits().await { - Ok((rate_limits, rate_limits_by_limit_id)) => { - let response = GetAccountRateLimitsResponse { - rate_limits: rate_limits.into(), - rate_limits_by_limit_id: Some( - rate_limits_by_limit_id - .into_iter() - .map(|(limit_id, snapshot)| (limit_id, snapshot.into())) - .collect(), - ), - }; - self.outgoing.send_response(request_id, response).await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } + let result = + self.fetch_account_rate_limits() + .await + .map( + |(rate_limits, rate_limits_by_limit_id)| GetAccountRateLimitsResponse { + rate_limits: rate_limits.into(), + rate_limits_by_limit_id: Some( + rate_limits_by_limit_id + .into_iter() + .map(|(limit_id, snapshot)| (limit_id, snapshot.into())) + .collect(), + ), + }, + ); + self.outgoing.send_result(request_id, result).await; } async fn send_add_credits_nudge_email( @@ -1962,16 +1929,11 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: SendAddCreditsNudgeEmailParams, ) { - match self.send_add_credits_nudge_email_inner(params).await { - Ok(status) => { - self.outgoing - .send_response(request_id, SendAddCreditsNudgeEmailResponse { status }) - .await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } + let result = self + .send_add_credits_nudge_email_inner(params) + .await + .map(|status| SendAddCreditsNudgeEmailResponse { status }); + self.outgoing.send_result(request_id, result).await; } async fn send_add_credits_nudge_email_inner( @@ -2099,18 +2061,24 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: CommandExecParams, ) { + let result = self + .exec_one_off_command_inner(request_id.clone(), params) + .await + .map(|()| None::); + self.send_optional_result(request_id, result).await; + } + + async fn exec_one_off_command_inner( + &self, + request_id: ConnectionRequestId, + params: CommandExecParams, + ) -> Result<(), JSONRPCErrorError> { tracing::debug!("ExecOneOffCommand params: {params:?}"); let request = request_id.clone(); if params.command.is_empty() { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "command must not be empty".to_string(), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; + return Err(invalid_request("command must not be empty")); } let CommandExecParams { @@ -2130,43 +2098,25 @@ impl CodexMessageProcessor { permission_profile, } = params; if sandbox_policy.is_some() && permission_profile.is_some() { - self.send_invalid_request_error( - request_id, - "`permissionProfile` cannot be combined with `sandboxPolicy`".to_string(), - ) - .await; - return; + return Err(invalid_request( + "`permissionProfile` cannot be combined with `sandboxPolicy`", + )); } if size.is_some() && !tty { - let error = JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message: "command/exec size requires tty: true".to_string(), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; + return Err(invalid_params("command/exec size requires tty: true")); } if disable_output_cap && output_bytes_cap.is_some() { - let error = JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message: "command/exec cannot set both outputBytesCap and disableOutputCap" - .to_string(), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; + return Err(invalid_params( + "command/exec cannot set both outputBytesCap and disableOutputCap", + )); } if disable_timeout && timeout_ms.is_some() { - let error = JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message: "command/exec cannot set both timeoutMs and disableTimeout".to_string(), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; + return Err(invalid_params( + "command/exec cannot set both timeoutMs and disableTimeout", + )); } let cwd = cwd.map_or_else(|| self.config.cwd.clone(), |cwd| self.config.cwd.join(cwd)); @@ -2190,15 +2140,9 @@ impl CodexMessageProcessor { Some(timeout_ms) => match u64::try_from(timeout_ms) { Ok(timeout_ms) => Some(timeout_ms), Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message: format!( - "command/exec timeoutMs must be non-negative, got {timeout_ms}" - ), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; + return Err(invalid_params(format!( + "command/exec timeoutMs must be non-negative, got {timeout_ms}" + ))); } }, None => None, @@ -2218,13 +2162,9 @@ impl CodexMessageProcessor { { Ok(started) => Some(started), Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to start managed network proxy: {err}"), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; + return Err(internal_error(format!( + "failed to start managed network proxy: {err}" + ))); } }, None => None, @@ -2289,68 +2229,33 @@ impl CodexMessageProcessor { &file_system_sandbox_policy, network_sandbox_policy, ); - match self - .config + self.config .permissions .permission_profile .can_set(&effective_permission_profile) - { - Ok(()) => effective_permission_profile, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid permission profile: {err}"), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; - } - } + .map_err(|err| invalid_request(format!("invalid permission profile: {err}")))?; + effective_permission_profile } else if let Some(policy) = sandbox_policy.map(|policy| policy.to_core()) { - match self - .config + self.config .permissions .can_set_legacy_sandbox_policy(&policy, &sandbox_cwd) - { - Ok(()) => { - let file_system_sandbox_policy = - codex_protocol::permissions::FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd(&policy, &sandbox_cwd); - let network_sandbox_policy = - codex_protocol::permissions::NetworkSandboxPolicy::from(&policy); - let permission_profile = - codex_protocol::models::PermissionProfile::from_runtime_permissions_with_enforcement( - codex_protocol::models::SandboxEnforcement::from_legacy_sandbox_policy( - &policy, - ), - &file_system_sandbox_policy, - network_sandbox_policy, - ); - if let Err(err) = self - .config - .permissions - .permission_profile - .can_set(&permission_profile) - { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid sandbox policy: {err}"), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; - } - permission_profile - } - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid sandbox policy: {err}"), - data: None, - }; - self.outgoing.send_error(request, error).await; - return; - } - } + .map_err(|err| invalid_request(format!("invalid sandbox policy: {err}")))?; + let file_system_sandbox_policy = + codex_protocol::permissions::FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd(&policy, &sandbox_cwd); + let network_sandbox_policy = + codex_protocol::permissions::NetworkSandboxPolicy::from(&policy); + let permission_profile = + codex_protocol::models::PermissionProfile::from_runtime_permissions_with_enforcement( + codex_protocol::models::SandboxEnforcement::from_legacy_sandbox_policy(&policy), + &file_system_sandbox_policy, + network_sandbox_policy, + ); + self.config + .permissions + .permission_profile + .can_set(&permission_profile) + .map_err(|err| invalid_request(format!("invalid sandbox policy: {err}")))?; + permission_profile } else { self.config.permissions.permission_profile() }; @@ -2362,49 +2267,32 @@ impl CodexMessageProcessor { let use_legacy_landlock = self.config.features.use_legacy_landlock(); let size = match size.map(crate::command_exec::terminal_size_from_protocol) { Some(Ok(size)) => Some(size), - Some(Err(error)) => { - self.outgoing.send_error(request, error).await; - return; - } + Some(Err(error)) => return Err(error), None => None, }; - match codex_core::exec::build_exec_request( + let exec_request = codex_core::exec::build_exec_request( exec_params, &effective_permission_profile, &sandbox_cwd, &codex_linux_sandbox_exe, use_legacy_landlock, - ) { - Ok(exec_request) => { - if let Err(error) = self - .command_exec_manager - .start(StartCommandExecParams { - outgoing, - request_id: request_for_task, - process_id, - exec_request, - started_network_proxy: started_network_proxy_for_task, - tty, - stream_stdin, - stream_stdout_stderr, - output_bytes_cap, - size, - }) - .await - { - self.outgoing.send_error(request, error).await; - } - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("exec failed: {err}"), - data: None, - }; - self.outgoing.send_error(request, error).await; - } - } + ) + .map_err(|err| internal_error(format!("exec failed: {err}")))?; + self.command_exec_manager + .start(StartCommandExecParams { + outgoing, + request_id: request_for_task, + process_id, + exec_request, + started_network_proxy: started_network_proxy_for_task, + tty, + stream_stdin, + stream_stdout_stderr, + output_bytes_cap, + size, + }) + .await } fn preserve_configured_deny_read_restrictions( @@ -2420,14 +2308,11 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: CommandExecWriteParams, ) { - match self + let result = self .command_exec_manager .write(request_id.clone(), params) - .await - { - Ok(response) => self.outgoing.send_response(request_id, response).await, - Err(error) => self.outgoing.send_error(request_id, error).await, - } + .await; + self.outgoing.send_result(request_id, result).await; } async fn command_exec_resize( @@ -2435,14 +2320,11 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: CommandExecResizeParams, ) { - match self + let result = self .command_exec_manager .resize(request_id.clone(), params) - .await - { - Ok(response) => self.outgoing.send_response(request_id, response).await, - Err(error) => self.outgoing.send_error(request_id, error).await, - } + .await; + self.outgoing.send_result(request_id, result).await; } async fn command_exec_terminate( @@ -2450,14 +2332,11 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: CommandExecTerminateParams, ) { - match self + let result = self .command_exec_manager .terminate(request_id.clone(), params) - .await - { - Ok(response) => self.outgoing.send_response(request_id, response).await, - Err(error) => self.outgoing.send_error(request_id, error).await, - } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_start( @@ -2491,11 +2370,12 @@ impl CodexMessageProcessor { persist_extended_history, } = params; if sandbox.is_some() && permission_profile.is_some() { - self.send_invalid_request_error( - request_id, - "`permissionProfile` cannot be combined with `sandbox`".to_string(), - ) - .await; + self.outgoing + .send_error( + request_id, + invalid_request("`permissionProfile` cannot be combined with `sandbox`"), + ) + .await; return; } let environments = environments.map(|environments| { @@ -2512,7 +2392,11 @@ impl CodexMessageProcessor { .thread_manager .validate_environment_selections(environments) { - self.send_invalid_request_error(request_id, environment_selection_error_message(err)) + self.outgoing + .send_error( + request_id, + invalid_request(environment_selection_error_message(err)), + ) .await; return; } @@ -2531,12 +2415,12 @@ impl CodexMessageProcessor { ); typesafe_overrides.ephemeral = ephemeral; let listener_task_context = ListenerTaskContext { + auth_manager: Arc::clone(&self.auth_manager), thread_manager: Arc::clone(&self.thread_manager), thread_state_manager: self.thread_state_manager.clone(), outgoing: Arc::clone(&self.outgoing), pending_thread_unloads: Arc::clone(&self.pending_thread_unloads), analytics_events_client: self.analytics_events_client.clone(), - general_analytics_enabled: self.config.features.enabled(Feature::GeneralAnalytics), thread_watch_manager: self.thread_watch_manager.clone(), fallback_model_provider: self.config.model_provider_id.clone(), codex_home: self.config.codex_home.to_path_buf(), @@ -2635,257 +2519,246 @@ impl CodexMessageProcessor { experimental_raw_events: bool, request_trace: Option, ) { - let requested_cwd = typesafe_overrides.cwd.clone(); - let mut config = match config_manager - .load_with_overrides(config_overrides.clone(), typesafe_overrides.clone()) - .await - { - Ok(config) => config, - Err(err) => { - let error = config_load_error(&err); - listener_task_context - .outgoing - .send_error(request_id, error) - .await; - return; - } - }; - - // The user may have requested WorkspaceWrite or DangerFullAccess via - // the command line, though in the process of deriving the Config, it - // could be downgraded to ReadOnly (perhaps there is no sandbox - // available on Windows or the enterprise config disallows it). The cwd - // should still be considered "trusted" in this case. - let requested_permissions_trust_project = - requested_permissions_trust_project(&typesafe_overrides, config.cwd.as_path()); - let effective_permissions_trust_project = permission_profile_trusts_project( - &config.permissions.permission_profile(), - config.cwd.as_path(), - ); - - if requested_cwd.is_some() - && config.active_project.trust_level.is_none() - && (requested_permissions_trust_project || effective_permissions_trust_project) - { - let trust_target = resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &config.cwd) + let result = async { + let requested_cwd = typesafe_overrides.cwd.clone(); + let mut config = config_manager + .load_with_overrides(config_overrides.clone(), typesafe_overrides.clone()) .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( - &listener_task_context.codex_home, - trust_target.as_path(), - TrustLevel::Trusted, - ) { - warn!( - "failed to persist trusted project state for {}; continuing with in-memory trust for this thread: {err}", - trust_target.display() - ); - let mut project = toml::map::Map::new(); - project.insert( - "trust_level".to_string(), - TomlValue::String("trusted".to_string()), - ); - let mut projects = toml::map::Map::new(); - projects.insert( - project_trust_key(trust_target.as_path()), - TomlValue::Table(project), - ); - cli_overrides_with_trust = current_cli_overrides - .iter() - .cloned() - .chain(std::iter::once(( - "projects".to_string(), - TomlValue::Table(projects), - ))) - .collect::>(); - cli_overrides_with_trust.as_slice() - } else { - current_cli_overrides.as_slice() - }; + .map_err(|err| config_load_error(&err))?; - config = match config_manager - .load_with_cli_overrides( - cli_overrides_for_reload, - config_overrides, - typesafe_overrides, - /*fallback_cwd*/ None, - ) - .await + // The user may have requested WorkspaceWrite or DangerFullAccess via + // the command line, though in the process of deriving the Config, it + // could be downgraded to ReadOnly (perhaps there is no sandbox + // available on Windows or the enterprise config disallows it). The cwd + // should still be considered "trusted" in this case. + let requested_permissions_trust_project = + requested_permissions_trust_project(&typesafe_overrides, config.cwd.as_path()); + let effective_permissions_trust_project = permission_profile_trusts_project( + &config.permissions.permission_profile(), + config.cwd.as_path(), + ); + + if requested_cwd.is_some() + && config.active_project.trust_level.is_none() + && (requested_permissions_trust_project || effective_permissions_trust_project) { - Ok(config) => config, - Err(err) => { - let error = config_load_error(&err); - listener_task_context - .outgoing - .send_error(request_id, error) - .await; - return; - } - }; - } + 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( + &listener_task_context.codex_home, + trust_target.as_path(), + TrustLevel::Trusted, + ) { + warn!( + "failed to persist trusted project state for {}; continuing with in-memory trust for this thread: {err}", + trust_target.display() + ); + let mut project = toml::map::Map::new(); + project.insert( + "trust_level".to_string(), + TomlValue::String("trusted".to_string()), + ); + let mut projects = toml::map::Map::new(); + projects.insert( + project_trust_key(trust_target.as_path()), + TomlValue::Table(project), + ); + cli_overrides_with_trust = current_cli_overrides + .iter() + .cloned() + .chain(std::iter::once(( + "projects".to_string(), + TomlValue::Table(projects), + ))) + .collect::>(); + cli_overrides_with_trust.as_slice() + } else { + current_cli_overrides.as_slice() + }; - let instruction_sources = Self::instruction_sources_from_config(&config).await; - let environments = environments.unwrap_or_else(|| { - listener_task_context - .thread_manager - .default_environment_selections(&config.cwd) - }); - let dynamic_tools = dynamic_tools.unwrap_or_default(); - let core_dynamic_tools = if dynamic_tools.is_empty() { - Vec::new() - } else { - if let Err(message) = validate_dynamic_tools(&dynamic_tools) { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message, - data: None, - }; - listener_task_context - .outgoing - .send_error(request_id, error) - .await; - return; - } - dynamic_tools - .into_iter() - .map(|tool| CoreDynamicToolSpec { - namespace: tool.namespace, - name: tool.name, - description: tool.description, - input_schema: tool.input_schema, - defer_loading: tool.defer_loading, - }) - .collect() - }; - let core_dynamic_tool_count = core_dynamic_tools.len(); - - match listener_task_context - .thread_manager - .start_thread_with_tools_and_service_name(StartThreadWithToolsOptions { - config, - initial_history: match session_start_source - .unwrap_or(codex_app_server_protocol::ThreadStartSource::Startup) - { - codex_app_server_protocol::ThreadStartSource::Startup => InitialHistory::New, - codex_app_server_protocol::ThreadStartSource::Clear => InitialHistory::Cleared, - }, - dynamic_tools: core_dynamic_tools, - persist_extended_history, - metrics_service_name: service_name, - parent_trace: request_trace, - environments, - }) - .instrument(tracing::info_span!( - "app_server.thread_start.create_thread", - otel.name = "app_server.thread_start.create_thread", - thread_start.dynamic_tool_count = core_dynamic_tool_count, - thread_start.persist_extended_history = persist_extended_history, - )) - .await - { - Ok(new_conv) => { - let NewThread { - thread_id, - thread, - session_configured, - .. - } = new_conv; - if let Err(error) = Self::set_app_server_client_info( - thread.as_ref(), - app_server_client_name, - app_server_client_version, - ) - .await - { - listener_task_context - .outgoing - .send_error(request_id, error) - .await; - return; - } - let config_snapshot = thread - .config_snapshot() - .instrument(tracing::info_span!( - "app_server.thread_start.config_snapshot", - otel.name = "app_server.thread_start.config_snapshot", - )) - .await; - let mut thread = build_thread_from_snapshot( - thread_id, - &config_snapshot, - session_configured.rollout_path.clone(), - ); - - // Auto-attach a thread listener when starting a thread. - Self::log_listener_attach_result( - Self::ensure_conversation_listener_task( - listener_task_context.clone(), - thread_id, - request_id.connection_id, - experimental_raw_events, - ApiVersion::V2, + config = config_manager + .load_with_cli_overrides( + cli_overrides_for_reload, + config_overrides, + typesafe_overrides, + /*fallback_cwd*/ None, ) - .instrument(tracing::info_span!( - "app_server.thread_start.attach_listener", - otel.name = "app_server.thread_start.attach_listener", - thread_start.experimental_raw_events = experimental_raw_events, - )) - .await, + .await + .map_err(|err| config_load_error(&err))?; + } + + let instruction_sources = Self::instruction_sources_from_config(&config).await; + let environments = environments.unwrap_or_else(|| { + listener_task_context + .thread_manager + .default_environment_selections(&config.cwd) + }); + let dynamic_tools = dynamic_tools.unwrap_or_default(); + let core_dynamic_tools = if dynamic_tools.is_empty() { + Vec::new() + } else { + validate_dynamic_tools(&dynamic_tools).map_err(invalid_request)?; + dynamic_tools + .into_iter() + .map(|tool| CoreDynamicToolSpec { + namespace: tool.namespace, + name: tool.name, + description: tool.description, + input_schema: tool.input_schema, + defer_loading: tool.defer_loading, + }) + .collect() + }; + let core_dynamic_tool_count = core_dynamic_tools.len(); + let memory_config = Arc::new(config.clone()); + + let NewThread { + thread_id, + thread, + session_configured, + .. + } = listener_task_context + .thread_manager + .start_thread_with_options(StartThreadOptions { + config, + initial_history: match session_start_source + .unwrap_or(codex_app_server_protocol::ThreadStartSource::Startup) + { + codex_app_server_protocol::ThreadStartSource::Startup => { + InitialHistory::New + } + codex_app_server_protocol::ThreadStartSource::Clear => { + InitialHistory::Cleared + } + }, + session_source: None, + dynamic_tools: core_dynamic_tools, + persist_extended_history, + metrics_service_name: service_name, + parent_trace: request_trace, + environments, + }) + .instrument(tracing::info_span!( + "app_server.thread_start.create_thread", + otel.name = "app_server.thread_start.create_thread", + thread_start.dynamic_tool_count = core_dynamic_tool_count, + thread_start.persist_extended_history = persist_extended_history, + )) + .await + .map_err(|err| match err { + CodexErr::InvalidRequest(message) => invalid_request(message), + err => internal_error(format!("error creating thread: {err}")), + })?; + + Self::set_app_server_client_info( + thread.as_ref(), + app_server_client_name, + app_server_client_version, + ) + .await?; + + let config_snapshot = thread + .config_snapshot() + .instrument(tracing::info_span!( + "app_server.thread_start.config_snapshot", + otel.name = "app_server.thread_start.config_snapshot", + )) + .await; + codex_memories_write::start_memories_startup_task( + Arc::clone(&listener_task_context.thread_manager), + Arc::clone(&listener_task_context.auth_manager), + thread_id, + Arc::clone(&thread), + Arc::clone(&memory_config), + &config_snapshot.session_source, + ); + let mut thread = build_thread_from_snapshot( + thread_id, + &config_snapshot, + session_configured.rollout_path.clone(), + ); + + // Auto-attach a thread listener when starting a thread. + Self::log_listener_attach_result( + Self::ensure_conversation_listener_task( + listener_task_context.clone(), thread_id, request_id.connection_id, - "thread", - ); + experimental_raw_events, + ApiVersion::V2, + ) + .instrument(tracing::info_span!( + "app_server.thread_start.attach_listener", + otel.name = "app_server.thread_start.attach_listener", + thread_start.experimental_raw_events = experimental_raw_events, + )) + .await, + thread_id, + request_id.connection_id, + "thread", + ); + listener_task_context + .thread_watch_manager + .upsert_thread_silently(thread.clone()) + .instrument(tracing::info_span!( + "app_server.thread_start.upsert_thread", + otel.name = "app_server.thread_start.upsert_thread", + )) + .await; + + thread.status = resolve_thread_status( listener_task_context .thread_watch_manager - .upsert_thread_silently(thread.clone()) + .loaded_status_for_thread(&thread.id) .instrument(tracing::info_span!( - "app_server.thread_start.upsert_thread", - otel.name = "app_server.thread_start.upsert_thread", + "app_server.thread_start.resolve_status", + otel.name = "app_server.thread_start.resolve_status", )) - .await; + .await, + /*has_in_progress_turn*/ false, + ); - thread.status = resolve_thread_status( - listener_task_context - .thread_watch_manager - .loaded_status_for_thread(&thread.id) - .instrument(tracing::info_span!( - "app_server.thread_start.resolve_status", - otel.name = "app_server.thread_start.resolve_status", - )) - .await, - /*has_in_progress_turn*/ false, - ); + let sandbox = thread_response_sandbox_policy( + &config_snapshot.permission_profile, + config_snapshot.cwd.as_path(), + ); + let permission_profile = + thread_response_permission_profile(config_snapshot.permission_profile); - let permission_profile = - thread_response_permission_profile(config_snapshot.permission_profile); + let response = ThreadStartResponse { + thread: thread.clone(), + model: config_snapshot.model, + model_provider: config_snapshot.model_provider_id, + service_tier: config_snapshot.service_tier, + cwd: config_snapshot.cwd, + instruction_sources, + approval_policy: config_snapshot.approval_policy.into(), + approvals_reviewer: config_snapshot.approvals_reviewer.into(), + sandbox, + permission_profile, + reasoning_effort: config_snapshot.reasoning_effort, + }; + Ok::<_, JSONRPCErrorError>((response, thread_started_notification(thread))) + } + .await; - let response = ThreadStartResponse { - thread: thread.clone(), - model: config_snapshot.model, - model_provider: config_snapshot.model_provider_id, - service_tier: config_snapshot.service_tier, - cwd: config_snapshot.cwd, - instruction_sources, - approval_policy: config_snapshot.approval_policy.into(), - approvals_reviewer: config_snapshot.approvals_reviewer.into(), - sandbox: config_snapshot.sandbox_policy.into(), - permission_profile, - reasoning_effort: config_snapshot.reasoning_effort, - }; - if listener_task_context.general_analytics_enabled { - listener_task_context - .analytics_events_client - .track_response( - request_id.connection_id.0, - ClientResponse::ThreadStart { - request_id: request_id.request_id.clone(), - response: response.clone(), - }, - ); - } + match result { + Ok((response, notif)) => { + listener_task_context + .analytics_events_client + .track_response( + request_id.connection_id.0, + ClientResponse::ThreadStart { + request_id: request_id.request_id.clone(), + response: response.clone(), + }, + ); listener_task_context .outgoing @@ -2896,7 +2769,6 @@ impl CodexMessageProcessor { )) .await; - let notif = thread_started_notification(thread); listener_task_context .outgoing .send_server_notification(ServerNotification::ThreadStarted(notif)) @@ -2906,23 +2778,7 @@ impl CodexMessageProcessor { )) .await; } - Err(CodexErr::InvalidRequest(message)) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message, - data: None, - }; - listener_task_context - .outgoing - .send_error(request_id, error) - .await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("error creating thread: {err}"), - data: None, - }; + Err(error) => { listener_task_context .outgoing .send_error(request_id, error) @@ -2967,39 +2823,42 @@ impl CodexMessageProcessor { } async fn thread_archive(&self, request_id: ConnectionRequestId, params: ThreadArchiveParams) { - let thread_id = match ThreadId::from_string(¶ms.thread_id) { - Ok(id) => id, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid thread id: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + let result = self.thread_archive_response(params).await; + let archived_thread_ids = result + .as_ref() + .ok() + .map(|(_, thread_ids)| thread_ids.clone()); + self.outgoing + .send_result(request_id, result.map(|(response, _)| response)) + .await; + + if let Some(archived_thread_ids) = archived_thread_ids { + for thread_id in archived_thread_ids { + let notification = ThreadArchivedNotification { thread_id }; + self.outgoing + .send_server_notification(ServerNotification::ThreadArchived(notification)) + .await; } - }; + } + } + + async fn thread_archive_response( + &self, + params: ThreadArchiveParams, + ) -> Result<(ThreadArchiveResponse, Vec), JSONRPCErrorError> { + let thread_id = ThreadId::from_string(¶ms.thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; let mut thread_ids = vec![thread_id]; if let Some(state_db_ctx) = get_state_db(&self.config).await { - let descendants = match state_db_ctx.list_thread_spawn_descendants(thread_id).await { - Ok(descendants) => descendants, - Err(err) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to list spawned descendants for thread id {thread_id}: {err}" - ), - data: None, - }, - ) - .await; - return; - } - }; + let descendants = state_db_ctx + .list_thread_spawn_descendants(thread_id) + .await + .map_err(|err| { + internal_error(format!( + "failed to list spawned descendants for thread id {thread_id}: {err}" + )) + })?; let mut seen = HashSet::from([thread_id]); for descendant_id in descendants { if seen.insert(descendant_id) { @@ -3023,12 +2882,7 @@ impl CodexMessageProcessor { archive_thread_ids.push(thread_id); } } - Err(err) => { - self.outgoing - .send_error(request_id, thread_store_archive_error("archive", err)) - .await; - return; - } + Err(err) => return Err(thread_store_archive_error("archive", err)), } for descendant_thread_id in thread_ids.into_iter().skip(1) { match self @@ -3056,10 +2910,7 @@ impl CodexMessageProcessor { let mut archived_thread_ids = Vec::new(); let Some((parent_thread_id, descendant_thread_ids)) = archive_thread_ids.split_first() else { - self.outgoing - .send_response(request_id, ThreadArchiveResponse {}) - .await; - return; + return Ok((ThreadArchiveResponse {}, archived_thread_ids)); }; self.prepare_thread_for_archive(*parent_thread_id).await; @@ -3073,12 +2924,7 @@ impl CodexMessageProcessor { Ok(()) => { archived_thread_ids.push(parent_thread_id.to_string()); } - Err(err) => { - self.outgoing - .send_error(request_id, thread_store_archive_error("archive", err)) - .await; - return; - } + Err(err) => return Err(thread_store_archive_error("archive", err)), } for descendant_thread_id in descendant_thread_ids.iter().rev().copied() { @@ -3101,15 +2947,7 @@ impl CodexMessageProcessor { } } - self.outgoing - .send_response(request_id, ThreadArchiveResponse {}) - .await; - for thread_id in archived_thread_ids { - let notification = ThreadArchivedNotification { thread_id }; - self.outgoing - .send_server_notification(ServerNotification::ThreadArchived(notification)) - .await; - } + Ok((ThreadArchiveResponse {}, archived_thread_ids)) } async fn thread_increment_elicitation( @@ -3117,34 +2955,23 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadIncrementElicitationParams, ) { - let (_, thread) = match self.load_thread(¶ms.thread_id).await { - Ok(value) => value, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - match thread.increment_out_of_band_elicitation_count().await { - Ok(count) => { - self.outgoing - .send_response( - request_id, - ThreadIncrementElicitationResponse { - count, - paused: count > 0, - }, - ) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to increment out-of-band elicitation counter: {err}"), - ) - .await; - } + let result = async { + let (_, thread) = self.load_thread(¶ms.thread_id).await?; + let count = thread + .increment_out_of_band_elicitation_count() + .await + .map_err(|err| { + internal_error(format!( + "failed to increment out-of-band elicitation counter: {err}" + )) + })?; + Ok::<_, JSONRPCErrorError>(ThreadIncrementElicitationResponse { + count, + paused: count > 0, + }) } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_decrement_elicitation( @@ -3152,76 +2979,64 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadDecrementElicitationParams, ) { - let (_, thread) = match self.load_thread(¶ms.thread_id).await { - Ok(value) => value, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - match thread.decrement_out_of_band_elicitation_count().await { - Ok(count) => { - self.outgoing - .send_response( - request_id, - ThreadDecrementElicitationResponse { - count, - paused: count > 0, - }, - ) - .await; - } - Err(CodexErr::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to decrement out-of-band elicitation counter: {err}"), - ) - .await; - } + let result = async { + let (_, thread) = self.load_thread(¶ms.thread_id).await?; + let count = thread + .decrement_out_of_band_elicitation_count() + .await + .map_err(|err| match err { + CodexErr::InvalidRequest(message) => invalid_request(message), + err => internal_error(format!( + "failed to decrement out-of-band elicitation counter: {err}" + )), + })?; + Ok::<_, JSONRPCErrorError>(ThreadDecrementElicitationResponse { + count, + paused: count > 0, + }) } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_set_name(&self, request_id: ConnectionRequestId, params: ThreadSetNameParams) { - let ThreadSetNameParams { thread_id, name } = params; - let thread_id = match ThreadId::from_string(&thread_id) { - Ok(id) => id, - Err(err) => { - self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) - .await; - return; - } - }; - let Some(name) = codex_core::util::normalize_thread_name(&name) else { - self.send_invalid_request_error( - request_id, - "thread name must not be empty".to_string(), - ) + let result = self.thread_set_name_response(&request_id, params).await; + let notification = result + .as_ref() + .ok() + .and_then(|(_, notification)| notification.clone()); + self.outgoing + .send_result(request_id, result.map(|(response, _)| response)) .await; - return; + + if let Some(notification) = notification { + self.outgoing + .send_server_notification(ServerNotification::ThreadNameUpdated(notification)) + .await; + } + } + + async fn thread_set_name_response( + &self, + request_id: &ConnectionRequestId, + params: ThreadSetNameParams, + ) -> Result<(ThreadSetNameResponse, Option), JSONRPCErrorError> + { + let ThreadSetNameParams { thread_id, name } = params; + let thread_id = ThreadId::from_string(&thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; + let Some(name) = codex_core::util::normalize_thread_name(&name) else { + return Err(invalid_request("thread name must not be empty")); }; if let Ok(thread) = self.thread_manager.get_thread(thread_id).await { - if let Err(err) = self - .submit_core_op(&request_id, thread.as_ref(), Op::SetThreadName { name }) + self.submit_core_op(request_id, thread.as_ref(), Op::SetThreadName { name }) .await - { - self.send_internal_error(request_id, format!("failed to set thread name: {err}")) - .await; - return; - } - - self.outgoing - .send_response(request_id, ThreadSetNameResponse {}) - .await; - return; + .map_err(|err| internal_error(format!("failed to set thread name: {err}")))?; + return Ok((ThreadSetNameResponse {}, None)); } - if let Err(err) = self - .thread_store + self.thread_store .update_thread_metadata(StoreUpdateThreadMetadataParams { thread_id, patch: StoreThreadMetadataPatch { @@ -3231,23 +3046,15 @@ impl CodexMessageProcessor { include_archived: false, }) .await - { - self.outgoing - .send_error(request_id, thread_store_write_error("set thread name", err)) - .await; - return; - } + .map_err(|err| thread_store_write_error("set thread name", err))?; - self.outgoing - .send_response(request_id, ThreadSetNameResponse {}) - .await; - let notification = ThreadNameUpdatedNotification { - thread_id: thread_id.to_string(), - thread_name: Some(name), - }; - self.outgoing - .send_server_notification(ServerNotification::ThreadNameUpdated(notification)) - .await; + Ok(( + ThreadSetNameResponse {}, + Some(ThreadNameUpdatedNotification { + thread_id: thread_id.to_string(), + thread_name: Some(name), + }), + )) } async fn thread_memory_mode_set( @@ -3255,43 +3062,35 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadMemoryModeSetParams, ) { + let result = self.thread_memory_mode_set_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_memory_mode_set_response( + &self, + params: ThreadMemoryModeSetParams, + ) -> Result { let ThreadMemoryModeSetParams { thread_id, mode } = params; - let thread_id = match ThreadId::from_string(&thread_id) { - Ok(id) => id, - Err(err) => { - self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) - .await; - return; - } - }; + let thread_id = ThreadId::from_string(&thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; if let Ok(thread) = self.thread_manager.get_thread(thread_id).await { if thread.config_snapshot().await.ephemeral { - self.send_invalid_request_error( - request_id, - format!("ephemeral thread does not support memory mode updates: {thread_id}"), - ) - .await; - return; + return Err(invalid_request(format!( + "ephemeral thread does not support memory mode updates: {thread_id}" + ))); } - if let Err(err) = thread.set_thread_memory_mode(mode.to_core()).await { - self.send_internal_error( - request_id, - format!("failed to set thread memory mode: {err}"), - ) - .await; - return; - } - - self.outgoing - .send_response(request_id, ThreadMemoryModeSetResponse {}) - .await; - return; + thread + .set_thread_memory_mode(mode.to_core()) + .await + .map_err(|err| { + internal_error(format!("failed to set thread memory mode: {err}")) + })?; + return Ok(ThreadMemoryModeSetResponse {}); } - if let Err(err) = self - .thread_store + self.thread_store .update_thread_metadata(StoreUpdateThreadMetadataParams { thread_id, patch: StoreThreadMetadataPatch { @@ -3301,63 +3100,40 @@ impl CodexMessageProcessor { include_archived: false, }) .await - { - self.outgoing - .send_error( - request_id, - thread_store_write_error("set thread memory mode", err), - ) - .await; - return; - } + .map_err(|err| thread_store_write_error("set thread memory mode", err))?; - self.outgoing - .send_response(request_id, ThreadMemoryModeSetResponse {}) - .await; + Ok(ThreadMemoryModeSetResponse {}) } async fn memory_reset(&self, request_id: ConnectionRequestId, _params: Option<()>) { - let state_db = match StateRuntime::init( + let result = self.memory_reset_response().await; + self.outgoing.send_result(request_id, result).await; + } + + async fn memory_reset_response(&self) -> Result { + let state_db = StateRuntime::init( self.config.sqlite_home.clone(), self.config.model_provider_id.clone(), ) .await - { - Ok(state_db) => state_db, - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to open state db for memory reset: {err}"), - ) - .await; - return; - } - }; + .map_err(|err| { + internal_error(format!("failed to open state db for memory reset: {err}")) + })?; - if let Err(err) = state_db.clear_memory_data().await { - self.send_internal_error( - request_id, - format!("failed to clear memory rows in state db: {err}"), - ) - .await; - return; - } + state_db.clear_memory_data().await.map_err(|err| { + internal_error(format!("failed to clear memory rows in state db: {err}")) + })?; - if let Err(err) = clear_memory_roots_contents(&self.config.codex_home).await { - self.send_internal_error( - request_id, - format!( + clear_memory_roots_contents(&self.config.codex_home) + .await + .map_err(|err| { + internal_error(format!( "failed to clear memory directories under {}: {err}", self.config.codex_home.display() - ), - ) - .await; - return; - } + )) + })?; - self.outgoing - .send_response(request_id, MemoryResetResponse {}) - .await; + Ok(MemoryResetResponse {}) } async fn thread_metadata_update( @@ -3365,19 +3141,21 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadMetadataUpdateParams, ) { + let result = self.thread_metadata_update_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_metadata_update_response( + &self, + params: ThreadMetadataUpdateParams, + ) -> Result { let ThreadMetadataUpdateParams { thread_id, git_info, } = params; - let thread_uuid = match ThreadId::from_string(&thread_id) { - Ok(id) => id, - Err(err) => { - self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) - .await; - return; - } - }; + let thread_uuid = ThreadId::from_string(&thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; let Some(ThreadMetadataGitInfoUpdateParams { sha, @@ -3385,21 +3163,11 @@ impl CodexMessageProcessor { origin_url, }) = git_info else { - self.send_invalid_request_error( - request_id, - "gitInfo must include at least one field".to_string(), - ) - .await; - return; + return Err(invalid_request("gitInfo must include at least one field")); }; if sha.is_none() && branch.is_none() && origin_url.is_none() { - self.send_invalid_request_error( - request_id, - "gitInfo must include at least one field".to_string(), - ) - .await; - return; + return Err(invalid_request("gitInfo must include at least one field")); } let loaded_thread = self.thread_manager.get_thread(thread_uuid).await.ok(); @@ -3408,72 +3176,20 @@ impl CodexMessageProcessor { state_db_ctx = get_state_db(&self.config).await; } let Some(state_db_ctx) = state_db_ctx else { - self.send_internal_error( - request_id, - format!("sqlite state db unavailable for thread {thread_uuid}"), - ) - .await; - return; + return Err(internal_error(format!( + "sqlite state db unavailable for thread {thread_uuid}" + ))); }; - if let Err(error) = self - .ensure_thread_metadata_row_exists(thread_uuid, &state_db_ctx, loaded_thread.as_ref()) - .await - { - self.outgoing.send_error(request_id, error).await; - return; - } + self.ensure_thread_metadata_row_exists(thread_uuid, &state_db_ctx, loaded_thread.as_ref()) + .await?; - let git_sha = match sha { - Some(Some(sha)) => { - let sha = sha.trim().to_string(); - if sha.is_empty() { - self.send_invalid_request_error( - request_id, - "gitInfo.sha must not be empty".to_string(), - ) - .await; - return; - } - Some(Some(sha)) - } - Some(None) => Some(None), - None => None, - }; - let git_branch = match branch { - Some(Some(branch)) => { - let branch = branch.trim().to_string(); - if branch.is_empty() { - self.send_invalid_request_error( - request_id, - "gitInfo.branch must not be empty".to_string(), - ) - .await; - return; - } - Some(Some(branch)) - } - Some(None) => Some(None), - None => None, - }; - let git_origin_url = match origin_url { - Some(Some(origin_url)) => { - let origin_url = origin_url.trim().to_string(); - if origin_url.is_empty() { - self.send_invalid_request_error( - request_id, - "gitInfo.originUrl must not be empty".to_string(), - ) - .await; - return; - } - Some(Some(origin_url)) - } - Some(None) => Some(None), - None => None, - }; + let git_sha = Self::normalize_thread_metadata_git_field(sha, "gitInfo.sha")?; + let git_branch = Self::normalize_thread_metadata_git_field(branch, "gitInfo.branch")?; + let git_origin_url = + Self::normalize_thread_metadata_git_field(origin_url, "gitInfo.originUrl")?; - let updated = match state_db_ctx + let updated = state_db_ctx .update_thread_git_info( thread_uuid, git_sha.as_ref().map(|value| value.as_deref()), @@ -3481,35 +3197,23 @@ impl CodexMessageProcessor { git_origin_url.as_ref().map(|value| value.as_deref()), ) .await - { - Ok(updated) => updated, - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to update thread metadata for {thread_uuid}: {err}"), - ) - .await; - return; - } - }; + .map_err(|err| { + internal_error(format!( + "failed to update thread metadata for {thread_uuid}: {err}" + )) + })?; if !updated { - self.send_internal_error( - request_id, - format!("thread metadata disappeared before update completed: {thread_uuid}"), - ) - .await; - return; + return Err(internal_error(format!( + "thread metadata disappeared before update completed: {thread_uuid}" + ))); } let Some(summary) = read_summary_from_state_db_context_by_thread_id(Some(&state_db_ctx), thread_uuid).await else { - self.send_internal_error( - request_id, - format!("failed to reload updated thread metadata for {thread_uuid}"), - ) - .await; - return; + return Err(internal_error(format!( + "failed to reload updated thread metadata for {thread_uuid}" + ))); }; let mut thread = summary_to_thread(summary, &self.config.cwd); @@ -3521,9 +3225,24 @@ impl CodexMessageProcessor { /*has_in_progress_turn*/ false, ); - self.outgoing - .send_response(request_id, ThreadMetadataUpdateResponse { thread }) - .await; + Ok(ThreadMetadataUpdateResponse { thread }) + } + + fn normalize_thread_metadata_git_field( + value: Option>, + name: &str, + ) -> Result>, JSONRPCErrorError> { + match value { + Some(Some(value)) => { + let value = value.trim().to_string(); + if value.is_empty() { + return Err(invalid_request(format!("{name} must not be empty"))); + } + Ok(Some(Some(value))) + } + Some(None) => Ok(Some(None)), + None => Ok(None), + } } async fn ensure_thread_metadata_row_exists( @@ -3532,22 +3251,6 @@ impl CodexMessageProcessor { state_db_ctx: &Arc, loaded_thread: Option<&Arc>, ) -> Result<(), JSONRPCErrorError> { - fn invalid_request(message: String) -> JSONRPCErrorError { - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message, - data: None, - } - } - - fn internal_error(message: String) -> JSONRPCErrorError { - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message, - data: None, - } - } - match state_db_ctx.get_thread(thread_uuid).await { Ok(Some(_)) => return Ok(()), Ok(None) => {} @@ -3597,7 +3300,7 @@ impl CodexMessageProcessor { builder.model_provider = Some(model_provider.clone()); builder.cwd = config_snapshot.cwd.to_path_buf(); builder.cli_version = Some(env!("CARGO_PKG_VERSION").to_string()); - builder.sandbox_policy = config_snapshot.sandbox_policy.clone(); + builder.sandbox_policy = config_snapshot.sandbox_policy(); builder.approval_mode = config_snapshot.approval_policy; let metadata = builder.build(model_provider.as_str()); if let Err(err) = state_db_ctx.insert_thread_if_absent(&metadata).await { @@ -3663,21 +3366,34 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadUnarchiveParams, ) { - let thread_id = match ThreadId::from_string(¶ms.thread_id) { - Ok(id) => id, - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid thread id: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let result = self.thread_unarchive_response(params).await; + let notification = + result + .as_ref() + .ok() + .map(|(_, thread_id)| ThreadUnarchivedNotification { + thread_id: thread_id.clone(), + }); + self.outgoing + .send_result(request_id, result.map(|(response, _)| response)) + .await; + + if let Some(notification) = notification { + self.outgoing + .send_server_notification(ServerNotification::ThreadUnarchived(notification)) + .await; + } + } + + async fn thread_unarchive_response( + &self, + params: ThreadUnarchiveParams, + ) -> Result<(ThreadUnarchiveResponse, String), JSONRPCErrorError> { + let thread_id = ThreadId::from_string(¶ms.thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; let fallback_provider = self.config.model_provider_id.clone(); - let result = self + let mut thread = self .thread_store .unarchive_thread(StoreArchiveThreadParams { thread_id }) .await @@ -3690,50 +3406,42 @@ impl CodexMessageProcessor { message: format!("failed to read unarchived thread {thread_id}"), data: None, }) - }); + })?; - match result { - Ok(mut thread) => { - thread.status = resolve_thread_status( - self.thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await, - /*has_in_progress_turn*/ false, - ); - self.attach_thread_name(thread_id, &mut thread).await; - let thread_id = thread.id.clone(); - let response = ThreadUnarchiveResponse { thread }; - self.outgoing.send_response(request_id, response).await; - let notification = ThreadUnarchivedNotification { thread_id }; - self.outgoing - .send_server_notification(ServerNotification::ThreadUnarchived(notification)) - .await; - } - Err(err) => { - self.outgoing.send_error(request_id, err).await; - } - } + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + /*has_in_progress_turn*/ false, + ); + self.attach_thread_name(thread_id, &mut thread).await; + let thread_id = thread.id.clone(); + Ok((ThreadUnarchiveResponse { thread }, thread_id)) } async fn thread_rollback(&self, request_id: ConnectionRequestId, params: ThreadRollbackParams) { + let result = self + .thread_rollback_start(&request_id, params) + .await + .map(|()| None::); + self.send_optional_result(request_id, result).await; + } + + async fn thread_rollback_start( + &self, + request_id: &ConnectionRequestId, + params: ThreadRollbackParams, + ) -> Result<(), JSONRPCErrorError> { let ThreadRollbackParams { thread_id, num_turns, } = params; if num_turns == 0 { - self.send_invalid_request_error(request_id, "numTurns must be >= 1".to_string()) - .await; - return; + return Err(invalid_request("numTurns must be >= 1")); } - let (thread_id, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let (thread_id, thread) = self.load_thread(&thread_id).await?; let request = request_id.clone(); @@ -3748,17 +3456,14 @@ impl CodexMessageProcessor { } }; if rollback_already_in_progress { - self.send_invalid_request_error( - request.clone(), - "rollback already in progress for this thread".to_string(), - ) - .await; - return; + return Err(invalid_request( + "rollback already in progress for this thread", + )); } if let Err(err) = self .submit_core_op( - &request_id, + request_id, thread.as_ref(), Op::ThreadRollback { num_turns }, ) @@ -3769,9 +3474,9 @@ impl CodexMessageProcessor { let thread_state = self.thread_state_manager.thread_state(thread_id).await; thread_state.lock().await.pending_rollbacks = None; - self.send_internal_error(request, format!("failed to start rollback: {err}")) - .await; + return Err(internal_error(format!("failed to start rollback: {err}"))); } + Ok(()) } async fn thread_compact_start( @@ -3781,28 +3486,15 @@ impl CodexMessageProcessor { ) { let ThreadCompactStartParams { thread_id } = params; - let (_, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - match self - .submit_core_op(&request_id, thread.as_ref(), Op::Compact) - .await - { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadCompactStartResponse {}) - .await; - } - Err(err) => { - self.send_internal_error(request_id, format!("failed to start compaction: {err}")) - .await; - } + let result = async { + let (_, thread) = self.load_thread(&thread_id).await?; + self.submit_core_op(&request_id, thread.as_ref(), Op::Compact) + .await + .map_err(|err| internal_error(format!("failed to start compaction: {err}")))?; + Ok::<_, JSONRPCErrorError>(ThreadCompactStartResponse {}) } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_background_terminals_clean( @@ -3812,31 +3504,17 @@ impl CodexMessageProcessor { ) { let ThreadBackgroundTerminalsCleanParams { thread_id } = params; - let (_, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - match self - .submit_core_op(&request_id, thread.as_ref(), Op::CleanBackgroundTerminals) - .await - { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadBackgroundTerminalsCleanResponse {}) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to clean background terminals: {err}"), - ) - .await; - } + let result = async { + let (_, thread) = self.load_thread(&thread_id).await?; + self.submit_core_op(&request_id, thread.as_ref(), Op::CleanBackgroundTerminals) + .await + .map_err(|err| { + internal_error(format!("failed to clean background terminals: {err}")) + })?; + Ok::<_, JSONRPCErrorError>(ThreadBackgroundTerminalsCleanResponse {}) } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_shell_command( @@ -3844,51 +3522,25 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadShellCommandParams, ) { - let ThreadShellCommandParams { thread_id, command } = params; - let command = command.trim().to_string(); - if command.is_empty() { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "command must not be empty".to_string(), - data: None, - }, - ) - .await; - return; - } - - let (_, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; + let result = async { + let ThreadShellCommandParams { thread_id, command } = params; + let command = command.trim().to_string(); + if command.is_empty() { + return Err(invalid_request("command must not be empty")); } - }; - match self - .submit_core_op( + let (_, thread) = self.load_thread(&thread_id).await?; + self.submit_core_op( &request_id, thread.as_ref(), Op::RunUserShellCommand { command }, ) .await - { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadShellCommandResponse {}) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to start shell command: {err}"), - ) - .await; - } + .map_err(|err| internal_error(format!("failed to start shell command: {err}")))?; + Ok::<_, JSONRPCErrorError>(ThreadShellCommandResponse {}) } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_approve_guardian_denied_action( @@ -3896,55 +3548,34 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadApproveGuardianDeniedActionParams, ) { - let ThreadApproveGuardianDeniedActionParams { thread_id, event } = params; - let event = match serde_json::from_value(event) { - Ok(event) => event, - Err(err) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid Guardian denial event: {err}"), - data: None, - }, - ) - .await; - return; - } - }; - let (_, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let result = async { + let ThreadApproveGuardianDeniedActionParams { thread_id, event } = params; + let event = serde_json::from_value(event) + .map_err(|err| invalid_request(format!("invalid Guardian denial event: {err}")))?; + let (_, thread) = self.load_thread(&thread_id).await?; - match self - .submit_core_op( + self.submit_core_op( &request_id, thread.as_ref(), Op::ApproveGuardianDeniedAction { event }, ) .await - { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadApproveGuardianDeniedActionResponse {}) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to approve Guardian denial: {err}"), - ) - .await; - } + .map_err(|err| internal_error(format!("failed to approve Guardian denial: {err}")))?; + Ok::<_, JSONRPCErrorError>(ThreadApproveGuardianDeniedActionResponse {}) } + .await; + self.outgoing.send_result(request_id, result).await; } async fn thread_list(&self, request_id: ConnectionRequestId, params: ThreadListParams) { + let result = self.thread_list_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_list_response( + &self, + params: ThreadListParams, + ) -> Result { let ThreadListParams { cursor, limit, @@ -3957,13 +3588,7 @@ impl CodexMessageProcessor { use_state_db_only, search_term, } = params; - let cwd_filters = match normalize_thread_list_cwd_filters(cwd) { - Ok(cwd_filters) => cwd_filters, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let cwd_filters = normalize_thread_list_cwd_filters(cwd)?; let requested_page_size = limit .map(|value| value as usize) @@ -3974,7 +3599,7 @@ impl CodexMessageProcessor { ThreadSortKey::UpdatedAt => StoreThreadSortKey::UpdatedAt, }; let sort_direction = sort_direction.unwrap_or(SortDirection::Desc); - let list_result = self + let (summaries, next_cursor) = self .list_threads_common( requested_page_size, cursor, @@ -3989,14 +3614,7 @@ impl CodexMessageProcessor { use_state_db_only, }, ) - .await; - let (summaries, next_cursor) = match list_result { - Ok(r) => r, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + .await?; let backwards_cursor = summaries.first().and_then(|summary| { thread_backwards_cursor_for_sort_key(summary, store_sort_key, sort_direction) }); @@ -4032,12 +3650,11 @@ impl CodexMessageProcessor { thread }) .collect(); - let response = ThreadListResponse { + Ok(ThreadListResponse { data, next_cursor, backwards_cursor, - }; - self.outgoing.send_response(request_id, response).await; + }) } async fn thread_loaded_list( @@ -4045,22 +3662,28 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadLoadedListParams, ) { + let result = self.thread_loaded_list_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_loaded_list_response( + &self, + params: ThreadLoadedListParams, + ) -> Result { let ThreadLoadedListParams { cursor, limit } = params; - let mut data = self + let mut data: Vec = self .thread_manager .list_thread_ids() .await .into_iter() .map(|thread_id| thread_id.to_string()) - .collect::>(); + .collect(); if data.is_empty() { - let response = ThreadLoadedListResponse { + return Ok(ThreadLoadedListResponse { data, next_cursor: None, - }; - self.outgoing.send_response(request_id, response).await; - return; + }); } data.sort(); @@ -4069,15 +3692,7 @@ impl CodexMessageProcessor { Some(cursor) => { let cursor = match ThreadId::from_string(&cursor) { Ok(id) => id.to_string(), - Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid cursor: {cursor}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } + Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))), }; match data.binary_search(&cursor) { Ok(idx) => idx + 1, @@ -4092,41 +3707,34 @@ impl CodexMessageProcessor { let page = data[start..end].to_vec(); let next_cursor = page.last().filter(|_| end < total).cloned(); - let response = ThreadLoadedListResponse { + Ok(ThreadLoadedListResponse { data: page, next_cursor, - }; - self.outgoing.send_response(request_id, response).await; + }) } async fn thread_read(&self, request_id: ConnectionRequestId, params: ThreadReadParams) { + let result = self.thread_read_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_read_response( + &self, + params: ThreadReadParams, + ) -> Result { let ThreadReadParams { thread_id, include_turns, } = params; - let thread_uuid = match ThreadId::from_string(&thread_id) { - Ok(id) => id, - Err(err) => { - self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) - .await; - return; - } - }; + let thread_uuid = ThreadId::from_string(&thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; - let thread = match self.read_thread_view(thread_uuid, include_turns).await { - Ok(thread) => thread, - Err(ThreadReadViewError::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - return; - } - Err(ThreadReadViewError::Internal(message)) => { - self.send_internal_error(request_id, message).await; - return; - } - }; - let response = ThreadReadResponse { thread }; - self.outgoing.send_response(request_id, response).await; + let thread = self + .read_thread_view(thread_uuid, include_turns) + .await + .map_err(thread_read_view_error)?; + Ok(ThreadReadResponse { thread }) } /// Builds the API view for `thread/read` from persisted metadata plus optional live state. @@ -4284,6 +3892,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadTurnsListParams, ) { + let result = self.thread_turns_list_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_turns_list_response( + &self, + params: ThreadTurnsListParams, + ) -> Result { let ThreadTurnsListParams { thread_id, cursor, @@ -4291,14 +3907,8 @@ impl CodexMessageProcessor { sort_direction, } = params; - let thread_uuid = match ThreadId::from_string(&thread_id) { - Ok(id) => id, - Err(err) => { - self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) - .await; - return; - } - }; + let thread_uuid = ThreadId::from_string(&thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; let state_db_ctx = get_state_db(&self.config).await; let mut rollout_path = self @@ -4318,21 +3928,15 @@ impl CodexMessageProcessor { { Ok(path) => path, Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to locate archived thread id {thread_uuid}: {err}"), - ) - .await; - return; + return Err(invalid_request(format!( + "failed to locate archived thread id {thread_uuid}: {err}" + ))); } }, Err(err) => { - self.send_invalid_request_error( - request_id, - format!("failed to locate thread id {thread_uuid}: {err}"), - ) - .await; - return; + return Err(invalid_request(format!( + "failed to locate thread id {thread_uuid}: {err}" + ))); } }; } @@ -4342,92 +3946,63 @@ impl CodexMessageProcessor { Ok(thread) => { rollout_path = thread.rollout_path(); if rollout_path.is_none() { - self.send_invalid_request_error( - request_id, - "ephemeral threads do not support thread/turns/list".to_string(), - ) - .await; - return; + return Err(invalid_request( + "ephemeral threads do not support thread/turns/list", + )); } } - Err(_) => { - self.send_invalid_request_error( - request_id, - format!("thread not loaded: {thread_uuid}"), - ) - .await; - return; - } + Err(_) => return Err(invalid_request(format!("thread not loaded: {thread_uuid}"))), } } let Some(rollout_path) = rollout_path.as_ref() else { - self.send_internal_error( - request_id, - format!("failed to locate rollout for thread {thread_uuid}"), - ) - .await; - return; + return Err(internal_error(format!( + "failed to locate rollout for thread {thread_uuid}" + ))); }; - match read_rollout_items_from_rollout(rollout_path).await { - Ok(items) => { - // This API optimizes network transfer by letting clients page through a - // thread's turns incrementally, but it still replays the entire rollout on - // every request. Rollback and compaction events can change earlier turns, so - // the server has to rebuild the full turn list until turn metadata is indexed - // separately. - let has_live_in_progress_turn = - match self.thread_manager.get_thread(thread_uuid).await { - Ok(thread) => matches!(thread.agent_status().await, AgentStatus::Running), - Err(_) => false, - }; - let turns = reconstruct_thread_turns_from_rollout_items( - &items, - self.thread_watch_manager - .loaded_status_for_thread(&thread_uuid.to_string()) - .await, - has_live_in_progress_turn, - ); - let page = match paginate_thread_turns( - turns, - cursor.as_deref(), - limit, - sort_direction.unwrap_or(SortDirection::Desc), - ) { - Ok(page) => page, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let response = ThreadTurnsListResponse { - data: page.turns, - next_cursor: page.next_cursor, - backwards_cursor: page.backwards_cursor, - }; - self.outgoing.send_response(request_id, response).await; - } + let items = match read_rollout_items_from_rollout(rollout_path).await { + Ok(items) => items, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - self.send_invalid_request_error( - request_id, - format!( - "thread {thread_uuid} is not materialized yet; thread/turns/list is unavailable before first user message" - ), - ) - .await; + return Err(invalid_request(format!( + "thread {thread_uuid} is not materialized yet; thread/turns/list is unavailable before first user message" + ))); } Err(err) => { - self.send_internal_error( - request_id, - format!( - "failed to load rollout `{}` for thread {thread_uuid}: {err}", - rollout_path.display() - ), - ) - .await; + return Err(internal_error(format!( + "failed to load rollout `{}` for thread {thread_uuid}: {err}", + rollout_path.display() + ))); } - } + }; + + // This API optimizes network transfer by letting clients page through a + // thread's turns incrementally, but it still replays the entire rollout on + // every request. Rollback and compaction events can change earlier turns, so + // the server has to rebuild the full turn list until turn metadata is indexed + // separately. + let has_live_in_progress_turn = match self.thread_manager.get_thread(thread_uuid).await { + Ok(thread) => matches!(thread.agent_status().await, AgentStatus::Running), + Err(_) => false, + }; + let turns = reconstruct_thread_turns_from_rollout_items( + &items, + self.thread_watch_manager + .loaded_status_for_thread(&thread_uuid.to_string()) + .await, + has_live_in_progress_turn, + ); + let page = paginate_thread_turns( + turns, + cursor.as_deref(), + limit, + sort_direction.unwrap_or(SortDirection::Desc), + )?; + Ok(ThreadTurnsListResponse { + data: page.turns, + next_cursor: page.next_cursor, + backwards_cursor: page.backwards_cursor, + }) } pub(crate) fn thread_created_receiver(&self) -> broadcast::Receiver { @@ -4499,30 +4074,34 @@ impl CodexMessageProcessor { .await .contains(&thread_id) { - self.send_invalid_request_error( - request_id, - format!( - "thread {thread_id} is closing; retry thread/resume after the thread is closed" - ), - ) - .await; + self.outgoing + .send_error( + request_id, + invalid_request(format!( + "thread {thread_id} is closing; retry thread/resume after the thread is closed" + )), + ) + .await; return; } if params.sandbox.is_some() && params.permission_profile.is_some() { - self.send_invalid_request_error( - request_id, - "`permissionProfile` cannot be combined with `sandbox`".to_string(), - ) - .await; + self.outgoing + .send_error( + request_id, + invalid_request("`permissionProfile` cannot be combined with `sandbox`"), + ) + .await; return; } - if self - .resume_running_thread(request_id.clone(), ¶ms) - .await - { - return; + match self.resume_running_thread(&request_id, ¶ms).await { + Ok(true) => return, + Ok(false) => {} + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return; + } } let ThreadResumeParams { @@ -4546,22 +4125,20 @@ impl CodexMessageProcessor { } = params; let include_turns = !exclude_turns; - let (thread_history, resume_source_thread) = if let Some(history) = history { - let Some(thread_history) = self - .resume_thread_from_history(request_id.clone(), history.as_slice()) + let (thread_history, resume_source_thread) = match if let Some(history) = history { + self.resume_thread_from_history(history.as_slice()) .await - else { - return; - }; - (thread_history, None) + .map(|thread_history| (thread_history, None)) } else { - let Some((thread_history, stored_thread)) = self - .resume_thread_from_rollout(request_id.clone(), &thread_id, path.as_ref()) + self.resume_thread_from_rollout(&thread_id, path.as_ref()) .await - else { + .map(|(thread_history, stored_thread)| (thread_history, Some(stored_thread))) + } { + Ok(value) => value, + Err(error) => { + self.outgoing.send_error(request_id, error).await; return; - }; - (thread_history, Some(stored_thread)) + } }; let history_cwd = thread_history.session_cwd(); @@ -4601,6 +4178,7 @@ impl CodexMessageProcessor { let instruction_sources = Self::instruction_sources_from_config(&config).await; let response_history = thread_history.clone(); + let memory_config = Arc::new(config.clone()); match self .thread_manager @@ -4621,11 +4199,9 @@ impl CodexMessageProcessor { }) => { let SessionConfiguredEvent { rollout_path, .. } = session_configured; let Some(rollout_path) = rollout_path else { - self.send_internal_error( - request_id, - format!("rollout path missing for thread {thread_id}"), - ) - .await; + let error = + internal_error(format!("rollout path missing for thread {thread_id}")); + self.outgoing.send_error(request_id, error).await; return; }; // Auto-attach a thread listener when resuming a thread. @@ -4655,7 +4231,9 @@ impl CodexMessageProcessor { { Ok(thread) => thread, Err(message) => { - self.send_internal_error(request_id, message).await; + self.outgoing + .send_error(request_id, internal_error(message)) + .await; return; } }; @@ -4674,9 +4252,21 @@ impl CodexMessageProcessor { thread_status, /*has_live_in_progress_turn*/ false, ); - let permission_profile = thread_response_permission_profile( - codex_thread.config_snapshot().await.permission_profile, + let config_snapshot = codex_thread.config_snapshot().await; + codex_memories_write::start_memories_startup_task( + Arc::clone(&self.thread_manager), + Arc::clone(&self.auth_manager), + thread_id, + Arc::clone(&codex_thread), + Arc::clone(&memory_config), + &config_snapshot.session_source, ); + let sandbox = thread_response_sandbox_policy( + &config_snapshot.permission_profile, + config_snapshot.cwd.as_path(), + ); + let permission_profile = + thread_response_permission_profile(config_snapshot.permission_profile.clone()); let response = ThreadResumeResponse { thread, @@ -4687,19 +4277,17 @@ impl CodexMessageProcessor { instruction_sources, approval_policy: session_configured.approval_policy.into(), approvals_reviewer: session_configured.approvals_reviewer.into(), - sandbox: session_configured.sandbox_policy.into(), + sandbox, permission_profile, reasoning_effort: session_configured.reasoning_effort, }; - if self.config.features.enabled(Feature::GeneralAnalytics) { - self.analytics_events_client.track_response( - request_id.connection_id.0, - ClientResponse::ThreadResume { - request_id: request_id.request_id.clone(), - response: response.clone(), - }, - ); - } + self.analytics_events_client.track_response( + request_id.connection_id.0, + ClientResponse::ThreadResume { + request_id: request_id.request_id.clone(), + response: response.clone(), + }, + ); let connection_id = request_id.connection_id; let token_usage_thread = include_turns.then(|| response.thread.clone()); @@ -4734,11 +4322,7 @@ impl CodexMessageProcessor { } } Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("error resuming thread: {err}"), - data: None, - }; + let error = internal_error(format!("error resuming thread: {err}")); self.outgoing.send_error(request_id, error).await; } } @@ -4765,21 +4349,16 @@ impl CodexMessageProcessor { async fn resume_running_thread( &self, - request_id: ConnectionRequestId, + request_id: &ConnectionRequestId, params: &ThreadResumeParams, - ) -> bool { + ) -> Result { if let Ok(existing_thread_id) = ThreadId::from_string(¶ms.thread_id) && let Ok(existing_thread) = self.thread_manager.get_thread(existing_thread_id).await { if params.history.is_some() { - self.send_invalid_request_error( - request_id, - format!( - "cannot resume thread {existing_thread_id} with history while it is already running" - ), - ) - .await; - return true; + return Err(invalid_request(format!( + "cannot resume thread {existing_thread_id} with history while it is already running" + ))); } if let (Some(requested_path), Some(active_path)) = ( @@ -4787,69 +4366,47 @@ impl CodexMessageProcessor { existing_thread.rollout_path().as_ref(), ) && requested_path != active_path { - self.send_invalid_request_error( - request_id, - format!( - "cannot resume running thread {existing_thread_id} with mismatched path: requested `{}`, active `{}`", - requested_path.display(), - active_path.display() - ), - ) - .await; - return true; + return Err(invalid_request(format!( + "cannot resume running thread {existing_thread_id} with mismatched path: requested `{}`, active `{}`", + requested_path.display(), + active_path.display() + ))); } - let Some(source_thread) = self + let source_thread = self .read_stored_thread_for_resume( - request_id.clone(), ¶ms.thread_id, params.path.as_ref(), /*include_history*/ true, ) - .await - else { - return true; - }; + .await?; if source_thread.thread_id != existing_thread_id { - self.send_invalid_request_error( - request_id, - format!( - "cannot resume running thread {existing_thread_id} from source thread {}", - source_thread.thread_id - ), - ) - .await; - return true; + return Err(invalid_request(format!( + "cannot resume running thread {existing_thread_id} from source thread {}", + source_thread.thread_id + ))); } - let Some(history_items) = source_thread + let history_items = source_thread .history .as_ref() .map(|history| history.items.clone()) - else { - self.send_internal_error( - request_id, - format!("thread {existing_thread_id} did not include persisted history"), - ) - .await; - return true; - }; + .ok_or_else(|| { + internal_error(format!( + "thread {existing_thread_id} did not include persisted history" + )) + })?; let thread_state = self .thread_state_manager .thread_state(existing_thread_id) .await; - if let Err(error) = self - .ensure_listener_task_running( - existing_thread_id, - existing_thread.clone(), - thread_state.clone(), - ApiVersion::V2, - ) - .await - { - self.outgoing.send_error(request_id, error).await; - return true; - } + self.ensure_listener_task_running( + existing_thread_id, + existing_thread.clone(), + thread_state.clone(), + ApiVersion::V2, + ) + .await?; let config_snapshot = existing_thread.config_snapshot().await; let mismatch_details = collect_resume_override_mismatches(params, &config_snapshot); @@ -4871,10 +4428,7 @@ impl CodexMessageProcessor { .await { Ok(thread) => thread, - Err(message) => { - self.send_internal_error(request_id, message).await; - return true; - } + Err(message) => return Err(internal_error(message)), }; let mut config_for_instruction_sources = self.config.as_ref().clone(); config_for_instruction_sources.cwd = config_snapshot.cwd.clone(); @@ -4886,15 +4440,9 @@ impl CodexMessageProcessor { thread_state.listener_command_tx() }; let Some(listener_command_tx) = listener_command_tx else { - let err = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to enqueue running thread resume for thread {existing_thread_id}: thread listener is not running" - ), - data: None, - }; - self.outgoing.send_error(request_id, err).await; - return true; + return Err(internal_error(format!( + "failed to enqueue running thread resume for thread {existing_thread_id}: thread listener is not running" + ))); }; let emit_thread_goal_update = self.config.features.enabled(Feature::Goals); @@ -4921,32 +4469,23 @@ impl CodexMessageProcessor { }), ); if listener_command_tx.send(command).is_err() { - let err = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed" - ), - data: None, - }; - self.outgoing.send_error(request_id, err).await; - return true; + return Err(internal_error(format!( + "failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed" + ))); } - return true; + return Ok(true); } - false + Ok(false) } async fn resume_thread_from_history( &self, - request_id: ConnectionRequestId, history: &[ResponseItem], - ) -> Option { + ) -> Result { if history.is_empty() { - self.send_invalid_request_error(request_id, "history must not be empty".to_string()) - .await; - return None; + return Err(invalid_request("history must not be empty")); } - Some(InitialHistory::Forked( + Ok(InitialHistory::Forked( history .iter() .cloned() @@ -4957,34 +4496,24 @@ impl CodexMessageProcessor { async fn resume_thread_from_rollout( &self, - request_id: ConnectionRequestId, thread_id: &str, path: Option<&PathBuf>, - ) -> Option<(InitialHistory, StoredThread)> { - match self - .read_stored_thread_for_resume( - request_id.clone(), - thread_id, - path, - /*include_history*/ true, - ) - .await - { - Some(stored_thread) => self - .stored_thread_to_initial_history(request_id, &stored_thread) - .await - .map(|history| (history, stored_thread)), - None => None, - } + ) -> Result<(InitialHistory, StoredThread), JSONRPCErrorError> { + let stored_thread = self + .read_stored_thread_for_resume(thread_id, path, /*include_history*/ true) + .await?; + let history = self + .stored_thread_to_initial_history(&stored_thread) + .await?; + Ok((history, stored_thread)) } async fn read_stored_thread_for_resume( &self, - request_id: ConnectionRequestId, thread_id: &str, path: Option<&PathBuf>, include_history: bool, - ) -> Option { + ) -> Result { let result = if let Some(path) = path { self.thread_store .read_thread_by_rollout_path(StoreReadThreadByRolloutPathParams { @@ -4997,12 +4526,7 @@ impl CodexMessageProcessor { let existing_thread_id = match ThreadId::from_string(thread_id) { Ok(id) => id, Err(err) => { - self.send_invalid_request_error( - request_id, - format!("invalid thread id: {err}"), - ) - .await; - return None; + return Err(invalid_request(format!("invalid thread id: {err}"))); } }; let params = StoreReadThreadParams { @@ -5013,35 +4537,24 @@ impl CodexMessageProcessor { self.thread_store.read_thread(params).await }; - match result { - Ok(thread) => Some(thread), - Err(err) => { - self.outgoing - .send_error(request_id, thread_store_resume_read_error(err)) - .await; - None - } - } + result.map_err(thread_store_resume_read_error) } async fn stored_thread_to_initial_history( &self, - request_id: ConnectionRequestId, stored_thread: &StoredThread, - ) -> Option { + ) -> Result { let thread_id = stored_thread.thread_id; - let history = match stored_thread.history.as_ref() { - Some(history) => history.items.clone(), - None => { - self.send_internal_error( - request_id, - format!("thread {thread_id} did not include persisted history"), - ) - .await; - return None; - } - }; - Some(InitialHistory::Resumed(ResumedHistory { + let history = stored_thread + .history + .as_ref() + .map(|history| history.items.clone()) + .ok_or_else(|| { + internal_error(format!( + "thread {thread_id} did not include persisted history" + )) + })?; + Ok(InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, history, rollout_path: stored_thread.rollout_path.clone(), @@ -5069,27 +4582,18 @@ impl CodexMessageProcessor { async fn read_stored_thread_for_new_fork( &self, - request_id: ConnectionRequestId, thread_store: &dyn ThreadStore, thread_id: ThreadId, include_history: bool, - ) -> Option { - match thread_store + ) -> Result { + thread_store .read_thread(StoreReadThreadParams { thread_id, include_archived: true, include_history, }) .await - { - Ok(thread) => Some(thread), - Err(err) => { - self.outgoing - .send_error(request_id, thread_store_resume_read_error(err)) - .await; - None - } - } + .map_err(thread_store_resume_read_error) } async fn load_thread_from_resume_source_or_send_internal( @@ -5190,247 +4694,227 @@ impl CodexMessageProcessor { persist_extended_history, } = params; let include_turns = !exclude_turns; - if sandbox.is_some() && permission_profile.is_some() { - self.send_invalid_request_error( - request_id, - "`permissionProfile` cannot be combined with `sandbox`".to_string(), - ) - .await; - return; - } - - let Some(source_thread) = self - .read_stored_thread_for_resume( - request_id.clone(), - &thread_id, - path.as_ref(), - /*include_history*/ true, - ) - .await - else { - return; - }; - let source_thread_id = source_thread.thread_id; - let Some(history_items) = source_thread - .history - .as_ref() - .map(|history| history.items.clone()) - else { - self.send_internal_error( - request_id, - format!("thread {source_thread_id} did not include persisted history"), - ) - .await; - return; - }; - let history_cwd = Some(source_thread.cwd.clone()); - - // Persist Windows sandbox mode. - let mut cli_overrides = cli_overrides.unwrap_or_default(); - if cfg!(windows) { - match WindowsSandboxLevel::from_config(&self.config) { - WindowsSandboxLevel::Elevated => { - cli_overrides - .insert("windows.sandbox".to_string(), serde_json::json!("elevated")); - } - WindowsSandboxLevel::RestrictedToken => { - cli_overrides.insert( - "windows.sandbox".to_string(), - serde_json::json!("unelevated"), - ); - } - WindowsSandboxLevel::Disabled => {} + let result = async { + if sandbox.is_some() && permission_profile.is_some() { + return Err(invalid_request( + "`permissionProfile` cannot be combined with `sandbox`", + )); } - } - let request_overrides = if cli_overrides.is_empty() { - None - } else { - Some(cli_overrides) - }; - let mut typesafe_overrides = self.build_thread_config_overrides( - model, - model_provider, - service_tier, - cwd, - approval_policy, - approvals_reviewer, - sandbox, - permission_profile, - base_instructions, - developer_instructions, - /*personality*/ None, - ); - typesafe_overrides.ephemeral = ephemeral.then_some(true); - // Derive a Config using the same logic as new conversation, honoring overrides if provided. - let config = match self - .config_manager - .load_for_cwd(request_overrides, typesafe_overrides, history_cwd) - .await - { - Ok(config) => config, - Err(err) => { - self.outgoing - .send_error(request_id, config_load_error(&err)) - .await; - return; + + let source_thread = self + .read_stored_thread_for_resume( + &thread_id, + path.as_ref(), + /*include_history*/ true, + ) + .await?; + let source_thread_id = source_thread.thread_id; + let history_items = source_thread + .history + .as_ref() + .map(|history| history.items.clone()) + .ok_or_else(|| { + internal_error(format!( + "thread {source_thread_id} did not include persisted history" + )) + })?; + let history_cwd = Some(source_thread.cwd.clone()); + + // Persist Windows sandbox mode. + let mut cli_overrides = cli_overrides.unwrap_or_default(); + if cfg!(windows) { + match WindowsSandboxLevel::from_config(&self.config) { + WindowsSandboxLevel::Elevated => { + cli_overrides + .insert("windows.sandbox".to_string(), serde_json::json!("elevated")); + } + WindowsSandboxLevel::RestrictedToken => { + cli_overrides.insert( + "windows.sandbox".to_string(), + serde_json::json!("unelevated"), + ); + } + WindowsSandboxLevel::Disabled => {} + } } - }; + let request_overrides = if cli_overrides.is_empty() { + None + } else { + Some(cli_overrides) + }; + let mut typesafe_overrides = self.build_thread_config_overrides( + model, + model_provider, + service_tier, + cwd, + approval_policy, + approvals_reviewer, + sandbox, + permission_profile, + base_instructions, + developer_instructions, + /*personality*/ None, + ); + typesafe_overrides.ephemeral = ephemeral.then_some(true); + // Derive a Config using the same logic as new conversation, honoring overrides if provided. + let config = self + .config_manager + .load_for_cwd(request_overrides, typesafe_overrides, history_cwd) + .await + .map_err(|err| config_load_error(&err))?; - let fallback_model_provider = config.model_provider_id.clone(); - let instruction_sources = Self::instruction_sources_from_config(&config).await; - let fork_thread_store = configured_thread_store(&config); + let fallback_model_provider = config.model_provider_id.clone(); + let instruction_sources = Self::instruction_sources_from_config(&config).await; + let fork_thread_store = configured_thread_store(&config); + let memory_config = Arc::new(config.clone()); - let NewThread { - thread_id, - thread: forked_thread, - session_configured, - .. - } = match self - .thread_manager - .fork_thread_from_history( - ForkSnapshot::Interrupted, - config, - InitialHistory::Resumed(ResumedHistory { - conversation_id: source_thread_id, - history: history_items.clone(), - rollout_path: source_thread.rollout_path.clone(), - }), - persist_extended_history, - self.request_trace_context(&request_id).await, - ) - .await - { - Ok(thread) => thread, - Err(err) => { - match err { + let NewThread { + thread_id, + thread: forked_thread, + session_configured, + .. + } = self + .thread_manager + .fork_thread_from_history( + ForkSnapshot::Interrupted, + config, + InitialHistory::Resumed(ResumedHistory { + conversation_id: source_thread_id, + history: history_items.clone(), + rollout_path: source_thread.rollout_path.clone(), + }), + persist_extended_history, + self.request_trace_context(&request_id).await, + ) + .await + .map_err(|err| match err { CodexErr::Io(_) | CodexErr::Json(_) => { - self.send_invalid_request_error( - request_id, - format!("failed to load thread {source_thread_id}: {err}"), - ) - .await; + invalid_request(format!("failed to load thread {source_thread_id}: {err}")) } - CodexErr::InvalidRequest(message) => { - self.send_invalid_request_error(request_id, message).await; - } - _ => { - self.send_internal_error( - request_id, - format!("error forking thread: {err}"), - ) - .await; - } - } - return; - } - }; + CodexErr::InvalidRequest(message) => invalid_request(message), + err => internal_error(format!("error forking thread: {err}")), + })?; - // Auto-attach a conversation listener when forking a thread. - Self::log_listener_attach_result( - self.ensure_conversation_listener( + // Auto-attach a conversation listener when forking a thread. + Self::log_listener_attach_result( + self.ensure_conversation_listener( + thread_id, + request_id.connection_id, + /*raw_events_enabled*/ false, + ApiVersion::V2, + ) + .await, thread_id, request_id.connection_id, - /*raw_events_enabled*/ false, - ApiVersion::V2, - ) - .await, - thread_id, - request_id.connection_id, - "thread", - ); + "thread", + ); - // Persistent forks materialize their own rollout immediately. Ephemeral forks stay - // pathless, so they rebuild their visible history from the copied source history instead. - let mut thread = if let Some(fork_rollout_path) = session_configured.rollout_path.as_ref() { - let Some(stored_thread) = self - .read_stored_thread_for_new_fork( - request_id.clone(), - fork_thread_store.as_ref(), - thread_id, - include_turns, - ) - .await - else { - return; - }; - match self - .stored_thread_to_api_thread( - stored_thread, - fallback_model_provider.as_str(), - include_turns, - ) - .await - { - Ok(thread) => thread, - Err(message) => { - self.send_internal_error( - request_id, - format!( + // Persistent forks materialize their own rollout immediately. Ephemeral forks stay + // pathless, so they rebuild their visible history from the copied source history instead. + let mut thread = + if let Some(fork_rollout_path) = session_configured.rollout_path.as_ref() { + let stored_thread = self + .read_stored_thread_for_new_fork( + fork_thread_store.as_ref(), + thread_id, + include_turns, + ) + .await?; + self.stored_thread_to_api_thread( + stored_thread, + fallback_model_provider.as_str(), + include_turns, + ) + .await + .map_err(|message| { + internal_error(format!( "failed to load rollout `{}` for thread {thread_id}: {message}", fork_rollout_path.display() - ), - ) - .await; - return; - } - } - } else { + )) + })? + } else { + let config_snapshot = forked_thread.config_snapshot().await; + // forked thread names do not inherit the source thread name + let mut thread = + build_thread_from_snapshot(thread_id, &config_snapshot, /*path*/ None); + thread.preview = preview_from_rollout_items(&history_items); + thread.forked_from_id = Some(source_thread_id.to_string()); + if include_turns { + populate_thread_turns( + &mut thread, + ThreadTurnSource::HistoryItems(&history_items), + /*active_turn*/ None, + ) + .await + .map_err(internal_error)?; + } + thread + }; + + self.thread_watch_manager + .upsert_thread_silently(thread.clone()) + .await; + + thread.status = resolve_thread_status( + self.thread_watch_manager + .loaded_status_for_thread(&thread.id) + .await, + /*has_in_progress_turn*/ false, + ); let config_snapshot = forked_thread.config_snapshot().await; - // forked thread names do not inherit the source thread name - let mut thread = - build_thread_from_snapshot(thread_id, &config_snapshot, /*path*/ None); - thread.preview = preview_from_rollout_items(&history_items); - thread.forked_from_id = Some(source_thread_id.to_string()); - if include_turns - && let Err(message) = populate_thread_turns( - &mut thread, - ThreadTurnSource::HistoryItems(&history_items), - /*active_turn*/ None, - ) - .await - { - self.send_internal_error(request_id, message).await; + codex_memories_write::start_memories_startup_task( + Arc::clone(&self.thread_manager), + Arc::clone(&self.auth_manager), + thread_id, + Arc::clone(&forked_thread), + Arc::clone(&memory_config), + &config_snapshot.session_source, + ); + let sandbox = thread_response_sandbox_policy( + &config_snapshot.permission_profile, + config_snapshot.cwd.as_path(), + ); + let permission_profile = + thread_response_permission_profile(config_snapshot.permission_profile); + + let response = ThreadForkResponse { + thread: thread.clone(), + model: session_configured.model, + model_provider: session_configured.model_provider_id, + service_tier: session_configured.service_tier, + cwd: session_configured.cwd, + instruction_sources, + approval_policy: session_configured.approval_policy.into(), + approvals_reviewer: session_configured.approvals_reviewer.into(), + sandbox, + permission_profile, + reasoning_effort: session_configured.reasoning_effort, + }; + + Ok::<_, JSONRPCErrorError>(( + response, + thread_id, + forked_thread, + history_items, + thread_started_notification(thread), + )) + } + .await; + + let (response, thread_id, forked_thread, history_items, notif) = match result { + Ok(value) => value, + Err(error) => { + self.outgoing.send_error(request_id, error).await; return; } - thread }; - - self.thread_watch_manager - .upsert_thread_silently(thread.clone()) - .await; - - thread.status = resolve_thread_status( - self.thread_watch_manager - .loaded_status_for_thread(&thread.id) - .await, - /*has_in_progress_turn*/ false, + self.analytics_events_client.track_response( + request_id.connection_id.0, + ClientResponse::ThreadFork { + request_id: request_id.request_id.clone(), + response: response.clone(), + }, ); - let permission_profile = thread_response_permission_profile( - forked_thread.config_snapshot().await.permission_profile, - ); - - let response = ThreadForkResponse { - thread: thread.clone(), - model: session_configured.model, - model_provider: session_configured.model_provider_id, - service_tier: session_configured.service_tier, - cwd: session_configured.cwd, - instruction_sources, - approval_policy: session_configured.approval_policy.into(), - approvals_reviewer: session_configured.approvals_reviewer.into(), - sandbox: session_configured.sandbox_policy.into(), - permission_profile, - reasoning_effort: session_configured.reasoning_effort, - }; - if self.config.features.enabled(Feature::GeneralAnalytics) { - self.analytics_events_client.track_response( - request_id.connection_id.0, - ClientResponse::ThreadFork { - request_id: request_id.request_id.clone(), - response: response.clone(), - }, - ); - } let connection_id = request_id.connection_id; let token_usage_thread = include_turns.then(|| response.thread.clone()); @@ -5461,7 +4945,6 @@ impl CodexMessageProcessor { .await; } - let notif = thread_started_notification(thread); self.outgoing .send_server_notification(ServerNotification::ThreadStarted(notif)) .await; @@ -5472,6 +4955,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: GetConversationSummaryParams, ) { + let result = self.get_thread_summary_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn get_thread_summary_response( + &self, + params: GetConversationSummaryParams, + ) -> Result { let fallback_provider = self.config.model_provider_id.as_str(); let read_result = match params { GetConversationSummaryParams::ThreadId { conversation_id } => self @@ -5489,13 +4980,9 @@ impl CodexMessageProcessor { .as_any() .downcast_ref::() else { - self.send_invalid_request_error( - request_id, - "rollout path queries are only supported with the local thread store" - .to_string(), - ) - .await; - return; + return Err(invalid_request( + "rollout path queries are only supported with the local thread store", + )); }; local_thread_store @@ -5509,27 +4996,14 @@ impl CodexMessageProcessor { } }; - match read_result { - Ok(stored_thread) => { - let Some(summary) = summary_from_stored_thread(stored_thread, fallback_provider) - else { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: - "failed to load conversation summary: thread is missing rollout path" - .to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - }; - let response = GetConversationSummaryResponse { summary }; - self.outgoing.send_response(request_id, response).await; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - } - } + let stored_thread = read_result?; + let summary = + summary_from_stored_thread(stored_thread, fallback_provider).ok_or_else(|| { + internal_error( + "failed to load conversation summary: thread is missing rollout path", + ) + })?; + Ok(GetConversationSummaryResponse { summary }) } async fn list_threads_common( @@ -5642,63 +5116,51 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ModelListParams, ) { - let ModelListParams { - limit, - cursor, - include_hidden, - } = params; - let models = supported_models(thread_manager, include_hidden.unwrap_or(false)).await; - let total = models.len(); + let result = async { + let ModelListParams { + limit, + cursor, + include_hidden, + } = params; + let models = supported_models(thread_manager, include_hidden.unwrap_or(false)).await; + let total = models.len(); - if total == 0 { - let response = ModelListResponse { - data: Vec::new(), - next_cursor: None, + if total == 0 { + return Ok(ModelListResponse { + data: Vec::new(), + next_cursor: None, + }); + } + + let effective_limit = limit.unwrap_or(total as u32).max(1) as usize; + let effective_limit = effective_limit.min(total); + let start = match cursor { + Some(cursor) => cursor + .parse::() + .map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?, + None => 0, }; - outgoing.send_response(request_id, response).await; - return; - } - let effective_limit = limit.unwrap_or(total as u32).max(1) as usize; - let effective_limit = effective_limit.min(total); - let start = match 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 { + return Err(invalid_request(format!( + "cursor {start} exceeds total models {total}" + ))); + } - if start > total { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("cursor {start} exceeds total models {total}"), - data: None, + let end = start.saturating_add(effective_limit).min(total); + let items = models[start..end].to_vec(); + let next_cursor = if end < total { + Some(end.to_string()) + } else { + None }; - outgoing.send_error(request_id, error).await; - return; + Ok::<_, JSONRPCErrorError>(ModelListResponse { + data: items, + next_cursor, + }) } - - let end = start.saturating_add(effective_limit).min(total); - let items = models[start..end].to_vec(); - let next_cursor = if end < total { - Some(end.to_string()) - } else { - None - }; - let response = ModelListResponse { - data: items, - next_cursor, - }; - outgoing.send_response(request_id, response).await; + .await; + outgoing.send_result(request_id, result).await; } async fn list_collaboration_modes( @@ -5722,14 +5184,16 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ExperimentalFeatureListParams, ) { + let result = self.experimental_feature_list_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn experimental_feature_list_response( + &self, + params: ExperimentalFeatureListParams, + ) -> Result { let ExperimentalFeatureListParams { cursor, limit } = params; - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; let auth = self.auth_manager.auth().await; let workspace_codex_plugins_enabled = self .workspace_codex_plugins_enabled(&config, auth.as_ref()) @@ -5778,16 +5242,10 @@ impl CodexMessageProcessor { let total = data.len(); if total == 0 { - self.outgoing - .send_response( - request_id, - ExperimentalFeatureListResponse { - data: Vec::new(), - next_cursor: None, - }, - ) - .await; - return; + return Ok(ExperimentalFeatureListResponse { + data: Vec::new(), + next_cursor: None, + }); } // Clamp to 1 so limit=0 cannot return a non-advancing page. @@ -5796,25 +5254,15 @@ impl CodexMessageProcessor { let start = match cursor { Some(cursor) => match cursor.parse::() { Ok(idx) => idx, - Err(_) => { - self.send_invalid_request_error( - request_id, - format!("invalid cursor: {cursor}"), - ) - .await; - return; - } + Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))), }, None => 0, }; if start > total { - self.send_invalid_request_error( - request_id, - format!("cursor {start} exceeds total feature flags {total}"), - ) - .await; - return; + return Err(invalid_request(format!( + "cursor {start} exceeds total feature flags {total}" + ))); } let end = start.saturating_add(effective_limit).min(total); @@ -5825,12 +5273,7 @@ impl CodexMessageProcessor { None }; - self.outgoing - .send_response( - request_id, - ExperimentalFeatureListResponse { data, next_cursor }, - ) - .await; + Ok(ExperimentalFeatureListResponse { data, next_cursor }) } async fn mock_experimental_method( @@ -5844,21 +5287,13 @@ impl CodexMessageProcessor { } async fn mcp_server_refresh(&self, request_id: ConnectionRequestId, _params: Option<()>) { - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - if let Err(error) = self.queue_mcp_server_refresh_for_config(&config).await { - self.outgoing.send_error(request_id, error).await; - return; + let result = async { + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; + self.queue_mcp_server_refresh_for_config(&config).await?; + Ok::<_, JSONRPCErrorError>(McpServerRefreshResponse {}) } - - let response = McpServerRefreshResponse {}; - self.outgoing.send_response(request_id, response).await; + .await; + self.outgoing.send_result(request_id, result).await; } async fn queue_mcp_server_refresh_for_config( @@ -5912,14 +5347,15 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: McpServerOauthLoginParams, ) { - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let result = self.mcp_server_oauth_login_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + async fn mcp_server_oauth_login_response( + &self, + params: McpServerOauthLoginParams, + ) -> Result { + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; let McpServerOauthLoginParams { name, scopes, @@ -5932,13 +5368,9 @@ impl CodexMessageProcessor { .configured_servers(&config) .await; let Some(server) = configured_servers.get(&name) else { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("No MCP server named '{name}' found."), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request(format!( + "No MCP server named '{name}' found." + ))); }; let (url, http_headers, env_http_headers) = match &server.transport { @@ -5949,14 +5381,9 @@ impl CodexMessageProcessor { .. } => (url.clone(), http_headers.clone(), env_http_headers.clone()), _ => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "OAuth login is only supported for streamable HTTP servers." - .to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request( + "OAuth login is only supported for streamable HTTP servers.", + )); } }; @@ -5968,7 +5395,7 @@ impl CodexMessageProcessor { let resolved_scopes = resolve_oauth_scopes(scopes, server.scopes.clone(), discovered_scopes); - match perform_oauth_login_return_url( + let handle = perform_oauth_login_return_url( &name, &url, config.mcp_oauth_credentials_store_mode, @@ -5981,40 +5408,28 @@ impl CodexMessageProcessor { config.mcp_oauth_callback_url.as_deref(), ) .await - { - Ok(handle) => { - let authorization_url = handle.authorization_url().to_string(); - let notification_name = name.clone(); - let outgoing = Arc::clone(&self.outgoing); + .map_err(|err| internal_error(format!("failed to login to MCP server '{name}': {err}")))?; + let authorization_url = handle.authorization_url().to_string(); + let notification_name = name.clone(); + let outgoing = Arc::clone(&self.outgoing); - tokio::spawn(async move { - let (success, error) = match handle.wait().await { - Ok(()) => (true, None), - Err(err) => (false, Some(err.to_string())), - }; + tokio::spawn(async move { + let (success, error) = match handle.wait().await { + Ok(()) => (true, None), + Err(err) => (false, Some(err.to_string())), + }; - let notification = ServerNotification::McpServerOauthLoginCompleted( - McpServerOauthLoginCompletedNotification { - name: notification_name, - success, - error, - }, - ); - outgoing.send_server_notification(notification).await; - }); + let notification = ServerNotification::McpServerOauthLoginCompleted( + McpServerOauthLoginCompletedNotification { + name: notification_name, + success, + error, + }, + ); + outgoing.send_server_notification(notification).await; + }); - let response = McpServerOauthLoginResponse { authorization_url }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to login to MCP server '{name}': {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } + Ok(McpServerOauthLoginResponse { authorization_url }) } async fn list_mcp_server_status( @@ -6072,6 +5487,26 @@ impl CodexMessageProcessor { auth: Option, runtime_environment: McpRuntimeEnvironment, ) { + let result = Self::list_mcp_server_status_response( + request_id.request_id.to_string(), + params, + config, + mcp_config, + auth, + runtime_environment, + ) + .await; + outgoing.send_result(request_id, result).await; + } + + async fn list_mcp_server_status_response( + request_id: String, + params: ListMcpServerStatusParams, + config: Config, + mcp_config: codex_mcp::McpConfig, + auth: Option, + runtime_environment: McpRuntimeEnvironment, + ) -> Result { let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) { McpServerStatusDetail::Full => McpSnapshotDetail::Full, McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly, @@ -6080,7 +5515,7 @@ impl CodexMessageProcessor { let snapshot = collect_mcp_server_status_snapshot_with_detail( &mcp_config, auth.as_ref(), - request_id.request_id.to_string(), + request_id, runtime_environment, detail, ) @@ -6115,27 +5550,15 @@ impl CodexMessageProcessor { 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; - } + Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))), }, 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; + return Err(invalid_request(format!( + "cursor {start} exceeds total MCP servers {total}" + ))); } let end = start.saturating_add(effective_limit).min(total); @@ -6161,9 +5584,7 @@ impl CodexMessageProcessor { None }; - let response = ListMcpServerStatusResponse { data, next_cursor }; - - outgoing.send_response(request_id, response).await; + Ok(ListMcpServerStatusResponse { data, next_cursor }) } async fn read_mcp_resource( @@ -6237,39 +5658,16 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, result: anyhow::Result, ) { - match result { - Ok(result) => match serde_json::from_value::(result) { - Ok(response) => { - outgoing.send_response(request_id, response).await; - } - Err(error) => { - outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "failed to deserialize MCP resource read response: {error}" - ), - data: None, - }, - ) - .await; - } - }, - Err(error) => { - outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("{error:#}"), - data: None, - }, - ) - .await; - } - } + let result = result + .map_err(|error| internal_error(format!("{error:#}"))) + .and_then(|result| { + serde_json::from_value::(result).map_err(|error| { + internal_error(format!( + "failed to deserialize MCP resource read response: {error}" + )) + }) + }); + outgoing.send_result(request_id, result).await; } async fn call_mcp_server_tool( @@ -6291,36 +5689,27 @@ impl CodexMessageProcessor { tokio::spawn(async move { let result = thread .call_mcp_tool(¶ms.server, ¶ms.tool, params.arguments, meta) - .await; - match result { - Ok(result) => { - outgoing - .send_response(request_id, McpServerToolCallResponse::from(result)) - .await; - } - Err(error) => { - outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("{error:#}"), - data: None, - }, - ) - .await; - } - } + .await + .map(McpServerToolCallResponse::from) + .map_err(|error| internal_error(format!("{error:#}"))); + outgoing.send_result(request_id, result).await; }); } - async fn send_invalid_request_error(&self, request_id: ConnectionRequestId, message: String) { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message, - data: None, - }; - self.outgoing.send_error(request_id, error).await; + async fn send_optional_result( + &self, + request_id: ConnectionRequestId, + result: Result, JSONRPCErrorError>, + ) where + T: serde::Serialize, + { + match result { + Ok(Some(response)) => self.outgoing.send_response(request_id, response).await, + Ok(None) => {} + Err(error) => { + self.outgoing.send_error(request_id, error).await; + } + } } fn input_too_large_error(actual_chars: usize) -> JSONRPCErrorError { @@ -6345,41 +5734,6 @@ impl CodexMessageProcessor { Ok(()) } - async fn send_internal_error(&self, request_id: ConnectionRequestId, message: String) { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message, - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - - async fn send_marketplace_error( - &self, - request_id: ConnectionRequestId, - err: MarketplaceError, - action: &str, - ) { - match err { - MarketplaceError::MarketplaceNotFound { .. } => { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - } - MarketplaceError::Io { .. } => { - self.send_internal_error(request_id, format!("failed to {action}: {err}")) - .await; - } - MarketplaceError::InvalidMarketplaceFile { .. } - | MarketplaceError::PluginNotFound { .. } - | MarketplaceError::PluginNotAvailable { .. } - | MarketplaceError::PluginsDisabled - | MarketplaceError::InvalidPlugin(_) => { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - } - } - } - async fn wait_for_thread_shutdown(thread: &Arc) -> ThreadShutdownResult { match tokio::time::timeout(Duration::from_secs(10), thread.shutdown_and_wait()).await { Ok(Ok(())) => ThreadShutdownResult::Complete, @@ -6458,34 +5812,33 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadUnsubscribeParams, ) { - let thread_id = match ThreadId::from_string(¶ms.thread_id) { - Ok(id) => id, - Err(err) => { - self.send_invalid_request_error(request_id, format!("invalid thread id: {err}")) - .await; - return; - } - }; + let result = self + .thread_unsubscribe_response(params, request_id.connection_id) + .await; + self.outgoing.send_result(request_id, result).await; + } + + async fn thread_unsubscribe_response( + &self, + params: ThreadUnsubscribeParams, + connection_id: ConnectionId, + ) -> Result { + let thread_id = ThreadId::from_string(¶ms.thread_id) + .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; if self.thread_manager.get_thread(thread_id).await.is_err() { // Reconcile stale app-server bookkeeping when the thread has already been // removed from the core manager. This keeps loaded-status/subscription state // consistent with the source of truth before reporting NotLoaded. self.finalize_thread_teardown(thread_id).await; - self.outgoing - .send_response( - request_id, - ThreadUnsubscribeResponse { - status: ThreadUnsubscribeStatus::NotLoaded, - }, - ) - .await; - return; + return Ok(ThreadUnsubscribeResponse { + status: ThreadUnsubscribeStatus::NotLoaded, + }); }; let was_subscribed = self .thread_state_manager - .unsubscribe_connection_from_thread(thread_id, request_id.connection_id) + .unsubscribe_connection_from_thread(thread_id, connection_id) .await; let status = if was_subscribed { @@ -6493,9 +5846,7 @@ impl CodexMessageProcessor { } else { ThreadUnsubscribeStatus::NotSubscribed }; - self.outgoing - .send_response(request_id, ThreadUnsubscribeResponse { status }) - .await; + Ok(ThreadUnsubscribeResponse { status }) } async fn prepare_thread_for_archive(&self, thread_id: ThreadId) { @@ -6589,6 +5940,16 @@ impl CodexMessageProcessor { config: Config, environment_manager: Arc, ) { + let result = Self::apps_list_response(&outgoing, params, config, environment_manager).await; + outgoing.send_result(request_id, result).await; + } + + async fn apps_list_response( + outgoing: &Arc, + params: AppsListParams, + config: Config, + environment_manager: Arc, + ) -> Result { let AppsListParams { cursor, limit, @@ -6598,15 +5959,7 @@ impl CodexMessageProcessor { let start = match 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; - } + Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))), }, None => 0, }; @@ -6660,7 +6013,7 @@ impl CodexMessageProcessor { accessible_loaded, all_loaded, ) { - apps_list_helpers::send_app_list_updated_notification(&outgoing, merged.clone()) + apps_list_helpers::send_app_list_updated_notification(outgoing, merged.clone()) .await; last_notified_apps = Some(merged); } @@ -6670,25 +6023,13 @@ impl CodexMessageProcessor { let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await { Ok(Some(result)) => result, Ok(None) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "failed to load app lists".to_string(), - data: None, - }; - outgoing.send_error(request_id, error).await; - return; + return Err(internal_error("failed to load app lists")); } Err(_) => { let timeout_seconds = APP_LIST_LOAD_TIMEOUT.as_secs(); - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "timed out waiting for app lists after {timeout_seconds} seconds" - ), - data: None, - }; - outgoing.send_error(request_id, error).await; - return; + return Err(internal_error(format!( + "timed out waiting for app lists after {timeout_seconds} seconds" + ))); } }; @@ -6698,26 +6039,14 @@ impl CodexMessageProcessor { accessible_loaded = true; } AppListLoadResult::Accessible(Err(err)) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err, - data: None, - }; - outgoing.send_error(request_id, error).await; - return; + return Err(internal_error(err)); } AppListLoadResult::Directory(Ok(connectors)) => { all_connectors = Some(connectors); all_loaded = true; } AppListLoadResult::Directory(Err(err)) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err, - data: None, - }; - outgoing.send_error(request_id, error).await; - return; + return Err(internal_error(err)); } } @@ -6747,27 +6076,26 @@ impl CodexMessageProcessor { all_loaded, ) && last_notified_apps.as_ref() != Some(&merged) { - apps_list_helpers::send_app_list_updated_notification(&outgoing, merged.clone()) + apps_list_helpers::send_app_list_updated_notification(outgoing, merged.clone()) .await; last_notified_apps = Some(merged.clone()); } if accessible_loaded && all_loaded { - match apps_list_helpers::paginate_apps(merged.as_slice(), start, limit) { - Ok(response) => { - outgoing.send_response(request_id, response).await; - return; - } - Err(error) => { - outgoing.send_error(request_id, error).await; - return; - } - } + return apps_list_helpers::paginate_apps(merged.as_slice(), start, limit); } } } async fn skills_list(&self, request_id: ConnectionRequestId, params: SkillsListParams) { + let result = self.skills_list_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn skills_list_response( + &self, + params: SkillsListParams, + ) -> Result { let SkillsListParams { cwds, force_reload, @@ -6792,17 +6120,13 @@ impl CodexMessageProcessor { let mut valid_extra_roots = Vec::new(); for root in entry.extra_user_roots { - let Ok(root) = AbsolutePathBuf::from_absolute_path_checked(root.as_path()) else { - self.send_invalid_request_error( - request_id, - format!( + let root = + AbsolutePathBuf::from_absolute_path_checked(root.as_path()).map_err(|_| { + invalid_request(format!( "skills/list perCwdExtraUserRoots extraUserRoots paths must be absolute: {}", root.display() - ), - ) - .await; - return; - }; + )) + })?; valid_extra_roots.push(root); } extra_roots_by_cwd @@ -6811,13 +6135,7 @@ impl CodexMessageProcessor { .extend(valid_extra_roots); } - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; let auth = self.auth_manager.auth().await; let workspace_codex_plugins_enabled = self .workspace_codex_plugins_enabled(&config, auth.as_ref()) @@ -6896,9 +6214,7 @@ impl CodexMessageProcessor { errors, }); } - self.outgoing - .send_response(request_id, SkillsListResponse { data }) - .await; + Ok(SkillsListResponse { data }) } async fn marketplace_remove( &self, @@ -6911,27 +6227,16 @@ impl CodexMessageProcessor { marketplace_name: params.marketplace_name, }, ) - .await; - - match result { - Ok(outcome) => { - self.outgoing - .send_response( - request_id, - MarketplaceRemoveResponse { - marketplace_name: outcome.marketplace_name, - installed_root: outcome.removed_installed_root, - }, - ) - .await; - } - Err(MarketplaceRemoveError::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(MarketplaceRemoveError::Internal(message)) => { - self.send_internal_error(request_id, message).await; - } - } + .await + .map(|outcome| MarketplaceRemoveResponse { + marketplace_name: outcome.marketplace_name, + installed_root: outcome.removed_installed_root, + }) + .map_err(|err| match err { + MarketplaceRemoveError::InvalidRequest(message) => invalid_request(message), + MarketplaceRemoveError::Internal(message) => internal_error(message), + }); + self.outgoing.send_result(request_id, result).await; } async fn marketplace_upgrade( @@ -6939,53 +6244,38 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: MarketplaceUpgradeParams, ) { - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } - }; + let result = self.marketplace_upgrade_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn marketplace_upgrade_response( + &self, + params: MarketplaceUpgradeParams, + ) -> Result { + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; let plugins_manager = self.thread_manager.plugins_manager(); let MarketplaceUpgradeParams { marketplace_name } = params; - let result = tokio::task::spawn_blocking(move || { + let outcome = tokio::task::spawn_blocking(move || { plugins_manager .upgrade_configured_marketplaces_for_config(&config, marketplace_name.as_deref()) }) - .await; + .await + .map_err(|err| internal_error(format!("failed to upgrade marketplaces: {err}")))? + .map_err(invalid_request)?; - match result { - Ok(Ok(outcome)) => { - self.outgoing - .send_response( - request_id, - MarketplaceUpgradeResponse { - selected_marketplaces: outcome.selected_marketplaces, - upgraded_roots: outcome.upgraded_roots, - errors: outcome - .errors - .into_iter() - .map(|err| MarketplaceUpgradeErrorInfo { - marketplace_name: err.marketplace_name, - message: err.message, - }) - .collect(), - }, - ) - .await; - } - Ok(Err(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to upgrade marketplaces: {err}"), - ) - .await; - } - } + Ok(MarketplaceUpgradeResponse { + selected_marketplaces: outcome.selected_marketplaces, + upgraded_roots: outcome.upgraded_roots, + errors: outcome + .errors + .into_iter() + .map(|err| MarketplaceUpgradeErrorInfo { + marketplace_name: err.marketplace_name, + message: err.message, + }) + .collect(), + }) } async fn marketplace_add(&self, request_id: ConnectionRequestId, params: MarketplaceAddParams) { @@ -6997,28 +6287,17 @@ impl CodexMessageProcessor { sparse_paths: params.sparse_paths.unwrap_or_default(), }, ) - .await; - - match result { - Ok(outcome) => { - self.outgoing - .send_response( - request_id, - MarketplaceAddResponse { - marketplace_name: outcome.marketplace_name, - installed_root: outcome.installed_root, - already_added: outcome.already_added, - }, - ) - .await; - } - Err(MarketplaceAddError::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(MarketplaceAddError::Internal(message)) => { - self.send_internal_error(request_id, message).await; - } - } + .await + .map(|outcome| MarketplaceAddResponse { + marketplace_name: outcome.marketplace_name, + installed_root: outcome.installed_root, + already_added: outcome.already_added, + }) + .map_err(|err| match err { + MarketplaceAddError::InvalidRequest(message) => invalid_request(message), + MarketplaceAddError::Internal(message) => internal_error(message), + }); + self.outgoing.send_result(request_id, result).await; } async fn skills_config_write( @@ -7026,6 +6305,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: SkillsConfigWriteParams, ) { + let result = self.skills_config_write_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn skills_config_write_response( + &self, + params: SkillsConfigWriteParams, + ) -> Result { let SkillsConfigWriteParams { path, name, @@ -7040,43 +6327,24 @@ impl CodexMessageProcessor { ConfigEdit::SetSkillConfigByName { name, enabled } } _ => { - let error = JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message: "skills/config/write requires exactly one of path or name".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_params( + "skills/config/write requires exactly one of path or name", + )); } }; let edits = vec![edit]; - let result = ConfigEditsBuilder::new(&self.config.codex_home) + ConfigEditsBuilder::new(&self.config.codex_home) .with_edits(edits) .apply() - .await; - - match result { - Ok(()) => { + .await + .map(|()| { self.thread_manager.plugins_manager().clear_cache(); self.thread_manager.skills_manager().clear_cache(); - self.outgoing - .send_response( - request_id, - SkillsConfigWriteResponse { - effective_enabled: enabled, - }, - ) - .await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to update skill settings: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } + SkillsConfigWriteResponse { + effective_enabled: enabled, + } + }) + .map_err(|err| internal_error(format!("failed to update skill settings: {err}"))) } async fn turn_start( @@ -7086,198 +6354,183 @@ impl CodexMessageProcessor { app_server_client_name: Option, app_server_client_version: Option, ) { - if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { - self.track_error_response( - &request_id, - &error, - Some(AnalyticsJsonRpcError::Input(InputError::TooLarge)), - ); - self.outgoing.send_error(request_id, error).await; - return; - } - let (_, thread) = match self.load_thread(¶ms.thread_id).await { - Ok(v) => v, - Err(error) => { - self.track_error_response(&request_id, &error, /*error_type*/ None); - self.outgoing.send_error(request_id, error).await; - return; + let result = async { + if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { + self.track_error_response( + &request_id, + &error, + Some(AnalyticsJsonRpcError::Input(InputError::TooLarge)), + ); + return Err(error); } - }; - if let Err(error) = Self::set_app_server_client_info( - thread.as_ref(), - app_server_client_name, - app_server_client_version, - ) - .await - { - self.track_error_response(&request_id, &error, /*error_type*/ None); - self.outgoing.send_error(request_id, error).await; - return; - } - - let collaboration_modes_config = CollaborationModesConfig { - default_mode_request_user_input: thread.enabled(Feature::DefaultModeRequestUserInput), - }; - let collaboration_mode = params.collaboration_mode.map(|mode| { - self.normalize_turn_start_collaboration_mode(mode, collaboration_modes_config) - }); - let environments: Option> = - params.environments.map(|environments| { - environments - .into_iter() - .map(|environment| TurnEnvironmentSelection { - environment_id: environment.environment_id, - cwd: environment.cwd, - }) - .collect() - }); - if let Some(environments) = environments.as_ref() - && let Err(err) = self - .thread_manager - .validate_environment_selections(environments) - { - self.send_invalid_request_error(request_id, environment_selection_error_message(err)) - .await; - return; - } - - // Map v2 input items to core input items. - let mapped_items: Vec = params - .input - .into_iter() - .map(V2UserInput::into_core) - .collect(); - - let has_any_overrides = params.cwd.is_some() - || params.approval_policy.is_some() - || params.approvals_reviewer.is_some() - || params.sandbox_policy.is_some() - || params.permission_profile.is_some() - || params.model.is_some() - || params.service_tier.is_some() - || params.effort.is_some() - || params.summary.is_some() - || collaboration_mode.is_some() - || params.personality.is_some(); - - if params.sandbox_policy.is_some() && params.permission_profile.is_some() { - self.send_invalid_request_error( - request_id, - "`permissionProfile` cannot be combined with `sandboxPolicy`".to_string(), + let (_, thread) = self + .load_thread(¶ms.thread_id) + .await + .inspect_err(|error| { + self.track_error_response(&request_id, error, /*error_type*/ None); + })?; + Self::set_app_server_client_info( + thread.as_ref(), + app_server_client_name, + app_server_client_version, ) - .await; - return; - } + .await + .inspect_err(|error| { + self.track_error_response(&request_id, error, /*error_type*/ None); + })?; - let cwd = params.cwd; - let approval_policy = params.approval_policy.map(AskForApproval::to_core); - let approvals_reviewer = params - .approvals_reviewer - .map(codex_app_server_protocol::ApprovalsReviewer::to_core); - let sandbox_policy = params.sandbox_policy.map(|p| p.to_core()); - let permission_profile = params.permission_profile.map(Into::into); - let model = params.model; - let effort = params.effort.map(Some); - let summary = params.summary; - let service_tier = params.service_tier; - let personality = params.personality; + let collaboration_modes_config = CollaborationModesConfig { + default_mode_request_user_input: thread + .enabled(Feature::DefaultModeRequestUserInput), + }; + let collaboration_mode = params.collaboration_mode.map(|mode| { + self.normalize_turn_start_collaboration_mode(mode, collaboration_modes_config) + }); + let environments: Option> = + params.environments.map(|environments| { + environments + .into_iter() + .map(|environment| TurnEnvironmentSelection { + environment_id: environment.environment_id, + cwd: environment.cwd, + }) + .collect() + }); + if let Some(environments) = environments.as_ref() { + self.thread_manager + .validate_environment_selections(environments) + .map_err(|err| invalid_request(environment_selection_error_message(err)))?; + } - // If any overrides are provided, validate them synchronously so the - // request can fail before accepting user input. The actual update is - // still queued together with the input below to preserve submission order. - if has_any_overrides { - let result = thread - .validate_turn_context_overrides(CodexThreadTurnContextOverrides { - cwd: cwd.clone(), + // Map v2 input items to core input items. + let mapped_items: Vec = params + .input + .into_iter() + .map(V2UserInput::into_core) + .collect(); + + let has_any_overrides = params.cwd.is_some() + || params.approval_policy.is_some() + || params.approvals_reviewer.is_some() + || params.sandbox_policy.is_some() + || params.permission_profile.is_some() + || params.model.is_some() + || params.service_tier.is_some() + || params.effort.is_some() + || params.summary.is_some() + || collaboration_mode.is_some() + || params.personality.is_some(); + + if params.sandbox_policy.is_some() && params.permission_profile.is_some() { + return Err(invalid_request( + "`permissionProfile` cannot be combined with `sandboxPolicy`", + )); + } + + let cwd = params.cwd; + let approval_policy = params.approval_policy.map(AskForApproval::to_core); + let approvals_reviewer = params + .approvals_reviewer + .map(codex_app_server_protocol::ApprovalsReviewer::to_core); + let sandbox_policy = params.sandbox_policy.map(|p| p.to_core()); + let permission_profile = params.permission_profile.map(Into::into); + let model = params.model; + let effort = params.effort.map(Some); + let summary = params.summary; + let service_tier = params.service_tier; + let personality = params.personality; + + // If any overrides are provided, validate them synchronously so the + // request can fail before accepting user input. The actual update is + // still queued together with the input below to preserve submission order. + if has_any_overrides { + thread + .validate_turn_context_overrides(CodexThreadTurnContextOverrides { + cwd: cwd.clone(), + approval_policy, + approvals_reviewer, + sandbox_policy: sandbox_policy.clone(), + permission_profile: permission_profile.clone(), + windows_sandbox_level: None, + model: model.clone(), + effort, + summary, + service_tier, + collaboration_mode: collaboration_mode.clone(), + personality, + }) + .await + .map_err(|err| { + invalid_request(format!("invalid turn context override: {err}")) + })?; + } + + // Start the turn by submitting the user input. Return its submission id as turn_id. + let turn_op = if has_any_overrides { + Op::UserInputWithTurnContext { + items: mapped_items, + environments, + final_output_json_schema: params.output_schema, + responsesapi_client_metadata: params.responsesapi_client_metadata, + cwd, approval_policy, approvals_reviewer, - sandbox_policy: sandbox_policy.clone(), - permission_profile: permission_profile.clone(), + sandbox_policy, + permission_profile, windows_sandbox_level: None, - model: model.clone(), + model, effort, summary, service_tier, - collaboration_mode: collaboration_mode.clone(), + collaboration_mode, personality, - }) - .await; - if let Err(err) = result { - self.send_invalid_request_error( - request_id, - format!("invalid turn context override: {err}"), - ) - .await; - return; - } - } - - // Start the turn by submitting the user input. Return its submission id as turn_id. - let turn_op = if has_any_overrides { - Op::UserInputWithTurnContext { - items: mapped_items, - environments, - final_output_json_schema: params.output_schema, - responsesapi_client_metadata: params.responsesapi_client_metadata, - cwd, - approval_policy, - approvals_reviewer, - sandbox_policy, - permission_profile, - windows_sandbox_level: None, - model, - effort, - summary, - service_tier, - collaboration_mode, - personality, - } - } else { - Op::UserInput { - items: mapped_items, - environments, - final_output_json_schema: params.output_schema, - responsesapi_client_metadata: params.responsesapi_client_metadata, - } - }; - let turn_id = self - .submit_core_op(&request_id, thread.as_ref(), turn_op) - .await; - - match turn_id { - Ok(turn_id) => { - self.outgoing - .record_request_turn_id(&request_id, &turn_id) - .await; - let turn = Turn { - id: turn_id.clone(), - items: vec![], - error: None, - status: TurnStatus::InProgress, - started_at: None, - completed_at: None, - duration_ms: None, - }; - - let response = TurnStartResponse { turn }; - if self.config.features.enabled(Feature::GeneralAnalytics) { - self.analytics_events_client.track_response( - request_id.connection_id.0, - ClientResponse::TurnStart { - request_id: request_id.request_id.clone(), - response: response.clone(), - }, - ); } + } else { + Op::UserInput { + items: mapped_items, + environments, + final_output_json_schema: params.output_schema, + responsesapi_client_metadata: params.responsesapi_client_metadata, + } + }; + let turn_id = self + .submit_core_op(&request_id, thread.as_ref(), turn_op) + .await + .map_err(|err| { + let error = internal_error(format!("failed to start turn: {err}")); + self.track_error_response(&request_id, &error, /*error_type*/ None); + error + })?; + + self.outgoing + .record_request_turn_id(&request_id, &turn_id) + .await; + let turn = Turn { + id: turn_id, + items: vec![], + error: None, + status: TurnStatus::InProgress, + started_at: None, + completed_at: None, + duration_ms: None, + }; + + Ok::<_, JSONRPCErrorError>(TurnStartResponse { turn }) + } + .await; + + match result { + Ok(response) => { + self.analytics_events_client.track_response( + request_id.connection_id.0, + ClientResponse::TurnStart { + request_id: request_id.request_id.clone(), + response: response.clone(), + }, + ); self.outgoing.send_response(request_id, response).await; } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to start turn: {err}"), - data: None, - }; - self.track_error_response(&request_id, &error, /*error_type*/ None); + Err(error) => { self.outgoing.send_error(request_id, error).await; } } @@ -7288,15 +6541,17 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadInjectItemsParams, ) { - let (_, thread) = match self.load_thread(¶ms.thread_id).await { - Ok(value) => value, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let result = self.thread_inject_items_response(params).await; + self.outgoing.send_result(request_id, result).await; + } - let items = match params + async fn thread_inject_items_response( + &self, + params: ThreadInjectItemsParams, + ) -> Result { + let (_, thread) = self.load_thread(¶ms.thread_id).await?; + + let items = params .items .into_iter() .enumerate() @@ -7305,31 +6560,16 @@ impl CodexMessageProcessor { .map_err(|err| format!("items[{index}] is not a valid response item: {err}")) }) .collect::, _>>() - { - Ok(items) => items, - Err(message) => { - self.send_invalid_request_error(request_id, message).await; - return; - } - }; + .map_err(invalid_request)?; - match thread.inject_response_items(items).await { - Ok(()) => { - self.outgoing - .send_response(request_id, ThreadInjectItemsResponse {}) - .await; - } - Err(CodexErr::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to inject response items: {err}"), - ) - .await; - } - } + thread + .inject_response_items(items) + .await + .map_err(|err| match err { + CodexErr::InvalidRequest(message) => invalid_request(message), + err => internal_error(format!("failed to inject response items: {err}")), + })?; + Ok(ThreadInjectItemsResponse {}) } async fn set_app_server_client_info( @@ -7348,129 +6588,126 @@ impl CodexMessageProcessor { } async fn turn_steer(&self, request_id: ConnectionRequestId, params: TurnSteerParams) { - let (_, thread) = match self.load_thread(¶ms.thread_id).await { - Ok(v) => v, - Err(error) => { - self.track_error_response(&request_id, &error, /*error_type*/ None); - self.outgoing.send_error(request_id, error).await; - return; + let result = async { + let (_, thread) = self + .load_thread(¶ms.thread_id) + .await + .inspect_err(|error| { + self.track_error_response(&request_id, error, /*error_type*/ None); + })?; + + if params.expected_turn_id.is_empty() { + return Err(invalid_request("expectedTurnId must not be empty")); + } + self.outgoing + .record_request_turn_id(&request_id, ¶ms.expected_turn_id) + .await; + if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { + self.track_error_response( + &request_id, + &error, + Some(AnalyticsJsonRpcError::Input(InputError::TooLarge)), + ); + return Err(error); } - }; - if params.expected_turn_id.is_empty() { - self.send_invalid_request_error( - request_id, - "expectedTurnId must not be empty".to_string(), - ) - .await; - return; - } - self.outgoing - .record_request_turn_id(&request_id, ¶ms.expected_turn_id) - .await; - if let Err(error) = Self::validate_v2_input_limit(¶ms.input) { - self.track_error_response( - &request_id, - &error, - Some(AnalyticsJsonRpcError::Input(InputError::TooLarge)), - ); - self.outgoing.send_error(request_id, error).await; - return; + let mapped_items: Vec = params + .input + .into_iter() + .map(V2UserInput::into_core) + .collect(); + + let turn_id = thread + .steer_input( + mapped_items, + Some(¶ms.expected_turn_id), + params.responsesapi_client_metadata, + ) + .await + .map_err(|err| { + let (code, message, data, error_type) = match err { + SteerInputError::NoActiveTurn(_) => ( + INVALID_REQUEST_ERROR_CODE, + "no active turn to steer".to_string(), + None, + Some(AnalyticsJsonRpcError::TurnSteer( + TurnSteerRequestError::NoActiveTurn, + )), + ), + SteerInputError::ExpectedTurnMismatch { expected, actual } => ( + INVALID_REQUEST_ERROR_CODE, + format!("expected active turn id `{expected}` but found `{actual}`"), + None, + Some(AnalyticsJsonRpcError::TurnSteer( + TurnSteerRequestError::ExpectedTurnMismatch, + )), + ), + SteerInputError::ActiveTurnNotSteerable { turn_kind } => { + let (message, turn_steer_error) = match turn_kind { + codex_protocol::protocol::NonSteerableTurnKind::Review => ( + "cannot steer a review turn".to_string(), + TurnSteerRequestError::NonSteerableReview, + ), + codex_protocol::protocol::NonSteerableTurnKind::Compact => ( + "cannot steer a compact turn".to_string(), + TurnSteerRequestError::NonSteerableCompact, + ), + }; + let error = TurnError { + message: message.clone(), + codex_error_info: Some(CodexErrorInfo::ActiveTurnNotSteerable { + turn_kind: turn_kind.into(), + }), + additional_details: None, + }; + let data = match serde_json::to_value(error) { + Ok(data) => Some(data), + Err(error) => { + tracing::error!( + ?error, + "failed to serialize active-turn-not-steerable turn error" + ); + None + } + }; + ( + INVALID_REQUEST_ERROR_CODE, + message, + data, + Some(AnalyticsJsonRpcError::TurnSteer(turn_steer_error)), + ) + } + SteerInputError::EmptyInput => ( + INVALID_REQUEST_ERROR_CODE, + "input must not be empty".to_string(), + None, + Some(AnalyticsJsonRpcError::Input(InputError::Empty)), + ), + }; + let error = JSONRPCErrorError { + code, + message, + data, + }; + self.track_error_response(&request_id, &error, error_type); + error + })?; + Ok::<_, JSONRPCErrorError>(TurnSteerResponse { turn_id }) } + .await; - let mapped_items: Vec = params - .input - .into_iter() - .map(V2UserInput::into_core) - .collect(); - - match thread - .steer_input( - mapped_items, - Some(¶ms.expected_turn_id), - params.responsesapi_client_metadata, - ) - .await - { - Ok(turn_id) => { - let response = TurnSteerResponse { turn_id }; - if self.config.features.enabled(Feature::GeneralAnalytics) { - self.analytics_events_client.track_response( - request_id.connection_id.0, - ClientResponse::TurnSteer { - request_id: request_id.request_id.clone(), - response: response.clone(), - }, - ); - } + match result { + Ok(response) => { + self.analytics_events_client.track_response( + request_id.connection_id.0, + ClientResponse::TurnSteer { + request_id: request_id.request_id.clone(), + response: response.clone(), + }, + ); self.outgoing.send_response(request_id, response).await; } - Err(err) => { - let (code, message, data, error_type) = match err { - SteerInputError::NoActiveTurn(_) => ( - INVALID_REQUEST_ERROR_CODE, - "no active turn to steer".to_string(), - None, - Some(AnalyticsJsonRpcError::TurnSteer( - TurnSteerRequestError::NoActiveTurn, - )), - ), - SteerInputError::ExpectedTurnMismatch { expected, actual } => ( - INVALID_REQUEST_ERROR_CODE, - format!("expected active turn id `{expected}` but found `{actual}`"), - None, - Some(AnalyticsJsonRpcError::TurnSteer( - TurnSteerRequestError::ExpectedTurnMismatch, - )), - ), - SteerInputError::ActiveTurnNotSteerable { turn_kind } => { - let (message, turn_steer_error) = match turn_kind { - codex_protocol::protocol::NonSteerableTurnKind::Review => ( - "cannot steer a review turn".to_string(), - TurnSteerRequestError::NonSteerableReview, - ), - codex_protocol::protocol::NonSteerableTurnKind::Compact => ( - "cannot steer a compact turn".to_string(), - TurnSteerRequestError::NonSteerableCompact, - ), - }; - let error = TurnError { - message: message.clone(), - codex_error_info: Some(CodexErrorInfo::ActiveTurnNotSteerable { - turn_kind: turn_kind.into(), - }), - additional_details: None, - }; - let data = match serde_json::to_value(error) { - Ok(data) => Some(data), - Err(error) => { - tracing::error!( - ?error, - "failed to serialize active-turn-not-steerable turn error" - ); - None - } - }; - ( - INVALID_REQUEST_ERROR_CODE, - message, - data, - Some(AnalyticsJsonRpcError::TurnSteer(turn_steer_error)), - ) - } - SteerInputError::EmptyInput => ( - INVALID_REQUEST_ERROR_CODE, - "input must not be empty".to_string(), - None, - Some(AnalyticsJsonRpcError::Input(InputError::Empty)), - ), - }; - let error = JSONRPCErrorError { - code, - message, - data, - }; - self.track_error_response(&request_id, &error, error_type); + Err(error) => { self.outgoing.send_error(request_id, error).await; } } @@ -7478,16 +6715,10 @@ impl CodexMessageProcessor { async fn prepare_realtime_conversation_thread( &self, - request_id: ConnectionRequestId, + request_id: &ConnectionRequestId, thread_id: &str, - ) -> Option<(ThreadId, Arc)> { - let (thread_id, thread) = match self.load_thread(thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return None; - } - }; + ) -> Result)>, JSONRPCErrorError> { + let (thread_id, thread) = self.load_thread(thread_id).await?; match self .ensure_conversation_listener( @@ -7500,24 +6731,18 @@ impl CodexMessageProcessor { { Ok(EnsureConversationListenerResult::Attached) => {} Ok(EnsureConversationListenerResult::ConnectionClosed) => { - return None; - } - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return None; + return Ok(None); } + Err(error) => return Err(error), } if !thread.enabled(Feature::RealtimeConversation) { - self.send_invalid_request_error( - request_id, - format!("thread {thread_id} does not support realtime conversation"), - ) - .await; - return None; + return Err(invalid_request(format!( + "thread {thread_id} does not support realtime conversation" + ))); } - Some((thread_id, thread)) + Ok(Some((thread_id, thread))) } async fn thread_realtime_start( @@ -7525,15 +6750,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadRealtimeStartParams, ) { - let Some((_, thread)) = self - .prepare_realtime_conversation_thread(request_id.clone(), ¶ms.thread_id) - .await - else { - return; - }; - - let submit = self - .submit_core_op( + let result = async { + let Some((_, thread)) = self + .prepare_realtime_conversation_thread(&request_id, ¶ms.thread_id) + .await? + else { + return Ok(None); + }; + self.submit_core_op( &request_id, thread.as_ref(), Op::RealtimeConversationStart(ConversationStartParams { @@ -7551,22 +6775,14 @@ impl CodexMessageProcessor { voice: params.voice, }), ) - .await; - - match submit { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadRealtimeStartResponse::default()) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to start realtime conversation: {err}"), - ) - .await; - } + .await + .map_err(|err| { + internal_error(format!("failed to start realtime conversation: {err}")) + })?; + Ok::<_, JSONRPCErrorError>(Some(ThreadRealtimeStartResponse::default())) } + .await; + self.send_optional_result(request_id, result).await; } async fn thread_realtime_append_audio( @@ -7574,37 +6790,30 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadRealtimeAppendAudioParams, ) { - let Some((_, thread)) = self - .prepare_realtime_conversation_thread(request_id.clone(), ¶ms.thread_id) - .await - else { - return; - }; - - let submit = self - .submit_core_op( + let result = async { + let Some((_, thread)) = self + .prepare_realtime_conversation_thread(&request_id, ¶ms.thread_id) + .await? + else { + return Ok(None); + }; + self.submit_core_op( &request_id, thread.as_ref(), Op::RealtimeConversationAudio(ConversationAudioParams { frame: params.audio.into(), }), ) - .await; - - match submit { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadRealtimeAppendAudioResponse::default()) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to append realtime conversation audio: {err}"), - ) - .await; - } + .await + .map_err(|err| { + internal_error(format!( + "failed to append realtime conversation audio: {err}" + )) + })?; + Ok::<_, JSONRPCErrorError>(Some(ThreadRealtimeAppendAudioResponse::default())) } + .await; + self.send_optional_result(request_id, result).await; } async fn thread_realtime_append_text( @@ -7612,35 +6821,28 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadRealtimeAppendTextParams, ) { - let Some((_, thread)) = self - .prepare_realtime_conversation_thread(request_id.clone(), ¶ms.thread_id) - .await - else { - return; - }; - - let submit = self - .submit_core_op( + let result = async { + let Some((_, thread)) = self + .prepare_realtime_conversation_thread(&request_id, ¶ms.thread_id) + .await? + else { + return Ok(None); + }; + self.submit_core_op( &request_id, thread.as_ref(), Op::RealtimeConversationText(ConversationTextParams { text: params.text }), ) - .await; - - match submit { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadRealtimeAppendTextResponse::default()) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to append realtime conversation text: {err}"), - ) - .await; - } + .await + .map_err(|err| { + internal_error(format!( + "failed to append realtime conversation text: {err}" + )) + })?; + Ok::<_, JSONRPCErrorError>(Some(ThreadRealtimeAppendTextResponse::default())) } + .await; + self.send_optional_result(request_id, result).await; } async fn thread_realtime_stop( @@ -7648,31 +6850,22 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: ThreadRealtimeStopParams, ) { - let Some((_, thread)) = self - .prepare_realtime_conversation_thread(request_id.clone(), ¶ms.thread_id) - .await - else { - return; - }; - - let submit = self - .submit_core_op(&request_id, thread.as_ref(), Op::RealtimeConversationClose) - .await; - - match submit { - Ok(_) => { - self.outgoing - .send_response(request_id, ThreadRealtimeStopResponse::default()) - .await; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to stop realtime conversation: {err}"), - ) - .await; - } + let result = async { + let Some((_, thread)) = self + .prepare_realtime_conversation_thread(&request_id, ¶ms.thread_id) + .await? + else { + return Ok(None); + }; + self.submit_core_op(&request_id, thread.as_ref(), Op::RealtimeConversationClose) + .await + .map_err(|err| { + internal_error(format!("failed to stop realtime conversation: {err}")) + })?; + Ok::<_, JSONRPCErrorError>(Some(ThreadRealtimeStopResponse::default())) } + .await; + self.send_optional_result(request_id, result).await; } async fn thread_realtime_list_voices( @@ -7886,139 +7079,104 @@ impl CodexMessageProcessor { target, delivery, } = params; - let (parent_thread_id, parent_thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let (review_request, display_text) = match Self::review_request_from_target(target) { - Ok(value) => value, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } - }; - - let delivery = delivery.unwrap_or(ApiReviewDelivery::Inline).to_core(); - match delivery { - CoreReviewDelivery::Inline => { - if let Err(err) = self - .start_inline_review( + let result = async { + let (parent_thread_id, parent_thread) = self.load_thread(&thread_id).await?; + let (review_request, display_text) = Self::review_request_from_target(target)?; + match delivery.unwrap_or(ApiReviewDelivery::Inline).to_core() { + CoreReviewDelivery::Inline => { + self.start_inline_review( &request_id, parent_thread, review_request, display_text.as_str(), - thread_id.clone(), + thread_id, ) - .await - { - self.outgoing.send_error(request_id, err).await; + .await?; } - } - CoreReviewDelivery::Detached => { - if let Err(err) = self - .start_detached_review( + CoreReviewDelivery::Detached => { + self.start_detached_review( &request_id, parent_thread_id, parent_thread, review_request, display_text.as_str(), ) - .await - { - self.outgoing.send_error(request_id, err).await; + .await?; } } + Ok::<_, JSONRPCErrorError>(None::) } + .await; + self.send_optional_result(request_id, result).await; } async fn turn_interrupt(&self, request_id: ConnectionRequestId, params: TurnInterruptParams) { let TurnInterruptParams { thread_id, turn_id } = params; let is_startup_interrupt = turn_id.is_empty(); - let (thread_uuid, thread) = match self.load_thread(&thread_id).await { - Ok(v) => v, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; + let result = async { + let (thread_uuid, thread) = self.load_thread(&thread_id).await?; - // Record turn interrupts so we can reply when TurnAborted arrives. Startup - // interrupts do not have a turn and are acknowledged after submission. - if !is_startup_interrupt { - let thread_state = self.thread_state_manager.thread_state(thread_uuid).await; - let is_running = matches!(thread.agent_status().await, AgentStatus::Running); - let interrupt_outcome = { - let mut thread_state = thread_state.lock().await; - if let Some(active_turn) = thread_state.active_turn_snapshot() { - if active_turn.id != turn_id { - Err(format!( - "expected active turn id {turn_id} but found {}", - active_turn.id - )) - } else { - thread_state - .pending_interrupts - .push((request_id.clone(), ApiVersion::V2)); - Ok(()) + // Record turn interrupts so we can reply when TurnAborted arrives. Startup + // interrupts do not have a turn and are acknowledged after submission. + if !is_startup_interrupt { + let thread_state = self.thread_state_manager.thread_state(thread_uuid).await; + let is_running = matches!(thread.agent_status().await, AgentStatus::Running); + { + let mut thread_state = thread_state.lock().await; + if let Some(active_turn) = thread_state.active_turn_snapshot() { + if active_turn.id != turn_id { + return Err(invalid_request(format!( + "expected active turn id {turn_id} but found {}", + active_turn.id + ))); + } + } else if thread_state.last_terminal_turn_id.as_deref() + == Some(turn_id.as_str()) + || !is_running + { + return Err(invalid_request("no active turn to interrupt")); } - } else if thread_state.last_terminal_turn_id.as_deref() == Some(turn_id.as_str()) { - Err("no active turn to interrupt".to_string()) - } else if is_running { thread_state .pending_interrupts .push((request_id.clone(), ApiVersion::V2)); - Ok(()) - } else { - Err("no active turn to interrupt".to_string()) } - }; - if let Err(message) = interrupt_outcome { - self.send_invalid_request_error(request_id, message).await; - return; - } - self.outgoing - .record_request_turn_id(&request_id, &turn_id) - .await; - } - - // Submit the interrupt. Turn interrupts respond upon TurnAborted; startup - // interrupts respond here because startup cancellation has no turn event. - let submit_result = self - .submit_core_op(&request_id, thread.as_ref(), Op::Interrupt) - .await; - match submit_result { - Ok(_) if is_startup_interrupt => { self.outgoing - .send_response(request_id, TurnInterruptResponse {}) + .record_request_turn_id(&request_id, &turn_id) .await; } - Ok(_) => {} - Err(err) => { - if !is_startup_interrupt { - let thread_state = self.thread_state_manager.thread_state(thread_uuid).await; - let mut thread_state = thread_state.lock().await; - thread_state - .pending_interrupts - .retain(|(pending_request_id, _)| pending_request_id != &request_id); + + // Submit the interrupt. Turn interrupts respond upon TurnAborted; startup + // interrupts respond here because startup cancellation has no turn event. + match self + .submit_core_op(&request_id, thread.as_ref(), Op::Interrupt) + .await + { + Ok(_) if is_startup_interrupt => Ok(Some(TurnInterruptResponse {})), + Ok(_) => Ok(None), + Err(err) => { + if !is_startup_interrupt { + let thread_state = + self.thread_state_manager.thread_state(thread_uuid).await; + let mut thread_state = thread_state.lock().await; + thread_state + .pending_interrupts + .retain(|(pending_request_id, _)| pending_request_id != &request_id); + } + let interrupt_target = if is_startup_interrupt { + "startup" + } else { + "turn" + }; + Err(internal_error(format!( + "failed to interrupt {interrupt_target}: {err}" + ))) } - let interrupt_target = if is_startup_interrupt { - "startup" - } else { - "turn" - }; - self.send_internal_error( - request_id, - format!("failed to interrupt {interrupt_target}: {err}"), - ) - .await; } } + .await; + self.send_optional_result(request_id, result).await; } async fn ensure_conversation_listener( @@ -8030,12 +7188,12 @@ impl CodexMessageProcessor { ) -> Result { Self::ensure_conversation_listener_task( ListenerTaskContext { + auth_manager: Arc::clone(&self.auth_manager), thread_manager: Arc::clone(&self.thread_manager), thread_state_manager: self.thread_state_manager.clone(), outgoing: Arc::clone(&self.outgoing), pending_thread_unloads: Arc::clone(&self.pending_thread_unloads), analytics_events_client: self.analytics_events_client.clone(), - general_analytics_enabled: self.config.features.enabled(Feature::GeneralAnalytics), thread_watch_manager: self.thread_watch_manager.clone(), fallback_model_provider: self.config.model_provider_id.clone(), codex_home: self.config.codex_home.to_path_buf(), @@ -8148,12 +7306,12 @@ impl CodexMessageProcessor { ) -> Result<(), JSONRPCErrorError> { Self::ensure_listener_task_running_task( ListenerTaskContext { + auth_manager: Arc::clone(&self.auth_manager), thread_manager: Arc::clone(&self.thread_manager), thread_state_manager: self.thread_state_manager.clone(), outgoing: Arc::clone(&self.outgoing), pending_thread_unloads: Arc::clone(&self.pending_thread_unloads), analytics_events_client: self.analytics_events_client.clone(), - general_analytics_enabled: self.config.features.enabled(Feature::GeneralAnalytics), thread_watch_manager: self.thread_watch_manager.clone(), fallback_model_provider: self.config.model_provider_id.clone(), codex_home: self.config.codex_home.to_path_buf(), @@ -8197,12 +7355,12 @@ impl CodexMessageProcessor { thread_state.set_listener(cancel_tx, &conversation) }; let ListenerTaskContext { + auth_manager: _, outgoing, thread_manager, thread_state_manager, pending_thread_unloads, analytics_events_client: _, - general_analytics_enabled: _, thread_watch_manager, fallback_model_provider, codex_home, @@ -8278,9 +7436,7 @@ impl CodexMessageProcessor { conversation_id, conversation.clone(), thread_manager.clone(), - listener_task_context - .general_analytics_enabled - .then(|| listener_task_context.analytics_events_client.clone()), + Some(listener_task_context.analytics_events_client.clone()), thread_outgoing, thread_state.clone(), thread_watch_manager.clone(), @@ -8334,24 +7490,18 @@ impl CodexMessageProcessor { Ok(()) } async fn git_diff_to_origin(&self, request_id: ConnectionRequestId, cwd: PathBuf) { - let diff = git_diff_to_remote(&cwd).await; - match diff { - Some(value) => { - let response = GitDiffToRemoteResponse { - sha: value.sha, - diff: value.diff, - }; - self.outgoing.send_response(request_id, response).await; - } - None => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("failed to compute git diff to remote for cwd: {cwd:?}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } + let result = git_diff_to_remote(&cwd) + .await + .map(|value| GitDiffToRemoteResponse { + sha: value.sha, + diff: value.diff, + }) + .ok_or_else(|| { + invalid_request(format!( + "failed to compute git diff to remote for cwd: {cwd:?}" + )) + }); + self.outgoing.send_result(request_id, result).await; } async fn fuzzy_file_search( @@ -8403,38 +7553,29 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: FuzzyFileSearchSessionStartParams, ) { + let result = self.fuzzy_file_search_session_start_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn fuzzy_file_search_session_start_response( + &self, + params: FuzzyFileSearchSessionStartParams, + ) -> Result { let FuzzyFileSearchSessionStartParams { session_id, roots } = params; if session_id.is_empty() { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "sessionId must not be empty".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request("sessionId must not be empty")); } let session = - start_fuzzy_file_search_session(session_id.clone(), roots, self.outgoing.clone()); - match session { - Ok(session) => { - self.fuzzy_search_sessions - .lock() - .await - .insert(session_id, session); - self.outgoing - .send_response(request_id, FuzzyFileSearchSessionStartResponse {}) - .await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to start fuzzy file search session: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } + start_fuzzy_file_search_session(session_id.clone(), roots, self.outgoing.clone()) + .map_err(|err| { + internal_error(format!("failed to start fuzzy file search session: {err}")) + })?; + self.fuzzy_search_sessions + .lock() + .await + .insert(session_id, session); + Ok(FuzzyFileSearchSessionStartResponse {}) } async fn fuzzy_file_search_session_update( @@ -8442,6 +7583,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: FuzzyFileSearchSessionUpdateParams, ) { + let result = self.fuzzy_file_search_session_update_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn fuzzy_file_search_session_update_response( + &self, + params: FuzzyFileSearchSessionUpdateParams, + ) -> Result { let FuzzyFileSearchSessionUpdateParams { session_id, query } = params; let found = { let sessions = self.fuzzy_search_sessions.lock().await; @@ -8453,18 +7602,12 @@ impl CodexMessageProcessor { } }; if !found { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("fuzzy file search session not found: {session_id}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request(format!( + "fuzzy file search session not found: {session_id}" + ))); } - self.outgoing - .send_response(request_id, FuzzyFileSearchSessionUpdateResponse {}) - .await; + Ok(FuzzyFileSearchSessionUpdateResponse {}) } async fn fuzzy_file_search_session_stop( @@ -8484,14 +7627,18 @@ impl CodexMessageProcessor { } async fn upload_feedback(&self, request_id: ConnectionRequestId, params: FeedbackUploadParams) { + let result = self.upload_feedback_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn upload_feedback_response( + &self, + params: FeedbackUploadParams, + ) -> Result { if !self.config.feedback_enabled { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "sending feedback is disabled by configuration".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(invalid_request( + "sending feedback is disabled by configuration", + )); } let FeedbackUploadParams { @@ -8506,15 +7653,7 @@ impl CodexMessageProcessor { let conversation_id = match thread_id.as_deref() { Some(thread_id) => match ThreadId::from_string(thread_id) { Ok(conversation_id) => Some(conversation_id), - Err(err) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid thread id: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } + Err(err) => return Err(invalid_request(format!("invalid thread id: {err}"))), }, None => None, }; @@ -8643,30 +7782,14 @@ impl CodexMessageProcessor { let upload_result = match upload_result { Ok(result) => result, Err(join_err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to upload feedback: {join_err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; + return Err(internal_error(format!( + "failed to upload feedback: {join_err}" + ))); } }; - match upload_result { - Ok(()) => { - let response = FeedbackUploadResponse { thread_id }; - self.outgoing.send_response(request_id, response).await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to upload feedback: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } + upload_result.map_err(|err| internal_error(format!("failed to upload feedback: {err}")))?; + Ok(FeedbackUploadResponse { thread_id }) } async fn windows_sandbox_setup_start( @@ -8759,6 +7882,26 @@ impl CodexMessageProcessor { None }) } + + async fn send_invalid_request_error( + &self, + request_id: ConnectionRequestId, + message: impl Into, + ) { + self.outgoing + .send_error(request_id, invalid_request(message)) + .await; + } + + async fn send_internal_error( + &self, + request_id: ConnectionRequestId, + message: impl Into, + ) { + self.outgoing + .send_error(request_id, internal_error(message)) + .await; + } } fn normalize_thread_list_cwd_filters( @@ -8938,14 +8081,7 @@ async fn handle_pending_thread_resume_request( .await { outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message, - data: None, - }, - ) + .send_error(request_id, internal_error(message)) .await; return; } @@ -8967,13 +8103,9 @@ async fn handle_pending_thread_resume_request( outgoing .send_error( request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!( - "thread {conversation_id} is closing; retry thread/resume after the thread is closed" - ), - data: None, - }, + invalid_request(format!( + "thread {conversation_id} is closing; retry thread/resume after the thread is closed" + )), ) .await; return; @@ -9003,13 +8135,13 @@ async fn handle_pending_thread_resume_request( service_tier, approval_policy, approvals_reviewer, - sandbox_policy, permission_profile, cwd, reasoning_effort, .. } = pending.config_snapshot; let instruction_sources = pending.instruction_sources; + let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path()); let permission_profile = thread_response_permission_profile(permission_profile); let response = ThreadResumeResponse { @@ -9021,7 +8153,7 @@ async fn handle_pending_thread_resume_request( instruction_sources, approval_policy: approval_policy.into(), approvals_reviewer: approvals_reviewer.into(), - sandbox: sandbox_policy.into(), + sandbox, permission_profile, reasoning_effort, }; @@ -9226,8 +8358,9 @@ fn collect_resume_override_mismatches( } } if let Some(requested_sandbox) = request.sandbox.as_ref() { + let active_sandbox = config_snapshot.sandbox_policy(); let sandbox_matches = matches!( - (requested_sandbox, &config_snapshot.sandbox_policy), + (requested_sandbox, &active_sandbox), ( SandboxMode::ReadOnly, codex_protocol::protocol::SandboxPolicy::ReadOnly { .. } @@ -9244,8 +8377,7 @@ fn collect_resume_override_mismatches( ); if !sandbox_matches { mismatch_details.push(format!( - "sandbox requested={requested_sandbox:?} active={:?}", - config_snapshot.sandbox_policy + "sandbox requested={requested_sandbox:?} active={active_sandbox:?}" )); } } @@ -10152,6 +9284,20 @@ fn thread_response_permission_profile( Some(permission_profile.into()) } +fn thread_response_sandbox_policy( + permission_profile: &codex_protocol::models::PermissionProfile, + cwd: &Path, +) -> codex_app_server_protocol::SandboxPolicy { + let file_system_policy = permission_profile.file_system_sandbox_policy(); + let sandbox_policy = codex_sandboxing::compatibility_sandbox_policy_for_permission_profile( + permission_profile, + &file_system_policy, + permission_profile.network_sandbox_policy(), + cwd, + ); + sandbox_policy.into() +} + fn requested_permissions_trust_project(overrides: &ConfigOverrides, cwd: &Path) -> bool { if matches!( overrides.sandbox_mode, @@ -10931,7 +10077,6 @@ mod tests { service_tier: Some(codex_protocol::config_types::ServiceTier::Flex), approval_policy: codex_protocol::protocol::AskForApproval::OnRequest, approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User, - sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, permission_profile: codex_protocol::models::PermissionProfile::Disabled, cwd, ephemeral: false, diff --git a/codex-rs/app-server/src/codex_message_processor/plugins.rs b/codex-rs/app-server/src/codex_message_processor/plugins.rs index 8f0f4dea9a..db8ade8c67 100644 --- a/codex-rs/app-server/src/codex_message_processor/plugins.rs +++ b/codex-rs/app-server/src/codex_message_processor/plugins.rs @@ -1,4 +1,6 @@ use super::*; +use crate::error_code::internal_error; +use crate::error_code::invalid_request; use codex_app_server_protocol::PluginInstallPolicy; impl CodexMessageProcessor { @@ -7,46 +9,33 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: PluginListParams, ) { + let result = self.plugin_list_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn plugin_list_response( + &self, + params: PluginListParams, + ) -> Result { let plugins_manager = self.thread_manager.plugins_manager(); let PluginListParams { cwds } = params; let roots = cwds.unwrap_or_default(); - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; + let empty_response = || PluginListResponse { + marketplaces: Vec::new(), + marketplace_load_errors: Vec::new(), + featured_plugin_ids: Vec::new(), }; if !config.features.enabled(Feature::Plugins) { - self.outgoing - .send_response( - request_id, - PluginListResponse { - marketplaces: Vec::new(), - marketplace_load_errors: Vec::new(), - featured_plugin_ids: Vec::new(), - }, - ) - .await; - return; + return Ok(empty_response()); } let auth = self.auth_manager.auth().await; if !self .workspace_codex_plugins_enabled(&config, auth.as_ref()) .await { - self.outgoing - .send_response( - request_id, - PluginListResponse { - marketplaces: Vec::new(), - marketplace_load_errors: Vec::new(), - featured_plugin_ids: Vec::new(), - }, - ) - .await; - return; + return Ok(empty_response()); } plugins_manager.maybe_start_non_curated_plugin_cache_refresh(&roots); @@ -100,18 +89,11 @@ impl CodexMessageProcessor { .await { Ok(Ok(outcome)) => outcome, - Ok(Err(err)) => { - self.send_marketplace_error(request_id, err, "list marketplace plugins") - .await; - return; - } + Ok(Err(err)) => return Err(Self::marketplace_error(err, "list marketplace plugins")), Err(err) => { - self.send_internal_error( - request_id, - format!("failed to list marketplace plugins: {err}"), - ) - .await; - return; + return Err(internal_error(format!( + "failed to list marketplace plugins: {err}" + ))); } }; @@ -174,16 +156,11 @@ impl CodexMessageProcessor { Vec::new() }; - self.outgoing - .send_response( - request_id, - PluginListResponse { - marketplaces: data, - marketplace_load_errors, - featured_plugin_ids, - }, - ) - .await; + Ok(PluginListResponse { + marketplaces: data, + marketplace_load_errors, + featured_plugin_ids, + }) } pub(super) async fn plugin_read( @@ -191,6 +168,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: PluginReadParams, ) { + let result = self.plugin_read_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn plugin_read_response( + &self, + params: PluginReadParams, + ) -> Result { let plugins_manager = self.thread_manager.plugins_manager(); let PluginReadParams { marketplace_path, @@ -201,30 +186,16 @@ impl CodexMessageProcessor { (Some(marketplace_path), None) => Ok(marketplace_path), (None, Some(remote_marketplace_name)) => Err(remote_marketplace_name), (Some(_), Some(_)) | (None, None) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "plugin/read requires exactly one of marketplacePath or remoteMarketplaceName".to_string(), - data: None, - }, - ) - .await; - return; + return Err(invalid_request( + "plugin/read requires exactly one of marketplacePath or remoteMarketplaceName", + )); } }; let config_cwd = read_source.as_ref().ok().and_then(|marketplace_path| { marketplace_path.as_path().parent().map(Path::to_path_buf) }); - let config = match self.load_latest_config(config_cwd).await { - Ok(config) => config, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } - }; + let config = self.load_latest_config(config_cwd).await?; let plugin = match read_source { Ok(marketplace_path) => { @@ -232,17 +203,10 @@ impl CodexMessageProcessor { plugin_name, marketplace_path, }; - let outcome = match plugins_manager + let outcome = plugins_manager .read_plugin_for_config(&config, &request) .await - { - Ok(outcome) => outcome, - Err(err) => { - self.send_marketplace_error(request_id, err, "read plugin details") - .await; - return; - } - }; + .map_err(|err| Self::marketplace_error(err, "read plugin details"))?; let environment_manager = self.thread_manager.environment_manager(); let app_summaries = plugin_app_helpers::load_plugin_app_summaries( &config, @@ -287,19 +251,9 @@ impl CodexMessageProcessor { if !config.features.enabled(Feature::Plugins) || !config.features.enabled(Feature::RemotePlugin) { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!( - "remote plugin read is not enabled for marketplace {remote_marketplace_name}" - ), - data: None, - }, - ) - .await; - return; + return Err(invalid_request(format!( + "remote plugin read is not enabled for marketplace {remote_marketplace_name}" + ))); } let auth = self.auth_manager.auth().await; let remote_plugin_service_config = RemotePluginServiceConfig { @@ -310,36 +264,20 @@ impl CodexMessageProcessor { .chars() .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '~') { - self.send_invalid_request_error( - request_id, - "invalid remote plugin id: only ASCII letters, digits, `_`, `-`, and `~` are allowed" - .to_string(), - ) - .await; - return; + return Err(invalid_request( + "invalid remote plugin id: only ASCII letters, digits, `_`, `-`, and `~` are allowed", + )); } - let remote_detail = match codex_core_plugins::remote::fetch_remote_plugin_detail( + let remote_detail = codex_core_plugins::remote::fetch_remote_plugin_detail( &remote_plugin_service_config, auth.as_ref(), &remote_marketplace_name, &plugin_name, ) .await - { - Ok(remote_detail) => remote_detail, - Err(err) => { - self.outgoing - .send_error( - request_id, - remote_plugin_catalog_error_to_jsonrpc( - err, - "read remote plugin details", - ), - ) - .await; - return; - } - }; + .map_err(|err| { + remote_plugin_catalog_error_to_jsonrpc(err, "read remote plugin details") + })?; let plugin_apps = remote_detail .app_ids .iter() @@ -357,9 +295,7 @@ impl CodexMessageProcessor { } }; - self.outgoing - .send_response(request_id, PluginReadResponse { plugin }) - .await; + Ok(PluginReadResponse { plugin }) } pub(super) async fn plugin_install( @@ -367,6 +303,14 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: PluginInstallParams, ) { + let result = self.plugin_install_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn plugin_install_response( + &self, + params: PluginInstallParams, + ) -> Result { let PluginInstallParams { marketplace_path, remote_marketplace_name, @@ -375,44 +319,27 @@ impl CodexMessageProcessor { let marketplace_path = match (marketplace_path, remote_marketplace_name) { (Some(marketplace_path), None) => marketplace_path, (None, Some(remote_marketplace_name)) => { - self.remote_plugin_install(request_id, remote_marketplace_name, plugin_name) + return self + .remote_plugin_install_response(remote_marketplace_name, plugin_name) .await; - return; } (Some(_), Some(_)) | (None, None) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "plugin/install requires exactly one of marketplacePath or remoteMarketplaceName".to_string(), - data: None, - }, - ) - .await; - return; + return Err(invalid_request( + "plugin/install requires exactly one of marketplacePath or remoteMarketplaceName", + )); } }; let config_cwd = marketplace_path.as_path().parent().map(Path::to_path_buf); - let config = match self.load_latest_config(config_cwd.clone()).await { - Ok(config) => config, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } - }; + let config = self.load_latest_config(config_cwd.clone()).await?; let auth = self.auth_manager.auth().await; if !self .workspace_codex_plugins_enabled(&config, auth.as_ref()) .await { - self.send_invalid_request_error( - request_id, - "Codex plugins are disabled for this workspace".to_string(), - ) - .await; - return; + return Err(invalid_request( + "Codex plugins are disabled for this workspace", + )); } let plugins_manager = self.thread_manager.plugins_manager(); @@ -421,223 +348,153 @@ impl CodexMessageProcessor { marketplace_path, }; - let install_result = plugins_manager.install_plugin(request).await; - - match install_result { - Ok(result) => { - let config = match self.load_latest_config(config_cwd).await { - Ok(config) => config, - Err(err) => { - warn!( - "failed to reload config after plugin install, using current config: {err:?}" - ); - config - } - }; - - self.clear_plugin_related_caches(); - - let plugin_mcp_servers = - load_plugin_mcp_servers(result.installed_path.as_path()).await; - - if !plugin_mcp_servers.is_empty() { - if let Err(err) = self.queue_mcp_server_refresh_for_config(&config).await { - warn!( - plugin = result.plugin_id.as_key(), - "failed to queue MCP refresh after plugin install: {err:?}" - ); - } - self.start_plugin_mcp_oauth_logins(&config, plugin_mcp_servers) - .await; - } - - let plugin_apps = load_plugin_apps(result.installed_path.as_path()).await; - let auth = self.auth_manager.auth().await; - let apps_needing_auth = self - .plugin_apps_needing_auth_for_install( - &config, - auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth), - &result.plugin_id.as_key(), - &plugin_apps, - ) - .await; - - self.outgoing - .send_response( - request_id, - PluginInstallResponse { - auth_policy: result.auth_policy.into(), - apps_needing_auth, - }, - ) - .await; - } - Err(err) => { - if err.is_invalid_request() { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - return; - } - - match err { - CorePluginInstallError::Marketplace(err) => { - self.send_marketplace_error(request_id, err, "install plugin") - .await; - } - CorePluginInstallError::Config(err) => { - self.send_internal_error( - request_id, - format!("failed to persist installed plugin config: {err}"), - ) - .await; - } - CorePluginInstallError::Remote(err) => { - self.send_internal_error( - request_id, - format!("failed to enable remote plugin: {err}"), - ) - .await; - } - CorePluginInstallError::Join(err) => { - self.send_internal_error( - request_id, - format!("failed to install plugin: {err}"), - ) - .await; - } - CorePluginInstallError::Store(err) => { - self.send_internal_error( - request_id, - format!("failed to install plugin: {err}"), - ) - .await; - } - } - } - } - } - - async fn remote_plugin_install( - &self, - request_id: ConnectionRequestId, - remote_marketplace_name: String, - plugin_name: String, - ) { - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { + let result = plugins_manager + .install_plugin(request) + .await + .map_err(Self::plugin_install_error)?; + let config = match self.load_latest_config(config_cwd).await { Ok(config) => config, Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; + warn!( + "failed to reload config after plugin install, using current config: {err:?}" + ); + config } }; + + self.clear_plugin_related_caches(); + + let plugin_mcp_servers = load_plugin_mcp_servers(result.installed_path.as_path()).await; + + if !plugin_mcp_servers.is_empty() { + if let Err(err) = self.queue_mcp_server_refresh_for_config(&config).await { + warn!( + plugin = result.plugin_id.as_key(), + "failed to queue MCP refresh after plugin install: {err:?}" + ); + } + self.start_plugin_mcp_oauth_logins(&config, plugin_mcp_servers) + .await; + } + + let plugin_apps = load_plugin_apps(result.installed_path.as_path()).await; + let auth = self.auth_manager.auth().await; + let apps_needing_auth = self + .plugin_apps_needing_auth_for_install( + &config, + auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth), + &result.plugin_id.as_key(), + &plugin_apps, + ) + .await; + + Ok(PluginInstallResponse { + auth_policy: result.auth_policy.into(), + apps_needing_auth, + }) + } + + async fn remote_plugin_install_response( + &self, + remote_marketplace_name: String, + plugin_name: String, + ) -> Result { + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; if !config.features.enabled(Feature::Plugins) || !config.features.enabled(Feature::RemotePlugin) { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!( - "remote plugin install is not enabled for marketplace {remote_marketplace_name}" - ), - data: None, - }, - ) - .await; - return; + return Err(invalid_request(format!( + "remote plugin install is not enabled for marketplace {remote_marketplace_name}" + ))); } - if plugin_name.is_empty() - || !plugin_name - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '~') - { - self.send_invalid_request_error( - request_id, - "invalid remote plugin id: only ASCII letters, digits, `_`, `-`, and `~` are allowed" - .to_string(), - ) - .await; - return; + if plugin_name.is_empty() || !is_valid_remote_plugin_id(&plugin_name) { + return Err(invalid_request( + "invalid remote plugin id: only ASCII letters, digits, `_`, `-`, and `~` are allowed", + )); } let auth = self.auth_manager.auth().await; let remote_plugin_service_config = RemotePluginServiceConfig { chatgpt_base_url: config.chatgpt_base_url.clone(), }; - let remote_detail = match codex_core_plugins::remote::fetch_remote_plugin_detail( - &remote_plugin_service_config, - auth.as_ref(), - &remote_marketplace_name, - &plugin_name, - ) - .await - { - Ok(remote_detail) => remote_detail, - Err(err) => { - self.outgoing - .send_error( - request_id, - remote_plugin_catalog_error_to_jsonrpc( - err, - "read remote plugin details before install", - ), - ) - .await; - return; - } - }; - if remote_detail.summary.install_policy == PluginInstallPolicy::NotAvailable { - self.send_invalid_request_error( - request_id, - format!("remote plugin {plugin_name} is not available for install"), + let remote_detail = + codex_core_plugins::remote::fetch_remote_plugin_detail_with_download_urls( + &remote_plugin_service_config, + auth.as_ref(), + &remote_marketplace_name, + &plugin_name, ) - .await; - return; + .await + .map_err(|err| { + remote_plugin_catalog_error_to_jsonrpc( + err, + "read remote plugin details before install", + ) + })?; + if remote_detail.summary.install_policy == PluginInstallPolicy::NotAvailable { + return Err(invalid_request(format!( + "remote plugin {plugin_name} is not available for install" + ))); } + let validated_bundle = codex_core_plugins::remote_bundle::validate_remote_plugin_bundle( + &plugin_name, + &remote_marketplace_name, + &remote_detail.summary.name, + remote_detail.release_version.as_deref(), + remote_detail.bundle_download_url.as_deref(), + ) + .map_err(remote_plugin_bundle_install_error_to_jsonrpc)?; - if let Err(err) = codex_core_plugins::remote::install_remote_plugin( + let result = codex_core_plugins::remote_bundle::download_and_install_remote_plugin_bundle( + config.codex_home.to_path_buf(), + validated_bundle, + ) + .await + .map_err(remote_plugin_bundle_install_error_to_jsonrpc)?; + + // Cache first so a backend install cannot succeed when local materialization fails. + // If this backend call fails, the cache entry is harmless because remote installed state + // is still backend-gated. + codex_core_plugins::remote::install_remote_plugin( &remote_plugin_service_config, auth.as_ref(), &remote_marketplace_name, &plugin_name, ) .await - { - self.outgoing - .send_error( - request_id, - remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin"), - ) - .await; - return; - } + .map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin"))?; + // TODO(remote plugins): remote marketplaces do not yet have a local + // marketplace/read-path sync, so this install path reads MCP/apps directly + // from the just-cached bundle. self.clear_plugin_related_caches(); - let plugin_apps = remote_detail - .app_ids - .into_iter() - .map(codex_core::plugins::AppConnectorId) - .collect::>(); + let plugin_mcp_servers = load_plugin_mcp_servers(result.installed_path.as_path()).await; + if !plugin_mcp_servers.is_empty() { + if let Err(err) = self.queue_mcp_server_refresh_for_config(&config).await { + warn!( + plugin = result.plugin_id.as_key(), + "failed to queue MCP refresh after remote plugin install: {err:?}" + ); + } + self.start_plugin_mcp_oauth_logins(&config, plugin_mcp_servers) + .await; + } + + let plugin_apps = load_plugin_apps(result.installed_path.as_path()).await; let apps_needing_auth = self .plugin_apps_needing_auth_for_install( &config, auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth), - &plugin_name, + &result.plugin_id.as_key(), &plugin_apps, ) .await; - self.outgoing - .send_response( - request_id, - PluginInstallResponse { - auth_policy: remote_detail.summary.auth_policy, - apps_needing_auth, - }, - ) - .await; + Ok(PluginInstallResponse { + auth_policy: remote_detail.summary.auth_policy, + apps_needing_auth, + }) } async fn plugin_apps_needing_auth_for_install( @@ -709,61 +566,142 @@ impl CodexMessageProcessor { request_id: ConnectionRequestId, params: PluginUninstallParams, ) { + let result = self.plugin_uninstall_response(params).await; + self.outgoing.send_result(request_id, result).await; + } + + async fn plugin_uninstall_response( + &self, + params: PluginUninstallParams, + ) -> Result { let PluginUninstallParams { plugin_id } = params; + if codex_core::plugins::PluginId::parse(&plugin_id).is_err() + && !is_valid_remote_uninstall_plugin_id(&plugin_id) + { + return Err(invalid_request( + "invalid plugin id: expected a local plugin id in the form `plugin@marketplace` or a remote plugin id starting with `plugins~`, `app_`, `asdk_app_`, or `connector_`", + )); + } + if is_valid_remote_uninstall_plugin_id(&plugin_id) { + return self.remote_plugin_uninstall_response(plugin_id).await; + } let plugins_manager = self.thread_manager.plugins_manager(); - let uninstall_result = plugins_manager.uninstall_plugin(plugin_id).await; + plugins_manager + .uninstall_plugin(plugin_id) + .await + .map_err(Self::plugin_uninstall_error)?; + self.clear_plugin_related_caches(); + Ok(PluginUninstallResponse {}) + } - match uninstall_result { - Ok(()) => { - self.clear_plugin_related_caches(); - self.outgoing - .send_response(request_id, PluginUninstallResponse {}) - .await; + fn plugin_install_error(err: CorePluginInstallError) -> JSONRPCErrorError { + if err.is_invalid_request() { + return invalid_request(err.to_string()); + } + + match err { + CorePluginInstallError::Marketplace(err) => { + Self::marketplace_error(err, "install plugin") } - Err(err) => { - if err.is_invalid_request() { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - return; - } - - match err { - CorePluginUninstallError::Config(err) => { - self.send_internal_error( - request_id, - format!("failed to clear plugin config: {err}"), - ) - .await; - } - CorePluginUninstallError::Remote(err) => { - self.send_internal_error( - request_id, - format!("failed to uninstall remote plugin: {err}"), - ) - .await; - } - CorePluginUninstallError::Join(err) => { - self.send_internal_error( - request_id, - format!("failed to uninstall plugin: {err}"), - ) - .await; - } - CorePluginUninstallError::Store(err) => { - self.send_internal_error( - request_id, - format!("failed to uninstall plugin: {err}"), - ) - .await; - } - CorePluginUninstallError::InvalidPluginId(_) => { - unreachable!("invalid plugin ids are handled above"); - } - } + CorePluginInstallError::Config(err) => { + internal_error(format!("failed to persist installed plugin config: {err}")) + } + CorePluginInstallError::Remote(err) => { + internal_error(format!("failed to enable remote plugin: {err}")) + } + CorePluginInstallError::Join(err) => { + internal_error(format!("failed to install plugin: {err}")) + } + CorePluginInstallError::Store(err) => { + internal_error(format!("failed to install plugin: {err}")) } } } + + fn plugin_uninstall_error(err: CorePluginUninstallError) -> JSONRPCErrorError { + if err.is_invalid_request() { + return invalid_request(err.to_string()); + } + + match err { + CorePluginUninstallError::Config(err) => { + internal_error(format!("failed to clear plugin config: {err}")) + } + CorePluginUninstallError::Remote(err) => { + internal_error(format!("failed to uninstall remote plugin: {err}")) + } + CorePluginUninstallError::Join(err) => { + internal_error(format!("failed to uninstall plugin: {err}")) + } + CorePluginUninstallError::Store(err) => { + internal_error(format!("failed to uninstall plugin: {err}")) + } + CorePluginUninstallError::InvalidPluginId(_) => { + unreachable!("invalid plugin ids are handled above"); + } + } + } + + fn marketplace_error(err: MarketplaceError, action: &str) -> JSONRPCErrorError { + match err { + MarketplaceError::MarketplaceNotFound { .. } + | MarketplaceError::InvalidMarketplaceFile { .. } + | MarketplaceError::PluginNotFound { .. } + | MarketplaceError::PluginNotAvailable { .. } + | MarketplaceError::PluginsDisabled + | MarketplaceError::InvalidPlugin(_) => invalid_request(err.to_string()), + MarketplaceError::Io { .. } => internal_error(format!("failed to {action}: {err}")), + } + } + + async fn remote_plugin_uninstall_response( + &self, + plugin_id: String, + ) -> Result { + let config = self.load_latest_config(/*fallback_cwd*/ None).await?; + if !config.features.enabled(Feature::Plugins) + || !config.features.enabled(Feature::RemotePlugin) + { + return Err(invalid_request("remote plugin uninstall is not enabled")); + } + if plugin_id.is_empty() || !is_valid_remote_plugin_id(&plugin_id) { + return Err(invalid_request( + "invalid remote plugin id: only ASCII letters, digits, `_`, `-`, and `~` are allowed", + )); + } + + let auth = self.auth_manager.auth().await; + let remote_plugin_service_config = RemotePluginServiceConfig { + chatgpt_base_url: config.chatgpt_base_url.clone(), + }; + codex_core_plugins::remote::uninstall_remote_plugin( + &remote_plugin_service_config, + auth.as_ref(), + config.codex_home.to_path_buf(), + &plugin_id, + ) + .await + .map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "uninstall remote plugin"))?; + + self.clear_plugin_related_caches(); + Ok(PluginUninstallResponse {}) + } +} + +fn is_valid_remote_plugin_id(plugin_name: &str) -> bool { + plugin_name + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '~') +} + +fn is_valid_remote_uninstall_plugin_id(plugin_name: &str) -> bool { + !plugin_name.is_empty() + && is_valid_remote_plugin_id(plugin_name) + && (plugin_name.starts_with("plugins~") + || plugin_name.starts_with("app_") + || plugin_name.starts_with("asdk_app_") + || plugin_name.starts_with("connector_")) } fn remote_marketplace_to_info(marketplace: RemoteMarketplace) -> PluginMarketplaceEntry { @@ -850,10 +788,17 @@ fn remote_plugin_catalog_error_to_jsonrpc( | RemotePluginCatalogError::UnexpectedStatus { .. } | RemotePluginCatalogError::Decode { .. } | RemotePluginCatalogError::UnexpectedPluginId { .. } - | RemotePluginCatalogError::UnexpectedEnabledState { .. } => JSONRPCErrorError { + | RemotePluginCatalogError::UnexpectedEnabledState { .. } + | RemotePluginCatalogError::CacheRemove(_) => JSONRPCErrorError { code: INTERNAL_ERROR_CODE, message: format!("{context}: {err}"), data: None, }, } } + +fn remote_plugin_bundle_install_error_to_jsonrpc( + err: codex_core_plugins::remote_bundle::RemotePluginBundleInstallError, +) -> JSONRPCErrorError { + internal_error(format!("install remote plugin bundle: {err}")) +} diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index cc4e22e923..73332394f4 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -391,7 +391,8 @@ 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); + AuthManager::shared_from_config(args.config.as_ref(), args.enable_codex_api_key_env) + .await; let config_manager = ConfigManager::new( args.config.codex_home.to_path_buf(), args.cli_overrides, diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 52b6de0e0c..de89608101 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -469,7 +469,7 @@ pub async fn run_main_with_transport_options( config_manager .replace_thread_config_loader(Arc::clone(&discovered_thread_config_loader)); let auth_manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await; config_manager.replace_cloud_requirements_loader(auth_manager, config.chatgpt_base_url); } Err(err) => { @@ -631,7 +631,7 @@ pub async fn run_main_with_transport_options( } let auth_manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await; let remote_control_enabled = config.features.enabled(Feature::RemoteControl); if transport_accept_handles.is_empty() && !remote_control_enabled { @@ -712,7 +712,7 @@ pub async fn run_main_with_transport_options( let outgoing_message_sender = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let outbound_control_tx = outbound_control_tx; let auth_manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await; let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs { outgoing: outgoing_message_sender, arg0_paths, diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 6cdb939364..071f69eb6a 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -653,14 +653,12 @@ impl MessageProcessor { } } } - if self.config.features.enabled(Feature::GeneralAnalytics) { - self.analytics_events_client.track_initialize( - connection_id.0, - analytics_initialize_params, - originator, - self.rpc_transport, - ); - } + self.analytics_events_client.track_initialize( + connection_id.0, + analytics_initialize_params, + originator, + self.rpc_transport, + ); set_default_client_residency_requirement(self.config.enforce_residency.value()); if let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() { *suffix = Some(user_agent_suffix); @@ -716,9 +714,8 @@ impl MessageProcessor { return Err(invalid_request(experimental_required_message(reason))); } let connection_id = connection_request_id.connection_id; - if self.config.features.enabled(Feature::GeneralAnalytics) - && let ClientRequest::TurnStart { request_id, .. } - | ClientRequest::TurnSteer { request_id, .. } = &codex_request + if let ClientRequest::TurnStart { request_id, .. } + | ClientRequest::TurnSteer { request_id, .. } = &codex_request { self.analytics_events_client.track_request( connection_id.0, 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 507d7865b9..850d05c04e 100644 --- a/codex-rs/app-server/src/message_processor/tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor/tracing_tests.rs @@ -127,7 +127,7 @@ impl TracingHarness { 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?); - let (processor, outgoing_rx) = build_test_processor(config); + let (processor, outgoing_rx) = build_test_processor(config).await; let tracing = init_test_tracing(); tracing.exporter.reset(); tracing::callsite::rebuild_interest_cache(); @@ -257,7 +257,7 @@ async fn build_test_config(codex_home: &Path, server_uri: &str) -> Result, ) -> ( Arc, @@ -266,7 +266,7 @@ fn build_test_processor( let (outgoing_tx, outgoing_rx) = mpsc::channel(16); let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); let auth_manager = - AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false).await; let config_manager = ConfigManager::new( config.codex_home.to_path_buf(), Vec::new(), 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 6b0051f8db..82e02ae5de 100644 --- a/codex-rs/app-server/src/transport/remote_control/tests.rs +++ b/codex-rs/app-server/src/transport/remote_control/tests.rs @@ -497,7 +497,8 @@ async fn remote_control_start_allows_missing_auth_when_enabled() { /*enable_codex_api_key_env*/ false, AuthCredentialsStoreMode::File, /*chatgpt_base_url*/ None, - ); + ) + .await; let (transport_event_tx, _transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let shutdown_token = CancellationToken::new(); @@ -1085,7 +1086,8 @@ async fn remote_control_waits_for_account_id_before_enrolling() { /*enable_codex_api_key_env*/ false, AuthCredentialsStoreMode::File, /*chatgpt_base_url*/ None, - ); + ) + .await; let expected_server_name = gethostname().to_string_lossy().trim().to_string(); let expected_enrollment = RemoteControlEnrollment { account_id: "account_id".to_string(), 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 464832e34a..4cd078455a 100644 --- a/codex-rs/app-server/src/transport/remote_control/websocket.rs +++ b/codex-rs/app-server/src/transport/remote_control/websocket.rs @@ -706,7 +706,7 @@ pub(crate) async fn load_remote_control_auth( "remote control requires ChatGPT authentication", )); } - auth_manager.reload(); + auth_manager.reload().await; reloaded = true; continue; }; @@ -714,7 +714,7 @@ pub(crate) async fn load_remote_control_auth( break auth; } if auth.get_account_id().is_none() && !reloaded { - auth_manager.reload(); + auth_manager.reload().await; reloaded = true; continue; } @@ -1090,7 +1090,8 @@ mod tests { /*enable_codex_api_key_env*/ false, AuthCredentialsStoreMode::File, /*chatgpt_base_url*/ None, - ); + ) + .await; let mut auth_recovery = auth_manager.unauthorized_recovery(); let mut enrollment = Some(RemoteControlEnrollment { account_id: "account_id".to_string(), @@ -1172,7 +1173,8 @@ mod tests { /*enable_codex_api_key_env*/ false, AuthCredentialsStoreMode::File, /*chatgpt_base_url*/ None, - ); + ) + .await; let mut auth_recovery = auth_manager.unauthorized_recovery(); let mut enrollment = None; save_auth( diff --git a/codex-rs/app-server/tests/suite/v2/analytics.rs b/codex-rs/app-server/tests/suite/v2/analytics.rs index a3ecdbc1f4..862721a154 100644 --- a/codex-rs/app-server/tests/suite/v2/analytics.rs +++ b/codex-rs/app-server/tests/suite/v2/analytics.rs @@ -79,24 +79,6 @@ async fn app_server_default_analytics_enabled_with_flag() -> Result<()> { Ok(()) } -pub(crate) async fn enable_analytics_capture(server: &MockServer, codex_home: &Path) -> Result<()> { - let config_path = codex_home.join("config.toml"); - let config_toml = std::fs::read_to_string(&config_path)?; - if !config_toml.contains("[features]") { - std::fs::write( - &config_path, - format!("{config_toml}\n[features]\ngeneral_analytics = true\n"), - )?; - } else if !config_toml.contains("general_analytics") { - std::fs::write( - &config_path, - config_toml.replace("[features]\n", "[features]\ngeneral_analytics = true\n"), - )?; - } - - mount_analytics_capture(server, codex_home).await -} - pub(crate) async fn mount_analytics_capture(server: &MockServer, codex_home: &Path) -> Result<()> { Mock::given(method("POST")) .and(path("/codex/analytics-events/events")) diff --git a/codex-rs/app-server/tests/suite/v2/command_exec.rs b/codex-rs/app-server/tests/suite/v2/command_exec.rs index 83718a8dc7..211cec9355 100644 --- a/codex-rs/app-server/tests/suite/v2/command_exec.rs +++ b/codex-rs/app-server/tests/suite/v2/command_exec.rs @@ -246,7 +246,7 @@ async fn command_exec_accepts_permission_profile() -> Result<()> { #[cfg(unix)] #[tokio::test] -async fn command_exec_permission_profile_cwd_uses_command_cwd() -> Result<()> { +async fn command_exec_permission_profile_project_roots_use_command_cwd() -> Result<()> { let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; let codex_home = TempDir::new()?; let command_dir = codex_home.path().join("command-cwd"); @@ -264,7 +264,7 @@ async fn command_exec_permission_profile_cwd_uses_command_cwd() -> Result<()> { }; entries.push(FileSystemSandboxEntry { path: FileSystemPath::Special { - value: FileSystemSpecialPath::CurrentWorkingDirectory, + value: FileSystemSpecialPath::ProjectRoots { subpath: None }, }, access: FileSystemAccessMode::Write, }); @@ -298,7 +298,7 @@ async fn command_exec_permission_profile_cwd_uses_command_cwd() -> Result<()> { let response: CommandExecResponse = to_response(response)?; assert_eq!( response.exit_code, 0, - "parent cwd write should fail under command-cwd-scoped profile: {response:?}" + "parent cwd write should fail under command project-root profile: {response:?}" ); assert_eq!( std::fs::read_to_string(command_dir.join("child.txt"))?, @@ -306,7 +306,7 @@ async fn command_exec_permission_profile_cwd_uses_command_cwd() -> Result<()> { ); assert!( !codex_home.path().join("parent.txt").exists(), - "permissionProfile :cwd write should not grant the server cwd when command cwd differs" + "permissionProfile :project_roots write should not grant the server cwd when command cwd differs" ); Ok(()) diff --git a/codex-rs/app-server/tests/suite/v2/plugin_install.rs b/codex-rs/app-server/tests/suite/v2/plugin_install.rs index 88403d8919..a115c83077 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_install.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_install.rs @@ -28,6 +28,8 @@ use codex_app_server_protocol::PluginInstallResponse; use codex_app_server_protocol::RequestId; use codex_config::types::AuthCredentialsStoreMode; use codex_utils_absolute_path::AbsolutePathBuf; +use flate2::Compression; +use flate2::write::GzEncoder; use pretty_assertions::assert_eq; use rmcp::handler::server::ServerHandler; use rmcp::model::JsonObject; @@ -45,8 +47,10 @@ use tempfile::TempDir; use tokio::net::TcpListener; use tokio::task::JoinHandle; use tokio::time::timeout; +use wiremock::Match; use wiremock::Mock; use wiremock::MockServer; +use wiremock::Request; use wiremock::ResponseTemplate; use wiremock::matchers::header; use wiremock::matchers::method; @@ -56,6 +60,9 @@ use wiremock::matchers::query_param; // Plugin install tests wait on connector discovery after the install response path // starts, which is noticeably slower on Windows CI. const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); +const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000"; +const TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS: &str = + "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS"; #[tokio::test] async fn plugin_install_rejects_relative_marketplace_paths() -> Result<()> { @@ -154,7 +161,7 @@ async fn plugin_install_rejects_remote_marketplace_when_remote_plugin_is_disable .send_plugin_install_request(PluginInstallParams { marketplace_path: None, remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "plugins~Plugin_sample".to_string(), + plugin_name: "plugins~Plugin_22222222222222222222222222222222".to_string(), }) .await?; @@ -175,84 +182,36 @@ async fn plugin_install_rejects_remote_marketplace_when_remote_plugin_is_disable } #[tokio::test] -async fn plugin_install_writes_remote_plugin_to_cloud_when_remote_plugin_enabled() -> Result<()> { +async fn plugin_install_writes_remote_plugin_to_cloud_and_cache() -> Result<()> { let codex_home = TempDir::new()?; let server = MockServer::start().await; - write_remote_plugin_catalog_config( + let installed_path = codex_home + .path() + .join("plugins/cache/chatgpt-global/linear/1.2.3"); + let bundle_url = mount_remote_plugin_bundle( + &server, + /*status_code*/ 200, + remote_plugin_bundle_tar_gz_bytes("linear")?, + ) + .await; + configure_remote_plugin_test(codex_home.path(), &server)?; + mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await; + mount_empty_remote_installed_plugins(&server).await; + mount_remote_plugin_install_after_cache_write( + &server, + REMOTE_PLUGIN_ID, + installed_path.join(".codex-plugin/plugin.json"), + ) + .await; + + let mut mcp = McpProcess::new_with_env( codex_home.path(), - &format!("{}/backend-api/", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let detail_body = r#"{ - "id": "plugins~Plugin_linear", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": { - "short_description": "Plan and track work" - }, - "skills": [] - } -}"#; - let empty_installed_body = r#"{ - "plugins": [], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/plugins~Plugin_linear")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(detail_body)) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "GLOBAL")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(empty_installed_body)) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path( - "/backend-api/ps/plugins/plugins~Plugin_linear/install", - )) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"id":"plugins~Plugin_linear","enabled":true}"#), - ) - .mount(&server) - .await; - - let mut mcp = McpProcess::new(codex_home.path()).await?; + &[(TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1"))], + ) + .await?; timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: None, - remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "plugins~Plugin_linear".to_string(), - }) - .await?; + let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?; let response: JSONRPCResponse = timeout( DEFAULT_TIMEOUT, mcp.read_stream_until_response_message(RequestId::Integer(request_id)), @@ -270,10 +229,156 @@ async fn plugin_install_writes_remote_plugin_to_cloud_when_remote_plugin_enabled wait_for_remote_plugin_request_count( &server, "POST", - "/ps/plugins/plugins~Plugin_linear/install", + &format!("/ps/plugins/{REMOTE_PLUGIN_ID}/install"), /*expected_count*/ 1, ) .await?; + wait_for_remote_plugin_request_count( + &server, + "GET", + "/bundles/linear.tar.gz", + /*expected_count*/ 1, + ) + .await?; + assert!(installed_path.join(".codex-plugin/plugin.json").is_file()); + assert!(installed_path.join("skills/plan-work/SKILL.md").is_file()); + assert!( + !codex_home + .path() + .join(format!( + "plugins/cache/chatgpt-global/{REMOTE_PLUGIN_ID}/1.2.3" + )) + .exists() + ); + Ok(()) +} + +#[tokio::test] +async fn plugin_install_rejects_missing_remote_bundle_url() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + configure_remote_plugin_test(codex_home.path(), &server)?; + mount_remote_plugin_detail( + &server, + REMOTE_PLUGIN_ID, + "1.2.3", + /*bundle_download_url*/ None, + ) + .await; + mount_empty_remote_installed_plugins(&server).await; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?; + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32603); + assert!( + err.error + .message + .contains("backend did not return a download URL") + ); + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/ps/plugins/{REMOTE_PLUGIN_ID}/install"), + /*expected_count*/ 0, + ) + .await?; + assert!( + !codex_home + .path() + .join("plugins/cache/chatgpt-global/linear") + .exists() + ); + Ok(()) +} + +#[tokio::test] +async fn plugin_install_rejects_plain_http_remote_bundle_url() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + let bundle_url = format!("{}/bundles/linear.tar.gz", server.uri()); + configure_remote_plugin_test(codex_home.path(), &server)?; + mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await; + mount_empty_remote_installed_plugins(&server).await; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?; + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32603); + assert!( + err.error + .message + .contains("unsupported download URL scheme") + ); + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/ps/plugins/{REMOTE_PLUGIN_ID}/install"), + /*expected_count*/ 0, + ) + .await?; + assert!( + !codex_home + .path() + .join("plugins/cache/chatgpt-global/linear") + .exists() + ); + Ok(()) +} + +#[tokio::test] +async fn plugin_install_rejects_invalid_remote_release_version() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + configure_remote_plugin_test(codex_home.path(), &server)?; + mount_remote_plugin_detail( + &server, + REMOTE_PLUGIN_ID, + "../1.2.3", + Some("https://127.0.0.1:1/bundles/linear.tar.gz"), + ) + .await; + mount_empty_remote_installed_plugins(&server).await; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?; + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32603); + assert!(err.error.message.contains("invalid release version")); + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/ps/plugins/{REMOTE_PLUGIN_ID}/install"), + /*expected_count*/ 0, + ) + .await?; + assert!( + !codex_home + .path() + .join("plugins/cache/chatgpt-global/linear") + .exists() + ); Ok(()) } @@ -571,6 +676,60 @@ async fn plugin_install_tracks_analytics_event() -> Result<()> { Ok(()) } +#[tokio::test] +async fn plugin_install_errors_when_remote_bundle_download_fails() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + let bundle_url = mount_remote_plugin_bundle( + &server, + /*status_code*/ 503, + b"bundle temporarily unavailable".to_vec(), + ) + .await; + configure_remote_plugin_test(codex_home.path(), &server)?; + mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await; + mount_empty_remote_installed_plugins(&server).await; + mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await; + + let mut mcp = McpProcess::new_with_env( + codex_home.path(), + &[(TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1"))], + ) + .await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?; + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32603); + assert!(err.error.message.contains("failed with status 503")); + wait_for_remote_plugin_request_count( + &server, + "GET", + "/bundles/linear.tar.gz", + /*expected_count*/ 1, + ) + .await?; + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/ps/plugins/{REMOTE_PLUGIN_ID}/install"), + /*expected_count*/ 0, + ) + .await?; + assert!( + !codex_home + .path() + .join("plugins/cache/chatgpt-global/linear") + .exists() + ); + Ok(()) +} + #[tokio::test] async fn plugin_install_returns_apps_needing_auth() -> Result<()> { let connectors = vec![ @@ -1014,6 +1173,152 @@ remote_plugin = true ) } +fn configure_remote_plugin_test(codex_home: &std::path::Path, server: &MockServer) -> Result<()> { + write_remote_plugin_catalog_config(codex_home, &format!("{}/backend-api/", server.uri()))?; + write_chatgpt_auth( + codex_home, + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + ) +} + +async fn mount_remote_plugin_bundle( + server: &MockServer, + status_code: u16, + body: Vec, +) -> String { + Mock::given(method("GET")) + .and(path("/bundles/linear.tar.gz")) + .respond_with( + ResponseTemplate::new(status_code) + .insert_header("content-type", "application/gzip") + .set_body_bytes(body), + ) + .mount(server) + .await; + format!("{}/bundles/linear.tar.gz", server.uri()) +} + +async fn mount_remote_plugin_detail( + server: &MockServer, + remote_plugin_id: &str, + release_version: &str, + bundle_download_url: Option<&str>, +) { + let bundle_download_url_field = bundle_download_url + .map(|url| format!(r#" "bundle_download_url": "{url}","#)) + .unwrap_or_default(); + let detail_body = format!( + r#"{{ + "id": "{remote_plugin_id}", + "name": "linear", + "scope": "GLOBAL", + "installation_policy": "AVAILABLE", + "authentication_policy": "ON_USE", + "release": {{ + "version": "{release_version}", +{bundle_download_url_field} + "display_name": "Linear", + "description": "Track work in Linear", + "app_ids": [], + "interface": {{ + "short_description": "Plan and track work" + }}, + "skills": [] + }} +}}"# + ); + + Mock::given(method("GET")) + .and(path(format!("/backend-api/ps/plugins/{remote_plugin_id}"))) + .and(query_param("includeDownloadUrls", "true")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_string(detail_body)) + .mount(server) + .await; +} + +async fn mount_empty_remote_installed_plugins(server: &MockServer) { + Mock::given(method("GET")) + .and(path("/backend-api/ps/plugins/installed")) + .and(query_param("scope", "GLOBAL")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{ + "plugins": [], + "pagination": { + "limit": 50, + "next_page_token": null + } +}"#, + )) + .mount(server) + .await; +} + +async fn mount_remote_plugin_install(server: &MockServer, remote_plugin_id: &str) { + Mock::given(method("POST")) + .and(path(format!( + "/backend-api/ps/plugins/{remote_plugin_id}/install" + ))) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(format!(r#"{{"id":"{remote_plugin_id}","enabled":true}}"#)), + ) + .mount(server) + .await; +} + +#[derive(Debug, Clone)] +struct CacheManifestExists { + manifest_path: std::path::PathBuf, +} + +impl Match for CacheManifestExists { + fn matches(&self, _request: &Request) -> bool { + self.manifest_path.is_file() + } +} + +async fn mount_remote_plugin_install_after_cache_write( + server: &MockServer, + remote_plugin_id: &str, + manifest_path: std::path::PathBuf, +) { + Mock::given(method("POST")) + .and(path(format!( + "/backend-api/ps/plugins/{remote_plugin_id}/install" + ))) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .and(CacheManifestExists { manifest_path }) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(format!(r#"{{"id":"{remote_plugin_id}","enabled":true}}"#)), + ) + .mount(server) + .await; +} + +async fn send_remote_plugin_install_request( + mcp: &mut McpProcess, + remote_plugin_id: &str, +) -> Result { + mcp.send_plugin_install_request(PluginInstallParams { + marketplace_path: None, + remote_marketplace_name: Some("chatgpt-global".to_string()), + plugin_name: remote_plugin_id.to_string(), + }) + .await +} + async fn wait_for_remote_plugin_request_count( server: &MockServer, method_name: &str, @@ -1115,3 +1420,29 @@ fn write_plugin_source( )?; Ok(()) } + +fn remote_plugin_bundle_tar_gz_bytes(plugin_name: &str) -> Result> { + let manifest = format!(r#"{{"name":"{plugin_name}"}}"#); + let skill = "# Plan Work\n\nTrack work in Linear.\n"; + let encoder = GzEncoder::new(Vec::new(), Compression::default()); + let mut tar = tar::Builder::new(encoder); + for (path, contents, mode) in [ + ( + ".codex-plugin/plugin.json", + manifest.as_bytes(), + /*mode*/ 0o644, + ), + ( + "skills/plan-work/SKILL.md", + skill.as_bytes(), + /*mode*/ 0o644, + ), + ] { + let mut header = tar::Header::new_gnu(); + header.set_size(contents.len() as u64); + header.set_mode(mode); + header.set_cksum(); + tar.append_data(&mut header, path, contents)?; + } + Ok(tar.into_inner()?.finish()?) +} 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 8735c20ff6..23f6e54969 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_list.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_list.rs @@ -1131,7 +1131,7 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - let global_directory_body = r#"{ "plugins": [ { - "id": "plugins~Plugin_linear", + "id": "plugins~Plugin_00000000000000000000000000000000", "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", @@ -1165,7 +1165,7 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - let global_installed_body = r#"{ "plugins": [ { - "id": "plugins~Plugin_linear", + "id": "plugins~Plugin_00000000000000000000000000000000", "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", @@ -1255,7 +1255,10 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - Some("ChatGPT Plugins") ); assert_eq!(remote_marketplace.plugins.len(), 1); - assert_eq!(remote_marketplace.plugins[0].id, "plugins~Plugin_linear"); + assert_eq!( + remote_marketplace.plugins[0].id, + "plugins~Plugin_00000000000000000000000000000000" + ); assert_eq!(remote_marketplace.plugins[0].name, "linear"); assert_eq!(remote_marketplace.plugins[0].source, PluginSource::Remote); assert_eq!(remote_marketplace.plugins[0].installed, true); @@ -1314,7 +1317,7 @@ async fn plugin_list_remote_marketplace_replaces_local_marketplace_with_same_nam let global_directory_body = r#"{ "plugins": [ { - "id": "plugins~Plugin_linear", + "id": "plugins~Plugin_00000000000000000000000000000000", "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", diff --git a/codex-rs/app-server/tests/suite/v2/plugin_read.rs b/codex-rs/app-server/tests/suite/v2/plugin_read.rs index 5360c381d8..753468345f 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_read.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_read.rs @@ -161,7 +161,7 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() -> )?; let detail_body = r#"{ - "id": "plugins~Plugin_linear", + "id": "plugins~Plugin_00000000000000000000000000000000", "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", @@ -192,7 +192,7 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() -> let installed_body = r#"{ "plugins": [ { - "id": "plugins~Plugin_linear", + "id": "plugins~Plugin_00000000000000000000000000000000", "name": "linear", "scope": "GLOBAL", "installation_policy": "AVAILABLE", @@ -230,7 +230,9 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() -> }"#; Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/plugins~Plugin_linear")) + .and(path( + "/backend-api/ps/plugins/plugins~Plugin_00000000000000000000000000000000", + )) .and(header("authorization", "Bearer chatgpt-token")) .and(header("chatgpt-account-id", "account-123")) .respond_with(ResponseTemplate::new(200).set_body_string(detail_body)) @@ -252,7 +254,7 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() -> .send_plugin_read_request(PluginReadParams { marketplace_path: None, remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "plugins~Plugin_linear".to_string(), + plugin_name: "plugins~Plugin_00000000000000000000000000000000".to_string(), }) .await?; @@ -266,7 +268,10 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() -> assert_eq!(response.plugin.marketplace_name, "chatgpt-global"); assert_eq!(response.plugin.marketplace_path, None); assert_eq!(response.plugin.summary.source, PluginSource::Remote); - assert_eq!(response.plugin.summary.id, "plugins~Plugin_linear"); + assert_eq!( + response.plugin.summary.id, + "plugins~Plugin_00000000000000000000000000000000" + ); assert_eq!(response.plugin.summary.name, "linear"); assert_eq!(response.plugin.summary.installed, true); assert_eq!(response.plugin.summary.enabled, false); diff --git a/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs b/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs index 512cce3994..e0f71f11b5 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs @@ -1,6 +1,7 @@ use std::time::Duration; use anyhow::Result; +use anyhow::bail; use app_test_support::ChatGptAuthFixture; use app_test_support::DEFAULT_CLIENT_NAME; use app_test_support::McpProcess; @@ -16,8 +17,15 @@ use pretty_assertions::assert_eq; use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::header; +use wiremock::matchers::method; +use wiremock::matchers::path; const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); +const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_linear"; #[tokio::test] async fn plugin_uninstall_removes_plugin_cache_and_config_entry() -> Result<()> { @@ -143,6 +151,340 @@ async fn plugin_uninstall_tracks_analytics_event() -> Result<()> { Ok(()) } +#[tokio::test] +async fn plugin_uninstall_rejects_remote_plugin_when_remote_plugin_is_disabled() -> Result<()> { + let codex_home = TempDir::new()?; + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: "plugins~Plugin_sample".to_string(), + }) + .await?; + + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32600); + assert!( + err.error + .message + .contains("remote plugin uninstall is not enabled") + ); + Ok(()) +} + +#[tokio::test] +async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabled() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + write_remote_plugin_catalog_config( + codex_home.path(), + &format!("{}/backend-api/", server.uri()), + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + + mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.0.0", "GLOBAL").await; + mount_empty_remote_installed_plugins(&server).await; + + Mock::given(method("POST")) + .and(path(format!( + "/backend-api/plugins/{REMOTE_PLUGIN_ID}/uninstall" + ))) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(format!(r#"{{"id":"{REMOTE_PLUGIN_ID}","enabled":false}}"#)), + ) + .mount(&server) + .await; + + let remote_plugin_cache_root = codex_home + .path() + .join("plugins/cache/chatgpt-global/linear"); + std::fs::create_dir_all(remote_plugin_cache_root.join("1.0.0/.codex-plugin"))?; + std::fs::write( + remote_plugin_cache_root.join("1.0.0/.codex-plugin/plugin.json"), + r#"{"name":"linear","version":"1.0.0"}"#, + )?; + let legacy_remote_plugin_cache_root = codex_home + .path() + .join(format!("plugins/cache/chatgpt-global/{REMOTE_PLUGIN_ID}")); + std::fs::create_dir_all(legacy_remote_plugin_cache_root.join("local/.codex-plugin"))?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: REMOTE_PLUGIN_ID.to_string(), + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let response: PluginUninstallResponse = to_response(response)?; + + assert_eq!(response, PluginUninstallResponse {}); + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/plugins/{REMOTE_PLUGIN_ID}/uninstall"), + /*expected_count*/ 1, + ) + .await?; + assert!(!remote_plugin_cache_root.exists()); + assert!(!legacy_remote_plugin_cache_root.exists()); + Ok(()) +} + +#[tokio::test] +async fn plugin_uninstall_uses_detail_scope_for_cache_namespace() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + write_remote_plugin_catalog_config( + codex_home.path(), + &format!("{}/backend-api/", server.uri()), + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.0.0", "WORKSPACE").await; + mount_empty_remote_installed_plugins(&server).await; + + Mock::given(method("POST")) + .and(path(format!( + "/backend-api/plugins/{REMOTE_PLUGIN_ID}/uninstall" + ))) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(format!(r#"{{"id":"{REMOTE_PLUGIN_ID}","enabled":false}}"#)), + ) + .mount(&server) + .await; + + let workspace_cache_root = codex_home + .path() + .join("plugins/cache/chatgpt-workspace/linear"); + std::fs::create_dir_all(workspace_cache_root.join("1.0.0/.codex-plugin"))?; + std::fs::write( + workspace_cache_root.join("1.0.0/.codex-plugin/plugin.json"), + r#"{"name":"linear","version":"1.0.0"}"#, + )?; + let global_cache_root = codex_home + .path() + .join("plugins/cache/chatgpt-global/linear"); + std::fs::create_dir_all(global_cache_root.join("1.0.0/.codex-plugin"))?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: REMOTE_PLUGIN_ID.to_string(), + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let response: PluginUninstallResponse = to_response(response)?; + + assert_eq!(response, PluginUninstallResponse {}); + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/plugins/{REMOTE_PLUGIN_ID}/uninstall"), + /*expected_count*/ 1, + ) + .await?; + assert!(!workspace_cache_root.exists()); + assert!(global_cache_root.exists()); + Ok(()) +} + +#[tokio::test] +async fn plugin_uninstall_posts_even_when_remote_detail_fetch_fails() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + write_remote_plugin_catalog_config( + codex_home.path(), + &format!("{}/backend-api/", server.uri()), + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + + Mock::given(method("POST")) + .and(path(format!( + "/backend-api/plugins/{REMOTE_PLUGIN_ID}/uninstall" + ))) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(format!(r#"{{"id":"{REMOTE_PLUGIN_ID}","enabled":false}}"#)), + ) + .mount(&server) + .await; + + let legacy_remote_plugin_cache_root = codex_home + .path() + .join(format!("plugins/cache/chatgpt-global/{REMOTE_PLUGIN_ID}")); + std::fs::create_dir_all(legacy_remote_plugin_cache_root.join("local/.codex-plugin"))?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: REMOTE_PLUGIN_ID.to_string(), + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let response: PluginUninstallResponse = to_response(response)?; + + assert_eq!(response, PluginUninstallResponse {}); + wait_for_remote_plugin_request_count( + &server, + "POST", + &format!("/plugins/{REMOTE_PLUGIN_ID}/uninstall"), + /*expected_count*/ 1, + ) + .await?; + assert!(!legacy_remote_plugin_cache_root.exists()); + Ok(()) +} + +#[tokio::test] +async fn plugin_uninstall_rejects_malformed_local_plugin_id_before_remote_path() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + write_remote_plugin_catalog_config( + codex_home.path(), + &format!("{}/backend-api/", server.uri()), + )?; + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: "sample-plugin".to_string(), + }) + .await?; + + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32600); + assert!(err.error.message.contains("invalid plugin id")); + wait_for_remote_plugin_request_count( + &server, + "POST", + "/plugins/sample-plugin/uninstall", + /*expected_count*/ 0, + ) + .await?; + Ok(()) +} + +#[tokio::test] +async fn plugin_uninstall_rejects_invalid_remote_plugin_id_before_network_call() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + write_remote_plugin_catalog_config( + codex_home.path(), + &format!("{}/backend-api/", server.uri()), + )?; + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: "linear/../../oops".to_string(), + }) + .await?; + + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32600); + assert!(err.error.message.contains("invalid plugin id")); + wait_for_remote_plugin_request_count( + &server, + "POST", + "/plugins/linear/../../oops/uninstall", + /*expected_count*/ 0, + ) + .await?; + Ok(()) +} + +#[tokio::test] +async fn plugin_uninstall_rejects_empty_remote_plugin_id() -> Result<()> { + let codex_home = TempDir::new()?; + let server = MockServer::start().await; + write_remote_plugin_catalog_config( + codex_home.path(), + &format!("{}/backend-api/", server.uri()), + )?; + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_plugin_uninstall_request(PluginUninstallParams { + plugin_id: String::new(), + }) + .await?; + let err = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + + assert_eq!(err.error.code, -32600); + assert!(err.error.message.contains("invalid plugin id")); + + Ok(()) +} + fn write_installed_plugin( codex_home: &TempDir, marketplace_name: &str, @@ -161,3 +503,109 @@ fn write_installed_plugin( )?; Ok(()) } + +fn write_remote_plugin_catalog_config( + codex_home: &std::path::Path, + base_url: &str, +) -> std::io::Result<()> { + std::fs::write( + codex_home.join("config.toml"), + format!( + r#" +chatgpt_base_url = "{base_url}" + +[features] +plugins = true +remote_plugin = true +"# + ), + ) +} + +async fn mount_remote_plugin_detail( + server: &MockServer, + remote_plugin_id: &str, + release_version: &str, + scope: &str, +) { + let detail_body = format!( + r#"{{ + "id": "{remote_plugin_id}", + "name": "linear", + "scope": "{scope}", + "installation_policy": "AVAILABLE", + "authentication_policy": "ON_USE", + "release": {{ + "version": "{release_version}", + "display_name": "Linear", + "description": "Track work in Linear", + "app_ids": [], + "interface": {{ + "short_description": "Plan and track work" + }}, + "skills": [] + }} +}}"# + ); + + Mock::given(method("GET")) + .and(path(format!("/backend-api/ps/plugins/{remote_plugin_id}"))) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_string(detail_body)) + .mount(server) + .await; +} + +async fn mount_empty_remote_installed_plugins(server: &MockServer) { + Mock::given(method("GET")) + .and(path("/backend-api/ps/plugins/installed")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{ + "plugins": [], + "pagination": { + "limit": 50, + "next_page_token": null + } +}"#, + )) + .mount(server) + .await; +} + +async fn wait_for_remote_plugin_request_count( + server: &MockServer, + method_name: &str, + path_suffix: &str, + expected_count: usize, +) -> Result<()> { + timeout(DEFAULT_TIMEOUT, async { + loop { + let Some(requests) = server.received_requests().await else { + if expected_count == 0 { + return Ok::<(), anyhow::Error>(()); + } + bail!("wiremock did not record requests"); + }; + let request_count = requests + .iter() + .filter(|request| { + request.method == method_name && request.url.path().ends_with(path_suffix) + }) + .count(); + if request_count == expected_count { + return Ok::<(), anyhow::Error>(()); + } + if request_count > expected_count { + bail!( + "expected exactly {expected_count} {method_name} {path_suffix} requests, got {request_count}" + ); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await??; + Ok(()) +} diff --git a/codex-rs/app-server/tests/suite/v2/thread_fork.rs b/codex-rs/app-server/tests/suite/v2/thread_fork.rs index 6c43ebd626..fd773f2e30 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -42,7 +42,7 @@ use wiremock::matchers::method; use wiremock::matchers::path; use super::analytics::assert_basic_thread_initialized_event; -use super::analytics::enable_analytics_capture; +use super::analytics::mount_analytics_capture; use super::analytics::thread_initialized_event; use super::analytics::wait_for_analytics_payload; @@ -385,13 +385,8 @@ async fn thread_fork_tracks_thread_initialized_analytics() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; - create_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &server.uri(), - /*general_analytics_enabled*/ true, - )?; - enable_analytics_capture(&server, codex_home.path()).await?; + create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?; + mount_analytics_capture(&server, codex_home.path()).await?; let conversation_id = create_fake_rollout( codex_home.path(), @@ -496,7 +491,6 @@ async fn thread_fork_surfaces_cloud_requirements_load_errors() -> Result<()> { codex_home.path(), &model_server.uri(), &chatgpt_base_url, - /*general_analytics_enabled*/ false, )?; write_chatgpt_auth( codex_home.path(), @@ -793,13 +787,7 @@ fn create_config_toml_with_chatgpt_base_url( codex_home: &Path, server_uri: &str, chatgpt_base_url: &str, - general_analytics_enabled: bool, ) -> std::io::Result<()> { - let general_analytics_toml = if general_analytics_enabled { - "\ngeneral_analytics = true".to_string() - } else { - "\ngeneral_analytics = false".to_string() - }; let config_toml = codex_home.join("config.toml"); std::fs::write( config_toml, @@ -812,9 +800,6 @@ chatgpt_base_url = "{chatgpt_base_url}" model_provider = "mock_provider" -[features] -{general_analytics_toml} - [model_providers.mock_provider] name = "Mock provider for test" base_url = "{server_uri}/v1" diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 5044fcd11a..d9f5f039de 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -84,7 +84,7 @@ use wiremock::matchers::method; use wiremock::matchers::path; use super::analytics::assert_basic_thread_initialized_event; -use super::analytics::enable_analytics_capture; +use super::analytics::mount_analytics_capture; use super::analytics::thread_initialized_event; use super::analytics::wait_for_analytics_payload; @@ -185,10 +185,7 @@ async fn thread_goal_get_rejects_unmaterialized_thread() -> Result<()> { let config = std::fs::read_to_string(&config_path)?; std::fs::write( &config_path, - config.replace( - "general_analytics = true\n", - "general_analytics = true\ngoals = true\n", - ), + config.replace("personality = true\n", "personality = true\ngoals = true\n"), )?; let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; @@ -238,13 +235,8 @@ async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; - create_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &server.uri(), - /*general_analytics_enabled*/ true, - )?; - enable_analytics_capture(&server, codex_home.path()).await?; + create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?; + mount_analytics_capture(&server, codex_home.path()).await?; let conversation_id = create_fake_rollout_with_text_elements( codex_home.path(), @@ -400,10 +392,7 @@ async fn thread_resume_emits_active_goal_update_before_continuation() -> Result< let config = std::fs::read_to_string(&config_path)?; std::fs::write( &config_path, - config.replace( - "general_analytics = true\n", - "general_analytics = true\ngoals = true\n", - ), + config.replace("personality = true\n", "personality = true\ngoals = true\n"), )?; let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; @@ -507,10 +496,7 @@ async fn thread_goal_set_preserves_budget_limited_same_objective() -> Result<()> let config = std::fs::read_to_string(&config_path)?; std::fs::write( &config_path, - config.replace( - "general_analytics = true\n", - "general_analytics = true\ngoals = true\n", - ), + config.replace("personality = true\n", "personality = true\ngoals = true\n"), )?; let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; @@ -608,10 +594,7 @@ async fn thread_goal_clear_deletes_goal_and_notifies() -> Result<()> { let config = std::fs::read_to_string(&config_path)?; std::fs::write( &config_path, - config.replace( - "general_analytics = true\n", - "general_analytics = true\ngoals = true\n", - ), + config.replace("personality = true\n", "personality = true\ngoals = true\n"), )?; let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; @@ -2414,7 +2397,6 @@ async fn thread_resume_surfaces_cloud_requirements_load_errors() -> Result<()> { codex_home.path(), &model_server.uri(), &chatgpt_base_url, - /*general_analytics_enabled*/ false, )?; write_chatgpt_auth( codex_home.path(), @@ -2859,7 +2841,6 @@ model_provider = "mock_provider" [features] personality = true -general_analytics = true [model_providers.mock_provider] name = "Mock provider for test" @@ -2890,7 +2871,6 @@ model_provider = "mock_provider" [features] personality = true -general_analytics = true [model_providers.mock_provider] name = "Mock provider for test" @@ -2907,13 +2887,7 @@ fn create_config_toml_with_chatgpt_base_url( codex_home: &std::path::Path, server_uri: &str, chatgpt_base_url: &str, - general_analytics_enabled: bool, ) -> std::io::Result<()> { - let general_analytics_toml = if general_analytics_enabled { - "\ngeneral_analytics = true".to_string() - } else { - "\ngeneral_analytics = false".to_string() - }; let config_toml = codex_home.join("config.toml"); std::fs::write( config_toml, @@ -2928,7 +2902,6 @@ model_provider = "mock_provider" [features] personality = true -{general_analytics_toml} [model_providers.mock_provider] name = "Mock provider for test" diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index f521d5509c..d8a50b88a4 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -34,7 +34,6 @@ use serde_json::Value; use serde_json::json; use std::path::Path; use std::path::PathBuf; -use std::time::Duration; use tempfile::TempDir; use tokio::time::timeout; use wiremock::Mock; @@ -265,12 +264,7 @@ async fn thread_start_tracks_thread_initialized_analytics() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; - create_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &server.uri(), - /*general_analytics_enabled*/ true, - )?; + create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?; mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; @@ -293,54 +287,6 @@ async fn thread_start_tracks_thread_initialized_analytics() -> Result<()> { Ok(()) } -#[tokio::test] -async fn thread_start_does_not_track_thread_initialized_analytics_without_feature() -> Result<()> { - let server = create_mock_responses_server_repeating_assistant("Done").await; - - let codex_home = TempDir::new()?; - create_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &server.uri(), - /*general_analytics_enabled*/ false, - )?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let req_id = mcp - .send_thread_start_request(ThreadStartParams::default()) - .await?; - let resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(req_id)), - ) - .await??; - let _ = to_response::(resp)?; - - assert_no_thread_initialized_analytics(&server, Duration::from_millis(250)).await?; - Ok(()) -} - -async fn assert_no_thread_initialized_analytics( - server: &MockServer, - wait_duration: Duration, -) -> Result<()> { - tokio::time::sleep(wait_duration).await; - let requests = server.received_requests().await.unwrap_or_default(); - for request in requests.iter().filter(|request| { - request.method == "POST" && request.url.path() == "/codex/analytics-events/events" - }) { - let payload: Value = serde_json::from_slice(&request.body)?; - assert!( - thread_initialized_event(&payload).is_err(), - "thread analytics should be gated off when general_analytics is disabled; payload={payload}" - ); - } - Ok(()) -} - #[tokio::test] async fn thread_start_respects_project_config_from_cwd() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; @@ -643,7 +589,6 @@ async fn thread_start_surfaces_cloud_requirements_load_errors() -> Result<()> { codex_home.path(), &model_server.uri(), &chatgpt_base_url, - /*general_analytics_enabled*/ false, )?; write_chatgpt_auth( codex_home.path(), @@ -966,13 +911,7 @@ fn create_config_toml_with_chatgpt_base_url( codex_home: &Path, server_uri: &str, chatgpt_base_url: &str, - general_analytics_enabled: bool, ) -> std::io::Result<()> { - let general_analytics_toml = if general_analytics_enabled { - "\ngeneral_analytics = true".to_string() - } else { - "\ngeneral_analytics = false".to_string() - }; let config_toml = codex_home.join("config.toml"); std::fs::write( config_toml, @@ -985,9 +924,6 @@ chatgpt_base_url = "{chatgpt_base_url}" model_provider = "mock_provider" -[features] -{general_analytics_toml} - [model_providers.mock_provider] name = "Mock provider for test" base_url = "{server_uri}/v1" diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 6d66edd3d3..f81ec5f168 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -78,7 +78,6 @@ use std::path::Path; use tempfile::TempDir; use tokio::time::timeout; -use super::analytics::enable_analytics_capture; use super::analytics::mount_analytics_capture; use super::analytics::wait_for_analytics_event; @@ -463,7 +462,7 @@ async fn turn_start_tracks_turn_event_analytics() -> Result<()> { &server.uri(), &server.uri(), )?; - enable_analytics_capture(&server, codex_home.path()).await?; + mount_analytics_capture(&server, codex_home.path()).await?; let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; @@ -538,77 +537,6 @@ async fn turn_start_tracks_turn_event_analytics() -> Result<()> { Ok(()) } -#[tokio::test] -async fn turn_start_does_not_track_turn_event_analytics_without_feature() -> Result<()> { - let responses = vec![create_final_assistant_message_sse_response("Done")?]; - let server = create_mock_responses_server_sequence_unchecked(responses).await; - - let codex_home = TempDir::new()?; - write_mock_responses_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &server.uri(), - )?; - let config_path = codex_home.path().join("config.toml"); - let config_toml = std::fs::read_to_string(&config_path)?; - std::fs::write( - &config_path, - format!("{config_toml}\n[features]\ngeneral_analytics = false\n"), - )?; - mount_analytics_capture(&server, codex_home.path()).await?; - - let mut mcp = McpProcess::new_without_managed_config(codex_home.path()).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - - let thread_req = mcp - .send_thread_start_request(ThreadStartParams { - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - let thread_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), - ) - .await??; - let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; - - let turn_req = mcp - .send_turn_start_request(TurnStartParams { - thread_id: thread.id, - input: vec![V2UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - let turn_resp: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), - ) - .await??; - let _ = to_response::(turn_resp)?; - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("turn/completed"), - ) - .await??; - - let turn_event = wait_for_analytics_event( - &server, - std::time::Duration::from_millis(250), - "codex_turn_event", - ) - .await; - assert!( - turn_event.is_err(), - "turn analytics should be gated off when general_analytics is disabled" - ); - Ok(()) -} - #[tokio::test] async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> { let responses = vec![create_final_assistant_message_sse_response("Done")?]; diff --git a/codex-rs/app-server/tests/suite/v2/turn_steer.rs b/codex-rs/app-server/tests/suite/v2/turn_steer.rs index 16e28d6cc5..a92b2db528 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_steer.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_steer.rs @@ -24,7 +24,7 @@ use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use tempfile::TempDir; use tokio::time::timeout; -use super::analytics::enable_analytics_capture; +use super::analytics::mount_analytics_capture; use super::analytics::wait_for_analytics_event; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); @@ -41,7 +41,7 @@ async fn turn_steer_requires_active_turn() -> Result<()> { &server.uri(), &server.uri(), )?; - enable_analytics_capture(&server, &codex_home).await?; + mount_analytics_capture(&server, &codex_home).await?; let mut mcp = McpProcess::new_without_managed_config(&codex_home).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; @@ -125,7 +125,7 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> { &server.uri(), &server.uri(), )?; - enable_analytics_capture(&server, &codex_home).await?; + mount_analytics_capture(&server, &codex_home).await?; let mut mcp = McpProcess::new_without_managed_config(&codex_home).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; @@ -234,7 +234,7 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { &server.uri(), &server.uri(), )?; - enable_analytics_capture(&server, &codex_home).await?; + mount_analytics_capture(&server, &codex_home).await?; let mut mcp = McpProcess::new_without_managed_config(&codex_home).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; diff --git a/codex-rs/chatgpt/src/chatgpt_client.rs b/codex-rs/chatgpt/src/chatgpt_client.rs index 42aac41138..05d8186686 100644 --- a/codex-rs/chatgpt/src/chatgpt_client.rs +++ b/codex-rs/chatgpt/src/chatgpt_client.rs @@ -21,7 +21,7 @@ pub(crate) async fn chatgpt_get_request_with_timeout( ) -> anyhow::Result { let chatgpt_base_url = &config.chatgpt_base_url; let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await; let auth = auth_manager .auth() .await diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index 62e8040940..9dba71ce3a 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -26,7 +26,7 @@ const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60); async fn apps_enabled(config: &Config) -> bool { let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await; let auth = auth_manager.auth().await; config .features @@ -35,7 +35,7 @@ async fn apps_enabled(config: &Config) -> bool { async fn connector_auth(config: &Config) -> anyhow::Result { let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await; let auth = auth_manager .auth() .await diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index 5f4f3aee10..cdee241b42 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -35,6 +35,7 @@ codex-exec-server = { workspace = true } codex-execpolicy = { workspace = true } codex-features = { workspace = true } codex-login = { workspace = true } +codex-memories-write = { workspace = true } codex-mcp = { workspace = true } codex-mcp-server = { workspace = true } codex-models-manager = { workspace = true } diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 4fa7272ae4..5c60c20cbf 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -362,7 +362,9 @@ pub async fn run_login_with_device_code_fallback_to_browser( pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! { let config = load_config_or_exit(cli_config_overrides).await; - match CodexAuth::from_auth_storage(&config.codex_home, config.cli_auth_credentials_store_mode) { + match CodexAuth::from_auth_storage(&config.codex_home, config.cli_auth_credentials_store_mode) + .await + { Ok(Some(auth)) => match auth.auth_mode() { AuthMode::ApiKey => match auth.get_token() { Ok(api_key) => { diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 9f465521da..1c2eabf986 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -52,7 +52,6 @@ use crate::marketplace_cmd::MarketplaceCli; use crate::mcp_cmd::McpCli; use codex_core::build_models_manager; -use codex_core::clear_memory_roots_contents; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config::edit::ConfigEditsBuilder; @@ -61,6 +60,7 @@ use codex_features::FEATURES; use codex_features::Stage; use codex_features::is_known_feature_key; use codex_login::AuthManager; +use codex_memories_write::clear_memory_roots_contents; use codex_models_manager::bundled_models_response; use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig; use codex_models_manager::manager::RefreshStrategy; @@ -134,6 +134,9 @@ enum Subcommand { /// Generate shell completion scripts. Completion(CompletionCommand), + /// Update Codex to the latest version. + Update, + /// Run commands within a Codex-provided sandbox. Sandbox(SandboxArgs), @@ -615,6 +618,25 @@ fn run_update_action(action: UpdateAction) -> anyhow::Result<()> { Ok(()) } +fn run_update_command() -> anyhow::Result<()> { + #[cfg(debug_assertions)] + { + anyhow::bail!( + "`codex update` is not available in debug builds. Install a release build of Codex to use this command." + ); + } + + #[cfg(not(debug_assertions))] + { + let Some(action) = codex_tui::get_update_action() else { + anyhow::bail!( + "Could not detect the Codex installation method. Please update manually: https://developers.openai.com/codex/cli/" + ); + }; + run_update_action(action) + } +} + fn run_execpolicycheck(cmd: ExecPolicyCheckCommand) -> anyhow::Result<()> { cmd.run() } @@ -998,6 +1020,14 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { )?; print_completion(completion_cli); } + Some(Subcommand::Update) => { + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "update", + )?; + run_update_command()?; + } Some(Subcommand::Cloud(mut cloud_cli)) => { reject_remote_mode_for_subcommand( root_remote.as_deref(), @@ -1384,7 +1414,7 @@ async fn run_debug_models_command( .map_err(anyhow::Error::msg)?; let config = Config::load_with_cli_overrides(cli_overrides).await?; let auth_manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ true); + AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ true).await; let models_manager = build_models_manager(&config, auth_manager, CollaborationModesConfig::default()); models_manager @@ -1890,6 +1920,12 @@ mod tests { assert!(matches!(cli.subcommand, Some(Subcommand::Plugin(_)))); } + #[test] + fn update_parses_as_update_subcommand() { + let cli = MultitoolCli::try_parse_from(["codex", "update"]).expect("parse"); + assert!(matches!(cli.subcommand, Some(Subcommand::Update))); + } + #[test] fn plugin_marketplace_remove_parses_under_plugin() { let cli = diff --git a/codex-rs/cli/tests/marketplace_upgrade.rs b/codex-rs/cli/tests/marketplace_upgrade.rs index 081203ebef..268d75358e 100644 --- a/codex-rs/cli/tests/marketplace_upgrade.rs +++ b/codex-rs/cli/tests/marketplace_upgrade.rs @@ -30,7 +30,7 @@ async fn marketplace_upgrade_no_longer_runs_at_top_level() -> Result<()> { .args(["marketplace", "upgrade"]) .assert() .failure() - .stderr(contains("unexpected argument 'upgrade' found")); + .stderr(contains("unrecognized subcommand 'upgrade'")); Ok(()) } diff --git a/codex-rs/cli/tests/update.rs b/codex-rs/cli/tests/update.rs new file mode 100644 index 0000000000..cf1742cda7 --- /dev/null +++ b/codex-rs/cli/tests/update.rs @@ -0,0 +1,24 @@ +use anyhow::Result; +use predicates::str::contains; +use std::path::Path; +use tempfile::TempDir; + +fn codex_command(codex_home: &Path) -> Result { + let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); + cmd.env("CODEX_HOME", codex_home); + Ok(cmd) +} + +#[cfg(debug_assertions)] +#[tokio::test] +async fn update_does_not_start_interactive_prompt() -> Result<()> { + let codex_home = TempDir::new()?; + + codex_command(codex_home.path())? + .arg("update") + .assert() + .failure() + .stderr(contains("`codex update` is not available in debug builds")); + + Ok(()) +} diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index 86a12e7d17..d38fbb0846 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -727,7 +727,7 @@ pub fn cloud_requirements_loader( }) } -pub fn cloud_requirements_loader_for_storage( +pub async fn cloud_requirements_loader_for_storage( codex_home: PathBuf, enable_codex_api_key_env: bool, credentials_store_mode: AuthCredentialsStoreMode, @@ -738,7 +738,8 @@ pub fn cloud_requirements_loader_for_storage( enable_codex_api_key_env, credentials_store_mode, Some(chatgpt_base_url.clone()), - ); + ) + .await; cloud_requirements_loader(auth_manager, chatgpt_base_url, codex_home) } @@ -853,7 +854,7 @@ mod tests { Ok(()) } - fn auth_manager_with_api_key() -> Arc { + async fn auth_manager_with_api_key() -> Arc { let tmp = tempdir().expect("tempdir"); let auth_json = json!({ "OPENAI_API_KEY": "sk-test-key", @@ -861,15 +862,18 @@ mod tests { "last_refresh": null, }); write_auth_json(tmp.path(), auth_json).expect("write auth"); - Arc::new(AuthManager::new( - tmp.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - )) + Arc::new( + AuthManager::new( + tmp.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await, + ) } - fn auth_manager_with_plan_and_identity( + async fn auth_manager_with_plan_and_identity( plan_type: &str, chatgpt_user_id: Option<&str>, account_id: Option<&str>, @@ -886,12 +890,15 @@ mod tests { ), ) .expect("write auth"); - Arc::new(AuthManager::new( - tmp.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - )) + Arc::new( + AuthManager::new( + tmp.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await, + ) } fn chatgpt_auth_json( @@ -975,7 +982,7 @@ mod tests { manager: Arc, } - fn managed_auth_context( + async fn managed_auth_context( plan_type: &str, chatgpt_user_id: Option<&str>, account_id: Option<&str>, @@ -995,18 +1002,22 @@ mod tests { ) .expect("write auth"); ManagedAuthContext { - manager: Arc::new(AuthManager::new( - home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - )), + manager: Arc::new( + AuthManager::new( + home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await, + ), _home: home, } } - fn auth_manager_with_plan(plan_type: &str) -> Arc { + async fn auth_manager_with_plan(plan_type: &str) -> Arc { auth_manager_with_plan_and_identity(plan_type, Some("user-12345"), Some("account-12345")) + .await } fn parse_for_fetch(contents: Option<&str>) -> Option { @@ -1118,7 +1129,7 @@ mod tests { #[tokio::test] async fn fetch_cloud_requirements_skips_non_chatgpt_auth() { - let auth_manager = auth_manager_with_api_key(); + let auth_manager = auth_manager_with_api_key().await; let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( auth_manager, @@ -1134,7 +1145,7 @@ mod tests { async fn fetch_cloud_requirements_skips_non_business_or_enterprise_plan() { let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("pro"), + auth_manager_with_plan("pro").await, Arc::new(StaticFetcher { contents: None }), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1147,7 +1158,7 @@ mod tests { async fn fetch_cloud_requirements_skips_team_like_usage_based_plan() { let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("self_serve_business_usage_based"), + auth_manager_with_plan("self_serve_business_usage_based").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1161,7 +1172,7 @@ mod tests { async fn fetch_cloud_requirements_allows_business_plan() { let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1193,7 +1204,7 @@ mod tests { async fn fetch_cloud_requirements_allows_business_like_usage_based_plan() { let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("enterprise_cbp_usage_based"), + auth_manager_with_plan("enterprise_cbp_usage_based").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1225,7 +1236,7 @@ mod tests { async fn fetch_cloud_requirements_allows_hc_plan_as_enterprise() { let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("hc"), + auth_manager_with_plan("hc").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1329,7 +1340,7 @@ enabled = false #[tokio::test(start_paused = true)] async fn fetch_cloud_requirements_times_out() { - let auth_manager = auth_manager_with_plan("enterprise"); + let auth_manager = auth_manager_with_plan("enterprise").await; let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( auth_manager, @@ -1356,7 +1367,7 @@ enabled = false ])); let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1405,12 +1416,15 @@ enabled = false ), ) .expect("write initial auth"); - let auth_manager = Arc::new(AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - )); + let auth_manager = Arc::new( + AuthManager::new( + auth_home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await, + ); write_auth_json( auth_home.path(), @@ -1479,12 +1493,15 @@ enabled = false ), ) .expect("write initial auth"); - let auth_manager = Arc::new(AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - )); + let auth_manager = Arc::new( + AuthManager::new( + auth_home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await, + ); write_auth_json( auth_home.path(), @@ -1559,7 +1576,8 @@ enabled = false Some("account-12345"), "stale-access-token", "test-refresh-token", - ); + ) + .await; write_auth_json( auth._home.path(), chatgpt_auth_json( @@ -1611,12 +1629,15 @@ enabled = false ), ) .expect("write auth"); - let auth_manager = Arc::new(AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - )); + let auth_manager = Arc::new( + AuthManager::new( + auth_home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await, + ); let fetcher = Arc::new(UnauthorizedFetcher { message: @@ -1653,7 +1674,7 @@ enabled = false ])); let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1678,7 +1699,7 @@ enabled = false ))])); let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, fetcher, codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1700,7 +1721,7 @@ enabled = false async fn fetch_cloud_requirements_uses_cache_when_valid() { let codex_home = tempdir().expect("tempdir"); let prime_service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1711,7 +1732,7 @@ enabled = false let fetcher = Arc::new(SequenceFetcher::new(vec![Err(request_error())])); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1747,7 +1768,8 @@ enabled = false "business", /*chatgpt_user_id*/ None, Some("account-12345"), - ), + ) + .await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1790,7 +1812,7 @@ enabled = false async fn fetch_cloud_requirements_does_not_use_cache_when_auth_identity_is_incomplete() { let codex_home = tempdir().expect("tempdir"); let prime_service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1807,7 +1829,8 @@ enabled = false "business", /*chatgpt_user_id*/ None, Some("account-12345"), - ), + ) + .await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1843,7 +1866,8 @@ enabled = false "business", Some("user-12345"), Some("account-12345"), - ), + ) + .await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1860,7 +1884,8 @@ enabled = false "business", Some("user-99999"), Some("account-12345"), - ), + ) + .await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1892,7 +1917,7 @@ enabled = false async fn fetch_cloud_requirements_ignores_tampered_cache() { let codex_home = tempdir().expect("tempdir"); let prime_service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -1917,7 +1942,7 @@ enabled = false "allowed_approval_policies = [\"never\"]".to_string(), ))])); let service = CloudRequirementsService::new( - auth_manager_with_plan("enterprise"), + auth_manager_with_plan("enterprise").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -1975,7 +2000,7 @@ enabled = false "allowed_approval_policies = [\"never\"]".to_string(), ))])); let service = CloudRequirementsService::new( - auth_manager_with_plan("enterprise"), + auth_manager_with_plan("enterprise").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -2007,7 +2032,7 @@ enabled = false async fn fetch_cloud_requirements_writes_signed_cache() { let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, Arc::new(StaticFetcher { contents: Some("allowed_approval_policies = [\"never\"]".to_string()), }), @@ -2070,7 +2095,7 @@ enabled = false let fetcher = Arc::new(SequenceFetcher::new(vec![Ok(None), Err(request_error())])); let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("enterprise"), + auth_manager_with_plan("enterprise").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -2088,7 +2113,7 @@ enabled = false ])); let codex_home = tempdir().expect("tempdir"); let service = CloudRequirementsService::new( - auth_manager_with_plan("enterprise"), + auth_manager_with_plan("enterprise").await, fetcher.clone(), codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, @@ -2121,7 +2146,7 @@ enabled = false )), ])); let service = CloudRequirementsService::new( - auth_manager_with_plan("business"), + auth_manager_with_plan("business").await, fetcher, codex_home.path().to_path_buf(), CLOUD_REQUIREMENTS_TIMEOUT, diff --git a/codex-rs/cloud-tasks/src/util.rs b/codex-rs/cloud-tasks/src/util.rs index e433b892e5..9a5056aa66 100644 --- a/codex-rs/cloud-tasks/src/util.rs +++ b/codex-rs/cloud-tasks/src/util.rs @@ -44,12 +44,15 @@ pub fn normalize_base_url(input: &str) -> String { pub async fn load_auth_manager(chatgpt_base_url: Option) -> Option { // TODO: pass in cli overrides once cloud tasks properly support them. let config = Config::load_with_cli_overrides(Vec::new()).await.ok()?; - Some(AuthManager::new( - config.codex_home.to_path_buf(), - /*enable_codex_api_key_env*/ false, - config.cli_auth_credentials_store_mode, - chatgpt_base_url.or(Some(config.chatgpt_base_url)), - )) + Some( + AuthManager::new( + config.codex_home.to_path_buf(), + /*enable_codex_api_key_env*/ false, + config.cli_auth_credentials_store_mode, + chatgpt_base_url.or(Some(config.chatgpt_base_url)), + ) + .await, + ) } /// Build headers for ChatGPT-backed requests: `User-Agent`, optional `Authorization`, diff --git a/codex-rs/config/Cargo.toml b/codex-rs/config/Cargo.toml index 3c7e5a8296..8cef4070c9 100644 --- a/codex-rs/config/Cargo.toml +++ b/codex-rs/config/Cargo.toml @@ -16,9 +16,9 @@ anyhow = { workspace = true } async-trait = { workspace = true } base64 = { workspace = true } codex-app-server-protocol = { workspace = true } -codex-exec-server = { workspace = true } codex-execpolicy = { workspace = true } codex-features = { workspace = true } +codex-file-system = { workspace = true } codex-git-utils = { workspace = true } codex-model-provider-info = { workspace = true } codex-network-proxy = { workspace = true } diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs index 2821de5a8b..a1692b2cb1 100644 --- a/codex-rs/config/src/config_toml.rs +++ b/codex-rs/config/src/config_toml.rs @@ -49,8 +49,8 @@ use codex_protocol::config_types::WebSearchToolConfig; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path::normalize_for_path_comparison; use schemars::JsonSchema; @@ -362,7 +362,8 @@ pub struct ConfigToml { /// Suppress warnings about unstable (under development) features. pub suppress_unstable_features_warning: Option, - /// Settings for ghost snapshots (used for undo). + /// Compatibility-only settings retained so legacy `ghost_snapshot` + /// config still loads. #[serde(default)] pub ghost_snapshot: Option, @@ -629,27 +630,30 @@ impl From for Tools { #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct GhostSnapshotToml { - /// Exclude untracked files larger than this many bytes from ghost snapshots. + /// Legacy no-op setting retained for compatibility. #[serde(alias = "ignore_untracked_files_over_bytes")] pub ignore_large_untracked_files: Option, - /// Ignore untracked directories that contain this many files or more. - /// (Still emits a warning unless warnings are disabled.) + /// Legacy no-op setting retained for compatibility. #[serde(alias = "large_untracked_dir_warning_threshold")] pub ignore_large_untracked_dirs: Option, - /// Disable all ghost snapshot warning events. + /// Legacy no-op setting retained for compatibility. pub disable_warnings: Option, } impl ConfigToml { - /// Derive the effective sandbox policy from the configuration. - pub async fn derive_sandbox_policy( + /// Derive the effective permission profile from legacy sandbox config. + /// + /// Call this only after ruling out `default_permissions`: named + /// `[permissions]` profiles must be compiled through the permissions + /// profile pipeline, not reconstructed from `sandbox_mode`. + pub async fn derive_permission_profile( &self, sandbox_mode_override: Option, profile_sandbox_mode: Option, windows_sandbox_level: WindowsSandboxLevel, active_project: Option<&ProjectConfig>, permission_profile_constraint: Option<&crate::Constrained>, - ) -> SandboxPolicy { + ) -> PermissionProfile { let sandbox_mode_was_explicit = sandbox_mode_override.is_some() || profile_sandbox_mode.is_some() || self.sandbox_mode.is_some(); @@ -677,50 +681,53 @@ impl ConfigToml { }) }) .unwrap_or_default(); - let mut sandbox_policy = match resolved_sandbox_mode { - SandboxMode::ReadOnly => SandboxPolicy::new_read_only_policy(), + let effective_sandbox_mode = if cfg!(target_os = "windows") + // If the experimental Windows sandbox is enabled, do not force a downgrade. + && windows_sandbox_level == WindowsSandboxLevel::Disabled + && matches!(resolved_sandbox_mode, SandboxMode::WorkspaceWrite) + { + SandboxMode::ReadOnly + } else { + resolved_sandbox_mode + }; + + let permission_profile = match effective_sandbox_mode { + SandboxMode::ReadOnly => PermissionProfile::read_only(), SandboxMode::WorkspaceWrite => match self.sandbox_workspace_write.as_ref() { Some(SandboxWorkspaceWrite { writable_roots, network_access, exclude_tmpdir_env_var, exclude_slash_tmp, - }) => SandboxPolicy::WorkspaceWrite { - writable_roots: writable_roots.clone(), - network_access: *network_access, - exclude_tmpdir_env_var: *exclude_tmpdir_env_var, - exclude_slash_tmp: *exclude_slash_tmp, - }, - None => SandboxPolicy::new_workspace_write_policy(), + }) => { + let network_policy = if *network_access { + NetworkSandboxPolicy::Enabled + } else { + NetworkSandboxPolicy::Restricted + }; + PermissionProfile::workspace_write_with( + writable_roots, + network_policy, + *exclude_tmpdir_env_var, + *exclude_slash_tmp, + ) + } + None => PermissionProfile::workspace_write(), }, - SandboxMode::DangerFullAccess => SandboxPolicy::DangerFullAccess, + SandboxMode::DangerFullAccess => PermissionProfile::Disabled, }; - let downgrade_workspace_write_if_unsupported = |policy: &mut SandboxPolicy| { - if cfg!(target_os = "windows") - // If the experimental Windows sandbox is enabled, do not force a downgrade. - && windows_sandbox_level == WindowsSandboxLevel::Disabled - && matches!(&*policy, SandboxPolicy::WorkspaceWrite { .. }) - { - *policy = SandboxPolicy::new_read_only_policy(); - } - }; - if matches!(resolved_sandbox_mode, SandboxMode::WorkspaceWrite) { - downgrade_workspace_write_if_unsupported(&mut sandbox_policy); - } if !sandbox_mode_was_explicit && let Some(constraint) = permission_profile_constraint - && let Err(err) = constraint.can_set(&PermissionProfile::from_legacy_sandbox_policy( - &sandbox_policy, - )) + && let Err(err) = constraint.can_set(&permission_profile) { tracing::warn!( error = %err, "default sandbox policy is disallowed by requirements; falling back to required default" ); - sandbox_policy = SandboxPolicy::new_read_only_policy(); - downgrade_workspace_write_if_unsupported(&mut sandbox_policy); + PermissionProfile::read_only() + } else { + permission_profile } - sandbox_policy } /// Resolves the cwd to an existing project, or returns None if ConfigToml diff --git a/codex-rs/config/src/key_aliases.rs b/codex-rs/config/src/key_aliases.rs index 8d417e269f..07cb44fa6d 100644 --- a/codex-rs/config/src/key_aliases.rs +++ b/codex-rs/config/src/key_aliases.rs @@ -8,18 +8,11 @@ struct ConfigKeyAlias { canonical_key: &'static str, } -const CONFIG_KEY_ALIASES: &[ConfigKeyAlias] = &[ - ConfigKeyAlias { - table_path: &["memories"], - legacy_key: "no_memories_if_mcp_or_web_search", - canonical_key: "disable_on_external_context", - }, - ConfigKeyAlias { - table_path: &["agents"], - legacy_key: "max_concurrent_threads_per_session", - canonical_key: "max_threads", - }, -]; +const CONFIG_KEY_ALIASES: &[ConfigKeyAlias] = &[ConfigKeyAlias { + table_path: &["memories"], + legacy_key: "no_memories_if_mcp_or_web_search", + canonical_key: "disable_on_external_context", +}]; pub(crate) fn normalize_key_aliases(path: &[String], table: &mut TomlMap) { for alias in CONFIG_KEY_ALIASES { diff --git a/codex-rs/config/src/loader/layer_io.rs b/codex-rs/config/src/loader/layer_io.rs index 773a71f3bf..9c15df7271 100644 --- a/codex-rs/config/src/loader/layer_io.rs +++ b/codex-rs/config/src/loader/layer_io.rs @@ -5,7 +5,7 @@ use super::macos::load_managed_admin_config_layer; use crate::diagnostics::config_error_from_toml; use crate::diagnostics::io_error_from_config_error; use crate::state::LoaderOverrides; -use codex_exec_server::ExecutorFileSystem; +use codex_file_system::ExecutorFileSystem; use codex_utils_absolute_path::AbsolutePathBuf; use std::io; use std::path::Path; diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs index 6375490354..28e5ff3426 100644 --- a/codex-rs/config/src/loader/mod.rs +++ b/codex-rs/config/src/loader/mod.rs @@ -25,7 +25,7 @@ use crate::state::LoaderOverrides; use crate::thread_config::ThreadConfigContext; use crate::thread_config::ThreadConfigLoader; use codex_app_server_protocol::ConfigLayerSource; -use codex_exec_server::ExecutorFileSystem; +use codex_file_system::ExecutorFileSystem; use codex_git_utils::resolve_root_git_project_for_trust; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::SandboxMode; diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index 114ded97e9..1b9066d07f 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -575,7 +575,9 @@ pub struct Tui { /// Ordered list of terminal title item identifiers. /// /// When set, the TUI renders the selected items into the terminal window/tab title. - /// When unset, the TUI defaults to: `spinner` and `project`. + /// When unset, the TUI defaults to: `activity` and `project`. + /// The `activity` item spins while working and shows an action-required + /// message when blocked on the user. #[serde(default)] pub terminal_title: Option>, diff --git a/codex-rs/core-plugins/Cargo.toml b/codex-rs/core-plugins/Cargo.toml index 8a0e4f7720..ee477a381f 100644 --- a/codex-rs/core-plugins/Cargo.toml +++ b/codex-rs/core-plugins/Cargo.toml @@ -27,9 +27,11 @@ codex-utils-absolute-path = { workspace = true } codex-utils-plugins = { workspace = true } chrono = { workspace = true } dirs = { workspace = true } +flate2 = { workspace = true } reqwest = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } +tar = { workspace = true } tempfile = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["fs", "macros", "rt", "time"] } diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index 61e5ef3724..45ce391073 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -6,6 +6,7 @@ pub mod marketplace_add; pub mod marketplace_remove; pub mod marketplace_upgrade; pub mod remote; +pub mod remote_bundle; pub mod remote_legacy; pub mod startup_sync; pub mod store; diff --git a/codex-rs/core-plugins/src/remote.rs b/codex-rs/core-plugins/src/remote.rs index e453c52f97..6c87f4dc30 100644 --- a/codex-rs/core-plugins/src/remote.rs +++ b/codex-rs/core-plugins/src/remote.rs @@ -1,15 +1,22 @@ +use crate::store::PLUGINS_CACHE_DIR; +use crate::store::PluginStore; use codex_app_server_protocol::PluginAuthPolicy; use codex_app_server_protocol::PluginInstallPolicy; use codex_app_server_protocol::PluginInterface; use codex_app_server_protocol::SkillInterface; use codex_login::CodexAuth; use codex_login::default_client::build_reqwest_client; +use codex_plugin::PluginId; use reqwest::RequestBuilder; use serde::Deserialize; use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashSet; +use std::fs; +use std::path::Path; +use std::path::PathBuf; use std::time::Duration; +use tracing::warn; pub const REMOTE_GLOBAL_MARKETPLACE_NAME: &str = "chatgpt-global"; pub const REMOTE_WORKSPACE_MARKETPLACE_NAME: &str = "chatgpt-workspace"; @@ -49,6 +56,8 @@ pub struct RemotePluginDetail { pub marketplace_display_name: String, pub summary: RemotePluginSummary, pub description: Option, + pub release_version: Option, + pub bundle_download_url: Option, pub skills: Vec, pub app_ids: Vec, } @@ -109,18 +118,21 @@ pub enum RemotePluginCatalogError { }, #[error( - "remote plugin install returned unexpected plugin id: expected `{expected}`, got `{actual}`" + "remote plugin mutation returned unexpected plugin id: expected `{expected}`, got `{actual}`" )] UnexpectedPluginId { expected: String, actual: String }, #[error( - "remote plugin install returned unexpected enabled state for `{plugin_id}`: expected {expected_enabled}, got {actual_enabled}" + "remote plugin mutation returned unexpected enabled state for `{plugin_id}`: expected {expected_enabled}, got {actual_enabled}" )] UnexpectedEnabledState { plugin_id: String, expected_enabled: bool, actual_enabled: bool, }, + + #[error("{0}")] + CacheRemove(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] @@ -168,23 +180,16 @@ impl RemotePluginScope { #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct RemotePluginPagination { - #[serde(alias = "nextPageToken")] next_page_token: Option, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct RemotePluginSkillInterfaceResponse { - #[serde(alias = "displayName")] display_name: Option, - #[serde(alias = "shortDescription")] short_description: Option, - #[serde(alias = "brandColor")] brand_color: Option, - #[serde(alias = "defaultPrompt")] default_prompt: Option, - #[serde(alias = "iconSmallUrl")] icon_small_url: Option, - #[serde(alias = "iconLargeUrl")] icon_large_url: Option, } @@ -197,41 +202,32 @@ struct RemotePluginSkillResponse { #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct RemotePluginReleaseInterfaceResponse { - #[serde(alias = "shortDescription")] short_description: Option, - #[serde(alias = "longDescription")] long_description: Option, - #[serde(alias = "developerName")] developer_name: Option, category: Option, #[serde(default)] capabilities: Vec, - #[serde(alias = "websiteUrl")] website_url: Option, - #[serde(alias = "privacyPolicyUrl")] privacy_policy_url: Option, - #[serde(alias = "termsOfServiceUrl")] terms_of_service_url: Option, - #[serde(alias = "brandColor")] brand_color: Option, - #[serde(alias = "defaultPrompt")] default_prompt: Option, - #[serde(alias = "composerIconUrl")] composer_icon_url: Option, - #[serde(alias = "logoUrl")] logo_url: Option, #[serde(default)] - #[serde(alias = "screenshotUrls")] screenshot_urls: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct RemotePluginReleaseResponse { - #[serde(alias = "displayName")] + #[serde(default)] + version: Option, display_name: String, description: String, #[serde(default)] - #[serde(alias = "appIds")] + bundle_download_url: Option, + #[serde(default)] app_ids: Vec, interface: RemotePluginReleaseInterfaceResponse, #[serde(default)] @@ -243,9 +239,7 @@ struct RemotePluginDirectoryItem { id: String, name: String, scope: RemotePluginScope, - #[serde(alias = "installationPolicy")] installation_policy: PluginInstallPolicy, - #[serde(alias = "authenticationPolicy")] authentication_policy: PluginAuthPolicy, release: RemotePluginReleaseResponse, } @@ -256,7 +250,6 @@ struct RemotePluginInstalledItem { plugin: RemotePluginDirectoryItem, enabled: bool, #[serde(default)] - #[serde(alias = "disabledSkillNames")] disabled_skill_names: Vec, } @@ -273,7 +266,7 @@ struct RemotePluginInstalledResponse { } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RemotePluginInstallResponse { +struct RemotePluginMutationResponse { id: String, enabled: bool, } @@ -381,6 +374,39 @@ pub async fn fetch_remote_plugin_detail( auth: Option<&CodexAuth>, marketplace_name: &str, plugin_id: &str, +) -> Result { + fetch_remote_plugin_detail_with_download_url_option( + config, + auth, + marketplace_name, + plugin_id, + /*include_download_urls*/ false, + ) + .await +} + +pub async fn fetch_remote_plugin_detail_with_download_urls( + config: &RemotePluginServiceConfig, + auth: Option<&CodexAuth>, + marketplace_name: &str, + plugin_id: &str, +) -> Result { + fetch_remote_plugin_detail_with_download_url_option( + config, + auth, + marketplace_name, + plugin_id, + /*include_download_urls*/ true, + ) + .await +} + +async fn fetch_remote_plugin_detail_with_download_url_option( + config: &RemotePluginServiceConfig, + auth: Option<&CodexAuth>, + marketplace_name: &str, + plugin_id: &str, + include_download_urls: bool, ) -> Result { let auth = ensure_chatgpt_auth(auth)?; let scope = RemotePluginScope::from_marketplace_name(marketplace_name).ok_or_else(|| { @@ -388,7 +414,7 @@ pub async fn fetch_remote_plugin_detail( marketplace_name: marketplace_name.to_string(), } })?; - let plugin = fetch_plugin_detail(config, auth, plugin_id).await?; + let plugin = fetch_plugin_detail(config, auth, plugin_id, include_download_urls).await?; let actual_marketplace_name = plugin.scope.marketplace_name(); if actual_marketplace_name != marketplace_name { return Err(RemotePluginCatalogError::MarketplaceMismatch { @@ -398,6 +424,46 @@ pub async fn fetch_remote_plugin_detail( }); } + build_remote_plugin_detail( + config, + auth, + scope, + marketplace_name.to_string(), + plugin_id, + plugin, + ) + .await +} + +async fn fetch_remote_plugin_detail_by_id( + config: &RemotePluginServiceConfig, + auth: &CodexAuth, + plugin_id: &str, +) -> Result { + let plugin = fetch_plugin_detail( + config, auth, plugin_id, /*include_download_urls*/ false, + ) + .await?; + let scope = plugin.scope; + build_remote_plugin_detail( + config, + auth, + scope, + scope.marketplace_name().to_string(), + plugin_id, + plugin, + ) + .await +} + +async fn build_remote_plugin_detail( + config: &RemotePluginServiceConfig, + auth: &CodexAuth, + scope: RemotePluginScope, + marketplace_name: String, + plugin_id: &str, + plugin: RemotePluginDirectoryItem, +) -> Result { let installed_plugin = fetch_installed_plugins_for_scope(config, auth, scope) .await? .into_iter() @@ -429,10 +495,12 @@ pub async fn fetch_remote_plugin_detail( .collect(); Ok(RemotePluginDetail { - marketplace_name: marketplace_name.to_string(), + marketplace_name, marketplace_display_name: scope.marketplace_display_name().to_string(), summary: build_remote_plugin_summary(&plugin, installed_plugin.as_ref()), description: non_empty_string(Some(&plugin.release.description)), + release_version: plugin.release.version, + bundle_download_url: plugin.release.bundle_download_url, skills, app_ids: plugin.release.app_ids, }) @@ -455,7 +523,7 @@ pub async fn install_remote_plugin( let url = format!("{base_url}/ps/plugins/{plugin_id}/install"); let client = build_reqwest_client(); let request = authenticated_request(client.post(&url), auth)?; - let response: RemotePluginInstallResponse = send_and_decode(request, &url).await?; + let response: RemotePluginMutationResponse = send_and_decode(request, &url).await?; if response.id != plugin_id { return Err(RemotePluginCatalogError::UnexpectedPluginId { expected: plugin_id.to_string(), @@ -473,6 +541,121 @@ pub async fn install_remote_plugin( Ok(()) } +pub async fn uninstall_remote_plugin( + config: &RemotePluginServiceConfig, + auth: Option<&CodexAuth>, + codex_home: PathBuf, + plugin_id: &str, +) -> Result<(), RemotePluginCatalogError> { + let auth = ensure_chatgpt_auth(auth)?; + + let base_url = config.chatgpt_base_url.trim_end_matches('/'); + let url = format!("{base_url}/plugins/{plugin_id}/uninstall"); + let client = build_reqwest_client(); + let request = authenticated_request(client.post(&url), auth)?; + let response: RemotePluginMutationResponse = send_and_decode(request, &url).await?; + if response.id != plugin_id { + return Err(RemotePluginCatalogError::UnexpectedPluginId { + expected: plugin_id.to_string(), + actual: response.id, + }); + } + if response.enabled { + return Err(RemotePluginCatalogError::UnexpectedEnabledState { + plugin_id: plugin_id.to_string(), + expected_enabled: false, + actual_enabled: response.enabled, + }); + } + + let remote_detail = match fetch_remote_plugin_detail_by_id(config, auth, plugin_id).await { + Ok(remote_detail) => Some(remote_detail), + Err(err) => { + warn!( + plugin_id, + "failed to read remote plugin details after uninstall; skipping named cache removal: {err}" + ); + None + } + }; + let legacy_plugin_id = plugin_id.to_string(); + tokio::task::spawn_blocking(move || { + remove_remote_plugin_cache(codex_home, remote_detail, legacy_plugin_id) + }) + .await + .map_err(|err| { + RemotePluginCatalogError::CacheRemove(format!( + "failed to join remote plugin cache removal task: {err}" + )) + })? + .map_err(RemotePluginCatalogError::CacheRemove)?; + + Ok(()) +} + +fn remove_remote_plugin_cache( + codex_home: PathBuf, + remote_detail: Option, + legacy_plugin_id: String, +) -> Result<(), String> { + if let Some(remote_detail) = remote_detail { + let marketplace_name = remote_detail.marketplace_name; + let plugin_name = remote_detail.summary.name; + let store = PluginStore::try_new(codex_home.clone()) + .map_err(|err| format!("failed to resolve remote plugin cache root: {err}"))?; + let plugin_id = PluginId::new(plugin_name.clone(), marketplace_name.clone()).map_err( + |err| { + format!( + "invalid remote plugin cache id for `{plugin_name}` in `{marketplace_name}`: {err}" + ) + }, + )?; + let plugin_cache_root = store.plugin_base_root(&plugin_id); + store.uninstall(&plugin_id).map_err(|err| { + format!( + "failed to remove remote plugin cache entry {}: {err}", + plugin_cache_root.display() + ) + })?; + + let legacy_remote_plugin_cache_root = codex_home + .join(PLUGINS_CACHE_DIR) + .join(marketplace_name) + .join(legacy_plugin_id); + if legacy_remote_plugin_cache_root != plugin_cache_root.as_path() { + remove_path_if_exists(&legacy_remote_plugin_cache_root)?; + } + return Ok(()); + } + + for scope in RemotePluginScope::all() { + let legacy_remote_plugin_cache_root = codex_home + .join(PLUGINS_CACHE_DIR) + .join(scope.marketplace_name()) + .join(&legacy_plugin_id); + remove_path_if_exists(&legacy_remote_plugin_cache_root)?; + } + Ok(()) +} + +fn remove_path_if_exists(path: &Path) -> Result<(), String> { + if !path.exists() { + return Ok(()); + } + + let result = if path.is_dir() { + fs::remove_dir_all(path) + } else { + fs::remove_file(path) + }; + result.map_err(|err| { + format!( + "failed to remove remote plugin cache entry {}: {err}", + path.display() + ) + }) +} + fn build_remote_plugin_summary( plugin: &RemotePluginDirectoryItem, installed_plugin: Option<&RemotePluginInstalledItem>, @@ -651,11 +834,15 @@ async fn fetch_plugin_detail( config: &RemotePluginServiceConfig, auth: &CodexAuth, plugin_id: &str, + include_download_urls: bool, ) -> Result { let base_url = config.chatgpt_base_url.trim_end_matches('/'); let url = format!("{base_url}/ps/plugins/{plugin_id}"); let client = build_reqwest_client(); - let request = authenticated_request(client.get(&url), auth)?; + let mut request = authenticated_request(client.get(&url), auth)?; + if include_download_urls { + request = request.query(&[("includeDownloadUrls", true)]); + } send_and_decode(request, &url).await } diff --git a/codex-rs/core-plugins/src/remote_bundle.rs b/codex-rs/core-plugins/src/remote_bundle.rs new file mode 100644 index 0000000000..92d5613846 --- /dev/null +++ b/codex-rs/core-plugins/src/remote_bundle.rs @@ -0,0 +1,848 @@ +use crate::store::PluginInstallResult; +use crate::store::PluginStore; +use crate::store::PluginStoreError; +use crate::store::validate_plugin_version_segment; +use codex_login::default_client::build_reqwest_client; +use codex_plugin::PluginId; +use codex_plugin::PluginIdError; +use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_plugins::find_plugin_manifest_path; +use flate2::read::GzDecoder; +use reqwest::Response; +use reqwest::StatusCode; +use std::fs; +use std::io; +use std::io::Read; +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; +use tar::Archive; +use url::Host; +use url::Url; + +const REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60); +const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 50 * 1024 * 1024; +const REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES: u64 = 8 * 1024; +const REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES: u64 = 250 * 1024 * 1024; +const REMOTE_PLUGIN_INSTALL_STAGING_DIR: &str = "plugins/.remote-plugin-install-staging"; +#[cfg(debug_assertions)] +const TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV: &str = + "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS"; + +#[derive(Debug, Clone)] +pub struct ValidatedRemotePluginBundle { + pub plugin_id: PluginId, + pub plugin_version: String, + bundle_download_url: String, +} + +#[derive(Debug, thiserror::Error)] +pub enum RemotePluginBundleInstallError { + #[error("backend did not return a release version for remote plugin `{remote_plugin_id}`")] + MissingReleaseVersion { remote_plugin_id: String }, + + #[error( + "backend returned an invalid release version for remote plugin `{remote_plugin_id}`: {message}" + )] + InvalidReleaseVersion { + remote_plugin_id: String, + message: String, + }, + + #[error("backend did not return a download URL for remote plugin `{remote_plugin_id}`")] + MissingBundleDownloadUrl { remote_plugin_id: String }, + + #[error( + "backend returned an invalid download URL for remote plugin `{remote_plugin_id}`: {url}" + )] + InvalidBundleDownloadUrl { + remote_plugin_id: String, + url: String, + #[source] + source: url::ParseError, + }, + + #[error( + "backend returned an unsupported download URL scheme for remote plugin `{remote_plugin_id}`: {scheme}" + )] + UnsupportedBundleDownloadUrlScheme { + remote_plugin_id: String, + scheme: String, + }, + + #[error( + "backend returned an invalid local plugin id for remote plugin `{remote_plugin_id}`: {source}" + )] + InvalidPluginId { + remote_plugin_id: String, + #[source] + source: PluginIdError, + }, + + #[error("failed to send remote plugin bundle download request to {url}: {source}")] + DownloadRequest { + url: String, + #[source] + source: reqwest::Error, + }, + + #[error("remote plugin bundle download from {url} failed with status {status}: {body}")] + DownloadStatus { + url: String, + status: StatusCode, + body: String, + }, + + #[error("failed to read remote plugin bundle download response from {url}: {source}")] + DownloadBody { + url: String, + #[source] + source: reqwest::Error, + }, + + #[error("remote plugin bundle download from {url} exceeded maximum size of {max_bytes} bytes")] + DownloadTooLarge { url: String, max_bytes: u64 }, + + #[error("remote plugin bundle download from {url} redirected to unsupported URL {final_url}")] + UnsupportedBundleDownloadFinalUrl { url: String, final_url: String }, + + #[error( + "remote plugin bundle extracted size would be {bytes} bytes, exceeding the maximum total size of {max_bytes} bytes" + )] + ExtractedBundleTooLarge { bytes: u64, max_bytes: u64 }, + + #[error("{context}: {source}")] + Io { + context: &'static str, + #[source] + source: io::Error, + }, + + #[error("{0}")] + InvalidBundle(String), + + #[error("{0}")] + Store(#[from] PluginStoreError), +} + +impl RemotePluginBundleInstallError { + fn io(context: &'static str, source: io::Error) -> Self { + Self::Io { context, source } + } +} + +pub fn validate_remote_plugin_bundle( + remote_plugin_id: &str, + remote_marketplace_name: &str, + plugin_name: &str, + release_version: Option<&str>, + bundle_download_url: Option<&str>, +) -> Result { + let plugin_id = PluginId::new(plugin_name.to_string(), remote_marketplace_name.to_string()) + .map_err(|source| RemotePluginBundleInstallError::InvalidPluginId { + remote_plugin_id: remote_plugin_id.to_string(), + source, + })?; + let plugin_version = release_version + .map(str::trim) + .filter(|version| !version.is_empty()) + .ok_or_else(|| RemotePluginBundleInstallError::MissingReleaseVersion { + remote_plugin_id: remote_plugin_id.to_string(), + })? + .to_string(); + validate_plugin_version_segment(&plugin_version).map_err(|message| { + RemotePluginBundleInstallError::InvalidReleaseVersion { + remote_plugin_id: remote_plugin_id.to_string(), + message, + } + })?; + let bundle_download_url = bundle_download_url + .map(str::trim) + .filter(|url| !url.is_empty()) + .ok_or_else( + || RemotePluginBundleInstallError::MissingBundleDownloadUrl { + remote_plugin_id: remote_plugin_id.to_string(), + }, + )? + .to_string(); + let parsed_bundle_url = Url::parse(&bundle_download_url).map_err(|source| { + RemotePluginBundleInstallError::InvalidBundleDownloadUrl { + remote_plugin_id: remote_plugin_id.to_string(), + url: bundle_download_url.clone(), + source, + } + })?; + if !is_allowed_bundle_download_url( + &parsed_bundle_url, + allow_test_loopback_http_bundle_downloads(), + ) { + return Err( + RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { + remote_plugin_id: remote_plugin_id.to_string(), + scheme: parsed_bundle_url.scheme().to_string(), + }, + ); + } + + Ok(ValidatedRemotePluginBundle { + plugin_id, + plugin_version, + bundle_download_url, + }) +} + +fn allow_test_loopback_http_bundle_downloads() -> bool { + #[cfg(debug_assertions)] + { + if let Ok(value) = std::env::var(TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV) { + return value == "1"; + } + } + + false +} + +fn is_allowed_bundle_download_url(url: &Url, allow_loopback_http: bool) -> bool { + match url.scheme() { + "https" => true, + "http" => allow_loopback_http && is_loopback_url(url), + _ => false, + } +} + +fn is_loopback_url(url: &Url) -> bool { + match url.host() { + Some(Host::Ipv4(addr)) => addr.is_loopback(), + Some(Host::Ipv6(addr)) => addr.is_loopback(), + Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), + None => false, + } +} + +pub async fn download_and_install_remote_plugin_bundle( + codex_home: PathBuf, + bundle: ValidatedRemotePluginBundle, +) -> Result { + let bundle_bytes = download_remote_plugin_bundle_with_limit( + &bundle.bundle_download_url, + /*max_bytes*/ REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES, + ) + .await?; + tokio::task::spawn_blocking(move || { + install_remote_plugin_bundle(codex_home, bundle, bundle_bytes) + }) + .await + .map_err(|err| { + RemotePluginBundleInstallError::InvalidBundle(format!( + "failed to join remote plugin bundle install task: {err}" + )) + })? +} + +async fn download_remote_plugin_bundle_with_limit( + bundle_download_url: &str, + max_bytes: u64, +) -> Result, RemotePluginBundleInstallError> { + let client = build_reqwest_client(); + let response = client + .get(bundle_download_url) + .timeout(REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT) + .send() + .await + .map_err(|source| RemotePluginBundleInstallError::DownloadRequest { + url: bundle_download_url.to_string(), + source, + })?; + + let final_url = response.url().clone(); + // reqwest may already have followed redirects here. For backend-issued bundle URLs, keep the + // shared client policy and fail unsupported final schemes before caching. + if !is_allowed_bundle_download_url(&final_url, allow_test_loopback_http_bundle_downloads()) { + return Err( + RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { + url: bundle_download_url.to_string(), + final_url: final_url.to_string(), + }, + ); + } + + let url = final_url.to_string(); + let status = response.status(); + if !status.is_success() { + let body = read_response_body_with_limit( + response, + &url, + /*max_bytes*/ REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES, + ) + .await?; + let body = String::from_utf8_lossy(&body).to_string(); + return Err(RemotePluginBundleInstallError::DownloadStatus { url, status, body }); + } + + read_response_body_with_limit(response, &url, max_bytes).await +} + +async fn read_response_body_with_limit( + mut response: Response, + url: &str, + max_bytes: u64, +) -> Result, RemotePluginBundleInstallError> { + if let Some(content_length) = response.content_length() { + enforce_download_size_limit(url, content_length, max_bytes)?; + } + + let mut body = Vec::new(); + while let Some(chunk) = + response + .chunk() + .await + .map_err(|source| RemotePluginBundleInstallError::DownloadBody { + url: url.to_string(), + source, + })? + { + let next_len = body.len() as u64 + chunk.len() as u64; + enforce_download_size_limit(url, next_len, max_bytes)?; + body.extend_from_slice(&chunk); + } + + Ok(body) +} + +fn enforce_download_size_limit( + url: &str, + bytes: u64, + max_bytes: u64, +) -> Result<(), RemotePluginBundleInstallError> { + if bytes > max_bytes { + return Err(RemotePluginBundleInstallError::DownloadTooLarge { + url: url.to_string(), + max_bytes, + }); + } + Ok(()) +} + +fn install_remote_plugin_bundle( + codex_home: PathBuf, + bundle: ValidatedRemotePluginBundle, + bundle_bytes: Vec, +) -> Result { + let staging_root = codex_home.join(REMOTE_PLUGIN_INSTALL_STAGING_DIR); + fs::create_dir_all(&staging_root).map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to create remote plugin bundle staging directory", + source, + ) + })?; + let extract_dir = tempfile::Builder::new() + .prefix("remote-plugin-bundle-") + .tempdir_in(&staging_root) + .map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to create remote plugin bundle extraction directory", + source, + ) + })?; + + extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?; + let plugin_root = find_extracted_plugin_root(extract_dir.path())?; + let plugin_root = AbsolutePathBuf::try_from(plugin_root).map_err(|err| { + RemotePluginBundleInstallError::InvalidBundle(format!( + "failed to resolve extracted remote plugin bundle root: {err}" + )) + })?; + + let store = PluginStore::try_new(codex_home)?; + store + .install_with_version(plugin_root, bundle.plugin_id, bundle.plugin_version) + .map_err(RemotePluginBundleInstallError::from) +} + +fn extract_plugin_bundle_tar_gz( + bytes: &[u8], + destination: &Path, +) -> Result<(), RemotePluginBundleInstallError> { + extract_plugin_bundle_tar_gz_with_limits( + bytes, + destination, + REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES, + ) +} + +fn extract_plugin_bundle_tar_gz_with_limits( + bytes: &[u8], + destination: &Path, + max_total_bytes: u64, +) -> Result<(), RemotePluginBundleInstallError> { + fs::create_dir_all(destination).map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to create remote plugin bundle extraction directory", + source, + ) + })?; + + let archive = GzDecoder::new(std::io::Cursor::new(bytes)); + let mut archive = Archive::new(archive); + extract_plugin_bundle_tar(&mut archive, destination, max_total_bytes) +} + +fn extract_plugin_bundle_tar( + archive: &mut Archive, + destination: &Path, + max_total_bytes: u64, +) -> Result<(), RemotePluginBundleInstallError> { + let mut extracted_bytes = 0u64; + let entries = archive.entries().map_err(|source| { + RemotePluginBundleInstallError::io("failed to read remote plugin bundle tar", source) + })?; + let entries = entries.raw(true); + for entry in entries { + let mut entry = entry.map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to read remote plugin bundle tar entry", + source, + ) + })?; + let entry_type = entry.header().entry_type(); + let entry_size = entry.size(); + let entry_path = entry.path().map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to read remote plugin bundle tar entry path", + source, + ) + })?; + let entry_path = entry_path.into_owned(); + let output_path = checked_tar_output_path(destination, &entry_path)?; + + if entry_type.is_dir() { + fs::create_dir_all(&output_path).map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to create remote plugin bundle directory", + source, + ) + })?; + continue; + } + + if entry_type.is_file() { + enforce_total_extracted_size(entry_size, &mut extracted_bytes, max_total_bytes)?; + let Some(parent) = output_path.parent() else { + return Err(RemotePluginBundleInstallError::InvalidBundle(format!( + "remote plugin bundle output path has no parent: {}", + output_path.display() + ))); + }; + fs::create_dir_all(parent).map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to create remote plugin bundle directory", + source, + ) + })?; + entry.unpack(&output_path).map_err(|source| { + RemotePluginBundleInstallError::io( + "failed to unpack remote plugin bundle entry", + source, + ) + })?; + continue; + } + + if entry_type.is_hard_link() || entry_type.is_symlink() { + return Err(RemotePluginBundleInstallError::InvalidBundle(format!( + "remote plugin bundle tar entry `{}` is a link", + entry_path.display() + ))); + } + + return Err(RemotePluginBundleInstallError::InvalidBundle(format!( + "remote plugin bundle tar entry `{}` has unsupported type {:?}", + entry_path.display(), + entry_type + ))); + } + + Ok(()) +} + +fn checked_tar_output_path( + destination: &Path, + entry_name: &Path, +) -> Result { + let mut output_path = destination.to_path_buf(); + let mut has_component = false; + for component in entry_name.components() { + match component { + std::path::Component::Normal(component) => { + has_component = true; + output_path.push(component); + } + std::path::Component::CurDir => {} + std::path::Component::ParentDir + | std::path::Component::RootDir + | std::path::Component::Prefix(_) => { + return Err(RemotePluginBundleInstallError::InvalidBundle(format!( + "remote plugin bundle tar entry `{}` escapes extraction root", + entry_name.display() + ))); + } + } + } + if !has_component { + return Err(RemotePluginBundleInstallError::InvalidBundle( + "remote plugin bundle tar entry has an empty path".to_string(), + )); + } + Ok(output_path) +} + +fn enforce_total_extracted_size( + entry_size: u64, + extracted_bytes: &mut u64, + max_total_bytes: u64, +) -> Result<(), RemotePluginBundleInstallError> { + let next_total = extracted_bytes.checked_add(entry_size).ok_or( + RemotePluginBundleInstallError::ExtractedBundleTooLarge { + bytes: u64::MAX, + max_bytes: max_total_bytes, + }, + )?; + if next_total > max_total_bytes { + return Err(RemotePluginBundleInstallError::ExtractedBundleTooLarge { + bytes: next_total, + max_bytes: max_total_bytes, + }); + } + *extracted_bytes = next_total; + Ok(()) +} + +fn find_extracted_plugin_root( + extraction_root: &Path, +) -> Result { + if is_standard_plugin_root(extraction_root) { + return Ok(extraction_root.to_path_buf()); + } + + Err(RemotePluginBundleInstallError::InvalidBundle( + "remote plugin bundle did not contain a standard plugin root with plugin.json".to_string(), + )) +} + +fn is_standard_plugin_root(path: &Path) -> bool { + find_plugin_manifest_path(path).is_some() +} + +#[cfg(test)] +mod tests { + use super::*; + use flate2::Compression; + use flate2::write::GzEncoder; + use pretty_assertions::assert_eq; + use tempfile::tempdir; + + const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000"; + + #[test] + fn validate_remote_plugin_bundle_uses_detail_name_for_local_plugin_id() { + let bundle = validate_remote_plugin_bundle( + REMOTE_PLUGIN_ID, + "chatgpt-global", + "linear", + Some("1.2.3"), + Some("https://example.com/linear.tar.gz"), + ) + .expect("valid install plan"); + + assert_eq!(bundle.plugin_id.plugin_name, "linear"); + assert_eq!(bundle.plugin_id.marketplace_name, "chatgpt-global"); + assert_eq!(bundle.plugin_version, "1.2.3"); + assert_eq!( + bundle.bundle_download_url.as_str(), + "https://example.com/linear.tar.gz" + ); + } + + #[test] + fn validate_remote_plugin_bundle_rejects_missing_release_version() { + let err = validate_remote_plugin_bundle( + REMOTE_PLUGIN_ID, + "chatgpt-global", + "linear", + /*release_version*/ None, + Some("https://example.com/linear.tar.gz"), + ) + .expect_err("missing release version should be rejected"); + + assert!(matches!( + err, + RemotePluginBundleInstallError::MissingReleaseVersion { .. } + )); + } + + #[test] + fn validate_remote_plugin_bundle_rejects_invalid_release_version() { + let err = validate_remote_plugin_bundle( + REMOTE_PLUGIN_ID, + "chatgpt-global", + "linear", + Some("../1.2.3"), + Some("https://example.com/linear.tar.gz"), + ) + .expect_err("invalid release version should be rejected"); + + assert!(matches!( + err, + RemotePluginBundleInstallError::InvalidReleaseVersion { .. } + )); + } + + #[test] + fn validate_remote_plugin_bundle_rejects_missing_download_url() { + let err = validate_remote_plugin_bundle( + REMOTE_PLUGIN_ID, + "chatgpt-global", + "linear", + Some("1.2.3"), + /*bundle_download_url*/ None, + ) + .expect_err("missing bundle download URL should be rejected"); + + assert!(matches!( + err, + RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. } + )); + } + + #[test] + fn validate_remote_plugin_bundle_rejects_unsupported_download_url_scheme() { + let err = validate_remote_plugin_bundle( + REMOTE_PLUGIN_ID, + "chatgpt-global", + "linear", + Some("1.2.3"), + Some("http://example.com/linear.tar.gz"), + ) + .expect_err("plain HTTP URLs should be rejected before cloud install"); + + assert!(matches!( + err, + RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. } + )); + } + + #[test] + fn download_size_limit_rejects_oversized_bundle() { + let err = enforce_download_size_limit( + "https://example.com/linear.tar.gz", + /*bytes*/ 5, + /*max_bytes*/ 4, + ) + .expect_err("oversized bundle download should fail"); + + assert!(matches!( + err, + RemotePluginBundleInstallError::DownloadTooLarge { .. } + )); + } + + #[test] + fn install_rejects_invalid_tar_gz_bundle() { + let codex_home = tempdir().expect("tempdir"); + let bundle = valid_remote_plugin_bundle(); + + let err = install_remote_plugin_bundle( + codex_home.path().to_path_buf(), + bundle, + b"not a tar.gz".to_vec(), + ) + .expect_err("invalid tar.gz should be rejected"); + + assert!(format!("{err}").contains("failed to read remote plugin bundle tar")); + } + + #[test] + fn install_rejects_bundle_without_standard_plugin_root() { + let codex_home = tempdir().expect("tempdir"); + let bundle = valid_remote_plugin_bundle(); + + let err = install_remote_plugin_bundle( + codex_home.path().to_path_buf(), + bundle, + tar_gz_bytes(&[("README.md", b"missing plugin manifest", /*mode*/ 0o644)]), + ) + .expect_err("bundle without plugin root should be rejected"); + + assert!( + format!("{err}").contains("did not contain a standard plugin root with plugin.json") + ); + } + + #[test] + fn find_extracted_plugin_root_uses_local_manifest_discovery() { + let extraction_root = tempdir().expect("tempdir"); + std::fs::create_dir_all(extraction_root.path().join(".codex-plugin")) + .expect("create manifest dir"); + std::fs::write( + extraction_root.path().join(".codex-plugin/plugin.json"), + r#"{"name":"linear"}"#, + ) + .expect("write manifest"); + + assert_eq!( + find_extracted_plugin_root(extraction_root.path()).expect("plugin root"), + extraction_root.path() + ); + } + + #[test] + fn find_extracted_plugin_root_rejects_nested_plugin_root() { + let extraction_root = tempdir().expect("tempdir"); + let plugin_root = extraction_root.path().join("linear"); + std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create manifest dir"); + std::fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"linear"}"#, + ) + .expect("write manifest"); + + let err = find_extracted_plugin_root(extraction_root.path()) + .expect_err("nested plugin root should be rejected"); + + assert!( + format!("{err}").contains("did not contain a standard plugin root with plugin.json") + ); + } + + #[test] + fn extraction_rejects_tar_path_traversal() { + let destination = tempdir().expect("tempdir"); + let err = checked_tar_output_path(destination.path(), Path::new("../evil.txt")) + .expect_err("tar path traversal should be rejected"); + + assert!(format!("{err}").contains("escapes extraction root")); + } + + #[test] + fn extraction_rejects_total_size_over_limit() { + let destination = tempdir().expect("tempdir"); + let err = extract_plugin_bundle_tar_gz_with_limits( + &tar_gz_bytes(&[ + ("a.txt", b"1234", /*mode*/ 0o644), + ("b.txt", b"5678", /*mode*/ 0o644), + ]), + destination.path(), + /*max_total_bytes*/ 6, + ) + .expect_err("oversized extracted bundle should be rejected"); + + assert!(matches!( + err, + RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. } + )); + } + + #[test] + fn extraction_rejects_pax_metadata_entries() { + let destination = tempdir().expect("tempdir"); + let err = extract_plugin_bundle_tar_gz( + &tar_gz_bytes_with_entry_type( + tar::EntryType::XHeader, + "PaxHeaders.0/linear", + b"18 path=linear\n", + /*mode*/ 0o644, + ), + destination.path(), + ) + .expect_err("pax metadata entries should be rejected"); + + assert!(format!("{err}").contains("unsupported type")); + } + + #[cfg(unix)] + #[test] + fn extraction_preserves_executable_permissions() { + use std::os::unix::fs::PermissionsExt; + + let destination = tempdir().expect("tempdir"); + extract_plugin_bundle_tar_gz( + &tar_gz_bytes(&[ + ( + ".codex-plugin/plugin.json", + b"{\"name\":\"linear\"}", + /*mode*/ 0o644, + ), + ("bin/helper", b"#!/bin/sh\n", /*mode*/ 0o755), + ]), + destination.path(), + ) + .expect("extract bundle"); + + let mode = std::fs::metadata(destination.path().join("bin/helper")) + .expect("helper metadata") + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o755); + } + + fn valid_remote_plugin_bundle() -> ValidatedRemotePluginBundle { + validate_remote_plugin_bundle( + REMOTE_PLUGIN_ID, + "chatgpt-global", + "linear", + Some("1.2.3"), + Some("https://example.com/linear.tar.gz"), + ) + .expect("valid install plan") + } + + fn tar_gz_bytes(entries: &[(&str, &[u8], u32)]) -> Vec { + let encoder = GzEncoder::new(Vec::new(), Compression::default()); + let mut tar = tar::Builder::new(encoder); + for (path, contents, mode) in entries { + append_tar_entry(&mut tar, tar::EntryType::Regular, path, contents, *mode); + } + finish_tar_gz(tar) + } + + fn tar_gz_bytes_with_entry_type( + entry_type: tar::EntryType, + path: &str, + contents: &[u8], + mode: u32, + ) -> Vec { + let encoder = GzEncoder::new(Vec::new(), Compression::default()); + let mut tar = tar::Builder::new(encoder); + append_tar_entry(&mut tar, entry_type, path, contents, mode); + finish_tar_gz(tar) + } + + fn append_tar_entry( + tar: &mut tar::Builder, + entry_type: tar::EntryType, + path: &str, + contents: &[u8], + mode: u32, + ) { + let mut header = tar::Header::new_gnu(); + header.set_entry_type(entry_type); + header.set_size(contents.len() as u64); + header.set_mode(mode); + header.set_cksum(); + if let Err(error) = tar.append_data(&mut header, path, contents) { + panic!("failed to append tar test data: {error}"); + } + } + + fn finish_tar_gz(tar: tar::Builder>>) -> Vec { + let encoder = match tar.into_inner() { + Ok(encoder) => encoder, + Err(error) => panic!("failed to finish tar test data: {error}"), + }; + match encoder.finish() { + Ok(bytes) => bytes, + Err(error) => panic!("failed to finish gzip test data: {error}"), + } + } +} diff --git a/codex-rs/core-plugins/src/store.rs b/codex-rs/core-plugins/src/store.rs index 757aec8bc5..2ffead0fbc 100644 --- a/codex-rs/core-plugins/src/store.rs +++ b/codex-rs/core-plugins/src/store.rs @@ -160,7 +160,7 @@ pub fn plugin_version_for_source(source_path: &Path) -> Result Result<(), String> { +pub fn validate_plugin_version_segment(plugin_version: &str) -> Result<(), String> { if plugin_version.is_empty() { return Err("invalid plugin version: must not be empty".to_string()); } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index b8d3b146f6..44c6aacac5 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -39,6 +39,7 @@ codex-exec-server = { workspace = true } codex-features = { workspace = true } codex-feedback = { workspace = true } codex-login = { workspace = true } +codex-memories-read = { workspace = true } codex-mcp = { workspace = true } codex-model-provider-info = { workspace = true } codex-models-manager = { workspace = true } @@ -69,7 +70,6 @@ codex-utils-path = { workspace = true } codex-utils-plugins = { workspace = true } codex-utils-pty = { workspace = true } codex-utils-readiness = { workspace = true } -codex-secrets = { workspace = true } codex-utils-string = { workspace = true } codex-utils-stream-parser = { workspace = true } codex-utils-template = { workspace = true } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 3fbbfaf6eb..c4a72c90b0 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -400,6 +400,9 @@ "enable_fanout": { "type": "boolean" }, + "enable_mcp_apps": { + "type": "boolean" + }, "enable_request_compression": { "type": "boolean" }, @@ -421,9 +424,6 @@ "fast_mode": { "type": "boolean" }, - "general_analytics": { - "type": "boolean" - }, "goals": { "type": "boolean" }, @@ -766,16 +766,16 @@ "additionalProperties": false, "properties": { "disable_warnings": { - "description": "Disable all ghost snapshot warning events.", + "description": "Legacy no-op setting retained for compatibility.", "type": "boolean" }, "ignore_large_untracked_dirs": { - "description": "Ignore untracked directories that contain this many files or more. (Still emits a warning unless warnings are disabled.)", + "description": "Legacy no-op setting retained for compatibility.", "format": "int64", "type": "integer" }, "ignore_large_untracked_files": { - "description": "Exclude untracked files larger than this many bytes from ghost snapshots.", + "description": "Legacy no-op setting retained for compatibility.", "format": "int64", "type": "integer" } @@ -1310,6 +1310,17 @@ "hide_spawn_agent_metadata": { "type": "boolean" }, + "max_concurrent_threads_per_session": { + "format": "uint", + "minimum": 1.0, + "type": "integer" + }, + "root_agent_usage_hint_text": { + "type": "string" + }, + "subagent_usage_hint_text": { + "type": "string" + }, "usage_hint_enabled": { "type": "boolean" }, @@ -2264,7 +2275,7 @@ }, "terminal_title": { "default": null, - "description": "Ordered list of terminal title item identifiers.\n\nWhen set, the TUI renders the selected items into the terminal window/tab title. When unset, the TUI defaults to: `spinner` and `project`.", + "description": "Ordered list of terminal title item identifiers.\n\nWhen set, the TUI renders the selected items into the terminal window/tab title. When unset, the TUI defaults to: `activity` and `project`. The `activity` item spins while working and shows an action-required message when blocked on the user.", "items": { "type": "string" }, @@ -2605,6 +2616,9 @@ "enable_fanout": { "type": "boolean" }, + "enable_mcp_apps": { + "type": "boolean" + }, "enable_request_compression": { "type": "boolean" }, @@ -2626,9 +2640,6 @@ "fast_mode": { "type": "boolean" }, - "general_analytics": { - "type": "boolean" - }, "goals": { "type": "boolean" }, @@ -2819,7 +2830,7 @@ } ], "default": null, - "description": "Settings for ghost snapshots (used for undo)." + "description": "Compatibility-only settings retained so legacy `ghost_snapshot` config still loads." }, "hide_agent_reasoning": { "description": "When set to `true`, `AgentReasoning` events will be hidden from the UI/output. Defaults to `false`.", diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index d4ec6858d1..19ef2a54fe 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -19,6 +19,7 @@ use codex_protocol::AgentPath; use codex_protocol::ThreadId; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; +use codex_protocol::models::ContentItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::InitialHistory; @@ -27,7 +28,6 @@ use codex_protocol::protocol::Op; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::user_input::UserInput; use codex_rollout::state_db; @@ -114,7 +114,6 @@ fn keep_forked_rollout_item(item: &RolloutItem) -> bool { | ResponseItem::ToolSearchOutput { .. } | ResponseItem::WebSearchCall { .. } | ResponseItem::ImageGenerationCall { .. } - | ResponseItem::GhostSnapshot { .. } | ResponseItem::Compaction { .. } | ResponseItem::Other, ) => false, @@ -149,16 +148,8 @@ impl AgentControl { } } - /// Create a control-plane handle over the same thread manager with an independent live-agent - /// registry. - pub(crate) fn detached_registry(&self) -> Self { - Self { - manager: self.manager.clone(), - ..Default::default() - } - } - /// Spawn a new agent thread and submit the initial prompt. + #[cfg(test)] pub(crate) async fn spawn_agent( &self, config: crate::config::Config, @@ -262,7 +253,6 @@ impl AgentControl { parent_thread_id, .. }, )) = notification_source.as_ref() - && new_thread.thread.enabled(Feature::GeneralAnalytics) { let client_metadata = match state.get_thread(*parent_thread_id).await { Ok(parent_thread) => { @@ -397,7 +387,40 @@ impl AgentControl { forked_rollout_items = truncate_rollout_to_last_n_fork_turns(&forked_rollout_items, *last_n_turns); } - forked_rollout_items.retain(keep_forked_rollout_item); + // MultiAgentV2 root/subagent usage hints are injected as standalone developer + // messages at thread start. When forking history, drop hints from the parent + // so the child gets a fresh hint that matches its own session source/config. + let multi_agent_v2_usage_hint_texts_to_filter: Vec = + if let Some(parent_thread) = parent_thread.as_ref() { + parent_thread + .codex + .session + .configured_multi_agent_v2_usage_hint_texts() + .await + } else if config.features.enabled(Feature::MultiAgentV2) { + [ + config.multi_agent_v2.root_agent_usage_hint_text.clone(), + config.multi_agent_v2.subagent_usage_hint_text.clone(), + ] + .into_iter() + .flatten() + .collect() + } else { + Vec::new() + }; + forked_rollout_items.retain(|item| { + if let RolloutItem::ResponseItem(ResponseItem::Message { role, content, .. }) = item + && role == "developer" + && let [ContentItem::InputText { text }] = content.as_slice() + && multi_agent_v2_usage_hint_texts_to_filter + .iter() + .any(|usage_hint_text| usage_hint_text == text) + { + return false; + } + + keep_forked_rollout_item(item) + }); state .fork_thread_with_source( @@ -799,16 +822,6 @@ impl AgentControl { Ok(thread.subscribe_status()) } - pub(crate) async fn get_total_token_usage(&self, agent_id: ThreadId) -> Option { - let Ok(state) = self.upgrade() else { - return None; - }; - let Ok(thread) = state.get_thread(agent_id).await else { - return None; - }; - thread.total_token_usage().await - } - pub(crate) async fn format_environment_context_subagents( &self, parent_thread_id: ThreadId, diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index daa86718fa..8ce7fa2ea2 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -595,7 +595,25 @@ async fn spawn_agent_creates_thread_and_sends_prompt() { #[tokio::test] async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() { let harness = AgentControlHarness::new().await; - let (parent_thread_id, parent_thread) = harness.start_thread().await; + let mut parent_config = harness.config.clone(); + let _ = parent_config.features.enable(Feature::MultiAgentV2); + parent_config.multi_agent_v2.root_agent_usage_hint_text = + Some("Parent root guidance.".to_string()); + parent_config.multi_agent_v2.subagent_usage_hint_text = + Some("Parent subagent guidance.".to_string()); + let mut child_config = harness.config.clone(); + let _ = child_config.features.enable(Feature::MultiAgentV2); + child_config.multi_agent_v2.root_agent_usage_hint_text = + Some("Child root guidance.".to_string()); + child_config.multi_agent_v2.subagent_usage_hint_text = + Some("Child subagent guidance.".to_string()); + let new_thread = harness + .manager + .start_thread(parent_config) + .await + .expect("start parent thread"); + let parent_thread_id = new_thread.thread_id; + let parent_thread = new_thread.thread; parent_thread .inject_user_message_without_turn("parent seed context".to_string()) .await; @@ -614,6 +632,22 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() { .record_conversation_items( turn_context.as_ref(), &[ + ResponseItem::Message { + id: None, + role: "developer".to_string(), + content: vec![ContentItem::InputText { + text: "Parent root guidance.".to_string(), + }], + phase: None, + }, + ResponseItem::Message { + id: None, + role: "developer".to_string(), + content: vec![ContentItem::InputText { + text: "Parent subagent guidance.".to_string(), + }], + phase: None, + }, assistant_message("parent commentary", Some(MessagePhase::Commentary)), assistant_message("parent final answer", Some(MessagePhase::FinalAnswer)), assistant_message("parent unknown phase", /*phase*/ None), @@ -643,7 +677,7 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() { let child_thread_id = harness .control .spawn_agent_with_metadata( - harness.config.clone(), + child_config, text_input("child task"), Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, diff --git a/codex-rs/core/src/arc_monitor.rs b/codex-rs/core/src/arc_monitor.rs index 08b7465178..c7f12e1024 100644 --- a/codex-rs/core/src/arc_monitor.rs +++ b/codex-rs/core/src/arc_monitor.rs @@ -383,7 +383,6 @@ fn build_arc_monitor_message_item( | ResponseItem::CustomToolCallOutput { .. } | ResponseItem::ToolSearchOutput { .. } | ResponseItem::ImageGenerationCall { .. } - | ResponseItem::GhostSnapshot { .. } | ResponseItem::Compaction { .. } | ResponseItem::Other => None, } diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index c49e28f20a..fe64099cc9 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -77,6 +77,7 @@ use codex_protocol::config_types::Verbosity as VerbosityConfig; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; +use codex_protocol::protocol::InternalSessionSource; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::W3cTraceContext; @@ -98,6 +99,7 @@ use tokio::sync::oneshot; use tokio::sync::oneshot::error::TryRecvError; use tokio_tungstenite::tungstenite::Error; use tokio_tungstenite::tungstenite::Message; +use tokio_util::sync::CancellationToken; use tracing::instrument; use tracing::trace; use tracing::warn; @@ -565,7 +567,7 @@ impl ModelClient { } if matches!( self.state.session_source, - SessionSource::SubAgent(SubAgentSource::MemoryConsolidation) + SessionSource::Internal(InternalSessionSource::MemoryConsolidation) ) { extra_headers.insert( X_OPENAI_MEMGEN_REQUEST_HEADER, @@ -1232,7 +1234,8 @@ impl ModelClientSession { Err(ApiError::Transport( unauthorized_transport @ TransportError::Http { status, .. }, )) if status == StatusCode::UNAUTHORIZED => { - inference_trace_attempt.record_failed(&unauthorized_transport); + inference_trace_attempt + .record_failed(&unauthorized_transport, /*output_items*/ &[]); pending_retry = PendingUnauthorizedRetry::from_recovery( handle_unauthorized( unauthorized_transport, @@ -1245,7 +1248,7 @@ impl ModelClientSession { } Err(err) => { let err = map_api_error(err); - inference_trace_attempt.record_failed(&err); + inference_trace_attempt.record_failed(&err, /*output_items*/ &[]); return Err(err); } } @@ -1372,7 +1375,7 @@ impl ModelClientSession { .await .map_err(|err| { let err = map_api_error(err); - inference_trace_attempt.record_failed(&err); + inference_trace_attempt.record_failed(&err, /*output_items*/ &[]); err })?; let (stream, last_request_rx) = map_response_stream( @@ -1594,15 +1597,23 @@ fn build_responses_headers( } fn subagent_header_value(session_source: &SessionSource) -> Option { - let SessionSource::SubAgent(subagent_source) = session_source else { - return None; - }; - match subagent_source { - SubAgentSource::Review => Some("review".to_string()), - SubAgentSource::Compact => Some("compact".to_string()), - SubAgentSource::MemoryConsolidation => Some("memory_consolidation".to_string()), - SubAgentSource::ThreadSpawn { .. } => Some("collab_spawn".to_string()), - SubAgentSource::Other(label) => Some(label.clone()), + match session_source { + SessionSource::SubAgent(subagent_source) => match subagent_source { + SubAgentSource::Review => Some("review".to_string()), + SubAgentSource::Compact => Some("compact".to_string()), + SubAgentSource::MemoryConsolidation => Some("memory_consolidation".to_string()), + SubAgentSource::ThreadSpawn { .. } => Some("collab_spawn".to_string()), + SubAgentSource::Other(label) => Some(label.clone()), + }, + SessionSource::Internal(InternalSessionSource::MemoryConsolidation) => { + Some("memory_consolidation".to_string()) + } + SessionSource::Cli + | SessionSource::VSCode + | SessionSource::Exec + | SessionSource::Mcp + | SessionSource::Custom(_) + | SessionSource::Unknown => None, } } @@ -1616,11 +1627,15 @@ fn parent_thread_id_header_value(session_source: &SessionSource) -> Option None, } } +const RESPONSE_STREAM_CHANNEL_CAPACITY: usize = 1600; +const STREAM_DROPPED_REASON: &str = "response stream dropped before provider terminal event"; + fn map_response_stream( api_stream: S, session_telemetry: SessionTelemetry, @@ -1632,15 +1647,28 @@ where + Send + 'static, { - let (tx_event, rx_event) = mpsc::channel::>(1600); + let (tx_event, rx_event) = + mpsc::channel::>(RESPONSE_STREAM_CHANNEL_CAPACITY); let (tx_last_response, rx_last_response) = oneshot::channel::(); + let consumer_dropped = CancellationToken::new(); + let consumer_dropped_for_stream = consumer_dropped.clone(); tokio::spawn(async move { let mut logged_error = false; let mut tx_last_response = Some(tx_last_response); let mut items_added: Vec = Vec::new(); let mut api_stream = api_stream; - while let Some(event) = api_stream.next().await { + loop { + let event = tokio::select! { + _ = consumer_dropped.cancelled() => { + inference_trace_attempt.record_cancelled(STREAM_DROPPED_REASON, &items_added); + return; + } + event = api_stream.next() => event, + }; + let Some(event) = event else { + break; + }; match event { Ok(ResponseEvent::OutputItemDone(item)) => { items_added.push(item.clone()); @@ -1649,6 +1677,8 @@ where .await .is_err() { + inference_trace_attempt + .record_cancelled(STREAM_DROPPED_REASON, &items_added); return; } } @@ -1691,12 +1721,14 @@ where } Ok(event) => { if tx_event.send(Ok(event)).await.is_err() { + inference_trace_attempt + .record_cancelled(STREAM_DROPPED_REASON, &items_added); return; } } Err(err) => { let mapped = map_api_error(err); - inference_trace_attempt.record_failed(&mapped); + inference_trace_attempt.record_failed(&mapped, &items_added); if !logged_error { session_telemetry.see_event_completed_failed(&mapped); logged_error = true; @@ -1707,9 +1739,17 @@ where } } } + inference_trace_attempt + .record_failed("stream closed before response.completed", &items_added); }); - (ResponseStream { rx_event }, rx_last_response) + ( + ResponseStream { + rx_event, + consumer_dropped: consumer_dropped_for_stream, + }, + rx_last_response, + ) } /// Handles a 401 response by optionally refreshing ChatGPT tokens once. diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index e8e3754003..efe2670652 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -13,6 +13,7 @@ use std::pin::Pin; use std::task::Context; use std::task::Poll; use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; /// Review thread system prompt. Edit `core/src/review_prompt.md` to customize. pub const REVIEW_PROMPT: &str = include_str!("../review_prompt.md"); @@ -175,6 +176,9 @@ fn strip_total_output_header(output: &str) -> Option<(&str, u32)> { pub struct ResponseStream { pub(crate) rx_event: mpsc::Receiver>, + /// Signals the mapper task that the consumer stopped polling before the + /// provider stream reached its own terminal event. + pub(crate) consumer_dropped: CancellationToken, } impl Stream for ResponseStream { @@ -185,6 +189,12 @@ impl Stream for ResponseStream { } } +impl Drop for ResponseStream { + fn drop(&mut self) { + self.consumer_dropped.cancel(); + } +} + #[cfg(test)] #[path = "client_common_tests.rs"] mod tests; diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index f4575b26a0..f7d263c0e7 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -7,17 +7,38 @@ 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 codex_api::ApiError; +use codex_api::ResponseEvent; use codex_app_server_protocol::AuthMode; use codex_model_provider::BearerAuthProvider; 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::models::ContentItem; +use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; +use codex_protocol::protocol::InternalSessionSource; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; +use codex_rollout_trace::ExecutionStatus; +use codex_rollout_trace::InferenceTraceAttempt; +use codex_rollout_trace::InferenceTraceContext; +use codex_rollout_trace::RawTraceEventPayload; +use codex_rollout_trace::RolloutTrace; +use codex_rollout_trace::TraceWriter; +use codex_rollout_trace::replay_bundle; +use futures::StreamExt; use pretty_assertions::assert_eq; use serde_json::json; +use std::collections::VecDeque; +use std::pin::Pin; +use std::sync::Arc; +use std::task::Context; +use std::task::Poll; +use std::time::Duration; +use tempfile::TempDir; +use tokio::sync::Notify; fn test_model_client(session_source: SessionSource) -> ModelClient { let provider = create_oss_provider_with_base_url("https://example.com/v1", WireApi::Responses); @@ -79,6 +100,92 @@ fn test_session_telemetry() -> SessionTelemetry { ) } +fn started_inference_attempt(temp: &TempDir) -> anyhow::Result { + let writer = Arc::new(TraceWriter::create( + temp.path(), + "trace-1".to_string(), + "rollout-1".to_string(), + "thread-root".to_string(), + )?); + writer.append(RawTraceEventPayload::ThreadStarted { + thread_id: "thread-root".to_string(), + agent_path: "/root".to_string(), + metadata_payload: None, + })?; + writer.append(RawTraceEventPayload::CodexTurnStarted { + codex_turn_id: "turn-1".to_string(), + thread_id: "thread-root".to_string(), + })?; + + let inference_trace = InferenceTraceContext::enabled( + writer, + "thread-root".to_string(), + "turn-1".to_string(), + "gpt-test".to_string(), + "test-provider".to_string(), + ); + let attempt = inference_trace.start_attempt(); + attempt.record_started(&json!({ + "model": "gpt-test", + "input": [{ + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "hello"}] + }], + })); + Ok(attempt) +} + +fn output_message(id: &str, text: &str) -> ResponseItem { + ResponseItem::Message { + id: Some(id.to_string()), + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: text.to_string(), + }], + phase: None, + } +} + +async fn replay_until_cancelled(temp: &TempDir) -> anyhow::Result { + let mut rollout = replay_bundle(temp.path())?; + for _ in 0..50 { + let inference = rollout + .inference_calls + .values() + .next() + .expect("inference should be reduced"); + if inference.execution.status == ExecutionStatus::Cancelled { + return Ok(rollout); + } + tokio::time::sleep(Duration::from_millis(10)).await; + rollout = replay_bundle(temp.path())?; + } + Ok(rollout) +} + +struct NotifyAfterEventStream { + events: VecDeque, + yielded: usize, + notify_after: usize, + notify: Arc, +} + +impl futures::Stream for NotifyAfterEventStream { + type Item = std::result::Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let Some(event) = self.events.pop_front() else { + return Poll::Pending; + }; + self.yielded += 1; + if self.yielded == self.notify_after { + self.notify.notify_one(); + } + Poll::Ready(Some(Ok(event))) + } +} + #[test] fn build_subagent_headers_sets_other_subagent_label() { let client = test_model_client(SessionSource::SubAgent(SubAgentSource::Other( @@ -91,6 +198,18 @@ fn build_subagent_headers_sets_other_subagent_label() { assert_eq!(value, Some("memory_consolidation")); } +#[test] +fn build_subagent_headers_sets_internal_memory_consolidation_label() { + let client = test_model_client(SessionSource::Internal( + InternalSessionSource::MemoryConsolidation, + )); + let headers = client.build_subagent_headers(); + let value = headers + .get(X_OPENAI_SUBAGENT_HEADER) + .and_then(|value| value.to_str().ok()); + assert_eq!(value, Some("memory_consolidation")); +} + #[test] fn build_ws_client_metadata_includes_window_lineage_and_turn_metadata() { let parent_thread_id = ThreadId::new(); @@ -151,6 +270,91 @@ async fn summarize_memories_returns_empty_for_empty_input() { assert_eq!(output.len(), 0); } +#[tokio::test] +async fn dropped_response_stream_traces_cancelled_partial_output() -> anyhow::Result<()> { + let temp = TempDir::new()?; + let attempt = started_inference_attempt(&temp)?; + + // The provider has produced one complete output item, but no terminal + // response.completed event. The harness has enough information to keep this + // item in history, so the trace should preserve it when the stream is + // abandoned. + let item = output_message("msg-1", "partial answer"); + let api_stream = futures::stream::iter([Ok(ResponseEvent::OutputItemDone(item))]) + .chain(futures::stream::pending()); + let (mut stream, _) = super::map_response_stream(api_stream, test_session_telemetry(), attempt); + + let observed = stream + .next() + .await + .expect("mapped stream should yield output item")?; + assert!(matches!(observed, ResponseEvent::OutputItemDone(_))); + + // Dropping the consumer is how turn interruption/preemption stops polling + // the provider stream. The mapper task observes that drop asynchronously + // and records cancellation using the output items it has already seen. + drop(stream); + + // Cancellation is recorded by the mapper task after Drop wakes it, so the + // replay may need a short wait before the terminal event appears on disk. + let rollout = replay_until_cancelled(&temp).await?; + let inference = rollout + .inference_calls + .values() + .next() + .expect("inference should be reduced"); + + assert_eq!(inference.execution.status, ExecutionStatus::Cancelled); + assert_eq!(inference.response_item_ids.len(), 1); + assert_eq!(rollout.raw_payloads.len(), 2); + + Ok(()) +} + +#[tokio::test] +async fn dropped_backpressured_response_stream_traces_cancelled_partial_output() +-> anyhow::Result<()> { + let temp = TempDir::new()?; + let attempt = started_inference_attempt(&temp)?; + let backpressured_item_yielded = Arc::new(Notify::new()); + let mut events = VecDeque::new(); + for _ in 0..super::RESPONSE_STREAM_CHANNEL_CAPACITY { + events.push_back(ResponseEvent::Created); + } + events.push_back(ResponseEvent::OutputItemDone(output_message( + "msg-1", + "partial answer", + ))); + let api_stream = NotifyAfterEventStream { + events, + yielded: 0, + notify_after: super::RESPONSE_STREAM_CHANNEL_CAPACITY + 1, + notify: Arc::clone(&backpressured_item_yielded), + }; + + let (stream, _) = super::map_response_stream(api_stream, test_session_telemetry(), attempt); + + // Fill the mapper channel with non-terminal events, then yield one output + // item. The mapper has observed that item and is blocked trying to send it + // downstream, so dropping the consumer covers the send-failure path rather + // than the `consumer_dropped` select branch. + backpressured_item_yielded.notified().await; + drop(stream); + + let rollout = replay_until_cancelled(&temp).await?; + let inference = rollout + .inference_calls + .values() + .next() + .expect("inference should be reduced"); + + assert_eq!(inference.execution.status, ExecutionStatus::Cancelled); + assert_eq!(inference.response_item_ids.len(), 1); + assert_eq!(rollout.raw_payloads.len(), 2); + + Ok(()) +} + #[test] fn auth_request_telemetry_context_tracks_attached_auth_and_retry_phase() { let auth_context = AuthRequestTelemetryContext::new( diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 1fb2f42f2e..f3df3cd4c6 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -104,18 +104,16 @@ pub(crate) async fn run_codex_thread_interactive( })) .or_cancel(&cancel_token) .await??; - if parent_session.enabled(codex_features::Feature::GeneralAnalytics) { - let thread_config = codex.thread_config_snapshot().await; - let client_metadata = parent_session.app_server_client_metadata().await; - emit_subagent_session_started( - &parent_session.services.analytics_events_client, - client_metadata, - codex.session.conversation_id, - Some(parent_session.conversation_id), - thread_config, - subagent_source, - ); - } + let thread_config = codex.thread_config_snapshot().await; + let client_metadata = parent_session.app_server_client_metadata().await; + emit_subagent_session_started( + &parent_session.services.analytics_events_client, + client_metadata, + codex.session.conversation_id, + Some(parent_session.conversation_id), + thread_config, + subagent_source, + ); let codex = Arc::new(codex); // Use a child token so parent cancel cascades but we can scope it to this task diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 7454b98651..eb5afe57f6 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -27,7 +27,6 @@ use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::Submission; use codex_protocol::protocol::ThreadMemoryMode; -use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; use codex_protocol::protocol::W3cTraceContext; use codex_protocol::user_input::UserInput; @@ -47,7 +46,6 @@ pub struct ThreadConfigSnapshot { pub service_tier: Option, pub approval_policy: AskForApproval, pub approvals_reviewer: ApprovalsReviewer, - pub sandbox_policy: SandboxPolicy, pub permission_profile: PermissionProfile, pub cwd: AbsolutePathBuf, pub ephemeral: bool, @@ -56,6 +54,18 @@ pub struct ThreadConfigSnapshot { pub session_source: SessionSource, } +impl ThreadConfigSnapshot { + pub fn sandbox_policy(&self) -> SandboxPolicy { + let file_system_sandbox_policy = self.permission_profile.file_system_sandbox_policy(); + codex_sandboxing::compatibility_sandbox_policy_for_permission_profile( + &self.permission_profile, + &file_system_sandbox_policy, + self.permission_profile.network_sandbox_policy(), + self.cwd.as_path(), + ) + } +} + /// Turn context overrides that app-server validates before starting a turn. #[derive(Clone, Default)] pub struct CodexThreadTurnContextOverrides { @@ -75,6 +85,7 @@ pub struct CodexThreadTurnContextOverrides { pub struct CodexThread { pub(crate) codex: Codex, + pub(crate) session_source: SessionSource, rollout_path: Option, out_of_band_elicitation_count: Mutex, _watch_registration: WatchRegistration, @@ -86,10 +97,12 @@ impl CodexThread { pub(crate) fn new( codex: Codex, rollout_path: Option, + session_source: SessionSource, watch_registration: WatchRegistration, ) -> Self { Self { codex, + session_source, rollout_path, out_of_band_elicitation_count: Mutex::new(0), _watch_registration: watch_registration, @@ -104,6 +117,11 @@ impl CodexThread { self.codex.shutdown_and_wait().await } + /// Wait until the underlying session loop has terminated. + pub async fn wait_until_terminated(&self) { + self.codex.session_loop_termination.clone().await; + } + pub async fn apply_goal_resume_runtime_effects(&self) -> anyhow::Result<()> { self.codex .session @@ -257,10 +275,6 @@ impl CodexThread { self.codex.agent_status.clone() } - pub(crate) async fn total_token_usage(&self) -> Option { - self.codex.session.total_token_usage().await - } - /// Returns the complete token usage snapshot currently cached for this thread. /// /// This accessor is intentionally narrower than direct session access: it lets diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index e9218ae7f0..1ebc307e33 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -18,7 +18,6 @@ use codex_analytics::CompactionStatus; use codex_analytics::CompactionStrategy; use codex_analytics::CompactionTrigger; use codex_analytics::now_unix_seconds; -use codex_features::Feature; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::items::ContextCompactionItem; @@ -266,12 +265,6 @@ async fn run_compact_task_inner_impl( new_history = insert_initial_context_before_last_real_user_or_summary(new_history, initial_context); } - let ghost_snapshots: Vec = history_items - .iter() - .filter(|item| matches!(item, ResponseItem::GhostSnapshot { .. })) - .cloned() - .collect(); - new_history.extend(ghost_snapshots); let reference_context_item = match initial_context_injection { InitialContextInjection::DoNotInject => None, InitialContextInjection::BeforeLastUserMessage => Some(turn_context.to_turn_context_item()), @@ -295,7 +288,6 @@ async fn run_compact_task_inner_impl( } pub(crate) struct CompactionAnalyticsAttempt { - enabled: bool, thread_id: String, turn_id: String, trigger: CompactionTrigger, @@ -316,10 +308,8 @@ impl CompactionAnalyticsAttempt { implementation: CompactionImplementation, phase: CompactionPhase, ) -> Self { - let enabled = sess.enabled(Feature::GeneralAnalytics); let active_context_tokens_before = sess.get_total_token_usage().await; Self { - enabled, thread_id: sess.conversation_id.to_string(), turn_id: turn_context.sub_id.clone(), trigger, @@ -338,9 +328,6 @@ impl CompactionAnalyticsAttempt { status: CompactionStatus, error: Option, ) { - if !self.enabled { - return; - } let active_context_tokens_after = sess.get_total_token_usage().await; sess.services .analytics_events_client diff --git a/codex-rs/core/src/compact_remote.rs b/codex-rs/core/src/compact_remote.rs index 0623ceb3b6..d8adb20772 100644 --- a/codex-rs/core/src/compact_remote.rs +++ b/codex-rs/core/src/compact_remote.rs @@ -145,14 +145,6 @@ async fn run_remote_compact_task_inner_impl( // compact endpoint. The checkpoint below records it separately from the next sampling request, // whose prompt will repeat current developer/context prefix items. let trace_input_history = history.raw_items().to_vec(); - // Required to keep `/undo` available after compaction - let ghost_snapshots: Vec = history - .raw_items() - .iter() - .filter(|item| matches!(item, ResponseItem::GhostSnapshot { .. })) - .cloned() - .collect(); - let prompt_input = history.for_prompt(&turn_context.model_info.input_modalities); let tool_router = built_tools( sess.as_ref(), @@ -204,9 +196,6 @@ async fn run_remote_compact_task_inner_impl( ) .await; - if !ghost_snapshots.is_empty() { - new_history.extend(ghost_snapshots); - } let reference_context_item = match initial_context_injection { InitialContextInjection::DoNotInject => None, InitialContextInjection::BeforeLastUserMessage => Some(turn_context.to_turn_context_item()), @@ -290,7 +279,6 @@ fn should_keep_compacted_history_item(item: &ResponseItem) -> bool { | ResponseItem::CustomToolCallOutput { .. } | ResponseItem::WebSearchCall { .. } | ResponseItem::ImageGenerationCall { .. } - | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other => false, } } diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index d0ea8980bf..a2b5312103 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -133,6 +133,34 @@ fn http_mcp(url: &str) -> McpServerConfig { } } +async fn derive_legacy_sandbox_policy_for_test( + cfg: &ConfigToml, + sandbox_mode_override: Option, + profile_sandbox_mode: Option, + windows_sandbox_level: WindowsSandboxLevel, + active_project: Option<&ProjectConfig>, + permission_profile_constraint: Option<&Constrained>, +) -> SandboxPolicy { + let permission_profile = cfg + .derive_permission_profile( + sandbox_mode_override, + profile_sandbox_mode, + windows_sandbox_level, + active_project, + permission_profile_constraint, + ) + .await; + permission_profile + .to_legacy_sandbox_policy(Path::new("/")) + .unwrap_or_else(|err| { + tracing::warn!( + error = %err, + "derived permission profile cannot be represented as a legacy sandbox policy; falling back to read-only" + ); + SandboxPolicy::new_read_only_policy() + }) +} + #[tokio::test] async fn load_config_normalizes_relative_cwd_override() -> std::io::Result<()> { let expected_cwd = AbsolutePathBuf::relative_to_current_dir("nested")?; @@ -947,7 +975,7 @@ async fn permission_profile_override_applies_runtime_roots_to_legacy_projection( }, FileSystemSandboxEntry { path: FileSystemPath::Special { - value: FileSystemSpecialPath::CurrentWorkingDirectory, + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), }, access: FileSystemAccessMode::Write, }, @@ -1630,15 +1658,15 @@ network_access = false # This should be ignored. let sandbox_full_access_cfg = toml::from_str::(sandbox_full_access) .expect("TOML deserialization should succeed"); let sandbox_mode_override = None; - let resolution = sandbox_full_access_cfg - .derive_sandbox_policy( - sandbox_mode_override, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - /*active_project*/ None, - /*permission_profile_constraint*/ None, - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &sandbox_full_access_cfg, + sandbox_mode_override, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + /*active_project*/ None, + /*permission_profile_constraint*/ None, + ) + .await; assert_eq!(resolution, SandboxPolicy::DangerFullAccess); let sandbox_read_only = r#" @@ -1651,15 +1679,15 @@ network_access = true # This should be ignored. let sandbox_read_only_cfg = toml::from_str::(sandbox_read_only) .expect("TOML deserialization should succeed"); let sandbox_mode_override = None; - let resolution = sandbox_read_only_cfg - .derive_sandbox_policy( - sandbox_mode_override, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - /*active_project*/ None, - /*permission_profile_constraint*/ None, - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &sandbox_read_only_cfg, + sandbox_mode_override, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + /*active_project*/ None, + /*permission_profile_constraint*/ None, + ) + .await; assert_eq!(resolution, SandboxPolicy::new_read_only_policy()); let writable_root = test_absolute_path("/my/workspace"); @@ -1683,15 +1711,15 @@ trust_level = "trusted" let sandbox_workspace_write_cfg = toml::from_str::(&sandbox_workspace_write) .expect("TOML deserialization should succeed"); let sandbox_mode_override = None; - let resolution = sandbox_workspace_write_cfg - .derive_sandbox_policy( - sandbox_mode_override, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - /*active_project*/ None, - /*permission_profile_constraint*/ None, - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &sandbox_workspace_write_cfg, + sandbox_mode_override, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + /*active_project*/ None, + /*permission_profile_constraint*/ None, + ) + .await; if cfg!(target_os = "windows") { assert_eq!(resolution, SandboxPolicy::new_read_only_policy()); } else { @@ -1723,15 +1751,15 @@ exclude_slash_tmp = true let sandbox_workspace_write_cfg = toml::from_str::(&sandbox_workspace_write) .expect("TOML deserialization should succeed"); let sandbox_mode_override = None; - let resolution = sandbox_workspace_write_cfg - .derive_sandbox_policy( - sandbox_mode_override, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - /*active_project*/ None, - /*permission_profile_constraint*/ None, - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &sandbox_workspace_write_cfg, + sandbox_mode_override, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + /*active_project*/ None, + /*permission_profile_constraint*/ None, + ) + .await; if cfg!(target_os = "windows") { assert_eq!(resolution, SandboxPolicy::new_read_only_policy()); } else { @@ -1748,7 +1776,7 @@ exclude_slash_tmp = true } #[tokio::test] -async fn legacy_sandbox_mode_config_builds_split_policies_without_drift() -> std::io::Result<()> { +async fn legacy_sandbox_mode_builds_profiles_with_compatible_projection() -> std::io::Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; let extra_root = test_absolute_path("/tmp/legacy-extra-root"); @@ -1793,26 +1821,91 @@ exclude_slash_tmp = true ) .await?; - let sandbox_policy = &config.legacy_sandbox_policy(); + let sandbox_policy = config.legacy_sandbox_policy(); + let file_system_policy = config.permissions.file_system_sandbox_policy(); + let network_policy = config.permissions.network_sandbox_policy(); + assert_eq!( - config.permissions.file_system_sandbox_policy(), - FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd(sandbox_policy, cwd.path()), - "case `{name}` should preserve filesystem semantics from legacy config" - ); - assert_eq!( - config.permissions.network_sandbox_policy(), - NetworkSandboxPolicy::from(sandbox_policy), + network_policy, + NetworkSandboxPolicy::from(&sandbox_policy), "case `{name}` should preserve network semantics from legacy config" ); assert_eq!( - config - .permissions - .file_system_sandbox_policy() - .to_legacy_sandbox_policy(config.permissions.network_sandbox_policy(), cwd.path()) + file_system_policy + .to_legacy_sandbox_policy(network_policy, cwd.path()) .unwrap_or_else(|err| panic!("case `{name}` should round-trip: {err}")), - sandbox_policy.clone(), - "case `{name}` should round-trip through split policies without drift" + sandbox_policy, + "case `{name}` should preserve its legacy compatibility projection" ); + + match name.as_str() { + "danger-full-access" | "read-only" => { + assert_eq!( + file_system_policy, + FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd( + &sandbox_policy, + cwd.path() + ), + "case `{name}` should match the legacy filesystem projection exactly" + ); + } + "workspace-write" => { + if cfg!(target_os = "windows") { + assert_eq!( + sandbox_policy, + SandboxPolicy::new_read_only_policy(), + "legacy workspace-write should keep the existing Windows downgrade when \ + the experimental Windows sandbox is disabled" + ); + assert_eq!( + file_system_policy, + FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd( + &sandbox_policy, + cwd.path() + ), + "downgraded workspace-write should match the legacy read-only projection" + ); + continue; + } + assert!( + file_system_policy + .entries + .contains(&FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), + }, + access: FileSystemAccessMode::Write, + }) + ); + assert!( + file_system_policy + .entries + .contains(&FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: extra_root.clone(), + }, + access: FileSystemAccessMode::Write, + }) + ); + for subpath in [".git", ".agents", ".codex"] { + assert!( + file_system_policy + .entries + .contains(&FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(Some( + subpath.into() + )), + }, + access: FileSystemAccessMode::Read, + }), + "case `{name}` should preserve `{subpath}` as a symbolic project-root \ + metadata carveout" + ); + } + } + _ => unreachable!("unexpected test case `{name}`"), + } } Ok(()) @@ -6310,15 +6403,15 @@ trust_level = "untrusted" trust_level: Some(TrustLevel::Untrusted), }; - let resolution = cfg - .derive_sandbox_policy( - /*sandbox_mode_override*/ None, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - Some(&active_project), - /*permission_profile_constraint*/ None, - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &cfg, + /*sandbox_mode_override*/ None, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + Some(&active_project), + /*permission_profile_constraint*/ None, + ) + .await; // Verify that untrusted projects get WorkspaceWrite (or ReadOnly on Windows due to downgrade) if cfg!(target_os = "windows") { @@ -6367,15 +6460,15 @@ async fn derive_sandbox_policy_falls_back_to_read_only_for_implicit_defaults() - } })?; - let resolution = cfg - .derive_sandbox_policy( - /*sandbox_mode_override*/ None, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - Some(&active_project), - Some(&constrained), - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &cfg, + /*sandbox_mode_override*/ None, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + Some(&active_project), + Some(&constrained), + ) + .await; assert_eq!(resolution, SandboxPolicy::new_read_only_policy()); Ok(()) @@ -6423,15 +6516,15 @@ async fn derive_sandbox_policy_preserves_windows_downgrade_for_unsupported_fallb }, )?; - let resolution = cfg - .derive_sandbox_policy( - /*sandbox_mode_override*/ None, - /*profile_sandbox_mode*/ None, - WindowsSandboxLevel::Disabled, - Some(&active_project), - Some(&constrained), - ) - .await; + let resolution = derive_legacy_sandbox_policy_for_test( + &cfg, + /*sandbox_mode_override*/ None, + /*profile_sandbox_mode*/ None, + WindowsSandboxLevel::Disabled, + Some(&active_project), + Some(&constrained), + ) + .await; if cfg!(target_os = "windows") { assert_eq!(resolution, SandboxPolicy::new_read_only_policy()); @@ -7348,8 +7441,11 @@ async fn multi_agent_v2_config_from_feature_table() -> std::io::Result<()> { codex_home.path().join(CONFIG_TOML_FILE), r#"[features.multi_agent_v2] enabled = true +max_concurrent_threads_per_session = 5 usage_hint_enabled = false usage_hint_text = "Custom delegation guidance." +root_agent_usage_hint_text = "Root guidance." +subagent_usage_hint_text = "Subagent guidance." hide_spawn_agent_metadata = true "#, )?; @@ -7361,11 +7457,21 @@ hide_spawn_agent_metadata = true .await?; assert!(config.features.enabled(Feature::MultiAgentV2)); + assert_eq!(config.multi_agent_v2.max_concurrent_threads_per_session, 5); + assert_eq!(config.agent_max_threads, Some(4)); assert!(!config.multi_agent_v2.usage_hint_enabled); assert_eq!( config.multi_agent_v2.usage_hint_text.as_deref(), Some("Custom delegation guidance.") ); + assert_eq!( + config.multi_agent_v2.root_agent_usage_hint_text.as_deref(), + Some("Root guidance.") + ); + assert_eq!( + config.multi_agent_v2.subagent_usage_hint_text.as_deref(), + Some("Subagent guidance.") + ); assert!(config.multi_agent_v2.hide_spawn_agent_metadata); Ok(()) @@ -7379,13 +7485,19 @@ async fn profile_multi_agent_v2_config_overrides_base() -> std::io::Result<()> { r#"profile = "no_hint" [features.multi_agent_v2] +max_concurrent_threads_per_session = 4 usage_hint_enabled = true usage_hint_text = "base hint" +root_agent_usage_hint_text = "base root hint" +subagent_usage_hint_text = "base subagent hint" hide_spawn_agent_metadata = true [profiles.no_hint.features.multi_agent_v2] +max_concurrent_threads_per_session = 6 usage_hint_enabled = false usage_hint_text = "profile hint" +root_agent_usage_hint_text = "profile root hint" +subagent_usage_hint_text = "profile subagent hint" hide_spawn_agent_metadata = false "#, )?; @@ -7396,16 +7508,99 @@ hide_spawn_agent_metadata = false .build() .await?; + assert_eq!(config.multi_agent_v2.max_concurrent_threads_per_session, 6); assert!(!config.multi_agent_v2.usage_hint_enabled); assert_eq!( config.multi_agent_v2.usage_hint_text.as_deref(), Some("profile hint") ); + assert_eq!( + config.multi_agent_v2.root_agent_usage_hint_text.as_deref(), + Some("profile root hint") + ); + assert_eq!( + config.multi_agent_v2.subagent_usage_hint_text.as_deref(), + Some("profile subagent hint") + ); assert!(!config.multi_agent_v2.hide_spawn_agent_metadata); Ok(()) } +#[tokio::test] +async fn multi_agent_v2_default_session_thread_cap_counts_root() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"[features.multi_agent_v2] +enabled = true +"#, + )?; + + let config = ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .build() + .await?; + + assert_eq!(config.multi_agent_v2.max_concurrent_threads_per_session, 4); + assert_eq!(config.agent_max_threads, Some(3)); + + Ok(()) +} + +#[tokio::test] +async fn multi_agent_v2_rejects_agents_max_threads() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"[features.multi_agent_v2] +enabled = true + +[agents] +max_threads = 3 +"#, + )?; + + let err = ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .build() + .await + .expect_err("agents.max_threads should conflict with multi_agent_v2"); + + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert_eq!( + err.to_string(), + "agents.max_threads cannot be set when multi_agent_v2 is enabled" + ); + + Ok(()) +} + +#[tokio::test] +async fn multi_agent_v2_session_thread_cap_one_disallows_subagents() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"[features.multi_agent_v2] +enabled = true +max_concurrent_threads_per_session = 1 +"#, + )?; + + let config = ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .build() + .await?; + + assert_eq!(config.multi_agent_v2.max_concurrent_threads_per_session, 1); + assert_eq!(config.agent_max_threads, Some(0)); + + Ok(()) +} + #[tokio::test] async fn feature_requirements_normalize_runtime_feature_mutations() -> std::io::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 9635034dcc..f8a079b1f2 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1,7 +1,6 @@ use crate::agents_md::AgentsMdManager; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; -use crate::memories::memory_root; use crate::path_utils::normalize_for_native_workdir; use crate::unified_exec::DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS; use crate::unified_exec::MIN_EMPTY_YIELD_TIME_MS; @@ -63,6 +62,7 @@ use codex_features::MultiAgentV2ConfigToml; use codex_git_utils::resolve_root_git_project_for_trust; use codex_login::AuthManagerConfig; use codex_mcp::McpConfig; +use codex_memories_read::memory_root; use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID; use codex_model_provider_info::ModelProviderInfo; use codex_model_provider_info::OLLAMA_CHAT_PROVIDER_REMOVED_ERROR; @@ -124,13 +124,34 @@ pub use network_proxy_spec::NetworkProxySpec; pub use network_proxy_spec::StartedNetworkProxy; pub(crate) use permissions::resolve_permission_profile; -pub use codex_git_utils::GhostSnapshotConfig; +const DEFAULT_IGNORE_LARGE_UNTRACKED_DIRS: i64 = 200; +const DEFAULT_IGNORE_LARGE_UNTRACKED_FILES: i64 = 10 * 1024 * 1024; + +/// Compatibility-only config retained so legacy `ghost_snapshot` settings +/// continue to load even though snapshots are no longer produced. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GhostSnapshotConfig { + pub ignore_large_untracked_files: Option, + pub ignore_large_untracked_dirs: Option, + pub disable_warnings: bool, +} + +impl Default for GhostSnapshotConfig { + fn default() -> Self { + Self { + ignore_large_untracked_files: Some(DEFAULT_IGNORE_LARGE_UNTRACKED_FILES), + ignore_large_untracked_dirs: Some(DEFAULT_IGNORE_LARGE_UNTRACKED_DIRS), + disable_warnings: false, + } + } +} /// Maximum number of bytes of the documentation that will be embedded. Larger /// files are *silently truncated* to this size so we do not take up too much of /// the context window. pub(crate) const AGENTS_MD_MAX_BYTES: usize = 32 * 1024; // 32 KiB pub(crate) const DEFAULT_AGENT_MAX_THREADS: Option = Some(6); +pub(crate) const DEFAULT_MULTI_AGENT_V2_MAX_CONCURRENT_THREADS_PER_SESSION: usize = 4; pub(crate) const DEFAULT_AGENT_MAX_DEPTH: i32 = 1; pub(crate) const DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS: Option = None; const LOCAL_DEV_BUILD_VERSION: &str = "0.0.0"; @@ -454,7 +475,9 @@ pub struct Config { /// Ordered list of terminal title item identifiers for the TUI. /// - /// When unset, the TUI defaults to: `project` and `spinner`. + /// When unset, the TUI defaults to: `activity` and `project`. + /// The `activity` item spins while working and shows an action-required + /// message when blocked on the user. pub tui_terminal_title: Option>, /// Syntax highlighting theme override (kebab-case name). @@ -652,7 +675,8 @@ pub struct Config { /// Default: `300000` (5 minutes). pub background_terminal_max_timeout: u64, - /// Settings for ghost snapshots (used for undo). + /// Compatibility-only settings retained for legacy `ghost_snapshot` + /// config loading. pub ghost_snapshot: GhostSnapshotConfig, /// Settings specific to the task-path-based multi-agent tool surface. @@ -704,16 +728,23 @@ pub struct Config { #[derive(Debug, Clone, PartialEq, Eq)] pub struct MultiAgentV2Config { + pub max_concurrent_threads_per_session: usize, pub usage_hint_enabled: bool, pub usage_hint_text: Option, + pub root_agent_usage_hint_text: Option, + pub subagent_usage_hint_text: Option, pub hide_spawn_agent_metadata: bool, } impl Default for MultiAgentV2Config { fn default() -> Self { Self { + max_concurrent_threads_per_session: + DEFAULT_MULTI_AGENT_V2_MAX_CONCURRENT_THREADS_PER_SESSION, usage_hint_enabled: true, usage_hint_text: None, + root_agent_usage_hint_text: None, + subagent_usage_hint_text: None, hide_spawn_agent_metadata: false, } } @@ -1579,6 +1610,10 @@ fn resolve_multi_agent_v2_config( let profile = multi_agent_v2_toml_config(config_profile.features.as_ref()); let default = MultiAgentV2Config::default(); + let max_concurrent_threads_per_session = profile + .and_then(|config| config.max_concurrent_threads_per_session) + .or_else(|| base.and_then(|config| config.max_concurrent_threads_per_session)) + .unwrap_or(default.max_concurrent_threads_per_session); let usage_hint_enabled = profile .and_then(|config| config.usage_hint_enabled) .or_else(|| base.and_then(|config| config.usage_hint_enabled)) @@ -1588,14 +1623,27 @@ fn resolve_multi_agent_v2_config( .or_else(|| base.and_then(|config| config.usage_hint_text.as_ref())) .cloned() .or(default.usage_hint_text); + let root_agent_usage_hint_text = profile + .and_then(|config| config.root_agent_usage_hint_text.as_ref()) + .or_else(|| base.and_then(|config| config.root_agent_usage_hint_text.as_ref())) + .cloned() + .or(default.root_agent_usage_hint_text); + let subagent_usage_hint_text = profile + .and_then(|config| config.subagent_usage_hint_text.as_ref()) + .or_else(|| base.and_then(|config| config.subagent_usage_hint_text.as_ref())) + .cloned() + .or(default.subagent_usage_hint_text); let hide_spawn_agent_metadata = profile .and_then(|config| config.hide_spawn_agent_metadata) .or_else(|| base.and_then(|config| config.hide_spawn_agent_metadata)) .unwrap_or(default.hide_spawn_agent_metadata); MultiAgentV2Config { + max_concurrent_threads_per_session, usage_hint_enabled, usage_hint_text, + root_agent_usage_hint_text, + subagent_usage_hint_text, hide_spawn_agent_metadata, } } @@ -1965,8 +2013,13 @@ impl Config { ) } else { let configured_network_proxy_config = NetworkProxyConfig::default(); - let mut sandbox_policy = cfg - .derive_sandbox_policy( + // No named `[permissions]` profile is active, but permissions + // should still flow through the canonical profile representation. + // Derive the old `sandbox_mode` defaults as a profile first, then + // keep a legacy-compatible projection only for the remaining code + // paths that still speak `SandboxPolicy`. + let mut permission_profile = cfg + .derive_permission_profile( sandbox_mode, config_profile.sandbox_mode, windows_sandbox_level, @@ -1974,24 +2027,46 @@ impl Config { Some(&constrained_permission_profile), ) .await; - if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &mut sandbox_policy { - for path in &additional_writable_roots { - if !writable_roots.iter().any(|existing| existing == path) { - writable_roots.push(path.clone()); - } - } + // The legacy-derived profiles above are expected to be + // representable as `SandboxPolicy`. This guard keeps the old safe + // fallback behavior if future changes make this branch derive a + // profile with split-only filesystem semantics, such as root write + // with carveouts or writes that are not expressible as + // workspace-write roots. + if let Err(err) = permission_profile.to_legacy_sandbox_policy(resolved_cwd.as_path()) { + tracing::warn!( + error = %err, + "derived permission profile cannot be represented as a legacy sandbox policy; falling back to read-only" + ); + permission_profile = PermissionProfile::read_only(); + } + let (mut file_system_sandbox_policy, network_sandbox_policy) = + permission_profile.to_runtime_permissions(); + // `additional_writable_roots` is a legacy workspace-write knob. It + // only applies when the derived managed profile has workspace-style + // write access to the project roots; read-only, disabled, external, + // and future non-workspace profiles must not silently grow extra + // write access. + if matches!(permission_profile.enforcement(), SandboxEnforcement::Managed) + && file_system_sandbox_policy.can_write_path_with_cwd( + resolved_cwd.as_path(), + resolved_cwd.as_path(), + ) + && !file_system_sandbox_policy.has_full_disk_write_access() + { + // Keep legacy behavior for extra writable roots while storing + // the result as the canonical permission profile. Explicit + // extra roots are concrete paths, so their metadata carveouts + // are also concrete rather than symbolic `:project_roots` + // entries. + file_system_sandbox_policy = file_system_sandbox_policy + .with_additional_legacy_workspace_writable_roots(&additional_writable_roots); + permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( + permission_profile.enforcement(), + &file_system_sandbox_policy, + network_sandbox_policy, + ); } - let file_system_sandbox_policy = - FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd( - &sandbox_policy, - resolved_cwd.as_path(), - ); - let network_sandbox_policy = NetworkSandboxPolicy::from(&sandbox_policy); - let permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - SandboxEnforcement::from_legacy_sandbox_policy(&sandbox_policy), - &file_system_sandbox_policy, - network_sandbox_policy, - ); ( configured_network_proxy_config, permission_profile, @@ -2078,17 +2153,35 @@ impl Config { let history = cfg.history.unwrap_or_default(); - let agent_max_threads = cfg - .agents - .as_ref() - .and_then(|agents| agents.max_threads) - .or(DEFAULT_AGENT_MAX_THREADS); - if agent_max_threads == Some(0) { + if multi_agent_v2.max_concurrent_threads_per_session == 0 { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, - "agents.max_threads must be at least 1", + "features.multi_agent_v2.max_concurrent_threads_per_session must be at least 1", )); } + let agent_max_threads_from_config = cfg.agents.as_ref().and_then(|agents| agents.max_threads); + let agent_max_threads = if features.enabled(Feature::MultiAgentV2) { + if agent_max_threads_from_config.is_some() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "agents.max_threads cannot be set when multi_agent_v2 is enabled", + )); + } + Some( + multi_agent_v2 + .max_concurrent_threads_per_session + .saturating_sub(1), + ) + } else { + let agent_max_threads = agent_max_threads_from_config.or(DEFAULT_AGENT_MAX_THREADS); + if agent_max_threads == Some(0) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "agents.max_threads must be at least 1", + )); + } + agent_max_threads + }; let agent_max_depth = cfg .agents .as_ref() diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 456f3a7eac..be4f56097f 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -144,11 +144,11 @@ pub async fn list_cached_accessible_connectors_from_mcp_tools( config: &Config, ) -> Option> { let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await; let auth = auth_manager.auth().await; if !config .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth)) + .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)) { return Some(Vec::new()); } @@ -216,11 +216,11 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_environment_manager( environment_manager: &EnvironmentManager, ) -> anyhow::Result { let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await; let auth = auth_manager.auth().await; if !config .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth)) + .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)) { return Ok(AccessibleConnectorsStatus { connectors: Vec::new(), @@ -434,7 +434,7 @@ async fn list_directory_connectors_for_tool_suggest_with_auth( Some(auth) } else { let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false); + AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await; loaded_auth = auth_manager.auth().await; loaded_auth.as_ref() }; diff --git a/codex-rs/core/src/context/contextual_user_message.rs b/codex-rs/core/src/context/contextual_user_message.rs index aeb54d61d7..cd7788afee 100644 --- a/codex-rs/core/src/context/contextual_user_message.rs +++ b/codex-rs/core/src/context/contextual_user_message.rs @@ -33,34 +33,12 @@ static CONTEXTUAL_USER_FRAGMENTS: &[&dyn FragmentRegistration] = &[ &SUBAGENT_NOTIFICATION_REGISTRATION, ]; -static MEMORY_EXCLUDED_CONTEXTUAL_USER_FRAGMENTS: &[&dyn FragmentRegistration] = &[ - &USER_INSTRUCTIONS_REGISTRATION, - &SKILL_INSTRUCTIONS_REGISTRATION, -]; - fn is_standard_contextual_user_text(text: &str) -> bool { CONTEXTUAL_USER_FRAGMENTS .iter() .any(|fragment| fragment.matches_text(text)) } -/// Returns whether a contextual user fragment should be omitted from memory -/// stage-1 inputs. -/// -/// We exclude injected `AGENTS.md` instructions and skill payloads because -/// they are prompt scaffolding rather than conversation content, so they do -/// not improve the resulting memory. We keep environment context and -/// subagent notifications because they can carry useful execution context or -/// subtask outcomes that should remain visible to memory generation. -pub(crate) fn is_memory_excluded_contextual_user_fragment(content_item: &ContentItem) -> bool { - let ContentItem::InputText { text } = content_item else { - return false; - }; - MEMORY_EXCLUDED_CONTEXTUAL_USER_FRAGMENTS - .iter() - .any(|fragment| fragment.matches_text(text)) -} - pub(crate) fn is_contextual_user_fragment(content_item: &ContentItem) -> bool { let ContentItem::InputText { text } = content_item else { return false; diff --git a/codex-rs/core/src/context/contextual_user_message_tests.rs b/codex-rs/core/src/context/contextual_user_message_tests.rs index d52cf27adb..a90b8f280a 100644 --- a/codex-rs/core/src/context/contextual_user_message_tests.rs +++ b/codex-rs/core/src/context/contextual_user_message_tests.rs @@ -33,38 +33,6 @@ fn ignores_regular_user_text() { })); } -#[test] -fn classifies_memory_excluded_fragments() { - let cases = [ - ( - "# AGENTS.md instructions for /tmp\n\n\nbody\n", - true, - ), - ( - "\ndemo\nskills/demo/SKILL.md\nbody\n", - true, - ), - ( - "\n/tmp\n", - false, - ), - ( - "{\"agent_id\":\"a\",\"status\":\"completed\"}", - false, - ), - ]; - - for (text, expected) in cases { - assert_eq!( - is_memory_excluded_contextual_user_fragment(&ContentItem::InputText { - text: text.to_string(), - }), - expected, - "{text}", - ); - } -} - #[test] fn detects_hook_prompt_fragment_and_roundtrips_escaping() { let message = build_hook_prompt_message(&[HookPromptFragment::from_single_hook( diff --git a/codex-rs/core/src/context/mod.rs b/codex-rs/core/src/context/mod.rs index 848a4f7f0c..25a6e1f134 100644 --- a/codex-rs/core/src/context/mod.rs +++ b/codex-rs/core/src/context/mod.rs @@ -31,7 +31,6 @@ 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 use fragment::ContextualUserFragment; diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index c4bdc916ff..415a601980 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -103,8 +103,7 @@ impl ContextManager { { for item in items { let item_ref = item.deref(); - let is_ghost_snapshot = matches!(item_ref, ResponseItem::GhostSnapshot { .. }); - if !is_api_message(item_ref) && !is_ghost_snapshot { + if !is_api_message(item_ref) { continue; } @@ -120,8 +119,6 @@ impl ContextManager { pub(crate) fn for_prompt(mut self, input_modalities: &[InputModality]) -> Vec { self.normalize_history(input_modalities); self.items - .retain(|item| !matches!(item, ResponseItem::GhostSnapshot { .. })); - self.items } /// Returns raw items in the history. @@ -403,7 +400,6 @@ impl ContextManager { | ResponseItem::ImageGenerationCall { .. } | ResponseItem::CustomToolCall { .. } | ResponseItem::Compaction { .. } - | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other => item.clone(), } } @@ -492,7 +488,6 @@ fn is_api_message(message: &ResponseItem) -> bool { | ResponseItem::WebSearchCall { .. } | ResponseItem::ImageGenerationCall { .. } | ResponseItem::Compaction { .. } => true, - ResponseItem::GhostSnapshot { .. } => false, ResponseItem::Other => false, } } @@ -519,6 +514,10 @@ const RESIZED_IMAGE_BYTES_ESTIMATE: i64 = 7373; // Use a direct 32px patch count only for `detail: "original"`; // all other image inputs continue to use `RESIZED_IMAGE_BYTES_ESTIMATE`. const ORIGINAL_IMAGE_PATCH_SIZE: u32 = 32; +// See https://platform.openai.com/docs/guides/images-vision#model-sizing-behavior. +// Keep this hard-coded for now; move it into model capabilities if the patch +// budget starts changing often across model releases. +const ORIGINAL_IMAGE_MAX_PATCHES: usize = 10_000; const ORIGINAL_IMAGE_ESTIMATE_CACHE_SIZE: usize = 32; static ORIGINAL_IMAGE_ESTIMATE_CACHE: LazyLock>> = @@ -530,7 +529,6 @@ static ORIGINAL_IMAGE_ESTIMATE_CACHE: LazyLock i64 { match item { - ResponseItem::GhostSnapshot { .. } => 0, ResponseItem::Reasoning { encrypted_content: Some(content), .. @@ -621,6 +619,7 @@ fn estimate_original_image_bytes(image_url: &str) -> Option { let patches_high = height.saturating_add(patch_size.saturating_sub(1)) / patch_size; let patch_count = patches_wide.saturating_mul(patches_high); let patch_count = usize::try_from(patch_count).unwrap_or(usize::MAX); + let patch_count = patch_count.min(ORIGINAL_IMAGE_MAX_PATCHES); Some(i64::try_from(approx_bytes_for_tokens(patch_count)).unwrap_or(i64::MAX)) }) } @@ -686,7 +685,6 @@ fn is_model_generated_item(item: &ResponseItem) -> bool { ResponseItem::FunctionCallOutput { .. } | ResponseItem::ToolSearchOutput { .. } | ResponseItem::CustomToolCallOutput { .. } - | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other => false, } } diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index f5c30af575..74f4d29bfb 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -1,7 +1,6 @@ use super::*; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use codex_git_utils::GhostCommit; use codex_protocol::AgentPath; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::models::BaseInstructions; @@ -26,6 +25,7 @@ use codex_utils_output_truncation::TruncationPolicy; use codex_utils_output_truncation::truncate_text; use image::ImageBuffer; use image::ImageFormat; +use image::Luma; use image::Rgba; use pretty_assertions::assert_eq; use regex_lite::Regex; @@ -593,22 +593,6 @@ fn for_prompt_clears_image_generation_result_when_images_are_unsupported() { ); } -#[test] -fn get_history_for_prompt_drops_ghost_commits() { - let items = vec![ResponseItem::GhostSnapshot { - ghost_commit: GhostCommit::new( - "ghost-1".to_string(), - /*parent*/ None, - Vec::new(), - Vec::new(), - ), - }]; - let history = create_history_with_items(items); - let modalities = default_input_modalities(); - let filtered = history.for_prompt(&modalities); - assert_eq!(filtered, vec![]); -} - #[test] fn estimate_token_count_with_base_instructions_uses_provided_text() { let history = create_history_with_items(vec![assistant_msg("hello from history")]); @@ -1900,6 +1884,38 @@ fn original_detail_images_scale_with_dimensions() { assert_eq!(estimated, expected); } +#[test] +fn original_detail_images_are_capped_at_max_patch_count() { + // 3201x3201 at 32px patches yields 101 * 101 = 10,201 patches, + // which exceeds the original-detail patch budget. + let width = 3201; + let height = 3201; + let image = ImageBuffer::from_pixel(width, height, Luma([12u8])); + let mut bytes = std::io::Cursor::new(Vec::new()); + image + .write_to(&mut bytes, ImageFormat::Png) + .expect("encode png"); + let payload = BASE64_STANDARD.encode(bytes.get_ref()); + let image_url = format!("data:image/png;base64,{payload}"); + let item = ResponseItem::FunctionCallOutput { + call_id: "call-original-capped".to_string(), + output: FunctionCallOutputPayload::from_content_items(vec![ + FunctionCallOutputContentItem::InputImage { + image_url, + detail: Some(ImageDetail::Original), + }, + ]), + }; + + let raw_len = serde_json::to_string(&item).unwrap().len() as i64; + let estimated = estimate_response_item_model_visible_bytes(&item); + let capped_original_detail_image_bytes = + i64::try_from(approx_bytes_for_tokens(ORIGINAL_IMAGE_MAX_PATCHES)).unwrap(); + let expected = raw_len - payload.len() as i64 + capped_original_detail_image_bytes; + + assert_eq!(estimated, expected); +} + #[test] fn original_detail_webp_images_scale_with_dimensions() { // Same dimensions as the PNG case above, so the patch-based replacement cost is the same. diff --git a/codex-rs/core/src/exec_policy_tests.rs b/codex-rs/core/src/exec_policy_tests.rs index fb90ef322f..2db07a0fce 100644 --- a/codex-rs/core/src/exec_policy_tests.rs +++ b/codex-rs/core/src/exec_policy_tests.rs @@ -111,7 +111,11 @@ fn read_only_file_system_sandbox_policy() -> FileSystemSandboxPolicy { } fn workspace_write_file_system_sandbox_policy() -> FileSystemSandboxPolicy { - FileSystemSandboxPolicy::from_legacy_sandbox_policy(&SandboxPolicy::new_workspace_write_policy()) + FileSystemSandboxPolicy::workspace_write( + &[], + /*exclude_tmpdir_env_var*/ false, + /*exclude_slash_tmp*/ false, + ) } fn unrestricted_file_system_sandbox_policy() -> FileSystemSandboxPolicy { @@ -1004,7 +1008,7 @@ fn managed_cwd_write_profile_is_not_read_only() { }, FileSystemSandboxEntry { path: FileSystemPath::Special { - value: FileSystemSpecialPath::CurrentWorkingDirectory, + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), }, access: FileSystemAccessMode::Write, }, diff --git a/codex-rs/core/src/exec_tests.rs b/codex-rs/core/src/exec_tests.rs index 4e8ba10c20..a9304e75ee 100644 --- a/codex-rs/core/src/exec_tests.rs +++ b/codex-rs/core/src/exec_tests.rs @@ -535,7 +535,9 @@ fn windows_restricted_token_rejects_split_only_filesystem_policies() { let file_system_policy = FileSystemSandboxPolicy::restricted(vec![ codex_protocol::permissions::FileSystemSandboxEntry { path: codex_protocol::permissions::FileSystemPath::Special { - value: codex_protocol::permissions::FileSystemSpecialPath::CurrentWorkingDirectory, + value: codex_protocol::permissions::FileSystemSpecialPath::project_roots( + /*subpath*/ None, + ), }, access: codex_protocol::permissions::FileSystemAccessMode::Write, }, @@ -630,7 +632,9 @@ fn windows_restricted_token_supports_full_read_split_write_read_carveouts() { }, codex_protocol::permissions::FileSystemSandboxEntry { path: codex_protocol::permissions::FileSystemPath::Special { - value: codex_protocol::permissions::FileSystemSpecialPath::CurrentWorkingDirectory, + value: codex_protocol::permissions::FileSystemSpecialPath::project_roots( + /*subpath*/ None, + ), }, access: codex_protocol::permissions::FileSystemAccessMode::Write, }, @@ -720,7 +724,9 @@ fn windows_elevated_supports_split_write_read_carveouts() { }, codex_protocol::permissions::FileSystemSandboxEntry { path: codex_protocol::permissions::FileSystemPath::Special { - value: codex_protocol::permissions::FileSystemSpecialPath::CurrentWorkingDirectory, + value: codex_protocol::permissions::FileSystemSpecialPath::project_roots( + /*subpath*/ None, + ), }, access: codex_protocol::permissions::FileSystemAccessMode::Write, }, @@ -774,7 +780,9 @@ fn windows_elevated_rejects_unreadable_split_carveouts() { }, codex_protocol::permissions::FileSystemSandboxEntry { path: codex_protocol::permissions::FileSystemPath::Special { - value: codex_protocol::permissions::FileSystemSpecialPath::CurrentWorkingDirectory, + value: codex_protocol::permissions::FileSystemSpecialPath::project_roots( + /*subpath*/ None, + ), }, access: codex_protocol::permissions::FileSystemAccessMode::Write, }, @@ -821,7 +829,9 @@ fn windows_elevated_rejects_unreadable_globs() { }, codex_protocol::permissions::FileSystemSandboxEntry { path: codex_protocol::permissions::FileSystemPath::Special { - value: codex_protocol::permissions::FileSystemSpecialPath::CurrentWorkingDirectory, + value: codex_protocol::permissions::FileSystemSpecialPath::project_roots( + /*subpath*/ None, + ), }, access: codex_protocol::permissions::FileSystemAccessMode::Write, }, @@ -870,7 +880,9 @@ fn windows_elevated_rejects_reopened_writable_descendants() { }, codex_protocol::permissions::FileSystemSandboxEntry { path: codex_protocol::permissions::FileSystemPath::Special { - value: codex_protocol::permissions::FileSystemSpecialPath::CurrentWorkingDirectory, + value: codex_protocol::permissions::FileSystemSpecialPath::project_roots( + /*subpath*/ None, + ), }, access: codex_protocol::permissions::FileSystemAccessMode::Write, }, diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs index 2635d641d5..850d84dd2a 100644 --- a/codex-rs/core/src/guardian/review.rs +++ b/codex-rs/core/src/guardian/review.rs @@ -6,7 +6,6 @@ use codex_analytics::GuardianReviewDecision; use codex_analytics::GuardianReviewFailureReason; use codex_analytics::GuardianReviewTerminalStatus; use codex_analytics::GuardianReviewTrackContext; -use codex_features::Feature; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -161,13 +160,9 @@ pub(crate) fn is_guardian_reviewer_source( fn track_guardian_review( session: &Session, - turn: &TurnContext, tracking: &GuardianReviewTrackContext, result: GuardianReviewAnalyticsResult, ) { - if !turn.config.features.enabled(Feature::GeneralAnalytics) { - return; - } session .services .analytics_events_client @@ -279,7 +274,6 @@ async fn run_guardian_review( { track_guardian_review( session.as_ref(), - turn.as_ref(), &review_tracking, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Aborted, @@ -325,7 +319,6 @@ async fn run_guardian_review( let approved = matches!(assessment.outcome, GuardianAssessmentOutcome::Allow); track_guardian_review( session.as_ref(), - turn.as_ref(), &review_tracking, GuardianReviewAnalyticsResult { decision: if approved { @@ -356,7 +349,6 @@ async fn run_guardian_review( .to_string(); track_guardian_review( session.as_ref(), - turn.as_ref(), &review_tracking, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Denied, @@ -395,7 +387,6 @@ async fn run_guardian_review( GuardianReviewError::Cancelled => { track_guardian_review( session.as_ref(), - turn.as_ref(), &review_tracking, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Aborted, @@ -437,7 +428,6 @@ async fn run_guardian_review( let rationale = format!("Automatic approval review failed: {message}"); track_guardian_review( session.as_ref(), - turn.as_ref(), &review_tracking, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Denied, diff --git a/codex-rs/core/src/installation_id.rs b/codex-rs/core/src/installation_id.rs index e9e5445c8c..a42e6b6d83 100644 --- a/codex-rs/core/src/installation_id.rs +++ b/codex-rs/core/src/installation_id.rs @@ -16,7 +16,7 @@ use uuid::Uuid; pub(crate) const INSTALLATION_ID_FILENAME: &str = "installation_id"; -pub(crate) async fn resolve_installation_id(codex_home: &AbsolutePathBuf) -> Result { +pub async fn resolve_installation_id(codex_home: &AbsolutePathBuf) -> Result { let path = codex_home.join(INSTALLATION_ID_FILENAME); fs::create_dir_all(codex_home).await?; tokio::task::spawn_blocking(move || { diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index c6f879209d..05e34efc8c 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -56,8 +56,6 @@ mod original_image_detail; pub use codex_mcp::SandboxState; mod mcp_openai_file; mod mcp_tool_call; -mod memories; -pub use memories::clear_memory_roots_contents; pub(crate) mod mention_syntax; pub(crate) mod message_history; pub(crate) mod utils; @@ -119,7 +117,7 @@ pub(crate) mod web_search; pub(crate) mod windows_sandbox_read_grants; pub use thread_manager::ForkSnapshot; pub use thread_manager::NewThread; -pub use thread_manager::StartThreadWithToolsOptions; +pub use thread_manager::StartThreadOptions; pub use thread_manager::ThreadManager; pub use thread_manager::build_models_manager; pub use web_search::web_search_action_detail; @@ -195,9 +193,11 @@ pub use exec_policy::check_execpolicy_for_warnings; pub use exec_policy::format_exec_policy_error_with_source; pub use exec_policy::load_exec_policy; pub use file_watcher::FileWatcherEvent; +pub use installation_id::resolve_installation_id; pub use turn_metadata::build_turn_metadata_header; pub mod compact; pub(crate) mod memory_trace; pub use memory_trace::BuiltMemory; pub use memory_trace::build_memories_from_trace_files; +mod memory_usage; pub mod otel_init; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index b6646a338d..efa50b2b4e 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1194,13 +1194,23 @@ pub(crate) async fn lookup_mcp_tool_metadata( .and_then(|meta| meta.get(MCP_TOOL_CODEX_APPS_META_KEY)) .and_then(serde_json::Value::as_object) .cloned(), - openai_file_input_params: Some(declared_openai_file_input_param_names( + // Disallow custom MCPs from uploading files via fileParams. + openai_file_input_params: openai_file_input_params_for_server( + server, tool_info.tool.meta.as_deref(), - )) - .filter(|params| !params.is_empty()), + ), }) } +fn openai_file_input_params_for_server( + server: &str, + meta: Option<&serde_json::Map>, +) -> Option> { + (server == CODEX_APPS_MCP_SERVER_NAME) + .then_some(declared_openai_file_input_param_names(meta)) + .filter(|params| !params.is_empty()) +} + fn get_mcp_app_resource_uri( meta: Option<&serde_json::Map>, ) -> Option { diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 8b3f22770a..5ab2c6c4e8 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -183,6 +183,23 @@ fn mcp_app_resource_uri_reads_known_tool_meta_keys() { ); } +#[test] +fn openai_file_params_are_only_honored_for_codex_apps() { + let meta = serde_json::json!({ + "openai/fileParams": ["file"], + }); + let meta = meta.as_object(); + + assert_eq!( + openai_file_input_params_for_server(CODEX_APPS_MCP_SERVER_NAME, meta), + Some(vec!["file".to_string()]) + ); + assert_eq!( + openai_file_input_params_for_server("minimaltest", meta), + None + ); +} + #[test] fn approval_required_when_read_only_false_and_destructive() { let annotations = annotations(Some(false), Some(true), /*open_world*/ None); diff --git a/codex-rs/core/src/memories/control.rs b/codex-rs/core/src/memories/control.rs deleted file mode 100644 index 4f09d3e74c..0000000000 --- a/codex-rs/core/src/memories/control.rs +++ /dev/null @@ -1,44 +0,0 @@ -use std::path::Path; - -pub async fn clear_memory_roots_contents(codex_home: &Path) -> std::io::Result<()> { - for memory_root in [ - codex_home.join("memories"), - codex_home.join("memories_extensions"), - ] { - clear_memory_root_contents(memory_root.as_path()).await?; - } - - Ok(()) -} - -pub(crate) async fn clear_memory_root_contents(memory_root: &Path) -> std::io::Result<()> { - match tokio::fs::symlink_metadata(memory_root).await { - Ok(metadata) if metadata.file_type().is_symlink() => { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!( - "refusing to clear symlinked memory root {}", - memory_root.display() - ), - )); - } - Ok(_) => {} - Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} - Err(err) => return Err(err), - } - - tokio::fs::create_dir_all(memory_root).await?; - - let mut entries = tokio::fs::read_dir(memory_root).await?; - while let Some(entry) = entries.next_entry().await? { - let path = entry.path(); - let file_type = entry.file_type().await?; - if file_type.is_dir() { - tokio::fs::remove_dir_all(path).await?; - } else { - tokio::fs::remove_file(path).await?; - } - } - - Ok(()) -} diff --git a/codex-rs/core/src/memories/extensions.rs b/codex-rs/core/src/memories/extensions.rs deleted file mode 100644 index 458197609f..0000000000 --- a/codex-rs/core/src/memories/extensions.rs +++ /dev/null @@ -1,251 +0,0 @@ -use crate::memories::memory_extensions_root; -use chrono::DateTime; -use chrono::Duration; -use chrono::NaiveDateTime; -use chrono::Utc; -use std::path::Path; -use std::path::PathBuf; -use tracing::warn; - -const FILENAME_TS_FORMAT: &str = "%Y-%m-%dT%H-%M-%S"; -pub(super) const EXTENSION_RESOURCE_RETENTION_DAYS: i64 = 7; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(super) struct RemovedExtensionResource { - pub(super) extension: String, - pub(super) resource_path: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(super) struct PendingExtensionResourceRemoval { - pub(super) removed: RemovedExtensionResource, - path: PathBuf, -} - -pub(super) async fn find_old_extension_resources( - memory_root: &Path, -) -> Vec { - find_old_extension_resources_with_now(memory_root, Utc::now()).await -} - -async fn find_old_extension_resources_with_now( - memory_root: &Path, - now: DateTime, -) -> Vec { - let mut pending = Vec::new(); - let cutoff = now - Duration::days(EXTENSION_RESOURCE_RETENTION_DAYS); - let extensions_root = memory_extensions_root(memory_root); - let mut extensions = match tokio::fs::read_dir(&extensions_root).await { - Ok(extensions) => extensions, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return pending, - Err(err) => { - warn!( - "failed reading memory extensions root {}: {err}", - extensions_root.display() - ); - return pending; - } - }; - - while let Ok(Some(extension_entry)) = extensions.next_entry().await { - let extension_path = extension_entry.path(); - let Ok(file_type) = extension_entry.file_type().await else { - continue; - }; - if !file_type.is_dir() { - continue; - } - let Some(extension) = extension_path - .file_name() - .and_then(|name| name.to_str()) - .map(ToOwned::to_owned) - else { - continue; - }; - if !tokio::fs::try_exists(extension_path.join("instructions.md")) - .await - .unwrap_or(false) - { - continue; - } - - let resources_path = extension_path.join("resources"); - let mut resources = match tokio::fs::read_dir(&resources_path).await { - Ok(resources) => resources, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(err) => { - warn!( - "failed reading memory extension resources {}: {err}", - resources_path.display() - ); - continue; - } - }; - - while let Ok(Some(resource_entry)) = resources.next_entry().await { - let resource_file_path = resource_entry.path(); - let Ok(file_type) = resource_entry.file_type().await else { - continue; - }; - if !file_type.is_file() { - continue; - } - let Some(file_name) = resource_file_path - .file_name() - .and_then(|name| name.to_str()) - else { - continue; - }; - if !file_name.ends_with(".md") { - continue; - } - let Some(resource_timestamp) = resource_timestamp(file_name) else { - continue; - }; - if resource_timestamp > cutoff { - continue; - } - - pending.push(PendingExtensionResourceRemoval { - removed: RemovedExtensionResource { - extension: extension.clone(), - resource_path: format!("resources/{file_name}"), - }, - path: resource_file_path, - }); - } - } - - pending.sort_by(|left, right| { - left.removed - .extension - .cmp(&right.removed.extension) - .then_with(|| left.removed.resource_path.cmp(&right.removed.resource_path)) - }); - pending -} - -pub(super) async fn remove_extension_resources(resources: &[PendingExtensionResourceRemoval]) { - for resource in resources { - if let Err(err) = tokio::fs::remove_file(&resource.path).await - && err.kind() != std::io::ErrorKind::NotFound - { - warn!( - "failed pruning old memory extension resource {}: {err}", - resource.path.display() - ); - } - } -} - -fn resource_timestamp(file_name: &str) -> Option> { - let timestamp = file_name.get(..19)?; - let naive = NaiveDateTime::parse_from_str(timestamp, FILENAME_TS_FORMAT).ok()?; - Some(DateTime::from_naive_utc_and_offset(naive, Utc)) -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[tokio::test] - async fn finds_only_old_resources_from_extensions_with_instructions() { - let codex_home = TempDir::new().expect("create temp codex home"); - let memory_root = codex_home.path().join("memories"); - let extensions_root = memory_extensions_root(&memory_root); - let chronicle_resources = extensions_root.join("chronicle/resources"); - tokio::fs::create_dir_all(&chronicle_resources) - .await - .expect("create chronicle resources"); - tokio::fs::write( - extensions_root.join("chronicle/instructions.md"), - "instructions", - ) - .await - .expect("write chronicle instructions"); - - let now = DateTime::from_naive_utc_and_offset( - NaiveDateTime::parse_from_str("2026-04-14T12-00-00", FILENAME_TS_FORMAT) - .expect("parse now"), - Utc, - ); - let old_file = chronicle_resources.join("2026-04-06T11-59-59-abcd-10min-old.md"); - let exact_cutoff_file = - chronicle_resources.join("2026-04-07T12-00-00-abcd-10min-cutoff.md"); - let recent_file = chronicle_resources.join("2026-04-08T12-00-00-abcd-10min-recent.md"); - let invalid_file = chronicle_resources.join("not-a-timestamp.md"); - for file in [&old_file, &exact_cutoff_file, &recent_file, &invalid_file] { - tokio::fs::write(file, "resource") - .await - .expect("write chronicle resource"); - } - - let ignored_resources = extensions_root.join("ignored/resources"); - tokio::fs::create_dir_all(&ignored_resources) - .await - .expect("create ignored resources"); - let ignored_old_file = ignored_resources.join("2026-04-06T11-59-59-abcd-10min-old.md"); - tokio::fs::write(&ignored_old_file, "ignored") - .await - .expect("write ignored resource"); - - let pending = find_old_extension_resources_with_now(&memory_root, now).await; - - assert_eq!( - pending - .iter() - .map(|resource| resource.removed.clone()) - .collect::>(), - vec![ - RemovedExtensionResource { - extension: "chronicle".to_string(), - resource_path: "resources/2026-04-06T11-59-59-abcd-10min-old.md".to_string(), - }, - RemovedExtensionResource { - extension: "chronicle".to_string(), - resource_path: "resources/2026-04-07T12-00-00-abcd-10min-cutoff.md".to_string(), - }, - ] - ); - assert!( - tokio::fs::try_exists(&old_file) - .await - .expect("check old file before remove") - ); - assert!( - tokio::fs::try_exists(&exact_cutoff_file) - .await - .expect("check cutoff file before remove") - ); - - remove_extension_resources(&pending).await; - - assert!( - !tokio::fs::try_exists(&old_file) - .await - .expect("check old file") - ); - assert!( - !tokio::fs::try_exists(&exact_cutoff_file) - .await - .expect("check cutoff file") - ); - assert!( - tokio::fs::try_exists(&recent_file) - .await - .expect("check recent file") - ); - assert!( - tokio::fs::try_exists(&invalid_file) - .await - .expect("check invalid file") - ); - assert!( - tokio::fs::try_exists(&ignored_old_file) - .await - .expect("check ignored old file") - ); - } -} diff --git a/codex-rs/core/src/memories/mod.rs b/codex-rs/core/src/memories/mod.rs deleted file mode 100644 index d796063d2d..0000000000 --- a/codex-rs/core/src/memories/mod.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! Memory subsystem for startup extraction and consolidation. -//! -//! The startup memory pipeline is split into two phases: -//! - Phase 1: select rollouts, extract stage-1 raw memories, persist stage-1 outputs, and enqueue consolidation. -//! - Phase 2: claim a global consolidation lock, materialize consolidation inputs, and dispatch one consolidation agent. - -pub(crate) mod citations; -mod control; -mod phase1; -mod phase2; -pub(crate) mod prompts; -mod start; -mod storage; -#[cfg(test)] -mod tests; -pub(crate) mod usage; - -use codex_protocol::openai_models::ReasoningEffort; - -pub use control::clear_memory_roots_contents; -/// Starts the memory startup pipeline for eligible root sessions. -/// This is the single entrypoint that `codex` uses to trigger memory startup. -/// -/// This is the entry point to read and understand this module. -pub(crate) use start::start_memories_startup_task; - -mod artifacts { - pub(super) const EXTENSIONS_SUBDIR: &str = "memories_extensions"; - pub(super) const ROLLOUT_SUMMARIES_SUBDIR: &str = "rollout_summaries"; - pub(super) const RAW_MEMORIES_FILENAME: &str = "raw_memories.md"; -} - -mod extensions; - -/// Phase 1 (startup extraction). -mod phase_one { - /// Default model used for phase 1. - pub(super) const MODEL: &str = "gpt-5.4-mini"; - /// Default reasoning effort used for phase 1. - pub(super) const REASONING_EFFORT: super::ReasoningEffort = super::ReasoningEffort::Low; - /// Prompt used for phase 1. - pub(super) const PROMPT: &str = include_str!("../../templates/memories/stage_one_system.md"); - /// Concurrency cap for startup memory extraction and consolidation scheduling. - pub(super) const CONCURRENCY_LIMIT: usize = 8; - /// Fallback stage-1 rollout truncation limit (tokens) when model metadata - /// does not include a valid context window. - pub(super) const DEFAULT_STAGE_ONE_ROLLOUT_TOKEN_LIMIT: usize = 150_000; - /// Maximum number of tokens from `memory_summary.md` injected into memory - /// tool developer instructions. - pub(super) const MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT: usize = 5_000; - /// Portion of the model effective input window reserved for the stage-1 - /// rollout input. - /// - /// Keeping this below 100% leaves room for system instructions, prompt - /// framing, and model output. - pub(super) const CONTEXT_WINDOW_PERCENT: i64 = 70; - /// Lease duration (seconds) for phase-1 job ownership. - pub(super) const JOB_LEASE_SECONDS: i64 = 3_600; - /// Backoff delay (seconds) before retrying a failed stage-1 extraction job. - pub(super) const JOB_RETRY_DELAY_SECONDS: i64 = 3_600; - /// Maximum number of threads to scan. - pub(super) const THREAD_SCAN_LIMIT: usize = 5_000; - /// Size of the batches when pruning old thread memories. - pub(super) const PRUNE_BATCH_SIZE: usize = 200; -} - -/// Phase 2 (aka `Consolidation`). -mod phase_two { - /// Default model used for phase 2. - pub(super) const MODEL: &str = "gpt-5.4"; - /// Default reasoning effort used for phase 2. - pub(super) const REASONING_EFFORT: super::ReasoningEffort = super::ReasoningEffort::Medium; - /// Lease duration (seconds) for phase-2 consolidation job ownership. - pub(super) const JOB_LEASE_SECONDS: i64 = 3_600; - /// Backoff delay (seconds) before retrying a failed phase-2 consolidation - /// job. - pub(super) const JOB_RETRY_DELAY_SECONDS: i64 = 3_600; - /// Heartbeat interval (seconds) for phase-2 running jobs. - pub(super) const JOB_HEARTBEAT_SECONDS: u64 = 90; -} - -mod metrics { - /// Number of phase-1 startup jobs grouped by status. - pub(super) const MEMORY_PHASE_ONE_JOBS: &str = "codex.memory.phase1"; - /// End-to-end latency for a single phase-1 startup run. - pub(super) const MEMORY_PHASE_ONE_E2E_MS: &str = "codex.memory.phase1.e2e_ms"; - /// Number of raw memories produced by phase-1 startup extraction. - pub(super) const MEMORY_PHASE_ONE_OUTPUT: &str = "codex.memory.phase1.output"; - /// Histogram for aggregate token usage across one phase-1 startup run. - pub(super) const MEMORY_PHASE_ONE_TOKEN_USAGE: &str = "codex.memory.phase1.token_usage"; - /// Number of phase-2 startup jobs grouped by status. - pub(super) const MEMORY_PHASE_TWO_JOBS: &str = "codex.memory.phase2"; - /// End-to-end latency for a single phase-2 consolidation run. - pub(super) const MEMORY_PHASE_TWO_E2E_MS: &str = "codex.memory.phase2.e2e_ms"; - /// Number of stage-1 memories included in each phase-2 consolidation step. - pub(super) const MEMORY_PHASE_TWO_INPUT: &str = "codex.memory.phase2.input"; - /// Histogram for aggregate token usage across one phase-2 consolidation run. - pub(super) const MEMORY_PHASE_TWO_TOKEN_USAGE: &str = "codex.memory.phase2.token_usage"; -} - -use codex_utils_absolute_path::AbsolutePathBuf; -use std::path::Path; -use std::path::PathBuf; - -pub fn memory_root(codex_home: &AbsolutePathBuf) -> AbsolutePathBuf { - codex_home.join("memories") -} - -fn rollout_summaries_dir(root: &Path) -> PathBuf { - root.join(artifacts::ROLLOUT_SUMMARIES_SUBDIR) -} - -fn memory_extensions_root(root: &Path) -> PathBuf { - root.with_file_name(artifacts::EXTENSIONS_SUBDIR) -} - -fn raw_memories_file(root: &Path) -> PathBuf { - root.join(artifacts::RAW_MEMORIES_FILENAME) -} - -async fn ensure_layout(root: &Path) -> std::io::Result<()> { - tokio::fs::create_dir_all(rollout_summaries_dir(root)).await -} diff --git a/codex-rs/core/src/memories/phase1.rs b/codex-rs/core/src/memories/phase1.rs deleted file mode 100644 index 8fed735c49..0000000000 --- a/codex-rs/core/src/memories/phase1.rs +++ /dev/null @@ -1,620 +0,0 @@ -use crate::Prompt; -use crate::RolloutRecorder; -use crate::config::Config; -use crate::context::is_memory_excluded_contextual_user_fragment; -use crate::memories::metrics; -use crate::memories::phase_one; -use crate::memories::phase_one::PRUNE_BATCH_SIZE; -use crate::memories::prompts::build_stage_one_input_message; -use crate::rollout::INTERACTIVE_SESSION_SOURCES; -use crate::rollout::policy::should_persist_response_item_for_memories; -use crate::session::session::Session; -use crate::session::turn_context::TurnContext; -use codex_api::ResponseEvent; -use codex_config::types::MemoriesConfig; -use codex_otel::SessionTelemetry; -use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; -use codex_protocol::config_types::ServiceTier; -use codex_protocol::error::CodexErr; -use codex_protocol::models::BaseInstructions; -use codex_protocol::models::ContentItem; -use codex_protocol::models::ResponseItem; -use codex_protocol::openai_models::ModelInfo; -use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; -use codex_protocol::protocol::RolloutItem; -use codex_protocol::protocol::TokenUsage; -use codex_rollout_trace::InferenceTraceContext; -use codex_secrets::redact_secrets; -use futures::StreamExt; -use serde::Deserialize; -use serde_json::Value; -use serde_json::json; -use std::path::Path; -use std::sync::Arc; -use tracing::info; -use tracing::warn; - -#[derive(Clone, Debug)] -pub(in crate::memories) struct RequestContext { - pub(in crate::memories) model_info: ModelInfo, - pub(in crate::memories) session_telemetry: SessionTelemetry, - pub(in crate::memories) reasoning_effort: Option, - pub(in crate::memories) reasoning_summary: ReasoningSummaryConfig, - pub(in crate::memories) service_tier: Option, - pub(in crate::memories) turn_metadata_header: Option, -} - -struct JobResult { - outcome: JobOutcome, - token_usage: Option, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum JobOutcome { - SucceededWithOutput, - SucceededNoOutput, - Failed, -} - -struct Stats { - claimed: usize, - succeeded_with_output: usize, - succeeded_no_output: usize, - failed: usize, - total_token_usage: Option, -} - -/// Phase 1 model output payload. -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -struct StageOneOutput { - /// Detailed markdown raw memory for a single rollout. - #[serde(rename = "raw_memory")] - pub(crate) raw_memory: String, - /// Compact summary line used for routing and indexing. - #[serde(rename = "rollout_summary")] - pub(crate) rollout_summary: String, - /// Optional slug used to derive rollout summary artifact filenames. - #[serde(default, rename = "rollout_slug")] - pub(crate) rollout_slug: Option, -} - -/// Runs memory phase 1 in strict step order: -/// 1) claim eligible rollout jobs -/// 2) build one stage-1 request context -/// 3) run stage-1 extraction jobs in parallel -/// 4) emit metrics and logs -pub(in crate::memories) async fn run(session: &Arc, config: &Config) { - let _phase_one_e2e_timer = session - .services - .session_telemetry - .start_timer(metrics::MEMORY_PHASE_ONE_E2E_MS, &[]) - .ok(); - - // 1. Claim startup job. - let Some(claimed_candidates) = claim_startup_jobs(session, &config.memories).await else { - return; - }; - if claimed_candidates.is_empty() { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_JOBS, - /*inc*/ 1, - &[("status", "skipped_no_candidates")], - ); - return; - } - - // 2. Build request. - let stage_one_context = build_request_context(session, config).await; - - // 3. Run the parallel sampling. - let outcomes = run_jobs(session, claimed_candidates, stage_one_context).await; - - // 4. Metrics and logs. - let counts = aggregate_stats(outcomes); - emit_metrics(session, &counts); - info!( - "memory stage-1 extraction complete: {} job(s) claimed, {} succeeded ({} with output, {} no output), {} failed", - counts.claimed, - counts.succeeded_with_output + counts.succeeded_no_output, - counts.succeeded_with_output, - counts.succeeded_no_output, - counts.failed - ); -} - -/// Prune old un-used "dead" raw memories. -pub(in crate::memories) async fn prune(session: &Arc, config: &Config) { - if let Some(db) = session.services.state_db.as_deref() { - let max_unused_days = config.memories.max_unused_days; - match db - .prune_stage1_outputs_for_retention(max_unused_days, PRUNE_BATCH_SIZE) - .await - { - Ok(pruned) => { - if pruned > 0 { - info!( - "memory startup pruned {pruned} stale stage-1 output row(s) older than {max_unused_days} days" - ); - } - } - Err(err) => { - warn!( - "state db prune_stage1_outputs_for_retention failed during memories startup: {err}" - ); - } - } - } -} - -/// JSON schema used to constrain phase-1 model output. -pub fn output_schema() -> Value { - json!({ - "type": "object", - "properties": { - "rollout_summary": { "type": "string" }, - "rollout_slug": { "type": ["string", "null"] }, - "raw_memory": { "type": "string" } - }, - "required": ["rollout_summary", "rollout_slug", "raw_memory"], - "additionalProperties": false - }) -} - -impl RequestContext { - pub(in crate::memories) fn from_turn_context( - turn_context: &TurnContext, - turn_metadata_header: Option, - model_info: ModelInfo, - ) -> Self { - Self { - model_info, - turn_metadata_header, - session_telemetry: turn_context.session_telemetry.clone(), - reasoning_effort: Some(phase_one::REASONING_EFFORT), - reasoning_summary: turn_context.reasoning_summary, - service_tier: turn_context.config.service_tier, - } - } -} - -async fn claim_startup_jobs( - session: &Arc, - memories_config: &MemoriesConfig, -) -> Option> { - let Some(state_db) = session.services.state_db.as_deref() else { - // This should not happen. - warn!("state db unavailable while claiming phase-1 startup jobs; skipping"); - return None; - }; - - let allowed_sources = INTERACTIVE_SESSION_SOURCES - .iter() - .map(ToString::to_string) - .collect::>(); - - match state_db - .claim_stage1_jobs_for_startup( - session.conversation_id, - codex_state::Stage1StartupClaimParams { - scan_limit: phase_one::THREAD_SCAN_LIMIT, - max_claimed: memories_config.max_rollouts_per_startup, - max_age_days: memories_config.max_rollout_age_days, - min_rollout_idle_hours: memories_config.min_rollout_idle_hours, - allowed_sources: allowed_sources.as_slice(), - lease_seconds: phase_one::JOB_LEASE_SECONDS, - }, - ) - .await - { - Ok(claims) => Some(claims), - Err(err) => { - warn!("state db claim_stage1_jobs_for_startup failed during memories startup: {err}"); - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_JOBS, - /*inc*/ 1, - &[("status", "failed_claim")], - ); - None - } - } -} - -async fn build_request_context(session: &Arc, config: &Config) -> RequestContext { - let model_name = config - .memories - .extract_model - .clone() - .unwrap_or(phase_one::MODEL.to_string()); - let model = session - .services - .models_manager - .get_model_info(&model_name, &config.to_models_manager_config()) - .await; - let turn_context = session.new_default_turn().await; - RequestContext::from_turn_context( - turn_context.as_ref(), - turn_context.turn_metadata_state.current_header_value(), - model, - ) -} - -async fn run_jobs( - session: &Arc, - claimed_candidates: Vec, - stage_one_context: RequestContext, -) -> Vec { - futures::stream::iter(claimed_candidates.into_iter()) - .map(|claim| { - let session = Arc::clone(session); - let stage_one_context = stage_one_context.clone(); - async move { job::run(session.as_ref(), claim, &stage_one_context).await } - }) - .buffer_unordered(phase_one::CONCURRENCY_LIMIT) - .collect::>() - .await -} - -mod job { - use super::*; - - pub(in crate::memories) async fn run( - session: &Session, - claim: codex_state::Stage1JobClaim, - stage_one_context: &RequestContext, - ) -> JobResult { - let thread = claim.thread; - let (stage_one_output, token_usage) = match sample( - session, - &thread.rollout_path, - &thread.cwd, - stage_one_context, - ) - .await - { - Ok(output) => output, - Err(reason) => { - result::failed( - session, - thread.id, - &claim.ownership_token, - &reason.to_string(), - ) - .await; - return JobResult { - outcome: JobOutcome::Failed, - token_usage: None, - }; - } - }; - - if stage_one_output.raw_memory.is_empty() || stage_one_output.rollout_summary.is_empty() { - return JobResult { - outcome: result::no_output(session, thread.id, &claim.ownership_token).await, - token_usage, - }; - } - - JobResult { - outcome: result::success( - session, - thread.id, - &claim.ownership_token, - thread.updated_at.timestamp(), - &stage_one_output.raw_memory, - &stage_one_output.rollout_summary, - stage_one_output.rollout_slug.as_deref(), - ) - .await, - token_usage, - } - } - - /// Extract the rollout and perform the actual sampling. - async fn sample( - session: &Session, - rollout_path: &Path, - rollout_cwd: &Path, - stage_one_context: &RequestContext, - ) -> anyhow::Result<(StageOneOutput, Option)> { - let (rollout_items, _, _) = RolloutRecorder::load_rollout_items(rollout_path).await?; - let rollout_contents = serialize_filtered_rollout_response_items(&rollout_items)?; - - let prompt = Prompt { - input: vec![ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: build_stage_one_input_message( - &stage_one_context.model_info, - rollout_path, - rollout_cwd, - &rollout_contents, - )?, - }], - phase: None, - }], - tools: Vec::new(), - parallel_tool_calls: false, - base_instructions: BaseInstructions { - text: phase_one::PROMPT.to_string(), - }, - personality: None, - output_schema: Some(output_schema()), - output_schema_strict: true, - }; - - let mut client_session = session.services.model_client.new_session(); - let mut stream = client_session - .stream( - &prompt, - &stage_one_context.model_info, - &stage_one_context.session_telemetry, - stage_one_context.reasoning_effort, - stage_one_context.reasoning_summary, - stage_one_context.service_tier, - stage_one_context.turn_metadata_header.as_deref(), - &InferenceTraceContext::disabled(), - ) - .await?; - - // TODO(jif) we should have a shared helper somewhere for this. - // Unwrap the stream. - let mut result = String::new(); - let mut token_usage = None; - while let Some(message) = stream.next().await.transpose()? { - match message { - ResponseEvent::OutputTextDelta(delta) => result.push_str(&delta), - ResponseEvent::OutputItemDone(item) => { - if result.is_empty() - && let ResponseItem::Message { content, .. } = item - && let Some(text) = crate::compact::content_items_to_text(&content) - { - result.push_str(&text); - } - } - ResponseEvent::Completed { - token_usage: usage, .. - } => { - token_usage = usage; - break; - } - _ => {} - } - } - - let mut output: StageOneOutput = serde_json::from_str(&result)?; - output.raw_memory = redact_secrets(output.raw_memory); - output.rollout_summary = redact_secrets(output.rollout_summary); - output.rollout_slug = output.rollout_slug.map(redact_secrets); - - Ok((output, token_usage)) - } - - mod result { - use super::*; - - pub(in crate::memories) async fn failed( - session: &Session, - thread_id: codex_protocol::ThreadId, - ownership_token: &str, - reason: &str, - ) { - tracing::warn!("Phase 1 job failed for thread {thread_id}: {reason}"); - if let Some(state_db) = session.services.state_db.as_deref() { - let _ = state_db - .mark_stage1_job_failed( - thread_id, - ownership_token, - reason, - phase_one::JOB_RETRY_DELAY_SECONDS, - ) - .await; - } - } - - pub(in crate::memories) async fn no_output( - session: &Session, - thread_id: codex_protocol::ThreadId, - ownership_token: &str, - ) -> JobOutcome { - let Some(state_db) = session.services.state_db.as_deref() else { - return JobOutcome::Failed; - }; - - if state_db - .mark_stage1_job_succeeded_no_output(thread_id, ownership_token) - .await - .unwrap_or(false) - { - JobOutcome::SucceededNoOutput - } else { - JobOutcome::Failed - } - } - - pub(in crate::memories) async fn success( - session: &Session, - thread_id: codex_protocol::ThreadId, - ownership_token: &str, - source_updated_at: i64, - raw_memory: &str, - rollout_summary: &str, - rollout_slug: Option<&str>, - ) -> JobOutcome { - let Some(state_db) = session.services.state_db.as_deref() else { - return JobOutcome::Failed; - }; - - if state_db - .mark_stage1_job_succeeded( - thread_id, - ownership_token, - source_updated_at, - raw_memory, - rollout_summary, - rollout_slug, - ) - .await - .unwrap_or(false) - { - JobOutcome::SucceededWithOutput - } else { - JobOutcome::Failed - } - } - } - - /// Serializes filtered stage-1 memory items for prompt inclusion. - pub(super) fn serialize_filtered_rollout_response_items( - items: &[RolloutItem], - ) -> codex_protocol::error::Result { - let filtered = items - .iter() - .filter_map(|item| { - if let RolloutItem::ResponseItem(item) = item { - sanitize_response_item_for_memories(item) - } else { - None - } - }) - .collect::>(); - let serialized = serde_json::to_string(&filtered).map_err(|err| { - CodexErr::InvalidRequest(format!("failed to serialize rollout memory: {err}")) - })?; - Ok(redact_secrets(serialized)) - } - - fn sanitize_response_item_for_memories(item: &ResponseItem) -> Option { - let ResponseItem::Message { - id, - role, - content, - phase, - } = item - else { - return should_persist_response_item_for_memories(item).then(|| item.clone()); - }; - - if role == "developer" { - return None; - } - - if role != "user" { - return Some(item.clone()); - } - - let content = content - .iter() - .filter(|content_item| !is_memory_excluded_contextual_user_fragment(content_item)) - .cloned() - .collect::>(); - if content.is_empty() { - return None; - } - - Some(ResponseItem::Message { - id: id.clone(), - role: role.clone(), - content, - phase: phase.clone(), - }) - } -} - -fn aggregate_stats(outcomes: Vec) -> Stats { - let claimed = outcomes.len(); - let mut succeeded_with_output = 0; - let mut succeeded_no_output = 0; - let mut failed = 0; - let mut total_token_usage = TokenUsage::default(); - let mut has_token_usage = false; - - for outcome in outcomes { - match outcome.outcome { - JobOutcome::SucceededWithOutput => succeeded_with_output += 1, - JobOutcome::SucceededNoOutput => succeeded_no_output += 1, - JobOutcome::Failed => failed += 1, - } - - if let Some(token_usage) = outcome.token_usage { - total_token_usage.add_assign(&token_usage); - has_token_usage = true; - } - } - - Stats { - claimed, - succeeded_with_output, - succeeded_no_output, - failed, - total_token_usage: has_token_usage.then_some(total_token_usage), - } -} - -fn emit_metrics(session: &Session, counts: &Stats) { - if counts.claimed > 0 { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_JOBS, - counts.claimed as i64, - &[("status", "claimed")], - ); - } - if counts.succeeded_with_output > 0 { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_JOBS, - counts.succeeded_with_output as i64, - &[("status", "succeeded")], - ); - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_OUTPUT, - counts.succeeded_with_output as i64, - &[], - ); - } - if counts.succeeded_no_output > 0 { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_JOBS, - counts.succeeded_no_output as i64, - &[("status", "succeeded_no_output")], - ); - } - if counts.failed > 0 { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_ONE_JOBS, - counts.failed as i64, - &[("status", "failed")], - ); - } - if let Some(token_usage) = counts.total_token_usage.as_ref() { - session.services.session_telemetry.histogram( - metrics::MEMORY_PHASE_ONE_TOKEN_USAGE, - token_usage.total_tokens.max(0), - &[("token_type", "total")], - ); - session.services.session_telemetry.histogram( - metrics::MEMORY_PHASE_ONE_TOKEN_USAGE, - token_usage.input_tokens.max(0), - &[("token_type", "input")], - ); - session.services.session_telemetry.histogram( - metrics::MEMORY_PHASE_ONE_TOKEN_USAGE, - token_usage.cached_input(), - &[("token_type", "cached_input")], - ); - session.services.session_telemetry.histogram( - metrics::MEMORY_PHASE_ONE_TOKEN_USAGE, - token_usage.output_tokens.max(0), - &[("token_type", "output")], - ); - session.services.session_telemetry.histogram( - metrics::MEMORY_PHASE_ONE_TOKEN_USAGE, - token_usage.reasoning_output_tokens.max(0), - &[("token_type", "reasoning_output")], - ); - } -} - -#[cfg(test)] -#[path = "phase1_tests.rs"] -mod tests; diff --git a/codex-rs/core/src/memories/phase1_tests.rs b/codex-rs/core/src/memories/phase1_tests.rs deleted file mode 100644 index 18a46d1740..0000000000 --- a/codex-rs/core/src/memories/phase1_tests.rs +++ /dev/null @@ -1,152 +0,0 @@ -use super::JobOutcome; -use super::JobResult; -use super::aggregate_stats; -use super::job::serialize_filtered_rollout_response_items; -use codex_protocol::models::ContentItem; -use codex_protocol::models::FunctionCallOutputBody; -use codex_protocol::models::FunctionCallOutputPayload; -use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::RolloutItem; -use codex_protocol::protocol::TokenUsage; -use pretty_assertions::assert_eq; - -#[test] -fn serializes_memory_rollout_with_agents_removed_but_environment_kept() { - let mixed_contextual_message = ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ - ContentItem::InputText { - text: "# AGENTS.md instructions for /tmp\n\n\nbody\n" - .to_string(), - }, - ContentItem::InputText { - text: "\n/tmp\n".to_string(), - }, - ], - phase: None, - }; - let skill_message = ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "\ndemo\nskills/demo/SKILL.md\nbody\n" - .to_string(), - }], - phase: None, - }; - let subagent_message = ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "{\"agent_id\":\"a\",\"status\":\"completed\"}" - .to_string(), - }], - phase: None, - }; - - let serialized = serialize_filtered_rollout_response_items(&[ - RolloutItem::ResponseItem(mixed_contextual_message), - RolloutItem::ResponseItem(skill_message), - RolloutItem::ResponseItem(subagent_message.clone()), - ]) - .expect("serialize"); - let parsed: Vec = serde_json::from_str(&serialized).expect("parse"); - - assert_eq!( - parsed, - vec![ - ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { - text: "\n/tmp\n" - .to_string(), - }], - phase: None, - }, - subagent_message, - ] - ); -} - -#[test] -fn serializes_memory_rollout_redacts_secrets_before_prompt_upload() { - let serialized = serialize_filtered_rollout_response_items(&[RolloutItem::ResponseItem( - ResponseItem::FunctionCallOutput { - call_id: "call_123".to_string(), - output: FunctionCallOutputPayload { - body: FunctionCallOutputBody::Text( - r#"{"token":"sk-abcdefghijklmnopqrstuvwxyz123456"}"#.to_string(), - ), - success: Some(true), - }, - }, - )]) - .expect("serialize"); - - assert!(!serialized.contains("sk-abcdefghijklmnopqrstuvwxyz123456")); - assert!(serialized.contains("[REDACTED_SECRET]")); -} - -#[test] -fn count_outcomes_sums_token_usage_across_all_jobs() { - let counts = aggregate_stats(vec![ - JobResult { - outcome: JobOutcome::SucceededWithOutput, - token_usage: Some(TokenUsage { - input_tokens: 10, - cached_input_tokens: 2, - output_tokens: 3, - reasoning_output_tokens: 1, - total_tokens: 13, - }), - }, - JobResult { - outcome: JobOutcome::SucceededNoOutput, - token_usage: Some(TokenUsage { - input_tokens: 7, - cached_input_tokens: 1, - output_tokens: 2, - reasoning_output_tokens: 0, - total_tokens: 9, - }), - }, - JobResult { - outcome: JobOutcome::Failed, - token_usage: None, - }, - ]); - - assert_eq!(counts.claimed, 3); - assert_eq!(counts.succeeded_with_output, 1); - assert_eq!(counts.succeeded_no_output, 1); - assert_eq!(counts.failed, 1); - assert_eq!( - counts.total_token_usage, - Some(TokenUsage { - input_tokens: 17, - cached_input_tokens: 3, - output_tokens: 5, - reasoning_output_tokens: 1, - total_tokens: 22, - }) - ); -} - -#[test] -fn count_outcomes_keeps_usage_empty_when_no_job_reports_it() { - let counts = aggregate_stats(vec![ - JobResult { - outcome: JobOutcome::SucceededWithOutput, - token_usage: None, - }, - JobResult { - outcome: JobOutcome::Failed, - token_usage: None, - }, - ]); - - assert_eq!(counts.claimed, 2); - assert_eq!(counts.total_token_usage, None); -} diff --git a/codex-rs/core/src/memories/phase2.rs b/codex-rs/core/src/memories/phase2.rs deleted file mode 100644 index 248e61dbab..0000000000 --- a/codex-rs/core/src/memories/phase2.rs +++ /dev/null @@ -1,537 +0,0 @@ -use crate::agent::AgentStatus; -use crate::agent::status::is_final as is_final_agent_status; -use crate::config::Config; -use crate::memories::extensions::PendingExtensionResourceRemoval; -use crate::memories::extensions::find_old_extension_resources; -use crate::memories::extensions::remove_extension_resources; -use crate::memories::memory_root; -use crate::memories::metrics; -use crate::memories::phase_two; -use crate::memories::prompts::build_consolidation_prompt; -use crate::memories::storage::rebuild_raw_memories_file_from_memories; -use crate::memories::storage::rollout_summary_file_stem; -use crate::memories::storage::sync_rollout_summaries_from_memories; -use crate::session::emit_subagent_session_started; -use crate::session::session::Session; -use codex_config::Constrained; -use codex_features::Feature; -use codex_protocol::ThreadId; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::protocol::TokenUsage; -use codex_protocol::user_input::UserInput; -use codex_state::Stage1Output; -use codex_state::StateRuntime; -use std::collections::HashMap; -use std::collections::HashSet; -use std::sync::Arc; -use std::time::Duration; -use tokio::sync::watch; -use tracing::warn; - -#[derive(Debug, Clone, Default)] -struct Claim { - token: String, - watermark: i64, -} - -#[derive(Debug, Clone, Default)] -struct Counters { - input: i64, -} - -/// Runs memory phase 2 (aka consolidation) in strict order. The method represents the linear -/// flow of the consolidation phase. -pub(super) async fn run(session: &Arc, config: Arc) { - let phase_two_e2e_timer = session - .services - .session_telemetry - .start_timer(metrics::MEMORY_PHASE_TWO_E2E_MS, &[]) - .ok(); - - let Some(db) = session.services.state_db.as_deref() else { - // This should not happen. - return; - }; - let root = memory_root(&config.codex_home); - let max_raw_memories = config.memories.max_raw_memories_for_consolidation; - let max_unused_days = config.memories.max_unused_days; - - // 1. Claim the job. - let claim = match job::claim(session, db).await { - Ok(claim) => claim, - Err(e) => { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_TWO_JOBS, - /*inc*/ 1, - &[("status", e)], - ); - return; - } - }; - - // 2. Get the config for the agent - let Some(agent_config) = agent::get_config(config.clone()) else { - // If we can't get the config, we can't consolidate. - tracing::error!("failed to get agent config"); - job::failed(session, db, &claim, "failed_sandbox_policy").await; - return; - }; - - // 3. Query the memories - let selection = match db - .get_phase2_input_selection(max_raw_memories, max_unused_days) - .await - { - Ok(selection) => selection, - Err(err) => { - tracing::error!("failed to list stage1 outputs from global: {}", err); - job::failed(session, db, &claim, "failed_load_stage1_outputs").await; - return; - } - }; - let raw_memories = selection.selected.to_vec(); - let artifact_memories = artifact_memories_for_phase2(&selection); - let new_watermark = get_watermark(claim.watermark, &raw_memories); - - // 4. Update the file system by syncing the raw memories with the one extracted from DB at - // step 3 - // [`rollout_summaries/`] - if let Err(err) = - sync_rollout_summaries_from_memories(&root, &artifact_memories, artifact_memories.len()) - .await - { - tracing::error!("failed syncing local memory artifacts for global consolidation: {err}"); - job::failed(session, db, &claim, "failed_sync_artifacts").await; - return; - } - // [`raw_memories.md`] - if let Err(err) = - rebuild_raw_memories_file_from_memories(&root, &artifact_memories, artifact_memories.len()) - .await - { - tracing::error!("failed syncing local memory artifacts for global consolidation: {err}"); - job::failed(session, db, &claim, "failed_rebuild_raw_memories").await; - return; - } - let pending_extension_resource_removals = find_old_extension_resources(&root).await; - let removed_extension_resources = pending_extension_resource_removals - .iter() - .map(|resource| resource.removed.clone()) - .collect::>(); - if raw_memories.is_empty() && pending_extension_resource_removals.is_empty() { - // We check only after sync of the file system. - job::succeed( - session, - db, - &claim, - new_watermark, - &[], - "succeeded_no_input", - ) - .await; - return; - } - - // 5. Spawn the agent - let prompt = agent::get_prompt(config, &selection, &removed_extension_resources); - let source = SessionSource::SubAgent(SubAgentSource::MemoryConsolidation); - let agent_control = session.services.agent_control.detached_registry(); - let thread_id = match agent_control - .spawn_agent(agent_config, prompt.into(), Some(source)) - .await - { - Ok(thread_id) => thread_id, - Err(err) => { - tracing::error!("failed to spawn global memory consolidation agent: {err}"); - job::failed(session, db, &claim, "failed_spawn_agent").await; - return; - } - }; - - if let Some(thread_config) = session - .services - .agent_control - .get_agent_config_snapshot(thread_id) - .await - { - if session.enabled(Feature::GeneralAnalytics) { - let client_metadata = session.app_server_client_metadata().await; - emit_subagent_session_started( - &session.services.analytics_events_client, - client_metadata, - thread_id, - /*parent_thread_id*/ None, - thread_config, - SubAgentSource::MemoryConsolidation, - ); - } - } else { - warn!("failed to load memory consolidation thread config for analytics: {thread_id}"); - } - - // 6. Spawn the agent handler. - agent::handle( - session, - claim, - new_watermark, - raw_memories.clone(), - pending_extension_resource_removals, - thread_id, - agent_control, - phase_two_e2e_timer, - ); - - // 7. Metrics and logs. - let counters = Counters { - input: raw_memories.len() as i64, - }; - emit_metrics(session, counters); -} - -fn artifact_memories_for_phase2( - selection: &codex_state::Phase2InputSelection, -) -> Vec { - let mut seen = HashSet::new(); - let mut memories = selection.selected.clone(); - for memory in &selection.selected { - seen.insert(rollout_summary_file_stem(memory)); - } - for memory in &selection.previous_selected { - if seen.insert(rollout_summary_file_stem(memory)) { - memories.push(memory.clone()); - } - } - memories -} - -mod job { - use super::*; - - pub(super) async fn claim( - session: &Arc, - db: &StateRuntime, - ) -> Result { - let session_telemetry = &session.services.session_telemetry; - let claim = db - .try_claim_global_phase2_job(session.conversation_id, phase_two::JOB_LEASE_SECONDS) - .await - .map_err(|e| { - tracing::error!("failed to claim job: {}", e); - "failed_claim" - })?; - let (token, watermark) = match claim { - codex_state::Phase2JobClaimOutcome::Claimed { - ownership_token, - input_watermark, - } => { - session_telemetry.counter( - metrics::MEMORY_PHASE_TWO_JOBS, - /*inc*/ 1, - &[("status", "claimed")], - ); - (ownership_token, input_watermark) - } - codex_state::Phase2JobClaimOutcome::SkippedNotDirty => return Err("skipped_not_dirty"), - codex_state::Phase2JobClaimOutcome::SkippedRunning => return Err("skipped_running"), - }; - - Ok(Claim { token, watermark }) - } - - pub(super) async fn failed( - session: &Arc, - db: &StateRuntime, - claim: &Claim, - reason: &'static str, - ) { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_TWO_JOBS, - /*inc*/ 1, - &[("status", reason)], - ); - if matches!( - db.mark_global_phase2_job_failed( - &claim.token, - reason, - phase_two::JOB_RETRY_DELAY_SECONDS, - ) - .await, - Ok(false) - ) { - let _ = db - .mark_global_phase2_job_failed_if_unowned( - &claim.token, - reason, - phase_two::JOB_RETRY_DELAY_SECONDS, - ) - .await; - } - } - - pub(super) async fn succeed( - session: &Arc, - db: &StateRuntime, - claim: &Claim, - completion_watermark: i64, - selected_outputs: &[codex_state::Stage1Output], - reason: &'static str, - ) -> bool { - session.services.session_telemetry.counter( - metrics::MEMORY_PHASE_TWO_JOBS, - /*inc*/ 1, - &[("status", reason)], - ); - db.mark_global_phase2_job_succeeded(&claim.token, completion_watermark, selected_outputs) - .await - .unwrap_or(false) - } -} - -mod agent { - use super::*; - - pub(super) fn get_config(config: Arc) -> Option { - let root = memory_root(&config.codex_home); - let mut agent_config = config.as_ref().clone(); - - agent_config.cwd = root.clone(); - // Consolidation threads must never feed back into phase-1 memory generation. - agent_config.ephemeral = true; - agent_config.memories.generate_memories = false; - agent_config.memories.use_memories = false; - agent_config.include_apps_instructions = false; - agent_config.mcp_servers = Constrained::allow_only(HashMap::new()); - // Approval policy - agent_config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never); - // Consolidation runs as an internal sub-agent and must not recursively delegate. - let _ = agent_config.features.disable(Feature::SpawnCsv); - let _ = agent_config.features.disable(Feature::Collab); - let _ = agent_config.features.disable(Feature::MemoryTool); - let _ = agent_config.features.disable(Feature::Apps); - let _ = agent_config.features.disable(Feature::Plugins); - let _ = agent_config - .features - .disable(Feature::SkillMcpDependencyInstall); - - // Sandbox policy - let writable_roots = vec![root]; - // The consolidation agent only needs local memory-root write access and no network. - let consolidation_sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots, - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; - agent_config - .permissions - .set_legacy_sandbox_policy(consolidation_sandbox_policy, agent_config.cwd.as_path()) - .ok()?; - - agent_config.model = Some( - config - .memories - .consolidation_model - .clone() - .unwrap_or(phase_two::MODEL.to_string()), - ); - agent_config.model_reasoning_effort = Some(phase_two::REASONING_EFFORT); - - Some(agent_config) - } - - pub(super) fn get_prompt( - config: Arc, - selection: &codex_state::Phase2InputSelection, - removed_extension_resources: &[crate::memories::extensions::RemovedExtensionResource], - ) -> Vec { - let root = memory_root(&config.codex_home); - let prompt = build_consolidation_prompt(&root, selection, removed_extension_resources); - vec![UserInput::Text { - text: prompt, - text_elements: vec![], - }] - } - - /// Handle the agent while it is running. - #[allow(clippy::too_many_arguments)] - pub(super) fn handle( - session: &Arc, - claim: Claim, - new_watermark: i64, - selected_outputs: Vec, - pending_extension_resource_removals: Vec, - thread_id: ThreadId, - agent_control: crate::agent::AgentControl, - phase_two_e2e_timer: Option, - ) { - let Some(db) = session.services.state_db.clone() else { - return; - }; - let session = session.clone(); - - tokio::spawn(async move { - let _phase_two_e2e_timer = phase_two_e2e_timer; - - // TODO(jif) we might have a very small race here. - let rx = match agent_control.subscribe_status(thread_id).await { - Ok(rx) => rx, - Err(err) => { - tracing::error!("agent_control.subscribe_status failed: {err:?}"); - job::failed(&session, &db, &claim, "failed_subscribe_status").await; - return; - } - }; - - // Loop the agent until we have the final status. - let final_status = loop_agent( - db.clone(), - claim.token.clone(), - new_watermark, - thread_id, - rx, - ) - .await; - - if matches!(final_status, AgentStatus::Completed(_)) { - if let Some(token_usage) = agent_control.get_total_token_usage(thread_id).await { - emit_token_usage_metrics(&session, &token_usage); - } - if job::succeed( - &session, - &db, - &claim, - new_watermark, - &selected_outputs, - "succeeded", - ) - .await - { - remove_extension_resources(&pending_extension_resource_removals).await; - } - } else { - job::failed(&session, &db, &claim, "failed_agent").await; - } - - // Fire and forget close of the agent. - if !matches!(final_status, AgentStatus::Shutdown | AgentStatus::NotFound) { - tokio::spawn(async move { - if let Err(err) = agent_control.shutdown_live_agent(thread_id).await { - warn!( - "failed to auto-close global memory consolidation agent {thread_id}: {err}" - ); - } - }); - } else { - tracing::warn!("The agent was already gone"); - } - }); - } - - async fn loop_agent( - db: Arc, - token: String, - _new_watermark: i64, - thread_id: ThreadId, - mut rx: watch::Receiver, - ) -> AgentStatus { - let mut heartbeat_interval = - tokio::time::interval(Duration::from_secs(phase_two::JOB_HEARTBEAT_SECONDS)); - heartbeat_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - - loop { - let status = rx.borrow().clone(); - if is_final_agent_status(&status) { - break status; - } - - tokio::select! { - update = rx.changed() => { - if update.is_err() { - tracing::warn!( - "lost status updates for global memory consolidation agent {thread_id}" - ); - break status; - } - } - _ = heartbeat_interval.tick() => { - match db - .heartbeat_global_phase2_job( - &token, - phase_two::JOB_LEASE_SECONDS, - ) - .await - { - Ok(true) => {} - Ok(false) => { - break AgentStatus::Errored( - "lost global phase-2 ownership during heartbeat".to_string(), - ); - } - Err(err) => { - break AgentStatus::Errored(format!( - "phase-2 heartbeat update failed: {err}" - )); - } - } - } - } - } - } -} - -pub(super) fn get_watermark( - claimed_watermark: i64, - latest_memories: &[codex_state::Stage1Output], -) -> i64 { - latest_memories - .iter() - .map(|memory| memory.source_updated_at.timestamp()) - .max() - .unwrap_or(claimed_watermark) - .max(claimed_watermark) // todo double check the claimed here. -} - -fn emit_metrics(session: &Arc, counters: Counters) { - let otel = session.services.session_telemetry.clone(); - if counters.input > 0 { - otel.counter(metrics::MEMORY_PHASE_TWO_INPUT, counters.input, &[]); - } - - otel.counter( - metrics::MEMORY_PHASE_TWO_JOBS, - /*inc*/ 1, - &[("status", "agent_spawned")], - ); -} - -fn emit_token_usage_metrics(session: &Arc, token_usage: &TokenUsage) { - let otel = session.services.session_telemetry.clone(); - otel.histogram( - metrics::MEMORY_PHASE_TWO_TOKEN_USAGE, - token_usage.total_tokens.max(0), - &[("token_type", "total")], - ); - otel.histogram( - metrics::MEMORY_PHASE_TWO_TOKEN_USAGE, - token_usage.input_tokens.max(0), - &[("token_type", "input")], - ); - otel.histogram( - metrics::MEMORY_PHASE_TWO_TOKEN_USAGE, - token_usage.cached_input(), - &[("token_type", "cached_input")], - ); - otel.histogram( - metrics::MEMORY_PHASE_TWO_TOKEN_USAGE, - token_usage.output_tokens.max(0), - &[("token_type", "output")], - ); - otel.histogram( - metrics::MEMORY_PHASE_TWO_TOKEN_USAGE, - token_usage.reasoning_output_tokens.max(0), - &[("token_type", "reasoning_output")], - ); -} diff --git a/codex-rs/core/src/memories/prompts.rs b/codex-rs/core/src/memories/prompts.rs deleted file mode 100644 index 9425a53804..0000000000 --- a/codex-rs/core/src/memories/prompts.rs +++ /dev/null @@ -1,293 +0,0 @@ -use crate::memories::extensions::EXTENSION_RESOURCE_RETENTION_DAYS; -use crate::memories::extensions::RemovedExtensionResource; -use crate::memories::memory_extensions_root; -use crate::memories::memory_root; -use crate::memories::phase_one; -use crate::memories::storage::rollout_summary_file_stem_from_parts; -use codex_protocol::openai_models::ModelInfo; -use codex_state::Phase2InputSelection; -use codex_state::Stage1Output; -use codex_state::Stage1OutputRef; -use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_output_truncation::TruncationPolicy; -use codex_utils_output_truncation::truncate_text; -use codex_utils_template::Template; -use std::fmt::Write as _; -use std::path::Path; -use std::sync::LazyLock; -use tokio::fs; -use tracing::warn; - -static CONSOLIDATION_PROMPT_TEMPLATE: LazyLock