Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/utils/absolute-path/BUILD.bazel
Normal file
6
akode-rs/utils/absolute-path/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "absolute-path",
|
||||
crate_name = "akode_utils_absolute_path",
|
||||
)
|
||||
27
akode-rs/utils/absolute-path/Cargo.toml
Normal file
27
akode-rs/utils/absolute-path/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
|
||||
[package]
|
||||
name = "akode-utils-absolute-path"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
dirs = { workspace = true }
|
||||
dunce = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
ts-rs = { workspace = true, features = [
|
||||
"serde-json-impl",
|
||||
"no-serde-warnings",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
171
akode-rs/utils/absolute-path/src/absolutize.rs
Normal file
171
akode-rs/utils/absolute-path/src/absolutize.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
// Adapted from path-absolutize 3.1.1:
|
||||
// Copyright (c) 2018 magiclen.org (Ron Li)
|
||||
// Licensed under the MIT License.
|
||||
//
|
||||
// Keep this implementation local so explicit-base normalization can be
|
||||
// infallible for `AbsolutePathBuf::resolve_path_against_base` and
|
||||
// `AbsolutePathBuf::join`; only current-working-directory lookup remains
|
||||
// fallible.
|
||||
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) fn absolutize(path: &Path) -> std::io::Result<PathBuf> {
|
||||
if path.is_absolute() {
|
||||
return Ok(normalize_path(path));
|
||||
}
|
||||
|
||||
Ok(absolutize_from(path, &std::env::current_dir()?))
|
||||
}
|
||||
|
||||
pub(super) fn absolutize_from(path: &Path, base_path: &Path) -> PathBuf {
|
||||
normalize_path(&path_with_base(path, base_path))
|
||||
}
|
||||
|
||||
fn normalize_path(path: &Path) -> PathBuf {
|
||||
let mut normalized = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
normalized.pop();
|
||||
}
|
||||
Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
|
||||
normalized.push(component.as_os_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if normalized.as_os_str().is_empty() {
|
||||
PathBuf::from(".")
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn path_with_base(path: &Path, base_path: &Path) -> PathBuf {
|
||||
if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
base_path.join(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn path_with_base(path: &Path, base_path: &Path) -> PathBuf {
|
||||
if path.is_absolute() || path.has_root() {
|
||||
return base_path.join(path);
|
||||
}
|
||||
|
||||
let mut components = path.components();
|
||||
let Some(Component::Prefix(prefix)) = components.next() else {
|
||||
return base_path.join(path);
|
||||
};
|
||||
|
||||
let mut path = PathBuf::new();
|
||||
path.push(prefix.as_os_str());
|
||||
|
||||
if components.clone().next().is_none() {
|
||||
path.push(std::path::MAIN_SEPARATOR_STR);
|
||||
return path;
|
||||
}
|
||||
|
||||
let skip_base_prefix = matches!(base_path.components().next(), Some(Component::Prefix(_)));
|
||||
for component in base_path
|
||||
.components()
|
||||
.skip(usize::from(skip_base_prefix))
|
||||
.chain(components)
|
||||
{
|
||||
path.push(component.as_os_str());
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn absolute_path_without_dots_is_unchanged() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new("/path/to/123/456"), Path::new("/base")),
|
||||
PathBuf::from("/path/to/123/456")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn absolute_path_dots_are_removed() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new("/path/to/./123/../456"), Path::new("/base")),
|
||||
PathBuf::from("/path/to/456")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn relative_path_without_dot_uses_base() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new("path/to/123/456"), Path::new("/base")),
|
||||
PathBuf::from("/base/path/to/123/456")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn relative_path_with_current_dir_uses_base() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new("./path/to/123/456"), Path::new("/base")),
|
||||
PathBuf::from("/base/path/to/123/456")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn relative_path_with_parent_dir_uses_base_parent() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new("../path/to/123/456"), Path::new("/base/cwd")),
|
||||
PathBuf::from("/base/path/to/123/456")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn parent_dir_above_root_stays_at_root() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new("../../path/to/123/456"), Path::new("/")),
|
||||
PathBuf::from("/path/to/123/456")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn empty_path_uses_base() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new(""), Path::new("/base/cwd")),
|
||||
PathBuf::from("/base/cwd")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_root_relative_path_uses_base_prefix() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new(r"\path\to\file"), Path::new(r"C:\base\cwd")),
|
||||
PathBuf::from(r"C:\path\to\file")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_drive_relative_path_uses_path_prefix_and_base_tail() {
|
||||
assert_eq!(
|
||||
absolutize_from(Path::new(r"D:path\to\file"), Path::new(r"C:\base\cwd")),
|
||||
PathBuf::from(r"D:\base\cwd\path\to\file")
|
||||
);
|
||||
}
|
||||
}
|
||||
797
akode-rs/utils/absolute-path/src/lib.rs
Normal file
797
akode-rs/utils/absolute-path/src/lib.rs
Normal file
@@ -0,0 +1,797 @@
|
||||
use dirs::home_dir;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::Error as SerdeError;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::path::Display;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use ts_rs::TS;
|
||||
|
||||
mod absolutize;
|
||||
mod system_aliases;
|
||||
|
||||
/// A path that is guaranteed to be absolute and normalized (though it is not
|
||||
/// guaranteed to be canonicalized or exist on the filesystem).
|
||||
///
|
||||
/// IMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set
|
||||
/// using [AbsolutePathBufGuard::new]. If no base path is set, the
|
||||
/// deserialization will fail unless the path being deserialized is already
|
||||
/// absolute.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, JsonSchema, TS)]
|
||||
pub struct AbsolutePathBuf(PathBuf);
|
||||
|
||||
impl AbsolutePathBuf {
|
||||
fn maybe_expand_home_directory(path: &Path) -> PathBuf {
|
||||
if let Some(path_str) = path.to_str()
|
||||
&& let Some(rest) = path_str.strip_prefix('~')
|
||||
&& let Some(home) = AbsolutePathBufGuard::home_directory()
|
||||
{
|
||||
if rest.is_empty() {
|
||||
return home;
|
||||
} else if let Some(rest) = rest.strip_prefix('/') {
|
||||
return home.join(rest.trim_start_matches('/'));
|
||||
} else if cfg!(windows)
|
||||
&& let Some(rest) = rest.strip_prefix('\\')
|
||||
{
|
||||
return home.join(rest.trim_start_matches('\\'));
|
||||
}
|
||||
}
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
pub fn resolve_path_against_base<P: AsRef<Path>, B: AsRef<Path>>(
|
||||
path: P,
|
||||
base_path: B,
|
||||
) -> Self {
|
||||
let expanded = Self::maybe_expand_home_directory(path.as_ref());
|
||||
let expanded = normalize_path_for_platform(&expanded);
|
||||
let base_path = normalize_path_for_platform(base_path.as_ref());
|
||||
Self(absolutize::absolutize_from(
|
||||
expanded.as_ref(),
|
||||
base_path.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn from_absolute_path<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
|
||||
let expanded = Self::maybe_expand_home_directory(path.as_ref());
|
||||
let expanded = normalize_path_for_platform(&expanded);
|
||||
Ok(Self(absolutize::absolutize(expanded.as_ref())?))
|
||||
}
|
||||
|
||||
pub fn from_absolute_path_checked<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
|
||||
let expanded = Self::maybe_expand_home_directory(path.as_ref());
|
||||
let expanded = normalize_path_for_platform(&expanded);
|
||||
if !expanded.is_absolute() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!("path is not absolute: {}", path.as_ref().display()),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Self(absolutize::absolutize_from(
|
||||
expanded.as_ref(),
|
||||
Path::new("/"),
|
||||
)))
|
||||
}
|
||||
|
||||
pub fn current_dir() -> std::io::Result<Self> {
|
||||
Self::from_absolute_path(std::env::current_dir()?)
|
||||
}
|
||||
|
||||
/// Construct an absolute path from `path`, resolving relative paths against
|
||||
/// the process current working directory.
|
||||
pub fn relative_to_current_dir<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
|
||||
if path.as_ref().is_absolute() {
|
||||
return Self::from_absolute_path(path);
|
||||
}
|
||||
|
||||
Ok(Self::resolve_path_against_base(
|
||||
path,
|
||||
std::env::current_dir()?,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn join<P: AsRef<Path>>(&self, path: P) -> Self {
|
||||
Self::resolve_path_against_base(path, &self.0)
|
||||
}
|
||||
|
||||
pub fn canonicalize(&self) -> std::io::Result<Self> {
|
||||
dunce::canonicalize(&self.0).map(Self)
|
||||
}
|
||||
|
||||
pub fn parent(&self) -> Option<Self> {
|
||||
self.0.parent().map(|p| {
|
||||
debug_assert!(
|
||||
p.is_absolute(),
|
||||
"parent of AbsolutePathBuf must be absolute"
|
||||
);
|
||||
Self(p.to_path_buf())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn ancestors(&self) -> impl Iterator<Item = Self> + '_ {
|
||||
self.0.ancestors().map(|p| {
|
||||
debug_assert!(
|
||||
p.is_absolute(),
|
||||
"ancestor of AbsolutePathBuf must be absolute"
|
||||
);
|
||||
Self(p.to_path_buf())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn into_path_buf(self) -> PathBuf {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn to_path_buf(&self) -> PathBuf {
|
||||
self.0.clone()
|
||||
}
|
||||
|
||||
pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
|
||||
self.0.to_string_lossy()
|
||||
}
|
||||
|
||||
pub fn display(&self) -> Display<'_> {
|
||||
self.0.display()
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_path_for_platform(path: &Path) -> Cow<'_, Path> {
|
||||
if cfg!(windows)
|
||||
&& let Some(path) = path.to_str()
|
||||
&& let Some(normalized) = normalize_windows_device_path(path)
|
||||
{
|
||||
return Cow::Owned(PathBuf::from(normalized));
|
||||
}
|
||||
|
||||
Cow::Borrowed(path)
|
||||
}
|
||||
|
||||
/// Normalizes Windows drive and UNC namespace aliases on any host.
|
||||
pub fn normalize_windows_device_path(path: &str) -> Option<String> {
|
||||
if let Some(unc) = path.strip_prefix(r"\\?\UNC\") {
|
||||
return Some(format!(r"\\{unc}"));
|
||||
}
|
||||
if let Some(unc) = path.strip_prefix(r"\\.\UNC\") {
|
||||
return Some(format!(r"\\{unc}"));
|
||||
}
|
||||
if let Some(path) = path.strip_prefix(r"\\?\")
|
||||
&& is_windows_drive_absolute_path(path)
|
||||
{
|
||||
return Some(path.to_string());
|
||||
}
|
||||
if let Some(path) = path.strip_prefix(r"\\.\")
|
||||
&& is_windows_drive_absolute_path(path)
|
||||
{
|
||||
return Some(path.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_windows_drive_absolute_path(path: &str) -> bool {
|
||||
let bytes = path.as_bytes();
|
||||
bytes.len() >= 3
|
||||
&& bytes[0].is_ascii_alphabetic()
|
||||
&& bytes[1] == b':'
|
||||
&& matches!(bytes[2], b'\\' | b'/')
|
||||
}
|
||||
|
||||
/// Canonicalize a path when possible, but preserve the logical absolute path
|
||||
/// whenever canonicalization would rewrite it through a nested symlink.
|
||||
///
|
||||
/// Top-level system aliases such as macOS `/var -> /private/var` still remain
|
||||
/// canonicalized so existing runtime expectations around those paths stay
|
||||
/// stable. If the full path cannot be canonicalized, this returns the logical
|
||||
/// absolute path; use [`canonicalize_existing_preserving_symlinks`] for paths
|
||||
/// that must exist.
|
||||
pub fn canonicalize_preserving_symlinks(path: &Path) -> std::io::Result<PathBuf> {
|
||||
let logical = AbsolutePathBuf::from_absolute_path(path)?.into_path_buf();
|
||||
let preserve_logical_path = should_preserve_logical_path(&logical);
|
||||
match dunce::canonicalize(path) {
|
||||
Ok(canonical) if preserve_logical_path && canonical != logical => Ok(logical),
|
||||
Ok(canonical) => Ok(canonical),
|
||||
Err(_) => Ok(logical),
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonicalize an existing path while preserving the logical absolute path
|
||||
/// whenever canonicalization would rewrite it through a nested symlink.
|
||||
///
|
||||
/// Unlike [`canonicalize_preserving_symlinks`], canonicalization failures are
|
||||
/// propagated so callers can reject invalid working directories early.
|
||||
pub fn canonicalize_existing_preserving_symlinks(path: &Path) -> std::io::Result<PathBuf> {
|
||||
let logical = AbsolutePathBuf::from_absolute_path(path)?.into_path_buf();
|
||||
let canonical = dunce::canonicalize(path)?;
|
||||
if should_preserve_logical_path(&logical) && canonical != logical {
|
||||
Ok(logical)
|
||||
} else {
|
||||
Ok(canonical)
|
||||
}
|
||||
}
|
||||
|
||||
fn should_preserve_logical_path(logical: &Path) -> bool {
|
||||
logical.ancestors().any(|ancestor| {
|
||||
let Ok(metadata) = std::fs::symlink_metadata(ancestor) else {
|
||||
return false;
|
||||
};
|
||||
metadata.file_type().is_symlink() && ancestor.parent().and_then(Path::parent).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
impl AsRef<Path> for AbsolutePathBuf {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for AbsolutePathBuf {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AbsolutePathBuf> for PathBuf {
|
||||
fn from(path: AbsolutePathBuf) -> Self {
|
||||
path.into_path_buf()
|
||||
}
|
||||
}
|
||||
|
||||
/// Helpers for constructing absolute paths in tests.
|
||||
pub mod test_support {
|
||||
use super::AbsolutePathBuf;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Creates a platform-absolute [`PathBuf`] from a Unix-style absolute test path.
|
||||
///
|
||||
/// On Windows, `/tmp/example` maps to `C:\tmp\example`.
|
||||
pub fn test_path_buf(unix_path: &str) -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
let mut path = PathBuf::from(r"C:\");
|
||||
path.extend(
|
||||
unix_path
|
||||
.trim_start_matches('/')
|
||||
.split('/')
|
||||
.filter(|segment| !segment.is_empty()),
|
||||
);
|
||||
path
|
||||
} else {
|
||||
PathBuf::from(unix_path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension methods for converting paths into [`AbsolutePathBuf`] values in tests.
|
||||
pub trait PathExt {
|
||||
/// Converts an already absolute path into an [`AbsolutePathBuf`].
|
||||
fn abs(&self) -> AbsolutePathBuf;
|
||||
}
|
||||
|
||||
impl PathExt for Path {
|
||||
#[expect(clippy::expect_used)]
|
||||
fn abs(&self) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path_checked(self)
|
||||
.expect("path should already be absolute")
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension methods for converting path buffers into [`AbsolutePathBuf`] values in tests.
|
||||
pub trait PathBufExt {
|
||||
/// Converts an already absolute path buffer into an [`AbsolutePathBuf`].
|
||||
fn abs(&self) -> AbsolutePathBuf;
|
||||
}
|
||||
|
||||
impl PathBufExt for PathBuf {
|
||||
fn abs(&self) -> AbsolutePathBuf {
|
||||
self.as_path().abs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&Path> for AbsolutePathBuf {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(value: &Path) -> Result<Self, Self::Error> {
|
||||
Self::from_absolute_path(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<PathBuf> for AbsolutePathBuf {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
|
||||
Self::from_absolute_path(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for AbsolutePathBuf {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
Self::from_absolute_path(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for AbsolutePathBuf {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
Self::from_absolute_path(value)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ABSOLUTE_PATH_BASE: RefCell<Option<PathBuf>> = const { RefCell::new(None) };
|
||||
static ABSOLUTE_PATH_HOME: RefCell<Option<PathBuf>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Ensure this guard is held while deserializing `AbsolutePathBuf` values to
|
||||
/// provide a base path for resolving relative paths. Because this relies on
|
||||
/// thread-local storage, the deserialization must be single-threaded and
|
||||
/// occur on the same thread that created the guard.
|
||||
pub struct AbsolutePathBufGuard;
|
||||
|
||||
impl AbsolutePathBufGuard {
|
||||
/// Reads the native deserialization base and validates the guard requirement
|
||||
/// before home expansion or namespace normalization. Does not look up cwd.
|
||||
pub fn deserialization_base(path: &Path) -> Result<Option<PathBuf>, &'static str> {
|
||||
let base = ABSOLUTE_PATH_BASE.with(|cell| cell.borrow().clone());
|
||||
if base.is_none() && !path.is_absolute() {
|
||||
return Err("AbsolutePathBuf deserialized without a base path");
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
/// Reads the effective native home, including the thread-local override.
|
||||
pub fn home_directory() -> Option<PathBuf> {
|
||||
ABSOLUTE_PATH_HOME
|
||||
.with(|cell| cell.borrow().clone())
|
||||
.or_else(home_dir)
|
||||
}
|
||||
|
||||
pub fn new(base_path: &Path) -> Self {
|
||||
ABSOLUTE_PATH_BASE.with(|cell| {
|
||||
*cell.borrow_mut() = Some(base_path.to_path_buf());
|
||||
});
|
||||
Self
|
||||
}
|
||||
|
||||
/// Resolves home-relative paths against `home_directory` during `operation`.
|
||||
/// The operation must complete synchronously on the current thread.
|
||||
pub fn with_home_directory<T>(home_directory: &Path, operation: impl FnOnce() -> T) -> T {
|
||||
let previous_home =
|
||||
ABSOLUTE_PATH_HOME.with(|cell| cell.replace(Some(home_directory.to_path_buf())));
|
||||
let _guard = HomeDirectoryGuard(previous_home);
|
||||
operation()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AbsolutePathBufGuard {
|
||||
fn drop(&mut self) {
|
||||
ABSOLUTE_PATH_BASE.with(|cell| {
|
||||
*cell.borrow_mut() = None;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct HomeDirectoryGuard(Option<PathBuf>);
|
||||
|
||||
impl Drop for HomeDirectoryGuard {
|
||||
fn drop(&mut self) {
|
||||
ABSOLUTE_PATH_HOME.with(|cell| {
|
||||
*cell.borrow_mut() = self.0.take();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for AbsolutePathBuf {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let path = PathBuf::deserialize(deserializer)?;
|
||||
match AbsolutePathBufGuard::deserialization_base(&path)
|
||||
.map_err(SerdeError::custom)?
|
||||
.as_deref()
|
||||
{
|
||||
Some(base) => Ok(Self::resolve_path_against_base(path, base)),
|
||||
None => Self::from_absolute_path(path).map_err(SerdeError::custom),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
#[cfg(unix)]
|
||||
use std::process::Command;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn create_with_absolute_path_ignores_base_path() {
|
||||
let base_dir = tempdir().expect("base dir");
|
||||
let absolute_dir = tempdir().expect("absolute dir");
|
||||
let base_path = base_dir.path();
|
||||
let absolute_path = absolute_dir.path().join("file.txt");
|
||||
let abs_path_buf =
|
||||
AbsolutePathBuf::resolve_path_against_base(absolute_path.clone(), base_path);
|
||||
assert_eq!(abs_path_buf.as_path(), absolute_path.as_path());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn absolute_paths_do_not_read_current_dir() {
|
||||
let status = Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.arg("absolute_paths_with_removed_current_dir_child")
|
||||
.arg("--ignored")
|
||||
.env("AKODE_ABSOLUTE_PATH_REMOVED_CWD_CHILD", "1")
|
||||
.status()
|
||||
.expect("run child test");
|
||||
|
||||
assert!(status.success());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn absolute_paths_with_removed_current_dir_child() {
|
||||
if std::env::var_os("AKODE_ABSOLUTE_PATH_REMOVED_CWD_CHILD").is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let original_cwd = std::env::current_dir().expect("original cwd");
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let removed_cwd = temp_dir.path().to_path_buf();
|
||||
std::env::set_current_dir(&removed_cwd).expect("enter temp dir");
|
||||
std::fs::remove_dir(&removed_cwd).expect("remove current dir");
|
||||
std::env::current_dir().expect_err("current dir should be unavailable");
|
||||
|
||||
let path = AbsolutePathBuf::from_absolute_path(test_path_buf(
|
||||
"/tmp/codex/../codex-home/plugins/cache",
|
||||
))
|
||||
.expect("absolute path should not require current dir");
|
||||
let relative_to_current_dir_path = AbsolutePathBuf::relative_to_current_dir(test_path_buf(
|
||||
"/tmp/codex/../codex-home/plugins/cache",
|
||||
))
|
||||
.expect("absolute path should not require current dir");
|
||||
|
||||
std::env::set_current_dir(original_cwd).expect("restore cwd");
|
||||
assert_eq!(
|
||||
path.as_path(),
|
||||
test_path_buf("/tmp/codex-home/plugins/cache")
|
||||
);
|
||||
assert_eq!(relative_to_current_dir_path, path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_absolute_path_checked_rejects_relative_path() {
|
||||
for path in [
|
||||
"",
|
||||
"relative/path",
|
||||
r"C:requirements.toml",
|
||||
r"\requirements.toml",
|
||||
] {
|
||||
let err = AbsolutePathBuf::from_absolute_path_checked(path)
|
||||
.expect_err("relative path should fail");
|
||||
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_windows_device_path_strips_supported_verbatim_prefixes() {
|
||||
assert_eq!(
|
||||
normalize_windows_device_path(r"\\?\D:\c\x\worktrees\2508\swift-base"),
|
||||
Some(r"D:\c\x\worktrees\2508\swift-base".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_windows_device_path(r"\\.\D:\c\x\worktrees\2508\swift-base"),
|
||||
Some(r"D:\c\x\worktrees\2508\swift-base".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_windows_device_path(r"\\?\UNC\server\share\workspace"),
|
||||
Some(r"\\server\share\workspace".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_windows_device_path(r"\\.\UNC\server\share\workspace"),
|
||||
Some(r"\\server\share\workspace".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_windows_device_path(r"\\?\GLOBALROOT\Device"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn from_absolute_path_strips_windows_verbatim_prefix() {
|
||||
let path =
|
||||
AbsolutePathBuf::from_absolute_path_checked(r"\\?\D:\c\x\worktrees\2508\swift-base")
|
||||
.expect("verbatim drive path should be absolute");
|
||||
|
||||
assert_eq!(
|
||||
path.as_path(),
|
||||
Path::new(r"D:\c\x\worktrees\2508\swift-base")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_is_resolved_against_base_path() {
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let base_dir = temp_dir.path();
|
||||
let abs_path_buf = AbsolutePathBuf::resolve_path_against_base("file.txt", base_dir);
|
||||
assert_eq!(abs_path_buf.as_path(), base_dir.join("file.txt").as_path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_dots_are_normalized_against_base_path() {
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let base_dir = temp_dir.path();
|
||||
let abs_path_buf =
|
||||
AbsolutePathBuf::resolve_path_against_base("./nested/../file.txt", base_dir);
|
||||
assert_eq!(abs_path_buf.as_path(), base_dir.join("file.txt").as_path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonicalize_returns_absolute_path_buf() {
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
fs::create_dir(temp_dir.path().join("one")).expect("create one dir");
|
||||
fs::create_dir(temp_dir.path().join("two")).expect("create two dir");
|
||||
fs::write(temp_dir.path().join("two").join("file.txt"), "").expect("write file");
|
||||
let abs_path_buf =
|
||||
AbsolutePathBuf::from_absolute_path(temp_dir.path().join("one/../two/./file.txt"))
|
||||
.expect("absolute path");
|
||||
assert_eq!(
|
||||
abs_path_buf
|
||||
.canonicalize()
|
||||
.expect("path should canonicalize")
|
||||
.as_path(),
|
||||
dunce::canonicalize(temp_dir.path().join("two").join("file.txt"))
|
||||
.expect("expected path should canonicalize")
|
||||
.as_path()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonicalize_returns_error_for_missing_path() {
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let abs_path_buf = AbsolutePathBuf::from_absolute_path(temp_dir.path().join("missing.txt"))
|
||||
.expect("absolute path");
|
||||
|
||||
assert!(abs_path_buf.canonicalize().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ancestors_returns_absolute_path_bufs() {
|
||||
let abs_path_buf =
|
||||
AbsolutePathBuf::from_absolute_path_checked(test_path_buf("/tmp/one/two"))
|
||||
.expect("absolute path");
|
||||
|
||||
let ancestors = abs_path_buf
|
||||
.ancestors()
|
||||
.map(|path| path.to_path_buf())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let expected = vec![
|
||||
test_path_buf("/tmp/one/two"),
|
||||
test_path_buf("/tmp/one"),
|
||||
test_path_buf("/tmp"),
|
||||
test_path_buf("/"),
|
||||
];
|
||||
|
||||
assert_eq!(ancestors, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_to_current_dir_resolves_relative_path() -> std::io::Result<()> {
|
||||
let current_dir = std::env::current_dir()?;
|
||||
let abs_path_buf = AbsolutePathBuf::relative_to_current_dir("file.txt")?;
|
||||
assert_eq!(
|
||||
abs_path_buf.as_path(),
|
||||
current_dir.join("file.txt").as_path()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_used_in_deserialization() {
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let base_dir = temp_dir.path();
|
||||
let relative_path = "subdir/file.txt";
|
||||
let abs_path_buf = {
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir);
|
||||
serde_json::from_str::<AbsolutePathBuf>(&format!(r#""{relative_path}""#))
|
||||
.expect("failed to deserialize")
|
||||
};
|
||||
assert_eq!(
|
||||
abs_path_buf.as_path(),
|
||||
base_dir.join(relative_path).as_path()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_directory_root_is_expanded_in_deserialization() {
|
||||
let Some(home) = home_dir() else {
|
||||
return;
|
||||
};
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let abs_path_buf = {
|
||||
let _guard = AbsolutePathBufGuard::new(temp_dir.path());
|
||||
serde_json::from_str::<AbsolutePathBuf>("\"~\"").expect("failed to deserialize")
|
||||
};
|
||||
assert_eq!(abs_path_buf.as_path(), home.as_path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_directory_subpath_is_expanded_in_deserialization() {
|
||||
let Some(home) = home_dir() else {
|
||||
return;
|
||||
};
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let abs_path_buf = {
|
||||
let _guard = AbsolutePathBufGuard::new(temp_dir.path());
|
||||
serde_json::from_str::<AbsolutePathBuf>("\"~/code\"").expect("failed to deserialize")
|
||||
};
|
||||
assert_eq!(abs_path_buf.as_path(), home.join("code").as_path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_home_directory_is_used_with_existing_path_guards() {
|
||||
let home_dir = tempdir().expect("explicit home directory");
|
||||
let base_dir = tempdir().expect("base directory");
|
||||
|
||||
let (home_path, relative_path) =
|
||||
AbsolutePathBufGuard::with_home_directory(home_dir.path(), || {
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir.path());
|
||||
let home_path = serde_json::from_str::<AbsolutePathBuf>("\"~/code\"")
|
||||
.expect("deserialize home-relative path");
|
||||
let relative_path = serde_json::from_str::<AbsolutePathBuf>("\"project/file\"")
|
||||
.expect("deserialize relative path");
|
||||
(home_path, relative_path)
|
||||
});
|
||||
|
||||
assert_eq!(home_path.as_path(), home_dir.path().join("code"));
|
||||
assert_eq!(
|
||||
relative_path.as_path(),
|
||||
base_dir.path().join("project/file")
|
||||
);
|
||||
assert!(serde_json::from_str::<AbsolutePathBuf>("\"project/file\"").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_explicit_home_directories_restore_the_previous_home() {
|
||||
let outer_home = tempdir().expect("outer home directory");
|
||||
let inner_home = tempdir().expect("inner home directory");
|
||||
|
||||
let (inner_path, restored_path) =
|
||||
AbsolutePathBufGuard::with_home_directory(outer_home.path(), || {
|
||||
let inner_path =
|
||||
AbsolutePathBufGuard::with_home_directory(inner_home.path(), || {
|
||||
AbsolutePathBuf::from_absolute_path("~/project")
|
||||
.expect("resolve path with inner home")
|
||||
});
|
||||
let restored_path = AbsolutePathBuf::from_absolute_path("~/project")
|
||||
.expect("resolve path with restored home");
|
||||
(inner_path, restored_path)
|
||||
});
|
||||
|
||||
assert_eq!(inner_path.as_path(), inner_home.path().join("project"));
|
||||
assert_eq!(restored_path.as_path(), outer_home.path().join("project"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_directory_double_slash_is_expanded_in_deserialization() {
|
||||
let Some(home) = home_dir() else {
|
||||
return;
|
||||
};
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let abs_path_buf = {
|
||||
let _guard = AbsolutePathBufGuard::new(temp_dir.path());
|
||||
serde_json::from_str::<AbsolutePathBuf>("\"~//code\"").expect("failed to deserialize")
|
||||
};
|
||||
assert_eq!(abs_path_buf.as_path(), home.join("code").as_path());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn canonicalize_preserving_symlinks_keeps_logical_symlink_path() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let real = temp_dir.path().join("real");
|
||||
let link = temp_dir.path().join("link");
|
||||
std::fs::create_dir_all(&real).expect("create real dir");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("create symlink");
|
||||
|
||||
let canonicalized =
|
||||
canonicalize_preserving_symlinks(&link).expect("canonicalize preserving symlinks");
|
||||
|
||||
assert_eq!(canonicalized, link);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn canonicalize_preserving_symlinks_keeps_logical_missing_child_under_symlink() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let real = temp_dir.path().join("real");
|
||||
let link = temp_dir.path().join("link");
|
||||
std::fs::create_dir_all(&real).expect("create real dir");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("create symlink");
|
||||
let missing = link.join("missing.txt");
|
||||
|
||||
let canonicalized =
|
||||
canonicalize_preserving_symlinks(&missing).expect("canonicalize preserving symlinks");
|
||||
|
||||
assert_eq!(canonicalized, missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonicalize_existing_preserving_symlinks_errors_for_missing_path() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let missing = temp_dir.path().join("missing");
|
||||
|
||||
let err = canonicalize_existing_preserving_symlinks(&missing)
|
||||
.expect_err("missing path should fail canonicalization");
|
||||
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn canonicalize_existing_preserving_symlinks_keeps_logical_symlink_path() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let real = temp_dir.path().join("real");
|
||||
let link = temp_dir.path().join("link");
|
||||
std::fs::create_dir_all(&real).expect("create real dir");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("create symlink");
|
||||
|
||||
let canonicalized =
|
||||
canonicalize_existing_preserving_symlinks(&link).expect("canonicalize symlink");
|
||||
|
||||
assert_eq!(canonicalized, link);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn home_directory_backslash_subpath_is_expanded_in_deserialization() {
|
||||
let Some(home) = home_dir() else {
|
||||
return;
|
||||
};
|
||||
let temp_dir = tempdir().expect("base dir");
|
||||
let abs_path_buf = {
|
||||
let _guard = AbsolutePathBufGuard::new(temp_dir.path());
|
||||
let input =
|
||||
serde_json::to_string(r#"~\code"#).expect("string should serialize as JSON");
|
||||
serde_json::from_str::<AbsolutePathBuf>(&input).expect("is valid abs path")
|
||||
};
|
||||
assert_eq!(abs_path_buf.as_path(), home.join("code").as_path());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn canonicalize_preserving_symlinks_avoids_verbatim_prefixes() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
|
||||
let canonicalized =
|
||||
canonicalize_preserving_symlinks(temp_dir.path()).expect("canonicalize");
|
||||
|
||||
assert_eq!(
|
||||
canonicalized,
|
||||
dunce::canonicalize(temp_dir.path()).expect("canonicalize temp dir")
|
||||
);
|
||||
assert!(
|
||||
!canonicalized.to_string_lossy().starts_with(r"\\?\"),
|
||||
"expected a non-verbatim Windows path, got {canonicalized:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
35
akode-rs/utils/absolute-path/src/system_aliases.rs
Normal file
35
akode-rs/utils/absolute-path/src/system_aliases.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Normalize aliases rooted directly in the trusted filesystem root.
|
||||
//! Never resolve mutable components below that root, including missing descendants.
|
||||
|
||||
use crate::AbsolutePathBuf;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
impl AbsolutePathBuf {
|
||||
/// Resolve a top-level system alias, such as macOS `/tmp -> /private/tmp`.
|
||||
/// All remaining components keep their logical spelling, even if they are
|
||||
/// symlinks or do not exist. Only call this on the host that owns the path.
|
||||
pub fn normalize_system_aliases(&self) -> io::Result<Self> {
|
||||
let Some(top_level) = self.as_path().ancestors().find(|ancestor| {
|
||||
ancestor.parent().is_some() && ancestor.parent().and_then(Path::parent).is_none()
|
||||
}) else {
|
||||
return Ok(self.clone());
|
||||
};
|
||||
match std::fs::symlink_metadata(top_level) {
|
||||
Ok(metadata) if metadata.file_type().is_symlink() => {}
|
||||
Ok(_) => return Ok(self.clone()),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(self.clone()),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let canonical_top_level = dunce::canonicalize(top_level)?;
|
||||
let suffix = self
|
||||
.as_path()
|
||||
.strip_prefix(top_level)
|
||||
.map_err(io::Error::other)?;
|
||||
Self::from_absolute_path(canonical_top_level.join(suffix))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "system_aliases_tests.rs"]
|
||||
mod tests;
|
||||
29
akode-rs/utils/absolute-path/src/system_aliases_tests.rs
Normal file
29
akode-rs/utils/absolute-path/src/system_aliases_tests.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use crate::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn system_aliases_preserve_mutable_symlinks_and_missing_descendants() -> std::io::Result<()> {
|
||||
let directory = tempfile::tempdir_in("/tmp")?;
|
||||
let outside = tempfile::tempdir()?;
|
||||
let logical = AbsolutePathBuf::from_absolute_path(directory.path())?;
|
||||
let physical = logical.canonicalize()?;
|
||||
std::os::unix::fs::symlink(outside.path(), logical.join("mutable"))?;
|
||||
|
||||
for suffix in ["", "missing/child", "mutable", "mutable/missing/child"] {
|
||||
assert_eq!(
|
||||
logical.join(suffix).normalize_system_aliases()?,
|
||||
physical.join(suffix),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_paths_keep_missing_descendants() -> std::io::Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let physical = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
|
||||
let missing = physical.join("missing/child");
|
||||
assert_eq!(missing.normalize_system_aliases()?, missing);
|
||||
Ok(())
|
||||
}
|
||||
6
akode-rs/utils/approval-presets/BUILD.bazel
Normal file
6
akode-rs/utils/approval-presets/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "approval-presets",
|
||||
crate_name = "akode_utils_approval_presets",
|
||||
)
|
||||
15
akode-rs/utils/approval-presets/Cargo.toml
Normal file
15
akode-rs/utils/approval-presets/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "akode-utils-approval-presets"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-protocol = { workspace = true }
|
||||
|
||||
[lib]
|
||||
test = false
|
||||
doctest = false
|
||||
77
akode-rs/utils/approval-presets/src/lib.rs
Normal file
77
akode-rs/utils/approval-presets/src/lib.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use akode_protocol::models::ActivePermissionProfile;
|
||||
use akode_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
|
||||
use akode_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
|
||||
use akode_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
|
||||
/// A simple preset pairing an approval policy with a permission profile.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApprovalPreset {
|
||||
/// Stable identifier for the preset.
|
||||
pub id: &'static str,
|
||||
/// Display label shown in UIs.
|
||||
pub label: &'static str,
|
||||
/// Short human description shown next to the label in UIs.
|
||||
pub description: &'static str,
|
||||
/// Approval policy to apply.
|
||||
pub approval: AskForApproval,
|
||||
/// Built-in permission profile selected by this preset.
|
||||
pub active_permission_profile: ActivePermissionProfile,
|
||||
/// Permission profile to apply.
|
||||
pub permission_profile: PermissionProfile,
|
||||
}
|
||||
|
||||
/// Built-in list of approval presets that pair approval and permissions.
|
||||
///
|
||||
/// Keep this UI-agnostic so it can be reused by both TUI and MCP server.
|
||||
pub fn builtin_approval_presets() -> Vec<ApprovalPreset> {
|
||||
vec![
|
||||
ApprovalPreset {
|
||||
id: "read-only",
|
||||
label: "Read Only",
|
||||
description: "aKode can read files in the current workspace. Approval is required to edit files or access the internet.",
|
||||
approval: AskForApproval::OnRequest,
|
||||
active_permission_profile: ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_READ_ONLY,
|
||||
),
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
},
|
||||
ApprovalPreset {
|
||||
id: "auto",
|
||||
label: "Default",
|
||||
description: "aKode can read and edit files in the current workspace, and run commands. Approval is required to access the internet or edit other files. (Identical to Agent mode)",
|
||||
approval: AskForApproval::OnRequest,
|
||||
active_permission_profile: ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE,
|
||||
),
|
||||
permission_profile: PermissionProfile::workspace_write(),
|
||||
},
|
||||
ApprovalPreset {
|
||||
id: "full-access",
|
||||
label: "Full Access",
|
||||
description: "aKode can edit files outside this workspace and access the internet without asking for approval. Exercise caution when using.",
|
||||
approval: AskForApproval::Never,
|
||||
active_permission_profile: ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS,
|
||||
),
|
||||
permission_profile: PermissionProfile::Disabled,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Return the concrete profile for one of the built-in active profile ids.
|
||||
pub fn builtin_permission_profile_for_active_permission_profile(
|
||||
active_permission_profile: &ActivePermissionProfile,
|
||||
) -> Option<PermissionProfile> {
|
||||
if active_permission_profile.extends.is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
match active_permission_profile.id.as_str() {
|
||||
BUILT_IN_PERMISSION_PROFILE_READ_ONLY => Some(PermissionProfile::read_only()),
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE => Some(PermissionProfile::workspace_write()),
|
||||
BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS => Some(PermissionProfile::Disabled),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/audio/BUILD.bazel
Normal file
6
akode-rs/utils/audio/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "audio",
|
||||
crate_name = "akode_utils_audio",
|
||||
)
|
||||
23
akode-rs/utils/audio/Cargo.toml
Normal file
23
akode-rs/utils/audio/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-utils-audio"
|
||||
version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-utils-cache = { workspace = true }
|
||||
akode-utils-string = { workspace = true }
|
||||
symphonia = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
212
akode-rs/utils/audio/src/audio_preparation_tests.rs
Normal file
212
akode-rs/utils/audio/src/audio_preparation_tests.rs
Normal file
@@ -0,0 +1,212 @@
|
||||
use akode_protocol::models::AudioReference;
|
||||
use akode_protocol::models::FunctionCallOutputBody;
|
||||
use akode_protocol::models::FunctionCallOutputPayload;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preparation_canonicalizes_data_urls_and_rejects_remote_urls() {
|
||||
let mut items = vec![ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::File {
|
||||
file_id: "file_audio".into(),
|
||||
},
|
||||
},
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/x-wav;base64,YXVkaW8=".to_string(),
|
||||
},
|
||||
},
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/ogg;base64,YXVkaW8=".to_string(),
|
||||
},
|
||||
},
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "https://example.com/audio.mp3".to_string(),
|
||||
},
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}];
|
||||
|
||||
prepare_response_items(&mut items);
|
||||
|
||||
assert_eq!(
|
||||
items,
|
||||
vec![ResponseItem::Message {
|
||||
encrypted_content: None,
|
||||
status: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::File {
|
||||
file_id: "file_audio".into(),
|
||||
}
|
||||
},
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/wav;base64,YXVkaW8=".to_string()
|
||||
}
|
||||
},
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/ogg;base64,YXVkaW8=".to_string()
|
||||
}
|
||||
},
|
||||
ContentItem::InputText {
|
||||
text: "audio content omitted because it could not be processed".to_string(),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preparation_replaces_invalid_message_audio_with_placeholders() {
|
||||
let mut items = vec![ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/wav;base64,%%%".to_string(),
|
||||
},
|
||||
},
|
||||
ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline {
|
||||
audio_url: "data:audio/flac;base64,YXVkaW8=".to_string(),
|
||||
},
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}];
|
||||
|
||||
prepare_response_items(&mut items);
|
||||
|
||||
assert_eq!(
|
||||
items,
|
||||
vec![ResponseItem::Message {
|
||||
encrypted_content: None,
|
||||
status: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputText {
|
||||
text: "audio content omitted because it could not be processed".to_string(),
|
||||
},
|
||||
ContentItem::InputText {
|
||||
text: "audio content omitted because its format is not supported; use wav, mp3, m4a, webm, or ogg".to_string(),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preparation_replaces_only_failed_tool_audio_and_preserves_metadata() {
|
||||
let mut items = vec![ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("call-1".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: FunctionCallOutputPayload {
|
||||
body: FunctionCallOutputBody::ContentItems(vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "before".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "data:audio/wav;base64,YXVkaW8=".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "data:audio/wav,not-base64".to_string(),
|
||||
},
|
||||
]),
|
||||
success: Some(true),
|
||||
},
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}];
|
||||
|
||||
prepare_response_items(&mut items);
|
||||
|
||||
assert_eq!(
|
||||
items,
|
||||
vec![ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some("call-1".to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: FunctionCallOutputPayload {
|
||||
body: FunctionCallOutputBody::ContentItems(vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "before".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "data:audio/wav;base64,YXVkaW8=".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "audio content omitted because it could not be processed".to_string(),
|
||||
},
|
||||
]),
|
||||
success: Some(true),
|
||||
},
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preparation_errors_map_to_expected_placeholders() {
|
||||
let cases = [
|
||||
(
|
||||
AudioPreparationError::InvalidDataUrl {
|
||||
reason: "details remain in logs",
|
||||
},
|
||||
"audio content omitted because it could not be processed",
|
||||
),
|
||||
(
|
||||
AudioPreparationError::UnsupportedFormat,
|
||||
"audio content omitted because its format is not supported; use wav, mp3, m4a, webm, or ogg",
|
||||
),
|
||||
(
|
||||
AudioPreparationError::AudioTooLarge { size: usize::MAX },
|
||||
"audio content omitted because it exceeded the supported size limit; use a smaller audio file",
|
||||
),
|
||||
];
|
||||
|
||||
for (error, expected) in cases {
|
||||
assert_eq!(error.placeholder(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_audio_uses_the_measured_length_or_the_full_file_budget() {
|
||||
use std::time::Duration;
|
||||
for (duration, expected) in [
|
||||
(None, 12_000),
|
||||
(Some(Duration::ZERO), 12_000),
|
||||
(Some(Duration::from_nanos(1)), 1),
|
||||
(Some(Duration::from_secs(2)), 20),
|
||||
(Some(Duration::from_millis(2_001)), 21),
|
||||
(Some(Duration::from_secs(20 * 60)), 12_000),
|
||||
(Some(Duration::MAX), 12_000),
|
||||
] {
|
||||
assert_eq!(super::estimate_file_audio_tokens(duration), expected);
|
||||
}
|
||||
}
|
||||
288
akode-rs/utils/audio/src/lib.rs
Normal file
288
akode-rs/utils/audio/src/lib.rs
Normal file
@@ -0,0 +1,288 @@
|
||||
//! Audio preparation and duration-based token estimates for model inputs.
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use akode_protocol::models::AudioReference;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::FunctionCallOutputContentItem;
|
||||
use akode_protocol::models::MAX_PROMPT_AUDIO_INPUT_BYTES;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_utils_cache::BlockingLruCache;
|
||||
use akode_utils_cache::sha1_digest;
|
||||
use akode_utils_string::approx_token_count;
|
||||
use std::io::Cursor;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::OnceLock;
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::formats::TrackType;
|
||||
use symphonia::core::formats::probe::Hint;
|
||||
use symphonia::core::io::MediaSourceStream;
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use tracing::warn;
|
||||
|
||||
const AUDIO_PROCESSING_ERROR_PLACEHOLDER: &str =
|
||||
"audio content omitted because it could not be processed";
|
||||
const AUDIO_TOO_LARGE_PLACEHOLDER: &str =
|
||||
"audio content omitted because it exceeded the supported size limit; use a smaller audio file";
|
||||
const UNSUPPORTED_AUDIO_FORMAT_PLACEHOLDER: &str =
|
||||
"audio content omitted because its format is not supported; use wav, mp3, m4a, webm, or ogg";
|
||||
|
||||
const MAX_PROMPT_AUDIO_BASE64_BYTES: usize = MAX_PROMPT_AUDIO_INPUT_BYTES.div_ceil(3) * 4;
|
||||
const AUDIO_TOKEN_ESTIMATE_CACHE_SIZE: usize = 32;
|
||||
const AUDIO_TOKENS_PER_SECOND: u32 = 10;
|
||||
|
||||
static AUDIO_TOKEN_ESTIMATE_CACHE: LazyLock<BlockingLruCache<[u8; 20], Arc<OnceLock<usize>>>> =
|
||||
LazyLock::new(|| {
|
||||
BlockingLruCache::new(
|
||||
NonZeroUsize::new(AUDIO_TOKEN_ESTIMATE_CACHE_SIZE).unwrap_or(NonZeroUsize::MIN),
|
||||
)
|
||||
});
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum AudioPreparationError {
|
||||
#[error("invalid audio data URL: {reason}")]
|
||||
InvalidDataUrl { reason: &'static str },
|
||||
#[error("unsupported audio format")]
|
||||
UnsupportedFormat,
|
||||
#[error("audio input is too large ({size} bytes; max {MAX_PROMPT_AUDIO_INPUT_BYTES} bytes)")]
|
||||
AudioTooLarge { size: usize },
|
||||
}
|
||||
|
||||
impl AudioPreparationError {
|
||||
fn placeholder(&self) -> &'static str {
|
||||
match self {
|
||||
AudioPreparationError::InvalidDataUrl { .. } => AUDIO_PROCESSING_ERROR_PLACEHOLDER,
|
||||
AudioPreparationError::UnsupportedFormat => UNSUPPORTED_AUDIO_FORMAT_PLACEHOLDER,
|
||||
AudioPreparationError::AudioTooLarge { .. } => AUDIO_TOO_LARGE_PLACEHOLDER,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonicalizes audio inputs and replaces unsupported inputs with text placeholders.
|
||||
pub fn prepare_response_items(items: &mut [ResponseItem]) {
|
||||
for item in items {
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => prepare_message_content(content),
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
if let Some(content) = output.content_items_mut() {
|
||||
prepare_tool_output_content(content);
|
||||
}
|
||||
}
|
||||
ResponseItem::AdditionalTools { .. }
|
||||
| ResponseItem::Reasoning { .. }
|
||||
| ResponseItem::AgentMessage { .. }
|
||||
| ResponseItem::LocalShellCall { .. }
|
||||
| ResponseItem::FunctionCall { .. }
|
||||
| ResponseItem::ToolSearchCall { .. }
|
||||
| ResponseItem::CustomToolCall { .. }
|
||||
| ResponseItem::ToolSearchOutput { .. }
|
||||
| ResponseItem::WebSearchCall { .. }
|
||||
| ResponseItem::ImageGenerationCall { .. }
|
||||
| ResponseItem::Compaction { .. }
|
||||
| ResponseItem::ConfigurationUpdate { .. }
|
||||
| ResponseItem::CompactionTrigger { .. }
|
||||
| ResponseItem::ContextCompaction { .. }
|
||||
| ResponseItem::Other => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_message_content(items: &mut [ContentItem]) {
|
||||
for item in items {
|
||||
if let ContentItem::InputAudio {
|
||||
audio: AudioReference::Inline { audio_url },
|
||||
} = item
|
||||
&& let Err(error) = prepare_audio(audio_url)
|
||||
{
|
||||
warn!(%error, "failed to prepare message audio");
|
||||
*item = ContentItem::InputText {
|
||||
text: error.placeholder().to_string(),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_tool_output_content(items: &mut [FunctionCallOutputContentItem]) {
|
||||
for item in items {
|
||||
if let FunctionCallOutputContentItem::InputAudio { audio_url } = item
|
||||
&& let Err(error) = prepare_audio(audio_url)
|
||||
{
|
||||
warn!(%error, "failed to prepare tool output audio");
|
||||
*item = FunctionCallOutputContentItem::InputText {
|
||||
text: error.placeholder().to_string(),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_data_url(audio_url: &str) -> bool {
|
||||
audio_url
|
||||
.get(.."data:".len())
|
||||
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("data:"))
|
||||
}
|
||||
|
||||
fn canonical_audio_mime(mime: &str) -> Option<&'static str> {
|
||||
if mime.eq_ignore_ascii_case("audio/wav")
|
||||
|| mime.eq_ignore_ascii_case("audio/x-wav")
|
||||
|| mime.eq_ignore_ascii_case("audio/wave")
|
||||
|| mime.eq_ignore_ascii_case("audio/vnd.wave")
|
||||
{
|
||||
Some("audio/wav")
|
||||
} else if mime.eq_ignore_ascii_case("audio/mpeg") || mime.eq_ignore_ascii_case("audio/mp3") {
|
||||
Some("audio/mpeg")
|
||||
} else if mime.eq_ignore_ascii_case("audio/mp4")
|
||||
|| mime.eq_ignore_ascii_case("audio/m4a")
|
||||
|| mime.eq_ignore_ascii_case("audio/x-m4a")
|
||||
{
|
||||
Some("audio/mp4")
|
||||
} else if mime.eq_ignore_ascii_case("audio/webm") {
|
||||
Some("audio/webm")
|
||||
} else if mime.eq_ignore_ascii_case("audio/ogg") {
|
||||
Some("audio/ogg")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Budget one file reference at the inline audio rate. Missing or unusable metadata
|
||||
/// reserves the full 20 minutes accepted by Responses. Admission belongs to Responses.
|
||||
pub fn estimate_file_audio_tokens(duration: Option<std::time::Duration>) -> usize {
|
||||
const MAX_DURATION: std::time::Duration = std::time::Duration::from_secs(20 * 60);
|
||||
let duration = duration
|
||||
.filter(|value| !value.is_zero())
|
||||
.unwrap_or(MAX_DURATION)
|
||||
.min(MAX_DURATION);
|
||||
let tokens =
|
||||
(duration.as_nanos() * u128::from(AUDIO_TOKENS_PER_SECOND)).div_ceil(1_000_000_000);
|
||||
usize::try_from(tokens).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// Estimates audio tokens from decoded duration, falling back to the data URL size.
|
||||
pub fn estimate_audio_token_count(audio_url: &str) -> usize {
|
||||
let key = sha1_digest(audio_url.as_bytes());
|
||||
AUDIO_TOKEN_ESTIMATE_CACHE
|
||||
.get_or_init(key, || estimate_audio_token_count_without_cache(audio_url))
|
||||
}
|
||||
|
||||
/// The same duration-based estimate without accessing the Tokio-dependent cache.
|
||||
/// Suitable for bounded output rendered on a current-thread runtime.
|
||||
pub fn estimate_audio_token_count_without_cache(audio_url: &str) -> usize {
|
||||
let Some(duration_seconds) = audio_duration_seconds(audio_url) else {
|
||||
return approx_token_count(audio_url);
|
||||
};
|
||||
let token_count = (duration_seconds * f64::from(AUDIO_TOKENS_PER_SECOND)).ceil();
|
||||
if token_count >= usize::MAX as f64 {
|
||||
usize::MAX
|
||||
} else {
|
||||
token_count as usize
|
||||
}
|
||||
}
|
||||
|
||||
fn audio_duration_seconds(audio_url: &str) -> Option<f64> {
|
||||
let (metadata, payload) = audio_url.split_once(',')?;
|
||||
let metadata = metadata.get("data:".len()..)?;
|
||||
let mut metadata_parts = metadata.split(';');
|
||||
let canonical_mime = canonical_audio_mime(metadata_parts.next()?)?;
|
||||
if !metadata_parts.any(|part| part.eq_ignore_ascii_case("base64")) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let bytes = match BASE64_STANDARD.decode(payload) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
tracing::trace!(%error, "failed to decode audio payload for token estimation");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let media_source = MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default());
|
||||
let mut hint = Hint::new();
|
||||
hint.mime_type(canonical_mime);
|
||||
let format = match symphonia::default::get_probe().probe(
|
||||
&hint,
|
||||
media_source,
|
||||
FormatOptions::default(),
|
||||
MetadataOptions::default(),
|
||||
) {
|
||||
Ok(format) => format,
|
||||
Err(error) => {
|
||||
tracing::trace!(%error, "failed to read audio duration for token estimation");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let track = format.default_track(TrackType::Audio)?;
|
||||
let timing = track.time_base.zip(track.duration).or_else(|| {
|
||||
format
|
||||
.media_info()
|
||||
.time_base
|
||||
.zip(format.media_info().duration)
|
||||
});
|
||||
let (time_base, duration) = timing?;
|
||||
let duration_seconds =
|
||||
duration.get() as f64 * f64::from(time_base.numer.get()) / f64::from(time_base.denom.get());
|
||||
duration_seconds.is_finite().then_some(duration_seconds)
|
||||
}
|
||||
|
||||
fn prepare_audio(audio_url: &mut String) -> Result<(), AudioPreparationError> {
|
||||
if !is_data_url(audio_url) {
|
||||
return Err(AudioPreparationError::InvalidDataUrl {
|
||||
reason: "audio input must be a data URL",
|
||||
});
|
||||
}
|
||||
|
||||
let (metadata, payload) =
|
||||
audio_url
|
||||
.split_once(',')
|
||||
.ok_or(AudioPreparationError::InvalidDataUrl {
|
||||
reason: "missing payload separator",
|
||||
})?;
|
||||
let metadata = metadata
|
||||
.get("data:".len()..)
|
||||
.ok_or(AudioPreparationError::InvalidDataUrl {
|
||||
reason: "missing data URL prefix",
|
||||
})?;
|
||||
let mut metadata_parts = metadata.split(';');
|
||||
let mime = metadata_parts
|
||||
.next()
|
||||
.filter(|mime| !mime.is_empty())
|
||||
.ok_or(AudioPreparationError::InvalidDataUrl {
|
||||
reason: "missing media type",
|
||||
})?;
|
||||
let canonical_mime =
|
||||
canonical_audio_mime(mime).ok_or(AudioPreparationError::UnsupportedFormat)?;
|
||||
if !metadata_parts.any(|part| part.eq_ignore_ascii_case("base64")) {
|
||||
return Err(AudioPreparationError::InvalidDataUrl {
|
||||
reason: "audio payload is not base64 encoded",
|
||||
});
|
||||
}
|
||||
if payload.len() > MAX_PROMPT_AUDIO_BASE64_BYTES {
|
||||
return Err(AudioPreparationError::AudioTooLarge {
|
||||
size: payload.len(),
|
||||
});
|
||||
}
|
||||
|
||||
let bytes =
|
||||
BASE64_STANDARD
|
||||
.decode(payload)
|
||||
.map_err(|_| AudioPreparationError::InvalidDataUrl {
|
||||
reason: "invalid base64 payload",
|
||||
})?;
|
||||
if bytes.is_empty() {
|
||||
return Err(AudioPreparationError::InvalidDataUrl {
|
||||
reason: "audio payload is empty",
|
||||
});
|
||||
}
|
||||
if bytes.len() > MAX_PROMPT_AUDIO_INPUT_BYTES {
|
||||
return Err(AudioPreparationError::AudioTooLarge { size: bytes.len() });
|
||||
}
|
||||
|
||||
let encoded = BASE64_STANDARD.encode(bytes);
|
||||
*audio_url = format!("data:{canonical_mime};base64,{encoded}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "audio_preparation_tests.rs"]
|
||||
mod tests;
|
||||
6
akode-rs/utils/cache/BUILD.bazel
vendored
Normal file
6
akode-rs/utils/cache/BUILD.bazel
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "cache",
|
||||
crate_name = "akode_utils_cache",
|
||||
)
|
||||
19
akode-rs/utils/cache/Cargo.toml
vendored
Normal file
19
akode-rs/utils/cache/Cargo.toml
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "akode-utils-cache"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
lru = { workspace = true }
|
||||
sha1 = { workspace = true }
|
||||
tokio = { workspace = true, features = ["sync", "rt", "rt-multi-thread"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
51
akode-rs/utils/cache/src/initialization_tests.rs
vendored
Normal file
51
akode-rs/utils/cache/src/initialization_tests.rs
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
//! Checks that initialization releases the global lock and survives LRU eviction.
|
||||
|
||||
use crate::BlockingLruCache;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn initialization_keeps_other_keys_available_through_eviction() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(/*n*/ 2).expect("capacity"));
|
||||
assert_eq!(cache.get_or_init("hot", || 3), 3);
|
||||
let handle = tokio::runtime::Handle::current();
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
|
||||
std::thread::scope(|scope| {
|
||||
let cache = &cache;
|
||||
let initializing = scope.spawn(move || {
|
||||
let _entered = handle.enter();
|
||||
cache.get_or_init("busy", || {
|
||||
started_tx.send(()).expect("signal initialization");
|
||||
release_rx
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 5))
|
||||
.expect("other keys should finish before initialization is released");
|
||||
7
|
||||
})
|
||||
});
|
||||
started_rx
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 5))
|
||||
.expect("initialization should start");
|
||||
|
||||
assert_eq!(cache.get_or_init("hot", || panic!("cached value")), 3);
|
||||
assert_eq!(cache.get_or_init("other", || 5), 5);
|
||||
assert!(cache.get(&"busy").is_none());
|
||||
|
||||
// The evicted initializer still owns its cell. A new resident cell can
|
||||
// independently initialize the same deterministic value for this key.
|
||||
assert_eq!(cache.get_or_init("busy", || 7), 7);
|
||||
release_tx.send(()).expect("release initialization");
|
||||
assert_eq!(initializing.join().expect("initialization thread"), 7);
|
||||
assert_eq!(
|
||||
cache.with_mut(|entries| {
|
||||
entries
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, *value.get().expect("initialized value")))
|
||||
.collect::<Vec<_>>()
|
||||
}),
|
||||
vec![("busy", 7), ("other", 5)]
|
||||
);
|
||||
});
|
||||
}
|
||||
167
akode-rs/utils/cache/src/lib.rs
vendored
Normal file
167
akode-rs/utils/cache/src/lib.rs
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
use std::borrow::Borrow;
|
||||
use std::hash::Hash;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use lru::LruCache;
|
||||
use sha1::Digest;
|
||||
use sha1::Sha1;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::MutexGuard;
|
||||
|
||||
/// A minimal LRU cache protected by a Tokio mutex.
|
||||
/// Calls outside a Tokio runtime are no-ops.
|
||||
pub struct BlockingLruCache<K, V> {
|
||||
inner: Mutex<LruCache<K, V>>,
|
||||
}
|
||||
|
||||
impl<K, V> BlockingLruCache<K, V>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
/// Creates a cache with the provided non-zero capacity.
|
||||
#[must_use]
|
||||
pub fn new(capacity: NonZeroUsize) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(LruCache::new(capacity)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a clone of the cached value for `key`, or computes and inserts it.
|
||||
pub fn get_or_insert_with(&self, key: K, value: impl FnOnce() -> V) -> V
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
if let Some(v) = guard.get(&key) {
|
||||
return v.clone();
|
||||
}
|
||||
let v = value();
|
||||
// Insert and return a clone to keep ownership in the cache.
|
||||
guard.put(key, v.clone());
|
||||
return v;
|
||||
}
|
||||
value()
|
||||
}
|
||||
|
||||
/// Like `get_or_insert_with`, but the value factory may fail.
|
||||
pub fn get_or_try_insert_with<E>(
|
||||
&self,
|
||||
key: K,
|
||||
value: impl FnOnce() -> Result<V, E>,
|
||||
) -> Result<V, E>
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
if let Some(v) = guard.get(&key) {
|
||||
return Ok(v.clone());
|
||||
}
|
||||
let v = value()?;
|
||||
guard.put(key, v.clone());
|
||||
return Ok(v);
|
||||
}
|
||||
value()
|
||||
}
|
||||
|
||||
/// Builds a cache if `capacity` is non-zero, returning `None` otherwise.
|
||||
#[must_use]
|
||||
pub fn try_with_capacity(capacity: usize) -> Option<Self> {
|
||||
NonZeroUsize::new(capacity).map(Self::new)
|
||||
}
|
||||
|
||||
/// Returns a clone of the cached value corresponding to `key`, if present.
|
||||
pub fn get<Q>(&self, key: &Q) -> Option<V>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
V: Clone,
|
||||
{
|
||||
let mut guard = lock_if_runtime(&self.inner)?;
|
||||
guard.get(key).cloned()
|
||||
}
|
||||
|
||||
/// Inserts `value` for `key`, returning the previous entry if it existed.
|
||||
pub fn insert(&self, key: K, value: V) -> Option<V> {
|
||||
let mut guard = lock_if_runtime(&self.inner)?;
|
||||
guard.put(key, value)
|
||||
}
|
||||
|
||||
/// Removes the entry for `key` if it exists, returning it.
|
||||
pub fn remove<Q>(&self, key: &Q) -> Option<V>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
{
|
||||
let mut guard = lock_if_runtime(&self.inner)?;
|
||||
guard.pop(key)
|
||||
}
|
||||
|
||||
/// Clears all entries from the cache.
|
||||
pub fn clear(&self) {
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
guard.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes `callback` with a mutable reference to the underlying cache.
|
||||
pub fn with_mut<R>(&self, callback: impl FnOnce(&mut LruCache<K, V>) -> R) -> R {
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
callback(&mut guard)
|
||||
} else {
|
||||
let mut disabled = LruCache::unbounded();
|
||||
callback(&mut disabled)
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides direct access to the cache guard when a Tokio runtime is available.
|
||||
pub fn blocking_lock(&self) -> Option<MutexGuard<'_, LruCache<K, V>>> {
|
||||
lock_if_runtime(&self.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> BlockingLruCache<K, Arc<OnceLock<V>>>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
V: Clone,
|
||||
{
|
||||
/// Returns the cached value, initializing it outside the global cache lock.
|
||||
///
|
||||
/// Concurrent callers share initialization while the entry remains cached.
|
||||
/// An in-flight entry can be evicted and initialized again, so factories must
|
||||
/// be deterministic. Initialization and same-key waits use a blocking region.
|
||||
pub fn get_or_init(&self, key: K, value: impl FnOnce() -> V) -> V {
|
||||
let entry = self.get_or_insert_with(key, || Arc::new(OnceLock::new()));
|
||||
if let Some(value) = entry.get() {
|
||||
return value.clone();
|
||||
}
|
||||
tokio::task::block_in_place(|| entry.get_or_init(value).clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_if_runtime<K, V>(m: &Mutex<LruCache<K, V>>) -> Option<MutexGuard<'_, LruCache<K, V>>>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
tokio::runtime::Handle::try_current().ok()?;
|
||||
Some(tokio::task::block_in_place(|| m.blocking_lock()))
|
||||
}
|
||||
|
||||
/// Computes the SHA-1 digest of `bytes`.
|
||||
///
|
||||
/// Useful for content-based cache keys when you want to avoid staleness
|
||||
/// caused by path-only keys.
|
||||
#[must_use]
|
||||
pub fn sha1_digest(bytes: &[u8]) -> [u8; 20] {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(bytes);
|
||||
let result = hasher.finalize();
|
||||
let mut out = [0; 20];
|
||||
out.copy_from_slice(&result);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
54
akode-rs/utils/cache/src/lib_tests.rs
vendored
Normal file
54
akode-rs/utils/cache/src/lib_tests.rs
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
use super::BlockingLruCache;
|
||||
use std::num::NonZeroUsize;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stores_and_retrieves_values() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity"));
|
||||
|
||||
assert!(cache.get(&"first").is_none());
|
||||
cache.insert("first", /*value*/ 1);
|
||||
assert_eq!(cache.get(&"first"), Some(1));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn evicts_least_recently_used() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity"));
|
||||
cache.insert("a", /*value*/ 1);
|
||||
cache.insert("b", /*value*/ 2);
|
||||
assert_eq!(cache.get(&"a"), Some(1));
|
||||
|
||||
cache.insert("c", /*value*/ 3);
|
||||
|
||||
assert!(cache.get(&"b").is_none());
|
||||
assert_eq!(cache.get(&"a"), Some(1));
|
||||
assert_eq!(cache.get(&"c"), Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_without_runtime() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity"));
|
||||
cache.insert("first", /*value*/ 1);
|
||||
assert!(cache.get(&"first").is_none());
|
||||
|
||||
assert_eq!(cache.get_or_insert_with("first", || 2), 2);
|
||||
assert!(cache.get(&"first").is_none());
|
||||
|
||||
assert!(cache.remove(&"first").is_none());
|
||||
cache.clear();
|
||||
|
||||
let result = cache.with_mut(|inner| {
|
||||
inner.put("tmp", 3);
|
||||
inner.get(&"tmp").cloned()
|
||||
});
|
||||
assert_eq!(result, Some(3));
|
||||
assert!(cache.get(&"tmp").is_none());
|
||||
|
||||
assert!(cache.blocking_lock().is_none());
|
||||
}
|
||||
|
||||
#[path = "initialization_tests.rs"]
|
||||
mod initialization_tests;
|
||||
17
akode-rs/utils/cargo-bin/BUILD.bazel
Normal file
17
akode-rs/utils/cargo-bin/BUILD.bazel
Normal file
@@ -0,0 +1,17 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
exports_files(
|
||||
["repo_root.marker"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
codex_rust_crate(
|
||||
name = "cargo-bin",
|
||||
compile_data = ["repo_root.marker"],
|
||||
crate_name = "akode_utils_cargo_bin",
|
||||
lib_data_extra = ["repo_root.marker"],
|
||||
rustc_env = {
|
||||
"AKODE_REPO_ROOT_MARKER": "$(rlocationpath :repo_root.marker)",
|
||||
},
|
||||
test_data_extra = ["repo_root.marker"],
|
||||
)
|
||||
17
akode-rs/utils/cargo-bin/Cargo.toml
Normal file
17
akode-rs/utils/cargo-bin/Cargo.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "akode-utils-cargo-bin"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
assert_cmd = { workspace = true }
|
||||
runfiles = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[lib]
|
||||
test = false
|
||||
doctest = false
|
||||
22
akode-rs/utils/cargo-bin/README.md
Normal file
22
akode-rs/utils/cargo-bin/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# akode-utils-cargo-bin runfiles strategy
|
||||
|
||||
We disable the directory-based runfiles strategy and rely on the manifest
|
||||
strategy across all platforms. This avoids Windows path length issues and keeps
|
||||
behavior consistent in local and remote builds on all platforms. Bazel sets
|
||||
`RUNFILES_MANIFEST_FILE`, and the `akode-utils-cargo-bin` helpers use the
|
||||
`runfiles` crate to resolve runfiles via that manifest.
|
||||
|
||||
Function behavior:
|
||||
|
||||
- `cargo_bin`: reads `CARGO_BIN_EXE_*` environment variables (set by Cargo or
|
||||
Bazel) and resolves them via the runfiles manifest when `RUNFILES_MANIFEST_FILE`
|
||||
is present. When not under runfiles, it only accepts absolute paths from
|
||||
`CARGO_BIN_EXE_*` and returns an error otherwise.
|
||||
- `find_resource!`: used by tests to locate fixtures. It chooses the Bazel
|
||||
runfiles resolution path when `RUNFILES_MANIFEST_FILE` is set, otherwise it
|
||||
falls back to a `CARGO_MANIFEST_DIR`-relative path for Cargo runs.
|
||||
|
||||
Background:
|
||||
|
||||
- https://bazel.build/docs/runfiles
|
||||
- https://bazel.build/docs/runfiles#runfiles-manifest
|
||||
1
akode-rs/utils/cargo-bin/repo_root.marker
Normal file
1
akode-rs/utils/cargo-bin/repo_root.marker
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
62
akode-rs/utils/cargo-bin/src/executable.rs
Normal file
62
akode-rs/utils/cargo-bin/src/executable.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
//! Creates executable test fixtures without exposing writable descriptors to sibling spawns.
|
||||
//! On Linux, writes and copies finish in a separate process before the fixture can be launched.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::process::Command;
|
||||
|
||||
/// Writes a small Unix script fixture and makes it executable with mode 0o755.
|
||||
#[cfg(unix)]
|
||||
pub fn write_executable(path: &Path, script: &str) -> io::Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// A sibling test can fork while a parent-owned file is open for writing.
|
||||
// CLOEXEC does not release that inherited descriptor until the sibling execs.
|
||||
let output = Command::new("/bin/sh")
|
||||
.arg("-c")
|
||||
.arg("printf '%s' \"$1\" > \"$2\"")
|
||||
.arg("write-executable-fixture")
|
||||
.arg(script)
|
||||
.arg(path)
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to write executable fixture {}: {}",
|
||||
path.display(),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
)));
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fs::write(path, script)?;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(/*mode*/ 0o755))
|
||||
}
|
||||
|
||||
/// Copies an executable fixture, preserving the source permissions like [`fs::copy`].
|
||||
pub fn copy_executable(source: &Path, destination: &Path) -> io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let output = Command::new("/bin/cp")
|
||||
.arg("--")
|
||||
.arg(source)
|
||||
.arg(destination)
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to copy executable fixture {} to {}: {}",
|
||||
source.display(),
|
||||
destination.display(),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
)));
|
||||
}
|
||||
// Match fs::copy even when the test process has a restrictive umask.
|
||||
fs::set_permissions(destination, fs::metadata(source)?.permissions())?;
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fs::copy(source, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
236
akode-rs/utils/cargo-bin/src/lib.rs
Normal file
236
akode-rs/utils/cargo-bin/src/lib.rs
Normal file
@@ -0,0 +1,236 @@
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use runfiles;
|
||||
|
||||
mod executable;
|
||||
pub use executable::copy_executable;
|
||||
#[cfg(unix)]
|
||||
pub use executable::write_executable;
|
||||
|
||||
/// Bazel sets this when runfiles directories are disabled, which we do on all platforms for consistency.
|
||||
const RUNFILES_MANIFEST_ONLY_ENV: &str = "RUNFILES_MANIFEST_ONLY";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CargoBinError {
|
||||
#[error("failed to read current exe")]
|
||||
CurrentExe {
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to read current directory")]
|
||||
CurrentDir {
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("CARGO_BIN_EXE env var {key} resolved to {path:?}, but it does not exist")]
|
||||
ResolvedPathDoesNotExist { key: String, path: PathBuf },
|
||||
#[error("could not locate binary {name:?}; tried env vars {env_keys:?}; {fallback}")]
|
||||
NotFound {
|
||||
name: String,
|
||||
env_keys: Vec<String>,
|
||||
fallback: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Returns an absolute path to a binary target built for the current test run.
|
||||
///
|
||||
/// In `cargo test`, `CARGO_BIN_EXE_*` env vars are absolute.
|
||||
/// In `bazel test`, `CARGO_BIN_EXE_*` env vars are rlocationpaths, intended to be consumed by `rlocation`.
|
||||
/// This helper allows callers to transparently support both.
|
||||
#[allow(deprecated)]
|
||||
pub fn cargo_bin(name: &str) -> Result<PathBuf, CargoBinError> {
|
||||
let env_keys = cargo_bin_env_keys(name);
|
||||
for key in &env_keys {
|
||||
if let Some(value) = std::env::var_os(key) {
|
||||
return resolve_bin_from_env(key, value);
|
||||
}
|
||||
}
|
||||
match assert_cmd::Command::cargo_bin(name) {
|
||||
Ok(cmd) => {
|
||||
let mut path = PathBuf::from(cmd.get_program());
|
||||
if !path.is_absolute() {
|
||||
path = std::env::current_dir()
|
||||
.map_err(|source| CargoBinError::CurrentDir { source })?
|
||||
.join(path);
|
||||
}
|
||||
if path.exists() {
|
||||
Ok(path)
|
||||
} else {
|
||||
Err(CargoBinError::ResolvedPathDoesNotExist {
|
||||
key: "assert_cmd::Command::cargo_bin".to_owned(),
|
||||
path,
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(err) => Err(CargoBinError::NotFound {
|
||||
name: name.to_owned(),
|
||||
env_keys,
|
||||
fallback: format!("assert_cmd fallback failed: {err}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn cargo_bin_env_keys(name: &str) -> Vec<String> {
|
||||
let mut keys = Vec::with_capacity(2);
|
||||
keys.push(format!("CARGO_BIN_EXE_{name}"));
|
||||
|
||||
// Cargo replaces dashes in target names when exporting env vars.
|
||||
let underscore_name = name.replace('-', "_");
|
||||
if underscore_name != name {
|
||||
keys.push(format!("CARGO_BIN_EXE_{underscore_name}"));
|
||||
}
|
||||
|
||||
keys
|
||||
}
|
||||
|
||||
pub fn runfiles_available() -> bool {
|
||||
std::env::var_os(RUNFILES_MANIFEST_ONLY_ENV).is_some()
|
||||
}
|
||||
|
||||
fn resolve_bin_from_env(key: &str, value: OsString) -> Result<PathBuf, CargoBinError> {
|
||||
let raw = PathBuf::from(&value);
|
||||
if runfiles_available() {
|
||||
let runfiles = runfiles::Runfiles::create().map_err(|err| CargoBinError::CurrentExe {
|
||||
source: std::io::Error::other(err),
|
||||
})?;
|
||||
if let Some(mut resolved) = runfiles::rlocation!(runfiles, &raw) {
|
||||
if !resolved.is_absolute() {
|
||||
resolved = std::env::current_dir()
|
||||
.map_err(|source| CargoBinError::CurrentDir { source })?
|
||||
.join(resolved);
|
||||
}
|
||||
if resolved.exists() {
|
||||
return Ok(resolved);
|
||||
}
|
||||
}
|
||||
} else if raw.is_absolute() && raw.exists() {
|
||||
return Ok(raw);
|
||||
}
|
||||
|
||||
Err(CargoBinError::ResolvedPathDoesNotExist {
|
||||
key: key.to_owned(),
|
||||
path: raw,
|
||||
})
|
||||
}
|
||||
|
||||
/// Macro that derives the path to a test resource at runtime, the value of
|
||||
/// which depends on whether Cargo or Bazel is being used to build and run a
|
||||
/// test. Note the return value may be a relative or absolute path.
|
||||
/// (Incidentally, this is a macro rather than a function because it reads
|
||||
/// compile-time environment variables that need to be captured at the call
|
||||
/// site.)
|
||||
///
|
||||
/// This is expected to be used exclusively in test code because Codex CLI is a
|
||||
/// standalone binary with no packaged resources.
|
||||
#[macro_export]
|
||||
macro_rules! find_resource {
|
||||
($resource:expr) => {{
|
||||
let resource = std::path::Path::new(&$resource);
|
||||
if $crate::runfiles_available() {
|
||||
// When this code is built and run with Bazel:
|
||||
// - we inject `BAZEL_PACKAGE` as a compile-time environment variable
|
||||
// that points to native.package_name()
|
||||
// - at runtime, Bazel will set runfiles-related env vars
|
||||
$crate::resolve_bazel_runfile(option_env!("BAZEL_PACKAGE"), resource)
|
||||
} else {
|
||||
let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
Ok(manifest_dir.join(resource))
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub fn resolve_bazel_runfile(
|
||||
bazel_package: Option<&str>,
|
||||
resource: &Path,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
let runfiles = runfiles::Runfiles::create()
|
||||
.map_err(|err| std::io::Error::other(format!("failed to create runfiles: {err}")))?;
|
||||
let runfile_path = match bazel_package {
|
||||
Some(bazel_package) => PathBuf::from("_main").join(bazel_package).join(resource),
|
||||
None => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"BAZEL_PACKAGE was not set at compile time",
|
||||
));
|
||||
}
|
||||
};
|
||||
let runfile_path = normalize_runfile_path(&runfile_path);
|
||||
if let Some(resolved) = runfiles::rlocation!(runfiles, &runfile_path)
|
||||
&& resolved.exists()
|
||||
{
|
||||
return Ok(resolved);
|
||||
}
|
||||
let runfile_path_display = runfile_path.display();
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
format!("runfile does not exist at: {runfile_path_display}"),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn resolve_cargo_runfile(resource: &Path) -> std::io::Result<PathBuf> {
|
||||
let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
Ok(manifest_dir.join(resource))
|
||||
}
|
||||
|
||||
pub fn repo_root() -> io::Result<PathBuf> {
|
||||
let marker = if runfiles_available() {
|
||||
let runfiles = runfiles::Runfiles::create()
|
||||
.map_err(|err| io::Error::other(format!("failed to create runfiles: {err}")))?;
|
||||
let marker_path = option_env!("AKODE_REPO_ROOT_MARKER")
|
||||
.map(PathBuf::from)
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"AKODE_REPO_ROOT_MARKER was not set at compile time",
|
||||
)
|
||||
})?;
|
||||
runfiles::rlocation!(runfiles, &marker_path).ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"repo_root.marker not available in runfiles",
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
resolve_cargo_runfile(Path::new("repo_root.marker"))?
|
||||
};
|
||||
let mut root = marker;
|
||||
for _ in 0..4 {
|
||||
root = root
|
||||
.parent()
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"repo_root.marker did not have expected parent depth",
|
||||
)
|
||||
})?
|
||||
.to_path_buf();
|
||||
}
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
fn normalize_runfile_path(path: &Path) -> PathBuf {
|
||||
let mut components = Vec::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir => {
|
||||
if matches!(components.last(), Some(std::path::Component::Normal(_))) {
|
||||
components.pop();
|
||||
} else {
|
||||
components.push(component);
|
||||
}
|
||||
}
|
||||
_ => components.push(component),
|
||||
}
|
||||
}
|
||||
|
||||
components
|
||||
.into_iter()
|
||||
.fold(PathBuf::new(), |mut acc, component| {
|
||||
acc.push(component.as_os_str());
|
||||
acc
|
||||
})
|
||||
}
|
||||
6
akode-rs/utils/cli/BUILD.bazel
Normal file
6
akode-rs/utils/cli/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "cli",
|
||||
crate_name = "akode_utils_cli",
|
||||
)
|
||||
21
akode-rs/utils/cli/Cargo.toml
Normal file
21
akode-rs/utils/cli/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "akode-utils-cli"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
clap = { workspace = true, features = ["derive", "wrap_help"] }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-shell-command = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
toml = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
25
akode-rs/utils/cli/src/approval_mode_cli_arg.rs
Normal file
25
akode-rs/utils/cli/src/approval_mode_cli_arg.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
//! Standard type to use with the `--approval-mode` CLI option.
|
||||
|
||||
use clap::ValueEnum;
|
||||
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
#[value(rename_all = "kebab-case")]
|
||||
pub enum ApprovalModeCliArg {
|
||||
/// The model decides when to ask the user for approval.
|
||||
OnRequest,
|
||||
|
||||
/// Never ask for user approval
|
||||
/// Execution failures are immediately returned to the model.
|
||||
Never,
|
||||
}
|
||||
|
||||
impl From<ApprovalModeCliArg> for AskForApproval {
|
||||
fn from(value: ApprovalModeCliArg) -> Self {
|
||||
match value {
|
||||
ApprovalModeCliArg::OnRequest => AskForApproval::OnRequest,
|
||||
ApprovalModeCliArg::Never => AskForApproval::Never,
|
||||
}
|
||||
}
|
||||
}
|
||||
203
akode-rs/utils/cli/src/config_override.rs
Normal file
203
akode-rs/utils/cli/src/config_override.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
//! Support for `-c key=value` overrides shared across Codex CLI tools.
|
||||
//!
|
||||
//! This module provides a [`CliConfigOverrides`] struct that can be embedded
|
||||
//! into a `clap`-derived CLI struct using `#[clap(flatten)]`. Each occurrence
|
||||
//! of `-c key=value` (or `--config key=value`) will be collected as a raw
|
||||
//! string. Helper methods are provided to convert the raw strings into
|
||||
//! key/value pairs as well as to apply them onto a mutable
|
||||
//! `serde_json::Value` representing the configuration tree.
|
||||
|
||||
use clap::ArgAction;
|
||||
use clap::Parser;
|
||||
use serde::de::Error as SerdeError;
|
||||
use toml::Value;
|
||||
|
||||
/// CLI option that captures arbitrary configuration overrides specified as
|
||||
/// `-c key=value`. It intentionally keeps both halves **unparsed** so that the
|
||||
/// calling code can decide how to interpret the right-hand side.
|
||||
#[derive(Parser, Debug, Default, Clone)]
|
||||
pub struct CliConfigOverrides {
|
||||
/// Override a configuration value that would otherwise be loaded from
|
||||
/// `~/.akode/config.toml`. Use a dotted path (`foo.bar.baz`) to override
|
||||
/// nested values. The `value` portion is parsed as TOML. If it fails to
|
||||
/// parse as TOML, the raw string is used as a literal.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `-c model="o3"`
|
||||
/// - `-c 'sandbox_permissions=["disk-full-read-access"]'`
|
||||
/// - `-c shell_environment_policy.inherit=all`
|
||||
#[arg(
|
||||
short = 'c',
|
||||
long = "config",
|
||||
value_name = "key=value",
|
||||
action = ArgAction::Append,
|
||||
global = true,
|
||||
)]
|
||||
pub raw_overrides: Vec<String>,
|
||||
}
|
||||
|
||||
impl CliConfigOverrides {
|
||||
/// Prepend root-level config flags so they have lower precedence than
|
||||
/// command-specific flags parsed after a subcommand.
|
||||
pub fn prepend_root_overrides(&mut self, root_overrides: Self) {
|
||||
self.raw_overrides
|
||||
.splice(0..0, root_overrides.raw_overrides);
|
||||
}
|
||||
|
||||
/// Parse the raw strings captured from the CLI into a list of `(path,
|
||||
/// value)` tuples where `value` is a `serde_json::Value`.
|
||||
pub fn parse_overrides(&self) -> Result<Vec<(String, Value)>, String> {
|
||||
self.raw_overrides
|
||||
.iter()
|
||||
.map(|s| {
|
||||
// Only split on the *first* '=' so values are free to contain
|
||||
// the character.
|
||||
let mut parts = s.splitn(2, '=');
|
||||
let key = match parts.next() {
|
||||
Some(k) => k.trim(),
|
||||
None => return Err("Override missing key".to_string()),
|
||||
};
|
||||
let value_str = parts
|
||||
.next()
|
||||
.ok_or_else(|| format!("Invalid override (missing '='): {s}"))?
|
||||
.trim();
|
||||
|
||||
if key.is_empty() {
|
||||
return Err(format!("Empty key in override: {s}"));
|
||||
}
|
||||
|
||||
// Attempt to parse as TOML. If that fails, treat it as a raw
|
||||
// string. This allows convenient usage such as
|
||||
// `-c model=o3` without the quotes.
|
||||
let value: Value = match parse_toml_value(value_str) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
// Strip leading/trailing quotes if present
|
||||
let trimmed = value_str.trim().trim_matches(|c| c == '"' || c == '\'');
|
||||
Value::String(trimmed.to_string())
|
||||
}
|
||||
};
|
||||
|
||||
Ok((canonicalize_override_key(key), value))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn canonicalize_override_key(key: &str) -> String {
|
||||
if key == "use_legacy_landlock" {
|
||||
"features.use_legacy_landlock".to_string()
|
||||
} else {
|
||||
key.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_toml_value(raw: &str) -> Result<Value, toml::de::Error> {
|
||||
let wrapped = format!("_x_ = {raw}");
|
||||
let table: toml::Table = toml::from_str(&wrapped)?;
|
||||
table
|
||||
.get("_x_")
|
||||
.cloned()
|
||||
.ok_or_else(|| SerdeError::custom("missing sentinel key"))
|
||||
}
|
||||
|
||||
/// Collects config overrides across command boundaries in argument order.
|
||||
///
|
||||
/// Clap keeps the deepest global argument's values instead of appending across
|
||||
/// scopes. Reparse with local config arguments after validating the typed CLI.
|
||||
pub fn collect_config_overrides(
|
||||
command: clap::Command,
|
||||
args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
|
||||
) -> Result<CliConfigOverrides, clap::Error> {
|
||||
let matches = localize_config_arg(command).try_get_matches_from(args)?;
|
||||
let raw_overrides = std::iter::successors(Some(&matches), |scope| {
|
||||
scope.subcommand().map(|(_, child)| child)
|
||||
})
|
||||
.filter_map(|scope| scope.get_many::<String>("raw_overrides"))
|
||||
.flatten()
|
||||
.cloned()
|
||||
.collect();
|
||||
Ok(CliConfigOverrides { raw_overrides })
|
||||
}
|
||||
|
||||
fn localize_config_arg(mut command: clap::Command) -> clap::Command {
|
||||
use clap::CommandFactory;
|
||||
|
||||
if !command
|
||||
.get_arguments()
|
||||
.any(|arg| arg.get_id() == "raw_overrides")
|
||||
{
|
||||
command = command.args(CliConfigOverrides::command().get_arguments().cloned());
|
||||
}
|
||||
command
|
||||
.mut_arg("raw_overrides", |arg| arg.global(false))
|
||||
.mut_subcommands(localize_config_arg)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_basic_scalar() {
|
||||
let v = parse_toml_value("42").expect("parse");
|
||||
assert_eq!(v.as_integer(), Some(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_bool() {
|
||||
let true_literal = parse_toml_value("true").expect("parse");
|
||||
assert_eq!(true_literal.as_bool(), Some(true));
|
||||
|
||||
let false_literal = parse_toml_value("false").expect("parse");
|
||||
assert_eq!(false_literal.as_bool(), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fails_on_unquoted_string() {
|
||||
assert!(parse_toml_value("hello").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_array() {
|
||||
let v = parse_toml_value("[1, 2, 3]").expect("parse");
|
||||
let arr = v.as_array().expect("array");
|
||||
assert_eq!(arr.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonicalizes_use_legacy_landlock_alias() {
|
||||
let overrides = CliConfigOverrides {
|
||||
raw_overrides: vec!["use_legacy_landlock=true".to_string()],
|
||||
};
|
||||
let parsed = overrides.parse_overrides().expect("parse_overrides");
|
||||
assert_eq!(parsed[0].0.as_str(), "features.use_legacy_landlock");
|
||||
assert_eq!(parsed[0].1.as_bool(), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepends_root_overrides() {
|
||||
let mut subcommand_overrides = CliConfigOverrides {
|
||||
raw_overrides: vec![r#"model="gpt-5.2""#.to_string()],
|
||||
};
|
||||
subcommand_overrides.prepend_root_overrides(CliConfigOverrides {
|
||||
raw_overrides: vec![r#"model="gpt-5.1""#.to_string()],
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
subcommand_overrides.raw_overrides,
|
||||
vec![
|
||||
r#"model="gpt-5.1""#.to_string(),
|
||||
r#"model="gpt-5.2""#.to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_inline_table() {
|
||||
let v = parse_toml_value("{a = 1, b = 2}").expect("parse");
|
||||
let tbl = v.as_table().expect("table");
|
||||
assert_eq!(tbl.get("a").unwrap().as_integer(), Some(1));
|
||||
assert_eq!(tbl.get("b").unwrap().as_integer(), Some(2));
|
||||
}
|
||||
}
|
||||
72
akode-rs/utils/cli/src/format_env_display.rs
Normal file
72
akode-rs/utils/cli/src/format_env_display.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub fn format_env_display<S: AsRef<str>>(
|
||||
env: Option<&HashMap<String, String>>,
|
||||
env_vars: &[S],
|
||||
) -> String {
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
|
||||
if let Some(map) = env {
|
||||
let mut pairs: Vec<_> = map.iter().collect();
|
||||
pairs.sort_by_key(|(key, _)| *key);
|
||||
parts.extend(pairs.into_iter().map(|(key, _)| format!("{key}=*****")));
|
||||
}
|
||||
|
||||
if !env_vars.is_empty() {
|
||||
parts.extend(env_vars.iter().map(|var| format!("{}=*****", var.as_ref())));
|
||||
}
|
||||
|
||||
if parts.is_empty() {
|
||||
"-".to_string()
|
||||
} else {
|
||||
parts.join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn returns_dash_when_empty() {
|
||||
let empty_vars: &[String] = &[];
|
||||
assert_eq!(format_env_display(/*env*/ None, empty_vars), "-");
|
||||
|
||||
let empty_map = HashMap::new();
|
||||
assert_eq!(format_env_display(Some(&empty_map), empty_vars), "-");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_sorted_env_pairs() {
|
||||
let mut env = HashMap::new();
|
||||
env.insert("B".to_string(), "two".to_string());
|
||||
env.insert("A".to_string(), "one".to_string());
|
||||
|
||||
assert_eq!(
|
||||
format_env_display(Some(&env), &[] as &[String]),
|
||||
"A=*****, B=*****"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_env_vars_with_dollar_prefix() {
|
||||
let vars = vec!["TOKEN".to_string(), "PATH".to_string()];
|
||||
|
||||
assert_eq!(
|
||||
format_env_display(/*env*/ None, &vars),
|
||||
"TOKEN=*****, PATH=*****"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combines_env_pairs_and_vars() {
|
||||
let mut env = HashMap::new();
|
||||
env.insert("HOME".to_string(), "/tmp".to_string());
|
||||
let vars = vec!["TOKEN".to_string()];
|
||||
|
||||
assert_eq!(
|
||||
format_env_display(Some(&env), &vars),
|
||||
"HOME=*****, TOKEN=*****"
|
||||
);
|
||||
}
|
||||
}
|
||||
16
akode-rs/utils/cli/src/lib.rs
Normal file
16
akode-rs/utils/cli/src/lib.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
mod approval_mode_cli_arg;
|
||||
mod config_override;
|
||||
pub(crate) mod format_env_display;
|
||||
mod resume_command;
|
||||
mod sandbox_mode_cli_arg;
|
||||
mod shared_options;
|
||||
|
||||
pub use approval_mode_cli_arg::ApprovalModeCliArg;
|
||||
pub use akode_protocol::config_types::ProfileV2Name;
|
||||
pub use config_override::CliConfigOverrides;
|
||||
pub use config_override::collect_config_overrides;
|
||||
pub use format_env_display::format_env_display;
|
||||
pub use resume_command::resume_command;
|
||||
pub use resume_command::resume_hint;
|
||||
pub use sandbox_mode_cli_arg::SandboxModeCliArg;
|
||||
pub use shared_options::SharedCliOptions;
|
||||
103
akode-rs/utils/cli/src/resume_command.rs
Normal file
103
akode-rs/utils/cli/src/resume_command.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Shared formatting for user-facing `akode resume` command hints.
|
||||
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_shell_command::parse_command::shlex_join;
|
||||
|
||||
pub fn resume_command(thread_name: Option<&str>, thread_id: Option<ThreadId>) -> Option<String> {
|
||||
let resume_target = thread_name
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
.or_else(|| thread_id.map(|thread_id| thread_id.to_string()));
|
||||
resume_target.map(|target| {
|
||||
let needs_double_dash = target.starts_with('-');
|
||||
let escaped = shlex_join(&[target]);
|
||||
if needs_double_dash {
|
||||
format!("codex resume -- {escaped}")
|
||||
} else {
|
||||
format!("codex resume {escaped}")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn resume_hint(thread_name: Option<&str>, thread_id: Option<ThreadId>) -> Option<String> {
|
||||
let thread_id = thread_id?;
|
||||
match thread_name.filter(|name| !name.is_empty()) {
|
||||
Some(thread_name) => Some(format!(
|
||||
"codex resume, then select {thread_name} ({thread_id})"
|
||||
)),
|
||||
None => resume_command(/*thread_name*/ None, Some(thread_id)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn prefers_name_over_id() {
|
||||
let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap();
|
||||
let command = resume_command(Some("my-thread"), Some(thread_id));
|
||||
assert_eq!(command, Some("codex resume my-thread".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_thread_id_when_name_is_missing() {
|
||||
let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap();
|
||||
let command = resume_command(/*thread_name*/ None, Some(thread_id));
|
||||
assert_eq!(
|
||||
command,
|
||||
Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_without_a_resume_target() {
|
||||
let command = resume_command(/*thread_name*/ None, /*thread_id*/ None);
|
||||
assert_eq!(command, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_thread_names_when_needed() {
|
||||
let command = resume_command(Some("-starts-with-dash"), /*thread_id*/ None);
|
||||
assert_eq!(
|
||||
command,
|
||||
Some("codex resume -- -starts-with-dash".to_string())
|
||||
);
|
||||
|
||||
let command = resume_command(Some("two words"), /*thread_id*/ None);
|
||||
assert_eq!(command, Some("codex resume 'two words'".to_string()));
|
||||
|
||||
let command = resume_command(Some("quote'case"), /*thread_id*/ None);
|
||||
assert_eq!(command, Some("codex resume \"quote'case\"".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_hint_names_picker_item_with_id() {
|
||||
let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap();
|
||||
let hint = resume_hint(Some("my-thread"), Some(thread_id));
|
||||
assert_eq!(
|
||||
hint,
|
||||
Some(
|
||||
"codex resume, then select my-thread (123e4567-e89b-12d3-a456-426614174000)"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_hint_uses_direct_id_command_without_name() {
|
||||
let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap();
|
||||
let hint = resume_hint(/*thread_name*/ None, Some(thread_id));
|
||||
assert_eq!(
|
||||
hint,
|
||||
Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_hint_requires_thread_id() {
|
||||
let hint = resume_hint(Some("my-thread"), /*thread_id*/ None);
|
||||
assert_eq!(hint, None);
|
||||
}
|
||||
}
|
||||
47
akode-rs/utils/cli/src/sandbox_mode_cli_arg.rs
Normal file
47
akode-rs/utils/cli/src/sandbox_mode_cli_arg.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
//! Standard type to use with the `--sandbox` (`-s`) CLI option.
|
||||
//!
|
||||
//! This mirrors the variants of [`akode_protocol::protocol::SandboxPolicy`], but
|
||||
//! without any of the associated data so it can be expressed as a simple flag
|
||||
//! on the command-line. Users that need to tweak the advanced options for
|
||||
//! `workspace-write` can continue to do so via `-c` overrides or their
|
||||
//! `config.toml`.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use akode_protocol::config_types::SandboxMode;
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
#[value(rename_all = "kebab-case")]
|
||||
pub enum SandboxModeCliArg {
|
||||
ReadOnly,
|
||||
WorkspaceWrite,
|
||||
DangerFullAccess,
|
||||
}
|
||||
|
||||
impl From<SandboxModeCliArg> for SandboxMode {
|
||||
fn from(value: SandboxModeCliArg) -> Self {
|
||||
match value {
|
||||
SandboxModeCliArg::ReadOnly => SandboxMode::ReadOnly,
|
||||
SandboxModeCliArg::WorkspaceWrite => SandboxMode::WorkspaceWrite,
|
||||
SandboxModeCliArg::DangerFullAccess => SandboxMode::DangerFullAccess,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn maps_cli_args_to_protocol_modes() {
|
||||
assert_eq!(SandboxMode::ReadOnly, SandboxModeCliArg::ReadOnly.into());
|
||||
assert_eq!(
|
||||
SandboxMode::WorkspaceWrite,
|
||||
SandboxModeCliArg::WorkspaceWrite.into()
|
||||
);
|
||||
assert_eq!(
|
||||
SandboxMode::DangerFullAccess,
|
||||
SandboxModeCliArg::DangerFullAccess.into()
|
||||
);
|
||||
}
|
||||
}
|
||||
220
akode-rs/utils/cli/src/shared_options.rs
Normal file
220
akode-rs/utils/cli/src/shared_options.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
//! Shared command-line flags used by both interactive and non-interactive Codex entry points.
|
||||
|
||||
use crate::CliConfigOverrides;
|
||||
use crate::SandboxModeCliArg;
|
||||
use clap::Args;
|
||||
use akode_protocol::config_types::ProfileV2Name;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Args, Clone, Debug, Default)]
|
||||
pub struct SharedCliOptions {
|
||||
/// Optional image(s) to attach to the initial prompt.
|
||||
#[arg(
|
||||
long = "image",
|
||||
short = 'i',
|
||||
value_name = "FILE",
|
||||
value_delimiter = ',',
|
||||
num_args = 1..
|
||||
)]
|
||||
pub images: Vec<PathBuf>,
|
||||
|
||||
/// Model the agent should use.
|
||||
#[arg(long, short = 'm')]
|
||||
pub model: Option<String>,
|
||||
|
||||
/// Use open-source provider.
|
||||
#[arg(long = "oss", default_value_t = false)]
|
||||
pub oss: bool,
|
||||
|
||||
/// Specify which local provider to use (lmstudio or ollama).
|
||||
/// If not specified with --oss, will use config default or show selection.
|
||||
#[arg(long = "local-provider")]
|
||||
pub oss_provider: Option<String>,
|
||||
|
||||
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
|
||||
#[arg(long = "profile", short = 'p')]
|
||||
pub config_profile_v2: Option<ProfileV2Name>,
|
||||
|
||||
/// Select the sandbox policy to use when executing model-generated shell
|
||||
/// commands.
|
||||
#[arg(long = "sandbox", short = 's')]
|
||||
pub sandbox_mode: Option<SandboxModeCliArg>,
|
||||
|
||||
/// Route approval requests through automatic review using the workspace-write sandbox.
|
||||
#[arg(
|
||||
long = "approve-for-me",
|
||||
alias = "not-so-yolo",
|
||||
default_value_t = false,
|
||||
conflicts_with_all = ["sandbox_mode", "dangerously_bypass_approvals_and_sandbox"]
|
||||
)]
|
||||
pub auto_review: bool,
|
||||
|
||||
/// Skip all confirmation prompts and execute commands without sandboxing.
|
||||
/// EXTREMELY DANGEROUS. Intended solely for running in environments that are externally sandboxed.
|
||||
#[arg(
|
||||
long = "dangerously-bypass-approvals-and-sandbox",
|
||||
alias = "yolo",
|
||||
default_value_t = false
|
||||
)]
|
||||
pub dangerously_bypass_approvals_and_sandbox: bool,
|
||||
|
||||
/// Run enabled hooks without requiring persisted hook trust for this invocation.
|
||||
/// DANGEROUS. Intended only for automation that already vets hook sources.
|
||||
#[arg(long = "dangerously-bypass-hook-trust", default_value_t = false)]
|
||||
pub bypass_hook_trust: bool,
|
||||
|
||||
/// Tell the agent to use the specified directory as its working root.
|
||||
#[clap(long = "cd", short = 'C', value_name = "DIR")]
|
||||
pub cwd: Option<PathBuf>,
|
||||
|
||||
/// Run the session in a new managed Git worktree.
|
||||
#[arg(long = "worktree", default_value_t = false)]
|
||||
pub worktree: bool,
|
||||
|
||||
/// Additional directories that should be writable alongside the primary workspace.
|
||||
#[arg(long = "add-dir", value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
|
||||
pub add_dir: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl SharedCliOptions {
|
||||
pub fn take_auto_review_config_overrides(&mut self, overrides: &mut CliConfigOverrides) {
|
||||
if self.auto_review {
|
||||
overrides
|
||||
.raw_overrides
|
||||
.push(r#"approvals_reviewer="auto_review""#.to_string());
|
||||
overrides
|
||||
.raw_overrides
|
||||
.push(r#"approval_policy="on-request""#.to_string());
|
||||
overrides
|
||||
.raw_overrides
|
||||
.push(r#"sandbox_mode="workspace-write""#.to_string());
|
||||
self.auto_review = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn inherit_exec_root_options(&mut self, root: &Self) {
|
||||
let self_selected_sandbox_mode = self.sandbox_mode.is_some()
|
||||
|| self.auto_review
|
||||
|| self.dangerously_bypass_approvals_and_sandbox;
|
||||
let Self {
|
||||
images,
|
||||
model,
|
||||
oss,
|
||||
oss_provider,
|
||||
config_profile_v2,
|
||||
sandbox_mode,
|
||||
auto_review,
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
bypass_hook_trust,
|
||||
cwd,
|
||||
worktree,
|
||||
add_dir,
|
||||
} = self;
|
||||
let Self {
|
||||
images: root_images,
|
||||
model: root_model,
|
||||
oss: root_oss,
|
||||
oss_provider: root_oss_provider,
|
||||
config_profile_v2: root_config_profile_v2,
|
||||
sandbox_mode: root_sandbox_mode,
|
||||
auto_review: root_auto_review,
|
||||
dangerously_bypass_approvals_and_sandbox: root_dangerously_bypass_approvals_and_sandbox,
|
||||
bypass_hook_trust: root_bypass_hook_trust,
|
||||
cwd: root_cwd,
|
||||
worktree: root_worktree,
|
||||
add_dir: root_add_dir,
|
||||
} = root;
|
||||
|
||||
if model.is_none() {
|
||||
model.clone_from(root_model);
|
||||
}
|
||||
if *root_oss {
|
||||
*oss = true;
|
||||
}
|
||||
if oss_provider.is_none() {
|
||||
oss_provider.clone_from(root_oss_provider);
|
||||
}
|
||||
if config_profile_v2.is_none() {
|
||||
config_profile_v2.clone_from(root_config_profile_v2);
|
||||
}
|
||||
if !self_selected_sandbox_mode {
|
||||
*sandbox_mode = *root_sandbox_mode;
|
||||
*auto_review = *root_auto_review;
|
||||
*dangerously_bypass_approvals_and_sandbox =
|
||||
*root_dangerously_bypass_approvals_and_sandbox;
|
||||
}
|
||||
if !*bypass_hook_trust {
|
||||
*bypass_hook_trust = *root_bypass_hook_trust;
|
||||
}
|
||||
if cwd.is_none() {
|
||||
cwd.clone_from(root_cwd);
|
||||
}
|
||||
*worktree |= *root_worktree;
|
||||
if !root_images.is_empty() {
|
||||
let mut merged_images = root_images.clone();
|
||||
merged_images.append(images);
|
||||
*images = merged_images;
|
||||
}
|
||||
if !root_add_dir.is_empty() {
|
||||
let mut merged_add_dir = root_add_dir.clone();
|
||||
merged_add_dir.append(add_dir);
|
||||
*add_dir = merged_add_dir;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_subcommand_overrides(&mut self, subcommand: Self) {
|
||||
let subcommand_selected_sandbox_mode = subcommand.sandbox_mode.is_some()
|
||||
|| subcommand.auto_review
|
||||
|| subcommand.dangerously_bypass_approvals_and_sandbox;
|
||||
let Self {
|
||||
images,
|
||||
model,
|
||||
oss,
|
||||
oss_provider,
|
||||
config_profile_v2,
|
||||
sandbox_mode,
|
||||
auto_review,
|
||||
dangerously_bypass_approvals_and_sandbox,
|
||||
bypass_hook_trust,
|
||||
cwd,
|
||||
worktree,
|
||||
add_dir,
|
||||
} = subcommand;
|
||||
|
||||
if let Some(model) = model {
|
||||
self.model = Some(model);
|
||||
}
|
||||
if oss {
|
||||
self.oss = true;
|
||||
}
|
||||
if let Some(oss_provider) = oss_provider {
|
||||
self.oss_provider = Some(oss_provider);
|
||||
}
|
||||
if let Some(config_profile_v2) = config_profile_v2 {
|
||||
self.config_profile_v2 = Some(config_profile_v2);
|
||||
}
|
||||
if subcommand_selected_sandbox_mode {
|
||||
self.sandbox_mode = sandbox_mode;
|
||||
self.auto_review = auto_review;
|
||||
self.dangerously_bypass_approvals_and_sandbox =
|
||||
dangerously_bypass_approvals_and_sandbox;
|
||||
}
|
||||
if bypass_hook_trust {
|
||||
self.bypass_hook_trust = true;
|
||||
}
|
||||
if let Some(cwd) = cwd {
|
||||
self.cwd = Some(cwd);
|
||||
}
|
||||
self.worktree |= worktree;
|
||||
if !images.is_empty() {
|
||||
self.images = images;
|
||||
}
|
||||
if !add_dir.is_empty() {
|
||||
self.add_dir.extend(add_dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "shared_options_tests.rs"]
|
||||
mod tests;
|
||||
30
akode-rs/utils/cli/src/shared_options_tests.rs
Normal file
30
akode-rs/utils/cli/src/shared_options_tests.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
//! Tests shared command-line option inheritance.
|
||||
|
||||
use super::SharedCliOptions;
|
||||
|
||||
#[test]
|
||||
fn inherits_worktree_from_root_without_clearing_subcommand_choice() {
|
||||
let mut options = SharedCliOptions::default();
|
||||
let root = SharedCliOptions {
|
||||
worktree: true,
|
||||
..Default::default()
|
||||
};
|
||||
options.inherit_exec_root_options(&root);
|
||||
assert!(options.worktree);
|
||||
|
||||
options.inherit_exec_root_options(&SharedCliOptions::default());
|
||||
assert!(options.worktree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_worktree_subcommand_override_without_clearing_root_choice() {
|
||||
let mut options = SharedCliOptions::default();
|
||||
options.apply_subcommand_overrides(SharedCliOptions {
|
||||
worktree: true,
|
||||
..Default::default()
|
||||
});
|
||||
assert!(options.worktree);
|
||||
|
||||
options.apply_subcommand_overrides(SharedCliOptions::default());
|
||||
assert!(options.worktree);
|
||||
}
|
||||
6
akode-rs/utils/critical-path/BUILD.bazel
Normal file
6
akode-rs/utils/critical-path/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "critical-path",
|
||||
crate_name = "akode_utils_critical_path",
|
||||
)
|
||||
14
akode-rs/utils/critical-path/Cargo.toml
Normal file
14
akode-rs/utils/critical-path/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "akode-utils-critical-path"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions.workspace = true
|
||||
615
akode-rs/utils/critical-path/src/critical_path_tests.rs
Normal file
615
akode-rs/utils/critical-path/src/critical_path_tests.rs
Normal file
@@ -0,0 +1,615 @@
|
||||
//! Reducer coverage for exclusive attribution, parallel joins, ties, and incomplete evidence.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn join_replaces_overlapping_work_with_the_full_winning_branch() {
|
||||
let turn_start = Instant::now();
|
||||
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
|
||||
let shared_initial_path = CriticalPath::default().work(
|
||||
time_after_turn_start(0),
|
||||
time_after_turn_start(100),
|
||||
WorkKind::Sampling,
|
||||
);
|
||||
let reviewed_tool_path = shared_initial_path
|
||||
.clone()
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(300),
|
||||
WorkKind::AutoReview,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(300),
|
||||
time_after_turn_start(400),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
let parallel_tool_path = shared_initial_path.clone().work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(700),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
let critical_path = shared_initial_path
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(200),
|
||||
WorkKind::Sampling,
|
||||
)
|
||||
.join(
|
||||
time_after_turn_start(200),
|
||||
time_after_turn_start(700),
|
||||
reviewed_tool_path.latest(parallel_tool_path),
|
||||
);
|
||||
assert_eq!(
|
||||
critical_path.durations(time_after_turn_start(0), time_after_turn_start(700)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(100),
|
||||
tools: Duration::from_millis(600),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_serial_dependencies_preserve_exclusive_categories() {
|
||||
let turn_start = Instant::now();
|
||||
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
|
||||
let shared_initial_path = CriticalPath::default().work(
|
||||
time_after_turn_start(0),
|
||||
time_after_turn_start(100),
|
||||
WorkKind::Sampling,
|
||||
);
|
||||
let child_path = shared_initial_path
|
||||
.clone()
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(300),
|
||||
WorkKind::AutoReview,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(300),
|
||||
time_after_turn_start(400),
|
||||
WorkKind::Tools,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(400),
|
||||
time_after_turn_start(500),
|
||||
WorkKind::Compaction,
|
||||
);
|
||||
let critical_path = shared_initial_path
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(200),
|
||||
WorkKind::Sampling,
|
||||
)
|
||||
.join(
|
||||
time_after_turn_start(200),
|
||||
time_after_turn_start(600),
|
||||
child_path,
|
||||
);
|
||||
assert_eq!(
|
||||
critical_path.durations(time_after_turn_start(0), time_after_turn_start(600)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(100),
|
||||
compaction: Duration::from_millis(100),
|
||||
auto_review: Duration::from_millis(200),
|
||||
auto_review_overhead: None,
|
||||
tools: Duration::from_millis(200),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_finish_times_select_one_path_without_double_counting() {
|
||||
let turn_start = Instant::now();
|
||||
let turn_end = turn_start + Duration::from_millis(100);
|
||||
let reviewed_tool_path =
|
||||
CriticalPath::default().work(turn_start, turn_end, WorkKind::AutoReview);
|
||||
let inference_path = CriticalPath::default().work(turn_start, turn_end, WorkKind::Sampling);
|
||||
// A tie has multiple valid paths. Stable left selection does not sum both.
|
||||
assert_eq!(
|
||||
reviewed_tool_path
|
||||
.clone()
|
||||
.latest(inference_path)
|
||||
.durations(turn_start, turn_end),
|
||||
reviewed_tool_path.durations(turn_start, turn_end)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_retention_exhaustion_marks_unknown_instead_of_claiming_zero() {
|
||||
let turn_start = Instant::now();
|
||||
let mut critical_path = CriticalPath::default();
|
||||
for segment_index in 0..=MAX_PATH_DEPTH {
|
||||
critical_path = critical_path.work(
|
||||
turn_start + Duration::from_micros(segment_index as u64),
|
||||
turn_start + Duration::from_micros(segment_index as u64 + 1),
|
||||
WorkKind::Sampling,
|
||||
);
|
||||
}
|
||||
let turn_end = turn_start + Duration::from_micros(MAX_PATH_DEPTH as u64 + 1);
|
||||
assert_eq!(
|
||||
critical_path.durations(turn_start, turn_end),
|
||||
PathDurations {
|
||||
unknown: turn_end.duration_since(turn_start),
|
||||
auto_review_overhead: None,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewed_branch_wins_even_when_some_review_overlapped_parent_inference() {
|
||||
let turn_start = Instant::now();
|
||||
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
|
||||
let shared_initial_path = CriticalPath::default().work(
|
||||
time_after_turn_start(0),
|
||||
time_after_turn_start(100),
|
||||
WorkKind::Sampling,
|
||||
);
|
||||
let reviewed_tool_path = shared_initial_path
|
||||
.clone()
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(300),
|
||||
WorkKind::AutoReview,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(300),
|
||||
time_after_turn_start(400),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
let parallel_tool_path = shared_initial_path.clone().work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(350),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
let critical_path = shared_initial_path
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(200),
|
||||
WorkKind::Sampling,
|
||||
)
|
||||
.join(
|
||||
time_after_turn_start(200),
|
||||
time_after_turn_start(400),
|
||||
reviewed_tool_path.latest(parallel_tool_path),
|
||||
);
|
||||
assert_eq!(
|
||||
critical_path.durations(time_after_turn_start(0), time_after_turn_start(400)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(100),
|
||||
auto_review: Duration::from_millis(200),
|
||||
auto_review_overhead: None,
|
||||
tools: Duration::from_millis(100),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn durations_clip_work_to_the_window_and_attribute_gaps_to_overhead() {
|
||||
let turn_start = Instant::now();
|
||||
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
|
||||
let critical_path = CriticalPath::default()
|
||||
.work(
|
||||
time_after_turn_start(10),
|
||||
time_after_turn_start(30),
|
||||
WorkKind::Sampling,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(50),
|
||||
time_after_turn_start(90),
|
||||
WorkKind::AutoReview,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
critical_path.durations(time_after_turn_start(0), time_after_turn_start(100)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(20),
|
||||
auto_review: Duration::from_millis(40),
|
||||
auto_review_overhead: None,
|
||||
overhead: Duration::from_millis(40),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
critical_path.durations(time_after_turn_start(20), time_after_turn_start(80)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(10),
|
||||
auto_review: Duration::from_millis(30),
|
||||
auto_review_overhead: None,
|
||||
overhead: Duration::from_millis(20),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_work_only_attributes_time_after_the_existing_path() {
|
||||
let turn_start = Instant::now();
|
||||
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
|
||||
let critical_path = CriticalPath::default()
|
||||
.work(
|
||||
time_after_turn_start(0),
|
||||
time_after_turn_start(10),
|
||||
WorkKind::Sampling,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(5),
|
||||
time_after_turn_start(20),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
critical_path.durations(time_after_turn_start(0), time_after_turn_start(20)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(10),
|
||||
tools: Duration::from_millis(10),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
critical_path.clone().work(
|
||||
time_after_turn_start(5),
|
||||
time_after_turn_start(15),
|
||||
WorkKind::AutoReview
|
||||
),
|
||||
critical_path
|
||||
);
|
||||
assert_eq!(
|
||||
critical_path.clone().work(
|
||||
time_after_turn_start(20),
|
||||
time_after_turn_start(20),
|
||||
WorkKind::Unknown
|
||||
),
|
||||
critical_path
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_path_debug_output_is_bounded_on_a_small_stack() {
|
||||
// Match a typical 2 MiB worker stack rather than nextest's larger test stack.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(2 * 1024 * 1024)
|
||||
.spawn(|| {
|
||||
let start = Instant::now();
|
||||
let mut path = CriticalPath::default();
|
||||
for index in 0..10_000 {
|
||||
path = path.work(
|
||||
start + Duration::from_micros(index),
|
||||
start + Duration::from_micros(index + 1),
|
||||
WorkKind::Sampling,
|
||||
);
|
||||
}
|
||||
assert!(format!("{path:?}").len() < 512);
|
||||
assert!(format!("{path:#?}").len() < 512);
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_prefixes_can_be_released_concurrently_on_small_stacks() {
|
||||
for _ in 0..8 {
|
||||
let start = Instant::now();
|
||||
let mut path = CriticalPath::default();
|
||||
let mut prefixes = [Vec::new(), Vec::new()];
|
||||
for index in 0..MAX_PATH_DEPTH {
|
||||
path = path.work(
|
||||
start + Duration::from_micros(index as u64),
|
||||
start + Duration::from_micros(index as u64 + 1),
|
||||
WorkKind::Sampling,
|
||||
);
|
||||
prefixes[index % 2].push(path.clone());
|
||||
}
|
||||
// Only the workers retain nodes when they begin releasing prefixes.
|
||||
drop(path);
|
||||
let ready = Arc::new(std::sync::Barrier::new(3));
|
||||
let workers = prefixes.map(|mut prefixes| {
|
||||
let ready = Arc::clone(&ready);
|
||||
std::thread::Builder::new()
|
||||
.stack_size(2 * 1024 * 1024)
|
||||
.spawn(move || {
|
||||
ready.wait();
|
||||
// Release newest first so adjacent retained prefixes race
|
||||
// to become the last owner of the shared chain.
|
||||
while let Some(prefix) = prefixes.pop() {
|
||||
drop(prefix);
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
});
|
||||
ready.wait();
|
||||
for worker in workers {
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn human_wait_is_retained_only_on_the_selected_parallel_path() {
|
||||
let start = Instant::now();
|
||||
let time_after_turn_start = |milliseconds| start + Duration::from_millis(milliseconds);
|
||||
let prefix =
|
||||
CriticalPath::default().work(start, time_after_turn_start(100), WorkKind::Sampling);
|
||||
let reviewed_tool = prefix
|
||||
.clone()
|
||||
.work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(200),
|
||||
WorkKind::AutoReview,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(200),
|
||||
time_after_turn_start(500),
|
||||
WorkKind::UserWait,
|
||||
)
|
||||
.work(
|
||||
time_after_turn_start(500),
|
||||
time_after_turn_start(600),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
let parallel_tool = prefix.clone().work(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(400),
|
||||
WorkKind::Tools,
|
||||
);
|
||||
let path = prefix.join(
|
||||
time_after_turn_start(100),
|
||||
time_after_turn_start(600),
|
||||
parallel_tool.latest(reviewed_tool),
|
||||
);
|
||||
assert_eq!(
|
||||
path.durations(start, time_after_turn_start(600)),
|
||||
PathDurations {
|
||||
sampling: Duration::from_millis(100),
|
||||
auto_review: Duration::from_millis(100),
|
||||
auto_review_overhead: None,
|
||||
user_wait: Duration::from_millis(300),
|
||||
tools: Duration::from_millis(100),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn observed_review(intervals: &[(Instant, Instant)]) -> ReviewExecution {
|
||||
let review = ReviewExecution::default();
|
||||
review.observe();
|
||||
for &(start, end) in intervals {
|
||||
review.started(start);
|
||||
review.completed(start, end);
|
||||
}
|
||||
review.seal();
|
||||
review
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_overhead_is_the_execution_complement_and_clips_to_the_requested_window() {
|
||||
let start = Instant::now();
|
||||
let at = |ms| start + Duration::from_millis(ms);
|
||||
let review = observed_review(&[(at(1000), at(4633))]);
|
||||
let path = CriticalPath::default().auto_review(start, at(5000), vec![review]);
|
||||
assert_eq!(
|
||||
path.durations(start, at(5000)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(5000),
|
||||
auto_review_overhead: Some(Duration::from_millis(1367)),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
path.durations(at(500), at(4800)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(4300),
|
||||
auto_review_overhead: Some(Duration::from_millis(667)),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_reviews_and_retries_subtract_a_clipped_union_once() {
|
||||
let start = Instant::now();
|
||||
let at = |ms| start + Duration::from_millis(ms);
|
||||
let first = observed_review(&[(at(0), at(30)), (at(25), at(50))]);
|
||||
let second = observed_review(&[(at(40), at(60)), (at(80), at(120))]);
|
||||
let path = CriticalPath::default().auto_review(at(10), at(100), vec![first, second]);
|
||||
assert_eq!(
|
||||
path.durations(at(10), at(100)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(90),
|
||||
auto_review_overhead: Some(Duration::from_millis(20)),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn human_wait_overlap_is_excluded_from_both_review_components() {
|
||||
let start = Instant::now();
|
||||
let at = |ms| start + Duration::from_millis(ms);
|
||||
let review = observed_review(&[(at(20), at(80))]);
|
||||
let path = CriticalPath::default()
|
||||
.auto_review(start, at(40), vec![review.clone()])
|
||||
.work(at(40), at(70), WorkKind::UserWait)
|
||||
.auto_review(at(70), at(100), vec![review]);
|
||||
assert_eq!(
|
||||
path.durations(start, at(100)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(70),
|
||||
auto_review_overhead: Some(Duration::from_millis(40)),
|
||||
user_wait: Duration::from_millis(30),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_review_has_only_overhead_and_losing_review_has_no_contribution() {
|
||||
let start = Instant::now();
|
||||
let at = |ms| start + Duration::from_millis(ms);
|
||||
let reviewed = CriticalPath::default().auto_review(start, at(10), vec![observed_review(&[])]);
|
||||
assert_eq!(
|
||||
reviewed.durations(start, at(10)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(10),
|
||||
auto_review_overhead: Some(Duration::from_millis(10)),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
let winner = CriticalPath::default().work(start, at(20), WorkKind::Tools);
|
||||
assert_eq!(
|
||||
reviewed.latest(winner).durations(start, at(20)),
|
||||
PathDurations {
|
||||
tools: Duration::from_millis(20),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_or_unobserved_reviews_leave_the_subcomponent_unknown() {
|
||||
let start = Instant::now();
|
||||
let end = start + Duration::from_millis(10);
|
||||
let unobserved = ReviewExecution::default();
|
||||
let canceled = ReviewExecution::default();
|
||||
canceled.observe();
|
||||
canceled.started(start);
|
||||
let missing = ReviewExecution::default();
|
||||
missing.observe();
|
||||
missing.mark_unknown();
|
||||
for review in [unobserved, canceled, missing] {
|
||||
review.seal();
|
||||
let path = CriticalPath::default().auto_review(start, end, vec![review.clone()]);
|
||||
let expected = PathDurations {
|
||||
auto_review: Duration::from_millis(10),
|
||||
auto_review_overhead: None,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(path.durations(start, end), expected);
|
||||
review.observe();
|
||||
review.completed(start, end);
|
||||
assert_eq!(path.durations(start, end), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_completed_retry_does_not_hide_another_canceled_attempt() {
|
||||
let start = Instant::now();
|
||||
let at = |ms| start + Duration::from_millis(ms);
|
||||
let review = ReviewExecution::default();
|
||||
review.observe();
|
||||
review.started(at(1));
|
||||
review.started(at(2));
|
||||
review.completed(at(2), at(5));
|
||||
review.seal();
|
||||
assert_eq!(
|
||||
CriticalPath::default()
|
||||
.auto_review(start, at(10), vec![review])
|
||||
.durations(start, at(10)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(10),
|
||||
auto_review_overhead: None,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indistinguishable_concurrent_attempts_remain_unknown_after_one_completes() {
|
||||
let start = Instant::now();
|
||||
let end = start + Duration::from_millis(10);
|
||||
let review = ReviewExecution::default();
|
||||
review.observe();
|
||||
review.started(start);
|
||||
review.started(start);
|
||||
review.completed(start, end);
|
||||
review.seal();
|
||||
assert_eq!(
|
||||
CriticalPath::default()
|
||||
.auto_review(start, end, vec![review])
|
||||
.durations(start, end),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(10),
|
||||
auto_review_overhead: None,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sealing_before_submission_starts_freezes_unknown_attribution() {
|
||||
let start = Instant::now();
|
||||
let end = start + Duration::from_millis(10);
|
||||
let review = ReviewExecution::default();
|
||||
review.observe();
|
||||
let attempt = review.start_attempt();
|
||||
review.seal();
|
||||
let path = CriticalPath::default().auto_review(start, end, vec![review.clone()]);
|
||||
let expected = PathDurations {
|
||||
auto_review: Duration::from_millis(10),
|
||||
auto_review_overhead: None,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(path.durations(start, end), expected);
|
||||
review.started(start);
|
||||
review.completed(start, end);
|
||||
attempt.finish(/*known*/ true);
|
||||
assert_eq!(path.durations(start, end), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_attempts_resolve_only_when_all_submissions_have_known_outcomes() {
|
||||
let start = Instant::now();
|
||||
let at = |ms| start + Duration::from_millis(ms);
|
||||
for known in [true, false] {
|
||||
let review = ReviewExecution::default();
|
||||
review.observe();
|
||||
let first = review.start_attempt();
|
||||
let second = review.start_attempt();
|
||||
review.started(at(2));
|
||||
review.completed(at(2), at(7));
|
||||
first.finish(/*known*/ true);
|
||||
let path = CriticalPath::default().auto_review(start, at(10), vec![review.clone()]);
|
||||
assert_eq!(path.durations(start, at(10)).auto_review_overhead, None);
|
||||
second.finish(known);
|
||||
review.seal();
|
||||
assert_eq!(
|
||||
path.durations(start, at(10)),
|
||||
PathDurations {
|
||||
auto_review: Duration::from_millis(10),
|
||||
auto_review_overhead: known.then_some(Duration::from_millis(5)),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_attempt_does_not_label_unobserved_execution_as_overhead() {
|
||||
for completed in [false, true] {
|
||||
let execution = ReviewExecution::default();
|
||||
execution.observe();
|
||||
let attempt = execution.start_attempt();
|
||||
let start = Instant::now();
|
||||
let end = start + Duration::from_millis(100);
|
||||
if completed {
|
||||
execution.started(start);
|
||||
execution.completed(start, end);
|
||||
attempt.finish(/*known*/ true);
|
||||
} else {
|
||||
drop(attempt);
|
||||
}
|
||||
execution.seal();
|
||||
let totals = CriticalPath::default()
|
||||
.auto_review(start, end, vec![execution])
|
||||
.durations(start, end);
|
||||
assert_eq!(
|
||||
totals.auto_review_overhead,
|
||||
completed.then_some(Duration::ZERO)
|
||||
);
|
||||
}
|
||||
}
|
||||
235
akode-rs/utils/critical-path/src/lib.rs
Normal file
235
akode-rs/utils/critical-path/src/lib.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
//! Persistent dependency paths and exclusive attribution over the observed turn interval.
|
||||
//! History is depth-limited; formatting and destruction never recurse through the chain.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
mod review_execution;
|
||||
pub use review_execution::ReviewExecution;
|
||||
pub use review_execution::ReviewExecutionAttempt;
|
||||
|
||||
const MAX_PATH_DEPTH: usize = 16_384;
|
||||
|
||||
/// Category attributed to an observed segment of dependency work.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum WorkKind {
|
||||
/// Model sampling work on the selected dependency path.
|
||||
Sampling,
|
||||
/// Compaction work, including its local bookkeeping.
|
||||
Compaction,
|
||||
/// Automatic review work, such as reviewing a tool call before execution.
|
||||
AutoReview,
|
||||
/// Time awaiting a human answer or approval on the selected dependency path.
|
||||
UserWait,
|
||||
/// Tool execution work, including work after a dependency join resumes.
|
||||
/// This is an aggregate category; tool-specific subtypes such as browser or
|
||||
/// computer use are not represented by this calculator.
|
||||
Tools,
|
||||
/// Time within the observed turn interval not covered by a recorded work segment.
|
||||
Overhead,
|
||||
/// Work whose category is unavailable, including history collapsed at the depth limit.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// A persistent observed dependency path. Review observers must be sealed before
|
||||
/// publishing completed paths. Forks share their prefix; a join
|
||||
/// retains only the dependency that actually released the waiting operation.
|
||||
/// Equality compares path identity rather than the contents of each segment.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct CriticalPath(Option<Arc<Node>>);
|
||||
|
||||
impl std::fmt::Debug for CriticalPath {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// Summarize the tail without traversing shared dependency history.
|
||||
f.debug_struct("CriticalPath")
|
||||
.field("depth", &self.0.as_ref().map_or(0, |node| node.depth))
|
||||
.field("end", &self.end())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CriticalPath {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (&self.0, &other.0) {
|
||||
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
|
||||
(None, None) => true,
|
||||
(Some(_), None) | (None, Some(_)) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for CriticalPath {}
|
||||
|
||||
struct Node {
|
||||
previous: CriticalPath,
|
||||
kind: WorkKind,
|
||||
reviews: Vec<ReviewExecution>,
|
||||
start: Instant,
|
||||
end: Instant,
|
||||
origin: Instant,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// Exclusive time attributed to each category within the requested interval.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct PathDurations {
|
||||
pub sampling: Duration,
|
||||
pub compaction: Duration,
|
||||
pub auto_review: Duration,
|
||||
/// Subcomponent of auto_review excluding the union of observed child execution.
|
||||
/// None means review attribution or dependency history is incomplete.
|
||||
pub auto_review_overhead: Option<Duration>,
|
||||
pub user_wait: Duration,
|
||||
pub tools: Duration,
|
||||
pub overhead: Duration,
|
||||
pub unknown: Duration,
|
||||
}
|
||||
|
||||
impl Default for PathDurations {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sampling: Duration::ZERO,
|
||||
compaction: Duration::ZERO,
|
||||
auto_review: Duration::ZERO,
|
||||
auto_review_overhead: Some(Duration::ZERO),
|
||||
user_wait: Duration::ZERO,
|
||||
tools: Duration::ZERO,
|
||||
overhead: Duration::ZERO,
|
||||
unknown: Duration::ZERO,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PathDurations {
|
||||
fn record(&mut self, kind: WorkKind, duration: Duration) {
|
||||
if matches!(kind, WorkKind::Unknown) {
|
||||
self.auto_review_overhead = None;
|
||||
}
|
||||
let total = match kind {
|
||||
WorkKind::Sampling => &mut self.sampling,
|
||||
WorkKind::Compaction => &mut self.compaction,
|
||||
WorkKind::AutoReview => &mut self.auto_review,
|
||||
WorkKind::UserWait => &mut self.user_wait,
|
||||
WorkKind::Tools => &mut self.tools,
|
||||
WorkKind::Overhead => &mut self.overhead,
|
||||
WorkKind::Unknown => &mut self.unknown,
|
||||
};
|
||||
*total = total.saturating_add(duration);
|
||||
}
|
||||
}
|
||||
|
||||
impl CriticalPath {
|
||||
/// End of the last recorded segment, or `None` for an empty path.
|
||||
pub fn end(&self) -> Option<Instant> {
|
||||
self.0.as_ref().map(|node| node.end)
|
||||
}
|
||||
|
||||
/// Retain the later-finishing path, choosing `self` on a tie.
|
||||
pub fn latest(self, other: Self) -> Self {
|
||||
if other.end() > self.end() {
|
||||
other
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Append work after the existing path ends, clipping overlap and ignoring empty segments.
|
||||
/// Exceeding the history limit collapses the retained interval into unknown work.
|
||||
pub fn work(self, start: Instant, end: Instant, kind: WorkKind) -> Self {
|
||||
self.append(start, end, kind, Vec::new())
|
||||
}
|
||||
|
||||
/// Adds review time with the exact reviews active during this segment. Their
|
||||
/// child execution union is clipped to the segment and requested window.
|
||||
pub fn auto_review(self, start: Instant, end: Instant, reviews: Vec<ReviewExecution>) -> Self {
|
||||
self.append(start, end, WorkKind::AutoReview, reviews)
|
||||
}
|
||||
|
||||
fn append(
|
||||
self,
|
||||
start: Instant,
|
||||
end: Instant,
|
||||
kind: WorkKind,
|
||||
reviews: Vec<ReviewExecution>,
|
||||
) -> Self {
|
||||
let start = self.end().map_or(start, |previous| previous.max(start));
|
||||
if start >= end {
|
||||
return self;
|
||||
}
|
||||
let origin = self.0.as_ref().map_or(start, |node| node.origin);
|
||||
let previous_depth = self.0.as_ref().map_or(0, |node| node.depth);
|
||||
let depth = previous_depth + 1;
|
||||
if depth > MAX_PATH_DEPTH {
|
||||
return Self::default().work(origin, end, WorkKind::Unknown);
|
||||
}
|
||||
Self(Some(Arc::new(Node {
|
||||
previous: self,
|
||||
kind,
|
||||
reviews,
|
||||
start,
|
||||
end,
|
||||
origin,
|
||||
depth,
|
||||
})))
|
||||
}
|
||||
|
||||
/// Select the full branch that released this join, not just its exposed
|
||||
/// waiting tail. Both branches carry their common causal prefix.
|
||||
pub fn join(self, start: Instant, end: Instant, dependency: Self) -> Self {
|
||||
let path = self.latest(dependency);
|
||||
let resumed_at = path.end().unwrap_or(start).max(start);
|
||||
path.work(resumed_at, end, WorkKind::Tools)
|
||||
}
|
||||
|
||||
/// Attribute the requested interval exclusively, counting unrecorded gaps as overhead.
|
||||
pub fn durations(&self, start: Instant, end: Instant) -> PathDurations {
|
||||
let mut totals = PathDurations::default();
|
||||
let mut path = self;
|
||||
let mut end = end;
|
||||
while let Some(node) = path.0.as_ref() {
|
||||
if end <= start {
|
||||
break;
|
||||
}
|
||||
let segment_end = end.min(node.end);
|
||||
let segment_start = start.max(node.start);
|
||||
if end > node.end {
|
||||
totals.record(WorkKind::Overhead, end.duration_since(start.max(node.end)));
|
||||
}
|
||||
if segment_start < segment_end {
|
||||
totals.record(node.kind, segment_end.duration_since(segment_start));
|
||||
if matches!(node.kind, WorkKind::AutoReview) {
|
||||
totals.auto_review_overhead = totals.auto_review_overhead.and_then(|total| {
|
||||
review_execution::overhead(&node.reviews, segment_start, segment_end)
|
||||
.map(|overhead| total.saturating_add(overhead))
|
||||
});
|
||||
}
|
||||
}
|
||||
end = end.min(node.start);
|
||||
path = &node.previous;
|
||||
}
|
||||
if start < end {
|
||||
totals.record(WorkKind::Overhead, end.duration_since(start));
|
||||
}
|
||||
totals
|
||||
}
|
||||
}
|
||||
|
||||
// Long sequential turns must not recursively destroy one Arc per operation.
|
||||
// into_inner consumes each reference atomically: concurrent releases cannot
|
||||
// leave an Err(Arc) whose subsequent drop recursively destroys the next node.
|
||||
impl Drop for Node {
|
||||
fn drop(&mut self) {
|
||||
let mut previous = self.previous.0.take();
|
||||
while let Some(node) = previous {
|
||||
let Some(mut node) = Arc::into_inner(node) else {
|
||||
break;
|
||||
};
|
||||
previous = node.previous.0.take();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "critical_path_tests.rs"]
|
||||
mod tests;
|
||||
168
akode-rs/utils/critical-path/src/review_execution.rs
Normal file
168
akode-rs/utils/critical-path/src/review_execution.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
//! Collects exact child execution intervals for one automatic review, then seals them.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Observes child turn execution for one review, including concurrent or retried turns.
|
||||
/// The owner must seal observations before publishing the completed dependency path.
|
||||
/// Equality compares review identity, not its collected intervals.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ReviewExecution(Arc<Mutex<State>>);
|
||||
|
||||
/// Resolves one submission exactly once, including cancellation before acknowledgement.
|
||||
#[must_use = "keep the attempt alive until submission completes"]
|
||||
pub struct ReviewExecutionAttempt {
|
||||
execution: ReviewExecution,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl ReviewExecutionAttempt {
|
||||
/// Records whether the submitted child's execution boundaries are known.
|
||||
pub fn finish(mut self, known: bool) {
|
||||
self.execution.attempt_finished(known);
|
||||
self.finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReviewExecutionAttempt {
|
||||
fn drop(&mut self) {
|
||||
if !self.finished {
|
||||
self.execution.attempt_finished(/*known*/ false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
observed: bool,
|
||||
sealed: bool,
|
||||
unknown: bool,
|
||||
pending: BTreeSet<Instant>,
|
||||
pending_attempts: usize,
|
||||
intervals: Vec<(Instant, Instant)>,
|
||||
}
|
||||
|
||||
impl ReviewExecution {
|
||||
/// Declares that this review's child executions are instrumented, even if none run.
|
||||
pub fn observe(&self) {
|
||||
let mut state = self.state();
|
||||
if !state.sealed {
|
||||
state.observed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers an unresolved submission before asynchronous work can be detached.
|
||||
pub fn start_attempt(&self) -> ReviewExecutionAttempt {
|
||||
let mut state = self.state();
|
||||
if !state.sealed {
|
||||
state.pending_attempts += 1;
|
||||
}
|
||||
ReviewExecutionAttempt {
|
||||
execution: self.clone(),
|
||||
finished: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves one submission. Unknown execution remains unknown after it finishes.
|
||||
fn attempt_finished(&self, known: bool) {
|
||||
let mut state = self.state();
|
||||
if state.sealed {
|
||||
return;
|
||||
}
|
||||
if let Some(pending) = state.pending_attempts.checked_sub(1) {
|
||||
state.pending_attempts = pending;
|
||||
} else {
|
||||
state.unknown = true;
|
||||
}
|
||||
state.unknown |= !known;
|
||||
}
|
||||
|
||||
/// Records the actual child turn start, before it can be canceled.
|
||||
pub fn started(&self, started_at: Instant) {
|
||||
let mut state = self.state();
|
||||
if !state.sealed && !state.pending.insert(started_at) {
|
||||
// Equal clock readings cannot distinguish two concurrent attempts.
|
||||
state.unknown = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Records exact turn bounds. Repeated completion notifications are harmless.
|
||||
pub fn completed(&self, started_at: Instant, completed_at: Instant) {
|
||||
let mut state = self.state();
|
||||
if state.sealed {
|
||||
return;
|
||||
}
|
||||
state.pending.remove(&started_at);
|
||||
if completed_at < started_at {
|
||||
state.unknown = true;
|
||||
} else {
|
||||
state.intervals.push((started_at, completed_at));
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks unavailable child attribution, rather than reporting it as review overhead.
|
||||
pub fn mark_unknown(&self) {
|
||||
let mut state = self.state();
|
||||
if !state.sealed {
|
||||
state.unknown = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Freezes this review's evidence. Later callbacks cannot change a completed path.
|
||||
pub fn seal(&self) {
|
||||
self.state().sealed = true;
|
||||
}
|
||||
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, State> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn overhead(
|
||||
reviews: &[ReviewExecution],
|
||||
start: Instant,
|
||||
end: Instant,
|
||||
) -> Option<Duration> {
|
||||
if reviews.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut intervals = Vec::new();
|
||||
for review in reviews {
|
||||
let state = review.state();
|
||||
if !state.observed
|
||||
|| state.unknown
|
||||
|| !state.pending.is_empty()
|
||||
|| state.pending_attempts > 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
intervals.extend(state.intervals.iter().filter_map(|&(left, right)| {
|
||||
let left = left.max(start);
|
||||
let right = right.min(end);
|
||||
(left < right).then_some((left, right))
|
||||
}));
|
||||
}
|
||||
intervals.sort_unstable();
|
||||
let mut execution = Duration::ZERO;
|
||||
let mut covered_until = start;
|
||||
for (left, right) in intervals {
|
||||
if right > covered_until {
|
||||
execution += right.duration_since(left.max(covered_until));
|
||||
covered_until = right;
|
||||
}
|
||||
}
|
||||
Some(end.duration_since(start).saturating_sub(execution))
|
||||
}
|
||||
|
||||
impl PartialEq for ReviewExecution {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.0, &other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ReviewExecution {}
|
||||
6
akode-rs/utils/elapsed/BUILD.bazel
Normal file
6
akode-rs/utils/elapsed/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "elapsed",
|
||||
crate_name = "akode_utils_elapsed",
|
||||
)
|
||||
11
akode-rs/utils/elapsed/Cargo.toml
Normal file
11
akode-rs/utils/elapsed/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "akode-utils-elapsed"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
71
akode-rs/utils/elapsed/src/lib.rs
Normal file
71
akode-rs/utils/elapsed/src/lib.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use std::time::Duration;
|
||||
|
||||
/// Convert a [`std::time::Duration`] into a human-readable, compact string.
|
||||
///
|
||||
/// Formatting rules:
|
||||
/// * < 1 s -> "{milli}ms"
|
||||
/// * < 60 s -> "{sec:.2}s" (two decimal places)
|
||||
/// * >= 60 s -> "{min}m {sec:02}s"
|
||||
pub fn format_duration(duration: Duration) -> String {
|
||||
let millis = duration.as_millis() as i64;
|
||||
format_elapsed_millis(millis)
|
||||
}
|
||||
|
||||
fn format_elapsed_millis(millis: i64) -> String {
|
||||
if millis < 1000 {
|
||||
format!("{millis}ms")
|
||||
} else if millis < 60_000 {
|
||||
format!("{:.2}s", millis as f64 / 1000.0)
|
||||
} else {
|
||||
let minutes = millis / 60_000;
|
||||
let seconds = (millis % 60_000) / 1000;
|
||||
format!("{minutes}m {seconds:02}s")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_format_duration_subsecond() {
|
||||
// Durations < 1s should be rendered in milliseconds with no decimals.
|
||||
let dur = Duration::from_millis(250);
|
||||
assert_eq!(format_duration(dur), "250ms");
|
||||
|
||||
// Exactly zero should still work.
|
||||
let dur_zero = Duration::from_millis(0);
|
||||
assert_eq!(format_duration(dur_zero), "0ms");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_duration_seconds() {
|
||||
// Durations between 1s (inclusive) and 60s (exclusive) should be
|
||||
// printed with 2-decimal-place seconds.
|
||||
let dur = Duration::from_millis(1_500); // 1.5s
|
||||
assert_eq!(format_duration(dur), "1.50s");
|
||||
|
||||
// 59.999s rounds to 60.00s
|
||||
let dur2 = Duration::from_millis(59_999);
|
||||
assert_eq!(format_duration(dur2), "60.00s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_duration_minutes() {
|
||||
// Durations ≥ 1 minute should be printed mmss.
|
||||
let dur = Duration::from_millis(75_000); // 1m15s
|
||||
assert_eq!(format_duration(dur), "1m 15s");
|
||||
|
||||
let dur_exact = Duration::from_millis(60_000); // 1m0s
|
||||
assert_eq!(format_duration(dur_exact), "1m 00s");
|
||||
|
||||
let dur_long = Duration::from_millis(3_601_000);
|
||||
assert_eq!(format_duration(dur_long), "60m 01s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_duration_one_hour_has_space() {
|
||||
let dur_hour = Duration::from_millis(3_600_000);
|
||||
assert_eq!(format_duration(dur_hour), "60m 00s");
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/fuzzy-match/BUILD.bazel
Normal file
6
akode-rs/utils/fuzzy-match/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "fuzzy-match",
|
||||
crate_name = "akode_utils_fuzzy_match",
|
||||
)
|
||||
11
akode-rs/utils/fuzzy-match/Cargo.toml
Normal file
11
akode-rs/utils/fuzzy-match/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "akode-utils-fuzzy-match"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
163
akode-rs/utils/fuzzy-match/src/lib.rs
Normal file
163
akode-rs/utils/fuzzy-match/src/lib.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
/// Simple case-insensitive subsequence matcher used for fuzzy filtering.
|
||||
///
|
||||
/// Returns the indices (character positions) of the matched characters in the
|
||||
/// ORIGINAL `haystack` string and a score where smaller is better.
|
||||
///
|
||||
/// Unicode correctness: we perform the match on a lowercased copy of the
|
||||
/// haystack and needle but maintain a mapping from each character in the
|
||||
/// lowercased haystack back to the original character index in `haystack`.
|
||||
/// This ensures the returned indices can be safely used with
|
||||
/// `str::chars().enumerate()` consumers for highlighting, even when
|
||||
/// lowercasing expands certain characters (e.g., İ → i̇).
|
||||
pub fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec<usize>, i32)> {
|
||||
if needle.is_empty() {
|
||||
return Some((Vec::new(), i32::MAX));
|
||||
}
|
||||
|
||||
let mut lowered_chars: Vec<char> = Vec::new();
|
||||
let mut lowered_to_orig_char_idx: Vec<usize> = Vec::new();
|
||||
for (orig_idx, ch) in haystack.chars().enumerate() {
|
||||
for lc in ch.to_lowercase() {
|
||||
lowered_chars.push(lc);
|
||||
lowered_to_orig_char_idx.push(orig_idx);
|
||||
}
|
||||
}
|
||||
|
||||
let lowered_needle: Vec<char> = needle.to_lowercase().chars().collect();
|
||||
|
||||
let mut result_orig_indices: Vec<usize> = Vec::with_capacity(lowered_needle.len());
|
||||
let mut first_lower_pos: Option<usize> = None;
|
||||
let mut last_lower_pos: Option<usize> = None;
|
||||
let mut cur = 0usize;
|
||||
for &nc in lowered_needle.iter() {
|
||||
let mut found_at: Option<usize> = None;
|
||||
while cur < lowered_chars.len() {
|
||||
if lowered_chars[cur] == nc {
|
||||
found_at = Some(cur);
|
||||
cur += 1;
|
||||
break;
|
||||
}
|
||||
cur += 1;
|
||||
}
|
||||
let pos = found_at?;
|
||||
result_orig_indices.push(lowered_to_orig_char_idx[pos]);
|
||||
first_lower_pos.get_or_insert(pos);
|
||||
last_lower_pos = Some(pos);
|
||||
}
|
||||
|
||||
// Score using the actual lowered positions, even within a character expansion.
|
||||
let first_lower_pos = first_lower_pos?;
|
||||
// last defaults to first for single-hit; score = extra span between first/last hit
|
||||
// minus needle len (≥0).
|
||||
// Strongly reward prefix matches by subtracting 100 when the first hit is at index 0.
|
||||
let last_lower_pos = last_lower_pos.unwrap_or(first_lower_pos);
|
||||
let window =
|
||||
(last_lower_pos as i32 - first_lower_pos as i32 + 1) - (lowered_needle.len() as i32);
|
||||
let mut score = window.max(0);
|
||||
if first_lower_pos == 0 {
|
||||
score -= 100;
|
||||
}
|
||||
|
||||
result_orig_indices.sort_unstable();
|
||||
result_orig_indices.dedup();
|
||||
Some((result_orig_indices, score))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ascii_basic_indices() {
|
||||
let (idx, score) = match fuzzy_match("hello", "hl") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
assert_eq!(idx, vec![0, 2]);
|
||||
// 'h' at 0, 'l' at 2 -> window 1; start-of-string bonus applies (-100)
|
||||
assert_eq!(score, -99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_dotted_i_istanbul_highlighting() {
|
||||
let (idx, score) = match fuzzy_match("İstanbul", "is") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
assert_eq!(idx, vec![0, 1]);
|
||||
// Matches at lowered positions 0 and 2 -> window 1; start-of-string bonus applies
|
||||
assert_eq!(score, -99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_german_sharp_s_casefold() {
|
||||
assert!(fuzzy_match("straße", "strasse").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefer_contiguous_match_over_spread() {
|
||||
let (_idx_a, score_a) = match fuzzy_match("abc", "abc") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
let (_idx_b, score_b) = match fuzzy_match("a-b-c", "abc") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
// Contiguous window -> 0; start-of-string bonus -> -100
|
||||
assert_eq!(score_a, -100);
|
||||
// Spread over 5 chars for 3-letter needle -> window 2; with bonus -> -98
|
||||
assert_eq!(score_b, -98);
|
||||
assert!(score_a < score_b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_of_string_bonus_applies() {
|
||||
let (_idx_a, score_a) = match fuzzy_match("file_name", "file") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
let (_idx_b, score_b) = match fuzzy_match("my_file_name", "file") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
// Start-of-string contiguous -> window 0; bonus -> -100
|
||||
assert_eq!(score_a, -100);
|
||||
// Non-prefix contiguous -> window 0; no bonus -> 0
|
||||
assert_eq!(score_b, 0);
|
||||
assert!(score_a < score_b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_needle_matches_with_max_score_and_no_indices() {
|
||||
let (idx, score) = match fuzzy_match("anything", "") {
|
||||
Some(v) => v,
|
||||
None => panic!("empty needle should match"),
|
||||
};
|
||||
assert!(idx.is_empty());
|
||||
assert_eq!(score, i32::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_insensitive_matching_basic() {
|
||||
let (idx, score) = match fuzzy_match("FooBar", "foO") {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
assert_eq!(idx, vec![0, 1, 2]);
|
||||
// Contiguous prefix match (case-insensitive) -> window 0 with bonus
|
||||
assert_eq!(score, -100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indices_are_deduped_for_multichar_lowercase_expansion() {
|
||||
let needle = "\u{0069}\u{0307}"; // "i" + combining dot above
|
||||
let (idx, score) = match fuzzy_match("İ", needle) {
|
||||
Some(v) => v,
|
||||
None => panic!("expected a match"),
|
||||
};
|
||||
assert_eq!(idx, vec![0]);
|
||||
// Lowercasing 'İ' expands to two chars; contiguous prefix -> window 0 with bonus
|
||||
assert_eq!(score, -100);
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/git-discovery/BUILD.bazel
Normal file
6
akode-rs/utils/git-discovery/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "git-discovery",
|
||||
crate_name = "akode_utils_git_discovery",
|
||||
)
|
||||
24
akode-rs/utils/git-discovery/Cargo.toml
Normal file
24
akode-rs/utils/git-discovery/Cargo.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "akode-utils-git-discovery"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-git-utils = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
futures = { workspace = true, features = ["std"] }
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
futures = { workspace = true, features = ["async-await"] }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread", "time"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
185
akode-rs/utils/git-discovery/src/git_root_discovery_tests.rs
Normal file
185
akode-rs/utils/git-discovery/src/git_root_discovery_tests.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
//! Verifies shared probe results, capacity retention after cancellation, and
|
||||
//! fresh discovery after repository changes. Blocked probes must not delay runtime shutdown.
|
||||
|
||||
use super::GitRootDiscovery;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Simulates a filesystem call that stays blocked until the test releases it.
|
||||
fn blocked_root_discovery(
|
||||
capacity: usize,
|
||||
) -> (Arc<GitRootDiscovery>, mpsc::Receiver<()>, mpsc::Sender<()>) {
|
||||
let (entered_tx, entered_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
let release_rx = Mutex::new(release_rx);
|
||||
let discovery = Arc::new(GitRootDiscovery {
|
||||
capacity,
|
||||
find_root: Arc::new(move |cwd| {
|
||||
entered_tx.send(()).expect("signal probe entry");
|
||||
let _ = release_rx
|
||||
.lock()
|
||||
.expect("release receiver")
|
||||
.recv_timeout(PROBE_TIMEOUT);
|
||||
Some(cwd.to_path_buf())
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
(discovery, entered_rx, release_tx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_discovery_shares_probes_across_callers_and_cancellation() {
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
let workspace = tempfile::tempdir().expect("workspace");
|
||||
let first_cwd = AbsolutePathBuf::from_absolute_path(workspace.path().join("first"))
|
||||
.expect("absolute first cwd");
|
||||
let second_cwd = AbsolutePathBuf::from_absolute_path(workspace.path().join("second"))
|
||||
.expect("absolute second cwd");
|
||||
let third_cwd = AbsolutePathBuf::from_absolute_path(workspace.path().join("third"))
|
||||
.expect("absolute third cwd");
|
||||
let (discovery, entered_rx, release_tx) = blocked_root_discovery(/*capacity*/ 2);
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("runtime");
|
||||
|
||||
runtime.block_on(async {
|
||||
let mut first = Box::pin(discovery.discover(first_cwd.clone()));
|
||||
let mut duplicate = Box::pin(discovery.discover(first_cwd.clone()));
|
||||
let mut second = Box::pin(discovery.discover(second_cwd.clone()));
|
||||
assert!(futures::poll!(first.as_mut()).is_pending());
|
||||
assert!(futures::poll!(duplicate.as_mut()).is_pending());
|
||||
// Sharing the first cwd leaves room for a different directory.
|
||||
assert!(futures::poll!(second.as_mut()).is_pending());
|
||||
entered_rx
|
||||
.recv_timeout(TIMEOUT)
|
||||
.expect("first probe started");
|
||||
entered_rx
|
||||
.recv_timeout(TIMEOUT)
|
||||
.expect("second probe started");
|
||||
drop(first);
|
||||
drop(duplicate);
|
||||
// Cancelling every waiter does not free capacity while its worker is blocked.
|
||||
let mut third = Box::pin(discovery.discover(third_cwd.clone()));
|
||||
assert!(futures::poll!(third.as_mut()).is_pending());
|
||||
let mut cancelled = Box::pin(discovery.discover(first_cwd.join("cancelled")));
|
||||
assert!(futures::poll!(cancelled.as_mut()).is_pending());
|
||||
drop(cancelled);
|
||||
assert!(entered_rx.try_recv().is_err());
|
||||
let mut retry = Box::pin(discovery.discover(first_cwd.clone()));
|
||||
// The same directory can still join its probe when capacity is full.
|
||||
assert!(futures::poll!(retry.as_mut()).is_pending());
|
||||
let mut follower = Box::pin(discovery.discover(first_cwd.clone()));
|
||||
assert!(futures::poll!(follower.as_mut()).is_pending());
|
||||
|
||||
release_tx.send(()).expect("release first probe");
|
||||
release_tx.send(()).expect("release second probe");
|
||||
release_tx.send(()).expect("release queued probe");
|
||||
let roots = timeout(TIMEOUT, async {
|
||||
(retry.await, follower.await, second.await, third.await)
|
||||
})
|
||||
.await
|
||||
.expect("running and queued root probes finished");
|
||||
assert_eq!(
|
||||
roots,
|
||||
(
|
||||
Some(first_cwd.to_path_buf()),
|
||||
Some(first_cwd.to_path_buf()),
|
||||
Some(second_cwd.to_path_buf()),
|
||||
Some(third_cwd.to_path_buf()),
|
||||
)
|
||||
);
|
||||
entered_rx.try_recv().expect("queued probe started");
|
||||
assert!(entered_rx.try_recv().is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_root_discoveries_are_not_cached() {
|
||||
let workspace = tempfile::tempdir().expect("workspace");
|
||||
let cwd = AbsolutePathBuf::from_absolute_path(workspace.path()).expect("absolute cwd");
|
||||
let discovery = Arc::new(GitRootDiscovery {
|
||||
capacity: 1,
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(discovery.discover(cwd.clone()).await, None);
|
||||
|
||||
std::fs::create_dir(cwd.join(".git")).expect("git directory");
|
||||
std::fs::write(cwd.join(".git/HEAD"), "ref: refs/heads/main\n").expect("git HEAD");
|
||||
assert_eq!(
|
||||
discovery.discover(cwd.clone()).await,
|
||||
Some(cwd.to_path_buf())
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(cwd.join(".git")).expect("remove Git metadata");
|
||||
assert_eq!(discovery.discover(cwd).await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saturated_discovery_does_not_block_other_instances() {
|
||||
let workspace = tempfile::tempdir().expect("workspace");
|
||||
let cwd = AbsolutePathBuf::from_absolute_path(workspace.path()).expect("absolute cwd");
|
||||
let (saturated, entered_rx, release_tx) = blocked_root_discovery(/*capacity*/ 1);
|
||||
let mut blocked = Box::pin(saturated.discover(cwd.clone()));
|
||||
assert!(futures::poll!(blocked.as_mut()).is_pending());
|
||||
entered_rx
|
||||
.recv_timeout(PROBE_TIMEOUT)
|
||||
.expect("probe started");
|
||||
|
||||
let available = Arc::new(GitRootDiscovery::default());
|
||||
let root = timeout(Duration::from_secs(5), available.discover(cwd.clone())).await;
|
||||
release_tx.send(()).expect("release probe");
|
||||
assert_eq!(root.expect("independent discovery finishes"), None);
|
||||
assert_eq!(blocked.await, Some(cwd.to_path_buf()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_root_discovery_does_not_delay_runtime_shutdown() {
|
||||
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const WORKER_THREADS: usize = 1;
|
||||
let workspace = tempfile::tempdir().expect("workspace");
|
||||
let cwd = AbsolutePathBuf::from_absolute_path(workspace.path()).expect("absolute cwd");
|
||||
let (discovery, entered_rx, release_tx) = blocked_root_discovery(/*capacity*/ 1);
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(WORKER_THREADS)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("runtime");
|
||||
let lookup = runtime.spawn({
|
||||
let discovery = Arc::clone(&discovery);
|
||||
async move { discovery.discover(cwd).await }
|
||||
});
|
||||
entered_rx
|
||||
.recv_timeout(PROBE_TIMEOUT)
|
||||
.expect("probe started");
|
||||
lookup.abort();
|
||||
assert!(
|
||||
runtime
|
||||
.block_on(lookup)
|
||||
.expect_err("cancelled lookup")
|
||||
.is_cancelled()
|
||||
);
|
||||
|
||||
let (shutdown_tx, shutdown_rx) = mpsc::channel();
|
||||
let shutdown = std::thread::spawn(move || {
|
||||
drop(runtime);
|
||||
let _ = shutdown_tx.send(());
|
||||
});
|
||||
let shutdown_result = shutdown_rx.recv_timeout(SHUTDOWN_TIMEOUT);
|
||||
let outstanding = discovery
|
||||
.in_flight
|
||||
.lock()
|
||||
.expect("outstanding probes")
|
||||
.len();
|
||||
// Release the probe even if shutdown timed out so a regression cannot hang the test.
|
||||
release_tx.send(()).expect("release probe");
|
||||
shutdown.join().expect("shutdown thread");
|
||||
assert_eq!((shutdown_result, outstanding), (Ok(()), 1));
|
||||
}
|
||||
120
akode-rs/utils/git-discovery/src/lib.rs
Normal file
120
akode-rs/utils/git-discovery/src/lib.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
//! Bounded, shared Git-root discovery for optional metadata.
|
||||
//!
|
||||
//! Each instance bounds detached probes and shares one outstanding probe per
|
||||
//! supplied cwd. Workers retain their entries through caller cancellation and remove
|
||||
//! them when filesystem work ends; completed results are not cached. Capacity waits
|
||||
//! are cancellable; keys are compared without filesystem canonicalization.
|
||||
//! Probes never enter Tokio's blocking pool, so a stuck filesystem cannot keep its
|
||||
//! runtime shutdown waiting for optional metadata work.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use akode_git_utils::get_git_repo_root;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::Shared;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const MAX_CONCURRENT_ROOT_PROBES: usize = 8;
|
||||
|
||||
type SharedRootProbe = Shared<BoxFuture<'static, Option<PathBuf>>>;
|
||||
type RootFinder = dyn Fn(&Path) -> Option<PathBuf> + Send + Sync;
|
||||
|
||||
/// Shares outstanding metadata probes by cwd and bounds probes across directories.
|
||||
/// Entries survive caller cancellation but are not cached after filesystem work ends.
|
||||
pub struct GitRootDiscovery {
|
||||
capacity: usize,
|
||||
in_flight: Mutex<HashMap<AbsolutePathBuf, SharedRootProbe>>,
|
||||
find_root: Arc<RootFinder>,
|
||||
capacity_changed: Notify,
|
||||
}
|
||||
|
||||
impl Default for GitRootDiscovery {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
capacity: MAX_CONCURRENT_ROOT_PROBES,
|
||||
in_flight: Mutex::new(HashMap::new()),
|
||||
find_root: Arc::new(get_git_repo_root),
|
||||
capacity_changed: Notify::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GitRootDiscovery {
|
||||
/// Joins the cwd's existing probe, waiting for capacity to start a detached
|
||||
/// worker when necessary. Dropping the future cancels only the wait.
|
||||
pub async fn discover(self: &Arc<Self>, cwd: AbsolutePathBuf) -> Option<PathBuf> {
|
||||
let (result, new_probe) = loop {
|
||||
// notify_waiters reaches futures created before the capacity check,
|
||||
// even if they have not been polled yet.
|
||||
let capacity_changed = self.capacity_changed.notified();
|
||||
{
|
||||
let mut in_flight = self
|
||||
.in_flight
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(result) = in_flight.get(&cwd) {
|
||||
break (result.clone(), None);
|
||||
}
|
||||
if in_flight.len() < self.capacity {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
let result = async move { result_rx.await.unwrap_or_default() }
|
||||
.boxed()
|
||||
.shared();
|
||||
in_flight.insert(cwd.clone(), result.clone());
|
||||
let probe = ProbeGuard {
|
||||
cwd,
|
||||
discovery: Arc::clone(self),
|
||||
};
|
||||
break (result, Some((probe, result_tx)));
|
||||
}
|
||||
}
|
||||
capacity_changed.await;
|
||||
};
|
||||
if let Some((probe, result_tx)) = new_probe {
|
||||
// Other waiters for this cwd can now join the new probe.
|
||||
self.capacity_changed.notify_waiters();
|
||||
// A failed spawn drops the closure and its guard, so do not hold the map lock.
|
||||
// Dropping the handle detaches the thread; Tokio never owns or joins it.
|
||||
let worker = std::thread::Builder::new()
|
||||
.name("codex-git-root".to_string())
|
||||
.spawn(move || {
|
||||
let root = (probe.discovery.find_root)(probe.cwd.as_path());
|
||||
drop(probe);
|
||||
let _ = result_tx.send(root);
|
||||
});
|
||||
if let Err(error) = worker {
|
||||
tracing::warn!(%error, "failed to start optional Git root probe");
|
||||
}
|
||||
}
|
||||
result.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps an outstanding entry owned by its blocking worker, including during
|
||||
/// cancellation or unwinding, rather than by any caller waiting for the result.
|
||||
struct ProbeGuard {
|
||||
cwd: AbsolutePathBuf,
|
||||
discovery: Arc<GitRootDiscovery>,
|
||||
}
|
||||
|
||||
impl Drop for ProbeGuard {
|
||||
fn drop(&mut self) {
|
||||
self.discovery
|
||||
.in_flight
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.remove(&self.cwd);
|
||||
self.discovery.capacity_changed.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "git_root_discovery_tests.rs"]
|
||||
mod tests;
|
||||
6
akode-rs/utils/head-tail-buffer/BUILD.bazel
Normal file
6
akode-rs/utils/head-tail-buffer/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "head-tail-buffer",
|
||||
crate_name = "akode_utils_head_tail_buffer",
|
||||
)
|
||||
14
akode-rs/utils/head-tail-buffer/Cargo.toml
Normal file
14
akode-rs/utils/head-tail-buffer/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "akode-utils-head-tail-buffer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
@@ -0,0 +1,91 @@
|
||||
use super::HeadTailBuffer;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn keeps_prefix_and_suffix_when_over_budget() {
|
||||
let mut buf = HeadTailBuffer::<10>::default();
|
||||
|
||||
buf.push_chunk(b"0123456789");
|
||||
assert_eq!(buf.omitted_bytes(), 0);
|
||||
|
||||
// Exceeds max by 2; we should keep head+tail and omit the middle.
|
||||
buf.push_chunk(b"ab");
|
||||
assert!(buf.omitted_bytes() > 0);
|
||||
|
||||
let rendered = String::from_utf8_lossy(&buf.to_bytes()).to_string();
|
||||
assert!(rendered.starts_with("01234"));
|
||||
assert!(rendered.ends_with("89ab"));
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&buf.to_bytes_with_omission_marker()),
|
||||
"01234\n... 2 bytes omitted ...\n789ab"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_bytes_zero_drops_everything() {
|
||||
let mut buf = HeadTailBuffer::<0>::default();
|
||||
buf.push_chunk(b"abc");
|
||||
|
||||
assert_eq!(buf.retained_bytes(), 0);
|
||||
assert_eq!(buf.omitted_bytes(), 3);
|
||||
assert_eq!(buf.to_bytes(), b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_budget_zero_keeps_only_last_byte_in_tail() {
|
||||
let mut buf = HeadTailBuffer::<1>::default();
|
||||
buf.push_chunk(b"abc");
|
||||
|
||||
assert_eq!(buf.retained_bytes(), 1);
|
||||
assert_eq!(buf.omitted_bytes(), 2);
|
||||
assert_eq!(buf.to_bytes(), b"c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_larger_than_tail_budget_keeps_only_tail_end() {
|
||||
let mut buf = HeadTailBuffer::<10>::default();
|
||||
buf.push_chunk(b"0123456789");
|
||||
|
||||
// Tail budget is 5 bytes. This chunk should replace the tail and keep only its last 5 bytes.
|
||||
buf.push_chunk(b"ABCDEFGHIJK");
|
||||
|
||||
let out = String::from_utf8_lossy(&buf.to_bytes()).to_string();
|
||||
assert!(out.starts_with("01234"));
|
||||
assert!(out.ends_with("GHIJK"));
|
||||
assert!(buf.omitted_bytes() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_head_then_tail_across_multiple_chunks() {
|
||||
let mut buf = HeadTailBuffer::<10>::default();
|
||||
|
||||
// Fill the 5-byte head budget across multiple chunks.
|
||||
buf.push_chunk(b"01");
|
||||
buf.push_chunk(b"234");
|
||||
assert_eq!(buf.to_bytes(), b"01234");
|
||||
|
||||
// Then fill the 5-byte tail budget.
|
||||
buf.push_chunk(b"567");
|
||||
buf.push_chunk(b"89");
|
||||
assert_eq!(buf.to_bytes(), b"0123456789");
|
||||
assert_eq!(buf.omitted_bytes(), 0);
|
||||
|
||||
// One more byte causes the tail to drop its oldest byte.
|
||||
buf.push_chunk(b"a");
|
||||
assert_eq!(buf.to_bytes(), b"012346789a");
|
||||
assert_eq!(buf.omitted_bytes(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_tiny_chunks_have_bounded_metadata() {
|
||||
let mut buf = HeadTailBuffer::<10>::default();
|
||||
|
||||
for byte in b"0123456789ab" {
|
||||
buf.push_chunk(&[]);
|
||||
buf.push_chunk(&[*byte]);
|
||||
}
|
||||
|
||||
assert_eq!(buf.retained_bytes(), 10);
|
||||
assert_eq!(buf.omitted_bytes(), 2);
|
||||
}
|
||||
170
akode-rs/utils/head-tail-buffer/src/lib.rs
Normal file
170
akode-rs/utils/head-tail-buffer/src/lib.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
//! A capped byte buffer that preserves a stable prefix and the most recent suffix.
|
||||
//! Retained bytes never exceed the caller's const-generic budget.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// A capped buffer that preserves a stable prefix ("head") and suffix ("tail"),
|
||||
/// dropping the middle once it exceeds the configured maximum. The buffer is
|
||||
/// symmetric meaning 50% of the capacity is allocated to the head and 50% is
|
||||
/// allocated to the tail.
|
||||
#[derive(Debug, Default, Eq, PartialEq)]
|
||||
pub struct HeadTailBuffer<const MAX_BYTES: usize> {
|
||||
head: Vec<u8>,
|
||||
tail: VecDeque<u8>,
|
||||
omitted_bytes: usize,
|
||||
}
|
||||
|
||||
impl<const MAX_BYTES: usize> HeadTailBuffer<MAX_BYTES> {
|
||||
const HEAD_BUDGET: usize = MAX_BYTES / 2;
|
||||
const TAIL_BUDGET: usize = MAX_BYTES.saturating_sub(Self::HEAD_BUDGET);
|
||||
|
||||
/// Total bytes currently retained by the buffer (head + tail).
|
||||
pub fn retained_bytes(&self) -> usize {
|
||||
self.head.len().saturating_add(self.tail.len())
|
||||
}
|
||||
|
||||
/// Total bytes that were dropped from the middle due to the size cap.
|
||||
pub fn omitted_bytes(&self) -> usize {
|
||||
self.omitted_bytes
|
||||
}
|
||||
|
||||
/// Total bytes observed by the buffer, including bytes omitted by the cap.
|
||||
pub fn total_bytes(&self) -> usize {
|
||||
self.retained_bytes().saturating_add(self.omitted_bytes)
|
||||
}
|
||||
|
||||
/// Append a chunk of bytes to the buffer.
|
||||
///
|
||||
/// Bytes are first added to the head until the head budget is full; any
|
||||
/// remaining bytes are added to the tail, with older tail bytes being
|
||||
/// dropped to preserve the tail budget.
|
||||
pub fn push_chunk(&mut self, chunk: &[u8]) {
|
||||
let chunk = self.fill_head(chunk);
|
||||
self.push_tail(chunk);
|
||||
}
|
||||
|
||||
/// Fill the stable prefix and return the bytes that did not fit.
|
||||
fn fill_head<'a>(&mut self, chunk: &'a [u8]) -> &'a [u8] {
|
||||
let Self {
|
||||
head,
|
||||
tail: _,
|
||||
omitted_bytes: _,
|
||||
} = self;
|
||||
|
||||
let remaining_head = Self::HEAD_BUDGET.saturating_sub(head.len());
|
||||
// A shorter chunk fits entirely in the head.
|
||||
let (chunk_head, chunk_tail) = chunk
|
||||
.split_at_checked(remaining_head)
|
||||
.unwrap_or((chunk, &[]));
|
||||
head.extend_from_slice(chunk_head);
|
||||
chunk_tail
|
||||
}
|
||||
|
||||
/// Append bytes known not to belong in the head, keeping the newest tail bytes.
|
||||
fn push_tail(&mut self, chunk: &[u8]) {
|
||||
let Self {
|
||||
head: _,
|
||||
tail,
|
||||
omitted_bytes,
|
||||
} = self;
|
||||
|
||||
let remaining_tail = Self::TAIL_BUDGET.saturating_sub(tail.len());
|
||||
let excess_tail = chunk.len().saturating_sub(remaining_tail);
|
||||
*omitted_bytes = omitted_bytes.saturating_add(excess_tail);
|
||||
|
||||
// Discard old tail bytes first, then skip any excess incoming bytes.
|
||||
let chunk = match excess_tail.checked_sub(tail.len()) {
|
||||
None => {
|
||||
tail.drain(..excess_tail);
|
||||
chunk
|
||||
}
|
||||
Some(skip) => {
|
||||
tail.clear();
|
||||
&chunk[skip..]
|
||||
}
|
||||
};
|
||||
tail.extend(chunk);
|
||||
}
|
||||
|
||||
/// Return the retained output as a single byte vector.
|
||||
///
|
||||
/// The output is formed by concatenating head chunks, then tail chunks.
|
||||
/// Omitted bytes are not represented in the returned value.
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(self.retained_bytes());
|
||||
out.extend_from_slice(&self.head);
|
||||
out.extend(self.tail.iter().copied());
|
||||
out
|
||||
}
|
||||
|
||||
/// Return the retained output with an explicit marker between the head and
|
||||
/// tail when bytes were omitted.
|
||||
pub fn to_bytes_with_omission_marker(&self) -> Vec<u8> {
|
||||
if self.omitted_bytes == 0 {
|
||||
return self.to_bytes();
|
||||
}
|
||||
|
||||
let marker = format_output_omission_marker(self.omitted_bytes);
|
||||
let marker_delimiter_bytes = 2;
|
||||
let mut out = Vec::with_capacity(
|
||||
self.retained_bytes()
|
||||
.saturating_add(marker.len())
|
||||
.saturating_add(marker_delimiter_bytes),
|
||||
);
|
||||
out.extend_from_slice(&self.head);
|
||||
out.push(b'\n');
|
||||
out.extend_from_slice(marker.as_bytes());
|
||||
out.push(b'\n');
|
||||
out.extend(self.tail.iter().copied());
|
||||
out
|
||||
}
|
||||
|
||||
/// Append a later buffer with the same budget. This preserves the summary
|
||||
/// of the original concatenated output, including its omission count.
|
||||
pub fn push_buffer(&mut self, buffer: Self) {
|
||||
let Self {
|
||||
head,
|
||||
tail,
|
||||
omitted_bytes,
|
||||
} = buffer;
|
||||
|
||||
self.omitted_bytes = self.omitted_bytes.saturating_add(omitted_bytes);
|
||||
|
||||
// Preserve an existing prefix; otherwise reuse the source head.
|
||||
let overflow = if self.head.is_empty() {
|
||||
self.head = head;
|
||||
&[]
|
||||
} else {
|
||||
self.fill_head(&head)
|
||||
};
|
||||
|
||||
// A full source tail displaces both the old tail and the unused source head.
|
||||
if tail.len() == Self::TAIL_BUDGET {
|
||||
self.omitted_bytes = self
|
||||
.omitted_bytes
|
||||
.saturating_add(self.tail.len())
|
||||
.saturating_add(overflow.len());
|
||||
self.tail = tail;
|
||||
} else {
|
||||
self.push_tail(overflow);
|
||||
// An empty destination can take a partial source tail without copying it.
|
||||
if self.tail.is_empty() {
|
||||
self.tail = tail;
|
||||
} else {
|
||||
// A nonempty source tail means its head, and now ours, is full.
|
||||
let (first, second) = tail.as_slices();
|
||||
self.push_tail(first);
|
||||
self.push_tail(second);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the byte omission notice used by callers of the buffer.
|
||||
pub fn format_output_omission_marker(omitted_bytes: usize) -> String {
|
||||
format!("... {omitted_bytes} bytes omitted ...")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "head_tail_buffer_tests.rs"]
|
||||
mod tests;
|
||||
6
akode-rs/utils/home-dir/BUILD.bazel
Normal file
6
akode-rs/utils/home-dir/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "home-dir",
|
||||
crate_name = "akode_utils_home_dir",
|
||||
)
|
||||
19
akode-rs/utils/home-dir/Cargo.toml
Normal file
19
akode-rs/utils/home-dir/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "akode-utils-home-dir"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
134
akode-rs/utils/home-dir/src/lib.rs
Normal file
134
akode-rs/utils/home-dir/src/lib.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use dirs::home_dir;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Returns the path to the Codex configuration directory, which can be
|
||||
/// specified by the `AKODE_HOME` environment variable. If not set, defaults to
|
||||
/// `~/.akode`.
|
||||
///
|
||||
/// - If `AKODE_HOME` is set, the value must exist and be a directory. The
|
||||
/// value will be canonicalized and this function will Err otherwise.
|
||||
/// - If `AKODE_HOME` is not set, this function does not verify that the
|
||||
/// directory exists.
|
||||
pub fn find_codex_home() -> std::io::Result<AbsolutePathBuf> {
|
||||
let codex_home_env = std::env::var("AKODE_HOME")
|
||||
.ok()
|
||||
.filter(|val| !val.is_empty());
|
||||
find_codex_home_from_env(codex_home_env.as_deref())
|
||||
}
|
||||
|
||||
fn find_codex_home_from_env(codex_home_env: Option<&str>) -> std::io::Result<AbsolutePathBuf> {
|
||||
// Honor the `AKODE_HOME` environment variable when it is set to allow users
|
||||
// (and tests) to override the default location.
|
||||
match codex_home_env {
|
||||
Some(val) => {
|
||||
let path = PathBuf::from(val);
|
||||
let metadata = std::fs::metadata(&path).map_err(|err| match err.kind() {
|
||||
std::io::ErrorKind::NotFound => std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
format!("AKODE_HOME points to {val:?}, but that path does not exist"),
|
||||
),
|
||||
_ => std::io::Error::new(
|
||||
err.kind(),
|
||||
format!("failed to read AKODE_HOME {val:?}: {err}"),
|
||||
),
|
||||
})?;
|
||||
|
||||
if !metadata.is_dir() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!("AKODE_HOME points to {val:?}, but that path is not a directory"),
|
||||
))
|
||||
} else {
|
||||
let canonical = path.canonicalize().map_err(|err| {
|
||||
std::io::Error::new(
|
||||
err.kind(),
|
||||
format!("failed to canonicalize AKODE_HOME {val:?}: {err}"),
|
||||
)
|
||||
})?;
|
||||
AbsolutePathBuf::from_absolute_path(canonical)
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut p = home_dir().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"Could not find home directory",
|
||||
)
|
||||
})?;
|
||||
p.push(".akode");
|
||||
AbsolutePathBuf::from_absolute_path(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::find_codex_home_from_env;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use dirs::home_dir;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn find_codex_home_env_missing_path_is_fatal() {
|
||||
let temp_home = TempDir::new().expect("temp home");
|
||||
let missing = temp_home.path().join("missing-codex-home");
|
||||
let missing_str = missing
|
||||
.to_str()
|
||||
.expect("missing codex home path should be valid utf-8");
|
||||
|
||||
let err = find_codex_home_from_env(Some(missing_str)).expect_err("missing AKODE_HOME");
|
||||
assert_eq!(err.kind(), ErrorKind::NotFound);
|
||||
assert!(
|
||||
err.to_string().contains("AKODE_HOME"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_codex_home_env_file_path_is_fatal() {
|
||||
let temp_home = TempDir::new().expect("temp home");
|
||||
let file_path = temp_home.path().join("akode-home.txt");
|
||||
fs::write(&file_path, "not a directory").expect("write temp file");
|
||||
let file_str = file_path
|
||||
.to_str()
|
||||
.expect("file codex home path should be valid utf-8");
|
||||
|
||||
let err = find_codex_home_from_env(Some(file_str)).expect_err("file AKODE_HOME");
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
assert!(
|
||||
err.to_string().contains("not a directory"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_codex_home_env_valid_directory_canonicalizes() {
|
||||
let temp_home = TempDir::new().expect("temp home");
|
||||
let temp_str = temp_home
|
||||
.path()
|
||||
.to_str()
|
||||
.expect("temp codex home path should be valid utf-8");
|
||||
|
||||
let resolved = find_codex_home_from_env(Some(temp_str)).expect("valid AKODE_HOME");
|
||||
let expected = temp_home
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonicalize temp home");
|
||||
let expected = AbsolutePathBuf::from_absolute_path(expected).expect("absolute home");
|
||||
assert_eq!(resolved, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_codex_home_without_env_uses_default_home_dir() {
|
||||
let resolved =
|
||||
find_codex_home_from_env(/*codex_home_env*/ None).expect("default AKODE_HOME");
|
||||
let mut expected = home_dir().expect("home dir");
|
||||
expected.push(".akode");
|
||||
let expected = AbsolutePathBuf::from_absolute_path(expected).expect("absolute home");
|
||||
assert_eq!(resolved, expected);
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/image/BUILD.bazel
Normal file
6
akode-rs/utils/image/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "image",
|
||||
crate_name = "akode_utils_image",
|
||||
)
|
||||
33
akode-rs/utils/image/Cargo.toml
Normal file
33
akode-rs/utils/image/Cargo.toml
Normal file
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "akode-utils-image"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
# "image" does not forward png's zlib-rs feature. This direct dependency keeps
|
||||
# encoded PNG bytes stable when WebSocket dependencies are absent from a build.
|
||||
ignored = ["png"]
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }
|
||||
png = { version = "0.18.0", features = ["zlib-rs"] }
|
||||
akode-utils-cache = { workspace = true }
|
||||
mime_guess = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs", "rt", "rt-multi-thread", "macros"] }
|
||||
|
||||
[dev-dependencies]
|
||||
divan = { workspace = true }
|
||||
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[[bench]]
|
||||
name = "prompt_images"
|
||||
harness = false
|
||||
178
akode-rs/utils/image/benches/prompt_images.rs
Normal file
178
akode-rs/utils/image/benches/prompt_images.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
use std::io::Cursor;
|
||||
use std::path::Path;
|
||||
|
||||
use akode_utils_image::PromptImageMode;
|
||||
use akode_utils_image::load_for_prompt_bytes;
|
||||
use divan::Bencher;
|
||||
use image::DynamicImage;
|
||||
use image::ImageFormat;
|
||||
use image::Rgb;
|
||||
use image::RgbImage;
|
||||
use image::Rgba;
|
||||
use image::RgbaImage;
|
||||
|
||||
const CACHE_MISS_VARIANT_COUNT: usize = 48;
|
||||
|
||||
const SMALL_SCREENSHOT: ImageSize = ImageSize {
|
||||
width: 1_536,
|
||||
height: 864,
|
||||
};
|
||||
const LARGE_SCREENSHOT: ImageSize = ImageSize {
|
||||
width: 2_560,
|
||||
height: 1_440,
|
||||
};
|
||||
const LARGE_PHOTO: ImageSize = ImageSize {
|
||||
width: 3_264,
|
||||
height: 2_448,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ImageSize {
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
divan::main();
|
||||
}
|
||||
|
||||
#[divan::bench]
|
||||
fn small_png_screenshot_fresh_attachment(bencher: Bencher) {
|
||||
bench_fresh_attachment(
|
||||
bencher,
|
||||
"small-screenshot.png",
|
||||
cache_miss_variants(screenshot_png(SMALL_SCREENSHOT)),
|
||||
);
|
||||
}
|
||||
|
||||
#[divan::bench]
|
||||
fn large_png_screenshot_fresh_attachment(bencher: Bencher) {
|
||||
bench_fresh_attachment(
|
||||
bencher,
|
||||
"large-screenshot.png",
|
||||
cache_miss_variants(screenshot_png(LARGE_SCREENSHOT)),
|
||||
);
|
||||
}
|
||||
|
||||
#[divan::bench]
|
||||
fn large_jpeg_photo_fresh_attachment(bencher: Bencher) {
|
||||
bench_fresh_attachment(
|
||||
bencher,
|
||||
"large-photo.jpg",
|
||||
cache_miss_variants(photo_jpeg(LARGE_PHOTO)),
|
||||
);
|
||||
}
|
||||
|
||||
#[divan::bench]
|
||||
fn small_png_screenshot_repeated_attachment(bencher: Bencher) {
|
||||
bench_repeated_attachment(
|
||||
bencher,
|
||||
"small-screenshot.png",
|
||||
screenshot_png(SMALL_SCREENSHOT),
|
||||
);
|
||||
}
|
||||
|
||||
fn bench_fresh_attachment(bencher: Bencher, path: &'static str, images: Vec<Vec<u8>>) {
|
||||
let mut image_index = 0;
|
||||
|
||||
bencher
|
||||
// Divan excludes `with_inputs` from the measured benchmark timing.
|
||||
.with_inputs(move || {
|
||||
let image = images[image_index].clone();
|
||||
image_index = (image_index + 1) % images.len();
|
||||
image
|
||||
})
|
||||
.bench_local_values(move |image| prepare_prompt_data_url(path, image));
|
||||
}
|
||||
|
||||
fn bench_repeated_attachment(bencher: Bencher, path: &'static str, image: Vec<u8>) {
|
||||
let _ = prepare_prompt_data_url(path, image.clone());
|
||||
|
||||
bencher
|
||||
// Divan excludes the per-iteration input clone from measured timing.
|
||||
.with_inputs(move || image.clone())
|
||||
.bench_local_values(move |image| prepare_prompt_data_url(path, image));
|
||||
}
|
||||
|
||||
fn prepare_prompt_data_url(path: &str, image: Vec<u8>) -> String {
|
||||
#[allow(clippy::expect_used)]
|
||||
load_for_prompt_bytes(Path::new(path), image, PromptImageMode::ResizeToFit)
|
||||
.expect("benchmark fixture should load")
|
||||
.into_data_url()
|
||||
}
|
||||
|
||||
fn cache_miss_variants(image: Vec<u8>) -> Vec<Vec<u8>> {
|
||||
// The loader caches by content digest. Suffixes keep this workload on the miss path.
|
||||
(0..CACHE_MISS_VARIANT_COUNT)
|
||||
.map(|variant| {
|
||||
let mut image = image.clone();
|
||||
image.extend_from_slice(&variant.to_le_bytes());
|
||||
image
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Encodes a synthetic UI screenshot fixture for prompt image benchmarks.
|
||||
fn screenshot_png(size: ImageSize) -> Vec<u8> {
|
||||
let image = RgbaImage::from_fn(size.width, size.height, |x, y| {
|
||||
let toolbar = y < 52;
|
||||
let sidebar = x < 240;
|
||||
let panel_border = x % 320 < 2 || y % 216 < 2;
|
||||
let text_row = x > 270 && y > 88 && x % 19 < 13 && y % 31 < 3;
|
||||
|
||||
if toolbar {
|
||||
Rgba([33, 40, 52, 255])
|
||||
} else if sidebar {
|
||||
let selection = y / 68 % 5 == 2;
|
||||
if selection {
|
||||
Rgba([65, 106, 171, 255])
|
||||
} else {
|
||||
Rgba([44, 54, 67, 255])
|
||||
}
|
||||
} else if panel_border {
|
||||
Rgba([198, 205, 216, 255])
|
||||
} else if text_row {
|
||||
Rgba([72, 82, 96, 255])
|
||||
} else {
|
||||
let panel = ((x / 320) + (y / 216) * 3) % 4;
|
||||
match panel {
|
||||
0 => Rgba([246, 248, 252, 255]),
|
||||
1 => Rgba([234, 241, 250, 255]),
|
||||
2 => Rgba([240, 247, 236, 255]),
|
||||
_ => Rgba([250, 240, 235, 255]),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
encode_fixture(DynamicImage::ImageRgba8(image), ImageFormat::Png)
|
||||
}
|
||||
|
||||
/// Encodes a synthetic textured photo fixture for prompt image benchmarks.
|
||||
fn photo_jpeg(size: ImageSize) -> Vec<u8> {
|
||||
let image = RgbImage::from_fn(size.width, size.height, |x, y| {
|
||||
let x_gradient = x * 255 / size.width;
|
||||
let y_gradient = y * 255 / size.height;
|
||||
let texture = ((x.wrapping_mul(17) ^ y.wrapping_mul(31) ^ (x / 7) ^ (y / 11)) & 0xff) as u8;
|
||||
|
||||
Rgb([
|
||||
blend_channel(x_gradient, texture, 3),
|
||||
blend_channel((x_gradient + y_gradient) / 2, texture, 5),
|
||||
blend_channel(255 - y_gradient, texture, 4),
|
||||
])
|
||||
});
|
||||
|
||||
encode_fixture(DynamicImage::ImageRgb8(image), ImageFormat::Jpeg)
|
||||
}
|
||||
|
||||
fn blend_channel(gradient: u32, texture: u8, divisor: u32) -> u8 {
|
||||
((gradient + u32::from(texture) / divisor) % 256) as u8
|
||||
}
|
||||
|
||||
fn encode_fixture(image: DynamicImage, format: ImageFormat) -> Vec<u8> {
|
||||
let mut encoded = Cursor::new(Vec::new());
|
||||
#[allow(clippy::expect_used)]
|
||||
image
|
||||
.write_to(&mut encoded, format)
|
||||
.expect("benchmark fixture should encode");
|
||||
encoded.into_inner()
|
||||
}
|
||||
63
akode-rs/utils/image/src/error.rs
Normal file
63
akode-rs/utils/image/src/error.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use image::ImageError;
|
||||
use image::ImageFormat;
|
||||
use std::path::PathBuf;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ImageProcessingError {
|
||||
#[error("failed to read image at {path}: {source}")]
|
||||
Read {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to decode image at {path}: {source}")]
|
||||
Decode {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: image::ImageError,
|
||||
},
|
||||
#[error("failed to encode image as {format:?}: {source}")]
|
||||
Encode {
|
||||
format: ImageFormat,
|
||||
#[source]
|
||||
source: image::ImageError,
|
||||
},
|
||||
#[error("unsupported image `{mime}`")]
|
||||
UnsupportedImageFormat { mime: String },
|
||||
#[error("invalid image data URL: {reason}")]
|
||||
InvalidDataUrl { reason: String },
|
||||
#[error("image {representation} is too large ({size} bytes; max {max} bytes)")]
|
||||
ImageTooLarge {
|
||||
representation: &'static str,
|
||||
size: usize,
|
||||
max: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl ImageProcessingError {
|
||||
pub fn decode_error(path: &std::path::Path, source: image::ImageError) -> Self {
|
||||
if matches!(source, ImageError::Decoding(_)) {
|
||||
return ImageProcessingError::Decode {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
let mime = mime_guess::from_path(path)
|
||||
.first()
|
||||
.map(|mime_guess| mime_guess.essence_str().to_owned())
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
ImageProcessingError::UnsupportedImageFormat { mime }
|
||||
}
|
||||
|
||||
pub fn is_invalid_image(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
ImageProcessingError::Decode {
|
||||
source: ImageError::Decoding(_),
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
408
akode-rs/utils/image/src/image_tests.rs
Normal file
408
akode-rs/utils/image/src/image_tests.rs
Normal file
@@ -0,0 +1,408 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use super::*;
|
||||
use image::GenericImageView;
|
||||
use image::ImageBuffer;
|
||||
use image::ImageDecoder;
|
||||
use image::Rgba;
|
||||
use image::metadata::Orientation;
|
||||
|
||||
const TEST_RGB_ICC_PROFILE: &[u8] = b"0123456789abcdefRGB ";
|
||||
const TEST_CMYK_ICC_PROFILE: &[u8] = b"0123456789abcdefCMYK";
|
||||
const ROTATE_90_EXIF: &[u8] = &[
|
||||
0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x12, 0x01, 0x03, 0x00, 0x01, 0x00,
|
||||
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
|
||||
fn image_bytes(image: &ImageBuffer<Rgba<u8>, Vec<u8>>, format: ImageFormat) -> Vec<u8> {
|
||||
let mut encoded = Cursor::new(Vec::new());
|
||||
DynamicImage::ImageRgba8(image.clone())
|
||||
.write_to(&mut encoded, format)
|
||||
.expect("encode image to bytes");
|
||||
encoded.into_inner()
|
||||
}
|
||||
|
||||
fn image_bytes_with_metadata(
|
||||
image: &ImageBuffer<Rgba<u8>, Vec<u8>>,
|
||||
format: ImageFormat,
|
||||
icc_profile: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut encoded = Vec::new();
|
||||
match format {
|
||||
ImageFormat::Png => {
|
||||
let mut encoder = PngEncoder::new(&mut encoded);
|
||||
encoder
|
||||
.set_icc_profile(icc_profile.to_vec())
|
||||
.expect("set PNG ICC profile");
|
||||
encoder
|
||||
.set_exif_metadata(ROTATE_90_EXIF.to_vec())
|
||||
.expect("set PNG EXIF metadata");
|
||||
encoder
|
||||
.write_image(
|
||||
image.as_raw(),
|
||||
image.width(),
|
||||
image.height(),
|
||||
ColorType::Rgba8.into(),
|
||||
)
|
||||
.expect("encode PNG with metadata");
|
||||
}
|
||||
ImageFormat::Jpeg => {
|
||||
let mut encoder = JpegEncoder::new_with_quality(&mut encoded, 90);
|
||||
encoder
|
||||
.set_icc_profile(icc_profile.to_vec())
|
||||
.expect("set JPEG ICC profile");
|
||||
encoder
|
||||
.set_exif_metadata(ROTATE_90_EXIF.to_vec())
|
||||
.expect("set JPEG EXIF metadata");
|
||||
encoder
|
||||
.encode_image(&DynamicImage::ImageRgba8(image.clone()))
|
||||
.expect("encode JPEG with metadata");
|
||||
}
|
||||
ImageFormat::WebP => {
|
||||
let mut encoder = WebPEncoder::new_lossless(&mut encoded);
|
||||
encoder
|
||||
.set_icc_profile(icc_profile.to_vec())
|
||||
.expect("set WebP ICC profile");
|
||||
encoder
|
||||
.set_exif_metadata(ROTATE_90_EXIF.to_vec())
|
||||
.expect("set WebP EXIF metadata");
|
||||
encoder
|
||||
.write_image(
|
||||
image.as_raw(),
|
||||
image.width(),
|
||||
image.height(),
|
||||
ColorType::Rgba8.into(),
|
||||
)
|
||||
.expect("encode WebP with metadata");
|
||||
}
|
||||
_ => panic!("unsupported test format"),
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn returns_original_image_when_within_bounds() {
|
||||
for (format, mime) in [
|
||||
(ImageFormat::Png, "image/png"),
|
||||
(ImageFormat::WebP, "image/webp"),
|
||||
] {
|
||||
let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255]));
|
||||
let original_bytes = image_bytes(&image, format);
|
||||
|
||||
let encoded = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
original_bytes.clone(),
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process image");
|
||||
|
||||
assert_eq!(encoded.width, 64);
|
||||
assert_eq!(encoded.height, 32);
|
||||
assert_eq!(encoded.mime, mime);
|
||||
assert_eq!(encoded.bytes.as_ref(), original_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn downscales_large_image() {
|
||||
for (format, mime) in [
|
||||
(ImageFormat::Png, "image/png"),
|
||||
(ImageFormat::WebP, "image/webp"),
|
||||
] {
|
||||
let image = ImageBuffer::from_pixel(4096, 2048, Rgba([200u8, 10, 10, 255]));
|
||||
let original_bytes = image_bytes(&image, format);
|
||||
|
||||
let processed = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
original_bytes,
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process image");
|
||||
|
||||
assert!(processed.width <= MAX_DIMENSION);
|
||||
assert!(processed.height <= MAX_DIMENSION);
|
||||
assert_eq!(processed.mime, mime);
|
||||
|
||||
let detected_format =
|
||||
image::guess_format(&processed.bytes).expect("detect resized output format");
|
||||
assert_eq!(detected_format, format);
|
||||
|
||||
let loaded =
|
||||
image::load_from_memory(&processed.bytes).expect("read resized bytes back into image");
|
||||
assert_eq!(loaded.dimensions(), (processed.width, processed.height));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn downscales_tall_image_to_fit_square_bounds() {
|
||||
let image = ImageBuffer::from_pixel(1024, 4096, Rgba([200u8, 10, 10, 255]));
|
||||
let original_bytes = image_bytes(&image, ImageFormat::Png);
|
||||
|
||||
let processed = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
original_bytes,
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process image");
|
||||
|
||||
assert_eq!(processed.width, 512);
|
||||
assert_eq!(processed.height, MAX_DIMENSION);
|
||||
assert_eq!(processed.mime, "image/png");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn resizing_preserves_supported_metadata() {
|
||||
for format in [ImageFormat::Png, ImageFormat::Jpeg, ImageFormat::WebP] {
|
||||
let image = ImageBuffer::from_pixel(2050, 2, Rgba([200u8, 10, 10, 255]));
|
||||
let original_bytes = image_bytes_with_metadata(&image, format, TEST_RGB_ICC_PROFILE);
|
||||
|
||||
let processed = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
original_bytes,
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process image");
|
||||
|
||||
assert_eq!((processed.width, processed.height), (2048, 2));
|
||||
|
||||
let mut decoder = ImageReader::with_format(Cursor::new(&processed.bytes), format)
|
||||
.into_decoder()
|
||||
.expect("create decoder");
|
||||
assert_eq!(
|
||||
(
|
||||
decoder.dimensions(),
|
||||
decoder.orientation().expect("read orientation"),
|
||||
decoder.icc_profile().expect("read ICC profile"),
|
||||
decoder.exif_metadata().expect("read EXIF metadata"),
|
||||
),
|
||||
(
|
||||
(2048, 2),
|
||||
Orientation::Rotate90,
|
||||
Some(TEST_RGB_ICC_PROFILE.to_vec()),
|
||||
Some(ROTATE_90_EXIF.to_vec()),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn resizing_drops_non_rgb_icc_profile() {
|
||||
let image = ImageBuffer::from_pixel(2050, 2, Rgba([200u8, 10, 10, 255]));
|
||||
let original_bytes =
|
||||
image_bytes_with_metadata(&image, ImageFormat::Jpeg, TEST_CMYK_ICC_PROFILE);
|
||||
|
||||
let processed = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
original_bytes,
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process image");
|
||||
|
||||
let mut decoder = ImageReader::with_format(Cursor::new(&processed.bytes), ImageFormat::Jpeg)
|
||||
.into_decoder()
|
||||
.expect("create decoder");
|
||||
assert_eq!(
|
||||
(
|
||||
decoder.icc_profile().expect("read ICC profile"),
|
||||
decoder.exif_metadata().expect("read EXIF metadata"),
|
||||
),
|
||||
(None, Some(ROTATE_90_EXIF.to_vec()))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn preserves_large_image_in_original_mode() {
|
||||
let image = ImageBuffer::from_pixel(4096, 2048, Rgba([180u8, 30, 30, 255]));
|
||||
let original_bytes = image_bytes(&image, ImageFormat::Png);
|
||||
|
||||
let processed = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
original_bytes.clone(),
|
||||
PromptImageMode::Original,
|
||||
)
|
||||
.expect("process image");
|
||||
|
||||
assert_eq!(processed.width, 4096);
|
||||
assert_eq!(processed.height, 2048);
|
||||
assert_eq!(processed.mime, "image/png");
|
||||
assert_eq!(processed.bytes.as_ref(), original_bytes);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn data_url_processing_preserves_supported_source_bytes() {
|
||||
let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255]));
|
||||
let original_bytes = image_bytes(&image, ImageFormat::Png);
|
||||
let image_url = data_url_from_bytes("image/png", &original_bytes)
|
||||
.replacen("data:", "DATA:", 1)
|
||||
.replacen(";base64,", ";BASE64,", 1);
|
||||
|
||||
let processed = load_data_url_for_prompt_uncached(&image_url, PromptImageMode::ResizeToFit)
|
||||
.expect("process data URL image");
|
||||
|
||||
assert_eq!(processed.width, 64);
|
||||
assert_eq!(processed.height, 32);
|
||||
assert_eq!(processed.mime, "image/png");
|
||||
assert_eq!(processed.bytes.as_ref(), original_bytes);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn data_url_processing_converts_gif_to_png() {
|
||||
let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255]));
|
||||
let gif_bytes = image_bytes(&image, ImageFormat::Gif);
|
||||
let image_url = data_url_from_bytes("image/gif", &gif_bytes);
|
||||
|
||||
let processed = load_data_url_for_prompt(&image_url, PromptImageMode::ResizeToFit)
|
||||
.expect("process GIF data URL");
|
||||
|
||||
assert_eq!(processed.mime, "image/png");
|
||||
assert_eq!(
|
||||
image::guess_format(&processed.bytes).expect("detect processed format"),
|
||||
ImageFormat::Png
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_url_processing_rejects_malformed_input() {
|
||||
for image_url in [
|
||||
"image/png;base64,AAAA",
|
||||
"data:image/png;base64",
|
||||
"data:image/png,AAAA",
|
||||
"data:image/png;base64,not base64",
|
||||
] {
|
||||
assert!(matches!(
|
||||
load_data_url_for_prompt(image_url, PromptImageMode::ResizeToFit),
|
||||
Err(ImageProcessingError::InvalidDataUrl { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared detail modes apply the policies used by external byte-oriented callers.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn detail_modes_apply_expected_budgets() {
|
||||
for (mode, input_dimensions, expected_dimensions) in [
|
||||
(PromptImageMode::HIGH_DETAIL, (2048, 2048), (1600, 1600)),
|
||||
(PromptImageMode::ORIGINAL_DETAIL, (6401, 100), (6000, 94)),
|
||||
] {
|
||||
let image = ImageBuffer::from_pixel(
|
||||
input_dimensions.0,
|
||||
input_dimensions.1,
|
||||
Rgba([200u8, 10, 10, 255]),
|
||||
);
|
||||
let original_bytes = image_bytes(&image, ImageFormat::Png);
|
||||
let processed = load_for_prompt_bytes(Path::new("in-memory-image"), original_bytes, mode)
|
||||
.expect("process image with detail mode");
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
processed.source_width,
|
||||
processed.source_height,
|
||||
processed.width,
|
||||
processed.height,
|
||||
),
|
||||
(
|
||||
input_dimensions.0,
|
||||
input_dimensions.1,
|
||||
expected_dimensions.0,
|
||||
expected_dimensions.1,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fails_cleanly_for_invalid_images() {
|
||||
let err = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
b"not an image".to_vec(),
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect_err("invalid image should fail");
|
||||
assert!(matches!(
|
||||
err,
|
||||
ImageProcessingError::Decode { .. } | ImageProcessingError::UnsupportedImageFormat { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_png_with_readable_dimensions_and_corrupt_pixels() {
|
||||
let image = ImageBuffer::from_pixel(100, 100, Rgba([10u8, 20, 30, 255]));
|
||||
let mut bytes = image_bytes(&image, ImageFormat::Png);
|
||||
let idat = bytes
|
||||
.windows(4)
|
||||
.position(|chunk_type| chunk_type == b"IDAT")
|
||||
.expect("PNG has an IDAT chunk");
|
||||
// Damage the compressed pixel data while keeping the PNG header intact.
|
||||
bytes[idat + 4] ^= 0xff;
|
||||
|
||||
let dimensions = ImageReader::with_format(Cursor::new(&bytes), ImageFormat::Png)
|
||||
.into_dimensions()
|
||||
.expect("dimensions should still be readable");
|
||||
assert_eq!(dimensions, (100, 100));
|
||||
|
||||
let error = load_for_prompt_bytes(
|
||||
Path::new("corrupt.png"),
|
||||
bytes,
|
||||
PromptImageMode::ORIGINAL_DETAIL,
|
||||
)
|
||||
.expect_err("even a PNG small enough to pass through must have decodable pixels");
|
||||
assert!(
|
||||
matches!(error, ImageProcessingError::Decode { .. }),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reprocesses_updated_file_contents() {
|
||||
IMAGE_CACHE.clear();
|
||||
|
||||
let first_image = ImageBuffer::from_pixel(32, 16, Rgba([20u8, 120, 220, 255]));
|
||||
let first_bytes = image_bytes(&first_image, ImageFormat::Png);
|
||||
|
||||
let first = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
first_bytes,
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process first image");
|
||||
|
||||
let second_image = ImageBuffer::from_pixel(96, 48, Rgba([50u8, 60, 70, 255]));
|
||||
let second_bytes = image_bytes(&second_image, ImageFormat::Png);
|
||||
|
||||
let second = load_for_prompt_bytes(
|
||||
Path::new("in-memory-image"),
|
||||
second_bytes,
|
||||
PromptImageMode::ResizeToFit,
|
||||
)
|
||||
.expect("process updated image");
|
||||
|
||||
assert_eq!(first.width, 32);
|
||||
assert_eq!(first.height, 16);
|
||||
assert_eq!(second.width, 96);
|
||||
assert_eq!(second.height, 48);
|
||||
assert_ne!(second.bytes, first.bytes);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bounds_cache_by_encoded_byte_size() {
|
||||
let cache = ImageCache::new(NonZeroUsize::new(4).expect("non-zero cache capacity"));
|
||||
let key = |digest_byte| ImageCacheKey {
|
||||
digest: [digest_byte; 20],
|
||||
mode: PromptImageMode::Original,
|
||||
};
|
||||
let image = |size| EncodedImage {
|
||||
bytes: vec![0; size].into(),
|
||||
mime: "image/png".to_string(),
|
||||
source_width: 1,
|
||||
source_height: 1,
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
|
||||
cache_image(&cache, key(1), image(3), /*byte_capacity*/ 5);
|
||||
cache_image(&cache, key(2), image(3), /*byte_capacity*/ 5);
|
||||
cache_image(&cache, key(3), image(6), /*byte_capacity*/ 5);
|
||||
|
||||
assert!(cache.get(&key(1)).is_none());
|
||||
assert!(cache.get(&key(2)).is_some());
|
||||
assert!(cache.get(&key(3)).is_none());
|
||||
}
|
||||
462
akode-rs/utils/image/src/lib.rs
Normal file
462
akode-rs/utils/image/src/lib.rs
Normal file
@@ -0,0 +1,462 @@
|
||||
use std::io::Cursor;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use akode_utils_cache::BlockingLruCache;
|
||||
use akode_utils_cache::sha1_digest;
|
||||
use image::ColorType;
|
||||
use image::DynamicImage;
|
||||
use image::GenericImageView;
|
||||
use image::ImageDecoder;
|
||||
use image::ImageEncoder;
|
||||
use image::ImageFormat;
|
||||
use image::ImageReader;
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
use image::codecs::png::PngEncoder;
|
||||
use image::codecs::webp::WebPEncoder;
|
||||
use image::imageops::FilterType;
|
||||
|
||||
const DATA_URL_PREFIX: &str = "data:";
|
||||
pub const PROMPT_IMAGE_PATCH_SIZE: u32 = 32;
|
||||
/// Maximum width or height used when resizing images before uploading.
|
||||
pub const MAX_DIMENSION: u32 = 2048;
|
||||
/// Maximum accepted byte length for prompt image input representations.
|
||||
///
|
||||
/// This is a high sanity guard against pathological inputs, not a protocol
|
||||
/// requirement or target upload size.
|
||||
pub const MAX_PROMPT_IMAGE_INPUT_BYTES: usize = 1024 * 1024 * 1024;
|
||||
const MAX_IMAGE_CACHE_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
pub mod error;
|
||||
|
||||
pub use crate::error::ImageProcessingError;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EncodedImage {
|
||||
pub bytes: Arc<[u8]>,
|
||||
pub mime: String,
|
||||
pub source_width: u32,
|
||||
pub source_height: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl EncodedImage {
|
||||
pub fn into_data_url(self) -> String {
|
||||
data_url_from_bytes(&self.mime, &self.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps image bytes in a data URL without decoding or validating them.
|
||||
pub fn data_url_from_bytes(mime: &str, bytes: &[u8]) -> String {
|
||||
let encoded = BASE64_STANDARD.encode(bytes);
|
||||
format!("data:{mime};base64,{encoded}")
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum PromptImageMode {
|
||||
ResizeToFit,
|
||||
Original,
|
||||
ResizeWithLimits(PromptImageResizeLimits),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct PromptImageResizeLimits {
|
||||
pub max_dimension: u32,
|
||||
pub max_patches: usize,
|
||||
}
|
||||
|
||||
impl PromptImageMode {
|
||||
/// Resize policy for high-detail prompt images.
|
||||
pub const HIGH_DETAIL: Self = Self::ResizeWithLimits(PromptImageResizeLimits {
|
||||
max_dimension: 2048,
|
||||
max_patches: 2_500,
|
||||
});
|
||||
/// Resize policy for original-detail prompt images.
|
||||
pub const ORIGINAL_DETAIL: Self = Self::ResizeWithLimits(PromptImageResizeLimits {
|
||||
max_dimension: 6000,
|
||||
max_patches: 10_000,
|
||||
});
|
||||
}
|
||||
|
||||
struct ImageMetadata {
|
||||
icc_profile: Option<Vec<u8>>,
|
||||
exif: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct ImageCacheKey {
|
||||
digest: [u8; 20],
|
||||
mode: PromptImageMode,
|
||||
}
|
||||
|
||||
type ImageCache = BlockingLruCache<ImageCacheKey, EncodedImage>;
|
||||
|
||||
static IMAGE_CACHE: LazyLock<ImageCache> =
|
||||
LazyLock::new(|| BlockingLruCache::new(NonZeroUsize::new(32).unwrap_or(NonZeroUsize::MIN)));
|
||||
|
||||
pub fn load_for_prompt_bytes(
|
||||
path: &Path,
|
||||
file_bytes: Vec<u8>,
|
||||
mode: PromptImageMode,
|
||||
) -> Result<EncodedImage, ImageProcessingError> {
|
||||
let path_buf = path.to_path_buf();
|
||||
|
||||
let key = ImageCacheKey {
|
||||
digest: sha1_digest(&file_bytes),
|
||||
mode,
|
||||
};
|
||||
|
||||
if let Some(image) = IMAGE_CACHE.get(&key) {
|
||||
return Ok(image);
|
||||
}
|
||||
|
||||
let image = load_for_prompt_bytes_uncached(&path_buf, file_bytes, mode)?;
|
||||
cache_image(&IMAGE_CACHE, key, image.clone(), MAX_IMAGE_CACHE_BYTES);
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
fn load_for_prompt_bytes_uncached(
|
||||
path: &Path,
|
||||
file_bytes: Vec<u8>,
|
||||
mode: PromptImageMode,
|
||||
) -> Result<EncodedImage, ImageProcessingError> {
|
||||
let path_buf = path.to_path_buf();
|
||||
(move || {
|
||||
let guessed_format = image::guess_format(&file_bytes)
|
||||
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
|
||||
let format = match guessed_format {
|
||||
ImageFormat::Png => Some(ImageFormat::Png),
|
||||
ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
|
||||
ImageFormat::Gif => Some(ImageFormat::Gif),
|
||||
ImageFormat::WebP => Some(ImageFormat::WebP),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut decoder = ImageReader::with_format(Cursor::new(&file_bytes), guessed_format)
|
||||
.into_decoder()
|
||||
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
|
||||
// Preserve the metadata most important for rendering prompt images faithfully: the color
|
||||
// profile and EXIF data, including orientation. Other format-specific metadata is
|
||||
// intentionally not copied.
|
||||
let metadata = ImageMetadata {
|
||||
// Only RGB profiles are safe across every re-encoding path. For example, JPEG decoding
|
||||
// can convert CMYK/YCCK pixels to RGB while retaining the source profile; copying it
|
||||
// would mislabel the output. Bytes 16..20 are the ICC data color space signature.
|
||||
icc_profile: decoder
|
||||
.icc_profile()
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|profile| profile.get(16..20) == Some(b"RGB ")),
|
||||
exif: decoder.exif_metadata().ok().flatten(),
|
||||
};
|
||||
let dynamic = DynamicImage::from_decoder(decoder)
|
||||
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
|
||||
|
||||
let (width, height) = dynamic.dimensions();
|
||||
|
||||
let target_dimensions = match mode {
|
||||
PromptImageMode::ResizeToFit if width > MAX_DIMENSION || height > MAX_DIMENSION => {
|
||||
let resized = dynamic.resize(MAX_DIMENSION, MAX_DIMENSION, FilterType::Triangle);
|
||||
Some((resized.width(), resized.height(), resized))
|
||||
}
|
||||
PromptImageMode::ResizeWithLimits(limits) => {
|
||||
let (target_width, target_height) =
|
||||
prompt_image_output_dimensions_for_limits(width, height, limits);
|
||||
if (target_width, target_height) == (width, height) {
|
||||
None
|
||||
} else {
|
||||
let resized =
|
||||
dynamic.resize_exact(target_width, target_height, FilterType::Triangle);
|
||||
Some((target_width, target_height, resized))
|
||||
}
|
||||
}
|
||||
PromptImageMode::ResizeToFit | PromptImageMode::Original => None,
|
||||
};
|
||||
|
||||
let encoded = if let Some((prepared_width, prepared_height, resized)) = target_dimensions {
|
||||
let target_format = format
|
||||
.filter(|format| can_preserve_source_bytes(*format))
|
||||
.unwrap_or(ImageFormat::Png);
|
||||
let (bytes, output_format) = encode_image(&resized, target_format, metadata)?;
|
||||
let mime = format_to_mime(output_format);
|
||||
EncodedImage {
|
||||
bytes: bytes.into(),
|
||||
mime,
|
||||
source_width: width,
|
||||
source_height: height,
|
||||
width: prepared_width,
|
||||
height: prepared_height,
|
||||
}
|
||||
} else {
|
||||
if let Some(format) = format.filter(|format| can_preserve_source_bytes(*format)) {
|
||||
let mime = format_to_mime(format);
|
||||
EncodedImage {
|
||||
bytes: file_bytes.into(),
|
||||
mime,
|
||||
source_width: width,
|
||||
source_height: height,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
} else {
|
||||
let (bytes, output_format) = encode_image(&dynamic, ImageFormat::Png, metadata)?;
|
||||
let mime = format_to_mime(output_format);
|
||||
EncodedImage {
|
||||
bytes: bytes.into(),
|
||||
mime,
|
||||
source_width: width,
|
||||
source_height: height,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(encoded)
|
||||
})()
|
||||
}
|
||||
|
||||
fn cache_image(cache: &ImageCache, key: ImageCacheKey, image: EncodedImage, byte_capacity: usize) {
|
||||
if image.bytes.len() > byte_capacity {
|
||||
return;
|
||||
}
|
||||
|
||||
cache.with_mut(|cache| {
|
||||
cache.put(key, image);
|
||||
let mut cached_bytes = cache
|
||||
.iter()
|
||||
.map(|(_, image)| image.bytes.len())
|
||||
.sum::<usize>();
|
||||
while cached_bytes > byte_capacity {
|
||||
let Some((_, evicted)) = cache.pop_lru() else {
|
||||
break;
|
||||
};
|
||||
cached_bytes -= evicted.bytes.len();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn load_data_url_for_prompt(
|
||||
image_url: &str,
|
||||
mode: PromptImageMode,
|
||||
) -> Result<EncodedImage, ImageProcessingError> {
|
||||
load_data_url_for_prompt_with(image_url, mode, load_for_prompt_bytes)
|
||||
}
|
||||
|
||||
pub fn load_data_url_for_prompt_uncached(
|
||||
image_url: &str,
|
||||
mode: PromptImageMode,
|
||||
) -> Result<EncodedImage, ImageProcessingError> {
|
||||
load_data_url_for_prompt_with(image_url, mode, load_for_prompt_bytes_uncached)
|
||||
}
|
||||
|
||||
fn load_data_url_for_prompt_with(
|
||||
image_url: &str,
|
||||
mode: PromptImageMode,
|
||||
load: impl FnOnce(&Path, Vec<u8>, PromptImageMode) -> Result<EncodedImage, ImageProcessingError>,
|
||||
) -> Result<EncodedImage, ImageProcessingError> {
|
||||
let rest = image_url
|
||||
.get(..DATA_URL_PREFIX.len())
|
||||
.filter(|prefix| prefix.eq_ignore_ascii_case(DATA_URL_PREFIX))
|
||||
.and_then(|_| image_url.get(DATA_URL_PREFIX.len()..))
|
||||
.ok_or_else(|| ImageProcessingError::InvalidDataUrl {
|
||||
reason: "missing data: prefix".to_string(),
|
||||
})?;
|
||||
let (metadata, encoded) =
|
||||
rest.split_once(',')
|
||||
.ok_or_else(|| ImageProcessingError::InvalidDataUrl {
|
||||
reason: "missing comma separator".to_string(),
|
||||
})?;
|
||||
if !metadata
|
||||
.split(';')
|
||||
.any(|part| part.eq_ignore_ascii_case("base64"))
|
||||
{
|
||||
return Err(ImageProcessingError::InvalidDataUrl {
|
||||
reason: "only base64 data URLs are supported".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
if encoded.len() > MAX_PROMPT_IMAGE_INPUT_BYTES {
|
||||
return Err(ImageProcessingError::ImageTooLarge {
|
||||
representation: "base64 payload",
|
||||
size: encoded.len(),
|
||||
max: MAX_PROMPT_IMAGE_INPUT_BYTES,
|
||||
});
|
||||
}
|
||||
let file_bytes =
|
||||
BASE64_STANDARD
|
||||
.decode(encoded)
|
||||
.map_err(|source| ImageProcessingError::InvalidDataUrl {
|
||||
reason: format!("invalid base64 payload: {source}"),
|
||||
})?;
|
||||
if file_bytes.len() > MAX_PROMPT_IMAGE_INPUT_BYTES {
|
||||
return Err(ImageProcessingError::ImageTooLarge {
|
||||
representation: "decoded input",
|
||||
size: file_bytes.len(),
|
||||
max: MAX_PROMPT_IMAGE_INPUT_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
load(Path::new("<data-url-image>"), file_bytes, mode)
|
||||
}
|
||||
|
||||
fn prompt_image_output_dimensions_for_limits(
|
||||
width: u32,
|
||||
height: u32,
|
||||
limits: PromptImageResizeLimits,
|
||||
) -> (u32, u32) {
|
||||
let width = width.max(1);
|
||||
let height = height.max(1);
|
||||
if prompt_image_dimensions_fit(width, height, limits) {
|
||||
return (width, height);
|
||||
}
|
||||
|
||||
let max_dimension_scale =
|
||||
(f64::from(limits.max_dimension) / f64::from(width.max(height))).min(1.0);
|
||||
let width = ((f64::from(width) * max_dimension_scale).round() as u32).max(1);
|
||||
let height = ((f64::from(height) * max_dimension_scale).round() as u32).max(1);
|
||||
if prompt_image_dimensions_fit(width, height, limits) {
|
||||
return (width, height);
|
||||
}
|
||||
|
||||
let width_f64 = f64::from(width);
|
||||
let height_f64 = f64::from(height);
|
||||
let patch_size = f64::from(PROMPT_IMAGE_PATCH_SIZE);
|
||||
let mut scale =
|
||||
(patch_size * patch_size * limits.max_patches as f64 / width_f64 / height_f64).sqrt();
|
||||
// Match Responses patch-budget math: shrink by area, then round the scaled
|
||||
// patch grid down so integer output dimensions remain within the budget.
|
||||
let scaled_patches_wide = width_f64 * scale / patch_size;
|
||||
let scaled_patches_high = height_f64 * scale / patch_size;
|
||||
scale *= (scaled_patches_wide.floor() / scaled_patches_wide)
|
||||
.min(scaled_patches_high.floor() / scaled_patches_high);
|
||||
|
||||
(
|
||||
((width_f64 * scale).floor() as u32).max(1),
|
||||
((height_f64 * scale).floor() as u32).max(1),
|
||||
)
|
||||
}
|
||||
|
||||
fn prompt_image_dimensions_fit(width: u32, height: u32, limits: PromptImageResizeLimits) -> bool {
|
||||
let patches_wide = width.div_ceil(PROMPT_IMAGE_PATCH_SIZE);
|
||||
let patches_high = height.div_ceil(PROMPT_IMAGE_PATCH_SIZE);
|
||||
let patch_count = u64::from(patches_wide) * u64::from(patches_high);
|
||||
width <= limits.max_dimension
|
||||
&& height <= limits.max_dimension
|
||||
&& patch_count <= limits.max_patches as u64
|
||||
}
|
||||
|
||||
fn can_preserve_source_bytes(format: ImageFormat) -> bool {
|
||||
// Public API docs explicitly call out non-animated GIF support only.
|
||||
// Preserve byte-for-byte only for formats we can safely pass through.
|
||||
matches!(
|
||||
format,
|
||||
ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP
|
||||
)
|
||||
}
|
||||
|
||||
fn encode_image(
|
||||
image: &DynamicImage,
|
||||
preferred_format: ImageFormat,
|
||||
metadata: ImageMetadata,
|
||||
) -> Result<(Vec<u8>, ImageFormat), ImageProcessingError> {
|
||||
let target_format = match preferred_format {
|
||||
ImageFormat::Jpeg => ImageFormat::Jpeg,
|
||||
ImageFormat::WebP => ImageFormat::WebP,
|
||||
_ => ImageFormat::Png,
|
||||
};
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
let ImageMetadata { icc_profile, exif } = metadata;
|
||||
|
||||
match target_format {
|
||||
ImageFormat::Png => {
|
||||
let rgba = image.to_rgba8();
|
||||
let mut encoder = PngEncoder::new(&mut buffer);
|
||||
apply_image_metadata(&mut encoder, icc_profile, exif, target_format)?;
|
||||
encoder
|
||||
.write_image(
|
||||
rgba.as_raw(),
|
||||
image.width(),
|
||||
image.height(),
|
||||
ColorType::Rgba8.into(),
|
||||
)
|
||||
.map_err(|source| ImageProcessingError::Encode {
|
||||
format: target_format,
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
ImageFormat::Jpeg => {
|
||||
let mut encoder = JpegEncoder::new_with_quality(&mut buffer, 85);
|
||||
apply_image_metadata(&mut encoder, icc_profile, exif, target_format)?;
|
||||
encoder
|
||||
.encode_image(image)
|
||||
.map_err(|source| ImageProcessingError::Encode {
|
||||
format: target_format,
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
ImageFormat::WebP => {
|
||||
let rgba = image.to_rgba8();
|
||||
let mut encoder = WebPEncoder::new_lossless(&mut buffer);
|
||||
apply_image_metadata(&mut encoder, icc_profile, exif, target_format)?;
|
||||
encoder
|
||||
.write_image(
|
||||
rgba.as_raw(),
|
||||
image.width(),
|
||||
image.height(),
|
||||
ColorType::Rgba8.into(),
|
||||
)
|
||||
.map_err(|source| ImageProcessingError::Encode {
|
||||
format: target_format,
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
_ => unreachable!("unsupported target_format should have been handled earlier"),
|
||||
}
|
||||
|
||||
Ok((buffer, target_format))
|
||||
}
|
||||
|
||||
fn apply_image_metadata(
|
||||
encoder: &mut impl ImageEncoder,
|
||||
icc_profile: Option<Vec<u8>>,
|
||||
exif: Option<Vec<u8>>,
|
||||
format: ImageFormat,
|
||||
) -> Result<(), ImageProcessingError> {
|
||||
if let Some(icc_profile) = icc_profile {
|
||||
encoder
|
||||
.set_icc_profile(icc_profile)
|
||||
.map_err(|source| ImageProcessingError::Encode {
|
||||
format,
|
||||
source: image::ImageError::Unsupported(source),
|
||||
})?;
|
||||
}
|
||||
if let Some(exif) = exif {
|
||||
encoder
|
||||
.set_exif_metadata(exif)
|
||||
.map_err(|source| ImageProcessingError::Encode {
|
||||
format,
|
||||
source: image::ImageError::Unsupported(source),
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn format_to_mime(format: ImageFormat) -> String {
|
||||
match format {
|
||||
ImageFormat::Jpeg => "image/jpeg".to_string(),
|
||||
ImageFormat::Gif => "image/gif".to_string(),
|
||||
ImageFormat::WebP => "image/webp".to_string(),
|
||||
_ => "image/png".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "image_tests.rs"]
|
||||
mod tests;
|
||||
6
akode-rs/utils/json-to-toml/BUILD.bazel
Normal file
6
akode-rs/utils/json-to-toml/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "json-to-toml",
|
||||
crate_name = "akode_utils_json_to_toml",
|
||||
)
|
||||
18
akode-rs/utils/json-to-toml/Cargo.toml
Normal file
18
akode-rs/utils/json-to-toml/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "akode-utils-json-to-toml"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde_json = { workspace = true }
|
||||
toml = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
83
akode-rs/utils/json-to-toml/src/lib.rs
Normal file
83
akode-rs/utils/json-to-toml/src/lib.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use serde_json::Value as JsonValue;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
/// Convert a `serde_json::Value` into a semantically equivalent `toml::Value`.
|
||||
pub fn json_to_toml(v: JsonValue) -> TomlValue {
|
||||
match v {
|
||||
JsonValue::Null => TomlValue::String(String::new()),
|
||||
JsonValue::Bool(b) => TomlValue::Boolean(b),
|
||||
JsonValue::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
TomlValue::Integer(i)
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
TomlValue::Float(f)
|
||||
} else {
|
||||
TomlValue::String(n.to_string())
|
||||
}
|
||||
}
|
||||
JsonValue::String(s) => TomlValue::String(s),
|
||||
JsonValue::Array(arr) => TomlValue::Array(arr.into_iter().map(json_to_toml).collect()),
|
||||
JsonValue::Object(map) => {
|
||||
let tbl = map
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k, json_to_toml(v)))
|
||||
.collect::<toml::value::Table>();
|
||||
TomlValue::Table(tbl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn json_number_to_toml() {
|
||||
let json_value = json!(123);
|
||||
assert_eq!(TomlValue::Integer(123), json_to_toml(json_value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_array_to_toml() {
|
||||
let json_value = json!([true, 1]);
|
||||
assert_eq!(
|
||||
TomlValue::Array(vec![TomlValue::Boolean(true), TomlValue::Integer(1)]),
|
||||
json_to_toml(json_value)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_bool_to_toml() {
|
||||
let json_value = json!(false);
|
||||
assert_eq!(TomlValue::Boolean(false), json_to_toml(json_value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_float_to_toml() {
|
||||
let json_value = json!(1.25);
|
||||
assert_eq!(TomlValue::Float(1.25), json_to_toml(json_value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_null_to_toml() {
|
||||
let json_value = serde_json::Value::Null;
|
||||
assert_eq!(TomlValue::String(String::new()), json_to_toml(json_value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_object_nested() {
|
||||
let json_value = json!({ "outer": { "inner": 2 } });
|
||||
let expected = {
|
||||
let mut inner = toml::value::Table::new();
|
||||
inner.insert("inner".into(), TomlValue::Integer(2));
|
||||
|
||||
let mut outer = toml::value::Table::new();
|
||||
outer.insert("outer".into(), TomlValue::Table(inner));
|
||||
TomlValue::Table(outer)
|
||||
};
|
||||
|
||||
assert_eq!(json_to_toml(json_value), expected);
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/model-facing-id/BUILD.bazel
Normal file
6
akode-rs/utils/model-facing-id/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "model-facing-id",
|
||||
crate_name = "akode_utils_model_facing_id",
|
||||
)
|
||||
23
akode-rs/utils/model-facing-id/Cargo.toml
Normal file
23
akode-rs/utils/model-facing-id/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "akode-utils-model-facing-id"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
test = false
|
||||
|
||||
[dependencies]
|
||||
blake3.workspace = true
|
||||
schemars.workspace = true
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
pretty_assertions.workspace = true
|
||||
197
akode-rs/utils/model-facing-id/src/lib.rs
Normal file
197
akode-rs/utils/model-facing-id/src/lib.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! Issues a salt followed by shuffled decimal IDs from `000`–`999`, then `001000`–`999999`.
|
||||
//! Each pool uses a four-round Feistel permutation with BLAKE3 and cycle-walking.
|
||||
//! The seed can be varied across sessions to change the order in which IDs are issued.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
const VERSION: u32 = 1;
|
||||
// Our tokenizers encode every decimal ID of up to three digits as a single token.
|
||||
const GROUP_SIZE: u64 = 1_000;
|
||||
|
||||
/// Stores the salt and numeric value separately. Display pads the value to groups of three digits.
|
||||
/// With salt `environment`, zero renders as `environment000` and 1000 as `environment001000`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct ModelFacingId {
|
||||
salt: Cow<'static, str>,
|
||||
value: u64,
|
||||
}
|
||||
|
||||
impl fmt::Display for ModelFacingId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}{}", self.salt, self.digits())
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelFacingId {
|
||||
/// Formats the padded digits for protocols that supply their own type prefix.
|
||||
pub fn digits(&self) -> impl fmt::Display + '_ {
|
||||
fmt::from_fn(|f| {
|
||||
write!(
|
||||
f,
|
||||
"{:0width$}",
|
||||
self.value,
|
||||
width = decimal_width(self.value)
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn decimal_width(value: u64) -> usize {
|
||||
(value.checked_ilog10().unwrap_or(0) as usize + 1).next_multiple_of(3)
|
||||
}
|
||||
|
||||
/// Generates token-efficient identifiers for model context.
|
||||
#[derive(Debug)]
|
||||
pub struct ModelFacingIdGenerator {
|
||||
state: ModelFacingIdGeneratorState,
|
||||
}
|
||||
|
||||
impl ModelFacingIdGenerator {
|
||||
/// Starts a sequence for one ID kind using a shared session seed.
|
||||
/// The salt also prefixes each displayed ID. Use the [tokenizer](https://platform.openai.com/tokenizer)
|
||||
/// to choose a stable, single-token salt such as `environment`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the salt is empty.
|
||||
pub fn new(seed: u64, salt: &'static str) -> Self {
|
||||
assert!(!salt.is_empty(), "a model ID salt must be nonempty");
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(&seed.to_le_bytes());
|
||||
hasher.update(salt.as_bytes());
|
||||
let mut seed_bytes = [0; 8];
|
||||
hasher.finalize_xof().fill(&mut seed_bytes);
|
||||
let derived_seed = u64::from_le_bytes(seed_bytes);
|
||||
Self {
|
||||
state: ModelFacingIdGeneratorState::new(
|
||||
VERSION,
|
||||
derived_seed,
|
||||
salt,
|
||||
/*next_ordinal*/ 0,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Issues the next ID. After all `u64` values are issued, the sequence repeats from zero.
|
||||
pub fn fetch_next(&mut self) -> ModelFacingId {
|
||||
let ordinal = self.state.next_ordinal;
|
||||
let mut pool = 0..=GROUP_SIZE - 1;
|
||||
while ordinal > *pool.end() {
|
||||
let start = pool.end() + 1;
|
||||
// The final decimal pool ends at u64::MAX, which has no representable successor.
|
||||
let last = start
|
||||
.checked_mul(GROUP_SIZE)
|
||||
.map_or(u64::MAX, |end| end - 1);
|
||||
pool = start..=last;
|
||||
}
|
||||
let id = permute(self.state.seed, pool, ordinal);
|
||||
let (next, wrapped) = ordinal.overflowing_add(1);
|
||||
if wrapped {
|
||||
tracing::error!(
|
||||
"model-facing ID generator exhausted all u64 values and wrapped to zero"
|
||||
);
|
||||
}
|
||||
self.state.next_ordinal = next;
|
||||
ModelFacingId {
|
||||
salt: self.state.salt.clone(),
|
||||
value: id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures the position of the next allocation.
|
||||
pub fn snapshot(&self) -> ModelFacingIdGeneratorState {
|
||||
self.state.clone()
|
||||
}
|
||||
|
||||
/// Continues the snapshot's sequence from its next unissued ordinal.
|
||||
pub fn restore(state: ModelFacingIdGeneratorState) -> Result<Self, RestoreError> {
|
||||
if state.version != VERSION {
|
||||
return Err(RestoreError::UnsupportedVersion(state.version));
|
||||
}
|
||||
if state.salt.is_empty() {
|
||||
return Err(RestoreError::InvalidSalt);
|
||||
}
|
||||
Ok(Self { state })
|
||||
}
|
||||
}
|
||||
|
||||
/// Persisted sequence version, derived seed, salt, and zero-based next allocation ordinal.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ModelFacingIdGeneratorState {
|
||||
version: u32,
|
||||
seed: u64,
|
||||
salt: Cow<'static, str>,
|
||||
next_ordinal: u64,
|
||||
}
|
||||
|
||||
impl ModelFacingIdGeneratorState {
|
||||
/// Returns the namespace this snapshot belongs to.
|
||||
pub fn salt(&self) -> &str {
|
||||
&self.salt
|
||||
}
|
||||
|
||||
/// Rebuilds a snapshot from its stored fields. [`ModelFacingIdGenerator::restore`] validates it.
|
||||
pub fn new(
|
||||
version: u32,
|
||||
seed: u64,
|
||||
salt: impl Into<Cow<'static, str>>,
|
||||
next_ordinal: u64,
|
||||
) -> Self {
|
||||
Self {
|
||||
version,
|
||||
seed,
|
||||
salt: salt.into(),
|
||||
next_ordinal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The snapshot cannot be used to resume an allocation sequence.
|
||||
#[derive(Debug, PartialEq, Eq, Error)]
|
||||
pub enum RestoreError {
|
||||
#[error("unsupported model-facing ID generator version {0}")]
|
||||
UnsupportedVersion(u32),
|
||||
#[error("a model ID salt must be nonempty")]
|
||||
InvalidSalt,
|
||||
}
|
||||
|
||||
// Use the smallest balanced Feistel domain that covers the pool to limit cycle-walking.
|
||||
// Both the four rounds and their input encoding are part of the snapshot format.
|
||||
fn permute(seed: u64, pool: RangeInclusive<u64>, ordinal: u64) -> u64 {
|
||||
let start = *pool.start();
|
||||
let size = pool.end() - start + 1;
|
||||
let bits = u64::BITS - (size - 1).leading_zeros();
|
||||
let half_bits = bits.div_ceil(2);
|
||||
let half_mask = (1_u64 << half_bits) - 1;
|
||||
// The seed, pool index, and round occupy 17 bytes. The pool width fixes the right half's length.
|
||||
let input_len = 17 + half_bits.div_ceil(8) as usize;
|
||||
let mut input = [0; 25];
|
||||
input[..8].copy_from_slice(&seed.to_le_bytes());
|
||||
input[8..16].copy_from_slice(&(start / GROUP_SIZE).to_le_bytes());
|
||||
|
||||
let mut slot = ordinal - start;
|
||||
loop {
|
||||
let (mut left, mut right) = (slot >> half_bits, slot & half_mask);
|
||||
for round in 0..4 {
|
||||
input[16] = round;
|
||||
input[17..].copy_from_slice(&right.to_le_bytes());
|
||||
let hash = blake3::hash(&input[..input_len]);
|
||||
let mut bytes = [0; 8];
|
||||
bytes.copy_from_slice(&hash.as_bytes()[..8]);
|
||||
let f = u64::from_le_bytes(bytes) & half_mask;
|
||||
(left, right) = (right, left ^ f);
|
||||
}
|
||||
slot = (left << half_bits) | right;
|
||||
// Following the permutation cycle must eventually return to the starting slot.
|
||||
if slot < size {
|
||||
return start + slot;
|
||||
}
|
||||
}
|
||||
}
|
||||
193
akode-rs/utils/model-facing-id/tests/generator.rs
Normal file
193
akode-rs/utils/model-facing-id/tests/generator.rs
Normal file
@@ -0,0 +1,193 @@
|
||||
//! Checks pool boundaries, snapshot restore, and the v1 sequence through the public API.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::error::Error;
|
||||
|
||||
use akode_utils_model_facing_id::ModelFacingId;
|
||||
use akode_utils_model_facing_id::ModelFacingIdGenerator;
|
||||
use akode_utils_model_facing_id::ModelFacingIdGeneratorState;
|
||||
use akode_utils_model_facing_id::RestoreError;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
/// Every three-digit suffix is issued before the first ID drawn from the six-digit pool.
|
||||
#[test]
|
||||
fn exhausts_three_digit_ids_before_opening_the_six_digit_pool() {
|
||||
let mut generator = ModelFacingIdGenerator::new(/*seed*/ 42, "environment");
|
||||
let mut actual = BTreeSet::new();
|
||||
for _ in 0..1_000 {
|
||||
actual.insert(generator.fetch_next().to_string());
|
||||
}
|
||||
let expected: BTreeSet<_> = (0..1_000).map(|id| format!("environment{id:03}")).collect();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(generator.fetch_next().to_string(), "environment825109");
|
||||
}
|
||||
|
||||
/// IDs can have the same display text and still round-trip with distinct salts and values.
|
||||
#[test]
|
||||
fn persisted_ids_keep_the_salt_and_value_separate() -> Result<(), serde_json::Error> {
|
||||
for (salt, value) in [("env123", 0), ("env", 123_000)] {
|
||||
let saved = json!({ "salt": salt, "value": value });
|
||||
let id: ModelFacingId = serde_json::from_value(saved.clone())?;
|
||||
assert_eq!(id.to_string(), "env123000");
|
||||
assert_eq!(serde_json::to_value(id)?, saved);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A saved cursor resumes the uninterrupted sequence both inside and between pools.
|
||||
#[test]
|
||||
fn serialized_snapshots_resume_the_sequence() -> Result<(), Box<dyn Error>> {
|
||||
let derived_seed = 0x9e6e_7c74_2945_897e;
|
||||
for next_ordinal in [437, 1_000, 1_437] {
|
||||
let mut original = ModelFacingIdGenerator::new(u64::MAX, "env2");
|
||||
for _ in 0..next_ordinal {
|
||||
original.fetch_next();
|
||||
}
|
||||
let snapshot = original.snapshot();
|
||||
assert_eq!(
|
||||
ModelFacingIdGeneratorState::new(
|
||||
/*version*/ 1,
|
||||
derived_seed,
|
||||
"env2",
|
||||
next_ordinal
|
||||
),
|
||||
snapshot
|
||||
);
|
||||
let saved = serde_json::to_value(snapshot)?;
|
||||
assert_eq!(
|
||||
saved,
|
||||
json!({"version": 1, "seed": derived_seed, "salt": "env2", "next_ordinal": next_ordinal})
|
||||
);
|
||||
let mut resumed = ModelFacingIdGenerator::restore(serde_json::from_value(saved)?)?;
|
||||
for _ in 0..1_001 {
|
||||
assert_eq!(resumed.fetch_next(), original.fetch_next());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// V1 must keep the initial outputs and repeated cycle walks stable.
|
||||
#[test]
|
||||
fn v1_known_outputs() -> Result<(), Box<dyn Error>> {
|
||||
let seed = 0x1234_5678_9abc_def0;
|
||||
let state = ModelFacingIdGeneratorState::new(
|
||||
/*version*/ 1,
|
||||
seed,
|
||||
"environment",
|
||||
/*next_ordinal*/ 0,
|
||||
);
|
||||
let mut generator = ModelFacingIdGenerator::restore(state)?;
|
||||
for id in ["895", "930", "155", "141", "916", "912", "678", "430"] {
|
||||
assert_eq!(
|
||||
generator.fetch_next().to_string(),
|
||||
format!("environment{id}")
|
||||
);
|
||||
}
|
||||
// Ordinal 1,605 visits two excluded slots before returning to the six-digit pool.
|
||||
let state = ModelFacingIdGeneratorState::new(
|
||||
/*version*/ 1,
|
||||
seed,
|
||||
"environment",
|
||||
/*next_ordinal*/ 1_605,
|
||||
);
|
||||
let mut resumed = ModelFacingIdGenerator::restore(state)?;
|
||||
assert_eq!(resumed.fetch_next().to_string(), "environment765577");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The last ID at each width and the first at the next width stay stable across restores.
|
||||
#[test]
|
||||
fn v1_known_outputs_at_every_pool_boundary() -> Result<(), Box<dyn Error>> {
|
||||
let seed = 0x1234_5678_9abc_def0;
|
||||
for (boundary, last, first) in [
|
||||
(1_000, "553", "661326"),
|
||||
(1_000_000, "753874", "286136338"),
|
||||
(1_000_000_000, "839882170", "813648058018"),
|
||||
(1_000_000_000_000, "634462456979", "134726697070558"),
|
||||
(
|
||||
1_000_000_000_000_000,
|
||||
"326088534089890",
|
||||
"563366069705075074",
|
||||
),
|
||||
(
|
||||
1_000_000_000_000_000_000,
|
||||
"633936232025849076",
|
||||
"012827849051678362461",
|
||||
),
|
||||
] {
|
||||
let state = ModelFacingIdGeneratorState::new(/*version*/ 1, seed, "env", boundary - 1);
|
||||
let mut generator = ModelFacingIdGenerator::restore(state)?;
|
||||
assert_eq!(generator.fetch_next().to_string(), format!("env{last}"));
|
||||
let mut resumed = ModelFacingIdGenerator::restore(generator.snapshot())?;
|
||||
let next = generator.fetch_next();
|
||||
assert_eq!(next.to_string(), format!("env{first}"));
|
||||
assert_eq!(resumed.fetch_next(), next);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The same session seed can drive several ID kinds, each with its own resumable seed.
|
||||
#[test]
|
||||
fn salts_derive_the_seed_stored_in_snapshots() {
|
||||
for (seed, salt, derived_seed) in [
|
||||
(42, "environment", 0xc9b5_d0ac_9722_ea42),
|
||||
(42, "context-window", 0x2747_db8a_6513_485b),
|
||||
(43, "environment", 0x70aa_a9fd_4bf2_6e41),
|
||||
] {
|
||||
assert_eq!(
|
||||
ModelFacingIdGenerator::new(seed, salt).snapshot(),
|
||||
ModelFacingIdGeneratorState::new(
|
||||
/*version*/ 1,
|
||||
derived_seed,
|
||||
salt,
|
||||
/*next_ordinal*/ 0
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The final ordinal belongs to the last decimal pool. Its successor restarts the sequence.
|
||||
#[test]
|
||||
fn wraps_after_the_last_u64_ordinal() -> Result<(), Box<dyn Error>> {
|
||||
let seed = 17;
|
||||
let last = ModelFacingIdGeneratorState::new(/*version*/ 1, seed, "env", u64::MAX);
|
||||
let mut generator = ModelFacingIdGenerator::restore(last)?;
|
||||
let text = generator.fetch_next().to_string();
|
||||
let last_id = text
|
||||
.strip_prefix("env")
|
||||
.expect("restored salt")
|
||||
.parse::<u64>()?;
|
||||
assert!(last_id >= 1_000_000_000_000_000_000);
|
||||
|
||||
let first =
|
||||
ModelFacingIdGeneratorState::new(/*version*/ 1, seed, "env", /*next_ordinal*/ 0);
|
||||
assert_eq!(generator.snapshot(), first);
|
||||
let mut fresh = ModelFacingIdGenerator::restore(first)?;
|
||||
let mut resumed = ModelFacingIdGenerator::restore(generator.snapshot())?;
|
||||
assert_eq!(resumed.fetch_next(), fresh.fetch_next());
|
||||
assert_eq!(resumed.snapshot(), fresh.snapshot());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsupported_snapshot_versions() {
|
||||
let saved = ModelFacingIdGeneratorState::new(
|
||||
/*version*/ 2, /*seed*/ 0, "env", /*next_ordinal*/ 0,
|
||||
);
|
||||
assert_eq!(
|
||||
ModelFacingIdGenerator::restore(saved).unwrap_err(),
|
||||
RestoreError::UnsupportedVersion(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_salts_on_restore() {
|
||||
let state = ModelFacingIdGeneratorState::new(
|
||||
/*version*/ 1, /*seed*/ 42, "", /*next_ordinal*/ 0,
|
||||
);
|
||||
assert_eq!(
|
||||
ModelFacingIdGenerator::restore(state).expect_err("empty salt"),
|
||||
RestoreError::InvalidSalt
|
||||
);
|
||||
}
|
||||
6
akode-rs/utils/oss/BUILD.bazel
Normal file
6
akode-rs/utils/oss/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "oss",
|
||||
crate_name = "akode_utils_oss",
|
||||
)
|
||||
17
akode-rs/utils/oss/Cargo.toml
Normal file
17
akode-rs/utils/oss/Cargo.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "akode-utils-oss"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-core = { workspace = true }
|
||||
akode-lmstudio = { workspace = true }
|
||||
akode-model-provider-info = { workspace = true }
|
||||
akode-ollama = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
62
akode-rs/utils/oss/src/lib.rs
Normal file
62
akode-rs/utils/oss/src/lib.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
//! OSS provider utilities shared between TUI and exec.
|
||||
|
||||
use akode_core::config::Config;
|
||||
use akode_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID;
|
||||
use akode_model_provider_info::OLLAMA_OSS_PROVIDER_ID;
|
||||
|
||||
/// Returns the default model for a given OSS provider.
|
||||
pub fn get_default_model_for_oss_provider(provider_id: &str) -> Option<&'static str> {
|
||||
match provider_id {
|
||||
LMSTUDIO_OSS_PROVIDER_ID => Some(akode_lmstudio::DEFAULT_OSS_MODEL),
|
||||
OLLAMA_OSS_PROVIDER_ID => Some(akode_ollama::DEFAULT_OSS_MODEL),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensures the specified OSS provider is ready (models downloaded, service reachable).
|
||||
pub async fn ensure_oss_provider_ready(
|
||||
provider_id: &str,
|
||||
config: &Config,
|
||||
) -> Result<(), std::io::Error> {
|
||||
match provider_id {
|
||||
LMSTUDIO_OSS_PROVIDER_ID => {
|
||||
akode_lmstudio::ensure_oss_ready(config)
|
||||
.await
|
||||
.map_err(|e| std::io::Error::other(format!("OSS setup failed: {e}")))?;
|
||||
}
|
||||
OLLAMA_OSS_PROVIDER_ID => {
|
||||
let client = akode_ollama::OllamaClient::try_from_oss_provider(config).await?;
|
||||
akode_ollama::ensure_responses_supported(&client).await?;
|
||||
akode_ollama::ensure_oss_ready(config, &client)
|
||||
.await
|
||||
.map_err(|e| std::io::Error::other(format!("OSS setup failed: {e}")))?;
|
||||
}
|
||||
_ => {
|
||||
// Unknown provider, skip setup
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_get_default_model_for_provider_lmstudio() {
|
||||
let result = get_default_model_for_oss_provider(LMSTUDIO_OSS_PROVIDER_ID);
|
||||
assert_eq!(result, Some(akode_lmstudio::DEFAULT_OSS_MODEL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_default_model_for_provider_ollama() {
|
||||
let result = get_default_model_for_oss_provider(OLLAMA_OSS_PROVIDER_ID);
|
||||
assert_eq!(result, Some(akode_ollama::DEFAULT_OSS_MODEL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_default_model_for_provider_unknown() {
|
||||
let result = get_default_model_for_oss_provider("unknown-provider");
|
||||
assert_eq!(result, None);
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/output-truncation/BUILD.bazel
Normal file
6
akode-rs/utils/output-truncation/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "output-truncation",
|
||||
crate_name = "akode_utils_output_truncation",
|
||||
)
|
||||
19
akode-rs/utils/output-truncation/Cargo.toml
Normal file
19
akode-rs/utils/output-truncation/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-utils-output-truncation"
|
||||
version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-protocol = { workspace = true }
|
||||
akode-utils-string = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
417
akode-rs/utils/output-truncation/src/lib.rs
Normal file
417
akode-rs/utils/output-truncation/src/lib.rs
Normal file
@@ -0,0 +1,417 @@
|
||||
//! Shared byte/token truncation for tool and exec output.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use akode_protocol::mcp::CallToolResult;
|
||||
use akode_protocol::models::FunctionCallOutputBody;
|
||||
use akode_protocol::models::FunctionCallOutputContentItem;
|
||||
use akode_protocol::models::FunctionCallOutputPayload;
|
||||
use akode_utils_string::TextTruncation;
|
||||
pub use akode_utils_string::approx_bytes_for_tokens;
|
||||
pub use akode_utils_string::approx_token_count;
|
||||
pub use akode_utils_string::approx_tokens_from_byte_count;
|
||||
use akode_utils_string::plan_token_truncation;
|
||||
use akode_utils_string::truncate_middle_chars;
|
||||
|
||||
pub use akode_protocol::protocol::TruncationPolicy;
|
||||
|
||||
/// Adds the existing 20% allowance for serialization and headers.
|
||||
/// Saved history budgets already include this allowance.
|
||||
pub fn with_serialization_allowance(policy: TruncationPolicy) -> TruncationPolicy {
|
||||
policy * 1.2
|
||||
}
|
||||
|
||||
pub fn formatted_truncate_text(content: &str, policy: TruncationPolicy) -> String {
|
||||
if content.len() <= policy.byte_budget() {
|
||||
return content.to_string();
|
||||
}
|
||||
|
||||
format_truncated_text(content, policy, &mut [])
|
||||
}
|
||||
|
||||
fn format_truncated_text(
|
||||
content: &str,
|
||||
policy: TruncationPolicy,
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) -> String {
|
||||
let original_token_count = approx_token_count(content);
|
||||
let total_lines = content.lines().count();
|
||||
let header = format!(
|
||||
"Warning: truncated output (original token count: {original_token_count})\nTotal output lines: {total_lines}\n\n"
|
||||
);
|
||||
let (snippet, edit) = truncate_text_with_plan(content, policy);
|
||||
if let Some(edit) = edit {
|
||||
for boundary in boundaries {
|
||||
boundary.text_offset = rendered_offset(&edit, boundary.text_offset, header.len());
|
||||
}
|
||||
}
|
||||
header + &snippet
|
||||
}
|
||||
|
||||
pub fn truncate_text(content: &str, policy: TruncationPolicy) -> String {
|
||||
truncate_text_with_plan(content, policy).0
|
||||
}
|
||||
|
||||
// Only token-budget callers supply boundaries that need remapping.
|
||||
fn truncate_text_with_plan(
|
||||
content: &str,
|
||||
policy: TruncationPolicy,
|
||||
) -> (String, Option<TextTruncation>) {
|
||||
match policy {
|
||||
TruncationPolicy::Bytes(bytes) => (truncate_middle_chars(content, bytes), None),
|
||||
TruncationPolicy::Tokens(tokens) => match plan_token_truncation(content, tokens) {
|
||||
Some(edit) => (edit.apply(content), Some(edit)),
|
||||
None => (content.to_owned(), None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces an oversized serialized MCP result with a bounded text preview while preserving its
|
||||
/// error status and supported bounded metadata.
|
||||
pub fn truncate_mcp_tool_result(
|
||||
result: &CallToolResult,
|
||||
max_bytes: usize,
|
||||
) -> Cow<'_, CallToolResult> {
|
||||
let Ok(serialized) = serde_json::to_string(result) else {
|
||||
return Cow::Borrowed(result);
|
||||
};
|
||||
if serialized.len() <= max_bytes {
|
||||
return Cow::Borrowed(result);
|
||||
}
|
||||
|
||||
let meta = None;
|
||||
|
||||
let mut preview_budget = max_bytes;
|
||||
loop {
|
||||
let preview = if preview_budget == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
truncate_text(&serialized, TruncationPolicy::Bytes(preview_budget))
|
||||
};
|
||||
let truncated = CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "text",
|
||||
"text": preview,
|
||||
})],
|
||||
structured_content: None,
|
||||
is_error: result.is_error,
|
||||
meta: meta.clone(),
|
||||
};
|
||||
let Ok(truncated_serialized) = serde_json::to_string(&truncated) else {
|
||||
return Cow::Borrowed(result);
|
||||
};
|
||||
let truncated_len = truncated_serialized.len();
|
||||
if truncated_len <= max_bytes || preview_budget == 0 {
|
||||
return Cow::Owned(truncated);
|
||||
}
|
||||
|
||||
// The preview is serialized as a JSON string, so escaping can make it exceed its raw byte
|
||||
// budget. Scale the next budget by the observed size of the complete replacement.
|
||||
preview_budget = (preview_budget.saturating_mul(max_bytes) / truncated_len)
|
||||
.min(preview_budget.saturating_sub(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the existing byte/token budget without changing success metadata or media ordering.
|
||||
pub fn truncate_function_output_payload(
|
||||
output: &mut FunctionCallOutputPayload,
|
||||
policy: TruncationPolicy,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
) {
|
||||
match &mut output.body {
|
||||
FunctionCallOutputBody::Text(text) => *text = truncate_text(text, policy),
|
||||
FunctionCallOutputBody::ContentItems(items) => {
|
||||
*items = truncate_function_output_items_with_policy(
|
||||
items,
|
||||
policy,
|
||||
estimate_audio_token_count,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An uncharged boundary in the original logical output. Token-boundary
|
||||
/// formatters update the item index and UTF-8 text offset to the rendered
|
||||
/// position, including when content at that position was omitted.
|
||||
///
|
||||
/// At entry, item indices are clamped to the end of the input, text offsets
|
||||
/// round down to an in-bounds UTF-8 boundary, and offsets on non-text items
|
||||
/// are zeroed. Positions preceding an earlier boundary move to that position,
|
||||
/// preserving caller order. On return, boundaries refer to the rendered items;
|
||||
/// an end boundary precedes any generated omission notices.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct OutputBoundary {
|
||||
pub item_index: usize,
|
||||
pub text_offset: usize,
|
||||
}
|
||||
|
||||
/// Format text-only output as a whole observation, including the truncation
|
||||
/// warning. Charge mixed text and audio against the budget in order while
|
||||
/// preserving images.
|
||||
pub fn formatted_truncate_function_output_items_with_policy<'a>(
|
||||
items: impl Into<Cow<'a, [FunctionCallOutputContentItem]>>,
|
||||
policy: TruncationPolicy,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
formatted_output(items.into(), policy, estimate_audio_token_count, &mut [])
|
||||
}
|
||||
|
||||
/// As above, with zero-width boundaries for callers that have already dropped
|
||||
/// output. Input positions are normalized as documented on [`OutputBoundary`].
|
||||
pub fn formatted_output_at_token_boundaries<'a>(
|
||||
items: impl Into<Cow<'a, [FunctionCallOutputContentItem]>>,
|
||||
max_tokens: usize,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
let items = items.into();
|
||||
normalize_boundaries(&items, boundaries);
|
||||
formatted_output(
|
||||
items,
|
||||
TruncationPolicy::Tokens(max_tokens),
|
||||
estimate_audio_token_count,
|
||||
boundaries,
|
||||
)
|
||||
}
|
||||
|
||||
fn formatted_output(
|
||||
items: Cow<'_, [FunctionCallOutputContentItem]>,
|
||||
policy: TruncationPolicy,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
let mut combined_len = 0;
|
||||
for item in items.iter() {
|
||||
let FunctionCallOutputContentItem::InputText { text } = item else {
|
||||
return truncate_output_items(items, policy, estimate_audio_token_count, boundaries);
|
||||
};
|
||||
combined_len += usize::from(combined_len != 0) + text.len();
|
||||
}
|
||||
if combined_len <= policy.byte_budget() {
|
||||
return items.into_owned();
|
||||
}
|
||||
|
||||
let mut combined = String::with_capacity(combined_len);
|
||||
let mut next_boundary = 0;
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
if let FunctionCallOutputContentItem::InputText { text } = item {
|
||||
if !combined.is_empty() {
|
||||
combined.push('\n');
|
||||
}
|
||||
while let Some(boundary) = boundaries.get_mut(next_boundary)
|
||||
&& boundary.item_index == index
|
||||
{
|
||||
boundary.item_index = 0;
|
||||
boundary.text_offset += combined.len();
|
||||
next_boundary += 1;
|
||||
}
|
||||
combined.push_str(text);
|
||||
}
|
||||
}
|
||||
// A boundary after the last item belongs at the end of the merged text.
|
||||
for boundary in &mut boundaries[next_boundary..] {
|
||||
boundary.item_index = 0;
|
||||
boundary.text_offset = combined.len();
|
||||
}
|
||||
vec![FunctionCallOutputContentItem::InputText {
|
||||
text: format_truncated_text(&combined, policy, boundaries),
|
||||
}]
|
||||
}
|
||||
|
||||
pub fn truncate_function_output_items_with_policy(
|
||||
items: &[FunctionCallOutputContentItem],
|
||||
policy: TruncationPolicy,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
truncate_output_items(
|
||||
Cow::Borrowed(items),
|
||||
policy,
|
||||
estimate_audio_token_count,
|
||||
&mut [],
|
||||
)
|
||||
}
|
||||
|
||||
/// Budget in input order even if a caller previously dropped every media item.
|
||||
/// Input positions are normalized as documented on [`OutputBoundary`].
|
||||
pub fn mixed_output_at_token_boundaries<'a>(
|
||||
items: impl Into<Cow<'a, [FunctionCallOutputContentItem]>>,
|
||||
max_tokens: usize,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
let items = items.into();
|
||||
normalize_boundaries(&items, boundaries);
|
||||
truncate_output_items(
|
||||
items,
|
||||
TruncationPolicy::Tokens(max_tokens),
|
||||
estimate_audio_token_count,
|
||||
boundaries,
|
||||
)
|
||||
}
|
||||
|
||||
fn normalize_boundaries(
|
||||
items: &[FunctionCallOutputContentItem],
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) {
|
||||
let mut previous = (0, 0);
|
||||
for boundary in boundaries {
|
||||
let item_index = boundary.item_index.min(items.len());
|
||||
let text_offset = match items.get(item_index) {
|
||||
Some(FunctionCallOutputContentItem::InputText { text }) => {
|
||||
text.floor_char_boundary(boundary.text_offset.min(text.len()))
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
previous = previous.max((item_index, text_offset));
|
||||
(boundary.item_index, boundary.text_offset) = previous;
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_output_items(
|
||||
items: Cow<'_, [FunctionCallOutputContentItem]>,
|
||||
policy: TruncationPolicy,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
match items {
|
||||
Cow::Borrowed(items) => truncate_output_iter(
|
||||
items.iter().map(Cow::Borrowed),
|
||||
policy,
|
||||
estimate_audio_token_count,
|
||||
boundaries,
|
||||
),
|
||||
Cow::Owned(items) => truncate_output_iter(
|
||||
items.into_iter().map(Cow::Owned),
|
||||
policy,
|
||||
estimate_audio_token_count,
|
||||
boundaries,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_output_iter<'a>(
|
||||
items: impl ExactSizeIterator<Item = Cow<'a, FunctionCallOutputContentItem>>,
|
||||
policy: TruncationPolicy,
|
||||
estimate_audio_token_count: impl Fn(&str) -> usize,
|
||||
boundaries: &mut [OutputBoundary],
|
||||
) -> Vec<FunctionCallOutputContentItem> {
|
||||
let mut out: Vec<FunctionCallOutputContentItem> = Vec::with_capacity(items.len());
|
||||
let mut remaining_budget = match policy {
|
||||
TruncationPolicy::Bytes(_) => policy.byte_budget(),
|
||||
TruncationPolicy::Tokens(_) => policy.token_budget(),
|
||||
};
|
||||
let mut omitted_text_items = 0usize;
|
||||
let mut omitted_audio_items = 0usize;
|
||||
let mut next_boundary = 0;
|
||||
|
||||
for (index, item) in items.enumerate() {
|
||||
let item_out = out.len();
|
||||
let item_policy = match policy {
|
||||
TruncationPolicy::Bytes(_) => TruncationPolicy::Bytes(remaining_budget),
|
||||
TruncationPolicy::Tokens(_) => TruncationPolicy::Tokens(remaining_budget),
|
||||
};
|
||||
let mut text_edit = None;
|
||||
let keep = match item.as_ref() {
|
||||
// Empty text contributes no model content but still consumes an API array slot.
|
||||
FunctionCallOutputContentItem::InputText { text } if text.is_empty() => false,
|
||||
FunctionCallOutputContentItem::InputText { .. } if remaining_budget == 0 => {
|
||||
omitted_text_items += 1;
|
||||
false
|
||||
}
|
||||
FunctionCallOutputContentItem::InputText { text } => {
|
||||
let cost = match policy {
|
||||
TruncationPolicy::Bytes(_) => text.len(),
|
||||
TruncationPolicy::Tokens(_) => approx_token_count(text),
|
||||
};
|
||||
if cost <= remaining_budget {
|
||||
remaining_budget = remaining_budget.saturating_sub(cost);
|
||||
true
|
||||
} else {
|
||||
let (snippet, edit) = truncate_text_with_plan(text, item_policy);
|
||||
text_edit = edit;
|
||||
if snippet.is_empty() {
|
||||
omitted_text_items += 1;
|
||||
} else {
|
||||
out.push(FunctionCallOutputContentItem::InputText { text: snippet });
|
||||
}
|
||||
remaining_budget = 0;
|
||||
false
|
||||
}
|
||||
}
|
||||
FunctionCallOutputContentItem::InputImage { .. }
|
||||
| FunctionCallOutputContentItem::EncryptedContent { .. } => true,
|
||||
FunctionCallOutputContentItem::InputAudio { audio_url } => {
|
||||
let token_cost = estimate_audio_token_count(audio_url);
|
||||
let cost = match policy {
|
||||
TruncationPolicy::Bytes(_) => approx_bytes_for_tokens(token_cost),
|
||||
TruncationPolicy::Tokens(_) => token_cost,
|
||||
};
|
||||
if cost <= remaining_budget {
|
||||
remaining_budget = remaining_budget.saturating_sub(cost);
|
||||
true
|
||||
} else {
|
||||
omitted_audio_items += 1;
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
while let Some(boundary) = boundaries.get_mut(next_boundary)
|
||||
&& boundary.item_index == index
|
||||
{
|
||||
boundary.item_index = item_out;
|
||||
if let Some(edit) = &text_edit {
|
||||
boundary.text_offset =
|
||||
rendered_offset(edit, boundary.text_offset, /*header_bytes*/ 0);
|
||||
} else if !keep {
|
||||
boundary.text_offset = 0;
|
||||
}
|
||||
next_boundary += 1;
|
||||
}
|
||||
if keep {
|
||||
out.push(item.into_owned());
|
||||
}
|
||||
}
|
||||
// End boundaries precede generated omission counts: counts are not original
|
||||
// content and must never move a collector notice away from its source.
|
||||
for boundary in &mut boundaries[next_boundary..] {
|
||||
boundary.item_index = out.len();
|
||||
boundary.text_offset = 0;
|
||||
}
|
||||
|
||||
if omitted_text_items > 0 {
|
||||
out.push(FunctionCallOutputContentItem::InputText {
|
||||
text: format!("[omitted {omitted_text_items} text items ...]"),
|
||||
});
|
||||
}
|
||||
if omitted_audio_items > 0 {
|
||||
out.push(FunctionCallOutputContentItem::InputText {
|
||||
text: format!("[omitted {omitted_audio_items} audio items ...]"),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn rendered_offset(edit: &TextTruncation, boundary: usize, header_bytes: usize) -> usize {
|
||||
if boundary == 0 {
|
||||
0
|
||||
} else if boundary <= edit.removed.start {
|
||||
header_bytes + boundary
|
||||
} else {
|
||||
header_bytes
|
||||
+ edit.removed.start
|
||||
+ edit.marker.len()
|
||||
+ boundary.saturating_sub(edit.removed.end)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn approx_tokens_from_byte_count_i64(bytes: i64) -> i64 {
|
||||
if bytes <= 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let bytes = usize::try_from(bytes).unwrap_or(usize::MAX);
|
||||
i64::try_from(approx_tokens_from_byte_count(bytes)).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod truncate_tests;
|
||||
564
akode-rs/utils/output-truncation/src/truncate_tests.rs
Normal file
564
akode-rs/utils/output-truncation/src/truncate_tests.rs
Normal file
@@ -0,0 +1,564 @@
|
||||
use crate::OutputBoundary;
|
||||
use crate::TruncationPolicy;
|
||||
use crate::approx_token_count;
|
||||
use crate::approx_tokens_from_byte_count_i64;
|
||||
use crate::formatted_output_at_token_boundaries;
|
||||
use crate::formatted_truncate_function_output_items_with_policy;
|
||||
use crate::formatted_truncate_text;
|
||||
use crate::mixed_output_at_token_boundaries;
|
||||
use crate::truncate_function_output_items_with_policy;
|
||||
use crate::truncate_mcp_tool_result;
|
||||
use crate::truncate_text;
|
||||
use akode_protocol::mcp::CallToolResult;
|
||||
use akode_protocol::models::DEFAULT_IMAGE_DETAIL;
|
||||
use akode_protocol::models::FunctionCallOutputContentItem;
|
||||
use akode_protocol::models::ImageReference;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn truncate_mcp_tool_result_borrows_small_result() {
|
||||
let result = CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "text",
|
||||
"text": "hello",
|
||||
})],
|
||||
structured_content: Some(serde_json::json!({"x": 1})),
|
||||
is_error: Some(false),
|
||||
meta: Some(serde_json::json!({"k": "v"})),
|
||||
};
|
||||
|
||||
let truncated = truncate_mcp_tool_result(&result, /*max_bytes*/ 1024);
|
||||
|
||||
assert!(matches!(truncated, std::borrow::Cow::Borrowed(_)));
|
||||
assert_eq!(truncated.as_ref(), &result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_mcp_tool_result_compacts_large_result() {
|
||||
let max_bytes = 1024;
|
||||
let result = CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "text",
|
||||
"text": format!("head\n{}\ntail", "\"\\\n".repeat(5_000)),
|
||||
})],
|
||||
structured_content: Some(serde_json::json!({"x": "y".repeat(5_000)})),
|
||||
is_error: Some(true),
|
||||
meta: Some(serde_json::json!({
|
||||
"private": format!("meta-head{}meta-tail", "z".repeat(5_000)),
|
||||
})),
|
||||
};
|
||||
|
||||
let truncated = truncate_mcp_tool_result(&result, max_bytes).into_owned();
|
||||
|
||||
let preview = truncated.content[0]["text"]
|
||||
.as_str()
|
||||
.expect("truncated result should contain a text preview");
|
||||
assert_eq!(
|
||||
truncated,
|
||||
CallToolResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "text",
|
||||
"text": preview,
|
||||
})],
|
||||
structured_content: None,
|
||||
is_error: Some(true),
|
||||
meta: None,
|
||||
}
|
||||
);
|
||||
assert!(serde_json::to_string(&truncated).unwrap().len() <= max_bytes);
|
||||
assert!(preview.contains("head"));
|
||||
assert!(preview.contains("chars truncated"));
|
||||
assert!(preview.contains("meta-tail"));
|
||||
|
||||
let truncated_again = truncate_mcp_tool_result(&truncated, max_bytes);
|
||||
assert!(matches!(truncated_again, std::borrow::Cow::Borrowed(_)));
|
||||
assert_eq!(truncated_again.as_ref(), &truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_bytes_less_than_placeholder_returns_placeholder() {
|
||||
let content = "example output";
|
||||
|
||||
assert_eq!(
|
||||
"Warning: truncated output (original token count: 4)\nTotal output lines: 1\n\n…13 chars truncated…t",
|
||||
formatted_truncate_text(content, TruncationPolicy::Bytes(1)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_tokens_less_than_placeholder_returns_placeholder() {
|
||||
let content = "example output";
|
||||
|
||||
assert_eq!(
|
||||
"Warning: truncated output (original token count: 4)\nTotal output lines: 1\n\nex…3 tokens truncated…ut",
|
||||
formatted_truncate_text(content, TruncationPolicy::Tokens(1)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_tokens_under_limit_returns_original() {
|
||||
let content = "example output";
|
||||
|
||||
assert_eq!(
|
||||
content,
|
||||
formatted_truncate_text(content, TruncationPolicy::Tokens(10)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_bytes_under_limit_returns_original() {
|
||||
let content = "example output";
|
||||
|
||||
assert_eq!(
|
||||
content,
|
||||
formatted_truncate_text(content, TruncationPolicy::Bytes(20)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_tokens_over_limit_returns_truncated() {
|
||||
let content = "this is an example of a long output that should be truncated";
|
||||
|
||||
assert_eq!(
|
||||
"Warning: truncated output (original token count: 15)\nTotal output lines: 1\n\nthis is an…10 tokens truncated… truncated",
|
||||
formatted_truncate_text(content, TruncationPolicy::Tokens(5)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_bytes_over_limit_returns_truncated() {
|
||||
let content = "this is an example of a long output that should be truncated";
|
||||
|
||||
assert_eq!(
|
||||
"Warning: truncated output (original token count: 15)\nTotal output lines: 1\n\nthis is an exam…30 chars truncated…ld be truncated",
|
||||
formatted_truncate_text(content, TruncationPolicy::Bytes(30)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_bytes_reports_original_line_count_when_truncated() {
|
||||
let content =
|
||||
"this is an example of a long output that should be truncated\nalso some other line";
|
||||
|
||||
assert_eq!(
|
||||
"Warning: truncated output (original token count: 21)\nTotal output lines: 2\n\nthis is an exam…51 chars truncated…some other line",
|
||||
formatted_truncate_text(content, TruncationPolicy::Bytes(30)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_tokens_reports_original_line_count_when_truncated() {
|
||||
let content =
|
||||
"this is an example of a long output that should be truncated\nalso some other line";
|
||||
|
||||
assert_eq!(
|
||||
"Warning: truncated output (original token count: 21)\nTotal output lines: 2\n\nthis is an example o…11 tokens truncated…also some other line",
|
||||
formatted_truncate_text(content, TruncationPolicy::Tokens(10)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_bytes_handles_utf8_content() {
|
||||
let s = "😀😀😀😀😀😀😀😀😀😀\nsecond line with text\n";
|
||||
let out = truncate_text(s, TruncationPolicy::Bytes(20));
|
||||
assert_eq!(out, "😀😀…21 chars truncated…with text\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncates_across_multiple_under_limit_texts_and_reports_omitted() {
|
||||
let chunk = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega.\n";
|
||||
let chunk_tokens = approx_token_count(chunk);
|
||||
assert!(chunk_tokens > 0, "chunk must consume tokens");
|
||||
let limit = chunk_tokens * 3;
|
||||
let t1 = chunk.to_string();
|
||||
let t2 = chunk.to_string();
|
||||
let t3 = chunk.repeat(10);
|
||||
let t4 = chunk.to_string();
|
||||
let t5 = chunk.to_string();
|
||||
|
||||
let items = vec![
|
||||
FunctionCallOutputContentItem::InputText { text: t1.clone() },
|
||||
FunctionCallOutputContentItem::InputText { text: t2.clone() },
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "img:mid".to_string(),
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputText { text: t3 },
|
||||
FunctionCallOutputContentItem::InputText { text: t4 },
|
||||
FunctionCallOutputContentItem::InputText { text: t5 },
|
||||
];
|
||||
|
||||
let output =
|
||||
truncate_function_output_items_with_policy(&items, TruncationPolicy::Tokens(limit), |_| 0);
|
||||
|
||||
assert_eq!(output.len(), 5);
|
||||
|
||||
let first_text = match &output[0] {
|
||||
FunctionCallOutputContentItem::InputText { text } => text,
|
||||
other => panic!("unexpected first item: {other:?}"),
|
||||
};
|
||||
assert_eq!(first_text, &t1);
|
||||
|
||||
let second_text = match &output[1] {
|
||||
FunctionCallOutputContentItem::InputText { text } => text,
|
||||
other => panic!("unexpected second item: {other:?}"),
|
||||
};
|
||||
assert_eq!(second_text, &t2);
|
||||
|
||||
assert_eq!(
|
||||
output[2],
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "img:mid".to_string()
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}
|
||||
);
|
||||
|
||||
let fourth_text = match &output[3] {
|
||||
FunctionCallOutputContentItem::InputText { text } => text,
|
||||
other => panic!("unexpected fourth item: {other:?}"),
|
||||
};
|
||||
assert!(
|
||||
fourth_text.contains("tokens truncated"),
|
||||
"expected marker in truncated snippet: {fourth_text}"
|
||||
);
|
||||
|
||||
let summary_text = match &output[4] {
|
||||
FunctionCallOutputContentItem::InputText { text } => text,
|
||||
other => panic!("unexpected summary item: {other:?}"),
|
||||
};
|
||||
assert!(summary_text.contains("omitted 2 text items"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_function_output_items_with_policy_discards_empty_text() {
|
||||
let mut items = vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: String::new(),
|
||||
};
|
||||
16_384
|
||||
];
|
||||
for policy in [TruncationPolicy::Bytes(0), TruncationPolicy::Tokens(1)] {
|
||||
assert_eq!(
|
||||
truncate_function_output_items_with_policy(&items, policy, |_| 0),
|
||||
Vec::new()
|
||||
);
|
||||
}
|
||||
|
||||
let content = vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "caption".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "img:one".to_string(),
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_123".to_string(),
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "audio:one".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_opaque".to_string(),
|
||||
},
|
||||
];
|
||||
items.extend(content.clone());
|
||||
for policy in [TruncationPolicy::Bytes(16), TruncationPolicy::Tokens(4)] {
|
||||
assert_eq!(
|
||||
truncate_function_output_items_with_policy(&items, policy, |_| 1),
|
||||
content
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_text_output_reuses_owned_items_under_limit() {
|
||||
let items = vec![text("alpha"), text(""), text("beta")];
|
||||
let policy = TruncationPolicy::Bytes(32);
|
||||
|
||||
let borrowed = formatted_truncate_function_output_items_with_policy(&items, policy, |_| 0);
|
||||
assert_eq!(borrowed, items);
|
||||
|
||||
let allocation = items.as_ptr();
|
||||
let owned = formatted_truncate_function_output_items_with_policy(items, policy, |_| 0);
|
||||
assert_eq!(owned, borrowed);
|
||||
assert_eq!(owned.as_ptr(), allocation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_text_output_preserves_empty_leading_text_behavior() {
|
||||
let items = vec![text(""), text("abc")];
|
||||
|
||||
let output = formatted_truncate_function_output_items_with_policy(
|
||||
items,
|
||||
TruncationPolicy::Bytes(0),
|
||||
|_| 0,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
output,
|
||||
vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "Warning: truncated output (original token count: 1)\nTotal output lines: 1\n\n…3 chars truncated…".to_string(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_mixed_output_budgets_text_and_audio_in_order() {
|
||||
let audio = FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "audio:one".to_owned(),
|
||||
};
|
||||
let file_image = FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_123".to_owned(),
|
||||
},
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
};
|
||||
let items = vec![
|
||||
text("abcd"),
|
||||
inline_image("img:one".to_owned()),
|
||||
text("efgh"),
|
||||
audio.clone(),
|
||||
file_image.clone(),
|
||||
text("ijkl"),
|
||||
inline_image("img:two".to_owned()),
|
||||
];
|
||||
|
||||
let output = formatted_truncate_function_output_items_with_policy(
|
||||
items,
|
||||
TruncationPolicy::Bytes(12),
|
||||
|_| 1,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
output,
|
||||
vec![
|
||||
text("abcd"),
|
||||
inline_image("img:one".to_owned()),
|
||||
text("efgh"),
|
||||
audio,
|
||||
file_image,
|
||||
inline_image("img:two".to_owned()),
|
||||
text("[omitted 1 text items ...]"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_mixed_output_preserves_encrypted_content() {
|
||||
let encrypted = FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_opaque".to_owned(),
|
||||
};
|
||||
let items = vec![text("abcdefgh"), encrypted.clone()];
|
||||
|
||||
let output = formatted_truncate_function_output_items_with_policy(
|
||||
items,
|
||||
TruncationPolicy::Bytes(2),
|
||||
|_| 0,
|
||||
);
|
||||
|
||||
assert_eq!(output, vec![text("a…6 chars truncated…h"), encrypted]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_function_output_items_with_policy_omits_audio_over_budget() {
|
||||
let items = vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "abcdefgh".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_opaque".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "audio:one".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let output =
|
||||
truncate_function_output_items_with_policy(&items, TruncationPolicy::Bytes(2), |_| 1);
|
||||
|
||||
assert_eq!(
|
||||
output,
|
||||
vec![
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "a…6 chars truncated…h".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content: "enc_opaque".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "[omitted 1 audio items ...]".to_string(),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_function_output_items_with_policy_charges_audio_against_byte_budget() {
|
||||
let audio = FunctionCallOutputContentItem::InputAudio {
|
||||
audio_url: "audio:one".to_string(),
|
||||
};
|
||||
let items = vec![
|
||||
audio.clone(),
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "abcdefgh".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let output =
|
||||
truncate_function_output_items_with_policy(&items, TruncationPolicy::Bytes(5), |_| 1);
|
||||
|
||||
assert_eq!(
|
||||
output,
|
||||
vec![
|
||||
audio,
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: truncate_text("abcdefgh", TruncationPolicy::Bytes(1)),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatted_text_output_merges_all_text_for_token_budget() {
|
||||
let items = vec![text("abcdefgh"), text("ijklmnop")];
|
||||
|
||||
let output = formatted_truncate_function_output_items_with_policy(
|
||||
items,
|
||||
TruncationPolicy::Tokens(2),
|
||||
|_| 0,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
output,
|
||||
vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "Warning: truncated output (original token count: 5)\nTotal output lines: 2\n\nabcd…3 tokens truncated…mnop".to_string(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_count_conversion_clamps_non_positive_values() {
|
||||
assert_eq!(approx_tokens_from_byte_count_i64(/*bytes*/ -1), 0);
|
||||
assert_eq!(approx_tokens_from_byte_count_i64(/*bytes*/ 0), 0);
|
||||
assert_eq!(approx_tokens_from_byte_count_i64(/*bytes*/ 5), 2);
|
||||
}
|
||||
|
||||
fn boundaries<const N: usize>(positions: [(usize, usize); N]) -> [OutputBoundary; N] {
|
||||
positions.map(|(item_index, text_offset)| OutputBoundary {
|
||||
item_index,
|
||||
text_offset,
|
||||
})
|
||||
}
|
||||
|
||||
fn positions<const N: usize>(boundaries: [OutputBoundary; N]) -> [(usize, usize); N] {
|
||||
boundaries.map(|b| (b.item_index, b.text_offset))
|
||||
}
|
||||
|
||||
fn text(s: &str) -> FunctionCallOutputContentItem {
|
||||
FunctionCallOutputContentItem::InputText { text: s.to_owned() }
|
||||
}
|
||||
|
||||
fn inline_image(image_url: String) -> FunctionCallOutputContentItem {
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundary_formatters_normalize_input_and_remap_truncated_text() {
|
||||
let audio_cost: fn(&str) -> usize = |_| 1;
|
||||
let items = [text("left-head"), text("right-tail")];
|
||||
let max_tokens = 2;
|
||||
let mut boundary = boundaries([(0, 0), (0, 2), (1, 0), (1, 8), (2, 0)]);
|
||||
let output =
|
||||
formatted_output_at_token_boundaries(&items, max_tokens, audio_cost, &mut boundary);
|
||||
let [FunctionCallOutputContentItem::InputText { text: rendered }] = output.as_slice() else {
|
||||
panic!("expected one merged text item")
|
||||
};
|
||||
let head = rendered.find("left").expect("expected retained prefix");
|
||||
let tail = rendered
|
||||
.strip_suffix("tail")
|
||||
.expect("expected retained suffix")
|
||||
.len();
|
||||
assert_eq!(
|
||||
positions(boundary),
|
||||
[
|
||||
(0, 0),
|
||||
(0, head + 2),
|
||||
(0, tail),
|
||||
(0, tail + 2),
|
||||
(0, rendered.len())
|
||||
]
|
||||
);
|
||||
|
||||
for (middle, middle_end) in [(text("after"), 5), (inline_image("img:one".to_owned()), 0)] {
|
||||
let items = [text("🙂é boundary"), middle, text("last")];
|
||||
for formatter in [
|
||||
formatted_output_at_token_boundaries,
|
||||
mixed_output_at_token_boundaries,
|
||||
] {
|
||||
for tokens in [0, 1, 2, 256] {
|
||||
let mut b = boundaries([(0, 1), (1, usize::MAX), (0, 8), (usize::MAX, usize::MAX)]);
|
||||
let output = formatter(&items, tokens, audio_cost, &mut b);
|
||||
assert_eq!(output, formatter(&items, tokens, audio_cost, &mut []));
|
||||
let result = positions(b);
|
||||
assert!(result.is_sorted());
|
||||
assert!(
|
||||
result
|
||||
.iter()
|
||||
.all(|&(index, offset)| match output.get(index) {
|
||||
Some(FunctionCallOutputContentItem::InputText { text }) =>
|
||||
text.is_char_boundary(offset),
|
||||
_ => index <= output.len() && offset == 0,
|
||||
})
|
||||
);
|
||||
if tokens == 256 {
|
||||
assert_eq!(result, [(0, 0), (1, middle_end), (1, middle_end), (3, 0)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_mixed_output_moves_a_preserved_image_across_text_truncation() {
|
||||
let image_url = "data:image/png;base64,".to_owned() + &"a".repeat(4096);
|
||||
let url_ptr = image_url.as_ptr();
|
||||
let items = vec![
|
||||
text("long prefix"),
|
||||
inline_image(image_url),
|
||||
text("omitted"),
|
||||
];
|
||||
let mut borrowed = boundaries([(0, 5), (2, 3)]);
|
||||
let mut owned = boundaries([(0, 5), (2, 3)]);
|
||||
let max_tokens = 1;
|
||||
let expected = formatted_output_at_token_boundaries(&items, max_tokens, |_| 0, &mut borrowed);
|
||||
let actual = formatted_output_at_token_boundaries(items, max_tokens, |_| 0, &mut owned);
|
||||
assert_eq!(actual, expected);
|
||||
let projected = positions(owned);
|
||||
assert_eq!(projected, positions(borrowed));
|
||||
let [(index, offset), omitted] = projected;
|
||||
let FunctionCallOutputContentItem::InputText { text: snippet } = &actual[index] else {
|
||||
panic!("expected boundary inside truncated text");
|
||||
};
|
||||
assert_eq!((index, &snippet[offset..], omitted), (0, "ix", (2, 0)));
|
||||
let FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
..
|
||||
} = &actual[1]
|
||||
else {
|
||||
panic!("expected preserved image")
|
||||
};
|
||||
assert_eq!(image_url.as_ptr(), url_ptr);
|
||||
}
|
||||
6
akode-rs/utils/path-uri/BUILD.bazel
Normal file
6
akode-rs/utils/path-uri/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "path-uri",
|
||||
crate_name = "akode_utils_path_uri",
|
||||
)
|
||||
25
akode-rs/utils/path-uri/Cargo.toml
Normal file
25
akode-rs/utils/path-uri/Cargo.toml
Normal file
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "akode-utils-path-uri"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
thiserror = { workspace = true }
|
||||
ts-rs = { workspace = true, features = ["no-serde-warnings"] }
|
||||
url = { workspace = true }
|
||||
urlencoding = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
46
akode-rs/utils/path-uri/src/absolute_path_normalization.rs
Normal file
46
akode-rs/utils/path-uri/src/absolute_path_normalization.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use url::Url;
|
||||
|
||||
pub(super) fn path_uri_from_segments<'a>(
|
||||
convention: PathConvention,
|
||||
host: Option<&str>,
|
||||
segments: impl Iterator<Item = &'a str>,
|
||||
) -> Option<PathUri> {
|
||||
let mut url = Url::parse("file:///").ok()?;
|
||||
if let Some(host) = host {
|
||||
url.set_host(Some(host)).ok()?;
|
||||
}
|
||||
let anchor_depth = usize::from(convention == PathConvention::Windows);
|
||||
let mut depth = 0;
|
||||
let mut normalized_segments = Vec::new();
|
||||
let mut has_trailing_separator = false;
|
||||
for segment in segments {
|
||||
match segment {
|
||||
"" => has_trailing_separator = true,
|
||||
"." => has_trailing_separator = false,
|
||||
".." => {
|
||||
has_trailing_separator = false;
|
||||
if depth > anchor_depth {
|
||||
normalized_segments.pop();
|
||||
depth -= 1;
|
||||
}
|
||||
}
|
||||
segment => {
|
||||
normalized_segments.push(segment);
|
||||
depth += 1;
|
||||
has_trailing_separator = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_trailing_separator
|
||||
|| (convention == PathConvention::Windows && host.is_none() && depth == anchor_depth)
|
||||
{
|
||||
normalized_segments.push("");
|
||||
}
|
||||
{
|
||||
let mut url_segments = url.path_segments_mut().ok()?;
|
||||
url_segments.clear().extend(normalized_segments);
|
||||
}
|
||||
PathUri::try_from(url).ok()
|
||||
}
|
||||
444
akode-rs/utils/path-uri/src/api_path_string.rs
Normal file
444
akode-rs/utils/path-uri/src/api_path_string.rs
Normal file
@@ -0,0 +1,444 @@
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use crate::PathUriParseError;
|
||||
use crate::is_windows_separator_byte;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde::Serializer;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use thiserror::Error;
|
||||
use ts_rs::TS;
|
||||
|
||||
/// A UTF-8 path for preserving raw path compatibility at the app-server API
|
||||
/// boundary while Codex migrates to [`PathUri`].
|
||||
///
|
||||
/// Supports storing arbitrary strings read from the API and converting to and
|
||||
/// from [`PathUri`] using an explicitly selected native path convention.
|
||||
///
|
||||
/// When converting from [`PathUri`], "native" refers to the supplied
|
||||
/// [`PathConvention`], which may be foreign to the operating system running
|
||||
/// this process. The inner string is private so path-producing code must use a
|
||||
/// path conversion method instead of bypassing the intended conversion
|
||||
/// boundary. Non-UTF-8 paths are converted to UTF-8 lossily because this API
|
||||
/// value is serialized as a JSON string.
|
||||
///
|
||||
/// Deserialization and [`Self::from_string`] accept any UTF-8 string without
|
||||
/// interpreting or validating it. Use [`Self::from_string`] when a caller
|
||||
/// already owns legacy app-server path text and needs to preserve its wire
|
||||
/// spelling; use [`Self::from_path`], [`Self::from_abs_path`], or
|
||||
/// [`Self::from_path_uri`] when converting an actual path value. Relative
|
||||
/// path text remains valid until an operation such as [`Self::to_path_uri`]
|
||||
/// requires an absolute path.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, TS)]
|
||||
#[serde(transparent)]
|
||||
#[ts(type = "string")]
|
||||
pub struct LegacyAppPathString(String);
|
||||
|
||||
impl LegacyAppPathString {
|
||||
/// Preserves already-legacy app-server path text without interpreting it
|
||||
/// using the current host.
|
||||
///
|
||||
/// This is for API-boundary values that are already strings, including
|
||||
/// relative or foreign-platform spellings. Callers with a local
|
||||
/// [`Path`], [`AbsolutePathBuf`], or [`PathUri`] should use the
|
||||
/// corresponding typed constructor instead.
|
||||
pub fn from_string(path: impl Into<String>) -> Self {
|
||||
Self(path.into())
|
||||
}
|
||||
|
||||
/// Preserves path text without interpreting it using the current host.
|
||||
pub fn from_path(path: &Path) -> Self {
|
||||
Self(path.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// Renders an absolute path using the current host's path convention.
|
||||
pub fn from_abs_path(path: &AbsolutePathBuf) -> Self {
|
||||
Self::from_path(path.as_path())
|
||||
}
|
||||
|
||||
/// Renders a path URI using the requested native path convention.
|
||||
///
|
||||
/// Rendering fails when the URI shape does not match the convention, such
|
||||
/// as a POSIX path rendered as Windows or a UNC path rendered as POSIX. It
|
||||
/// also fails when an opaque fallback does not encode an absolute path for
|
||||
/// the convention. Non-UTF-8 segments are rendered lossily, and encoded
|
||||
/// separators are emitted as native path text.
|
||||
pub fn from_path_uri(
|
||||
path: &PathUri,
|
||||
convention: PathConvention,
|
||||
) -> Result<Self, LegacyAppPathStringError> {
|
||||
if let Some(path_bytes) = path.opaque_fallback_bytes() {
|
||||
return render_opaque_fallback(path, &path_bytes, convention).map(Self);
|
||||
}
|
||||
match convention {
|
||||
PathConvention::Posix => render_posix_path(path),
|
||||
PathConvention::Windows => render_windows_path(path),
|
||||
}
|
||||
.map(Self)
|
||||
}
|
||||
|
||||
/// Parses this API string as an absolute path using the requested native
|
||||
/// path convention and returns its canonical path URI.
|
||||
pub fn to_path_uri(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<PathUri, LegacyAppPathStringError> {
|
||||
PathUri::from_absolute_native_path(&self.0, convention).ok_or_else(|| {
|
||||
LegacyAppPathStringError::InvalidNativePath {
|
||||
path: self.0.clone(),
|
||||
convention: Some(convention),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves this raw API path spelling against an executor cwd.
|
||||
///
|
||||
/// Relative paths use the cwd's inferred convention. Home-relative paths
|
||||
/// use the supplied executor home, and clearly foreign absolute paths are
|
||||
/// rejected rather than reinterpreted as relative path text.
|
||||
pub fn resolve_against(
|
||||
&self,
|
||||
cwd: &PathUri,
|
||||
user_home_dir: Option<&PathUri>,
|
||||
) -> Result<PathUri, LegacyAppPathStringError> {
|
||||
let convention = cwd.infer_path_convention().ok_or_else(|| {
|
||||
LegacyAppPathStringError::MissingBaseConvention {
|
||||
cwd: cwd.to_string(),
|
||||
}
|
||||
})?;
|
||||
let is_windows = convention == PathConvention::Windows;
|
||||
let path = self.as_str();
|
||||
let home_relative = convention.home_relative_suffix(path);
|
||||
if let Some(suffix) = home_relative {
|
||||
let home =
|
||||
user_home_dir.ok_or_else(|| LegacyAppPathStringError::MissingHomeDirectory {
|
||||
path: path.to_string(),
|
||||
})?;
|
||||
return Ok(home.join(suffix.trim_start_matches(|separator| {
|
||||
separator == '/' || is_windows && separator == '\\'
|
||||
}))?);
|
||||
}
|
||||
|
||||
if is_windows && (path.starts_with("//") || path.starts_with(r"\\")) {
|
||||
return self.to_path_uri(PathConvention::Windows);
|
||||
}
|
||||
|
||||
match self.infer_absolute_path_convention() {
|
||||
Some(path_convention) if path_convention == convention => self.to_path_uri(convention),
|
||||
Some(PathConvention::Posix) if is_windows => Ok(cwd.join(path)?),
|
||||
Some(path_convention) => Err(LegacyAppPathStringError::MismatchedConvention {
|
||||
path: path.to_string(),
|
||||
path_convention,
|
||||
cwd: cwd.to_string(),
|
||||
convention,
|
||||
}),
|
||||
None => Ok(cwd.join(path)?),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses this API string as an absolute path using the convention inferred from its spelling.
|
||||
pub fn to_inferred_path_uri(&self) -> Option<PathUri> {
|
||||
PathUri::try_from(self.clone()).ok()
|
||||
}
|
||||
|
||||
/// Renders this API path for display in a user interface.
|
||||
///
|
||||
/// Absolute paths are normalized using their inferred native convention.
|
||||
/// Strings that cannot be interpreted as absolute paths retain their raw
|
||||
/// API spelling.
|
||||
pub fn render_for_ui(&self) -> String {
|
||||
self.to_inferred_path_uri()
|
||||
.map(|path| path.inferred_native_path_string())
|
||||
.unwrap_or_else(|| self.0.clone())
|
||||
}
|
||||
|
||||
/// Parses this API string as a host-native absolute path.
|
||||
pub fn to_inferred_abs_path(&self) -> Option<AbsolutePathBuf> {
|
||||
AbsolutePathBuf::try_from(self.clone()).ok()
|
||||
}
|
||||
|
||||
/// Infers the path convention of an absolute API path from its spelling.
|
||||
///
|
||||
/// Two leading separators select Windows UNC or namespace syntax, including
|
||||
/// forward and mixed slashes, independently of the current host. This favors
|
||||
/// UNC paths over ambiguous double-slash POSIX paths. Call [`Self::to_path_uri`]
|
||||
/// with an explicit POSIX convention to preserve that interpretation.
|
||||
/// Relative paths return `None`; inferred prefixes still require validation.
|
||||
pub fn infer_absolute_path_convention(&self) -> Option<PathConvention> {
|
||||
let bytes = self.0.as_bytes();
|
||||
let has_windows_drive_root = matches!(
|
||||
bytes,
|
||||
[drive, b':', separator, ..]
|
||||
if drive.is_ascii_alphabetic() && is_windows_separator_byte(*separator)
|
||||
);
|
||||
let has_windows_unc_root = matches!(
|
||||
bytes,
|
||||
[first, second, ..]
|
||||
if is_windows_separator_byte(*first) && is_windows_separator_byte(*second)
|
||||
);
|
||||
if has_windows_drive_root || has_windows_unc_root {
|
||||
Some(PathConvention::Windows)
|
||||
} else if self.0.starts_with('/') {
|
||||
Some(PathConvention::Posix)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AbsolutePathBuf> for LegacyAppPathString {
|
||||
fn from(path: AbsolutePathBuf) -> Self {
|
||||
Self::from_abs_path(&path)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathUri> for LegacyAppPathString {
|
||||
fn from(path: PathUri) -> Self {
|
||||
Self(path.inferred_native_path_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<LegacyAppPathString> for PathUri {
|
||||
type Error = LegacyAppPathStringError;
|
||||
|
||||
fn try_from(path: LegacyAppPathString) -> Result<Self, Self::Error> {
|
||||
let Some(convention) = path.infer_absolute_path_convention() else {
|
||||
return Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: path.0,
|
||||
convention: None,
|
||||
});
|
||||
};
|
||||
PathUri::from_absolute_native_path(path.as_str(), convention).ok_or({
|
||||
LegacyAppPathStringError::InvalidNativePath {
|
||||
path: path.0,
|
||||
convention: Some(convention),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<LegacyAppPathString> for AbsolutePathBuf {
|
||||
type Error = LegacyAppPathStringError;
|
||||
|
||||
fn try_from(path: LegacyAppPathString) -> Result<Self, Self::Error> {
|
||||
AbsolutePathBuf::from_absolute_path_checked(path.as_str()).map_err(|_| {
|
||||
LegacyAppPathStringError::InvalidNativePath {
|
||||
path: path.0,
|
||||
convention: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn render_opaque_fallback(
|
||||
path: &PathUri,
|
||||
path_bytes: &[u8],
|
||||
convention: PathConvention,
|
||||
) -> Result<String, LegacyAppPathStringError> {
|
||||
let rendered = match convention {
|
||||
PathConvention::Posix if path_bytes.starts_with(b"/") => {
|
||||
Some(String::from_utf8_lossy(path_bytes).into_owned())
|
||||
}
|
||||
PathConvention::Windows => render_windows_opaque_fallback(path_bytes),
|
||||
PathConvention::Posix => None,
|
||||
};
|
||||
rendered.ok_or_else(|| LegacyAppPathStringError::OpaqueFallback {
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn render_windows_opaque_fallback(path_bytes: &[u8]) -> Option<String> {
|
||||
if !path_bytes.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let path_wide = path_bytes
|
||||
.chunks_exact(2)
|
||||
.map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]]))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Windows absolute paths either have a rooted drive prefix (`C:\\`) or a
|
||||
// rooted namespace/UNC prefix (`\\server`, `\\.\\`, or `\\?\\`).
|
||||
let has_drive_root = matches!(
|
||||
path_wide.as_slice(),
|
||||
[drive, colon, separator, ..]
|
||||
if ((u16::from(b'A')..=u16::from(b'Z')).contains(drive)
|
||||
|| (u16::from(b'a')..=u16::from(b'z')).contains(drive))
|
||||
&& *colon == u16::from(b':')
|
||||
&& is_windows_separator(*separator)
|
||||
);
|
||||
let has_namespace_or_unc_root = matches!(
|
||||
path_wide.as_slice(),
|
||||
[first, second, ..]
|
||||
if is_windows_separator(*first) && is_windows_separator(*second)
|
||||
);
|
||||
(has_drive_root || has_namespace_or_unc_root).then(|| String::from_utf16_lossy(&path_wide))
|
||||
}
|
||||
|
||||
fn is_windows_separator(character: u16) -> bool {
|
||||
character == u16::from(b'\\') || character == u16::from(b'/')
|
||||
}
|
||||
|
||||
impl fmt::Display for LegacyAppPathString {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for LegacyAppPathString {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for LegacyAppPathString {
|
||||
fn schema_name() -> String {
|
||||
"LegacyAppPathString".to_string()
|
||||
}
|
||||
|
||||
fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
|
||||
String::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
fn render_posix_path(path: &PathUri) -> Result<String, LegacyAppPathStringError> {
|
||||
let url = path.to_url();
|
||||
// POSIX file paths do not have a UNC authority, so `file://server/share`
|
||||
// cannot be represented as `/share` without losing the server identity.
|
||||
if url.host_str().is_some() {
|
||||
return Err(incompatible_convention(path, PathConvention::Posix));
|
||||
}
|
||||
|
||||
// URI segments are already separated with `/` on every host. Decode each
|
||||
// one independently so `file:///a%20dir/file` becomes `/a dir/file`.
|
||||
let mut rendered = String::new();
|
||||
for segment in path_segments(&url) {
|
||||
rendered.push('/');
|
||||
rendered.push_str(&decode_native_segment(segment));
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
fn render_windows_path(path: &PathUri) -> Result<String, LegacyAppPathStringError> {
|
||||
let url = path.to_url();
|
||||
let mut segments = path_segments(&url);
|
||||
let mut rendered = String::new();
|
||||
if let Some(host) = url.host_str() {
|
||||
// A URI authority selects the UNC form: `file://server/share/file`
|
||||
// becomes `\\server\share\file`. The first segment is the share name,
|
||||
// which must be present.
|
||||
let Some(share) = segments.next() else {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
};
|
||||
let share = decode_native_segment(share);
|
||||
if share.is_empty() {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
}
|
||||
rendered.push_str(r"\\");
|
||||
rendered.push_str(host);
|
||||
rendered.push('\\');
|
||||
rendered.push_str(&share);
|
||||
} else {
|
||||
// Without an authority, Windows requires a drive root. For example,
|
||||
// `file:///C:/src/main.rs` begins with the `C:` URI segment and renders
|
||||
// as `C:\src\main.rs`; a POSIX URI such as `file:///usr/bin` is rejected.
|
||||
let Some(drive) = segments.next() else {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
};
|
||||
let drive = decode_native_segment(drive);
|
||||
let bytes = drive.as_bytes();
|
||||
if bytes.len() != 2 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
}
|
||||
rendered.push_str(&drive);
|
||||
}
|
||||
|
||||
for segment in segments {
|
||||
// URL path separators become Windows separators after each component
|
||||
// has been decoded.
|
||||
let segment = decode_native_segment(segment);
|
||||
rendered.push('\\');
|
||||
rendered.push_str(&segment);
|
||||
}
|
||||
// `file:///C:` and `file:///C:/` both identify the drive root, never the
|
||||
// drive-relative path `C:`.
|
||||
if rendered.len() == 2 && rendered.as_bytes()[1] == b':' {
|
||||
rendered.push('\\');
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
fn path_segments(url: &url::Url) -> std::str::Split<'_, char> {
|
||||
url.path_segments()
|
||||
.unwrap_or_else(|| unreachable!("validated file URLs have path segments"))
|
||||
}
|
||||
|
||||
fn decode_native_segment(segment: &str) -> String {
|
||||
// Decode exactly once. Thus `%20` becomes a space and `%252F` becomes the
|
||||
// literal text `%2F`, rather than being decoded a second time into `/`.
|
||||
let bytes = urlencoding::decode_binary(segment.as_bytes());
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
}
|
||||
|
||||
fn incompatible_convention(path: &PathUri, convention: PathConvention) -> LegacyAppPathStringError {
|
||||
LegacyAppPathStringError::IncompatibleConvention {
|
||||
path: path.to_string(),
|
||||
convention,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum LegacyAppPathStringError {
|
||||
#[error("opaque fallback path URI `{path}` cannot be recovered as a native path")]
|
||||
OpaqueFallback { path: String },
|
||||
#[error("path URI `{path}` cannot be rendered using {convention} path syntax")]
|
||||
IncompatibleConvention {
|
||||
path: String,
|
||||
convention: PathConvention,
|
||||
},
|
||||
#[error(
|
||||
"path `{path}` is not absolute{convention}",
|
||||
convention = .convention.map(|convention| format!(" using {convention} path syntax")).unwrap_or_default()
|
||||
)]
|
||||
InvalidNativePath {
|
||||
path: String,
|
||||
convention: Option<PathConvention>,
|
||||
},
|
||||
#[error("unsupported configuration path {path:?} using {convention} path syntax")]
|
||||
UnsupportedConfigPath {
|
||||
path: String,
|
||||
convention: PathConvention,
|
||||
},
|
||||
#[error("path URI `{cwd}` has no path convention")]
|
||||
MissingBaseConvention { cwd: String },
|
||||
#[error("cannot resolve home-relative path `{path}` without an executor home")]
|
||||
MissingHomeDirectory { path: String },
|
||||
#[error(
|
||||
"path {path} uses {path_convention} paths, but executor cwd {cwd} uses {convention} paths"
|
||||
)]
|
||||
MismatchedConvention {
|
||||
path: String,
|
||||
path_convention: PathConvention,
|
||||
cwd: String,
|
||||
convention: PathConvention,
|
||||
},
|
||||
#[error(transparent)]
|
||||
PathUri(#[from] PathUriParseError),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "api_path_string_tests.rs"]
|
||||
mod tests;
|
||||
718
akode-rs/utils/path-uri/src/api_path_string_tests.rs
Normal file
718
akode-rs/utils/path-uri/src/api_path_string_tests.rs
Normal file
@@ -0,0 +1,718 @@
|
||||
use super::*;
|
||||
use crate::PathUri;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RenderCase {
|
||||
uri: &'static str,
|
||||
convention: PathConvention,
|
||||
expected: RenderExpectation,
|
||||
}
|
||||
|
||||
impl RenderCase {
|
||||
const fn round_trips(
|
||||
uri: &'static str,
|
||||
convention: PathConvention,
|
||||
rendered: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
uri,
|
||||
convention,
|
||||
expected: RenderExpectation::RoundTrip(rendered),
|
||||
}
|
||||
}
|
||||
|
||||
const fn rejects(uri: &'static str, convention: PathConvention, error: ExpectedError) -> Self {
|
||||
Self {
|
||||
uri,
|
||||
convention,
|
||||
expected: RenderExpectation::Error(error),
|
||||
}
|
||||
}
|
||||
|
||||
const fn renders_lossily(
|
||||
uri: &'static str,
|
||||
convention: PathConvention,
|
||||
rendered: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
uri,
|
||||
convention,
|
||||
expected: RenderExpectation::RenderOnly(rendered),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum RenderExpectation {
|
||||
RoundTrip(&'static str),
|
||||
RenderOnly(&'static str),
|
||||
Error(ExpectedError),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ExpectedError {
|
||||
OpaqueFallback,
|
||||
IncompatibleConvention,
|
||||
}
|
||||
|
||||
const RENDER_CASES: &[RenderCase] = &[
|
||||
// POSIX paths.
|
||||
RenderCase::round_trips("file:///", PathConvention::Posix, "/"),
|
||||
RenderCase::round_trips(
|
||||
"file:///home/alice/src/main.rs",
|
||||
PathConvention::Posix,
|
||||
"/home/alice/src/main.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///home/alice/a%20file.rs",
|
||||
PathConvention::Posix,
|
||||
"/home/alice/a file.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///workspace/src/lib.rs",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src/lib.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///workspace/tests/test.rs",
|
||||
PathConvention::Posix,
|
||||
"/workspace/tests/test.rs",
|
||||
),
|
||||
RenderCase::round_trips("file:///etc", PathConvention::Posix, "/etc"),
|
||||
RenderCase::round_trips("file:///tmp/", PathConvention::Posix, "/tmp/"),
|
||||
RenderCase::renders_lossily("file:///C:/Project", PathConvention::Posix, "/C:/Project"),
|
||||
RenderCase::renders_lossily("file:///C:", PathConvention::Posix, "/C:"),
|
||||
RenderCase::round_trips("file:///tmp/%E2%98%83", PathConvention::Posix, "/tmp/☃"),
|
||||
RenderCase::round_trips("file:///tmp/a%5Cb", PathConvention::Posix, "/tmp/a\\b"),
|
||||
RenderCase::round_trips(
|
||||
"file:///tmp/100%25/file",
|
||||
PathConvention::Posix,
|
||||
"/tmp/100%/file",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///tmp/a%3Fb%23c%25d",
|
||||
PathConvention::Posix,
|
||||
"/tmp/a?b#c%d",
|
||||
),
|
||||
RenderCase::round_trips("file:///tmp/a%252Fb", PathConvention::Posix, "/tmp/a%2Fb"),
|
||||
RenderCase::round_trips(
|
||||
"file:///bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
PathConvention::Posix,
|
||||
"/bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"FILE:///workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:/workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://localhost/workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://LOCALHOST/workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
// Windows drive paths.
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/Users/Alice%20Smith/src/main.rs",
|
||||
PathConvention::Windows,
|
||||
r"C:\Users\Alice Smith\src\main.rs",
|
||||
),
|
||||
RenderCase::round_trips("file:///C:/", PathConvention::Windows, "C:\\"),
|
||||
RenderCase::renders_lossily("file:///C:", PathConvention::Windows, "C:\\"),
|
||||
RenderCase::round_trips("file:///C:/Users", PathConvention::Windows, r"C:\Users"),
|
||||
RenderCase::round_trips("file:///C:/Windows", PathConvention::Windows, r"C:\Windows"),
|
||||
RenderCase::round_trips(
|
||||
"file:///d:/snowman/%E2%98%83",
|
||||
PathConvention::Windows,
|
||||
r"D:\snowman\☃",
|
||||
),
|
||||
RenderCase::round_trips("file:///C:/tmp/", PathConvention::Windows, "C:\\tmp\\"),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/test%20with%20%25/path",
|
||||
PathConvention::Windows,
|
||||
r"C:\test with %\path",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/test%20with%20%2525/c%23code",
|
||||
PathConvention::Windows,
|
||||
r"C:\test with %25\c#code",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins/c%23/plugin.json",
|
||||
PathConvention::Windows,
|
||||
r"C:\Source\Zürich or Zurich (ˈzjʊərɪk,\Code\resources\app\plugins\c#\plugin.json",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/project/owner's_file/database.sqlite",
|
||||
PathConvention::Windows,
|
||||
r"C:\project\owner's_file\database.sqlite",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/project/%25A0.txt",
|
||||
PathConvention::Windows,
|
||||
r"C:\project\%A0.txt",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/project/%252e.txt",
|
||||
PathConvention::Windows,
|
||||
r"C:\project\%2e.txt",
|
||||
),
|
||||
// Windows UNC paths.
|
||||
RenderCase::round_trips(
|
||||
"file://server/share/src/main.rs",
|
||||
PathConvention::Windows,
|
||||
r"\\server\share\src\main.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://server/share",
|
||||
PathConvention::Windows,
|
||||
r"\\server\share",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://server/share/",
|
||||
PathConvention::Windows,
|
||||
"\\\\server\\share\\",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://shares/files/c%23/p.cs",
|
||||
PathConvention::Windows,
|
||||
r"\\shares\files\c#\p.cs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://monacotools1/certificates/SSL/",
|
||||
PathConvention::Windows,
|
||||
"\\\\monacotools1\\certificates\\SSL\\",
|
||||
),
|
||||
// Opaque fallbacks rendered according to their source convention.
|
||||
RenderCase::renders_lossily(
|
||||
"file:///%00/bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
PathConvention::Posix,
|
||||
"/tmp/null-\0-<2D>-byte",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///%00/bad/path/XABcAC4AXABDAE8ATQAxAFwA",
|
||||
PathConvention::Windows,
|
||||
r"\\.\COM1\",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///%00/bad/path/XABcAD8AXABWAG8AbAB1AG0AZQB7ADAAMAAwADAAMAAwADAAMAAtADAAMAAwADAALQAwADAAMAAwAC0AMAAwADAAMAAtADAAMAAwADAAMAAwADAAMAAwADAAMAAwAH0AXABmAGkAbABlAC4AcgBzAA",
|
||||
PathConvention::Windows,
|
||||
r"\\?\Volume{00000000-0000-0000-0000-000000000000}\file.rs",
|
||||
),
|
||||
// Windows rendering preserves path text without filesystem validation.
|
||||
RenderCase::round_trips("file:///C:/a%3Fb", PathConvention::Windows, "C:\\a?b"),
|
||||
RenderCase::round_trips("file:///C:/a*b", PathConvention::Windows, "C:\\a*b"),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/trailing.",
|
||||
PathConvention::Windows,
|
||||
"C:\\trailing.",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/trailing%20",
|
||||
PathConvention::Windows,
|
||||
"C:\\trailing ",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/control-%01",
|
||||
PathConvention::Windows,
|
||||
"C:\\control-\u{1}",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/file.txt:stream",
|
||||
PathConvention::Windows,
|
||||
"C:\\file.txt:stream",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://server/sh%3Fare/file.rs",
|
||||
PathConvention::Windows,
|
||||
"\\\\server\\sh?are\\file.rs",
|
||||
),
|
||||
// These renderings intentionally lose URI byte or segment boundaries.
|
||||
RenderCase::renders_lossily(
|
||||
"file:///tmp/non-utf8-%FF",
|
||||
PathConvention::Posix,
|
||||
"/tmp/non-utf8-<2D>",
|
||||
),
|
||||
RenderCase::renders_lossily(
|
||||
"file:///tmp/non-utf8-%A0",
|
||||
PathConvention::Posix,
|
||||
"/tmp/non-utf8-<2D>",
|
||||
),
|
||||
RenderCase::renders_lossily("file:///tmp/a%2Fb", PathConvention::Posix, "/tmp/a/b"),
|
||||
RenderCase::renders_lossily("file:///C:/a%2Fb", PathConvention::Windows, "C:\\a/b"),
|
||||
RenderCase::renders_lossily("file:///C:/a%5Cb", PathConvention::Windows, "C:\\a\\b"),
|
||||
// URI shapes that do not match the requested convention.
|
||||
RenderCase::rejects(
|
||||
"file://server/share/file.txt",
|
||||
PathConvention::Posix,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file://server/share/file.rs",
|
||||
PathConvention::Posix,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///usr/local/file.txt",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///home/alice/file.rs",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file://server/",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///_:/path",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
// Invalid opaque fallback payloads.
|
||||
RenderCase::rejects(
|
||||
"file:///%00/bad/path/YQ",
|
||||
PathConvention::Posix,
|
||||
ExpectedError::OpaqueFallback,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///%00/bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::OpaqueFallback,
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn renders_native_paths_from_shared_cases() {
|
||||
for case in RENDER_CASES {
|
||||
let path = PathUri::parse(case.uri).expect("valid file URI");
|
||||
let expected = match case.expected {
|
||||
RenderExpectation::RoundTrip(rendered) => Ok(LegacyAppPathString(rendered.to_string())),
|
||||
RenderExpectation::RenderOnly(rendered) => {
|
||||
Ok(LegacyAppPathString(rendered.to_string()))
|
||||
}
|
||||
RenderExpectation::Error(ExpectedError::OpaqueFallback) => {
|
||||
Err(LegacyAppPathStringError::OpaqueFallback {
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
RenderExpectation::Error(ExpectedError::IncompatibleConvention) => {
|
||||
Err(LegacyAppPathStringError::IncompatibleConvention {
|
||||
path: path.to_string(),
|
||||
convention: case.convention,
|
||||
})
|
||||
}
|
||||
};
|
||||
let actual = LegacyAppPathString::from_path_uri(&path, case.convention);
|
||||
|
||||
assert_eq!(actual, expected, "rendering {case:?}");
|
||||
if let Ok(rendered) = &actual {
|
||||
assert_eq!(
|
||||
rendered.infer_absolute_path_convention(),
|
||||
Some(case.convention),
|
||||
"inferring {case:?}"
|
||||
);
|
||||
}
|
||||
|
||||
if let RenderExpectation::RoundTrip(rendered) = case.expected {
|
||||
let api_path =
|
||||
serde_json::from_value::<LegacyAppPathString>(serde_json::json!(rendered))
|
||||
.expect("native path should deserialize from API text");
|
||||
let reparsed = api_path
|
||||
.to_path_uri(case.convention)
|
||||
.expect("native path should parse using its convention");
|
||||
assert_eq!(reparsed, path, "parsing {case:?}");
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_path_uri(&reparsed, case.convention),
|
||||
Ok(api_path),
|
||||
"round-tripping {case:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_api_path_serializes_and_deserializes_unchanged() {
|
||||
for raw_path in [".", "subdir", "subdir/file.rs"] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("relative API path should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(path).expect("relative API path should serialize"),
|
||||
serde_json::json!(raw_path)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_api_path_is_invalid_when_converted_to_a_path_uri() {
|
||||
let raw_path = "subdir";
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("relative API path should deserialize");
|
||||
|
||||
assert_eq!(path.infer_absolute_path_convention(), None);
|
||||
assert_eq!(
|
||||
path.to_path_uri(PathConvention::Posix),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: Some(PathConvention::Posix),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
PathUri::try_from(path.clone()),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
AbsolutePathBuf::try_from(path),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_non_absolute_api_paths_cannot_be_converted_to_path_uris() {
|
||||
for (raw_path, convention) in [
|
||||
(r"workspace\file.rs", PathConvention::Windows),
|
||||
(r"C:file.rs", PathConvention::Windows),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("API path should deserialize without validation");
|
||||
|
||||
assert_eq!(path.infer_absolute_path_convention(), None);
|
||||
assert_eq!(
|
||||
path.to_path_uri(convention),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: Some(convention),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn infers_absolute_path_conventions_from_api_text() {
|
||||
for (raw_path, expected) in [
|
||||
(r"C:\workspace\file.rs", Some(PathConvention::Windows)),
|
||||
("c:/workspace/file.rs", Some(PathConvention::Windows)),
|
||||
(r"\\server\share\file.rs", Some(PathConvention::Windows)),
|
||||
(r"\\?\C:\workspace\file.rs", Some(PathConvention::Windows)),
|
||||
(r"\\.\COM1", Some(PathConvention::Windows)),
|
||||
("/workspace/file.rs", Some(PathConvention::Posix)),
|
||||
("/C:/workspace/file.rs", Some(PathConvention::Posix)),
|
||||
("//server/share/file.rs", Some(PathConvention::Windows)),
|
||||
("", None),
|
||||
(".", None),
|
||||
("subdir/file.rs", None),
|
||||
(r"subdir\file.rs", None),
|
||||
(r"C:file.rs", None),
|
||||
(r"\rooted-without-drive", None),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("API path should deserialize without validation");
|
||||
|
||||
assert_eq!(
|
||||
path.infer_absolute_path_convention(),
|
||||
expected,
|
||||
"inferring {raw_path:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_absolute_api_paths_using_the_inferred_convention() {
|
||||
for (raw_path, convention, expected_uri) in [
|
||||
(
|
||||
r"C:\workspace\file.rs",
|
||||
PathConvention::Windows,
|
||||
"file:///C:/workspace/file.rs",
|
||||
),
|
||||
(
|
||||
"/workspace/file.rs",
|
||||
PathConvention::Posix,
|
||||
"file:///workspace/file.rs",
|
||||
),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("absolute API path should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
path.to_inferred_path_uri(),
|
||||
Some(PathUri::parse(expected_uri).expect("expected URI should parse")),
|
||||
);
|
||||
assert_eq!(path.render_for_ui(), raw_path);
|
||||
assert_eq!(
|
||||
PathUri::try_from(path.clone()),
|
||||
path.to_path_uri(convention)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_legacy_paths_against_executor_context() {
|
||||
for (cwd, path, user_home_dir, expected) in [
|
||||
(
|
||||
"file:///workspace",
|
||||
"relative.txt",
|
||||
None,
|
||||
"file:///workspace/relative.txt",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace",
|
||||
"/Windows",
|
||||
None,
|
||||
"file:///C:/Windows",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace",
|
||||
"//server/share/file.txt",
|
||||
None,
|
||||
"file://server/share/file.txt",
|
||||
),
|
||||
(
|
||||
"file:///workspace",
|
||||
"~//notes",
|
||||
Some("file:///home/executor"),
|
||||
"file:///home/executor/notes",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace",
|
||||
r"~\\notes",
|
||||
Some("file:///C:/Users/executor"),
|
||||
"file:///C:/Users/executor/notes",
|
||||
),
|
||||
] {
|
||||
let cwd = PathUri::parse(cwd).expect("valid cwd");
|
||||
let user_home_dir = user_home_dir.map(|home| PathUri::parse(home).expect("valid home"));
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_string(path).resolve_against(&cwd, user_home_dir.as_ref()),
|
||||
Ok(PathUri::parse(expected).expect("valid expected path")),
|
||||
"resolving {path:?} against {cwd}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_legacy_paths_without_executor_context() {
|
||||
let cwd = PathUri::parse("file:///workspace").expect("valid cwd");
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_string(r"C:\\tmp")
|
||||
.resolve_against(&cwd, /*user_home_dir*/ None),
|
||||
Err(LegacyAppPathStringError::MismatchedConvention {
|
||||
path: r"C:\\tmp".to_string(),
|
||||
path_convention: PathConvention::Windows,
|
||||
cwd: cwd.to_string(),
|
||||
convention: PathConvention::Posix,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_string("~/secret")
|
||||
.resolve_against(&cwd, /*user_home_dir*/ None),
|
||||
Err(LegacyAppPathStringError::MissingHomeDirectory {
|
||||
path: "~/secret".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_absolute_api_paths_preserve_their_inferred_convention() {
|
||||
for (raw_path, convention) in [
|
||||
("/C:/secret", PathConvention::Posix),
|
||||
(r"\\localhost\share", PathConvention::Windows),
|
||||
] {
|
||||
let path = LegacyAppPathString::from_string(raw_path);
|
||||
let uri = PathUri::try_from(path.clone()).expect("absolute API path should convert");
|
||||
assert_eq!(uri.infer_path_convention(), Some(convention));
|
||||
assert_eq!(LegacyAppPathString::from(uri), path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_native_api_path_to_inferred_absolute_path() {
|
||||
#[cfg(windows)]
|
||||
let raw_path = r"C:\workspace\file.rs";
|
||||
#[cfg(not(windows))]
|
||||
let raw_path = "/workspace/file.rs";
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("absolute API path should deserialize");
|
||||
let expected = AbsolutePathBuf::try_from(raw_path).expect("native absolute path should parse");
|
||||
|
||||
assert_eq!(
|
||||
AbsolutePathBuf::try_from(path.clone()),
|
||||
Ok(expected.clone())
|
||||
);
|
||||
assert_eq!(path.to_inferred_abs_path(), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_absolute_syntax_deserializes_without_host_interpretation() {
|
||||
for (raw_path, convention) in [
|
||||
(r"C:\workspace\file.rs", PathConvention::Windows),
|
||||
("/workspace/file.rs", PathConvention::Posix),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("foreign API path should deserialize");
|
||||
|
||||
assert_eq!(path.as_str(), raw_path);
|
||||
assert_eq!(path.infer_absolute_path_convention(), Some(convention));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_path_preserves_foreign_absolute_path_for_uri_conversion() {
|
||||
#[cfg(not(windows))]
|
||||
let (foreign_path, expected_uri) = (r"C:\Users\openai\share", "file:///C:/Users/openai/share");
|
||||
#[cfg(windows)]
|
||||
let (foreign_path, expected_uri) = ("/home/openai/share", "file:///home/openai/share");
|
||||
|
||||
let path: PathUri = LegacyAppPathString::from_path(std::path::Path::new(foreign_path))
|
||||
.try_into()
|
||||
.expect("foreign absolute path should convert");
|
||||
|
||||
assert_eq!(
|
||||
path,
|
||||
PathUri::parse(expected_uri).expect("valid expected URI")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_an_absolute_path_using_the_host_convention() {
|
||||
#[cfg(unix)]
|
||||
let native_path = "/workspace/a file.rs";
|
||||
#[cfg(windows)]
|
||||
let native_path = r"C:\workspace\a file.rs";
|
||||
let path = AbsolutePathBuf::from_absolute_path_checked(native_path)
|
||||
.expect("native path should be absolute");
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from(path),
|
||||
LegacyAppPathString(native_path.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn renders_native_non_unicode_windows_fallback_lossily() {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
|
||||
let native_path = std::path::PathBuf::from(std::ffi::OsString::from_wide(
|
||||
&r"C:\bad\"
|
||||
.encode_utf16()
|
||||
.chain([0xd800])
|
||||
.collect::<Vec<_>>(),
|
||||
));
|
||||
let native_path =
|
||||
AbsolutePathBuf::from_absolute_path_checked(native_path).expect("absolute native path");
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_abs_path(&native_path),
|
||||
LegacyAppPathString(r"C:\bad\<5C>".to_string())
|
||||
);
|
||||
|
||||
let path = PathUri::from_abs_path(&native_path);
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_path_uri(&path, PathConvention::Windows),
|
||||
Ok(LegacyAppPathString(r"C:\bad\<5C>".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_path_uri(&path, PathConvention::Posix),
|
||||
Err(LegacyAppPathStringError::OpaqueFallback {
|
||||
path: path.to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_and_deserializes_as_a_string() {
|
||||
let path = PathUri::parse("file:///workspace/src/lib.rs").expect("valid file URI");
|
||||
let rendered = LegacyAppPathString::from_path_uri(&path, PathConvention::Posix)
|
||||
.expect("POSIX URI should render");
|
||||
|
||||
let json = serde_json::to_string(&rendered).expect("rendered path should serialize");
|
||||
assert_eq!(json, r#""/workspace/src/lib.rs""#);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<LegacyAppPathString>(&json)
|
||||
.expect("rendered path should deserialize from a string"),
|
||||
rendered
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inferred_unc_paths_accept_forward_and_mixed_slashes_on_every_host() {
|
||||
for raw in [
|
||||
"//server/share/project",
|
||||
r"//server/share\project",
|
||||
r"/\server/share/project",
|
||||
r"\/server/share/project",
|
||||
r"\\server\share\project",
|
||||
"//wsl.localhost/Ubuntu/home/user/project",
|
||||
"//127.0.0.1/c$/project",
|
||||
"//LOCALHOST/c$/project",
|
||||
"//?/C:/project",
|
||||
] {
|
||||
let path = LegacyAppPathString::from_string(raw);
|
||||
let expected = path.to_path_uri(PathConvention::Windows).expect(raw);
|
||||
let inferred = path.to_inferred_path_uri().expect(raw);
|
||||
assert_eq!(
|
||||
(inferred.clone(), inferred.infer_path_convention()),
|
||||
(expected, Some(PathConvention::Windows)),
|
||||
"{raw}"
|
||||
);
|
||||
let serialized = serde_json::to_string(&inferred).expect("serialize URI");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<PathUri>(&serialized).expect("deserialize URI"),
|
||||
inferred,
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
let slash = LegacyAppPathString::from_string("//server/share/project")
|
||||
.to_inferred_path_uri()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
slash,
|
||||
PathUri::parse("file://server/share/project").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_slash_posix_paths_require_an_explicit_convention() {
|
||||
let path = LegacyAppPathString::from_string("//server/share/project");
|
||||
assert_eq!(
|
||||
path.to_path_uri(PathConvention::Posix).unwrap(),
|
||||
PathUri::parse("file:///server/share/project").unwrap()
|
||||
);
|
||||
let cwd = PathUri::parse("file:///workspace").unwrap();
|
||||
assert!(matches!(
|
||||
path.resolve_against(&cwd, /*user_home_dir*/ None),
|
||||
Err(LegacyAppPathStringError::MismatchedConvention { .. })
|
||||
));
|
||||
for raw in ["//", "//server", "//server/", "///server/share"] {
|
||||
assert!(
|
||||
LegacyAppPathString::from_string(raw)
|
||||
.to_inferred_path_uri()
|
||||
.is_none(),
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
}
|
||||
177
akode-rs/utils/path-uri/src/config_path.rs
Normal file
177
akode-rs/utils/path-uri/src/config_path.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Resolve filesystem denial paths with the existing URI parser and lexical join.
|
||||
//! Reject ambiguous or lossy representations before rendering security constraints.
|
||||
|
||||
use crate::LegacyAppPathString;
|
||||
use crate::LegacyAppPathStringError;
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use crate::PathUriParseError;
|
||||
|
||||
impl PathUri {
|
||||
/// Resolves configuration text using only the supplied convention, base, and home.
|
||||
/// Home-relative inputs require a home; other relative inputs require a base.
|
||||
/// Used facts and results must have an unambiguous, lossless native spelling.
|
||||
pub fn resolve_config_path(
|
||||
input: &str,
|
||||
convention: PathConvention,
|
||||
base: Option<&Self>,
|
||||
user_home_dir: Option<&Self>,
|
||||
) -> Result<String, LegacyAppPathStringError> {
|
||||
Self::resolve_config_path_uri(input, convention, base, user_home_dir)?
|
||||
.to_config_path_string(convention)
|
||||
}
|
||||
|
||||
/// Resolves and validates configuration text as a URI using only supplied path facts.
|
||||
/// Normalizes trailing separators while preserving the path's root.
|
||||
pub fn resolve_config_path_uri(
|
||||
input: &str,
|
||||
convention: PathConvention,
|
||||
base: Option<&Self>,
|
||||
user_home_dir: Option<&Self>,
|
||||
) -> Result<Self, LegacyAppPathStringError> {
|
||||
Self::validate_config_path_text(input, convention)?;
|
||||
let path = LegacyAppPathString::from_string(input);
|
||||
let resolved = if convention.home_relative_suffix(input).is_some() {
|
||||
let home =
|
||||
user_home_dir.ok_or_else(|| LegacyAppPathStringError::MissingHomeDirectory {
|
||||
path: input.to_string(),
|
||||
})?;
|
||||
home.validate_config_path(convention)?;
|
||||
if contains_glob_metacharacter(input) {
|
||||
home.validate_glob_directory(convention)?;
|
||||
}
|
||||
path.resolve_against(home, Some(home))?
|
||||
} else {
|
||||
match path.to_path_uri(convention) {
|
||||
Ok(absolute) => absolute,
|
||||
Err(error) => {
|
||||
let base = base.ok_or(error)?;
|
||||
base.validate_config_path(convention)?;
|
||||
if contains_glob_metacharacter(input) {
|
||||
base.validate_glob_directory(convention)?;
|
||||
}
|
||||
path.resolve_against(base, /*user_home_dir*/ None)?
|
||||
}
|
||||
}
|
||||
};
|
||||
resolved.validate_config_path(convention)?;
|
||||
// Config paths historically omit trailing separators except at a root.
|
||||
Ok(resolved.join(".")?)
|
||||
}
|
||||
|
||||
/// Renders an already resolved configuration path with legacy root separators.
|
||||
/// Use [`Self::resolve_config_path_uri`] to validate and normalize config input first.
|
||||
pub fn to_config_path_string(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<String, LegacyAppPathStringError> {
|
||||
let mut rendered = LegacyAppPathString::from_path_uri(self, convention)?.into_string();
|
||||
if self.0.host_str().is_some() && self.parent().is_none() {
|
||||
rendered.push('\\');
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
/// Checks that a literal directory can be inserted into a glob unchanged.
|
||||
/// Rejects metacharacters instead of turning directory names into patterns.
|
||||
/// POSIX backslashes would escape the following pattern character.
|
||||
pub fn validate_glob_directory(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<(), LegacyAppPathStringError> {
|
||||
self.validate_config_path(convention)?;
|
||||
let path = LegacyAppPathString::from_path_uri(self, convention)?.into_string();
|
||||
if contains_glob_metacharacter(&path)
|
||||
|| convention == PathConvention::Posix && path.contains('\\')
|
||||
{
|
||||
return Err(LegacyAppPathStringError::UnsupportedConfigPath { path, convention });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that a resolved configuration URI has a lossless native spelling
|
||||
/// in the owning executor's convention. Opaque and ambiguous paths fail.
|
||||
pub fn validate_config_path(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<(), LegacyAppPathStringError> {
|
||||
if self.infer_path_convention() != Some(convention) {
|
||||
return Err(LegacyAppPathStringError::IncompatibleConvention {
|
||||
path: self.to_string(),
|
||||
convention,
|
||||
});
|
||||
}
|
||||
let bytes = self.decoded_path_bytes();
|
||||
if self.lexical_depth().is_none()
|
||||
|| bytes.contains(&0)
|
||||
|| std::str::from_utf8(&bytes).is_err()
|
||||
{
|
||||
return Err(PathUriParseError::InvalidFileUriPath {
|
||||
path: self.to_string(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
Self::validate_config_path_text(
|
||||
LegacyAppPathString::from_path_uri(self, convention)?.as_str(),
|
||||
convention,
|
||||
)
|
||||
}
|
||||
|
||||
/// Validates native configuration text without resolving paths or glob syntax.
|
||||
/// Rejects spellings that could change targets during later native conversion.
|
||||
pub fn validate_config_path_text(
|
||||
input: &str,
|
||||
convention: PathConvention,
|
||||
) -> Result<(), LegacyAppPathStringError> {
|
||||
let namespace_alias = akode_utils_absolute_path::normalize_windows_device_path(input);
|
||||
let native_input = namespace_alias.as_deref().unwrap_or(input);
|
||||
let has_windows_component_colon = convention == PathConvention::Windows
|
||||
&& convention
|
||||
.path_segments(native_input)
|
||||
.enumerate()
|
||||
.any(|(index, segment)| {
|
||||
let segment = if index == 0
|
||||
&& segment
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphabetic)
|
||||
&& segment.as_bytes().get(/*index*/ 1) == Some(&b':')
|
||||
{
|
||||
&segment[2..]
|
||||
} else {
|
||||
segment
|
||||
};
|
||||
segment.contains(':')
|
||||
});
|
||||
let mixed_home_separators = convention == PathConvention::Windows
|
||||
&& convention
|
||||
.home_relative_suffix(input)
|
||||
.is_some_and(|suffix| {
|
||||
suffix.starts_with('/') && suffix.trim_start_matches('/').starts_with('\\')
|
||||
|| suffix.starts_with('\\')
|
||||
&& suffix.trim_start_matches('\\').starts_with('/')
|
||||
});
|
||||
let bare_windows_drive = convention == PathConvention::Windows
|
||||
&& matches!(native_input.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic());
|
||||
if input.contains('\0')
|
||||
|| has_windows_component_colon
|
||||
|| mixed_home_separators
|
||||
|| bare_windows_drive
|
||||
{
|
||||
return Err(LegacyAppPathStringError::UnsupportedConfigPath {
|
||||
path: input.to_string(),
|
||||
convention,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_glob_metacharacter(path: &str) -> bool {
|
||||
path.chars()
|
||||
.any(|character| matches!(character, '*' | '?' | '[' | ']' | '{' | '}'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "config_path_tests.rs"]
|
||||
mod tests;
|
||||
228
akode-rs/utils/path-uri/src/config_path_tests.rs
Normal file
228
akode-rs/utils/path-uri/src/config_path_tests.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
//! The configuration boundary shares URI resolution and rejects lossy denials.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn configuration_paths_resolve_with_the_supplied_platform_and_home() {
|
||||
for (convention, base, home, input, expected, expected_uri) in [
|
||||
(
|
||||
PathConvention::Posix,
|
||||
"file:///work/project",
|
||||
"file:///home/user",
|
||||
"~/a b/雪%/",
|
||||
"/home/user/a b/雪%",
|
||||
"file:///home/user/a%20b/%E9%9B%AA%25",
|
||||
),
|
||||
(
|
||||
PathConvention::Posix,
|
||||
"file:///work/project",
|
||||
"file:///home/user",
|
||||
"/",
|
||||
"/",
|
||||
"file:///",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"..\private\",
|
||||
r"C:\work\private",
|
||||
"file:///C:/work/private",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"d:\private\*.env\",
|
||||
r"D:\private\*.env",
|
||||
"file:///D:/private/*.env",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"D:\",
|
||||
r"D:\",
|
||||
"file:///D:",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"~\a b\雪%\",
|
||||
r"C:\Users\user\a b\雪%",
|
||||
"file:///C:/Users/user/a%20b/%E9%9B%AA%25",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work",
|
||||
"file:///C:/Users/user",
|
||||
r"\\SERVER\Share\private\*.env\",
|
||||
r"\\server\Share\private\*.env",
|
||||
"file://server/Share/private/*.env",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work",
|
||||
"file:///C:/Users/user",
|
||||
r"\\server\share",
|
||||
r"\\server\share\",
|
||||
"file://server/share",
|
||||
),
|
||||
] {
|
||||
let base = PathUri::parse(base).unwrap();
|
||||
let home = PathUri::parse(home).unwrap();
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path_uri(input, convention, Some(&base), Some(&home)),
|
||||
Ok(PathUri::parse(expected_uri).unwrap()),
|
||||
"{input:?}",
|
||||
);
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(input, convention, Some(&base), Some(&home)),
|
||||
Ok(expected.to_string()),
|
||||
"{input:?}",
|
||||
);
|
||||
if !input.starts_with('.') && !input.starts_with('\\') || input.starts_with(r"\\") {
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(input, convention, /*base*/ None, Some(&home)),
|
||||
Ok(expected.to_string()),
|
||||
"without base: {input:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuration_paths_reject_ambiguous_or_lossy_denials() {
|
||||
for (convention, base) in [
|
||||
(PathConvention::Posix, "file:///base/%FF"),
|
||||
(PathConvention::Posix, "file:///base/encoded%2Fname"),
|
||||
(PathConvention::Posix, "file:///C:/base"),
|
||||
(PathConvention::Windows, "file:///base"),
|
||||
(PathConvention::Windows, "file:///C:/encoded%5Cname"),
|
||||
(PathConvention::Windows, "file:///C:/%FF"),
|
||||
(PathConvention::Windows, "file:///C:/base/a:b"),
|
||||
] {
|
||||
let base = PathUri::parse(base).unwrap();
|
||||
assert!(base.validate_config_path(convention).is_err());
|
||||
}
|
||||
let base = PathUri::parse("file:///base").unwrap();
|
||||
let opaque = PathUri::from_opaque_path_bytes(b"/base");
|
||||
for input in ["nul\0", "nul\0/../private", "/nul\0", "~/private"] {
|
||||
assert!(
|
||||
PathUri::resolve_config_path(
|
||||
input,
|
||||
PathConvention::Posix,
|
||||
Some(&base),
|
||||
/*user_home_dir*/ None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
PathUri::resolve_config_path(
|
||||
"child",
|
||||
PathConvention::Posix,
|
||||
Some(&opaque),
|
||||
/*user_home_dir*/ None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
for input in [
|
||||
r"\\server\.\private",
|
||||
r"\\server\..\private",
|
||||
r"\\.\COM1",
|
||||
r"C:\private\file:stream",
|
||||
r"C:\base\a:b\..\private",
|
||||
] {
|
||||
assert!(
|
||||
PathUri::resolve_config_path(
|
||||
input,
|
||||
PathConvention::Windows,
|
||||
/*base*/ None,
|
||||
/*user_home_dir*/ None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let home = PathUri::parse("file:///C:/Users/user").unwrap();
|
||||
for input in [
|
||||
"C:",
|
||||
r"~/\private",
|
||||
r"~\/private",
|
||||
r"\\0x7f000001\share\private",
|
||||
r"\\bücher\share\private",
|
||||
] {
|
||||
assert!(
|
||||
PathUri::resolve_config_path(input, PathConvention::Windows, Some(&home), Some(&home))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
// Unused facts cannot change an already absolute path.
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(
|
||||
"/private",
|
||||
PathConvention::Posix,
|
||||
Some(&opaque),
|
||||
Some(&opaque)
|
||||
),
|
||||
Ok("/private".to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_resolution_rejects_metacharacters_in_used_directory_facts() {
|
||||
for (convention, prefix, separator) in [
|
||||
(PathConvention::Posix, "/home/", "/"),
|
||||
(PathConvention::Windows, r"C:\Users\", r"\"),
|
||||
] {
|
||||
let clean = LegacyAppPathString::from_string(format!("{prefix}sam"))
|
||||
.to_path_uri(convention)
|
||||
.unwrap();
|
||||
for name in ["sam[1]", "sam{1,2}"] {
|
||||
let directory = LegacyAppPathString::from_string(format!("{prefix}{name}"))
|
||||
.to_path_uri(convention)
|
||||
.unwrap();
|
||||
// The directory remains valid as a literal path, and unused facts
|
||||
// cannot reject an absolute pattern supplied by the user.
|
||||
let absolute = format!("{prefix}ordinary{separator}*.key");
|
||||
let literal = format!("{prefix}{name}{separator}private{separator}key");
|
||||
for (input, base, home, expected) in [
|
||||
("private/*.key", &directory, None, None),
|
||||
("~/private/*.key", &clean, Some(&directory), None),
|
||||
("private/key", &directory, None, Some(literal.as_str())),
|
||||
(
|
||||
absolute.as_str(),
|
||||
&directory,
|
||||
Some(&directory),
|
||||
Some(absolute.as_str()),
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(input, convention, Some(base), home)
|
||||
.ok()
|
||||
.as_deref(),
|
||||
expected,
|
||||
"{convention:?}: {name}: {input}",
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path("~/private/*.key", convention, Some(&clean), Some(&clean),),
|
||||
Ok(format!("{prefix}sam{separator}private{separator}*.key")),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_directory_validation_rejects_posix_escape_characters() {
|
||||
let directory = LegacyAppPathString::from_string(r"/home/sam\name")
|
||||
.to_path_uri(PathConvention::Posix)
|
||||
.unwrap();
|
||||
assert!(
|
||||
directory
|
||||
.validate_glob_directory(PathConvention::Posix)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
1044
akode-rs/utils/path-uri/src/lib.rs
Normal file
1044
akode-rs/utils/path-uri/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
51
akode-rs/utils/path-uri/src/native_path_bytes.rs
Normal file
51
akode-rs/utils/path-uri/src/native_path_bytes.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use crate::PathUriParseError;
|
||||
|
||||
impl PathUri {
|
||||
/// Resolves a native path stored as bytes, using this URI's path convention.
|
||||
///
|
||||
/// UTF-8 paths follow [`Self::join`]. Non-UTF-8 POSIX names are preserved
|
||||
/// losslessly, including when the filesystem is on another host. Invalid
|
||||
/// UTF-8 Windows paths, null bytes, and opaque base URIs are rejected.
|
||||
pub fn join_native_bytes(&self, path: &[u8]) -> Result<Self, PathUriParseError> {
|
||||
if let Ok(path) = std::str::from_utf8(path) {
|
||||
return self.join(path);
|
||||
}
|
||||
if self.infer_path_convention() != Some(PathConvention::Posix)
|
||||
|| self.opaque_fallback_bytes().is_some()
|
||||
|| path.contains(&0)
|
||||
{
|
||||
return Err(PathUriParseError::InvalidFileUriPath {
|
||||
path: self.to_string(),
|
||||
});
|
||||
}
|
||||
let mut segments = if path.starts_with(b"/") {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.encoded_path()
|
||||
.split('/')
|
||||
.filter(|segment| !segment.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for component in path.split(|byte| *byte == b'/') {
|
||||
match component {
|
||||
b"" | b"." => {}
|
||||
b".." => {
|
||||
segments.pop();
|
||||
}
|
||||
component => segments.push(urlencoding::encode_binary(component).into_owned()),
|
||||
}
|
||||
}
|
||||
let mut url = self.to_url();
|
||||
url.set_path(&format!("/{}", segments.join("/")));
|
||||
let uri = Self::try_from(url)?;
|
||||
if uri.infer_path_convention() != Some(PathConvention::Posix) {
|
||||
return Err(PathUriParseError::InvalidFileUriPath {
|
||||
path: uri.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(uri)
|
||||
}
|
||||
}
|
||||
51
akode-rs/utils/path-uri/src/platform.rs
Normal file
51
akode-rs/utils/path-uri/src/platform.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
//! Platform identity and its path convention, independent of the resolving host.
|
||||
|
||||
use crate::PathConvention;
|
||||
|
||||
/// Operating system whose paths and execution configuration are being resolved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Platform {
|
||||
Linux,
|
||||
Macos,
|
||||
Windows,
|
||||
/// Missing or unrecognized platform metadata carries no path convention.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
/// Read platform metadata without substituting the current host's platform.
|
||||
pub fn from_platform_os(platform_os: Option<&str>) -> Self {
|
||||
match platform_os {
|
||||
Some("linux") => Self::Linux,
|
||||
Some("macos") => Self::Macos,
|
||||
Some("windows") => Self::Windows,
|
||||
Some(_) | None => Self::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the platform of the current process.
|
||||
pub const fn native() -> Self {
|
||||
if cfg!(target_os = "linux") {
|
||||
Self::Linux
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Self::Macos
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Self::Windows
|
||||
} else {
|
||||
Self::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// Derive path grammar from platform identity while preserving unknown metadata.
|
||||
pub const fn path_convention(self) -> Option<PathConvention> {
|
||||
match self {
|
||||
Self::Linux | Self::Macos => Some(PathConvention::Posix),
|
||||
Self::Windows => Some(PathConvention::Windows),
|
||||
Self::Unknown => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "platform_tests.rs"]
|
||||
mod tests;
|
||||
43
akode-rs/utils/path-uri/src/platform_tests.rs
Normal file
43
akode-rs/utils/path-uri/src/platform_tests.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Coverage for platform metadata and platform-derived path conventions.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn platform_metadata_preserves_missing_and_unrecognized_values() {
|
||||
for (metadata, expected) in [
|
||||
(Some("linux"), Platform::Linux),
|
||||
(Some("macos"), Platform::Macos),
|
||||
(Some("windows"), Platform::Windows),
|
||||
(None, Platform::Unknown),
|
||||
(Some("freebsd"), Platform::Unknown),
|
||||
(Some("Windows"), Platform::Unknown),
|
||||
(Some(""), Platform::Unknown),
|
||||
] {
|
||||
assert_eq!(
|
||||
Platform::from_platform_os(metadata),
|
||||
expected,
|
||||
"{metadata:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_convention_is_derived_from_platform() {
|
||||
for (platform, expected) in [
|
||||
(Platform::Linux, Some(PathConvention::Posix)),
|
||||
(Platform::Macos, Some(PathConvention::Posix)),
|
||||
(Platform::Windows, Some(PathConvention::Windows)),
|
||||
(Platform::Unknown, None),
|
||||
] {
|
||||
assert_eq!(platform.path_convention(), expected, "{platform:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_platform_matches_current_process_metadata() {
|
||||
assert_eq!(
|
||||
Platform::native(),
|
||||
Platform::from_platform_os(Some(std::env::consts::OS)),
|
||||
);
|
||||
}
|
||||
1427
akode-rs/utils/path-uri/src/tests.rs
Normal file
1427
akode-rs/utils/path-uri/src/tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
6
akode-rs/utils/path-utils/BUILD.bazel
Normal file
6
akode-rs/utils/path-utils/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "path-utils",
|
||||
crate_name = "akode_utils_path",
|
||||
)
|
||||
27
akode-rs/utils/path-utils/Cargo.toml
Normal file
27
akode-rs/utils/path-utils/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-utils-path"
|
||||
version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
dunce = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_UI_Shell",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
19
akode-rs/utils/path-utils/src/env.rs
Normal file
19
akode-rs/utils/path-utils/src/env.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
//! Functions for environment detection that need to be shared across crates.
|
||||
|
||||
/// Returns true if the current process is running under Windows Subsystem for Linux.
|
||||
pub fn is_wsl() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if std::env::var_os("WSL_DISTRO_NAME").is_some() {
|
||||
return true;
|
||||
}
|
||||
match std::fs::read_to_string("/proc/version") {
|
||||
Ok(version) => version.to_lowercase().contains("microsoft"),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
252
akode-rs/utils/path-utils/src/lib.rs
Normal file
252
akode-rs/utils/path-utils/src/lib.rs
Normal file
@@ -0,0 +1,252 @@
|
||||
//! Path normalization, replacement, metadata inspection, symlink resolution, and atomic writes.
|
||||
|
||||
pub(crate) mod env;
|
||||
pub use env::is_wsl;
|
||||
mod system_commands;
|
||||
pub use system_commands::system_executable;
|
||||
pub use system_commands::system_path;
|
||||
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::collections::HashSet;
|
||||
use std::hash::Hash;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
/// Read metadata without following the final symlink, returning `None` for a missing path.
|
||||
/// Other I/O errors are returned to the caller.
|
||||
pub fn symlink_metadata_if_exists(path: &Path) -> io::Result<Option<std::fs::Metadata>> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) => Ok(Some(metadata)),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_for_path_comparison(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
|
||||
let canonical = path.as_ref().canonicalize()?;
|
||||
Ok(normalize_for_wsl(canonical))
|
||||
}
|
||||
|
||||
/// Compare paths after applying Codex's filesystem normalization.
|
||||
///
|
||||
/// If either path cannot be normalized, this falls back to direct path equality.
|
||||
pub fn paths_match_after_normalization(left: impl AsRef<Path>, right: impl AsRef<Path>) -> bool {
|
||||
if let (Ok(left), Ok(right)) = (
|
||||
normalize_for_path_comparison(left.as_ref()),
|
||||
normalize_for_path_comparison(right.as_ref()),
|
||||
) {
|
||||
return left == right;
|
||||
}
|
||||
left.as_ref() == right.as_ref()
|
||||
}
|
||||
|
||||
/// Replace paths equal to `old_path` and remove duplicates, preserving their order.
|
||||
///
|
||||
/// Other paths, including descendants of `old_path`, remain unchanged. This uses
|
||||
/// path equality without filesystem access or normalization; callers validate paths.
|
||||
pub fn replace_path_and_deduplicate<P>(mut paths: Vec<P>, old_path: &Path, new_path: P) -> Vec<P>
|
||||
where
|
||||
P: AsRef<Path> + Clone + Eq + Hash,
|
||||
{
|
||||
for path in &mut paths {
|
||||
if path.as_ref() == old_path {
|
||||
*path = new_path.clone();
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
paths.retain(|path| seen.insert(path.clone()));
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn normalize_for_native_workdir(path: impl AsRef<Path>) -> PathBuf {
|
||||
normalize_for_native_workdir_with_flag(path.as_ref().to_path_buf(), cfg!(windows))
|
||||
}
|
||||
|
||||
pub struct SymlinkWritePaths {
|
||||
pub read_path: Option<PathBuf>,
|
||||
pub write_path: PathBuf,
|
||||
}
|
||||
|
||||
/// Resolve the final filesystem target for `path` while retaining a safe write path.
|
||||
///
|
||||
/// This follows symlink chains (including relative symlink targets) until it reaches a
|
||||
/// non-symlink path. If the chain cycles or any metadata/link resolution fails, it
|
||||
/// returns `read_path: None` and uses the original absolute path as `write_path`.
|
||||
/// There is no fixed max-resolution count; cycles are detected via a visited set.
|
||||
pub fn resolve_symlink_write_paths(path: &Path) -> io::Result<SymlinkWritePaths> {
|
||||
let root = AbsolutePathBuf::from_absolute_path(path)
|
||||
.map(AbsolutePathBuf::into_path_buf)
|
||||
.unwrap_or_else(|_| path.to_path_buf());
|
||||
let mut current = root.clone();
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
// Follow symlink chains while guarding against cycles.
|
||||
loop {
|
||||
let meta = match std::fs::symlink_metadata(¤t) {
|
||||
Ok(meta) => meta,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: Some(current.clone()),
|
||||
write_path: current,
|
||||
});
|
||||
}
|
||||
Err(_) => {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: None,
|
||||
write_path: root,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if !meta.file_type().is_symlink() {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: Some(current.clone()),
|
||||
write_path: current,
|
||||
});
|
||||
}
|
||||
|
||||
// If we've already seen this path, the chain cycles.
|
||||
if !visited.insert(current.clone()) {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: None,
|
||||
write_path: root,
|
||||
});
|
||||
}
|
||||
|
||||
let target = match std::fs::read_link(¤t) {
|
||||
Ok(target) => target,
|
||||
Err(_) => {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: None,
|
||||
write_path: root,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let next = if target.is_absolute() {
|
||||
AbsolutePathBuf::from_absolute_path(&target)
|
||||
} else if let Some(parent) = current.parent() {
|
||||
Ok(AbsolutePathBuf::resolve_path_against_base(&target, parent))
|
||||
} else {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: None,
|
||||
write_path: root,
|
||||
});
|
||||
};
|
||||
|
||||
let next = match next {
|
||||
Ok(path) => path.into_path_buf(),
|
||||
Err(_) => {
|
||||
return Ok(SymlinkWritePaths {
|
||||
read_path: None,
|
||||
write_path: root,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
|
||||
let parent = write_path.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path {} has no parent directory", write_path.display()),
|
||||
)
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let mut tmp = NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(contents.as_bytes())?;
|
||||
tmp.persist(write_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn normalize_for_wsl(path: PathBuf) -> PathBuf {
|
||||
normalize_for_wsl_with_flag(path, env::is_wsl())
|
||||
}
|
||||
|
||||
fn normalize_for_native_workdir_with_flag(path: PathBuf, is_windows: bool) -> PathBuf {
|
||||
if is_windows {
|
||||
dunce::simplified(&path).to_path_buf()
|
||||
} else {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_for_wsl_with_flag(path: PathBuf, is_wsl: bool) -> PathBuf {
|
||||
if !is_wsl {
|
||||
return path;
|
||||
}
|
||||
|
||||
if !is_wsl_case_insensitive_path(&path) {
|
||||
return path;
|
||||
}
|
||||
|
||||
lower_ascii_path(path)
|
||||
}
|
||||
|
||||
fn is_wsl_case_insensitive_path(path: &Path) -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::Component;
|
||||
|
||||
let mut components = path.components();
|
||||
let Some(Component::RootDir) = components.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(Component::Normal(mnt)) = components.next() else {
|
||||
return false;
|
||||
};
|
||||
if !ascii_eq_ignore_case(mnt.as_bytes(), b"mnt") {
|
||||
return false;
|
||||
}
|
||||
let Some(Component::Normal(drive)) = components.next() else {
|
||||
return false;
|
||||
};
|
||||
let drive_bytes = drive.as_bytes();
|
||||
drive_bytes.len() == 1 && drive_bytes[0].is_ascii_alphabetic()
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn ascii_eq_ignore_case(left: &[u8], right: &[u8]) -> bool {
|
||||
left.len() == right.len()
|
||||
&& left
|
||||
.iter()
|
||||
.zip(right)
|
||||
.all(|(lhs, rhs)| lhs.to_ascii_lowercase() == *rhs)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn lower_ascii_path(path: PathBuf) -> PathBuf {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
// WSL mounts Windows drives under /mnt/<drive>, which are case-insensitive.
|
||||
let bytes = path.as_os_str().as_bytes();
|
||||
let mut lowered = Vec::with_capacity(bytes.len());
|
||||
for byte in bytes {
|
||||
lowered.push(byte.to_ascii_lowercase());
|
||||
}
|
||||
PathBuf::from(OsString::from_vec(lowered))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn lower_ascii_path(path: PathBuf) -> PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "path_utils_tests.rs"]
|
||||
mod tests;
|
||||
180
akode-rs/utils/path-utils/src/path_utils_tests.rs
Normal file
180
akode-rs/utils/path-utils/src/path_utils_tests.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
use super::replace_path_and_deduplicate;
|
||||
use super::symlink_metadata_if_exists;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn symlink_metadata_if_exists_distinguishes_files_directories_and_missing_paths()
|
||||
-> std::io::Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let file = directory.path().join("file");
|
||||
std::fs::write(&file, "contents")?;
|
||||
|
||||
let directory_metadata =
|
||||
symlink_metadata_if_exists(directory.path())?.expect("directory exists");
|
||||
let file_metadata = symlink_metadata_if_exists(&file)?.expect("file exists");
|
||||
assert_eq!(
|
||||
(directory_metadata.is_dir(), file_metadata.is_file()),
|
||||
(true, true)
|
||||
);
|
||||
assert!(symlink_metadata_if_exists(&directory.path().join("missing"))?.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symlink_metadata_if_exists_preserves_io_errors() {
|
||||
let error = symlink_metadata_if_exists(Path::new("invalid\0path"))
|
||||
.expect_err("an invalid path must not be treated as missing");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_path_and_deduplicate_preserves_other_paths_and_order() {
|
||||
let old_path = Path::new("old");
|
||||
let new_path = Path::new("new");
|
||||
let extra = Path::new("extra");
|
||||
let descendant = Path::new("old/child");
|
||||
|
||||
assert_eq!(
|
||||
replace_path_and_deduplicate(
|
||||
vec![old_path, extra, descendant, new_path, extra],
|
||||
old_path,
|
||||
new_path,
|
||||
),
|
||||
vec![new_path, extra, descendant]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod symlinks {
|
||||
use super::super::resolve_symlink_write_paths;
|
||||
use super::super::symlink_metadata_if_exists;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
#[test]
|
||||
fn symlink_metadata_if_exists_preserves_links_with_and_without_targets() -> std::io::Result<()>
|
||||
{
|
||||
let directory = tempfile::tempdir()?;
|
||||
let target = directory.path().join("target");
|
||||
let link = directory.path().join("link");
|
||||
std::fs::write(&target, "contents")?;
|
||||
symlink(&target, &link)?;
|
||||
|
||||
let linked_metadata = symlink_metadata_if_exists(&link)?.expect("symlink exists");
|
||||
std::fs::remove_file(target)?;
|
||||
let dangling_metadata = symlink_metadata_if_exists(&link)?.expect("symlink still exists");
|
||||
assert!(linked_metadata.is_symlink());
|
||||
assert_eq!(dangling_metadata.file_type(), linked_metadata.file_type());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symlink_cycles_fall_back_to_root_write_path() -> std::io::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let a = dir.path().join("a");
|
||||
let b = dir.path().join("b");
|
||||
|
||||
symlink(&b, &a)?;
|
||||
symlink(&a, &b)?;
|
||||
|
||||
let resolved = resolve_symlink_write_paths(&a)?;
|
||||
|
||||
assert_eq!(resolved.read_path, None);
|
||||
assert_eq!(resolved.write_path, a);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod wsl {
|
||||
use super::super::normalize_for_wsl_with_flag;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn wsl_mnt_drive_paths_lowercase() {
|
||||
let normalized =
|
||||
normalize_for_wsl_with_flag(PathBuf::from("/mnt/C/Users/Dev"), /*is_wsl*/ true);
|
||||
|
||||
assert_eq!(normalized, PathBuf::from("/mnt/c/users/dev"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_non_drive_paths_unchanged() {
|
||||
let path = PathBuf::from("/mnt/cc/Users/Dev");
|
||||
let normalized = normalize_for_wsl_with_flag(path.clone(), /*is_wsl*/ true);
|
||||
|
||||
assert_eq!(normalized, path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_non_mnt_paths_unchanged() {
|
||||
let path = PathBuf::from("/home/Dev");
|
||||
let normalized = normalize_for_wsl_with_flag(path.clone(), /*is_wsl*/ true);
|
||||
|
||||
assert_eq!(normalized, path);
|
||||
}
|
||||
}
|
||||
|
||||
mod native_workdir {
|
||||
use super::super::normalize_for_native_workdir_with_flag;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn windows_verbatim_paths_are_simplified() {
|
||||
let path = PathBuf::from(r"\\?\D:\c\x\worktrees\2508\swift-base");
|
||||
let normalized = normalize_for_native_workdir_with_flag(path, /*is_windows*/ true);
|
||||
|
||||
assert_eq!(
|
||||
normalized,
|
||||
PathBuf::from(r"D:\c\x\worktrees\2508\swift-base")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_windows_paths_are_unchanged() {
|
||||
let path = PathBuf::from(r"\\?\D:\c\x\worktrees\2508\swift-base");
|
||||
let normalized =
|
||||
normalize_for_native_workdir_with_flag(path.clone(), /*is_windows*/ false);
|
||||
|
||||
assert_eq!(normalized, path);
|
||||
}
|
||||
}
|
||||
|
||||
mod path_comparison {
|
||||
use super::super::paths_match_after_normalization;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn matches_identical_existing_paths() -> std::io::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
|
||||
assert!(paths_match_after_normalization(dir.path(), dir.path()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_raw_equality_when_paths_cannot_be_normalized() {
|
||||
assert!(paths_match_after_normalization(
|
||||
PathBuf::from("missing"),
|
||||
PathBuf::from("missing"),
|
||||
));
|
||||
assert!(!paths_match_after_normalization(
|
||||
PathBuf::from("missing-a"),
|
||||
PathBuf::from("missing-b"),
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn matches_windows_verbatim_paths() -> std::io::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let verbatim_dir = PathBuf::from(format!(r"\\?\{}", dir.path().display()));
|
||||
|
||||
assert!(paths_match_after_normalization(verbatim_dir, dir.path()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
166
akode-rs/utils/path-utils/src/system_commands.rs
Normal file
166
akode-rs/utils/path-utils/src/system_commands.rs
Normal file
@@ -0,0 +1,166 @@
|
||||
//! Installed helper discovery for automatic work before workspace trust.
|
||||
//!
|
||||
//! Only OS and conventional package-manager locations are trusted, never ambient
|
||||
//! PATH or the working directory. Nix system profiles must resolve into the
|
||||
//! trusted store. Custom installations fall back to no helper.
|
||||
//! This assumes the installed software directories themselves are trusted; it
|
||||
//! does not defend against an attacker who can modify system installations.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Finds an installed helper without consulting PATH, PATHEXT, or the working directory.
|
||||
pub fn system_executable(name: &str) -> Option<PathBuf> {
|
||||
executable_in_directories(name, &system_directories())
|
||||
}
|
||||
|
||||
/// Child-process PATH for automatic helpers, not for user-requested tools.
|
||||
pub fn system_path() -> std::io::Result<OsString> {
|
||||
let directories = system_directories();
|
||||
if directories.is_empty() {
|
||||
return Err(std::io::Error::other("no trusted executable directories"));
|
||||
}
|
||||
std::env::join_paths(directories).map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
fn executable_in_directories(name: &str, directories: &[PathBuf]) -> Option<PathBuf> {
|
||||
// Do not allow callers to accidentally escape the installation directories.
|
||||
if Path::new(name).file_name() != Some(std::ffi::OsStr::new(name)) {
|
||||
return None;
|
||||
}
|
||||
let name = format!("{name}{}", std::env::consts::EXE_SUFFIX);
|
||||
directories.iter().find_map(|directory| {
|
||||
let executable = dunce::canonicalize(directory.join(&name)).ok()?;
|
||||
// A symlink into a workspace is not an installed executable. Package
|
||||
// manager links may target sibling libexec/Cellar directories.
|
||||
let installed = directories.iter().any(|root| executable.starts_with(root))
|
||||
|| installation_roots()
|
||||
.iter()
|
||||
.any(|root| executable.starts_with(root));
|
||||
if !installed || !executable.is_file() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if executable.metadata().ok()?.permissions().mode() & 0o111 == 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(executable)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn installation_roots() -> Vec<PathBuf> {
|
||||
[
|
||||
"/usr/bin",
|
||||
"/bin",
|
||||
"/usr/sbin",
|
||||
"/sbin",
|
||||
"/usr/local",
|
||||
"/opt/homebrew",
|
||||
"/opt/local",
|
||||
"/Library/Developer/CommandLineTools",
|
||||
"/Applications/Xcode.app/Contents/Developer",
|
||||
"/nix/store",
|
||||
"/mnt/c/Windows/System32",
|
||||
]
|
||||
.into_iter()
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn system_directories() -> Vec<PathBuf> {
|
||||
#[cfg(unix)]
|
||||
let directories = [
|
||||
"/opt/homebrew/bin",
|
||||
"/usr/local/bin",
|
||||
"/opt/local/bin",
|
||||
"/run/current-system/sw/bin",
|
||||
"/nix/var/nix/profiles/default/bin",
|
||||
"/Library/Developer/CommandLineTools/usr/bin",
|
||||
"/Applications/Xcode.app/Contents/Developer/usr/bin",
|
||||
"/usr/bin",
|
||||
"/bin",
|
||||
"/usr/sbin",
|
||||
"/sbin",
|
||||
]
|
||||
.into_iter()
|
||||
.map(PathBuf::from);
|
||||
#[cfg(target_os = "linux")]
|
||||
let directories = directories.chain(
|
||||
crate::is_wsl()
|
||||
.then_some([
|
||||
PathBuf::from("/mnt/c/Windows/System32"),
|
||||
PathBuf::from("/mnt/c/Windows/System32/WindowsPowerShell/v1.0"),
|
||||
])
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
);
|
||||
#[cfg(windows)]
|
||||
let directories = installation_roots().into_iter().flat_map(|root| {
|
||||
vec![
|
||||
root.join("Git/cmd"),
|
||||
root.join("Git/mingw64/bin"),
|
||||
root.join("Git/usr/bin"),
|
||||
root,
|
||||
]
|
||||
});
|
||||
let roots = installation_roots();
|
||||
directories
|
||||
.filter_map(|directory| dunce::canonicalize(directory).ok())
|
||||
.filter(|directory| roots.iter().any(|root| directory.starts_with(root)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn installation_roots() -> Vec<PathBuf> {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use windows_sys::Win32::System::Com::CoTaskMemFree;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFiles;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFilesX86;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_System;
|
||||
use windows_sys::Win32::UI::Shell::KF_FLAG_DEFAULT_PATH;
|
||||
use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath;
|
||||
|
||||
[
|
||||
FOLDERID_ProgramFiles,
|
||||
FOLDERID_ProgramFilesX86,
|
||||
FOLDERID_System,
|
||||
]
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let mut path = std::ptr::null_mut();
|
||||
// SAFETY: the API writes a CoTaskMem-allocated, NUL-terminated UTF-16 path.
|
||||
let result = unsafe {
|
||||
SHGetKnownFolderPath(
|
||||
id,
|
||||
KF_FLAG_DEFAULT_PATH as u32,
|
||||
std::ptr::null_mut(),
|
||||
&mut path,
|
||||
)
|
||||
};
|
||||
if result != 0 || path.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: success guarantees the string; free it after copying.
|
||||
let directory = unsafe {
|
||||
let mut len = 0;
|
||||
while *path.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
let directory =
|
||||
PathBuf::from(OsString::from_wide(std::slice::from_raw_parts(path, len)));
|
||||
CoTaskMemFree(path.cast());
|
||||
directory
|
||||
};
|
||||
dunce::canonicalize(directory).ok()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "system_commands_tests.rs"]
|
||||
mod tests;
|
||||
31
akode-rs/utils/path-utils/src/system_commands_tests.rs
Normal file
31
akode-rs/utils/path-utils/src/system_commands_tests.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn resolves_only_executables_inside_installation_directories() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let bin = root.path().join("bin");
|
||||
std::fs::create_dir(&bin).unwrap();
|
||||
let executable = bin.join(format!("helper{}", std::env::consts::EXE_SUFFIX));
|
||||
std::fs::write(&executable, "installed helper").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(/*mode*/ 0o755))
|
||||
.unwrap();
|
||||
}
|
||||
let directories = vec![dunce::canonicalize(bin).unwrap()];
|
||||
assert_eq!(
|
||||
executable_in_directories("helper", &directories),
|
||||
Some(dunce::canonicalize(&executable).unwrap())
|
||||
);
|
||||
assert_eq!(executable_in_directories("../helper", &directories), None);
|
||||
assert_eq!(executable_in_directories("missing", &directories), None);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let outside = root.path().join("outside");
|
||||
std::fs::rename(&executable, &outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &executable).unwrap();
|
||||
assert_eq!(executable_in_directories("helper", &directories), None);
|
||||
}
|
||||
}
|
||||
6
akode-rs/utils/plugins/BUILD.bazel
Normal file
6
akode-rs/utils/plugins/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "plugins",
|
||||
crate_name = "akode_utils_plugins",
|
||||
)
|
||||
26
akode-rs/utils/plugins/Cargo.toml
Normal file
26
akode-rs/utils/plugins/Cargo.toml
Normal file
@@ -0,0 +1,26 @@
|
||||
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-utils-plugins"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_utils_plugins"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-exec-server = { workspace = true }
|
||||
akode-exec-server-protocol = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
akode-utils-path-uri = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
52
akode-rs/utils/plugins/src/lib.rs
Normal file
52
akode-rs/utils/plugins/src/lib.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
//! Plugin path resolution, plaintext mention sigils, and MCP connector helpers shared across Codex
|
||||
//! crates.
|
||||
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
pub mod mcp_connector;
|
||||
pub mod mention_syntax;
|
||||
pub mod plugin_namespace;
|
||||
|
||||
pub use akode_exec_server_protocol::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
|
||||
pub use plugin_namespace::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
|
||||
pub use plugin_namespace::AGENT_PLUGIN_SCHEMA_PREFIX;
|
||||
pub use plugin_namespace::AGENT_PLUGIN_SCHEMA_URI;
|
||||
pub use plugin_namespace::AgentPluginSchemaStatus;
|
||||
pub use plugin_namespace::SUPPORTED_AGENT_PLUGIN_SCHEMA_URIS;
|
||||
pub use plugin_namespace::agent_plugin_schema_status;
|
||||
pub use plugin_namespace::find_plugin_manifest_path;
|
||||
pub use plugin_namespace::plugin_namespace_for_root_uri;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub enum SkillDiscoveryMode {
|
||||
#[default]
|
||||
Recursive,
|
||||
DirectChildren,
|
||||
}
|
||||
|
||||
/// The local identifier for a plugin.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct PluginIdentity {
|
||||
pub plugin_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct PluginSkillRoot {
|
||||
pub path: AbsolutePathBuf,
|
||||
pub plugin_identity: PluginIdentity,
|
||||
pub plugin_namespace: String,
|
||||
pub plugin_root: AbsolutePathBuf,
|
||||
pub discovery_mode: SkillDiscoveryMode,
|
||||
}
|
||||
|
||||
/// Directory containing private plugin metadata.
|
||||
const PLUGIN_METADATA_DIR: &str = ".codex-plugin";
|
||||
/// Directory containing commands converted into skills during plugin installation.
|
||||
const MIGRATED_COMMAND_SKILLS_DIR: &str = "migrated-command-skills";
|
||||
|
||||
/// Returns the install-time command migration output directory for a plugin.
|
||||
pub fn migrated_command_skills_root(plugin_root: &AbsolutePathBuf) -> AbsolutePathBuf {
|
||||
plugin_root
|
||||
.join(PLUGIN_METADATA_DIR)
|
||||
.join(MIGRATED_COMMAND_SKILLS_DIR)
|
||||
}
|
||||
20
akode-rs/utils/plugins/src/mcp_connector.rs
Normal file
20
akode-rs/utils/plugins/src/mcp_connector.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
pub fn sanitize_name(name: &str) -> String {
|
||||
sanitize_slug(name).replace("-", "_")
|
||||
}
|
||||
|
||||
fn sanitize_slug(name: &str) -> String {
|
||||
let mut normalized = String::with_capacity(name.len());
|
||||
for character in name.chars() {
|
||||
if character.is_ascii_alphanumeric() {
|
||||
normalized.push(character.to_ascii_lowercase());
|
||||
} else {
|
||||
normalized.push('-');
|
||||
}
|
||||
}
|
||||
let normalized = normalized.trim_matches('-');
|
||||
if normalized.is_empty() {
|
||||
"app".to_string()
|
||||
} else {
|
||||
normalized.to_string()
|
||||
}
|
||||
}
|
||||
7
akode-rs/utils/plugins/src/mention_syntax.rs
Normal file
7
akode-rs/utils/plugins/src/mention_syntax.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
//! Sigils for tool/plugin mentions in plaintext (shared across Codex crates).
|
||||
|
||||
/// Default plaintext sigil for tools.
|
||||
pub const TOOL_MENTION_SIGIL: char = '$';
|
||||
|
||||
/// Plugins use `@` in linked plaintext outside TUI.
|
||||
pub const PLUGIN_TEXT_MENTION_SIGIL: char = '@';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user