diff --git a/codex-rs/core/src/agents_md.rs b/codex-rs/core/src/agents_md.rs index 08983d72ff..570260be03 100644 --- a/codex-rs/core/src/agents_md.rs +++ b/codex-rs/core/src/agents_md.rs @@ -30,6 +30,8 @@ use codex_exec_server::ReadFileOptions; use codex_extension_api::Instructions; use codex_file_system::FileSystemSandboxContext; use codex_file_system::FindUpErrorPolicy; +use codex_file_system::MAX_METADATA_BATCH_BYTES; +use codex_file_system::MAX_METADATA_BATCH_PROBES; use codex_file_system::find_nearest_ancestor_with_markers; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathConvention; @@ -219,6 +221,13 @@ async fn agents_md_paths( default_project_root_markers() } }; + let filenames = candidate_filenames(config, cwd); + match batched_instruction_paths(fs, cwd, &project_root_markers, &filenames, sandbox).await { + Ok(paths) => return Ok(paths), + Err(err) if err.kind() == io::ErrorKind::Unsupported => {} + Err(err) => return Err(err), + } + let project_root = find_nearest_ancestor_with_markers( fs, &dir, @@ -246,22 +255,18 @@ async fn agents_md_paths( vec![dir] }; - let candidate_filenames = candidate_filenames(config, cwd); - let candidate_filenames = &candidate_filenames; + let candidate_filenames = &filenames; let mut results = futures::stream::iter(search_dirs) .map(|directory| async move { for name in candidate_filenames { let candidate = directory .join(name) .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?; - match fs + let metadata = fs .get_metadata(&candidate, GetMetadataOptions::default(), sandbox) - .await - { - Ok(metadata) if metadata.is_file => return Ok(Some(candidate)), - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => return Err(err), + .await; + if let Some(result) = select_instruction(candidate, metadata) { + return result.map(Some); } } Ok(None) @@ -276,6 +281,96 @@ async fn agents_md_paths( Ok(found) } +/// Start with the working directory, which is always in scope. The first batch +/// also checks root markers to find any other directories to include. Each round +/// checks just the next filename in each unresolved directory. +async fn batched_instruction_paths( + fs: &dyn ExecutorFileSystem, + cwd: &PathUri, + markers: &[String], + names: &[&str], + sandbox: Option<&FileSystemSandboxContext>, +) -> io::Result> { + let search_directory = |dir| (dir, names.iter(), None); + let mut directories = vec![search_directory(cwd.clone())]; + let mut check_markers = !markers.is_empty(); + + loop { + let mut paths = Vec::new(); + let mut bytes = 0usize; + let mut add_path = |dir: &PathUri, name: &str| { + let path = dir.join(name).map_err(|_| io::ErrorKind::Unsupported)?; + bytes = bytes.saturating_add(path.to_string().len()); + if paths.len() >= MAX_METADATA_BATCH_PROBES || bytes > MAX_METADATA_BATCH_BYTES { + return Err(io::ErrorKind::Unsupported); + } + paths.push(path); + Ok(()) + }; + let mut instruction_slots = Vec::new(); + for (dir, remaining, found) in directories.iter_mut().rev() { + if matches!(found, Some(Err(_))) { + break; + } + if found.is_none() + && let Some(name) = remaining.next() + { + add_path(dir, name)?; + instruction_slots.push(found); + } + } + if instruction_slots.is_empty() { + break; + } + + if check_markers { + for dir in cwd.ancestors() { + for marker in markers { + add_path(&dir, marker)?; + } + } + check_markers = false; + } + + let results = fs + .get_metadata_batch(&paths, GetMetadataOptions::default(), sandbox) + .await?; + if results.len() != paths.len() { + return Err(io::ErrorKind::InvalidData.into()); + } + + // Marker results, when present, follow the instruction results, nearest directory first. + let nearest_marker = results[instruction_slots.len()..] + .iter() + .position(Result::is_ok); + for ((slot, path), result) in instruction_slots.into_iter().zip(paths).zip(results) { + *slot = select_instruction(path, result); + } + + if let Some(index) = nearest_marker { + let depth = index / markers.len(); + directories.extend(cwd.ancestors().skip(1).take(depth).map(search_directory)); + } + } + directories + .into_iter() + .rev() + .filter_map(|(_, _, found)| found) + .collect() +} + +fn select_instruction( + path: PathUri, + result: io::Result, +) -> Option> { + match result { + Ok(metadata) if metadata.is_file => Some(Ok(path)), + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(err) => Some(Err(err)), + } +} + fn candidate_filenames<'a>(config: &'a Config, cwd: &PathUri) -> Vec<&'a str> { let mut names: Vec<&str> = Vec::with_capacity(2 + config.project_doc_fallback_filenames.len()); names.push(LOCAL_AGENTS_MD_FILENAME); diff --git a/codex-rs/core/src/agents_md_tests.rs b/codex-rs/core/src/agents_md_tests.rs index 354c5d21a5..06ebbc96ca 100644 --- a/codex-rs/core/src/agents_md_tests.rs +++ b/codex-rs/core/src/agents_md_tests.rs @@ -46,6 +46,8 @@ use std::ops::DerefMut; use std::path::PathBuf; use std::sync::Arc; use std::sync::Mutex; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use tempfile::TempDir; use tokio::sync::Notify; use tokio::sync::Semaphore; @@ -67,6 +69,7 @@ struct FailingFileSystem { } struct MetadataCallCounts { + batch_calls: Option>, paths: Mutex>, started: Notify, release: Semaphore, @@ -75,6 +78,7 @@ struct MetadataCallCounts { impl Default for MetadataCallCounts { fn default() -> Self { Self { + batch_calls: None, paths: Mutex::new(Vec::new()), started: Notify::new(), release: Semaphore::new(0), @@ -272,6 +276,21 @@ impl ExecutorFileSystem for FailingFileSystem { )) } + fn get_metadata_batch<'a>( + &'a self, + paths: &'a [PathUri], + options: GetMetadataOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + Box::pin(async move { + let Some(calls) = &self.metadata_calls.batch_calls else { + return Err(io::ErrorKind::Unsupported.into()); + }; + calls.fetch_add(1, Ordering::Relaxed); + codex_file_system::resolve_metadata_batch(self, paths, options, sandbox).await + }) + } + fn read_directory<'a>( &'a self, path: &'a PathUri, @@ -1103,6 +1122,30 @@ async fn finds_doc_in_repo_root() { let res = get_user_instructions(&cfg).await.expect("doc expected"); assert_eq!(res, "root level doc"); + let batch_calls = Arc::new(AtomicUsize::new(0)); + let metadata_calls = Arc::new(MetadataCallCounts { + batch_calls: Some(Arc::clone(&batch_calls)), + ..MetadataCallCounts::default() + }); + let filesystem = FailingFileSystem { + path: cfg.cwd.join("unused"), + failure: InjectedFailure::Read(io::ErrorKind::PermissionDenied), + metadata_calls: Arc::clone(&metadata_calls), + }; + let cwd = PathUri::from_abs_path(&cfg.cwd); + assert_eq!( + super::agents_md_paths(&cfg.config, &cwd, &filesystem, /*sandbox*/ None) + .await + .expect("batched nested discovery"), + vec![PathUri::from_abs_path(&repo.path().join("AGENTS.md").abs())] + ); + assert_eq!(batch_calls.load(Ordering::Relaxed), 3); + batch_calls.store(0, Ordering::Relaxed); + let cwd = PathUri::from_abs_path(&repo.abs()); + super::agents_md_paths(&cfg.config, &cwd, &filesystem, /*sandbox*/ None) + .await + .expect("batched shallow discovery"); + assert_eq!(batch_calls.load(Ordering::Relaxed), 2); } /// Explicitly setting the byte-limit to zero disables project docs. diff --git a/codex-rs/exec-server-protocol/src/protocol.rs b/codex-rs/exec-server-protocol/src/protocol.rs index 5977f8caa5..539f94f689 100644 --- a/codex-rs/exec-server-protocol/src/protocol.rs +++ b/codex-rs/exec-server-protocol/src/protocol.rs @@ -42,6 +42,7 @@ pub const FS_CLOSE_METHOD: &str = "fs/close"; pub const FS_WRITE_FILE_METHOD: &str = "fs/writeFile"; pub const FS_CREATE_DIRECTORY_METHOD: &str = "fs/createDirectory"; pub const FS_GET_METADATA_METHOD: &str = "fs/getMetadata"; +pub const FS_GET_METADATA_BATCH_METHOD: &str = "fs/getMetadataBatch"; pub const FS_WATCH_MISSING_METHOD: &str = "fs/watchMissing"; pub const FS_MISSING_CHANGED_METHOD: &str = "fs/missingChanged"; pub const FS_CANONICALIZE_METHOD: &str = "fs/canonicalize"; @@ -170,6 +171,9 @@ pub struct EnvironmentCapabilities { /// Whether capability discovery applies the filesystem sandbox sent with each root. #[serde(default)] pub capability_discovery_sandbox: bool, + /// Whether this executor supports ordered per-path metadata results in one request. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub fs_metadata_batch: bool, /// Whether missing metadata paths can be watched on this physical connection. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub fs_watch_missing: bool, @@ -330,6 +334,7 @@ impl EnvironmentInfo { credential_masking, credential_masking_custom_providers: credential_masking, capability_discovery_sandbox: true, + fs_metadata_batch: true, fs_watch_missing: cfg!(target_os = "linux"), capability_discovery_v2: true, environment_config_read: true, @@ -796,6 +801,21 @@ pub struct FsGetMetadataParams { pub sandbox: Option, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FsGetMetadataBatchParams { + pub paths: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub follow_symlinks: Option, + pub sandbox: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FsGetMetadataBatchResponse { + pub results: Vec>, +} + /// One unsandboxed metadata observation per connection. A newer id supersedes the prior watch. #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1612,6 +1632,7 @@ mod tests { credential_masking: false, credential_masking_custom_providers: false, capability_discovery_sandbox: true, + fs_metadata_batch: false, fs_watch_missing: false, capability_discovery_v2: false, environment_config_read: false, diff --git a/codex-rs/exec-server/README.md b/codex-rs/exec-server/README.md index 20f4a2af72..fcbfbee532 100644 --- a/codex-rs/exec-server/README.md +++ b/codex-rs/exec-server/README.md @@ -470,6 +470,7 @@ callers must convert them to `file:` URIs before sending requests: reads also back `ExecutorFileSystem::read_file_stream`) - `fs/writeFile` - `fs/createDirectory` +- `fs/getMetadataBatch` (requires `fsMetadataBatch`, returns metadata or an error for each input path in the same order) - `fs/getMetadata` - `fs/canonicalize` - `fs/readDirectory` diff --git a/codex-rs/exec-server/src/client.rs b/codex-rs/exec-server/src/client.rs index 9d7ea0683d..c5d94e1e9b 100644 --- a/codex-rs/exec-server/src/client.rs +++ b/codex-rs/exec-server/src/client.rs @@ -77,6 +77,7 @@ use crate::protocol::FS_CANONICALIZE_METHOD; use crate::protocol::FS_CLOSE_METHOD; use crate::protocol::FS_COPY_METHOD; use crate::protocol::FS_CREATE_DIRECTORY_METHOD; +use crate::protocol::FS_GET_METADATA_BATCH_METHOD; use crate::protocol::FS_GET_METADATA_METHOD; use crate::protocol::FS_OPEN_METHOD; use crate::protocol::FS_READ_BLOCK_METHOD; @@ -94,6 +95,8 @@ use crate::protocol::FsCopyParams; use crate::protocol::FsCopyResponse; use crate::protocol::FsCreateDirectoryParams; use crate::protocol::FsCreateDirectoryResponse; +use crate::protocol::FsGetMetadataBatchParams; +use crate::protocol::FsGetMetadataBatchResponse; use crate::protocol::FsGetMetadataParams; use crate::protocol::FsGetMetadataResponse; use crate::protocol::FsOpenMode; @@ -1086,6 +1089,20 @@ impl ExecServerClient { .await?) } + pub(crate) fn supports_metadata_batch(&self) -> bool { + self.inner + .environment_info + .get() + .is_some_and(|info| info.capabilities.fs_metadata_batch) + } + + pub(crate) async fn fs_get_metadata_batch( + &self, + params: FsGetMetadataBatchParams, + ) -> Result { + self.call(FS_GET_METADATA_BATCH_METHOD, ¶ms).await + } + pub async fn fs_get_metadata( &self, params: FsGetMetadataParams, diff --git a/codex-rs/exec-server/src/fs_helper.rs b/codex-rs/exec-server/src/fs_helper.rs index d30766370c..75a04b77ce 100644 --- a/codex-rs/exec-server/src/fs_helper.rs +++ b/codex-rs/exec-server/src/fs_helper.rs @@ -24,6 +24,7 @@ use crate::protocol::CAPABILITY_ROOTS_DISCOVER_METHOD; use crate::protocol::FS_CANONICALIZE_METHOD; use crate::protocol::FS_COPY_METHOD; use crate::protocol::FS_CREATE_DIRECTORY_METHOD; +use crate::protocol::FS_GET_METADATA_BATCH_METHOD; use crate::protocol::FS_GET_METADATA_METHOD; use crate::protocol::FS_OPEN_METHOD; use crate::protocol::FS_READ_DIRECTORY_METHOD; @@ -37,6 +38,8 @@ use crate::protocol::FsCopyParams; use crate::protocol::FsCopyResponse; use crate::protocol::FsCreateDirectoryParams; use crate::protocol::FsCreateDirectoryResponse; +use crate::protocol::FsGetMetadataBatchParams; +use crate::protocol::FsGetMetadataBatchResponse; use crate::protocol::FsGetMetadataParams; use crate::protocol::FsGetMetadataResponse; use crate::protocol::FsOpenMode; @@ -77,6 +80,8 @@ pub(crate) enum FsHelperRequest { CreateDirectory(FsCreateDirectoryParams), #[serde(rename = "fs/getMetadata")] GetMetadata(FsGetMetadataParams), + #[serde(rename = "fs/getMetadataBatch")] + GetMetadataBatch(FsGetMetadataBatchParams), #[serde(rename = "fs/canonicalize")] Canonicalize(FsCanonicalizeParams), #[serde(rename = "fs/readDirectory")] @@ -115,7 +120,7 @@ pub(crate) struct FsHelperOpenResponse { pub(crate) file_handle: u64, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "operation", content = "response")] pub(crate) enum FsHelperPayload { #[serde(rename = "capabilities/loadDiscoveries")] @@ -132,6 +137,8 @@ pub(crate) enum FsHelperPayload { CreateDirectory(FsCreateDirectoryResponse), #[serde(rename = "fs/getMetadata")] GetMetadata(FsGetMetadataResponse), + #[serde(rename = "fs/getMetadataBatch")] + GetMetadataBatch(FsGetMetadataBatchResponse), #[serde(rename = "fs/canonicalize")] Canonicalize(FsCanonicalizeResponse), #[serde(rename = "fs/readDirectory")] @@ -154,6 +161,7 @@ impl FsHelperPayload { Self::WriteFile(_) => FS_WRITE_FILE_METHOD, Self::CreateDirectory(_) => FS_CREATE_DIRECTORY_METHOD, Self::GetMetadata(_) => FS_GET_METADATA_METHOD, + Self::GetMetadataBatch(_) => FS_GET_METADATA_BATCH_METHOD, Self::Canonicalize(_) => FS_CANONICALIZE_METHOD, Self::ReadDirectory(_) => FS_READ_DIRECTORY_METHOD, Self::Walk(_) => FS_WALK_METHOD, @@ -222,6 +230,18 @@ impl FsHelperPayload { } } + pub(crate) fn expect_get_metadata_batch( + self, + ) -> Result { + match self { + Self::GetMetadataBatch(response) => Ok(response), + other => Err(unexpected_response( + FS_GET_METADATA_BATCH_METHOD, + other.operation(), + )), + } + } + pub(crate) fn expect_canonicalize(self) -> Result { match self { Self::Canonicalize(response) => Ok(response), @@ -366,6 +386,21 @@ pub(crate) async fn run_direct_request( modified_at_ms: metadata.modified_at_ms, })) } + FsHelperRequest::GetMetadataBatch(params) => { + let results = codex_file_system::resolve_metadata_batch( + &file_system, + ¶ms.paths, + GetMetadataOptions { + follow_symlinks: params.follow_symlinks.unwrap_or(true), + }, + /*sandbox*/ None, + ) + .await + .map_err(map_fs_error)?; + Ok(FsHelperPayload::GetMetadataBatch(encode_metadata_batch( + results, + ))) + } FsHelperRequest::Canonicalize(params) => { let path = file_system .canonicalize(¶ms.path, /*sandbox*/ None) @@ -430,6 +465,34 @@ pub(crate) async fn run_direct_request( } } +pub(crate) fn encode_metadata_batch( + results: Vec>, +) -> FsGetMetadataBatchResponse { + FsGetMetadataBatchResponse { + results: results + .into_iter() + .map(|result| result.map_err(map_fs_error)) + .collect(), + } +} + +pub(crate) fn decode_metadata_batch( + response: FsGetMetadataBatchResponse, + expected: usize, +) -> io::Result>> { + if response.results.len() != expected { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid metadata batch response", + )); + } + Ok(response + .results + .into_iter() + .map(|result| result.map_err(crate::sandboxed_file_system::map_sandbox_error)) + .collect()) +} + pub(crate) fn map_fs_error(err: io::Error) -> JSONRPCErrorError { match err.kind() { io::ErrorKind::NotFound => not_found(err.to_string()), diff --git a/codex-rs/exec-server/src/local_file_system.rs b/codex-rs/exec-server/src/local_file_system.rs index abe2a0a6f1..fc7f710f54 100644 --- a/codex-rs/exec-server/src/local_file_system.rs +++ b/codex-rs/exec-server/src/local_file_system.rs @@ -344,6 +344,18 @@ impl ExecutorFileSystem for LocalFileSystem { Box::pin(LocalFileSystem::get_metadata(self, path, options, sandbox)) } + fn get_metadata_batch<'a>( + &'a self, + paths: &'a [PathUri], + options: GetMetadataOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + Box::pin(async move { + let (fs, sandbox) = self.file_system_for_reads(sandbox)?; + fs.get_metadata_batch(paths, options, sandbox).await + }) + } + fn read_directory<'a>( &'a self, path: &'a PathUri, diff --git a/codex-rs/exec-server/src/remote_file_system.rs b/codex-rs/exec-server/src/remote_file_system.rs index 06762ed9b4..7d946a2119 100644 --- a/codex-rs/exec-server/src/remote_file_system.rs +++ b/codex-rs/exec-server/src/remote_file_system.rs @@ -7,6 +7,7 @@ use base64::Engine as _; use base64::engine::general_purpose::STANDARD; use bytes::Bytes; use codex_file_system::FILE_WRITE_CHUNK_SIZE; +use codex_file_system::metadata_batch_fits; use codex_protocol::models::ManagedFileSystemPermissions; use codex_protocol::models::PermissionProfile; use codex_protocol::permissions::FileSystemPath; @@ -43,6 +44,7 @@ use crate::protocol::FsCanonicalizeParams; use crate::protocol::FsCloseParams; use crate::protocol::FsCopyParams; use crate::protocol::FsCreateDirectoryParams; +use crate::protocol::FsGetMetadataBatchParams; use crate::protocol::FsGetMetadataParams; use crate::protocol::FsOpenMode; use crate::protocol::FsOpenParams; @@ -499,6 +501,38 @@ impl ExecutorFileSystem for RemoteFileSystem { Box::pin(RemoteFileSystem::get_metadata(self, path, options, sandbox)) } + fn get_metadata_batch<'a>( + &'a self, + paths: &'a [PathUri], + options: GetMetadataOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + Box::pin(async move { + let Some((first_path, rest)) = paths.split_first() else { + return Ok(Vec::new()); + }; + let client = self.client.get().await.map_err(map_remote_error)?; + let convention = first_path.infer_path_convention(); + if !client.supports_metadata_batch() + || !metadata_batch_fits(paths) + || rest + .iter() + .any(|path| path.infer_path_convention() != convention) + { + return Err(io::ErrorKind::Unsupported.into()); + } + let response = client + .fs_get_metadata_batch(FsGetMetadataBatchParams { + paths: paths.to_vec(), + follow_symlinks: (!options.follow_symlinks).then_some(false), + sandbox: read_sandbox(&client, first_path, sandbox).await?.cloned(), + }) + .await + .map_err(map_remote_error)?; + crate::fs_helper::decode_metadata_batch(response, paths.len()) + }) + } + fn read_directory<'a>( &'a self, path: &'a PathUri, diff --git a/codex-rs/exec-server/src/sandboxed_file_system.rs b/codex-rs/exec-server/src/sandboxed_file_system.rs index f1fedc9f53..a3c3e22dd4 100644 --- a/codex-rs/exec-server/src/sandboxed_file_system.rs +++ b/codex-rs/exec-server/src/sandboxed_file_system.rs @@ -1,6 +1,7 @@ use base64::Engine as _; use base64::engine::general_purpose::STANDARD; use codex_exec_server_protocol::JSONRPCErrorError; +use codex_file_system::metadata_batch_fits; use codex_utils_path_uri::PathUri; use tokio::io; use tokio_util::io::ReaderStream; @@ -32,6 +33,7 @@ use crate::fs_sandbox::FileSystemSandboxRunner; use crate::protocol::FsCanonicalizeParams; use crate::protocol::FsCopyParams; use crate::protocol::FsCreateDirectoryParams; +use crate::protocol::FsGetMetadataBatchParams; use crate::protocol::FsGetMetadataParams; use crate::protocol::FsOpenMode; use crate::protocol::FsReadDirectoryParams; @@ -412,6 +414,36 @@ impl ExecutorFileSystem for SandboxedFileSystem { )) } + fn get_metadata_batch<'a>( + &'a self, + paths: &'a [PathUri], + options: GetMetadataOptions, + sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + Box::pin(async move { + if paths.is_empty() { + return Ok(Vec::new()); + } + if !metadata_batch_fits(paths) { + return Err(io::ErrorKind::Unsupported.into()); + } + let sandbox = require_platform_sandbox(sandbox)?; + let response = self + .run_sandboxed( + sandbox, + FsHelperRequest::GetMetadataBatch(FsGetMetadataBatchParams { + paths: paths.to_vec(), + follow_symlinks: (!options.follow_symlinks).then_some(false), + sandbox: None, + }), + ) + .await? + .expect_get_metadata_batch() + .map_err(map_sandbox_error)?; + crate::fs_helper::decode_metadata_batch(response, paths.len()) + }) + } + fn read_directory<'a>( &'a self, path: &'a PathUri, @@ -477,7 +509,7 @@ fn require_platform_sandbox( }) } -fn map_sandbox_error(error: JSONRPCErrorError) -> io::Error { +pub(crate) fn map_sandbox_error(error: JSONRPCErrorError) -> io::Error { match error.code { -32004 => io::Error::new(io::ErrorKind::NotFound, error.message), -32600 => io::Error::new(io::ErrorKind::InvalidInput, error.message), diff --git a/codex-rs/exec-server/src/server/file_system_handler.rs b/codex-rs/exec-server/src/server/file_system_handler.rs index fe5bd75d3f..d345630696 100644 --- a/codex-rs/exec-server/src/server/file_system_handler.rs +++ b/codex-rs/exec-server/src/server/file_system_handler.rs @@ -26,6 +26,8 @@ use crate::protocol::FsCopyParams; use crate::protocol::FsCopyResponse; use crate::protocol::FsCreateDirectoryParams; use crate::protocol::FsCreateDirectoryResponse; +use crate::protocol::FsGetMetadataBatchParams; +use crate::protocol::FsGetMetadataBatchResponse; use crate::protocol::FsGetMetadataParams; use crate::protocol::FsGetMetadataResponse; use crate::protocol::FsOpenParams; @@ -235,6 +237,38 @@ impl FileSystemHandler { Ok(FsCreateDirectoryResponse {}) } + pub(crate) async fn get_metadata_batch( + &self, + params: FsGetMetadataBatchParams, + ) -> Result { + if !codex_file_system::metadata_batch_fits(¶ms.paths) { + return Err(invalid_request( + "metadata batch exceeds size limit".to_string(), + )); + } + let options = GetMetadataOptions { + follow_symlinks: params.follow_symlinks.unwrap_or(true), + }; + let results = match self + .file_system + .get_metadata_batch(¶ms.paths, options, params.sandbox.as_ref()) + .await + { + Err(error) if error.kind() == io::ErrorKind::Unsupported => { + codex_file_system::resolve_metadata_batch( + &self.file_system, + ¶ms.paths, + options, + params.sandbox.as_ref(), + ) + .await + } + result => result, + } + .map_err(map_fs_error)?; + Ok(crate::fs_helper::encode_metadata_batch(results)) + } + pub(crate) async fn get_metadata( &self, params: FsGetMetadataParams, diff --git a/codex-rs/exec-server/src/server/handler.rs b/codex-rs/exec-server/src/server/handler.rs index 37737d782c..6613e9f377 100644 --- a/codex-rs/exec-server/src/server/handler.rs +++ b/codex-rs/exec-server/src/server/handler.rs @@ -39,6 +39,8 @@ use crate::protocol::FsCopyParams; use crate::protocol::FsCopyResponse; use crate::protocol::FsCreateDirectoryParams; use crate::protocol::FsCreateDirectoryResponse; +use crate::protocol::FsGetMetadataBatchParams; +use crate::protocol::FsGetMetadataBatchResponse; use crate::protocol::FsGetMetadataParams; use crate::protocol::FsGetMetadataResponse; use crate::protocol::FsOpenParams; @@ -419,6 +421,14 @@ impl ExecServerHandler { .map_err(|error| crate::rpc::internal_error(error.to_string()))? } + pub(crate) async fn fs_get_metadata_batch( + &self, + params: FsGetMetadataBatchParams, + ) -> Result { + self.require_initialized_for("filesystem")?; + self.file_system.get_metadata_batch(params).await + } + pub(crate) async fn fs_get_metadata( &self, params: FsGetMetadataParams, diff --git a/codex-rs/exec-server/src/server/registry.rs b/codex-rs/exec-server/src/server/registry.rs index 46690ba83c..e82fd9d08d 100644 --- a/codex-rs/exec-server/src/server/registry.rs +++ b/codex-rs/exec-server/src/server/registry.rs @@ -21,6 +21,7 @@ use crate::protocol::FS_CANONICALIZE_METHOD; use crate::protocol::FS_CLOSE_METHOD; use crate::protocol::FS_COPY_METHOD; use crate::protocol::FS_CREATE_DIRECTORY_METHOD; +use crate::protocol::FS_GET_METADATA_BATCH_METHOD; use crate::protocol::FS_GET_METADATA_METHOD; use crate::protocol::FS_OPEN_METHOD; use crate::protocol::FS_READ_BLOCK_METHOD; @@ -31,6 +32,7 @@ use crate::protocol::FS_WALK_METHOD; use crate::protocol::FS_WRITE_BLOCK_METHOD; use crate::protocol::FS_WRITE_FILE_METHOD; use crate::protocol::FsCloseParams; +use crate::protocol::FsGetMetadataBatchParams; use crate::protocol::FsReadBlockParams; use crate::protocol::FsWriteBlockParams; use crate::protocol::HTTP_REQUEST_METHOD; @@ -193,6 +195,12 @@ pub(crate) fn build_router() -> RpcRouter { handler.fs_watch_missing(params).await }, ); + router.request( + FS_GET_METADATA_BATCH_METHOD, + |handler: Arc, params: FsGetMetadataBatchParams| async move { + handler.fs_get_metadata_batch(params).await + }, + ); router.request( FS_GET_METADATA_METHOD, |handler: Arc, params: WireFsGetMetadataParams| async move { diff --git a/codex-rs/exec-server/tests/file_system/shared.rs b/codex-rs/exec-server/tests/file_system/shared.rs index 1ecefb5e64..961ce816f7 100644 --- a/codex-rs/exec-server/tests/file_system/shared.rs +++ b/codex-rs/exec-server/tests/file_system/shared.rs @@ -131,6 +131,49 @@ async fn file_system_get_metadata_reports_files_and_directories( ); assert!(directory_metadata.modified_at_ms > 0); + let nested = directory_path.join("note.txt"); + std::fs::write(&nested, "nested")?; + let paths = [ + PathUri::from_host_native_path(&nested)?, + PathUri::from_host_native_path(tmp.path().join("missing"))?, + PathUri::from_host_native_path(&directory_path)?, + ]; + let batch = file_system + .get_metadata_batch(&paths, Default::default(), /*sandbox*/ None) + .await; + if matches!(implementation, FileSystemImplementation::Local) { + assert_eq!( + batch + .expect_err("unrestricted local metadata keeps the original short-circuit path") + .kind(), + std::io::ErrorKind::Unsupported + ); + return Ok(()); + } + let results = batch?; + assert_eq!(results.len(), paths.len()); + assert!(results[0].as_ref().expect("file metadata").is_file); + assert_eq!( + results[1].as_ref().expect_err("missing metadata").kind(), + std::io::ErrorKind::NotFound + ); + assert!( + results[2] + .as_ref() + .expect("directory metadata") + .is_directory + ); + #[cfg(unix)] + { + std::fs::remove_file(&nested)?; + std::os::unix::fs::symlink("note.txt", &nested)?; + let results = file_system + .get_metadata_batch(&paths, Default::default(), /*sandbox*/ None) + .await?; + assert!(results[0].is_err(), "individual path errors are preserved"); + assert!(results[2].as_ref().expect("later result").is_directory); + } + Ok(()) } diff --git a/codex-rs/ext/skills/src/host_roots.rs b/codex-rs/ext/skills/src/host_roots.rs index 940b263dbb..69bdf9bc9b 100644 --- a/codex-rs/ext/skills/src/host_roots.rs +++ b/codex-rs/ext/skills/src/host_roots.rs @@ -10,6 +10,7 @@ use codex_config::merge_toml_values; use codex_config::project_root_markers_from_config; use codex_exec_server::EnvironmentAccess; use codex_exec_server::EnvironmentAccessKey; +use codex_exec_server::FileMetadata; use codex_exec_server::FileSystemEnvironmentAccessor; use codex_exec_server::GetMetadataOptions; use codex_exec_server::LOCAL_FS; @@ -239,20 +240,18 @@ async fn repo_agents_skill_roots<'a>( cwd, ) .await; - let directories = dirs_between_project_root_and_cwd(cwd, &project_root); + let mut candidates = Vec::new(); + for directory in cwd.ancestors() { + candidates.push(directory.join(AGENTS_DIR_NAME).join(SKILLS_DIR_NAME)); + if directory == project_root { + break; + } + } + candidates.reverse(); + let results = skill_root_metadata(repository_fs_accessor, &candidates).await; let mut roots = Vec::new(); let mut missing = Vec::new(); - let mut results = futures::stream::iter(directories) - .map(|directory| async move { - let agents_skills = directory.join(AGENTS_DIR_NAME).join(SKILLS_DIR_NAME); - let agents_skills_uri = PathUri::from_abs_path(&agents_skills); - let result = repository_fs_accessor - .get_metadata(&agents_skills_uri, GetMetadataOptions::default()) - .await; - (agents_skills, result) - }) - .buffered(MAX_CONCURRENT_ANCESTOR_PROBES); - while let Some((agents_skills, result)) = results.next().await { + for (agents_skills, result) in candidates.into_iter().zip(results) { match result { Ok(metadata) if metadata.is_directory => roots.push(HostSkillRoot::host( agents_skills, @@ -332,6 +331,36 @@ async fn repo_agents_skill_roots<'a>( roots } +async fn skill_root_metadata( + fs: &dyn EnvironmentAccess, + paths: &[AbsolutePathBuf], +) -> Vec> { + let options = GetMetadataOptions::default(); + let mut results = Vec::with_capacity(paths.len()); + // Keep the existing probe concurrency limit inside each helper. If a batch fails, + // retry the remaining paths individually. + for chunk in paths.chunks(MAX_CONCURRENT_ANCESTOR_PROBES) { + if chunk.len() == 1 { + break; + } + let uris = chunk.iter().map(PathUri::from_abs_path).collect::>(); + match fs.get_metadata_batch(&uris, options).await { + Ok(batch) if batch.len() == chunk.len() => results.extend(batch), + _ => break, + } + } + let mut remaining = futures::stream::iter(results.len()..paths.len()) + .map(|index| async move { + fs.get_metadata(&PathUri::from_abs_path(&paths[index]), options) + .await + }) + .buffered(MAX_CONCURRENT_ANCESTOR_PROBES); + while let Some(metadata) = remaining.next().await { + results.push(metadata); + } + results +} + fn project_root_markers_from_stack(config_layer_stack: &ConfigLayerStack) -> Vec { let mut merged = TomlValue::Table(toml::map::Map::new()); for layer in config_layer_stack.layers_low_to_high() { @@ -419,27 +448,6 @@ async fn find_project_root( } } -fn dirs_between_project_root_and_cwd( - cwd: &AbsolutePathBuf, - project_root: &AbsolutePathBuf, -) -> Vec { - let mut directories = cwd - .ancestors() - .scan(false, |done, directory| { - if *done { - None - } else { - if &directory == project_root { - *done = true; - } - Some(directory) - } - }) - .collect::>(); - directories.reverse(); - directories -} - fn dedupe_skill_roots_by_path(roots: &mut Vec) { let mut seen = HashSet::new(); roots.retain(|root| seen.insert(root.path.clone())); diff --git a/codex-rs/file-system/src/environment_accessor.rs b/codex-rs/file-system/src/environment_accessor.rs index ed16a9f077..e0f54d7e74 100644 --- a/codex-rs/file-system/src/environment_accessor.rs +++ b/codex-rs/file-system/src/environment_accessor.rs @@ -82,6 +82,13 @@ pub trait EnvironmentAccess: Send + Sync { options: GetMetadataOptions, ) -> ExecutorFileSystemFuture<'a, FileMetadata>; + /// Get one metadata result per path using this accessor's captured permissions. + fn get_metadata_batch<'a>( + &'a self, + paths: &'a [PathUri], + options: GetMetadataOptions, + ) -> ExecutorFileSystemFuture<'a, Vec>>; + fn read_directory<'a>( &'a self, path: &'a PathUri, @@ -294,6 +301,15 @@ impl EnvironmentAccess for FileSystemEnvironmentAccessor<'_> { .get_metadata(path, options, self.key.sandbox.as_deref()) } + fn get_metadata_batch<'a>( + &'a self, + paths: &'a [PathUri], + options: GetMetadataOptions, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + self.file_system + .get_metadata_batch(paths, options, self.key.sandbox.as_deref()) + } + fn read_directory<'a>( &'a self, path: &'a PathUri, diff --git a/codex-rs/file-system/src/lib.rs b/codex-rs/file-system/src/lib.rs index 4756de18de..a0b0e29fd9 100644 --- a/codex-rs/file-system/src/lib.rs +++ b/codex-rs/file-system/src/lib.rs @@ -2,6 +2,7 @@ mod environment_accessor; mod exec_permission_profile_serde; mod find_up; mod local_logs; +mod metadata_batch; mod nfs; use bytes::Bytes; @@ -29,6 +30,10 @@ pub use find_up::find_nearest_native_ancestor_with_markers; use futures::Stream; use futures::stream::BoxStream; pub use local_logs::LocalLogsDir; +pub use metadata_batch::MAX_METADATA_BATCH_BYTES; +pub use metadata_batch::MAX_METADATA_BATCH_PROBES; +pub use metadata_batch::metadata_batch_fits; +pub use metadata_batch::resolve_metadata_batch; pub use nfs::is_nfs; use serde::Deserialize; use serde::Serialize; @@ -112,7 +117,8 @@ pub struct CopyOptions { pub recursive: bool, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] pub struct FileMetadata { pub is_directory: bool, pub is_file: bool, @@ -716,6 +722,16 @@ pub trait ExecutorFileSystem: Send + Sync { sandbox: Option<&'a FileSystemSandboxContext>, ) -> ExecutorFileSystemFuture<'a, FileMetadata>; + /// Return one metadata result or error per input path, in the same order. + fn get_metadata_batch<'a>( + &'a self, + _paths: &'a [PathUri], + _options: GetMetadataOptions, + _sandbox: Option<&'a FileSystemSandboxContext>, + ) -> ExecutorFileSystemFuture<'a, Vec>> { + Box::pin(async { Err(io::ErrorKind::Unsupported.into()) }) + } + fn read_directory<'a>( &'a self, path: &'a PathUri, diff --git a/codex-rs/file-system/src/metadata_batch.rs b/codex-rs/file-system/src/metadata_batch.rs new file mode 100644 index 0000000000..cd34a3faa6 --- /dev/null +++ b/codex-rs/file-system/src/metadata_batch.rs @@ -0,0 +1,39 @@ +//! Bounded batches of independent metadata requests. +use crate::ExecutorFileSystem; +use crate::FileMetadata; +use crate::FileSystemSandboxContext; +use crate::GetMetadataOptions; +use codex_utils_path_uri::PathUri; +use futures::StreamExt; +use std::io; + +const MAX_CONCURRENT_PROBES: usize = 256; +pub const MAX_METADATA_BATCH_PROBES: usize = 1024; +pub const MAX_METADATA_BATCH_BYTES: usize = 1024 * 1024; + +/// Bound both the number of paths and encoded request bytes. +pub fn metadata_batch_fits(paths: &[PathUri]) -> bool { + paths.len() <= MAX_METADATA_BATCH_PROBES + && paths + .iter() + .try_fold(0usize, |bytes, path| { + bytes + .checked_add(path.to_string().len()) + .filter(|total| *total <= MAX_METADATA_BATCH_BYTES) + }) + .is_some() +} + +/// Fall back to individual calls while preserving each result and request order. +pub async fn resolve_metadata_batch( + fs: &(impl ExecutorFileSystem + ?Sized), + paths: &[PathUri], + options: GetMetadataOptions, + sandbox: Option<&FileSystemSandboxContext>, +) -> io::Result>> { + Ok(futures::stream::iter(0..paths.len()) + .map(|index: usize| async move { fs.get_metadata(&paths[index], options, sandbox).await }) + .buffered(MAX_CONCURRENT_PROBES) + .collect() + .await) +}