Merge branch 'main' into dev/stevenlee/plugin-service-preview-routing

This commit is contained in:
stevenlee-oai
2026-06-23 12:35:28 -04:00
committed by GitHub
49 changed files with 1344 additions and 213 deletions
+2 -2
View File
@@ -1449,8 +1449,8 @@
"resolv-conf_0.7.6": "{\"dependencies\":[],\"features\":{\"system\":[]}}",
"rfc6979_0.4.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.3\"},{\"default_features\":false,\"features\":[\"reset\"],\"name\":\"hmac\",\"req\":\"^0.12\"},{\"kind\":\"dev\",\"name\":\"sha2\",\"req\":\"^0.10\"},{\"default_features\":false,\"name\":\"subtle\",\"req\":\"^2\"}],\"features\":{}}",
"ring_0.17.14": "{\"dependencies\":[{\"default_features\":false,\"kind\":\"build\",\"name\":\"cc\",\"req\":\"^1.2.8\"},{\"default_features\":false,\"name\":\"cfg-if\",\"req\":\"^1.0.0\"},{\"name\":\"getrandom\",\"req\":\"^0.2.10\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(all(any(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), all(target_arch = \\\"arm\\\", target_endian = \\\"little\\\")), any(target_os = \\\"android\\\", target_os = \\\"linux\\\")))\"},{\"default_features\":false,\"name\":\"libc\",\"req\":\"^0.2.155\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_vendor = \\\"apple\\\", any(target_os = \\\"ios\\\", target_os = \\\"macos\\\", target_os = \\\"tvos\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\")))\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"libc\",\"req\":\"^0.2.148\",\"target\":\"cfg(any(unix, windows, target_os = \\\"wasi\\\"))\"},{\"name\":\"untrusted\",\"req\":\"^0.9\"},{\"default_features\":false,\"features\":[\"std\"],\"kind\":\"dev\",\"name\":\"wasm-bindgen-test\",\"req\":\"^0.3.37\",\"target\":\"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"unknown\\\"))\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Threading\"],\"name\":\"windows-sys\",\"req\":\"^0.52\",\"target\":\"cfg(all(all(target_arch = \\\"aarch64\\\", target_endian = \\\"little\\\"), target_os = \\\"windows\\\"))\"}],\"features\":{\"alloc\":[],\"default\":[\"alloc\",\"dev_urandom_fallback\"],\"dev_urandom_fallback\":[],\"less-safe-getrandom-custom-or-rdrand\":[],\"less-safe-getrandom-espidf\":[],\"slow_tests\":[],\"std\":[\"alloc\"],\"test_logging\":[],\"unstable-testing-arm-no-hw\":[],\"unstable-testing-arm-no-neon\":[],\"wasm32_unknown_unknown_js\":[\"getrandom/js\"]}}",
"rmcp-macros_1.7.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"local\":[]}}",
"rmcp_1.7.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"http1\",\"tokio\"],\"kind\":\"dev\",\"name\":\"axum\",\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"default_features\":false,\"features\":[\"serde\",\"now\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"client\",\"http1\"],\"name\":\"hyper\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"server\",\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"jsonwebtoken\",\"optional\":true,\"req\":\"^10\"},{\"default_features\":false,\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.13.2\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^1.7.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"which\",\"optional\":true,\"req\":\"^8\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"auth-client-credentials-jwt\":[\"auth\",\"dep:jsonwebtoken\",\"uuid\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[\"dep:url\"],\"local\":[\"rmcp-macros?/local\"],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls\"],\"reqwest-native-tls\":[\"__reqwest\",\"reqwest?/native-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\",\"dep:pastey\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"__reqwest\"],\"transport-streamable-http-client-unix-socket\":[\"transport-streamable-http-client\",\"dep:hyper\",\"dep:hyper-util\",\"dep:http-body-util\",\"dep:http\",\"dep:bytes\",\"tokio/net\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"],\"which-command\":[\"transport-child-process\",\"dep:which\"]}}",
"rmcp-macros_1.8.0": "{\"dependencies\":[{\"name\":\"darling\",\"req\":\"^0.23\"},{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2\"}],\"features\":{\"local\":[]}}",
"rmcp_1.8.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0\"},{\"name\":\"async-trait\",\"req\":\"^0.1.89\"},{\"kind\":\"dev\",\"name\":\"async-trait\",\"req\":\"^0.1\"},{\"default_features\":false,\"features\":[\"http1\",\"tokio\"],\"kind\":\"dev\",\"name\":\"axum\",\"req\":\"^0.8\"},{\"name\":\"base64\",\"optional\":true,\"req\":\"^0.22\"},{\"name\":\"bytes\",\"optional\":true,\"req\":\"^1\"},{\"default_features\":false,\"features\":[\"serde\",\"clock\",\"std\",\"oldtime\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\"))\"},{\"default_features\":false,\"features\":[\"serde\",\"now\"],\"name\":\"chrono\",\"req\":\"^0.4.38\",\"target\":\"cfg(not(all(target_family = \\\"wasm\\\", target_os = \\\"unknown\\\")))\"},{\"name\":\"futures\",\"req\":\"^0.3\"},{\"name\":\"http\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"http-body-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"client\",\"http1\"],\"name\":\"hyper\",\"optional\":true,\"req\":\"^1\"},{\"features\":[\"server\",\"http1\"],\"kind\":\"dev\",\"name\":\"hyper\",\"req\":\"^1\"},{\"features\":[\"tokio\"],\"name\":\"hyper-util\",\"optional\":true,\"req\":\"^0.1\"},{\"features\":[\"tokio\"],\"kind\":\"dev\",\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"jsonwebtoken\",\"optional\":true,\"req\":\"^10\"},{\"default_features\":false,\"name\":\"oauth2\",\"optional\":true,\"req\":\"^5.0\"},{\"name\":\"pastey\",\"optional\":true,\"req\":\"^0.2.0\"},{\"name\":\"pin-project-lite\",\"req\":\"^0.2\"},{\"features\":[\"tokio1\"],\"name\":\"process-wrap\",\"optional\":true,\"req\":\"^9.0\"},{\"name\":\"rand\",\"optional\":true,\"req\":\"^0.10\"},{\"default_features\":false,\"features\":[\"json\",\"stream\"],\"name\":\"reqwest\",\"optional\":true,\"req\":\"^0.13.2\"},{\"name\":\"rmcp-macros\",\"optional\":true,\"req\":\"^1.8.0\"},{\"features\":[\"chrono04\"],\"name\":\"schemars\",\"optional\":true,\"req\":\"^1.0\"},{\"features\":[\"chrono04\"],\"kind\":\"dev\",\"name\":\"schemars\",\"req\":\"^1.1.0\"},{\"features\":[\"derive\",\"rc\"],\"name\":\"serde\",\"req\":\"^1.0\"},{\"name\":\"serde_json\",\"req\":\"^1.0\"},{\"name\":\"sse-stream\",\"optional\":true,\"req\":\"^0.2\"},{\"name\":\"thiserror\",\"req\":\"^2\"},{\"features\":[\"sync\",\"macros\",\"rt\",\"time\"],\"name\":\"tokio\",\"req\":\"^1\"},{\"features\":[\"full\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1\"},{\"name\":\"tokio-stream\",\"optional\":true,\"req\":\"^0.1\"},{\"name\":\"tokio-util\",\"req\":\"^0.7\"},{\"name\":\"tower-service\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"tower-service\",\"req\":\"^0.3\"},{\"name\":\"tracing\",\"req\":\"^0.1\"},{\"features\":[\"env-filter\",\"std\",\"fmt\"],\"kind\":\"dev\",\"name\":\"tracing-subscriber\",\"req\":\"^0.3\"},{\"name\":\"url\",\"optional\":true,\"req\":\"^2.4\"},{\"kind\":\"dev\",\"name\":\"url\",\"req\":\"^2.4\"},{\"features\":[\"v4\"],\"name\":\"uuid\",\"optional\":true,\"req\":\"^1\"},{\"name\":\"which\",\"optional\":true,\"req\":\"^8\"}],\"features\":{\"__reqwest\":[\"dep:reqwest\"],\"auth\":[\"dep:oauth2\",\"__reqwest\",\"dep:url\"],\"auth-client-credentials-jwt\":[\"auth\",\"dep:jsonwebtoken\",\"uuid\"],\"client\":[\"dep:tokio-stream\"],\"client-side-sse\":[\"dep:sse-stream\",\"dep:http\"],\"default\":[\"base64\",\"macros\",\"server\"],\"elicitation\":[\"dep:url\"],\"local\":[\"rmcp-macros?/local\"],\"macros\":[\"dep:rmcp-macros\",\"dep:pastey\"],\"reqwest\":[\"__reqwest\",\"reqwest?/rustls\"],\"reqwest-native-tls\":[\"__reqwest\",\"reqwest?/native-tls\"],\"reqwest-tls-no-provider\":[\"__reqwest\",\"reqwest?/rustls-no-provider\"],\"schemars\":[\"dep:schemars\"],\"server\":[\"transport-async-rw\",\"dep:schemars\",\"dep:pastey\"],\"server-side-http\":[\"uuid\",\"dep:rand\",\"dep:tokio-stream\",\"dep:http\",\"dep:http-body\",\"dep:http-body-util\",\"dep:bytes\",\"dep:sse-stream\",\"tower\"],\"tower\":[\"dep:tower-service\"],\"transport-async-rw\":[\"tokio/io-util\",\"tokio-util/codec\"],\"transport-child-process\":[\"transport-async-rw\",\"tokio/process\",\"dep:process-wrap\"],\"transport-io\":[\"transport-async-rw\",\"tokio/io-std\"],\"transport-streamable-http-client\":[\"client-side-sse\",\"transport-worker\"],\"transport-streamable-http-client-reqwest\":[\"transport-streamable-http-client\",\"__reqwest\"],\"transport-streamable-http-client-unix-socket\":[\"transport-streamable-http-client\",\"dep:hyper\",\"dep:hyper-util\",\"dep:http-body-util\",\"dep:http\",\"dep:bytes\",\"tokio/net\"],\"transport-streamable-http-server\":[\"transport-streamable-http-server-session\",\"server-side-http\",\"transport-worker\"],\"transport-streamable-http-server-session\":[\"transport-async-rw\",\"dep:tokio-stream\"],\"transport-worker\":[\"dep:tokio-stream\"],\"which-command\":[\"transport-child-process\",\"dep:which\"]}}",
"rtrb_0.3.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"default_features\":false,\"kind\":\"dev\",\"name\":\"crossbeam-utils\",\"req\":\"^0.8\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.10\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}",
"rust-embed-impl_8.11.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"rust-embed-utils\",\"req\":\"^8.11.0\"},{\"name\":\"shellexpand\",\"optional\":true,\"req\":\"^3\"},{\"default_features\":false,\"features\":[\"derive\",\"parsing\",\"proc-macro\",\"printing\"],\"name\":\"syn\",\"req\":\"^2\"},{\"name\":\"walkdir\",\"req\":\"^2.3.1\"}],\"features\":{\"compression\":[],\"debug-embed\":[],\"deterministic-timestamps\":[],\"include-exclude\":[\"rust-embed-utils/include-exclude\"],\"interpolate-folder-path\":[\"shellexpand\"],\"mime-guess\":[\"rust-embed-utils/mime-guess\"]}}",
"rust-embed-utils_8.11.0": "{\"dependencies\":[{\"name\":\"globset\",\"optional\":true,\"req\":\"^0.4.8\"},{\"name\":\"mime_guess\",\"optional\":true,\"req\":\"^2.0.4\"},{\"name\":\"sha2\",\"req\":\"^0.10.5\"},{\"name\":\"walkdir\",\"req\":\"^2.3.1\"}],\"features\":{\"debug-embed\":[],\"include-exclude\":[\"globset\"],\"mime-guess\":[\"mime_guess\"]}}",
+7 -6
View File
@@ -3981,6 +3981,7 @@ dependencies = [
"chrono",
"codex-git-utils",
"codex-install-context",
"codex-otel",
"codex-protocol",
"codex-rollout",
"codex-state",
@@ -9452,7 +9453,7 @@ version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d"
dependencies = [
"base64 0.21.7",
"base64 0.22.1",
"chrono",
"getrandom 0.2.17",
"http 1.4.0",
@@ -10538,7 +10539,7 @@ version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7"
dependencies = [
"heck 0.4.1",
"heck 0.5.0",
"itertools 0.14.0",
"log",
"multimap",
@@ -11458,9 +11459,9 @@ dependencies = [
[[package]]
name = "rmcp"
version = "1.7.0"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0810a9f717d9828f475fe1f629f4c305c8464b7f496c3a854b58d29e65f4058e"
checksum = "1d1f571c72940a19d9532fe52dbea8bc9912bf1d766c2970bb824056b86f3f59"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -11493,9 +11494,9 @@ dependencies = [
[[package]]
name = "rmcp-macros"
version = "1.7.0"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6aefac48c364756e97f04c0401ba3231e8607882c7c1d92da0437dc16307904d"
checksum = "1aad0035b69380782d78ea95b508327e6deaa2235909053e596eea8f27b5e1d5"
dependencies = [
"darling 0.23.0",
"proc-macro2",
+2 -2
View File
@@ -368,7 +368,7 @@ rcgen = { version = "0.14.7", default-features = false, features = [
regex = "1.12.3"
regex-lite = "0.1.8"
reqwest = { version = "0.12", features = ["cookies"] }
rmcp = { version = "1.7.0", default-features = false }
rmcp = { version = "1.8.0", default-features = false }
runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" }
rustls = { version = "0.23", default-features = false, features = [
"aws_lc_rs",
@@ -380,7 +380,7 @@ schemars = "0.8.22"
seccompiler = "0.5.0"
semver = "1.0"
sentry = "0.46.0"
serde = "1"
serde = { version = "1", features = ["rc"] }
serde_ignored = "0.1.14"
serde_json = "1"
serde_path_to_error = "0.1.20"
@@ -2604,8 +2604,8 @@ impl ThreadRequestProcessor {
self.resume_thread_from_history(history.as_slice())
.await
.map(|thread_history| (thread_history, None))
} else if let Some(stored_thread) = stored_thread_from_running_probe {
self.stored_thread_to_initial_history(&stored_thread)
} else if let Some(mut stored_thread) = stored_thread_from_running_probe {
self.stored_thread_to_initial_history(&mut stored_thread)
.await
.map(|thread_history| (thread_history, Some(*stored_thread)))
} else {
@@ -2758,7 +2758,7 @@ impl ThreadRequestProcessor {
let token_usage_thread = include_turns.then(|| thread.clone());
let mut initial_turns_page = if let Some(params) = initial_turns_page.as_ref() {
match build_thread_resume_initial_turns_page(
&response_history.get_rollout_items(),
response_history.get_rollout_items(),
thread.status.clone(),
/*has_live_running_thread*/ false,
/*active_turn*/ None,
@@ -2803,7 +2803,7 @@ impl ThreadRequestProcessor {
// rebuilding history only to attribute a replayed usage update.
if let Some(token_usage_thread) = token_usage_thread {
let token_usage_turn_id = latest_token_usage_turn_id_from_rollout_items(
&response_history.get_rollout_items(),
response_history.get_rollout_items(),
token_usage_thread.turns.as_slice(),
);
// The client needs restored usage before it starts another turn.
@@ -2901,7 +2901,7 @@ impl ThreadRequestProcessor {
}
};
if let Some((existing_thread_id, existing_thread, source_thread)) = running_thread {
if let Some((existing_thread_id, existing_thread, mut source_thread)) = running_thread {
let existing_thread_rollout_path = existing_thread.rollout_path();
let active_path = existing_thread_rollout_path
.as_ref()
@@ -2963,8 +2963,8 @@ impl ThreadRequestProcessor {
should_redact_thread_resume_payloads(app_server_client_name.as_deref());
let history_items = source_thread
.history
.as_ref()
.map(|history| history.items.clone())
.take()
.map(|history| history.items)
.ok_or_else(|| {
internal_error(format!(
"thread {existing_thread_id} did not include persisted history"
@@ -2988,10 +2988,8 @@ impl ThreadRequestProcessor {
)
.await?;
let mut summary_source_thread = source_thread;
summary_source_thread.history = None;
let mut thread_summary = self.stored_thread_to_api_thread(
summary_source_thread,
source_thread,
config_snapshot.model_provider_id.as_str(),
/*include_turns*/ false,
);
@@ -3060,11 +3058,11 @@ impl ThreadRequestProcessor {
thread_id: &str,
path: Option<&PathBuf>,
) -> Result<(InitialHistory, StoredThread), JSONRPCErrorError> {
let stored_thread = self
let mut 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)
.stored_thread_to_initial_history(&mut stored_thread)
.await?;
Ok((history, stored_thread))
}
@@ -3112,13 +3110,13 @@ impl ThreadRequestProcessor {
#[tracing::instrument(level = "trace", skip_all)]
async fn stored_thread_to_initial_history(
&self,
stored_thread: &StoredThread,
stored_thread: &mut StoredThread,
) -> Result<InitialHistory, JSONRPCErrorError> {
let thread_id = stored_thread.thread_id;
let history = stored_thread
.history
.as_ref()
.map(|history| history.items.clone())
.take()
.map(|history| history.items)
.ok_or_else(|| {
internal_error(format!(
"thread {thread_id} did not include persisted history"
@@ -3126,7 +3124,7 @@ impl ThreadRequestProcessor {
})?;
Ok(InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history,
history: Arc::new(history),
rollout_path: stored_thread.rollout_path.clone(),
}))
}
@@ -3255,7 +3253,7 @@ impl ThreadRequestProcessor {
let history_items = thread_history.get_rollout_items();
populate_thread_turns_from_history(
&mut thread,
&history_items,
history_items,
/*active_turn*/ None,
);
}
@@ -3313,7 +3311,7 @@ impl ThreadRequestProcessor {
"`permissions` cannot be combined with `sandbox`",
));
}
let source_thread = self
let mut 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;
@@ -3323,8 +3321,8 @@ impl ThreadRequestProcessor {
.and_then(codex_core::util::normalize_thread_name);
let history_items = source_thread
.history
.as_ref()
.map(|history| history.items.clone())
.take()
.map(|history| Arc::new(history.items))
.ok_or_else(|| {
internal_error(format!(
"thread {source_thread_id} did not include persisted history"
@@ -3391,7 +3389,7 @@ impl ThreadRequestProcessor {
config,
InitialHistory::Resumed(ResumedHistory {
conversation_id: source_thread_id,
history: history_items.clone(),
history: Arc::clone(&history_items),
rollout_path: source_thread.rollout_path.clone(),
}),
thread_source.map(Into::into),
@@ -1237,7 +1237,7 @@ impl TurnRequestProcessor {
config.clone(),
InitialHistory::Resumed(ResumedHistory {
conversation_id: parent_thread_id,
history: parent_history.items,
history: Arc::new(parent_history.items),
rollout_path: parent_thread.rollout_path(),
}),
/*thread_source*/ None,
@@ -100,6 +100,7 @@ const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const TEST_ORIGINATOR: &str = "codex_vscode";
const LOCAL_PRAGMATIC_TEMPLATE: &str = "You are a deeply pragmatic, effective software engineer.";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
const TINY_PNG_BYTES: &[u8] = &[
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
@@ -3650,7 +3651,12 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
|req: &wiremock::Request| body_contains(req, PARENT_PROMPT),
responses::sse(vec![
responses::ev_response_created("resp-parent-1"),
responses::ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
responses::ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
responses::ev_completed("resp-parent-1"),
]),
)
+115 -7
View File
@@ -6,6 +6,7 @@ mod seatbelt;
use std::path::PathBuf;
use std::process::Stdio;
use anyhow::Context as _;
use codex_config::LoaderOverrides;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
@@ -16,6 +17,8 @@ use codex_core::exec_env::create_env;
use codex_core::spawn::CODEX_SANDBOX_ENV_VAR;
use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR;
use codex_protocol::config_types::SandboxMode;
use codex_protocol::models::PermissionProfile;
use codex_protocol::models::SandboxEnforcement;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_sandboxing::landlock::allow_network_for_proxy;
use codex_sandboxing::landlock::create_linux_sandbox_command_args_for_permission_profile;
@@ -45,6 +48,7 @@ pub async fn run_command_under_seatbelt(
loader_overrides: LoaderOverrides,
) -> anyhow::Result<()> {
let SeatbeltCommand {
sandbox_state,
permissions_profile,
config_profile: _,
cwd,
@@ -60,6 +64,7 @@ pub async fn run_command_under_seatbelt(
);
run_command_under_sandbox(
DebugSandboxConfigOptions {
sandbox_state,
permissions_profile,
cwd,
managed_requirements_mode,
@@ -90,6 +95,7 @@ pub async fn run_command_under_landlock(
loader_overrides: LoaderOverrides,
) -> anyhow::Result<()> {
let LandlockCommand {
sandbox_state,
permissions_profile,
config_profile: _,
cwd,
@@ -103,6 +109,7 @@ pub async fn run_command_under_landlock(
);
run_command_under_sandbox(
DebugSandboxConfigOptions {
sandbox_state,
permissions_profile,
cwd,
managed_requirements_mode,
@@ -124,6 +131,7 @@ pub async fn run_command_under_windows_sandbox(
loader_overrides: LoaderOverrides,
) -> anyhow::Result<()> {
let WindowsCommand {
sandbox_state,
permissions_profile,
config_profile: _,
cwd,
@@ -137,6 +145,7 @@ pub async fn run_command_under_windows_sandbox(
);
run_command_under_sandbox(
DebugSandboxConfigOptions {
sandbox_state,
permissions_profile,
cwd,
managed_requirements_mode,
@@ -161,6 +170,7 @@ enum SandboxType {
#[derive(Debug)]
struct DebugSandboxConfigOptions {
sandbox_state: crate::SandboxStateArgs,
permissions_profile: Option<String>,
cwd: Option<PathBuf>,
managed_requirements_mode: ManagedRequirementsMode,
@@ -187,7 +197,7 @@ impl ManagedRequirementsMode {
}
async fn run_command_under_sandbox(
config_options: DebugSandboxConfigOptions,
mut config_options: DebugSandboxConfigOptions,
command: Vec<String>,
config_overrides: CliConfigOverrides,
codex_linux_sandbox_exe: Option<PathBuf>,
@@ -196,6 +206,34 @@ async fn run_command_under_sandbox(
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
allow_unix_sockets: &[AbsolutePathBuf],
) -> anyhow::Result<()> {
let sandbox_state = config_options
.sandbox_state
.sandbox_state_json
.as_deref()
.map(serde_json::from_str::<codex_mcp::SandboxState>)
.transpose()
.map_err(|err| anyhow::anyhow!("invalid --sandbox-state-json value: {err}"))?;
let sandbox_state_readable_root = config_options
.sandbox_state
.sandbox_state_readable_root
.clone();
let sandbox_state_disable_network = config_options.sandbox_state.sandbox_state_disable_network;
let codex_linux_sandbox_exe = match sandbox_state.as_ref() {
Some(state) => {
config_options.cwd = Some(
state
.sandbox_cwd
.to_abs_path()
.context("sandbox state cwd is not native to this host")?
.to_path_buf(),
);
state
.codex_linux_sandbox_exe
.clone()
.or(codex_linux_sandbox_exe)
}
None => codex_linux_sandbox_exe,
};
let config = load_debug_sandbox_config(
config_overrides
.parse_overrides()
@@ -220,12 +258,75 @@ async fn run_command_under_sandbox(
&config.permissions.shell_environment_policy,
/*thread_id*/ None,
);
let mut permission_profile = match sandbox_state.as_ref() {
Some(state) => match &state.permission_profile {
PermissionProfile::External { .. } => {
// `External` only says that the producer relies on an outer sandbox; it does not
// include filesystem permissions we can recreate here. The consumer may not share
// that sandbox, so use a locally enforceable read-only profile instead of spawning
// without a sandbox.
PermissionProfile::read_only()
}
permission_profile => permission_profile.clone(),
},
None => config.permissions.effective_permission_profile(),
};
if matches!(permission_profile, PermissionProfile::Disabled) && sandbox_state_disable_network {
anyhow::bail!(
"--sandbox-state-disable-network cannot be applied to a disabled permission profile"
);
}
if !matches!(permission_profile, PermissionProfile::Disabled)
&& (!sandbox_state_readable_root.is_empty() || sandbox_state_disable_network)
{
let file_system = permission_profile
.file_system_sandbox_policy()
.with_additional_readable_roots(&cwd, &sandbox_state_readable_root);
let network = if sandbox_state_disable_network {
NetworkSandboxPolicy::Restricted
} else {
permission_profile.network_sandbox_policy()
};
permission_profile = PermissionProfile::from_runtime_permissions(&file_system, network);
}
let use_legacy_landlock = sandbox_state.as_ref().map_or_else(
|| config.features.use_legacy_landlock(),
|state| state.use_legacy_landlock,
);
match permission_profile.enforcement() {
SandboxEnforcement::Managed => {}
SandboxEnforcement::Disabled | SandboxEnforcement::External => {
let (program, args) = command
.split_first()
.context("sandbox command must not be empty")?;
let mut child = spawn_debug_sandbox_child(
PathBuf::from(program),
args.to_vec(),
/*arg0*/ None,
cwd.to_path_buf(),
permission_profile.network_sandbox_policy(),
env,
|_| {},
)
.await?;
handle_exit_status(child.wait().await?);
}
}
// Special-case Windows sandbox: execute and exit the process to emulate inherited stdio.
if let SandboxType::Windows = sandbox_type {
#[cfg(target_os = "windows")]
{
run_command_under_windows_session(&config, command, cwd, workspace_roots, env).await;
run_command_under_windows_session(
&config,
&permission_profile,
command,
cwd,
workspace_roots,
env,
)
.await;
}
#[cfg(not(target_os = "windows"))]
{
@@ -244,7 +345,7 @@ async fn run_command_under_sandbox(
let network_proxy = match config.permissions.network.as_ref() {
Some(spec) => Some(
spec.start_proxy(
config.permissions.permission_profile(),
&permission_profile,
/*policy_decider*/ None,
/*blocked_request_observer*/ None,
managed_network_requirements_enabled,
@@ -266,7 +367,7 @@ async fn run_command_under_sandbox(
None => None,
};
let runtime_permission_profile = with_managed_mitm_ca_readable_root(
config.permissions.effective_permission_profile(),
permission_profile,
managed_mitm_ca_trust_bundle_path.as_ref(),
sandbox_policy_cwd.as_path(),
);
@@ -308,7 +409,6 @@ async fn run_command_under_sandbox(
let codex_linux_sandbox_exe = config
.codex_linux_sandbox_exe
.expect("codex-linux-sandbox executable not found");
let use_legacy_landlock = config.features.use_legacy_landlock();
let network_sandbox_policy = runtime_permission_profile.network_sandbox_policy();
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
@@ -364,6 +464,7 @@ async fn run_command_under_sandbox(
#[cfg(target_os = "windows")]
async fn run_command_under_windows_session(
config: &Config,
permission_profile: &PermissionProfile,
command: Vec<String>,
cwd: AbsolutePathBuf,
workspace_roots: Vec<AbsolutePathBuf>,
@@ -374,10 +475,9 @@ async fn run_command_under_windows_session(
use codex_windows_sandbox::WindowsSandboxSessionRequest;
use codex_windows_sandbox::spawn_windows_sandbox_session_for_level;
let permission_profile = config.permissions.effective_permission_profile();
let empty_paths: &[AbsolutePathBuf] = &[];
let spawned = spawn_windows_sandbox_session_for_level(WindowsSandboxSessionRequest {
permission_profile: &permission_profile,
permission_profile,
workspace_roots: workspace_roots.as_slice(),
codex_home: config.codex_home.as_path(),
command,
@@ -464,6 +564,7 @@ async fn load_debug_sandbox_config_with_codex_home(
strict_config: bool,
) -> anyhow::Result<Config> {
let DebugSandboxConfigOptions {
sandbox_state: _,
permissions_profile,
cwd,
managed_requirements_mode,
@@ -649,6 +750,7 @@ mod tests {
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: None,
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Include,
@@ -717,6 +819,7 @@ mod tests {
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: None,
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Include,
@@ -774,6 +877,7 @@ mod tests {
cli_overrides,
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: None,
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Include,
@@ -832,6 +936,7 @@ mod tests {
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: None,
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Include,
@@ -859,6 +964,7 @@ mod tests {
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: Some(":workspace".to_string()),
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Ignore,
@@ -898,6 +1004,7 @@ mod tests {
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: Some("limited-read-test".to_string()),
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Ignore,
@@ -937,6 +1044,7 @@ mod tests {
Vec::new(),
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: Some(":workspace".to_string()),
cwd: Some(cwd.path().to_path_buf()),
managed_requirements_mode: ManagedRequirementsMode::Ignore,
+35 -2
View File
@@ -2,6 +2,7 @@ pub(crate) mod debug_sandbox;
mod exit_status;
pub(crate) mod login;
use clap::Args;
use clap::Parser;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
@@ -21,10 +22,36 @@ pub use login::run_login_with_device_code;
pub use login::run_login_with_device_code_fallback_to_browser;
pub use login::run_logout;
#[derive(Debug, Default, Args)]
pub struct SandboxStateArgs {
/// JSON value from `codex/sandbox-state-meta` to apply directly.
#[arg(
long = "sandbox-state-json",
value_name = "JSON",
conflicts_with_all = ["permissions_profile", "cwd", "include_managed_config"]
)]
pub sandbox_state_json: Option<String>,
/// Add a readable root to the supplied sandbox state. Repeat for multiple roots.
#[arg(
long,
requires = "sandbox_state_json",
value_parser = parse_absolute_path
)]
pub sandbox_state_readable_root: Vec<AbsolutePathBuf>,
/// Disable direct network access in the supplied sandbox state.
#[arg(long, requires = "sandbox_state_json", default_value_t = false)]
pub sandbox_state_disable_network: bool,
}
// These command structs share common sandbox options, but remain separate
// because each host backend has a slightly different option surface.
#[derive(Debug, Parser)]
pub struct SeatbeltCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(long = "permissions-profile", short = 'P', value_name = "NAME")]
pub permissions_profile: Option<String>,
@@ -51,7 +78,7 @@ pub struct SeatbeltCommand {
pub include_managed_config: bool,
/// Allow the sandboxed command to bind/connect AF_UNIX sockets rooted at this path. Relative paths are resolved against the current directory. Repeat to allow multiple paths.
#[arg(long = "allow-unix-socket", value_parser = parse_allow_unix_socket_path)]
#[arg(long = "allow-unix-socket", value_parser = parse_absolute_path)]
pub allow_unix_sockets: Vec<AbsolutePathBuf>,
/// While the command runs, capture macOS sandbox denials via `log stream` and print them after exit
@@ -66,13 +93,16 @@ pub struct SeatbeltCommand {
pub command: Vec<String>,
}
fn parse_allow_unix_socket_path(raw: &str) -> Result<AbsolutePathBuf, String> {
fn parse_absolute_path(raw: &str) -> Result<AbsolutePathBuf, String> {
AbsolutePathBuf::relative_to_current_dir(raw)
.map_err(|err| format!("invalid path {raw}: {err}"))
}
#[derive(Debug, Parser)]
pub struct LandlockCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(long = "permissions-profile", short = 'P', value_name = "NAME")]
pub permissions_profile: Option<String>,
@@ -108,6 +138,9 @@ pub struct LandlockCommand {
#[derive(Debug, Parser)]
pub struct WindowsCommand {
#[command(flatten)]
pub sandbox_state: SandboxStateArgs,
/// Named permissions profile to apply from the active configuration stack.
#[arg(long = "permissions-profile", short = 'P', value_name = "NAME")]
pub permissions_profile: Option<String>,
+1 -7
View File
@@ -8,7 +8,6 @@
use std::path::PathBuf;
use std::time::Instant;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::runtime::emit_duration;
use crate::tools::MCP_TOOLS_CACHE_WRITE_DURATION_METRIC;
use crate::tools::ToolInfo;
@@ -131,16 +130,11 @@ pub(crate) fn normalize_codex_apps_callable_namespace(
}
}
pub(crate) fn write_cached_codex_apps_tools_if_needed(
server_name: &str,
pub(crate) fn write_codex_apps_tools_cache(
cache_context: Option<&CodexAppsToolsCacheContext>,
server_info: &McpServerInfo,
tools: &[ToolInfo],
) {
if server_name != CODEX_APPS_MCP_SERVER_NAME {
return;
}
if let Some(cache_context) = cache_context {
let cache_write_start = Instant::now();
write_cached_codex_apps_tools(cache_context, tools);
+58 -26
View File
@@ -7,6 +7,7 @@
//! `codex-core`.
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::Ordering;
@@ -16,7 +17,7 @@ use std::time::Instant;
use crate::McpAuthStatusEntry;
use crate::codex_apps::CodexAppsToolsCacheContext;
use crate::codex_apps::CodexAppsToolsCacheKey;
use crate::codex_apps::write_cached_codex_apps_tools_if_needed;
use crate::codex_apps::write_codex_apps_tools_cache;
use crate::elicitation::ElicitationRequestManager;
use crate::elicitation::ElicitationReviewerHandle;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
@@ -40,6 +41,7 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use async_channel::Sender;
use codex_api::SharedAuthProvider;
use codex_config::Constrained;
use codex_config::McpServerTransportConfig;
use codex_config::types::AuthKeyringBackendKind;
@@ -171,29 +173,16 @@ impl McpConnectionManager {
},
)
.await;
let codex_apps_tools_cache_context = if server_name == CODEX_APPS_MCP_SERVER_NAME {
Some(CodexAppsToolsCacheContext {
codex_home: codex_home.clone(),
user_key: codex_apps_tools_cache_key.clone(),
})
} else {
None
};
let uses_env_bearer_token =
server
.configured_config()
.is_some_and(|config| match &config.transport {
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
..
} => bearer_token_env_var.is_some(),
McpServerTransportConfig::Stdio { .. } => false,
});
let runtime_auth_provider =
if server_name == CODEX_APPS_MCP_SERVER_NAME && !uses_env_bearer_token {
codex_apps_auth_provider.clone()
let (codex_apps_tools_cache_context, runtime_auth_provider) =
if server_name == CODEX_APPS_MCP_SERVER_NAME {
codex_apps_cache_context_and_auth_provider(
&server,
&codex_home,
&codex_apps_tools_cache_key,
codex_apps_auth_provider.clone(),
)
} else {
None
regular_mcp_cache_context_and_auth_provider()
};
let async_managed_client = AsyncManagedClient::new(
server_name.clone(),
@@ -402,7 +391,7 @@ impl McpConnectionManager {
}
pub fn is_host_owned_codex_apps_server(&self, server_name: &str) -> bool {
server_name == CODEX_APPS_MCP_SERVER_NAME
server_name == CODEX_APPS_MCP_SERVER_NAME && self.server_metadata.contains_key(server_name)
}
pub fn set_approval_policy(&self, approval_policy: &Constrained<AskForApproval>) {
@@ -521,8 +510,7 @@ impl McpConnectionManager {
&[],
);
write_cached_codex_apps_tools_if_needed(
CODEX_APPS_MCP_SERVER_NAME,
write_codex_apps_tools_cache(
managed_client.codex_apps_tools_cache_context.as_ref(),
&managed_client.server_info,
&tools,
@@ -857,6 +845,50 @@ impl Drop for McpConnectionManager {
}
}
/// Creates the host-owned state used only by the Codex Apps server.
///
/// The tools cache is scoped to the authenticated user. Runtime authentication is supplied only
/// when the server is not already configured to read a bearer token from the environment.
fn codex_apps_cache_context_and_auth_provider(
server: &EffectiveMcpServer,
codex_home: &Path,
codex_apps_tools_cache_key: &CodexAppsToolsCacheKey,
codex_apps_auth_provider: Option<SharedAuthProvider>,
) -> (
Option<CodexAppsToolsCacheContext>,
Option<SharedAuthProvider>,
) {
let uses_env_bearer_token =
server
.configured_config()
.is_some_and(|config| match &config.transport {
McpServerTransportConfig::StreamableHttp {
bearer_token_env_var,
..
} => bearer_token_env_var.is_some(),
McpServerTransportConfig::Stdio { .. } => false,
});
(
Some(CodexAppsToolsCacheContext {
codex_home: codex_home.to_path_buf(),
user_key: codex_apps_tools_cache_key.clone(),
}),
if uses_env_bearer_token {
None
} else {
codex_apps_auth_provider
},
)
}
/// Keeps regular MCP servers isolated from the host-owned Codex Apps cache and auth provider.
fn regular_mcp_cache_context_and_auth_provider() -> (
Option<CodexAppsToolsCacheContext>,
Option<SharedAuthProvider>,
) {
(None, None)
}
async fn emit_update(
submit_id: &str,
tx_event: &Sender<Event>,
@@ -5,7 +5,7 @@ use crate::codex_apps::load_startup_cached_codex_apps_server_info;
use crate::codex_apps::load_startup_cached_codex_apps_tools_snapshot;
use crate::codex_apps::read_cached_codex_apps_tools;
use crate::codex_apps::write_cached_codex_apps_tools;
use crate::codex_apps::write_cached_codex_apps_tools_if_needed;
use crate::codex_apps::write_codex_apps_tools_cache;
use crate::declared_openai_file_input_param_names;
use crate::elicitation::ElicitationRequestManager;
use crate::elicitation::elicitation_is_rejected_by_policy;
@@ -723,12 +723,7 @@ fn startup_cached_codex_apps_tools_loads_from_disk_cache() {
"calendar_search",
)];
let server_info = create_test_server_info("Codex Apps");
write_cached_codex_apps_tools_if_needed(
CODEX_APPS_MCP_SERVER_NAME,
Some(&cache_context),
&server_info,
&cached_tools,
);
write_codex_apps_tools_cache(Some(&cache_context), &server_info, &cached_tools);
let startup_tools = load_startup_cached_codex_apps_tools_snapshot(Some(&cache_context))
.expect("expected startup snapshot to load from cache");
@@ -777,8 +772,7 @@ fn codex_apps_server_info_cache_survives_legacy_tools_cache_write() {
Some("user-one"),
);
let server_info = create_test_server_info("Codex Apps");
write_cached_codex_apps_tools_if_needed(
CODEX_APPS_MCP_SERVER_NAME,
write_codex_apps_tools_cache(
Some(&cache_context),
&server_info,
&[create_test_tool(
@@ -1203,6 +1197,41 @@ fn server_metadata_preserves_tool_approval_policy() {
);
}
#[test]
fn host_owned_codex_apps_requires_server_metadata() {
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let manager = McpConnectionManager::new_uninitialized(
&approval_policy,
&permission_profile,
/*prefix_mcp_tool_names*/ true,
);
assert!(!manager.is_host_owned_codex_apps_server(CODEX_APPS_MCP_SERVER_NAME));
}
#[test]
fn host_owned_codex_apps_matches_reserved_name_with_server_metadata() {
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
&permission_profile,
/*prefix_mcp_tool_names*/ true,
);
let server = EffectiveMcpServer::configured(crate::codex_apps_mcp_server_config(
"https://chatgpt.com",
/*apps_mcp_product_sku*/ None,
));
manager.server_metadata.insert(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
McpServerMetadata::from(&server),
);
assert!(manager.is_host_owned_codex_apps_server(CODEX_APPS_MCP_SERVER_NAME));
assert!(!manager.is_host_owned_codex_apps_server("docs"));
}
#[tokio::test]
async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() {
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
+2
View File
@@ -10,6 +10,7 @@ use codex_protocol::protocol::McpAuthStatus;
use codex_rmcp_client::OAuthProviderError;
use codex_rmcp_client::determine_streamable_http_auth_status;
use codex_rmcp_client::discover_streamable_http_oauth;
use futures::FutureExt;
use futures::future::join_all;
use tracing::warn;
@@ -217,6 +218,7 @@ async fn compute_auth_status(
store_mode,
keyring_backend_kind,
)
.boxed()
.await
}
}
+2 -3
View File
@@ -25,7 +25,7 @@ use crate::codex_apps::load_startup_cached_codex_apps_tools_snapshot;
use crate::codex_apps::normalize_codex_apps_callable_name;
use crate::codex_apps::normalize_codex_apps_callable_namespace;
use crate::codex_apps::normalize_codex_apps_tool_title;
use crate::codex_apps::write_cached_codex_apps_tools_if_needed;
use crate::codex_apps::write_codex_apps_tools_cache;
use crate::elicitation::ElicitationRequestManager;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::mcp::ToolPluginProvenance;
@@ -581,8 +581,7 @@ async fn start_server_task(
);
let server_info = mcp_server_info_from_implementation(initialize_result.server_info);
let codex_apps_tools_cache_context = if is_codex_apps_mcp_server {
write_cached_codex_apps_tools_if_needed(
&server_name,
write_codex_apps_tools_cache(
codex_apps_tools_cache_context.as_ref(),
&server_info,
&tools,
+2 -3
View File
@@ -17,11 +17,10 @@ use codex_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxState {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permission_profile: Option<PermissionProfile>,
pub permission_profile: PermissionProfile,
pub codex_linux_sandbox_exe: Option<PathBuf>,
pub sandbox_cwd: PathUri,
#[serde(default)]
+2 -2
View File
@@ -143,7 +143,7 @@ impl AgentControl {
.items;
let initial_history = InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history,
history: Arc::new(history),
rollout_path: stored_thread.rollout_path,
});
if initial_history.get_multi_agent_version() != Some(MultiAgentVersion::V2) {
@@ -626,7 +626,7 @@ impl AgentControl {
.items;
let initial_history = InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history,
history: Arc::new(history),
rollout_path: stored_thread.rollout_path,
});
let parent_thread_id = stored_thread.parent_thread_id;
+3 -2
View File
@@ -246,7 +246,8 @@ Payload:
```
You may also see them addressed as to=/root/..., which indicates your identity is /root/...
"#;
const DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT: &str = r#"Note that collaboration tools cannot be called from inside `functions.exec`. Call `spawn_agent`, `send_message`, `followup_task`, `wait_agent`, `interrupt_agent`, and `list_agents` only as direct tool calls using the recipient shown in their tool definitions, such as `to=functions.spawn_agent` without a configured namespace or `to=functions.agents.spawn_agent` with `tool_namespace = "agents"`, since they are intentionally absent from the `functions.exec` `tools.*` namespace. Available tools in `functions.exec` are explicitly described with a `tools` namespace in the developer message.
const DEFAULT_MULTI_AGENT_V2_TOOL_NAMESPACE: &str = "collaboration";
const DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT: &str = r#"Note that collaboration tools cannot be called from inside `functions.exec`. Call `spawn_agent`, `send_message`, `followup_task`, `wait_agent`, `interrupt_agent`, and `list_agents` only as direct tool calls using the recipient shown in their tool definitions, such as `to=functions.collaboration.spawn_agent`, since they are intentionally absent from the `functions.exec` `tools.*` namespace. Available tools in `functions.exec` are explicitly described with a `tools` namespace in the developer message.
All agents share the same directory. In detail:
- All agents have access to the same container and filesystem as you.
@@ -1157,7 +1158,7 @@ impl MultiAgentV2Config {
DEFAULT_MULTI_AGENT_V2_SUBAGENT_USAGE_HINT_TEXT,
max_concurrent_threads_per_session,
)),
tool_namespace: None,
tool_namespace: Some(DEFAULT_MULTI_AGENT_V2_TOOL_NAMESPACE.to_string()),
hide_spawn_agent_metadata: true,
non_code_mode_only: true,
}
+1 -1
View File
@@ -744,7 +744,7 @@ async fn augment_mcp_tool_request_meta_with_sandbox_state(
};
let permission_profile = turn_context.permission_profile();
let sandbox_state = serde_json::to_value(SandboxState {
permission_profile: Some(permission_profile),
permission_profile,
codex_linux_sandbox_exe: turn_context.config.codex_linux_sandbox_exe.clone(),
sandbox_cwd,
use_legacy_landlock: turn_context.config.features.use_legacy_landlock(),
+13 -3
View File
@@ -1335,15 +1335,25 @@ fn codex_apps_auth_failure_metadata() -> McpToolApprovalMetadata {
async fn install_host_owned_codex_apps_manager(session: &Session, turn_context: &TurnContext) {
let auth = session.services.auth_manager.auth().await;
let startup_cancellation_token = CancellationToken::new();
startup_cancellation_token.cancel();
let (tx_event, _rx_event) = async_channel::unbounded();
let mcp_servers = HashMap::from([(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
codex_mcp::EffectiveMcpServer::configured(codex_mcp::codex_apps_mcp_server_config(
"https://chatgpt.com",
/*apps_mcp_product_sku*/ None,
)),
)]);
let manager = codex_mcp::McpConnectionManager::new(
&HashMap::new(),
&mcp_servers,
turn_context.config.mcp_oauth_credentials_store_mode,
turn_context.config.auth_keyring_backend_kind(),
HashMap::new(),
&turn_context.approval_policy,
turn_context.sub_id.clone(),
session.get_tx_event(),
CancellationToken::new(),
tx_event,
startup_cancellation_token,
turn_context.permission_profile(),
codex_mcp::McpRuntimeContext::new(
session.services.turn_environments.environment_manager(),
@@ -355,7 +355,7 @@ impl Session {
id: None,
});
RolloutReconstruction {
history: history.raw_items().to_vec(),
history: history.into_raw_items(),
previous_turn_settings,
reference_context_item,
window_number: window.number,
@@ -69,7 +69,9 @@ async fn record_initial_history_reconstructs_typed_inter_agent_message() {
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: vec![RolloutItem::InterAgentCommunication(communication.clone())],
history: Arc::new(vec![RolloutItem::InterAgentCommunication(
communication.clone(),
)]),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -112,7 +114,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -189,7 +191,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -757,7 +759,7 @@ async fn record_initial_history_resumed_rollback_skips_only_user_turns() {
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -841,7 +843,7 @@ async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_comp
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -871,7 +873,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_seed_referenc
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -898,7 +900,7 @@ async fn record_initial_history_resumed_does_not_seed_reference_context_item_aft
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1070,7 +1072,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1215,7 +1217,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1338,7 +1340,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1454,7 +1456,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1505,7 +1507,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_preserves_turn_
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1633,7 +1635,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
+11 -11
View File
@@ -1697,7 +1697,7 @@ async fn record_initial_history_reconstructs_resumed_transcript() {
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1862,7 +1862,7 @@ async fn prepares_resumed_history_before_installing_it() {
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: vec![RolloutItem::ResponseItem(resumed_item)],
history: Arc::new(vec![RolloutItem::ResponseItem(resumed_item)]),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -1905,7 +1905,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
resolve_multi_agent_version(
&InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history: Vec::new(),
history: Arc::new(Vec::new()),
rollout_path: None,
}),
/*inherited_multi_agent_version*/ None,
@@ -1916,7 +1916,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
resolve_multi_agent_version(
&InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history: Vec::new(),
history: Arc::new(Vec::new()),
rollout_path: None,
}),
Some(MultiAgentVersion::V2),
@@ -1927,10 +1927,10 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
resolve_multi_agent_version(
&InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history: vec![session_meta_item(
history: Arc::new(vec![session_meta_item(
thread_id,
Some(MultiAgentVersion::Disabled)
)],
)]),
rollout_path: None,
}),
Some(MultiAgentVersion::V2),
@@ -1991,7 +1991,7 @@ async fn resumed_history_injects_initial_context_on_first_context_update_only()
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -2085,7 +2085,7 @@ async fn record_initial_history_seeds_token_info_from_rollout() {
session
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: rollout_items,
history: Arc::new(rollout_items),
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
}))
.await;
@@ -5508,7 +5508,7 @@ async fn resumed_root_session_uses_thread_id_as_session_id() {
let (session, rx_event) = make_session_with_history_source_and_agent_control_and_rx(
InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history: Vec::new(),
history: Arc::new(Vec::new()),
rollout_path: None,
}),
SessionSource::Exec,
@@ -5543,7 +5543,7 @@ async fn resumed_subagent_session_restores_persisted_session_id() {
let (session, rx_event) = make_session_with_history_source_and_agent_control_and_rx(
InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history: vec![RolloutItem::SessionMeta(SessionMetaLine {
history: Arc::new(vec![RolloutItem::SessionMeta(SessionMetaLine {
meta: SessionMeta {
session_id: parent_session_id,
id: thread_id,
@@ -5551,7 +5551,7 @@ async fn resumed_subagent_session_restores_persisted_session_id() {
..SessionMeta::default()
},
git: None,
})],
})]),
rollout_path: None,
}),
session_source,
+12 -9
View File
@@ -1602,7 +1602,7 @@ fn stored_thread_to_initial_history(
})?;
Ok(InitialHistory::Resumed(ResumedHistory {
conversation_id: thread_id,
history: history.items,
history: Arc::new(history.items),
rollout_path: rollout_path.or(stored_thread.rollout_path),
}))
}
@@ -1639,7 +1639,7 @@ fn truncate_before_nth_user_message(
n: usize,
snapshot_state: &SnapshotTurnState,
) -> InitialHistory {
let items: Vec<RolloutItem> = history.get_rollout_items();
let items = history.get_rollout_items().to_vec();
let user_positions = truncation::user_message_positions_in_rollout(&items);
let rolled = if snapshot_state.ends_mid_turn && n >= user_positions.len() {
if let Some(cut_idx) = snapshot_state
@@ -1671,7 +1671,7 @@ struct SnapshotTurnState {
fn snapshot_turn_state(history: &InitialHistory) -> SnapshotTurnState {
let rollout_items = history.get_rollout_items();
let mut builder = ThreadHistoryBuilder::new();
for item in &rollout_items {
for item in rollout_items {
builder.handle_rollout_item(item);
}
let active_turn_id = builder.active_turn_id_if_explicit();
@@ -1695,7 +1695,7 @@ fn snapshot_turn_state(history: &InitialHistory) -> SnapshotTurnState {
};
}
let Some(last_user_position) = truncation::user_message_positions_in_rollout(&rollout_items)
let Some(last_user_position) = truncation::user_message_positions_in_rollout(rollout_items)
.last()
.copied()
else {
@@ -1736,7 +1736,9 @@ fn fork_history_from_snapshot(
InitialHistory::New => InitialHistory::New,
InitialHistory::Cleared => InitialHistory::Cleared,
InitialHistory::Forked(history) => InitialHistory::Forked(history),
InitialHistory::Resumed(resumed) => InitialHistory::Forked(resumed.history),
InitialHistory::Resumed(resumed) => {
InitialHistory::Forked(Arc::unwrap_or_clone(resumed.history))
}
};
if snapshot_state.ends_mid_turn {
append_interrupted_boundary(
@@ -1782,12 +1784,13 @@ fn append_interrupted_boundary(
history.push(aborted_event);
InitialHistory::Forked(history)
}
InitialHistory::Resumed(mut resumed) => {
InitialHistory::Resumed(resumed) => {
let mut history = Arc::unwrap_or_clone(resumed.history);
if let Some(marker) = interrupted_turn_history_marker(interrupted_marker) {
resumed.history.push(RolloutItem::ResponseItem(marker));
history.push(RolloutItem::ResponseItem(marker));
}
resumed.history.push(aborted_event);
InitialHistory::Forked(resumed.history)
history.push(aborted_event);
InitialHistory::Forked(history)
}
}
}
+7 -7
View File
@@ -116,7 +116,7 @@ fn truncates_before_requested_user_message() {
RolloutItem::ResponseItem(items[2].clone()),
];
assert_eq!(
serde_json::to_value(&got_items).unwrap(),
serde_json::to_value(got_items).unwrap(),
serde_json::to_value(&expected_items).unwrap()
);
@@ -256,7 +256,7 @@ async fn ignores_session_prefix_messages_when_truncating() {
];
assert_eq!(
serde_json::to_value(&got_items).unwrap(),
serde_json::to_value(got_items).unwrap(),
serde_json::to_value(&expected).unwrap()
);
}
@@ -964,7 +964,7 @@ async fn rollout_path_resume_and_fork_read_history_through_thread_store() {
config.clone(),
InitialHistory::Resumed(ResumedHistory {
conversation_id: source.thread_id,
history: vec![RolloutItem::ResponseItem(user_msg("hello"))],
history: Arc::new(vec![RolloutItem::ResponseItem(user_msg("hello"))]),
rollout_path: Some(rollout_path.clone()),
}),
auth_manager.clone(),
@@ -1316,7 +1316,7 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor
assert!(!snapshot_turn_state(&history).ends_mid_turn);
let rollout_items: Vec<_> = history
.get_rollout_items()
.into_iter()
.iter()
.filter(|item| !matches!(item, RolloutItem::SessionMeta(_)))
.collect();
let interrupted_marker_json = serde_json::to_value(RolloutItem::ResponseItem(
@@ -1436,7 +1436,7 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() {
.expect("read forked rollout history");
let rollout_items: Vec<_> = history
.get_rollout_items()
.into_iter()
.iter()
.filter(|item| !matches!(item, RolloutItem::SessionMeta(_)))
.collect();
@@ -1523,7 +1523,7 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_
let forked_rollout_items: Vec<_> = history
.get_rollout_items()
.into_iter()
.iter()
.filter(|item| !matches!(item, RolloutItem::SessionMeta(_)))
.collect();
let interrupted_marker_json = serde_json::to_value(RolloutItem::ResponseItem(
@@ -1561,7 +1561,7 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_
.expect("read re-forked rollout history");
let reforked_rollout_items: Vec<_> = reforked_history
.get_rollout_items()
.into_iter()
.iter()
.filter(|item| !matches!(item, RolloutItem::SessionMeta(_)))
.collect();
+51 -15
View File
@@ -39,6 +39,8 @@ use crate::tools::router::ToolRouterParams;
use crate::tools::router::ToolSuggestCandidates;
use crate::tools::router::ToolSuggestPresentation;
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
#[derive(Default)]
struct ToolPlanInputs {
mcp_tools: Option<Vec<ToolInfo>>,
@@ -1151,19 +1153,48 @@ async fn multi_agent_feature_selects_one_agent_tool_family() {
});
})
.await;
v2.assert_visible_contains(&[
v2.assert_visible_contains(&[MULTI_AGENT_V2_NAMESPACE]);
v2.assert_visible_lacks(&[
"spawn_agent",
"send_message",
"followup_task",
"wait_agent",
"interrupt_agent",
"list_agents",
"send_input",
"resume_agent",
"assign_task",
"close_agent",
]);
v2.assert_visible_lacks(&["send_input", "resume_agent", "assign_task", "close_agent"]);
let spawn_agent_description = match v2.visible_spec("spawn_agent") {
ToolSpec::Function(tool) => tool.description.as_str(),
other => panic!("expected spawn_agent function spec, got {other:?}"),
for tool_name in [
"spawn_agent",
"send_message",
"followup_task",
"wait_agent",
"interrupt_agent",
"list_agents",
] {
assert!(
v2.namespace_function_names(MULTI_AGENT_V2_NAMESPACE)
.iter()
.any(|name| name == tool_name),
"expected {tool_name} in {MULTI_AGENT_V2_NAMESPACE} namespace"
);
}
let ToolSpec::Namespace(namespace) = v2.visible_spec(MULTI_AGENT_V2_NAMESPACE) else {
panic!("expected {MULTI_AGENT_V2_NAMESPACE} namespace");
};
let Some(ResponsesApiNamespaceTool::Function(spawn_agent)) =
namespace.tools.iter().find(|tool| {
matches!(
tool,
ResponsesApiNamespaceTool::Function(tool) if tool.name == "spawn_agent"
)
})
else {
panic!("expected spawn_agent in {MULTI_AGENT_V2_NAMESPACE} namespace");
};
let spawn_agent_description = spawn_agent.description.as_str();
assert!(!spawn_agent_description.contains("max_concurrent_threads_per_session"));
assert!(spawn_agent_description.contains(
"Note that passing `fork_turns=\"none\"` will not pass any surrounding context to the spawned subagent"
@@ -1183,9 +1214,11 @@ async fn multi_agent_feature_selects_one_agent_tool_family() {
});
})
.await;
direct_model_only.assert_visible_contains(&["spawn_agent", "send_message", "wait_agent"]);
direct_model_only.assert_visible_contains(&[MULTI_AGENT_V2_NAMESPACE]);
direct_model_only.assert_visible_lacks(&["spawn_agent", "send_message", "wait_agent"]);
assert_eq!(
direct_model_only.exposure("spawn_agent"),
direct_model_only
.exposure(&ToolName::namespaced(MULTI_AGENT_V2_NAMESPACE, "spawn_agent").to_string()),
ToolExposure::DirectModelOnly
);
}
@@ -1196,9 +1229,17 @@ async fn multi_agent_v2_message_schemas_are_encrypted() {
set_feature(turn, Feature::MultiAgentV2, /*enabled*/ true);
})
.await;
let ToolSpec::Namespace(namespace) = plan.visible_spec(MULTI_AGENT_V2_NAMESPACE) else {
panic!("expected {MULTI_AGENT_V2_NAMESPACE} namespace");
};
for tool_name in ["spawn_agent", "send_message", "followup_task"] {
let ToolSpec::Function(tool) = plan.visible_spec(tool_name) else {
panic!("expected {tool_name} function spec");
let Some(ResponsesApiNamespaceTool::Function(tool)) = namespace.tools.iter().find(|tool| {
matches!(
tool,
ResponsesApiNamespaceTool::Function(tool) if tool.name == tool_name
)
}) else {
panic!("expected {tool_name} in {MULTI_AGENT_V2_NAMESPACE} namespace");
};
let properties = tool
.parameters
@@ -1464,12 +1505,7 @@ async fn hosted_tools_follow_provider_auth_model_and_config_gates() {
codex_code_mode::WAIT_TOOL_NAME,
"request_user_input",
// Multi-agent v2 tools.
"spawn_agent",
"send_message",
"followup_task",
"wait_agent",
"interrupt_agent",
"list_agents",
MULTI_AGENT_V2_NAMESPACE,
// Hosted Responses tools.
"web_search",
"image_generation",
+14 -3
View File
@@ -2,7 +2,7 @@ use anyhow::Result;
use codex_features::Feature;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::sse;
@@ -15,6 +15,7 @@ use std::time::Duration;
const FIRST_PROMPT: &str = "spawn the first worker";
const FIRST_TASK: &str = "first worker task";
const SECOND_TASK: &str = "second worker task";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
fn body_contains(request: &wiremock::Request, text: &str) -> bool {
serde_json::from_slice::<serde_json::Value>(&request.body)
@@ -47,7 +48,12 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()>
|request: &wiremock::Request| body_contains(request, FIRST_PROMPT),
sse(vec![
ev_response_created("first-response"),
ev_function_call("first-call", "spawn_agent", &first_args),
ev_function_call_with_namespace(
"first-call",
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&first_args,
),
ev_completed("first-response"),
]),
)
@@ -63,7 +69,12 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()>
},
sse(vec![
ev_response_created("first-worker-response"),
ev_function_call("second-call", "spawn_agent", &second_args),
ev_function_call_with_namespace(
"second-call",
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&second_args,
),
ev_completed("first-worker-response"),
]),
)
+3 -1
View File
@@ -1,3 +1,5 @@
use std::sync::Arc;
use codex_core::ForkSnapshot;
use codex_core::NewThread;
use codex_core::parse_turn_item;
@@ -196,7 +198,7 @@ async fn fork_thread_from_history_does_not_require_source_rollout_path() {
test.config.clone(),
InitialHistory::Resumed(ResumedHistory {
conversation_id: test.session_configured.thread_id,
history: source_items.clone(),
history: Arc::new(source_items.clone()),
rollout_path: None,
}),
/*thread_source*/ None,
@@ -37,6 +37,7 @@ use tokio::time::sleep;
const CHILD_MODEL: &str = "test-multi-agent-child";
const ROOT_MODEL: &str = "test-multi-agent-root";
const ROOT_PROMPT: &str = "spawn a child";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
const UNSUPPORTED_CODE_MODE_WARNING: &str = "does not advertise Code Mode support";
struct RemoteModelResponse {
@@ -335,7 +336,7 @@ async fn remote_multi_agent_selector_overrides_feature_flags() -> Result<()> {
.expect("test config should allow feature update");
})
.await?;
assert!(tool_names(&v2_body).contains(&"send_message".to_string()));
assert!(tool_names(&v2_body).contains(&MULTI_AGENT_V2_NAMESPACE.to_string()));
let mut disabled_model = remote_model("test-multi-agent-disabled");
disabled_model.multi_agent_version = Some(MultiAgentVersion::Disabled);
@@ -349,7 +350,12 @@ async fn remote_multi_agent_selector_overrides_feature_flags() -> Result<()> {
let disabled_tools = tool_names(&disabled_body);
assert!(disabled_tools.iter().all(|name| !matches!(
name.as_str(),
"multi_agent_v1" | "spawn_agent" | "send_message" | "wait_agent" | "list_agents"
"multi_agent_v1"
| MULTI_AGENT_V2_NAMESPACE
| "spawn_agent"
| "send_message"
| "wait_agent"
| "list_agents"
)));
Ok(())
@@ -432,7 +438,7 @@ async fn remote_multi_agent_selector_uses_model_selected_before_first_turn() ->
.expect("expected response request")
.body_json(),
)
.contains(&"send_message".to_string()),
.contains(&MULTI_AGENT_V2_NAMESPACE.to_string()),
),
(1, Some(MultiAgentVersion::V2), true)
);
+4 -1
View File
@@ -20,6 +20,7 @@ use core_test_support::responses;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_completed_with_tokens;
use core_test_support::responses::ev_function_call;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::responses::ev_message_item_added;
use core_test_support::responses::ev_output_text_delta;
use core_test_support::responses::ev_reasoning_item;
@@ -290,11 +291,13 @@ async fn steer_interrupts_wait_agent_and_is_sent_in_follow_up_request() {
const WAIT_CALL_ID: &str = "wait-call";
const INITIAL_PROMPT: &str = "wait for an agent";
const STEER_PROMPT: &str = "stop waiting and continue";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
let first_chunks = vec![
chunk(ev_response_created("resp-1")),
chunk(ev_function_call(
chunk(ev_function_call_with_namespace(
WAIT_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"wait_agent",
r#"{"timeout_ms":10000}"#,
)),
+4 -2
View File
@@ -1,5 +1,7 @@
#![allow(clippy::unwrap_used)]
use std::sync::Arc;
use codex_core::NewThread;
use codex_login::CodexAuth;
use codex_protocol::ThreadId;
@@ -51,7 +53,7 @@ fn resume_history(
InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: vec![
history: Arc::new(vec![
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: turn_id.clone(),
trace_id: None,
@@ -75,7 +77,7 @@ fn resume_history(
duration_ms: None,
time_to_first_token_ms: None,
})),
],
]),
rollout_path: Some(rollout_path.to_path_buf()),
})
}
+9 -5
View File
@@ -26,6 +26,7 @@ use codex_exec_server::Environment;
use codex_exec_server::HttpRequestParams;
use codex_login::CodexAuth;
use codex_mcp::MCP_SANDBOX_STATE_META_CAPABILITY;
use codex_mcp::SandboxState;
use codex_models_manager::manager::RefreshStrategy;
use codex_utils_path_uri::LegacyAppPathString;
@@ -933,13 +934,16 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
let sandbox_meta = meta
.get(MCP_SANDBOX_STATE_META_CAPABILITY)
.expect("sandbox state metadata should be present");
assert_eq!(sandbox_meta.get("sandboxPolicy"), None);
let expected_sandbox_cwd = PathUri::from_abs_path(&fixture.config.cwd).to_string();
let sandbox_state: SandboxState = serde_json::from_value(sandbox_meta.clone())?;
assert_eq!(
sandbox_meta.get("sandboxCwd").and_then(Value::as_str),
Some(expected_sandbox_cwd.as_str())
sandbox_state,
SandboxState {
permission_profile: PermissionProfile::read_only(),
codex_linux_sandbox_exe: fixture.config.codex_linux_sandbox_exe.clone(),
sandbox_cwd: PathUri::from_abs_path(&fixture.config.cwd),
use_legacy_landlock: false,
}
);
assert_eq!(sandbox_meta.get("useLegacyLandlock"), Some(&json!(false)));
server.verify().await;
+9 -2
View File
@@ -10,7 +10,7 @@ use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_completed_with_tokens;
use core_test_support::responses::ev_function_call;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::mount_sse_sequence;
@@ -25,6 +25,8 @@ use std::time::Duration;
use test_case::test_case;
use tokio::time::timeout;
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
fn rollout_budget() -> RolloutBudgetConfig {
RolloutBudgetConfig {
limit_tokens: 100,
@@ -130,7 +132,12 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> {
|request: &wiremock::Request| wire_request_contains(request, ROOT_PROMPT),
sse(vec![
ev_response_created("root-1"),
ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed_with_tokens("root-1", /*total_tokens*/ 10),
]),
)
@@ -17,7 +17,6 @@ use core_test_support::hooks::trust_discovered_hooks;
use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::ev_tool_search_call;
@@ -48,6 +47,7 @@ use wiremock::MockServer;
const SPAWN_CALL_ID: &str = "spawn-call-1";
const MULTI_AGENT_V1_NAMESPACE: &str = "multi_agent_v1";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
const TURN_0_FORK_PROMPT: &str = "seed fork context";
const TURN_1_PROMPT: &str = "spawn a child and continue";
const TURN_2_NO_WAIT_PROMPT: &str = "follow up without wait";
@@ -63,6 +63,23 @@ const SUBAGENT_STOP_CONTINUATION: &str = "continue only the child";
const INTERNAL_SUBAGENT_PROMPT: &str = "internal subagent: review";
fn body_contains(req: &wiremock::Request, text: &str) -> bool {
decoded_body(req)
.and_then(|body| String::from_utf8(body).ok())
.is_some_and(|body| body.contains(text))
}
fn request_has_input_type(req: &wiremock::Request, ty: &str) -> bool {
decoded_body(req)
.and_then(|body| serde_json::from_slice::<Value>(&body).ok())
.and_then(|body| body.get("input").and_then(Value::as_array).cloned())
.is_some_and(|items| {
items
.iter()
.any(|item| item.get("type").and_then(Value::as_str) == Some(ty))
})
}
fn decoded_body(req: &wiremock::Request) -> Option<Vec<u8>> {
let is_zstd = req
.headers
.get("content-encoding")
@@ -72,14 +89,11 @@ fn body_contains(req: &wiremock::Request, text: &str) -> bool {
.split(',')
.any(|entry| entry.trim().eq_ignore_ascii_case("zstd"))
});
let bytes = if is_zstd {
if is_zstd {
zstd::stream::decode_all(std::io::Cursor::new(&req.body)).ok()
} else {
Some(req.body.clone())
};
bytes
.and_then(|body| String::from_utf8(body).ok())
.is_some_and(|body| body.contains(text))
}
}
fn has_subagent_notification(req: &ResponsesRequest) -> bool {
@@ -1040,14 +1054,19 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
|req: &wiremock::Request| body_contains(req, TURN_1_PROMPT),
sse(vec![
ev_response_created("resp-parent-1"),
ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed("resp-parent-1"),
]),
)
.await;
let child_request_log = mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, "\"type\":\"agent_message\""),
|req: &wiremock::Request| request_has_input_type(req, "agent_message"),
sse(vec![
ev_response_created("resp-child-1"),
ev_completed("resp-child-1"),
@@ -1057,7 +1076,7 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
mount_sse_once_match(
&server,
|req: &wiremock::Request| {
body_contains(req, SPAWN_CALL_ID) && !body_contains(req, "\"type\":\"agent_message\"")
body_contains(req, SPAWN_CALL_ID) && !request_has_input_type(req, "agent_message")
},
sse(vec![
ev_response_created("resp-parent-2"),
@@ -1129,7 +1148,12 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
|req: &wiremock::Request| body_contains(req, TURN_1_PROMPT),
sse(vec![
ev_response_created("resp-parent-1"),
ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed("resp-parent-1"),
]),
)
@@ -1144,7 +1168,7 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
};
let child_request = mount_response_once_match(
&server,
|req: &wiremock::Request| body_contains(req, "\"type\":\"agent_message\""),
|req: &wiremock::Request| request_has_input_type(req, "agent_message"),
sse_response(sse(child_events)).set_delay(Duration::from_secs(1)),
)
.await;
@@ -1183,7 +1207,12 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
},
sse(vec![
ev_response_created("resp-parent-3"),
ev_function_call("wait-agent-call", "wait_agent", "{}"),
ev_function_call_with_namespace(
"wait-agent-call",
MULTI_AGENT_V2_NAMESPACE,
"wait_agent",
"{}",
),
ev_completed("resp-parent-3"),
]),
)
+6 -5
View File
@@ -10,6 +10,7 @@ use std::ops::Mul;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use strum_macros::EnumIter;
@@ -2460,7 +2461,7 @@ pub struct ConversationPathResponseEvent {
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)]
pub struct ResumedHistory {
pub conversation_id: ThreadId,
pub history: Vec<RolloutItem>,
pub history: Arc<Vec<RolloutItem>>,
pub rollout_path: Option<PathBuf>,
}
@@ -2505,11 +2506,11 @@ impl InitialHistory {
}
}
pub fn get_rollout_items(&self) -> Vec<RolloutItem> {
pub fn get_rollout_items(&self) -> &[RolloutItem] {
match self {
InitialHistory::New | InitialHistory::Cleared => Vec::new(),
InitialHistory::Resumed(resumed) => resumed.history.clone(),
InitialHistory::Forked(items) => items.clone(),
InitialHistory::New | InitialHistory::Cleared => &[],
InitialHistory::Resumed(resumed) => &resumed.history,
InitialHistory::Forked(items) => items,
}
}
+1 -1
View File
@@ -455,7 +455,7 @@ impl RmcpClient {
.peer()
.peer_info()
.ok_or_else(|| anyhow!("handshake succeeded but server info was missing"))?;
let initialize_result = initialize_result_rmcp.clone();
let initialize_result = initialize_result_rmcp.as_ref().clone();
{
let mut initialize_context = self.initialize_context.lock().await;
+4
View File
@@ -8,6 +8,7 @@ pub(crate) mod compression;
pub(crate) mod config;
pub(crate) mod list;
pub(crate) mod metadata;
mod persistence_metrics;
pub(crate) mod policy;
pub(crate) mod recorder;
pub(crate) mod search;
@@ -60,6 +61,9 @@ pub use list::read_session_meta_line;
pub use list::read_thread_item_from_rollout;
pub use list::rollout_date_parts;
pub use metadata::builder_from_items;
pub use persistence_metrics::RolloutPersistenceBatchMeasurement;
pub use persistence_metrics::RolloutPersistenceTelemetry;
pub use persistence_metrics::measure_and_filter_rollout_items;
pub use policy::is_persisted_rollout_item;
pub use policy::persisted_rollout_items;
pub use policy::should_persist_response_item_for_memories;
+406
View File
@@ -0,0 +1,406 @@
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use codex_otel::MetricsClient;
use codex_protocol::ThreadId;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::RolloutItem;
use crate::policy::is_persisted_rollout_item;
const ITEM_BYTES_METRIC: &str = "codex.rollout.persistence.item_bytes";
const APPEND_METRIC: &str = "codex.rollout.persistence.append";
const TURN_BYTES_METRIC: &str = "codex.rollout.persistence.turn_bytes";
const MEASUREMENT_ERROR_METRIC: &str = "codex.rollout.persistence.measurement_error";
const SAMPLE_DENOMINATOR: u64 = 100;
const SAMPLE_RATE_LABEL: &str = "0.01";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PersistenceDecision {
Kept,
Dropped,
}
impl PersistenceDecision {
fn as_str(self) -> &'static str {
match self {
Self::Kept => "kept",
Self::Dropped => "dropped",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RolloutSizeTotals {
pub items: u64,
pub payload_bytes: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RolloutItemMeasurement {
pub decision: PersistenceDecision,
pub rollout_item_type: String,
pub payload_bytes: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RolloutPersistenceBatchMeasurement {
pub pre_filter: RolloutSizeTotals,
pub post_filter: RolloutSizeTotals,
pub items: Vec<RolloutItemMeasurement>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct TurnSizeTotals {
pre_filter: RolloutSizeTotals,
post_filter: RolloutSizeTotals,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TurnOutcome {
Completed,
Aborted,
}
impl TurnOutcome {
fn as_str(self) -> &'static str {
match self {
Self::Completed => "completed",
Self::Aborted => "aborted",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CompletedTurnMeasurement {
totals: TurnSizeTotals,
outcome: TurnOutcome,
}
#[derive(Debug, Default, PartialEq, Eq)]
struct TurnMeasurementState {
pending: TurnSizeTotals,
active: Option<TurnSizeTotals>,
}
#[derive(Debug, Default, PartialEq, Eq)]
struct TurnMeasurementUpdate {
completed: Vec<CompletedTurnMeasurement>,
boundary_errors: Vec<&'static str>,
}
/// Measures logical JSON sizes while applying the shared rollout persistence policy once.
pub fn measure_and_filter_rollout_items(
items: &[RolloutItem],
) -> (Vec<RolloutItem>, RolloutPersistenceBatchMeasurement) {
let mut persisted = Vec::new();
let mut measurement = RolloutPersistenceBatchMeasurement {
items: Vec::with_capacity(items.len()),
..Default::default()
};
for item in items {
let kept = is_persisted_rollout_item(item);
let decision = if kept {
PersistenceDecision::Kept
} else {
PersistenceDecision::Dropped
};
let payload_bytes = serialized_len(item).ok();
add_to_totals(&mut measurement.pre_filter, payload_bytes);
if kept {
add_to_totals(&mut measurement.post_filter, payload_bytes);
persisted.push(item.clone());
}
measurement.items.push(RolloutItemMeasurement {
decision,
rollout_item_type: rollout_item_type(item),
payload_bytes,
});
}
(persisted, measurement)
}
fn add_to_totals(totals: &mut RolloutSizeTotals, payload_bytes: Option<u64>) {
totals.items = totals.items.saturating_add(1);
if let Some(payload_bytes) = payload_bytes {
totals.payload_bytes = totals.payload_bytes.saturating_add(payload_bytes);
}
}
fn update_turn_measurements(
state: &mut TurnMeasurementState,
items: &[RolloutItem],
measurement: &RolloutPersistenceBatchMeasurement,
) -> TurnMeasurementUpdate {
let mut update = TurnMeasurementUpdate::default();
for (item, item_measurement) in items.iter().zip(&measurement.items) {
match item {
RolloutItem::EventMsg(EventMsg::TurnStarted(_)) => {
if state.active.take().is_some() {
update.boundary_errors.push("event.turn_started");
}
let mut totals = std::mem::take(&mut state.pending);
add_item_to_turn(&mut totals, item_measurement);
state.active = Some(totals);
}
RolloutItem::EventMsg(EventMsg::TurnComplete(_)) => {
finish_turn(
state,
item_measurement,
TurnOutcome::Completed,
"event.turn_complete",
&mut update,
);
}
RolloutItem::EventMsg(EventMsg::TurnAborted(_)) => {
finish_turn(
state,
item_measurement,
TurnOutcome::Aborted,
"event.turn_aborted",
&mut update,
);
}
_ => match state.active.as_mut() {
Some(totals) => add_item_to_turn(totals, item_measurement),
None => add_item_to_turn(&mut state.pending, item_measurement),
},
}
}
update
}
fn finish_turn(
state: &mut TurnMeasurementState,
item: &RolloutItemMeasurement,
outcome: TurnOutcome,
boundary_type: &'static str,
update: &mut TurnMeasurementUpdate,
) {
let Some(mut totals) = state.active.take() else {
state.pending = TurnSizeTotals::default();
update.boundary_errors.push(boundary_type);
return;
};
add_item_to_turn(&mut totals, item);
update
.completed
.push(CompletedTurnMeasurement { totals, outcome });
}
fn add_item_to_turn(totals: &mut TurnSizeTotals, item: &RolloutItemMeasurement) {
add_to_totals(&mut totals.pre_filter, item.payload_bytes);
if item.decision == PersistenceDecision::Kept {
add_to_totals(&mut totals.post_filter, item.payload_bytes);
}
}
fn serialized_len(item: &RolloutItem) -> serde_json::Result<u64> {
let mut writer = CountingWriter::default();
serde_json::to_writer(&mut writer, item)?;
Ok(writer.bytes)
}
#[derive(Default)]
struct CountingWriter {
bytes: u64,
}
impl Write for CountingWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.bytes = self.bytes.saturating_add(buf.len() as u64);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn rollout_item_type(item: &RolloutItem) -> String {
match item {
RolloutItem::SessionMeta(_) => "session_meta".to_string(),
RolloutItem::ResponseItem(item) => response_item_type(item).to_string(),
RolloutItem::InterAgentCommunication(_) => "inter_agent_communication".to_string(),
RolloutItem::Compacted(_) => "compacted".to_string(),
RolloutItem::TurnContext(_) => "turn_context".to_string(),
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => {
format!("event.item_completed.{}", turn_item_type(&event.item))
}
RolloutItem::EventMsg(event) => format!("event.{event}"),
}
}
fn turn_item_type(item: &TurnItem) -> &'static str {
match item {
TurnItem::UserMessage(_) => "user_message",
TurnItem::HookPrompt(_) => "hook_prompt",
TurnItem::AgentMessage(_) => "agent_message",
TurnItem::Plan(_) => "plan",
TurnItem::Reasoning(_) => "reasoning",
TurnItem::WebSearch(_) => "web_search",
TurnItem::ImageView(_) => "image_view",
TurnItem::Sleep(_) => "sleep",
TurnItem::ImageGeneration(_) => "image_generation",
TurnItem::FileChange(_) => "file_change",
TurnItem::McpToolCall(_) => "mcp_tool_call",
TurnItem::ContextCompaction(_) => "context_compaction",
}
}
fn response_item_type(item: &ResponseItem) -> &'static str {
match item {
ResponseItem::Message { .. } => "response.message",
ResponseItem::AgentMessage { .. } => "response.agent_message",
ResponseItem::Reasoning { .. } => "response.reasoning",
ResponseItem::LocalShellCall { .. } => "response.local_shell_call",
ResponseItem::FunctionCall { .. } => "response.function_call",
ResponseItem::ToolSearchCall { .. } => "response.tool_search_call",
ResponseItem::FunctionCallOutput { .. } => "response.function_call_output",
ResponseItem::ToolSearchOutput { .. } => "response.tool_search_output",
ResponseItem::CustomToolCall { .. } => "response.custom_tool_call",
ResponseItem::CustomToolCallOutput { .. } => "response.custom_tool_call_output",
ResponseItem::WebSearchCall { .. } => "response.web_search_call",
ResponseItem::ImageGenerationCall { .. } => "response.image_generation_call",
ResponseItem::Compaction { .. } => "response.compaction",
ResponseItem::CompactionTrigger { .. } => "response.compaction_trigger",
ResponseItem::ContextCompaction { .. } => "response.context_compaction",
ResponseItem::Other => "response.other",
}
}
#[derive(Clone)]
pub struct RolloutPersistenceTelemetry {
metrics: Option<MetricsClient>,
sampled: bool,
turn_state: Option<Arc<Mutex<TurnMeasurementState>>>,
}
impl RolloutPersistenceTelemetry {
pub fn new(thread_id: ThreadId) -> Self {
let metrics = codex_otel::global();
let sampled = metrics.is_some() && is_thread_sampled(thread_id);
Self {
metrics,
sampled,
turn_state: sampled.then(|| Arc::new(Mutex::new(TurnMeasurementState::default()))),
}
}
pub fn is_enabled(&self) -> bool {
self.enabled_metrics().is_some()
}
pub fn record_batch(
&self,
items: &[RolloutItem],
measurement: &RolloutPersistenceBatchMeasurement,
) {
let Some(metrics) = self.enabled_metrics() else {
return;
};
for item in &measurement.items {
if let Some(payload_bytes) = item.payload_bytes {
let _ = metrics.histogram(
ITEM_BYTES_METRIC,
saturating_i64(payload_bytes),
&[
("decision", item.decision.as_str()),
("rollout_item_type", item.rollout_item_type.as_str()),
("encoding", "rollout_item_json_v1"),
("sample_rate", SAMPLE_RATE_LABEL),
],
);
} else {
let _ = metrics.counter(
MEASUREMENT_ERROR_METRIC,
/*inc*/ 1,
&[
("rollout_item_type", item.rollout_item_type.as_str()),
("phase", "serialize"),
],
);
}
}
// Count successful input appends and the subset that remain storage operations after the
// persistence policy removes filtered items.
let _ = metrics.counter(
APPEND_METRIC,
/*inc*/ 1,
&[("stage", "pre_filter"), ("sample_rate", SAMPLE_RATE_LABEL)],
);
if measurement.post_filter.items > 0 {
let _ = metrics.counter(
APPEND_METRIC,
/*inc*/ 1,
&[("stage", "post_filter"), ("sample_rate", SAMPLE_RATE_LABEL)],
);
}
let Some(turn_state) = self.turn_state.as_ref() else {
return;
};
let turn_update = update_turn_measurements(
&mut turn_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
items,
measurement,
);
for boundary_type in turn_update.boundary_errors {
let _ = metrics.counter(
MEASUREMENT_ERROR_METRIC,
/*inc*/ 1,
&[
("rollout_item_type", boundary_type),
("phase", "turn_boundary"),
],
);
}
for turn in turn_update.completed {
for (stage, totals) in [
("pre_filter", turn.totals.pre_filter),
("post_filter", turn.totals.post_filter),
] {
let _ = metrics.histogram(
TURN_BYTES_METRIC,
saturating_i64(totals.payload_bytes),
&[
("stage", stage),
("outcome", turn.outcome.as_str()),
("encoding", "rollout_item_json_v1"),
("sample_rate", SAMPLE_RATE_LABEL),
],
);
}
}
}
fn enabled_metrics(&self) -> Option<&MetricsClient> {
self.sampled.then_some(self.metrics.as_ref()).flatten()
}
}
fn saturating_i64(value: u64) -> i64 {
value.try_into().unwrap_or(i64::MAX)
}
fn is_thread_sampled(thread_id: ThreadId) -> bool {
let hash = thread_id
.to_string()
.bytes()
.fold(0xcbf29ce484222325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x100000001b3)
});
hash % SAMPLE_DENOMINATOR == 0
}
#[cfg(test)]
#[path = "persistence_metrics_tests.rs"]
mod tests;
@@ -0,0 +1,260 @@
use codex_protocol::ThreadId;
use codex_protocol::items::TurnItem;
use codex_protocol::items::UserMessageItem;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use pretty_assertions::assert_eq;
use super::CompletedTurnMeasurement;
use super::TurnMeasurementState;
use super::TurnOutcome;
use super::TurnSizeTotals;
use super::is_thread_sampled;
use super::measure_and_filter_rollout_items;
use super::update_turn_measurements;
fn retained_message(text: &str) -> RolloutItem {
RolloutItem::ResponseItem(ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: text.to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
})
}
fn turn_started(turn_id: &str) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: turn_id.to_string(),
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
}))
}
fn turn_complete(turn_id: &str) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: turn_id.to_string(),
last_agent_message: None,
completed_at: None,
duration_ms: None,
time_to_first_token_ms: None,
}))
}
fn turn_aborted(turn_id: &str) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::TurnAborted(TurnAbortedEvent {
turn_id: Some(turn_id.to_string()),
reason: TurnAbortReason::Interrupted,
completed_at: None,
duration_ms: None,
}))
}
fn update_for_batch(
state: &mut TurnMeasurementState,
items: &[RolloutItem],
) -> super::TurnMeasurementUpdate {
let (_, measurement) = measure_and_filter_rollout_items(items);
update_turn_measurements(state, items, &measurement)
}
#[test]
fn thread_sampling_is_stable_and_selects_whole_threads() {
let mut sampled = None;
let mut unsampled = None;
for value in 0..10_000_u128 {
let thread_id = ThreadId::from_string(&format!("00000000-0000-0000-0000-{value:012x}"))
.expect("valid thread id");
if is_thread_sampled(thread_id) {
sampled.get_or_insert(thread_id);
} else {
unsampled.get_or_insert(thread_id);
}
if sampled.is_some() && unsampled.is_some() {
break;
}
}
let sampled = sampled.expect("at least one sampled thread");
let unsampled = unsampled.expect("at least one unsampled thread");
assert!(is_thread_sampled(sampled));
assert!(is_thread_sampled(sampled));
assert!(!is_thread_sampled(unsampled));
assert!(!is_thread_sampled(unsampled));
}
#[test]
fn mixed_batch_reports_exact_policy_counts_and_bytes() {
let kept = retained_message("hello");
let dropped = RolloutItem::ResponseItem(ResponseItem::Other);
let items = vec![kept.clone(), dropped.clone()];
let (persisted, measurement) = measure_and_filter_rollout_items(&items);
let kept_bytes = serde_json::to_vec(&kept)
.expect("serialize kept item")
.len() as u64;
let dropped_bytes = serde_json::to_vec(&dropped)
.expect("serialize dropped item")
.len() as u64;
assert_eq!(
serde_json::to_value(persisted).expect("serialize persisted items"),
serde_json::to_value([kept]).expect("serialize expected items")
);
assert_eq!(measurement.pre_filter.items, 2);
assert_eq!(
measurement.pre_filter.payload_bytes,
kept_bytes + dropped_bytes
);
assert_eq!(measurement.post_filter.items, 1);
assert_eq!(measurement.post_filter.payload_bytes, kept_bytes);
assert_eq!(measurement.items[0].payload_bytes, Some(kept_bytes));
assert_eq!(measurement.items[1].payload_bytes, Some(dropped_bytes));
assert_eq!(measurement.items[0].rollout_item_type, "response.message");
assert_eq!(measurement.items[1].rollout_item_type, "response.other");
}
#[test]
fn retained_items_are_byte_identical() {
let item = retained_message("a moderately sized payload");
let (persisted, measurement) = measure_and_filter_rollout_items(std::slice::from_ref(&item));
assert_eq!(
serde_json::to_vec(&persisted[0]).expect("serialize persisted item"),
serde_json::to_vec(&item).expect("serialize candidate item")
);
assert_eq!(
measurement.post_filter.payload_bytes,
measurement.items[0].payload_bytes.expect("payload bytes")
);
}
#[test]
fn turn_measurements_span_batches_and_include_items_before_start() {
let first_turn = vec![
retained_message("first prompt"),
turn_started("turn-1"),
retained_message("first response"),
RolloutItem::ResponseItem(ResponseItem::Other),
turn_complete("turn-1"),
];
let second_turn = vec![
retained_message("second prompt"),
turn_started("turn-2"),
retained_message("second response"),
turn_aborted("turn-2"),
];
let (_, first_expected) = measure_and_filter_rollout_items(&first_turn);
let (_, second_expected) = measure_and_filter_rollout_items(&second_turn);
let batches = [
first_turn[..1].to_vec(),
first_turn[1..3].to_vec(),
vec![
first_turn[3].clone(),
first_turn[4].clone(),
second_turn[0].clone(),
],
second_turn[1..].to_vec(),
];
let mut state = TurnMeasurementState::default();
let mut completed = Vec::new();
let mut boundary_errors = Vec::new();
for batch in batches {
let update = update_for_batch(&mut state, &batch);
completed.extend(update.completed);
boundary_errors.extend(update.boundary_errors);
}
assert_eq!(
completed,
vec![
CompletedTurnMeasurement {
totals: TurnSizeTotals {
pre_filter: first_expected.pre_filter,
post_filter: first_expected.post_filter,
},
outcome: TurnOutcome::Completed,
},
CompletedTurnMeasurement {
totals: TurnSizeTotals {
pre_filter: second_expected.pre_filter,
post_filter: second_expected.post_filter,
},
outcome: TurnOutcome::Aborted,
},
]
);
assert_eq!(boundary_errors, Vec::<&str>::new());
assert_eq!(state, TurnMeasurementState::default());
}
#[test]
fn invalid_turn_boundaries_reset_partial_measurements() {
let mut state = TurnMeasurementState::default();
let unmatched_completion = vec![retained_message("orphan"), turn_complete("turn-1")];
let update = update_for_batch(&mut state, &unmatched_completion);
assert_eq!(update.completed, Vec::new());
assert_eq!(update.boundary_errors, vec!["event.turn_complete"]);
assert_eq!(state, TurnMeasurementState::default());
let replacement = vec![
turn_started("turn-1"),
retained_message("discarded partial turn"),
turn_started("turn-2"),
retained_message("retained turn"),
turn_complete("turn-2"),
];
let (_, expected) = measure_and_filter_rollout_items(&replacement[2..]);
let update = update_for_batch(&mut state, &replacement);
assert_eq!(
update.completed,
vec![CompletedTurnMeasurement {
totals: TurnSizeTotals {
pre_filter: expected.pre_filter,
post_filter: expected.post_filter,
},
outcome: TurnOutcome::Completed,
}]
);
assert_eq!(update.boundary_errors, vec!["event.turn_started"]);
assert_eq!(state, TurnMeasurementState::default());
}
#[test]
fn filtered_item_completion_includes_its_nested_item_type() {
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
thread_id: ThreadId::default(),
turn_id: "turn".to_string(),
item: TurnItem::UserMessage(UserMessageItem {
id: "item".to_string(),
client_id: None,
content: Vec::new(),
}),
completed_at_ms: 0,
}));
let (_, measurement) = measure_and_filter_rollout_items(&[item]);
assert_eq!(
measurement.items[0].rollout_item_type,
"event.item_completed.user_message"
);
assert_eq!(
measurement.items[0].decision,
super::PersistenceDecision::Dropped
);
}
+1 -1
View File
@@ -947,7 +947,7 @@ impl RolloutRecorder {
info!("Resumed rollout successfully from {path:?}");
Ok(InitialHistory::Resumed(ResumedHistory {
conversation_id,
history: items,
history: Arc::new(items),
rollout_path: Some(compression::plain_rollout_path(path)),
}))
}
+7
View File
@@ -199,6 +199,13 @@ where
fn on_event(&self, event: &Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
let metadata = event.metadata();
// `tracing-log` checks filters with the original log target before
// dispatching an event whose tracing target is `log`, so the outer
// target filter cannot reliably reject these bridged events.
if metadata.target() == "log" {
return;
}
// The SDK emits DEBUG timer meta-events every second per process; these
// were over 30% of retained logs in measured high-fanout Codex environments.
if metadata.target() == "opentelemetry_sdk"
+1
View File
@@ -16,6 +16,7 @@ workspace = true
chrono = { workspace = true, features = ["serde"] }
codex-git-utils = { workspace = true }
codex-install-context = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-rollout = { workspace = true }
codex-state = { workspace = true }
+3 -1
View File
@@ -266,7 +266,9 @@ impl InMemoryThreadStore {
let mut state = self.state.lock().await;
state.calls.resume_thread += 1;
if let Some(history) = params.history {
state.histories.insert(params.thread_id, history);
state
.histories
.insert(params.thread_id, Arc::unwrap_or_clone(history));
} else {
state.histories.entry(params.thread_id).or_default();
}
+19 -5
View File
@@ -4,6 +4,8 @@ use std::sync::Arc;
use codex_protocol::ThreadId;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::ThreadMemoryMode;
use codex_rollout::RolloutPersistenceTelemetry;
use codex_rollout::measure_and_filter_rollout_items;
use codex_rollout::persisted_rollout_items;
use tokio::sync::Mutex;
use tracing::warn;
@@ -32,6 +34,7 @@ pub struct LiveThread {
thread_id: ThreadId,
thread_store: Arc<dyn ThreadStore>,
metadata_sync: Arc<Mutex<ThreadMetadataSync>>,
persistence_telemetry: RolloutPersistenceTelemetry,
}
/// Owns a live thread while session initialization is still fallible.
@@ -95,17 +98,19 @@ impl LiveThread {
thread_id,
thread_store,
metadata_sync: Arc::new(Mutex::new(metadata_sync)),
persistence_telemetry: RolloutPersistenceTelemetry::new(thread_id),
})
}
pub async fn resume(
thread_store: Arc<dyn ThreadStore>,
mut params: ResumeThreadParams,
params: ResumeThreadParams,
) -> ThreadStoreResult<Self> {
let thread_id = params.thread_id;
let should_load_history = params.history.is_none();
let include_archived = params.include_archived;
thread_store.resume_thread(params.clone()).await?;
let mut metadata_sync = ThreadMetadataSync::for_resume(&params);
thread_store.resume_thread(params).await?;
if should_load_history {
match thread_store
.load_history(LoadThreadHistoryParams {
@@ -114,7 +119,7 @@ impl LiveThread {
})
.await
{
Ok(history) => params.history = Some(history.items),
Ok(history) => metadata_sync.record_resume_history(&history.items),
Err(err) => {
if let Err(discard_err) = thread_store.discard_thread(thread_id).await {
warn!(
@@ -125,11 +130,11 @@ impl LiveThread {
}
}
}
let metadata_sync = ThreadMetadataSync::for_resume(&params);
Ok(Self {
thread_id,
thread_store,
metadata_sync: Arc::new(Mutex::new(metadata_sync)),
persistence_telemetry: RolloutPersistenceTelemetry::new(thread_id),
})
}
@@ -139,16 +144,25 @@ impl LiveThread {
fields(item_count = items.len())
)]
pub async fn append_items(&self, items: &[RolloutItem]) -> ThreadStoreResult<()> {
let canonical_items = persisted_rollout_items(items);
// Empty appends are intentionally ignored rather than represented as zero-sized batches.
if items.is_empty() {
return Ok(());
}
let (canonical_items, measurement) = if self.persistence_telemetry.is_enabled() {
let (canonical_items, measurement) = measure_and_filter_rollout_items(items);
(canonical_items, Some(measurement))
} else {
(persisted_rollout_items(items), None)
};
self.thread_store
.append_items(AppendThreadItemsParams {
thread_id: self.thread_id,
items: items.to_vec(),
})
.await?;
if let Some(measurement) = measurement.as_ref() {
self.persistence_telemetry.record_batch(items, measurement);
}
if canonical_items.is_empty() {
return Ok(());
}
@@ -17,6 +17,8 @@ use crate::ResumeThreadParams;
use crate::ThreadStoreError;
use crate::ThreadStoreResult;
const ROLLOUT_SIZE_BYTES_METRIC: &str = "codex.rollout.size_bytes";
pub(super) async fn create_thread(
store: &LocalThreadStore,
params: CreateThreadParams,
@@ -128,8 +130,15 @@ pub(super) async fn shutdown_thread(
thread_id: ThreadId,
) -> ThreadStoreResult<()> {
let recorder = store.live_recorder(thread_id).await?;
let rollout_path = recorder.rollout_path().to_path_buf();
recorder.shutdown().await.map_err(thread_store_io_error)?;
sync_materialized_rollout_path(store, thread_id).await?;
if let Some(metrics) = codex_otel::global()
&& let Ok(metadata) = tokio::fs::metadata(rollout_path).await
{
let size_bytes = i64::try_from(metadata.len()).unwrap_or(i64::MAX);
let _ = metrics.histogram(ROLLOUT_SIZE_BYTES_METRIC, size_bytes, &[]);
}
store.live_recorders.lock().await.remove(&thread_id);
Ok(())
}
@@ -1,3 +1,5 @@
#[cfg(test)]
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
@@ -108,13 +110,17 @@ impl ThreadMetadataSync {
defer_resume_update_until_append: false,
};
if let Some(history) = params.history.as_deref() {
let update = sync.observe_resume_history(history);
sync.merge_pending_update(update);
sync.defer_resume_update_until_append = sync.pending_update.is_some();
sync.record_resume_history(history);
}
sync
}
pub(crate) fn record_resume_history(&mut self, history: &[RolloutItem]) {
let update = self.observe_resume_history(history);
self.merge_pending_update(update);
self.defer_resume_update_until_append = self.pending_update.is_some();
}
pub(crate) fn take_pending_update(&self) -> Option<PendingThreadMetadataPatch> {
self.pending_update
.clone()
@@ -555,7 +561,7 @@ mod tests {
ResumeThreadParams {
thread_id,
rollout_path: None,
history: Some(history),
history: Some(Arc::new(history)),
include_archived: false,
metadata: ThreadPersistenceMetadata {
cwd: None,
+2 -1
View File
@@ -1,4 +1,5 @@
use std::path::PathBuf;
use std::sync::Arc;
use chrono::DateTime;
use chrono::Utc;
@@ -96,7 +97,7 @@ pub struct ResumeThreadParams {
/// Known local rollout path when the caller resumed from a specific file.
pub rollout_path: Option<PathBuf>,
/// Known replay history for the resumed thread, if already loaded by the caller.
pub history: Option<Vec<RolloutItem>>,
pub history: Option<Arc<Vec<RolloutItem>>>,
/// Whether archived threads may be reopened.
pub include_archived: bool,
/// Metadata for future writes appended to the resumed live thread.
+40
View File
@@ -247,6 +247,33 @@ impl PathUri {
std::iter::successors(Some(self.clone()), Self::parent)
}
/// Returns true when this URI is lexically equal to or below `base`.
///
/// Containment is computed using URI authority and path-segment boundaries,
/// without consulting the host filesystem. Percent-encoded path separators
/// fail closed because native path conversion may interpret them as segment
/// boundaries. Opaque fallback URIs created by [`Self::from_abs_path`] only
/// contain themselves.
pub fn starts_with(&self, base: &Self) -> bool {
if self == base {
return true;
}
if decode_bad_path_uri(&self.0).is_some() || decode_bad_path_uri(&base.0).is_some() {
return false;
}
if self.0.host_str() != base.0.host_str() {
return false;
}
let Some(path_segments) = containment_path_segments(&self.0) else {
return false;
};
let Some(base_segments) = containment_path_segments(&base.0) else {
return false;
};
path_segments.starts_with(&base_segments)
}
/// Lexically resolves native absolute or relative path text against this URI.
///
/// Path text is interpreted using the POSIX or Windows convention inferred
@@ -542,6 +569,19 @@ fn is_windows_drive_uri_segment(segment: &str) -> bool {
matches!(segment.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic())
}
fn containment_path_segments(url: &Url) -> Option<Vec<&str>> {
let segments = url
.path_segments()?
.filter(|segment| !segment.is_empty())
.collect::<Vec<_>>();
(!segments.iter().any(|segment| {
urlencoding::decode_binary(segment.as_bytes())
.iter()
.any(|byte| matches!(*byte, b'/' | b'\\'))
}))
.then_some(segments)
}
fn infer_opaque_path_convention(path_bytes: &[u8]) -> Option<PathConvention> {
if path_bytes.starts_with(b"/") {
return Some(PathConvention::Posix);
+59
View File
@@ -283,9 +283,16 @@ fn structurally_valid_bad_path_uri_with_invalid_native_payload_fails_conversion(
fn bad_path_uris_are_opaque_to_lexical_operations() {
let uri = PathUri::parse("file:///%00/bad/path/YQ")
.expect("canonical base64 fallback URI should parse");
let other = PathUri::parse("file:///%00/bad/path/Yg")
.expect("canonical base64 fallback URI should parse");
let root = PathUri::parse("file:///").expect("valid root URI");
assert_eq!(uri.basename(), None);
assert_eq!(uri.parent(), None);
assert!(uri.starts_with(&uri));
assert!(!uri.starts_with(&root));
assert!(!uri.starts_with(&other));
assert!(!other.starts_with(&uri));
assert_eq!(uri.join(""), Ok(uri.clone()));
assert_eq!(
uri.join("child"),
@@ -698,6 +705,58 @@ fn join_uses_the_base_uri_path_convention() {
}
}
#[test]
fn starts_with_uses_uri_segment_boundaries() {
for (path, base, expected) in [
("file:///workspace/plugin", "file:///", true),
("file:///workspace/plugin", "file:///workspace/plugin", true),
(
"file:///workspace/plugin/assets/icon.svg",
"file:///workspace/plugin",
true,
),
(
"file:///workspace/plugin-other/icon.svg",
"file:///workspace/plugin",
false,
),
(
"file:///C:/plugins/foo/assets/icon.svg",
"file:///C:/plugins/foo",
true,
),
(
"file:///C:/plugins/foo2/assets/icon.svg",
"file:///C:/plugins/foo",
false,
),
(
"file://server/share/plugins/foo/icon.svg",
"file://server/share/plugins/foo",
true,
),
(
"file://other/share/plugins/foo/icon.svg",
"file://server/share/plugins/foo",
false,
),
(
"file:///workspace/plugin/%2F..%2Foutside",
"file:///workspace/plugin",
false,
),
(
"file:///workspace/plugin/%5C..%5Coutside",
"file:///workspace/plugin",
false,
),
] {
let path = PathUri::parse(path).expect("valid path URI");
let base = PathUri::parse(base).expect("valid base URI");
assert_eq!(path.starts_with(&base), expected);
}
}
#[test]
fn to_url_returns_the_validated_url() {
let uri = PathUri::parse("file://localhost/workspace/a%20file.rs").expect("valid file URI");
+2
View File
@@ -14,9 +14,11 @@
"@modelcontextprotocol/sdk": "1.26.0",
"braces": "^3.0.3",
"esbuild": "0.28.1",
"fast-uri": "3.1.1",
"flatted": "3.4.2",
"glob@10.4.5": "10.5.0",
"handlebars": "4.7.9",
"hono": "4.12.25",
"micromatch": "^4.0.8",
"minimatch@3.1.2": "3.1.4",
"minimatch@9.0.5": "9.0.7",
+14 -12
View File
@@ -8,9 +8,11 @@ overrides:
'@modelcontextprotocol/sdk': 1.26.0
braces: ^3.0.3
esbuild: 0.28.1
fast-uri: 3.1.1
flatted: 3.4.2
glob@10.4.5: 10.5.0
handlebars: 4.7.9
hono: 4.12.25
micromatch: ^4.0.8
minimatch@3.1.2: 3.1.4
minimatch@9.0.5: 9.0.7
@@ -455,7 +457,7 @@ packages:
resolution: {integrity: sha512-TsQLe4i2gvoTtrHje625ngThGBySOgSK3Xo2XRYOdqGN1teR8+I7vchQC46uLJi8OF62YTYA3AhSpumtkhsaKQ==}
engines: {node: '>=18.14.1'}
peerDependencies:
hono: ^4
hono: 4.12.25
'@humanfs/core@0.19.1':
resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==}
@@ -1341,8 +1343,8 @@ packages:
fast-levenshtein@2.0.6:
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
fast-uri@3.1.0:
resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==}
fast-uri@3.1.1:
resolution: {integrity: sha512-h2r7rcm6Ee/J8o0LD5djLuFVcfbZxhvho4vvsbeV0aMvXjUgqv4YpxpkEx0d68l6+IleVfLAdVEfhR7QNMkGHQ==}
fastq@1.19.1:
resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==}
@@ -1484,8 +1486,8 @@ packages:
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
engines: {node: '>= 0.4'}
hono@4.12.12:
resolution: {integrity: sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==}
hono@4.12.25:
resolution: {integrity: sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==}
engines: {node: '>=16.9.0'}
html-escaper@2.0.2:
@@ -2873,9 +2875,9 @@ snapshots:
'@eslint/core': 0.15.2
levn: 0.4.1
'@hono/node-server@1.19.13(hono@4.12.12)':
'@hono/node-server@1.19.13(hono@4.12.25)':
dependencies:
hono: 4.12.12
hono: 4.12.25
'@humanfs/core@0.19.1': {}
@@ -3095,7 +3097,7 @@ snapshots:
'@modelcontextprotocol/sdk@1.26.0(zod@3.25.76)':
dependencies:
'@hono/node-server': 1.19.13(hono@4.12.12)
'@hono/node-server': 1.19.13(hono@4.12.25)
ajv: 8.17.1
ajv-formats: 3.0.1(ajv@8.17.1)
content-type: 1.0.5
@@ -3105,7 +3107,7 @@ snapshots:
eventsource-parser: 3.0.6
express: 5.2.1
express-rate-limit: 8.3.2(express@5.2.1)
hono: 4.12.12
hono: 4.12.25
jose: 6.1.3
json-schema-typed: 8.0.2
pkce-challenge: 5.0.0
@@ -3401,7 +3403,7 @@ snapshots:
ajv@8.17.1:
dependencies:
fast-deep-equal: 3.1.3
fast-uri: 3.1.0
fast-uri: 3.1.1
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@@ -3905,7 +3907,7 @@ snapshots:
fast-levenshtein@2.0.6: {}
fast-uri@3.1.0: {}
fast-uri@3.1.1: {}
fastq@1.19.1:
dependencies:
@@ -4054,7 +4056,7 @@ snapshots:
dependencies:
function-bind: 1.1.2
hono@4.12.12: {}
hono@4.12.25: {}
html-escaper@2.0.2: {}