Vendor Codex and land Phase 1 Epiphany state slice

This commit is contained in:
Meta Vens 2026-04-23 23:20:16 +01:00
commit 2042687e30
3959 changed files with 953751 additions and 7 deletions

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "absolute-path",
crate_name = "codex_utils_absolute_path",
)

View file

@ -0,0 +1,24 @@
[package]
name = "codex-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 }

View 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")
);
}
}

View file

@ -0,0 +1,617 @@
use dirs::home_dir;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::de::Error as SerdeError;
use std::cell::RefCell;
use std::path::Display;
use std::path::Path;
use std::path::PathBuf;
use ts_rs::TS;
mod absolutize;
/// 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(home) = home_dir()
&& let Some(rest) = path_str.strip_prefix('~')
{
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());
Self(absolutize::absolutize_from(&expanded, 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());
Ok(Self(absolutize::absolutize(&expanded)?))
}
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());
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, Path::new("/"))))
}
pub fn current_dir() -> std::io::Result<Self> {
let current_dir = std::env::current_dir()?;
Ok(Self(absolutize::absolutize_from(
&current_dir,
&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> {
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()
}
}
/// 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) };
}
/// 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 {
pub fn new(base_path: &Path) -> Self {
ABSOLUTE_PATH_BASE.with(|cell| {
*cell.borrow_mut() = Some(base_path.to_path_buf());
});
Self
}
}
impl Drop for AbsolutePathBufGuard {
fn drop(&mut self) {
ABSOLUTE_PATH_BASE.with(|cell| {
*cell.borrow_mut() = None;
});
}
}
impl<'de> Deserialize<'de> for AbsolutePathBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let path = PathBuf::deserialize(deserializer)?;
ABSOLUTE_PATH_BASE.with(|cell| match cell.borrow().as_deref() {
Some(base) => Ok(Self::resolve_path_against_base(path, base)),
None if path.is_absolute() => {
Self::from_absolute_path(path).map_err(SerdeError::custom)
}
None => Err(SerdeError::custom(
"AbsolutePathBuf deserialized without a base path",
)),
})
}
}
#[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 from_absolute_path_does_not_read_current_dir_when_path_is_absolute() {
let status = Command::new(std::env::current_exe().expect("current test binary"))
.arg("from_absolute_path_with_removed_current_dir_child")
.arg("--ignored")
.env("CODEX_ABSOLUTE_PATH_REMOVED_CWD_CHILD", "1")
.status()
.expect("run child test");
assert!(status.success());
}
#[cfg(unix)]
#[test]
#[ignore]
fn from_absolute_path_with_removed_current_dir_child() {
if std::env::var_os("CODEX_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");
std::env::set_current_dir(original_cwd).expect("restore cwd");
assert_eq!(
path.as_path(),
test_path_buf("/tmp/codex-home/plugins/cache")
);
}
#[test]
fn from_absolute_path_checked_rejects_relative_path() {
let err = AbsolutePathBuf::from_absolute_path_checked("relative/path")
.expect_err("relative path should fail");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
}
#[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 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:?}"
);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "approval-presets",
crate_name = "codex_utils_approval_presets",
)

View file

@ -0,0 +1,11 @@
[package]
name = "codex-utils-approval-presets"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
codex-protocol = { workspace = true }

View file

@ -0,0 +1,46 @@
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SandboxPolicy;
/// A simple preset pairing an approval policy with a sandbox policy.
#[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,
/// Sandbox policy to apply.
pub sandbox: SandboxPolicy,
}
/// Built-in list of approval presets that pair approval and sandbox policy.
///
/// 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: "Codex can read files in the current workspace. Approval is required to edit files or access the internet.",
approval: AskForApproval::OnRequest,
sandbox: SandboxPolicy::new_read_only_policy(),
},
ApprovalPreset {
id: "auto",
label: "Default",
description: "Codex 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,
sandbox: SandboxPolicy::new_workspace_write_policy(),
},
ApprovalPreset {
id: "full-access",
label: "Full Access",
description: "Codex can edit files outside this workspace and access the internet without asking for approval. Exercise caution when using.",
approval: AskForApproval::Never,
sandbox: SandboxPolicy::DangerFullAccess,
},
]
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "cache",
crate_name = "codex_utils_cache",
)

View file

@ -0,0 +1,16 @@
[package]
name = "codex-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"] }

View file

@ -0,0 +1,193 @@
use std::borrow::Borrow;
use std::hash::Hash;
use std::num::NonZeroUsize;
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)
}
}
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)]
mod tests {
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());
}
}

View 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",
crate_name = "codex_utils_cargo_bin",
compile_data = ["repo_root.marker"],
lib_data_extra = ["repo_root.marker"],
test_data_extra = ["repo_root.marker"],
rustc_env = {
"CODEX_REPO_ROOT_MARKER": "$(rlocationpath :repo_root.marker)",
},
)

View file

@ -0,0 +1,13 @@
[package]
name = "codex-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 }

View file

@ -0,0 +1,20 @@
# codex-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 `codex-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

View file

@ -0,0 +1 @@

View file

@ -0,0 +1,226 @@
use std::ffi::OsString;
use std::io;
use std::path::Path;
use std::path::PathBuf;
pub use runfiles;
/// 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(resolved) = runfiles::rlocation!(runfiles, &raw)
&& 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!("CODEX_REPO_ROOT_MARKER")
.map(PathBuf::from)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"CODEX_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
})
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "cli",
crate_name = "codex_utils_cli",
)

View file

@ -0,0 +1,17 @@
[package]
name = "codex-utils-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
clap = { workspace = true, features = ["derive", "wrap_help"] }
codex-protocol = { workspace = true }
serde = { workspace = true }
toml = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }

View file

@ -0,0 +1,38 @@
//! Standard type to use with the `--approval-mode` CLI option.
use clap::ValueEnum;
use codex_protocol::protocol::AskForApproval;
#[derive(Clone, Copy, Debug, ValueEnum)]
#[value(rename_all = "kebab-case")]
pub enum ApprovalModeCliArg {
/// Only run "trusted" commands (e.g. ls, cat, sed) without asking for user
/// approval. Will escalate to the user if the model proposes a command that
/// is not in the "trusted" set.
Untrusted,
/// DEPRECATED: Run all commands without asking for user approval.
/// Only asks for approval if a command fails to execute, in which case it
/// will escalate to the user to ask for un-sandboxed execution.
/// Prefer `on-request` for interactive runs or `never` for non-interactive runs.
OnFailure,
/// 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::Untrusted => AskForApproval::UnlessTrusted,
ApprovalModeCliArg::OnFailure => AskForApproval::OnFailure,
ApprovalModeCliArg::OnRequest => AskForApproval::OnRequest,
ApprovalModeCliArg::Never => AskForApproval::Never,
}
}
}

View file

@ -0,0 +1,200 @@
//! 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
/// `~/.codex/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 {
/// 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()
}
/// Apply all parsed overrides onto `target`. Intermediate objects will be
/// created as necessary. Values located at the destination path will be
/// replaced.
pub fn apply_on_value(&self, target: &mut Value) -> Result<(), String> {
let overrides = self.parse_overrides()?;
for (path, value) in overrides {
apply_single_override(target, &path, value);
}
Ok(())
}
}
fn canonicalize_override_key(key: &str) -> String {
if key == "use_legacy_landlock" {
"features.use_legacy_landlock".to_string()
} else {
key.to_string()
}
}
/// Apply a single override onto `root`, creating intermediate objects as
/// necessary.
fn apply_single_override(root: &mut Value, path: &str, value: Value) {
use toml::value::Table;
let parts: Vec<&str> = path.split('.').collect();
let mut current = root;
for (i, part) in parts.iter().enumerate() {
let is_last = i == parts.len() - 1;
if is_last {
match current {
Value::Table(tbl) => {
tbl.insert((*part).to_string(), value);
}
_ => {
let mut tbl = Table::new();
tbl.insert((*part).to_string(), value);
*current = Value::Table(tbl);
}
}
return;
}
// Traverse or create intermediate table.
match current {
Value::Table(tbl) => {
current = tbl
.entry((*part).to_string())
.or_insert_with(|| Value::Table(Table::new()));
}
_ => {
*current = Value::Table(Table::new());
if let Value::Table(tbl) = current {
current = tbl
.entry((*part).to_string())
.or_insert_with(|| Value::Table(Table::new()));
}
}
}
}
}
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"))
}
#[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 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));
}
}

View 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(|(a, _), (b, _)| a.cmp(b));
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=*****"
);
}
}

View file

@ -0,0 +1,11 @@
mod approval_mode_cli_arg;
mod config_override;
pub(crate) mod format_env_display;
mod sandbox_mode_cli_arg;
mod shared_options;
pub use approval_mode_cli_arg::ApprovalModeCliArg;
pub use config_override::CliConfigOverrides;
pub use format_env_display::format_env_display;
pub use sandbox_mode_cli_arg::SandboxModeCliArg;
pub use shared_options::SharedCliOptions;

View file

@ -0,0 +1,47 @@
//! Standard type to use with the `--sandbox` (`-s`) CLI option.
//!
//! This mirrors the variants of [`codex_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 codex_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()
);
}
}

View file

@ -0,0 +1,174 @@
//! Shared command-line flags used by both interactive and non-interactive Codex entry points.
use crate::SandboxModeCliArg;
use clap::Args;
use std::path::PathBuf;
#[derive(Args, 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>,
/// Configuration profile from config.toml to specify default options.
#[arg(long = "profile", short = 'p')]
pub config_profile: Option<String>,
/// Select the sandbox policy to use when executing model-generated shell
/// commands.
#[arg(long = "sandbox", short = 's')]
pub sandbox_mode: Option<SandboxModeCliArg>,
/// Convenience alias for low-friction sandboxed automatic execution.
#[arg(long = "full-auto", default_value_t = false)]
pub full_auto: 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,
conflicts_with = "full_auto"
)]
pub dangerously_bypass_approvals_and_sandbox: 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>,
/// 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 inherit_exec_root_options(&mut self, root: &Self) {
let self_selected_sandbox_mode = self.sandbox_mode.is_some()
|| self.full_auto
|| self.dangerously_bypass_approvals_and_sandbox;
let Self {
images,
model,
oss,
oss_provider,
config_profile,
sandbox_mode,
full_auto,
dangerously_bypass_approvals_and_sandbox,
cwd,
add_dir,
} = self;
let Self {
images: root_images,
model: root_model,
oss: root_oss,
oss_provider: root_oss_provider,
config_profile: root_config_profile,
sandbox_mode: root_sandbox_mode,
full_auto: root_full_auto,
dangerously_bypass_approvals_and_sandbox: root_dangerously_bypass_approvals_and_sandbox,
cwd: root_cwd,
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.is_none() {
config_profile.clone_from(root_config_profile);
}
if sandbox_mode.is_none() {
*sandbox_mode = *root_sandbox_mode;
}
if !self_selected_sandbox_mode {
*full_auto = *root_full_auto;
*dangerously_bypass_approvals_and_sandbox =
*root_dangerously_bypass_approvals_and_sandbox;
}
if cwd.is_none() {
cwd.clone_from(root_cwd);
}
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.full_auto
|| subcommand.dangerously_bypass_approvals_and_sandbox;
let Self {
images,
model,
oss,
oss_provider,
config_profile,
sandbox_mode,
full_auto,
dangerously_bypass_approvals_and_sandbox,
cwd,
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) = config_profile {
self.config_profile = Some(config_profile);
}
if subcommand_selected_sandbox_mode {
self.sandbox_mode = sandbox_mode;
self.full_auto = full_auto;
self.dangerously_bypass_approvals_and_sandbox =
dangerously_bypass_approvals_and_sandbox;
}
if let Some(cwd) = cwd {
self.cwd = Some(cwd);
}
if !images.is_empty() {
self.images = images;
}
if !add_dir.is_empty() {
self.add_dir.extend(add_dir);
}
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "elapsed",
crate_name = "codex_utils_elapsed",
)

View file

@ -0,0 +1,8 @@
[package]
name = "codex-utils-elapsed"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true

View 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");
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "fuzzy-match",
crate_name = "codex_utils_fuzzy_match",
)

View file

@ -0,0 +1,8 @@
[package]
name = "codex-utils-fuzzy-match"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true

View file

@ -0,0 +1,168 @@
/// 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., ß → ss, İ → 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 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]);
last_lower_pos = Some(pos);
}
let first_lower_pos = if result_orig_indices.is_empty() {
0usize
} else {
let target_orig = result_orig_indices[0];
lowered_to_orig_char_idx
.iter()
.position(|&oi| oi == target_orig)
.unwrap_or(0)
};
// 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);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "home-dir",
crate_name = "codex_utils_home_dir",
)

View file

@ -0,0 +1,16 @@
[package]
name = "codex-utils-home-dir"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
codex-utils-absolute-path = { workspace = true }
dirs = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }

View file

@ -0,0 +1,134 @@
use codex_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 `CODEX_HOME` environment variable. If not set, defaults to
/// `~/.codex`.
///
/// - If `CODEX_HOME` is set, the value must exist and be a directory. The
/// value will be canonicalized and this function will Err otherwise.
/// - If `CODEX_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("CODEX_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 `CODEX_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!("CODEX_HOME points to {val:?}, but that path does not exist"),
),
_ => std::io::Error::new(
err.kind(),
format!("failed to read CODEX_HOME {val:?}: {err}"),
),
})?;
if !metadata.is_dir() {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("CODEX_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 CODEX_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(".codex");
AbsolutePathBuf::from_absolute_path(p)
}
}
}
#[cfg(test)]
mod tests {
use super::find_codex_home_from_env;
use codex_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 CODEX_HOME");
assert_eq!(err.kind(), ErrorKind::NotFound);
assert!(
err.to_string().contains("CODEX_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("codex-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 CODEX_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 CODEX_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 CODEX_HOME");
let mut expected = home_dir().expect("home dir");
expected.push(".codex");
let expected = AbsolutePathBuf::from_absolute_path(expected).expect("absolute home");
assert_eq!(resolved, expected);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "image",
crate_name = "codex_utils_image",
)

View file

@ -0,0 +1,19 @@
[package]
name = "codex-utils-image"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
base64 = { workspace = true }
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }
codex-utils-cache = { workspace = true }
mime_guess = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["fs", "rt", "rt-multi-thread", "macros"] }
[dev-dependencies]
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }

View file

@ -0,0 +1,55 @@
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 },
}
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(_),
..
}
)
}
}

View file

@ -0,0 +1,349 @@
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::LazyLock;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_utils_cache::BlockingLruCache;
use codex_utils_cache::sha1_digest;
use image::ColorType;
use image::DynamicImage;
use image::GenericImageView;
use image::ImageEncoder;
use image::ImageFormat;
use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::PngEncoder;
use image::codecs::webp::WebPEncoder;
use image::imageops::FilterType;
/// Maximum width or height used when resizing images before uploading.
pub const MAX_DIMENSION: u32 = 2048;
pub mod error;
pub use crate::error::ImageProcessingError;
#[derive(Debug, Clone)]
pub struct EncodedImage {
pub bytes: Vec<u8>,
pub mime: String,
pub width: u32,
pub height: u32,
}
impl EncodedImage {
pub fn into_data_url(self) -> String {
let encoded = BASE64_STANDARD.encode(&self.bytes);
format!("data:{};base64,{encoded}", self.mime)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PromptImageMode {
ResizeToFit,
Original,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ImageCacheKey {
digest: [u8; 20],
mode: PromptImageMode,
}
static IMAGE_CACHE: LazyLock<BlockingLruCache<ImageCacheKey, EncodedImage>> =
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,
};
IMAGE_CACHE.get_or_try_insert_with(key, move || {
let format = match image::guess_format(&file_bytes) {
Ok(ImageFormat::Png) => Some(ImageFormat::Png),
Ok(ImageFormat::Jpeg) => Some(ImageFormat::Jpeg),
Ok(ImageFormat::Gif) => Some(ImageFormat::Gif),
Ok(ImageFormat::WebP) => Some(ImageFormat::WebP),
_ => None,
};
let dynamic = image::load_from_memory(&file_bytes)
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
let (width, height) = dynamic.dimensions();
let encoded = if mode == PromptImageMode::Original
|| (width <= MAX_DIMENSION && height <= MAX_DIMENSION)
{
if let Some(format) = format.filter(|format| can_preserve_source_bytes(*format)) {
let mime = format_to_mime(format);
EncodedImage {
bytes: file_bytes,
mime,
width,
height,
}
} else {
let (bytes, output_format) = encode_image(&dynamic, ImageFormat::Png)?;
let mime = format_to_mime(output_format);
EncodedImage {
bytes,
mime,
width,
height,
}
}
} else {
let resized = dynamic.resize(MAX_DIMENSION, MAX_DIMENSION, FilterType::Triangle);
let target_format = format
.filter(|format| can_preserve_source_bytes(*format))
.unwrap_or(ImageFormat::Png);
let (bytes, output_format) = encode_image(&resized, target_format)?;
let mime = format_to_mime(output_format);
EncodedImage {
bytes,
mime,
width: resized.width(),
height: resized.height(),
}
};
Ok(encoded)
})
}
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,
) -> 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();
match target_format {
ImageFormat::Png => {
let rgba = image.to_rgba8();
let encoder = PngEncoder::new(&mut buffer);
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);
encoder
.encode_image(image)
.map_err(|source| ImageProcessingError::Encode {
format: target_format,
source,
})?;
}
ImageFormat::WebP => {
let rgba = image.to_rgba8();
let encoder = WebPEncoder::new_lossless(&mut buffer);
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 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)]
mod tests {
use std::io::Cursor;
use super::*;
use image::GenericImageView;
use image::ImageBuffer;
use image::Rgba;
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()
}
#[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, 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 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, original_bytes);
}
#[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 { .. }
));
}
#[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);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "json-to-toml",
crate_name = "codex_utils_json_to_toml",
)

View file

@ -0,0 +1,15 @@
[package]
name = "codex-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

View 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);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "oss",
crate_name = "codex_utils_oss",
)

View file

@ -0,0 +1,14 @@
[package]
name = "codex-utils-oss"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
codex-core = { workspace = true }
codex-lmstudio = { workspace = true }
codex-model-provider-info = { workspace = true }
codex-ollama = { workspace = true }

View file

@ -0,0 +1,61 @@
//! OSS provider utilities shared between TUI and exec.
use codex_core::config::Config;
use codex_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID;
use codex_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(codex_lmstudio::DEFAULT_OSS_MODEL),
OLLAMA_OSS_PROVIDER_ID => Some(codex_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 => {
codex_lmstudio::ensure_oss_ready(config)
.await
.map_err(|e| std::io::Error::other(format!("OSS setup failed: {e}")))?;
}
OLLAMA_OSS_PROVIDER_ID => {
codex_ollama::ensure_responses_supported(&config.model_provider).await?;
codex_ollama::ensure_oss_ready(config)
.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(codex_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(codex_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);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "output-truncation",
crate_name = "codex_utils_output_truncation",
)

View file

@ -0,0 +1,15 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-utils-output-truncation"
version.workspace = true
[lints]
workspace = true
[dependencies]
codex-protocol = { workspace = true }
codex-utils-string = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }

View file

@ -0,0 +1,142 @@
//! Helpers for truncating tool and exec output using [`TruncationPolicy`](codex_protocol::protocol::TruncationPolicy).
use codex_protocol::models::FunctionCallOutputContentItem;
pub use codex_utils_string::approx_bytes_for_tokens;
pub use codex_utils_string::approx_token_count;
pub use codex_utils_string::approx_tokens_from_byte_count;
use codex_utils_string::truncate_middle_chars;
use codex_utils_string::truncate_middle_with_token_budget;
pub use codex_protocol::protocol::TruncationPolicy;
pub fn formatted_truncate_text(content: &str, policy: TruncationPolicy) -> String {
if content.len() <= policy.byte_budget() {
return content.to_string();
}
let total_lines = content.lines().count();
let result = truncate_text(content, policy);
format!("Total output lines: {total_lines}\n\n{result}")
}
pub fn truncate_text(content: &str, policy: TruncationPolicy) -> String {
match policy {
TruncationPolicy::Bytes(bytes) => truncate_middle_chars(content, bytes),
TruncationPolicy::Tokens(tokens) => truncate_middle_with_token_budget(content, tokens).0,
}
}
pub fn formatted_truncate_text_content_items_with_policy(
items: &[FunctionCallOutputContentItem],
policy: TruncationPolicy,
) -> (Vec<FunctionCallOutputContentItem>, Option<usize>) {
let text_segments = items
.iter()
.filter_map(|item| match item {
FunctionCallOutputContentItem::InputText { text } => Some(text.as_str()),
FunctionCallOutputContentItem::InputImage { .. } => None,
})
.collect::<Vec<_>>();
if text_segments.is_empty() {
return (items.to_vec(), None);
}
let mut combined = String::new();
for text in &text_segments {
if !combined.is_empty() {
combined.push('\n');
}
combined.push_str(text);
}
if combined.len() <= policy.byte_budget() {
return (items.to_vec(), None);
}
let mut out = vec![FunctionCallOutputContentItem::InputText {
text: formatted_truncate_text(&combined, policy),
}];
out.extend(items.iter().filter_map(|item| match item {
FunctionCallOutputContentItem::InputImage { image_url, detail } => {
Some(FunctionCallOutputContentItem::InputImage {
image_url: image_url.clone(),
detail: *detail,
})
}
FunctionCallOutputContentItem::InputText { .. } => None,
}));
(out, Some(approx_token_count(&combined)))
}
pub fn truncate_function_output_items_with_policy(
items: &[FunctionCallOutputContentItem],
policy: TruncationPolicy,
) -> 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;
for item in items {
match item {
FunctionCallOutputContentItem::InputText { text } => {
if remaining_budget == 0 {
omitted_text_items += 1;
continue;
}
let cost = match policy {
TruncationPolicy::Bytes(_) => text.len(),
TruncationPolicy::Tokens(_) => approx_token_count(text),
};
if cost <= remaining_budget {
out.push(FunctionCallOutputContentItem::InputText { text: text.clone() });
remaining_budget = remaining_budget.saturating_sub(cost);
} else {
let snippet_policy = match policy {
TruncationPolicy::Bytes(_) => TruncationPolicy::Bytes(remaining_budget),
TruncationPolicy::Tokens(_) => TruncationPolicy::Tokens(remaining_budget),
};
let snippet = truncate_text(text, snippet_policy);
if snippet.is_empty() {
omitted_text_items += 1;
} else {
out.push(FunctionCallOutputContentItem::InputText { text: snippet });
}
remaining_budget = 0;
}
}
FunctionCallOutputContentItem::InputImage { image_url, detail } => {
out.push(FunctionCallOutputContentItem::InputImage {
image_url: image_url.clone(),
detail: *detail,
});
}
}
}
if omitted_text_items > 0 {
out.push(FunctionCallOutputContentItem::InputText {
text: format!("[omitted {omitted_text_items} text items ...]"),
});
}
out
}
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;

View file

@ -0,0 +1,282 @@
use crate::TruncationPolicy;
use crate::approx_token_count;
use crate::approx_tokens_from_byte_count_i64;
use crate::formatted_truncate_text;
use crate::formatted_truncate_text_content_items_with_policy;
use crate::truncate_function_output_items_with_policy;
use crate::truncate_text;
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
use codex_protocol::models::FunctionCallOutputContentItem;
use pretty_assertions::assert_eq;
#[test]
fn truncate_bytes_less_than_placeholder_returns_placeholder() {
let content = "example output";
assert_eq!(
"Total 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!(
"Total 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!(
"Total 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!(
"Total 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!(
"Total 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!(
"Total 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_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));
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_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 formatted_truncate_text_content_items_with_policy_returns_original_under_limit() {
let items = vec![
FunctionCallOutputContentItem::InputText {
text: "alpha".to_string(),
},
FunctionCallOutputContentItem::InputText {
text: String::new(),
},
FunctionCallOutputContentItem::InputText {
text: "beta".to_string(),
},
];
let (output, original_token_count) =
formatted_truncate_text_content_items_with_policy(&items, TruncationPolicy::Bytes(32));
assert_eq!(output, items);
assert_eq!(original_token_count, None);
}
#[test]
fn formatted_truncate_text_content_items_with_policy_preserves_empty_leading_text_behavior() {
let items = vec![
FunctionCallOutputContentItem::InputText {
text: String::new(),
},
FunctionCallOutputContentItem::InputText {
text: "abc".to_string(),
},
];
let (output, original_token_count) =
formatted_truncate_text_content_items_with_policy(&items, TruncationPolicy::Bytes(0));
assert_eq!(
output,
vec![FunctionCallOutputContentItem::InputText {
text: "Total output lines: 1\n\n…3 chars truncated…".to_string(),
}]
);
assert_eq!(original_token_count, Some(1));
}
#[test]
fn formatted_truncate_text_content_items_with_policy_merges_text_and_appends_images() {
let items = vec![
FunctionCallOutputContentItem::InputText {
text: "abcd".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image_url: "img:one".to_string(),
detail: Some(DEFAULT_IMAGE_DETAIL),
},
FunctionCallOutputContentItem::InputText {
text: "efgh".to_string(),
},
FunctionCallOutputContentItem::InputText {
text: "ijkl".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image_url: "img:two".to_string(),
detail: Some(DEFAULT_IMAGE_DETAIL),
},
];
let (output, original_token_count) =
formatted_truncate_text_content_items_with_policy(&items, TruncationPolicy::Bytes(8));
assert_eq!(
output,
vec![
FunctionCallOutputContentItem::InputText {
text: "Total output lines: 3\n\nabcd…6 chars truncated…ijkl".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image_url: "img:one".to_string(),
detail: Some(DEFAULT_IMAGE_DETAIL),
},
FunctionCallOutputContentItem::InputImage {
image_url: "img:two".to_string(),
detail: Some(DEFAULT_IMAGE_DETAIL),
},
]
);
assert_eq!(original_token_count, Some(4));
}
#[test]
fn formatted_truncate_text_content_items_with_policy_merges_all_text_for_token_budget() {
let items = vec![
FunctionCallOutputContentItem::InputText {
text: "abcdefgh".to_string(),
},
FunctionCallOutputContentItem::InputText {
text: "ijklmnop".to_string(),
},
];
let (output, original_token_count) =
formatted_truncate_text_content_items_with_policy(&items, TruncationPolicy::Tokens(2));
assert_eq!(
output,
vec![FunctionCallOutputContentItem::InputText {
text: "Total output lines: 2\n\nabcd…3 tokens truncated…mnop".to_string(),
}]
);
assert_eq!(original_token_count, Some(5));
}
#[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);
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "path-utils",
crate_name = "codex_utils_path",
)

View file

@ -0,0 +1,17 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-utils-path"
version.workspace = true
[lints]
workspace = true
[dependencies]
codex-utils-absolute-path = { workspace = true }
dunce = { workspace = true }
tempfile = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }

View 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
}
}

View file

@ -0,0 +1,219 @@
//! Path normalization, symlink resolution, and atomic writes shared across Codex crates.
pub(crate) mod env;
pub use env::is_wsl;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashSet;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use tempfile::NamedTempFile;
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()
}
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(&current) {
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(&current) {
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 tmp = NamedTempFile::new_in(parent)?;
std::fs::write(tmp.path(), contents)?;
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;

View file

@ -0,0 +1,115 @@
#[cfg(unix)]
mod symlinks {
use super::super::resolve_symlink_write_paths;
use pretty_assertions::assert_eq;
use std::os::unix::fs::symlink;
#[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(())
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "plugins",
crate_name = "codex_utils_plugins",
)

View file

@ -0,0 +1,25 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-utils-plugins"
version.workspace = true
[lib]
doctest = false
name = "codex_utils_plugins"
path = "src/lib.rs"
[lints]
workspace = true
[dependencies]
codex-exec-server = { workspace = true }
codex-login = { workspace = true }
codex-utils-absolute-path = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }

View file

@ -0,0 +1,9 @@
//! Plugin path resolution, plaintext mention sigils, and MCP connector helpers shared across Codex
//! crates.
pub mod mcp_connector;
pub mod mention_syntax;
pub mod plugin_namespace;
pub use plugin_namespace::find_plugin_manifest_path;
pub use plugin_namespace::plugin_namespace_for_skill_path;

View file

@ -0,0 +1,50 @@
use codex_login::default_client::is_first_party_chat_originator;
use codex_login::default_client::originator;
const DISALLOWED_CONNECTOR_IDS: &[&str] = &[
"asdk_app_6938a94a61d881918ef32cb999ff937c",
"connector_2b0a9009c9c64bf9933a3dae3f2b1254",
"connector_3f8d1a79f27c4c7ba1a897ab13bf37dc",
"connector_68de829bf7648191acd70a907364c67c",
"connector_68e004f14af881919eb50893d3d9f523",
"connector_69272cb413a081919685ec3c88d1744e",
];
const FIRST_PARTY_CHAT_DISALLOWED_CONNECTOR_IDS: &[&str] =
&["connector_0f9c9d4592e54d0a9a12b3f44a1e2010"];
const DISALLOWED_CONNECTOR_PREFIX: &str = "connector_openai_";
pub fn is_connector_id_allowed(connector_id: &str) -> bool {
is_connector_id_allowed_for_originator(connector_id, originator().value.as_str())
}
fn is_connector_id_allowed_for_originator(connector_id: &str, originator_value: &str) -> bool {
let disallowed_connector_ids = if is_first_party_chat_originator(originator_value) {
FIRST_PARTY_CHAT_DISALLOWED_CONNECTOR_IDS
} else {
DISALLOWED_CONNECTOR_IDS
};
!connector_id.starts_with(DISALLOWED_CONNECTOR_PREFIX)
&& !disallowed_connector_ids.contains(&connector_id)
}
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()
}
}

View 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 = '@';

View file

@ -0,0 +1,121 @@
//! Resolve plugin namespace from skill file paths by walking ancestors for `plugin.json`.
use codex_exec_server::ExecutorFileSystem;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::path::Path;
use std::path::PathBuf;
const DISCOVERABLE_PLUGIN_MANIFEST_PATHS: &[&str] =
&[".codex-plugin/plugin.json", ".claude-plugin/plugin.json"];
pub fn find_plugin_manifest_path(plugin_root: &Path) -> Option<PathBuf> {
DISCOVERABLE_PLUGIN_MANIFEST_PATHS
.iter()
.map(|relative_path| plugin_root.join(relative_path))
.find(|manifest_path| manifest_path.is_file())
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawPluginManifestName {
#[serde(default)]
name: String,
}
async fn plugin_manifest_name(
fs: &dyn ExecutorFileSystem,
plugin_root: &AbsolutePathBuf,
) -> Option<String> {
let mut manifest_path = None;
for relative_path in DISCOVERABLE_PLUGIN_MANIFEST_PATHS {
let candidate = plugin_root.join(relative_path);
match fs.get_metadata(&candidate, /*sandbox*/ None).await {
Ok(metadata) if metadata.is_file => {
manifest_path = Some(candidate);
break;
}
Ok(_) | Err(_) => {}
}
}
let manifest_path = manifest_path?;
let contents = fs
.read_file_text(&manifest_path, /*sandbox*/ None)
.await
.ok()?;
let RawPluginManifestName { name: raw_name } = serde_json::from_str(&contents).ok()?;
Some(
plugin_root
.file_name()
.and_then(|entry| entry.to_str())
.filter(|_| raw_name.trim().is_empty())
.unwrap_or(raw_name.as_str())
.to_string(),
)
}
/// Returns the plugin manifest `name` for the nearest ancestor of `path` that contains a valid
/// plugin manifest (same `name` rules as full manifest loading in codex-core).
pub async fn plugin_namespace_for_skill_path(
fs: &dyn ExecutorFileSystem,
path: &AbsolutePathBuf,
) -> Option<String> {
for ancestor in path.ancestors() {
if let Some(name) = plugin_manifest_name(fs, &ancestor).await {
return Some(name);
}
}
None
}
#[cfg(test)]
mod tests {
use super::find_plugin_manifest_path;
use super::plugin_namespace_for_skill_path;
use codex_exec_server::LOCAL_FS;
use codex_utils_absolute_path::test_support::PathBufExt;
use std::fs;
use tempfile::tempdir;
const ALTERNATE_PLUGIN_MANIFEST_RELATIVE_PATH: &str = ".claude-plugin/plugin.json";
#[tokio::test]
async fn uses_manifest_name() {
let tmp = tempdir().expect("tempdir");
let plugin_root = tmp.path().join("plugins/sample");
let skill_path = plugin_root.join("skills/search/SKILL.md");
fs::create_dir_all(skill_path.parent().expect("parent")).expect("mkdir");
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("mkdir manifest");
fs::write(
plugin_root.join(".codex-plugin/plugin.json"),
r#"{"name":"sample"}"#,
)
.expect("write manifest");
fs::write(&skill_path, "---\ndescription: search\n---\n").expect("write skill");
assert_eq!(
plugin_namespace_for_skill_path(LOCAL_FS.as_ref(), &skill_path.abs()).await,
Some("sample".to_string())
);
}
#[tokio::test]
async fn uses_name_from_alternate_discoverable_manifest_path() {
let tmp = tempdir().expect("tempdir");
let plugin_root = tmp.path().join("plugins/sample");
let skill_path = plugin_root.join("skills/search/SKILL.md");
let manifest_path = plugin_root.join(ALTERNATE_PLUGIN_MANIFEST_RELATIVE_PATH);
fs::create_dir_all(skill_path.parent().expect("parent")).expect("mkdir");
fs::create_dir_all(manifest_path.parent().expect("manifest parent"))
.expect("mkdir manifest");
fs::write(&manifest_path, r#"{"name":"sample"}"#).expect("write manifest");
fs::write(&skill_path, "---\ndescription: search\n---\n").expect("write skill");
assert_eq!(
plugin_namespace_for_skill_path(LOCAL_FS.as_ref(), &skill_path.abs()).await,
Some("sample".to_string())
);
assert_eq!(find_plugin_manifest_path(&plugin_root), Some(manifest_path));
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "pty",
crate_name = "codex_utils_pty",
)

View file

@ -0,0 +1,34 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-utils-pty"
version.workspace = true
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
portable-pty = { workspace = true }
tokio = { workspace = true, features = ["io-util", "macros", "process", "rt-multi-thread", "sync", "time"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
[target.'cfg(windows)'.dependencies]
filedescriptor = "0.8.3"
lazy_static = { workspace = true }
log = { workspace = true }
shared_library = "0.1.9"
winapi = { version = "0.3.9", features = [
"handleapi",
"minwinbase",
"processthreadsapi",
"synchapi",
"winbase",
"wincon",
"winerror",
"winnt",
] }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }

View file

@ -0,0 +1,64 @@
# codex-utils-pty
Lightweight helpers for spawning interactive processes either under a PTY (pseudo terminal) or regular pipes. The public API is minimal and mirrors both backends so callers can switch based on their needs (e.g., enabling or disabling TTY).
## API surface
- `spawn_pty_process(program, args, cwd, env, arg0, size)` → `SpawnedProcess`
- `spawn_pipe_process(program, args, cwd, env, arg0)` → `SpawnedProcess`
- `spawn_pipe_process_no_stdin(program, args, cwd, env, arg0)` → `SpawnedProcess`
- `combine_output_receivers(stdout_rx, stderr_rx)` → `broadcast::Receiver<Vec<u8>>`
- `conpty_supported()` → `bool` (Windows only; always true elsewhere)
- `TerminalSize { rows, cols }` selects PTY dimensions in character cells.
- `ProcessHandle` exposes:
- `writer_sender()` → `mpsc::Sender<Vec<u8>>` (stdin)
- `resize(TerminalSize)`
- `close_stdin()`
- `has_exited()`, `exit_code()`, `terminate()`
- `SpawnedProcess` bundles `session`, `stdout_rx`, `stderr_rx`, and `exit_rx` (oneshot exit code).
## Usage examples
```rust
use std::collections::HashMap;
use std::path::Path;
use codex_utils_pty::combine_output_receivers;
use codex_utils_pty::spawn_pty_process;
use codex_utils_pty::TerminalSize;
# tokio_test::block_on(async {
let env_map: HashMap<String, String> = std::env::vars().collect();
let spawned = spawn_pty_process(
"bash",
&["-lc".into(), "echo hello".into()],
Path::new("."),
&env_map,
&None,
TerminalSize::default(),
).await?;
let writer = spawned.session.writer_sender();
writer.send(b"exit\n".to_vec()).await?;
// Collect output until the process exits.
let mut output_rx = combine_output_receivers(spawned.stdout_rx, spawned.stderr_rx);
let mut collected = Vec::new();
while let Ok(chunk) = output_rx.try_recv() {
collected.extend_from_slice(&chunk);
}
let exit_code = spawned.exit_rx.await.unwrap_or(-1);
# let _ = (collected, exit_code);
# anyhow::Ok(())
# });
```
Swap in `spawn_pipe_process` for a non-TTY subprocess; the rest of the API stays the same.
Use `spawn_pipe_process_no_stdin` to force stdin closed (commands that read stdin will see EOF immediately).
## Tests
Unit tests live in `src/lib.rs` and cover both backends (PTY Python REPL and pipe-based stdin roundtrip). Run with:
```
cargo test -p codex-utils-pty -- --nocapture
```

View file

@ -0,0 +1,37 @@
pub mod pipe;
mod process;
pub mod process_group;
pub mod pty;
#[cfg(test)]
mod tests;
#[cfg(windows)]
mod win;
pub const DEFAULT_OUTPUT_BYTES_CAP: usize = 1024 * 1024;
/// Spawn a non-interactive process using regular pipes for stdin/stdout/stderr.
pub use pipe::spawn_process as spawn_pipe_process;
/// Spawn a non-interactive process using regular pipes, but close stdin immediately.
pub use pipe::spawn_process_no_stdin as spawn_pipe_process_no_stdin;
/// Driver-backed process adapter used by integrations with their own process transport.
pub use process::ProcessDriver;
/// Handle for interacting with a spawned process (PTY or pipe).
pub use process::ProcessHandle;
/// Bundle of process handles plus split output and exit receivers returned by spawn helpers.
pub use process::SpawnedProcess;
/// Terminal size in character cells used for PTY spawn and resize operations.
pub use process::TerminalSize;
/// Combine stdout/stderr receivers into a single broadcast receiver.
pub use process::combine_output_receivers;
/// Adapt an externally-driven process into the standard spawned-process handle.
pub use process::spawn_from_driver;
/// Backwards-compatible alias for ProcessHandle.
pub type ExecCommandSession = ProcessHandle;
/// Backwards-compatible alias for SpawnedProcess.
pub type SpawnedPty = SpawnedProcess;
/// Report whether ConPTY is available on this platform (Windows only).
pub use pty::conpty_supported;
/// Spawn a process attached to a PTY for interactive use.
pub use pty::spawn_process as spawn_pty_process;
#[cfg(windows)]
pub use win::conpty::RawConPty;

View file

@ -0,0 +1,290 @@
use std::collections::HashMap;
use std::io;
use std::io::ErrorKind;
use std::path::Path;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use anyhow::Result;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use crate::process::ChildTerminator;
use crate::process::ProcessHandle;
use crate::process::SpawnedProcess;
#[cfg(target_os = "linux")]
use libc;
struct PipeChildTerminator {
#[cfg(windows)]
pid: u32,
#[cfg(unix)]
process_group_id: u32,
}
impl ChildTerminator for PipeChildTerminator {
fn kill(&mut self) -> io::Result<()> {
#[cfg(unix)]
{
crate::process_group::kill_process_group(self.process_group_id)
}
#[cfg(windows)]
{
kill_process(self.pid)
}
#[cfg(not(any(unix, windows)))]
{
Ok(())
}
}
}
#[cfg(windows)]
fn kill_process(pid: u32) -> io::Result<()> {
unsafe {
let handle = winapi::um::processthreadsapi::OpenProcess(
winapi::um::winnt::PROCESS_TERMINATE,
0,
pid,
);
if handle.is_null() {
return Err(io::Error::last_os_error());
}
let success = winapi::um::processthreadsapi::TerminateProcess(handle, 1);
let err = io::Error::last_os_error();
winapi::um::handleapi::CloseHandle(handle);
if success == 0 { Err(err) } else { Ok(()) }
}
}
async fn read_output_stream<R>(mut reader: R, output_tx: mpsc::Sender<Vec<u8>>)
where
R: AsyncRead + Unpin,
{
let mut buf = vec![0u8; 8_192];
loop {
match reader.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
let _ = output_tx.send(buf[..n].to_vec()).await;
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
}
#[derive(Clone, Copy)]
enum PipeStdinMode {
Piped,
Null,
}
async fn spawn_process_with_stdin_mode(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
stdin_mode: PipeStdinMode,
inherited_fds: &[i32],
) -> Result<SpawnedProcess> {
if program.is_empty() {
anyhow::bail!("missing program for pipe spawn");
}
#[cfg(not(unix))]
let _ = inherited_fds;
let mut command = Command::new(program);
#[cfg(unix)]
if let Some(arg0) = arg0 {
command.arg0(arg0);
}
#[cfg(target_os = "linux")]
let parent_pid = unsafe { libc::getpid() };
#[cfg(unix)]
let inherited_fds = inherited_fds.to_vec();
#[cfg(unix)]
unsafe {
command.pre_exec(move || {
crate::process_group::detach_from_tty()?;
#[cfg(target_os = "linux")]
crate::process_group::set_parent_death_signal(parent_pid)?;
crate::pty::close_inherited_fds_except(&inherited_fds);
Ok(())
});
}
#[cfg(not(unix))]
let _ = arg0;
command.current_dir(cwd);
command.env_clear();
for (key, value) in env {
command.env(key, value);
}
for arg in args {
command.arg(arg);
}
match stdin_mode {
PipeStdinMode::Piped => {
command.stdin(Stdio::piped());
}
PipeStdinMode::Null => {
command.stdin(Stdio::null());
}
}
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
let mut child = command.spawn()?;
let pid = child
.id()
.ok_or_else(|| io::Error::other("missing child pid"))?;
#[cfg(unix)]
let process_group_id = pid;
let stdin = child.stdin.take();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(128);
let (stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(128);
let writer_handle = if let Some(stdin) = stdin {
tokio::spawn(async move {
let mut writer = stdin;
while let Some(bytes) = writer_rx.recv().await {
let _ = writer.write_all(&bytes).await;
let _ = writer.flush().await;
}
})
} else {
drop(writer_rx);
tokio::spawn(async {})
};
let stdout_handle = stdout.map(|stdout| {
let stdout_tx = stdout_tx.clone();
tokio::spawn(async move {
read_output_stream(BufReader::new(stdout), stdout_tx).await;
})
});
let stderr_handle = stderr.map(|stderr| {
let stderr_tx = stderr_tx.clone();
tokio::spawn(async move {
read_output_stream(BufReader::new(stderr), stderr_tx).await;
})
});
let mut reader_abort_handles = Vec::new();
if let Some(handle) = stdout_handle.as_ref() {
reader_abort_handles.push(handle.abort_handle());
}
if let Some(handle) = stderr_handle.as_ref() {
reader_abort_handles.push(handle.abort_handle());
}
let reader_handle = tokio::spawn(async move {
if let Some(handle) = stdout_handle {
let _ = handle.await;
}
if let Some(handle) = stderr_handle {
let _ = handle.await;
}
});
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let wait_handle: JoinHandle<()> = tokio::spawn(async move {
let code = match child.wait().await {
Ok(status) => status.code().unwrap_or(-1),
Err(_) => -1,
};
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_tx.send(code);
});
let handle = ProcessHandle::new(
writer_tx,
Box::new(PipeChildTerminator {
#[cfg(windows)]
pid,
#[cfg(unix)]
process_group_id,
}),
reader_handle,
reader_abort_handles,
writer_handle,
wait_handle,
exit_status,
exit_code,
/*pty_handles*/ None,
/*resizer*/ None,
);
Ok(SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx,
})
}
/// Spawn a process using regular pipes (no PTY), returning handles for stdin, split output, and exit.
pub async fn spawn_process(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
) -> Result<SpawnedProcess> {
spawn_process_with_stdin_mode(program, args, cwd, env, arg0, PipeStdinMode::Piped, &[]).await
}
/// Spawn a process using regular pipes, but close stdin immediately.
pub async fn spawn_process_no_stdin(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
) -> Result<SpawnedProcess> {
spawn_process_no_stdin_with_inherited_fds(program, args, cwd, env, arg0, &[]).await
}
/// Spawn a process using regular pipes, close stdin immediately, and preserve
/// selected inherited file descriptors across exec on Unix.
pub async fn spawn_process_no_stdin_with_inherited_fds(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
inherited_fds: &[i32],
) -> Result<SpawnedProcess> {
spawn_process_with_stdin_mode(
program,
args,
cwd,
env,
arg0,
PipeStdinMode::Null,
inherited_fds,
)
.await
}

View file

@ -0,0 +1,410 @@
use core::fmt;
use std::io;
#[cfg(unix)]
use std::os::fd::RawFd;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use anyhow::anyhow;
use portable_pty::MasterPty;
use portable_pty::PtySize;
use portable_pty::SlavePty;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
pub(crate) trait ChildTerminator: Send + Sync {
fn kill(&mut self) -> io::Result<()>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TerminalSize {
pub rows: u16,
pub cols: u16,
}
impl Default for TerminalSize {
fn default() -> Self {
Self { rows: 24, cols: 80 }
}
}
impl From<TerminalSize> for PtySize {
fn from(value: TerminalSize) -> Self {
Self {
rows: value.rows,
cols: value.cols,
pixel_width: 0,
pixel_height: 0,
}
}
}
#[cfg(unix)]
pub(crate) trait PtyHandleKeepAlive: Send {}
#[cfg(unix)]
impl<T: Send + ?Sized> PtyHandleKeepAlive for T {}
pub(crate) enum PtyMasterHandle {
Resizable(Box<dyn MasterPty + Send>),
#[cfg(unix)]
Opaque {
raw_fd: RawFd,
_handle: Box<dyn PtyHandleKeepAlive>,
},
}
pub struct PtyHandles {
pub _slave: Option<Box<dyn SlavePty + Send>>,
pub(crate) _master: PtyMasterHandle,
}
impl fmt::Debug for PtyHandles {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PtyHandles").finish()
}
}
/// Callback used by driver-backed sessions to resize a PTY-like backend when
/// there is no local `PtyHandles` instance to resize directly.
type ResizeFn = Box<dyn FnMut(TerminalSize) -> anyhow::Result<()> + Send>;
/// Handle for driving an interactive process (PTY or pipe).
pub struct ProcessHandle {
writer_tx: StdMutex<Option<mpsc::Sender<Vec<u8>>>>,
killer: StdMutex<Option<Box<dyn ChildTerminator>>>,
reader_handle: StdMutex<Option<JoinHandle<()>>>,
reader_abort_handles: StdMutex<Vec<AbortHandle>>,
writer_handle: StdMutex<Option<JoinHandle<()>>>,
wait_handle: StdMutex<Option<JoinHandle<()>>>,
exit_status: Arc<AtomicBool>,
exit_code: Arc<StdMutex<Option<i32>>>,
// PtyHandles must be preserved because the process will receive Control+C if the
// slave is closed
_pty_handles: StdMutex<Option<PtyHandles>>,
// Optional resize hook for driver-backed sessions that proxy PTY control to
// another backend instead of owning local PTY handles.
resizer: StdMutex<Option<ResizeFn>>,
}
impl fmt::Debug for ProcessHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProcessHandle").finish()
}
}
impl ProcessHandle {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
writer_tx: mpsc::Sender<Vec<u8>>,
killer: Box<dyn ChildTerminator>,
reader_handle: JoinHandle<()>,
reader_abort_handles: Vec<AbortHandle>,
writer_handle: JoinHandle<()>,
wait_handle: JoinHandle<()>,
exit_status: Arc<AtomicBool>,
exit_code: Arc<StdMutex<Option<i32>>>,
pty_handles: Option<PtyHandles>,
resizer: Option<ResizeFn>,
) -> Self {
Self {
writer_tx: StdMutex::new(Some(writer_tx)),
killer: StdMutex::new(Some(killer)),
reader_handle: StdMutex::new(Some(reader_handle)),
reader_abort_handles: StdMutex::new(reader_abort_handles),
writer_handle: StdMutex::new(Some(writer_handle)),
wait_handle: StdMutex::new(Some(wait_handle)),
exit_status,
exit_code,
_pty_handles: StdMutex::new(pty_handles),
resizer: StdMutex::new(resizer),
}
}
/// Returns a channel sender for writing raw bytes to the child stdin.
pub fn writer_sender(&self) -> mpsc::Sender<Vec<u8>> {
if let Ok(writer_tx) = self.writer_tx.lock()
&& let Some(writer_tx) = writer_tx.as_ref()
{
return writer_tx.clone();
}
let (writer_tx, writer_rx) = mpsc::channel(1);
drop(writer_rx);
writer_tx
}
/// True if the child process has exited.
pub fn has_exited(&self) -> bool {
self.exit_status.load(std::sync::atomic::Ordering::SeqCst)
}
/// Returns the exit code if known.
pub fn exit_code(&self) -> Option<i32> {
self.exit_code.lock().ok().and_then(|guard| *guard)
}
/// Resize the PTY in character cells.
pub fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
{
let handles = self
._pty_handles
.lock()
.map_err(|_| anyhow!("failed to lock PTY handles"))?;
if let Some(handles) = handles.as_ref() {
return match &handles._master {
PtyMasterHandle::Resizable(master) => master.resize(size.into()),
#[cfg(unix)]
PtyMasterHandle::Opaque { raw_fd, .. } => resize_raw_pty(*raw_fd, size),
};
}
}
let mut resizer = self
.resizer
.lock()
.map_err(|_| anyhow!("failed to lock PTY resizer"))?;
if let Some(resizer) = resizer.as_mut() {
resizer(size)
} else {
Err(anyhow!("process is not attached to a PTY"))
}
}
/// Close the child's stdin channel.
pub fn close_stdin(&self) {
if let Ok(mut writer_tx) = self.writer_tx.lock() {
writer_tx.take();
}
}
/// Attempts to kill the child while leaving the reader/writer tasks alive
/// so callers can still drain output until EOF.
pub fn request_terminate(&self) {
if let Ok(mut killer_opt) = self.killer.lock()
&& let Some(mut killer) = killer_opt.take()
{
let _ = killer.kill();
}
}
/// Attempts to kill the child and abort helper tasks.
pub fn terminate(&self) {
self.request_terminate();
if let Ok(mut h) = self.reader_handle.lock()
&& let Some(handle) = h.take()
{
handle.abort();
}
if let Ok(mut handles) = self.reader_abort_handles.lock() {
for handle in handles.drain(..) {
handle.abort();
}
}
if let Ok(mut h) = self.writer_handle.lock()
&& let Some(handle) = h.take()
{
handle.abort();
}
if let Ok(mut h) = self.wait_handle.lock()
&& let Some(handle) = h.take()
{
handle.abort();
}
}
}
impl Drop for ProcessHandle {
fn drop(&mut self) {
self.terminate();
}
}
/// Adapts a closure into a `ChildTerminator` implementation.
struct ClosureTerminator {
inner: Option<Box<dyn FnMut() + Send + Sync>>,
}
impl ChildTerminator for ClosureTerminator {
fn kill(&mut self) -> io::Result<()> {
if let Some(inner) = self.inner.as_mut() {
(inner)();
}
Ok(())
}
}
#[cfg(unix)]
fn resize_raw_pty(raw_fd: RawFd, size: TerminalSize) -> anyhow::Result<()> {
let mut winsize = libc::winsize {
ws_row: size.rows,
ws_col: size.cols,
ws_xpixel: 0,
ws_ypixel: 0,
};
let result = unsafe { libc::ioctl(raw_fd, libc::TIOCSWINSZ, &mut winsize) };
if result == -1 {
return Err(std::io::Error::last_os_error().into());
}
Ok(())
}
/// Combine split stdout/stderr receivers into a single broadcast receiver.
pub fn combine_output_receivers(
mut stdout_rx: mpsc::Receiver<Vec<u8>>,
mut stderr_rx: mpsc::Receiver<Vec<u8>>,
) -> broadcast::Receiver<Vec<u8>> {
let (combined_tx, combined_rx) = broadcast::channel(256);
tokio::spawn(async move {
let mut stdout_open = true;
let mut stderr_open = true;
loop {
tokio::select! {
stdout = stdout_rx.recv(), if stdout_open => match stdout {
Some(chunk) => {
let _ = combined_tx.send(chunk);
}
None => {
stdout_open = false;
}
},
stderr = stderr_rx.recv(), if stderr_open => match stderr {
Some(chunk) => {
let _ = combined_tx.send(chunk);
}
None => {
stderr_open = false;
}
},
else => break,
}
}
});
combined_rx
}
/// Return value from PTY or pipe spawn helpers.
#[derive(Debug)]
pub struct SpawnedProcess {
pub session: ProcessHandle,
pub stdout_rx: mpsc::Receiver<Vec<u8>>,
pub stderr_rx: mpsc::Receiver<Vec<u8>>,
pub exit_rx: oneshot::Receiver<i32>,
}
/// Driver-backed process handles for non-standard spawn backends.
pub struct ProcessDriver {
pub writer_tx: mpsc::Sender<Vec<u8>>,
pub stdout_rx: broadcast::Receiver<Vec<u8>>,
pub stderr_rx: Option<broadcast::Receiver<Vec<u8>>>,
pub exit_rx: oneshot::Receiver<i32>,
pub terminator: Option<Box<dyn FnMut() + Send + Sync>>,
pub writer_handle: Option<JoinHandle<()>>,
pub resizer: Option<ResizeFn>,
}
/// Build a `SpawnedProcess` from a driver that supplies stdin/output/exit channels.
pub fn spawn_from_driver(driver: ProcessDriver) -> SpawnedProcess {
let ProcessDriver {
writer_tx,
stdout_rx: stdout_driver_rx,
stderr_rx: mut stderr_driver_rx,
exit_rx,
terminator,
writer_handle,
resizer,
} = driver;
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(256);
let (stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(256);
let (exit_seen_tx, exit_seen_rx) = watch::channel(false);
let spawn_stream_reader =
|mut output_rx: broadcast::Receiver<Vec<u8>>,
output_tx: mpsc::Sender<Vec<u8>>,
mut exit_seen_rx: watch::Receiver<bool>| {
tokio::spawn(async move {
let mut process_exited = false;
loop {
let recv_result = if process_exited {
match tokio::time::timeout(
std::time::Duration::from_millis(200),
output_rx.recv(),
)
.await
{
Ok(result) => result,
Err(_) => break,
}
} else {
tokio::select! {
_ = exit_seen_rx.changed() => {
process_exited = *exit_seen_rx.borrow();
continue;
}
result = output_rx.recv() => result,
}
};
match recv_result {
Ok(chunk) => {
if output_tx.send(chunk).await.is_err() {
break;
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
})
};
let reader_handle = spawn_stream_reader(stdout_driver_rx, stdout_tx, exit_seen_rx.clone());
let stderr_reader_handle = stderr_driver_rx
.take()
.map(|rx| spawn_stream_reader(rx, stderr_tx, exit_seen_rx));
let writer_handle = writer_handle.unwrap_or_else(|| tokio::spawn(async {}));
let (exit_tx, exit_rx_out) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let wait_handle = tokio::spawn(async move {
let code = exit_rx.await.unwrap_or(-1);
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_seen_tx.send(true);
let _ = exit_tx.send(code);
});
let handle = ProcessHandle::new(
writer_tx,
Box::new(ClosureTerminator { inner: terminator }),
reader_handle,
stderr_reader_handle
.map(|handle| handle.abort_handle())
.into_iter()
.collect(),
writer_handle,
wait_handle,
exit_status,
exit_code,
/*pty_handles*/ None,
resizer,
);
SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx: exit_rx_out,
}
}

View file

@ -0,0 +1,184 @@
//! Process-group helpers shared by pipe/pty and shell command execution.
//!
//! This module centralizes the OS-specific pieces that ensure a spawned
//! command can be cleaned up reliably:
//! - `set_process_group` is called in `pre_exec` so the child starts its own
//! process group.
//! - `detach_from_tty` starts a new session so non-interactive children do not
//! inherit the controlling TTY.
//! - `kill_process_group_by_pid` targets the whole group (children/grandchildren)
//! - `kill_process_group` targets a known process group ID directly
//! instead of a single PID.
//! - `set_parent_death_signal` (Linux only) arranges for the child to receive a
//! `SIGTERM` when the parent exits, and re-checks the parent PID to avoid
//! races during fork/exec.
//!
//! On non-Unix platforms these helpers are no-ops.
use std::io;
use tokio::process::Child;
#[cfg(target_os = "linux")]
/// Ensure the child receives SIGTERM when the original parent dies.
///
/// This should run in `pre_exec` and uses `parent_pid` captured before spawn to
/// avoid a race where the parent exits between fork and exec.
pub fn set_parent_death_signal(parent_pid: libc::pid_t) -> io::Result<()> {
if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) } == -1 {
return Err(io::Error::last_os_error());
}
if unsafe { libc::getppid() } != parent_pid {
unsafe {
libc::raise(libc::SIGTERM);
}
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
/// No-op on non-Linux platforms.
pub fn set_parent_death_signal(_parent_pid: i32) -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Detach from the controlling TTY by starting a new session.
pub fn detach_from_tty() -> io::Result<()> {
let result = unsafe { libc::setsid() };
if result == -1 {
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EPERM) {
return set_process_group();
}
return Err(err);
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn detach_from_tty() -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Put the calling process into its own process group.
///
/// Intended for use in `pre_exec` so the child becomes the group leader.
pub fn set_process_group() -> io::Result<()> {
let result = unsafe { libc::setpgid(0, 0) };
if result == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn set_process_group() -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Kill the process group for the given PID (best-effort).
///
/// This resolves the PGID for `pid` and sends SIGKILL to the whole group.
pub fn kill_process_group_by_pid(pid: u32) -> io::Result<()> {
use std::io::ErrorKind;
let pid = pid as libc::pid_t;
let pgid = unsafe { libc::getpgid(pid) };
if pgid == -1 {
let err = io::Error::last_os_error();
if err.kind() != ErrorKind::NotFound {
return Err(err);
}
return Ok(());
}
let result = unsafe { libc::killpg(pgid, libc::SIGKILL) };
if result == -1 {
let err = io::Error::last_os_error();
if err.kind() != ErrorKind::NotFound {
return Err(err);
}
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn kill_process_group_by_pid(_pid: u32) -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Send SIGTERM to a specific process group ID (best-effort).
///
/// Returns `Ok(true)` when SIGTERM was delivered to an existing group and
/// `Ok(false)` when the group no longer exists.
pub fn terminate_process_group(process_group_id: u32) -> io::Result<bool> {
use std::io::ErrorKind;
let pgid = process_group_id as libc::pid_t;
let result = unsafe { libc::killpg(pgid, libc::SIGTERM) };
if result == -1 {
let err = io::Error::last_os_error();
if err.kind() == ErrorKind::NotFound {
return Ok(false);
}
return Err(err);
}
Ok(true)
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn terminate_process_group(_process_group_id: u32) -> io::Result<bool> {
Ok(false)
}
#[cfg(unix)]
/// Kill a specific process group ID (best-effort).
pub fn kill_process_group(process_group_id: u32) -> io::Result<()> {
use std::io::ErrorKind;
let pgid = process_group_id as libc::pid_t;
let result = unsafe { libc::killpg(pgid, libc::SIGKILL) };
if result == -1 {
let err = io::Error::last_os_error();
if err.kind() != ErrorKind::NotFound {
return Err(err);
}
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn kill_process_group(_process_group_id: u32) -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
/// Kill the process group for a tokio child (best-effort).
pub fn kill_child_process_group(child: &mut Child) -> io::Result<()> {
if let Some(pid) = child.id() {
return kill_process_group_by_pid(pid);
}
Ok(())
}
#[cfg(not(unix))]
/// No-op on non-Unix platforms.
pub fn kill_child_process_group(_child: &mut Child) -> io::Result<()> {
Ok(())
}

View file

@ -0,0 +1,483 @@
use std::collections::HashMap;
#[cfg(unix)]
use std::fs::File;
use std::io::ErrorKind;
#[cfg(unix)]
use std::os::fd::AsRawFd;
#[cfg(unix)]
use std::os::fd::FromRawFd;
#[cfg(unix)]
use std::os::fd::RawFd;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::Path;
#[cfg(unix)]
use std::process::Command as StdCommand;
#[cfg(unix)]
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use anyhow::Result;
use portable_pty::CommandBuilder;
#[cfg(not(windows))]
use portable_pty::native_pty_system;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use crate::process::ChildTerminator;
use crate::process::ProcessHandle;
use crate::process::PtyHandles;
use crate::process::PtyMasterHandle;
use crate::process::SpawnedProcess;
use crate::process::TerminalSize;
/// Returns true when ConPTY support is available (Windows only).
#[cfg(windows)]
pub fn conpty_supported() -> bool {
crate::win::conpty_supported()
}
/// Returns true when ConPTY support is available (non-Windows always true).
#[cfg(not(windows))]
pub fn conpty_supported() -> bool {
true
}
struct PtyChildTerminator {
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
#[cfg(unix)]
process_group_id: Option<u32>,
}
impl ChildTerminator for PtyChildTerminator {
fn kill(&mut self) -> std::io::Result<()> {
#[cfg(unix)]
if let Some(process_group_id) = self.process_group_id {
// Match the pipe backend's hard-kill behavior so descendant
// processes from interactive shells/REPLs do not survive shutdown.
// Also try the direct child killer in case the cached PGID is stale.
let process_group_kill_result =
crate::process_group::kill_process_group(process_group_id);
let child_kill_result = self.killer.kill();
return match child_kill_result {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => process_group_kill_result,
Err(err) => process_group_kill_result.or(Err(err)),
};
}
self.killer.kill()
}
}
#[cfg(unix)]
struct RawPidTerminator {
process_group_id: u32,
}
#[cfg(unix)]
impl ChildTerminator for RawPidTerminator {
fn kill(&mut self) -> std::io::Result<()> {
crate::process_group::kill_process_group(self.process_group_id)
}
}
fn platform_native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
{
Box::new(crate::win::ConPtySystem::default())
}
#[cfg(not(windows))]
{
native_pty_system()
}
}
/// Spawn a process attached to a PTY, returning handles for stdin, split output, and exit.
pub async fn spawn_process(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
) -> Result<SpawnedProcess> {
spawn_process_with_inherited_fds(program, args, cwd, env, arg0, size, &[]).await
}
/// Spawn a process attached to a PTY, preserving any inherited file
/// descriptors listed in `inherited_fds` across exec on Unix.
pub async fn spawn_process_with_inherited_fds(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
inherited_fds: &[i32],
) -> Result<SpawnedProcess> {
if program.is_empty() {
anyhow::bail!("missing program for PTY spawn");
}
#[cfg(not(unix))]
let _ = inherited_fds;
#[cfg(unix)]
if !inherited_fds.is_empty() {
return spawn_process_preserving_fds(program, args, cwd, env, arg0, size, inherited_fds)
.await;
}
spawn_process_portable(program, args, cwd, env, arg0, size).await
}
async fn spawn_process_portable(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
) -> Result<SpawnedProcess> {
let pty_system = platform_native_pty_system();
let pair = pty_system.openpty(size.into())?;
let mut command_builder = CommandBuilder::new(arg0.as_ref().unwrap_or(&program.to_string()));
command_builder.cwd(cwd);
command_builder.env_clear();
for arg in args {
command_builder.arg(arg);
}
for (key, value) in env {
command_builder.env(key, value);
}
let mut child = pair.slave.spawn_command(command_builder)?;
#[cfg(unix)]
// portable-pty establishes the spawned PTY child as a new session leader on
// Unix, so PID == PGID and we can reuse the pipe backend's process-group
// hard-kill semantics for descendants.
let process_group_id = child.process_id();
let killer = child.clone_killer();
let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(128);
let (_stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(1);
let mut reader = pair.master.try_clone_reader()?;
let reader_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || {
let mut buf = [0u8; 8_192];
loop {
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
let _ = stdout_tx.blocking_send(buf[..n].to_vec());
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
continue;
}
Err(_) => break,
}
}
});
let writer = pair.master.take_writer()?;
let writer = Arc::new(tokio::sync::Mutex::new(writer));
let writer_handle: JoinHandle<()> = tokio::spawn({
let writer = Arc::clone(&writer);
async move {
while let Some(bytes) = writer_rx.recv().await {
let mut guard = writer.lock().await;
use std::io::Write;
let _ = guard.write_all(&bytes);
let _ = guard.flush();
}
}
});
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let wait_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || {
let code = match child.wait() {
Ok(status) => status.exit_code() as i32,
Err(_) => -1,
};
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_tx.send(code);
});
let handles = PtyHandles {
_slave: if cfg!(windows) {
Some(pair.slave)
} else {
None
},
_master: PtyMasterHandle::Resizable(pair.master),
};
let handle = ProcessHandle::new(
writer_tx,
Box::new(PtyChildTerminator {
killer,
#[cfg(unix)]
process_group_id,
}),
reader_handle,
Vec::new(),
writer_handle,
wait_handle,
exit_status,
exit_code,
Some(handles),
/*resizer*/ None,
);
Ok(SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx,
})
}
#[cfg(unix)]
async fn spawn_process_preserving_fds(
program: &str,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
arg0: &Option<String>,
size: TerminalSize,
inherited_fds: &[RawFd],
) -> Result<SpawnedProcess> {
let (master, slave) = open_unix_pty(size)?;
let mut command = StdCommand::new(program);
if let Some(arg0) = arg0 {
command.arg0(arg0);
}
command.current_dir(cwd);
command.env_clear();
for arg in args {
command.arg(arg);
}
for (key, value) in env {
command.env(key, value);
}
// The child should see one terminal on all three stdio streams. Cloning
// the slave fd gives us three owned handles to the same PTY slave device
// so Command can wire them up independently as stdin/stdout/stderr.
let stdin = slave.try_clone()?;
let stdout = slave.try_clone()?;
let stderr = slave.try_clone()?;
let inherited_fds = inherited_fds.to_vec();
unsafe {
command
.stdin(Stdio::from(stdin))
.stdout(Stdio::from(stdout))
.stderr(Stdio::from(stderr))
.pre_exec(move || {
for signo in &[
libc::SIGCHLD,
libc::SIGHUP,
libc::SIGINT,
libc::SIGQUIT,
libc::SIGTERM,
libc::SIGALRM,
] {
libc::signal(*signo, libc::SIG_DFL);
}
let empty_set: libc::sigset_t = std::mem::zeroed();
libc::sigprocmask(libc::SIG_SETMASK, &empty_set, std::ptr::null_mut());
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
// stdin now refers to the PTY slave, so make that fd the
// controlling terminal for the child's new session. stdout and
// stderr point at clones of the same slave device.
#[allow(clippy::cast_lossless)]
if libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
return Err(std::io::Error::last_os_error());
}
close_inherited_fds_except(&inherited_fds);
Ok(())
});
}
let mut child = command.spawn()?;
drop(slave);
let process_group_id = child.id();
let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(128);
let (_stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(1);
let mut reader = master.try_clone()?;
let reader_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || {
let mut buf = [0u8; 8_192];
loop {
match std::io::Read::read(&mut reader, &mut buf) {
Ok(0) => break,
Ok(n) => {
let _ = stdout_tx.blocking_send(buf[..n].to_vec());
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
continue;
}
Err(_) => break,
}
}
});
let writer = Arc::new(tokio::sync::Mutex::new(master.try_clone()?));
let writer_handle: JoinHandle<()> = tokio::spawn({
let writer = Arc::clone(&writer);
async move {
while let Some(bytes) = writer_rx.recv().await {
let mut guard = writer.lock().await;
use std::io::Write;
let _ = guard.write_all(&bytes);
let _ = guard.flush();
}
}
});
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let exit_status = Arc::new(AtomicBool::new(false));
let wait_exit_status = Arc::clone(&exit_status);
let exit_code = Arc::new(StdMutex::new(None));
let wait_exit_code = Arc::clone(&exit_code);
let wait_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || {
let code = match child.wait() {
Ok(status) => status.code().unwrap_or(-1),
Err(_) => -1,
};
wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = wait_exit_code.lock() {
*guard = Some(code);
}
let _ = exit_tx.send(code);
});
let handles = PtyHandles {
_slave: None,
_master: PtyMasterHandle::Opaque {
raw_fd: master.as_raw_fd(),
_handle: Box::new(master),
},
};
let handle = ProcessHandle::new(
writer_tx,
Box::new(RawPidTerminator { process_group_id }),
reader_handle,
Vec::new(),
writer_handle,
wait_handle,
exit_status,
exit_code,
Some(handles),
/*resizer*/ None,
);
Ok(SpawnedProcess {
session: handle,
stdout_rx,
stderr_rx,
exit_rx,
})
}
#[cfg(unix)]
fn open_unix_pty(size: TerminalSize) -> Result<(File, File)> {
let mut master: RawFd = -1;
let mut slave: RawFd = -1;
let mut size = libc::winsize {
ws_row: size.rows,
ws_col: size.cols,
ws_xpixel: 0,
ws_ypixel: 0,
};
let winp = std::ptr::addr_of_mut!(size);
let result = unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null_mut(),
winp,
)
};
if result != 0 {
anyhow::bail!("failed to openpty: {:?}", std::io::Error::last_os_error());
}
set_cloexec(master)?;
set_cloexec(slave)?;
Ok(unsafe { (File::from_raw_fd(master), File::from_raw_fd(slave)) })
}
#[cfg(unix)]
fn set_cloexec(fd: RawFd) -> std::io::Result<()> {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags == -1 {
return Err(std::io::Error::last_os_error());
}
let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
if result == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
#[cfg(unix)]
pub(crate) fn close_inherited_fds_except(preserved_fds: &[RawFd]) {
if let Ok(dir) = std::fs::read_dir("/dev/fd") {
let mut fds = Vec::new();
for entry in dir {
let num = entry
.ok()
.map(|entry| entry.file_name())
.and_then(|name| name.into_string().ok())
.and_then(|name| name.parse::<RawFd>().ok());
if let Some(num) = num {
if num <= 2 || preserved_fds.contains(&num) {
continue;
}
// Keep CLOEXEC descriptors open so std::process can still use
// its internal exec-error pipe to report spawn failures.
let flags = unsafe { libc::fcntl(num, libc::F_GETFD) };
if flags == -1 || flags & libc::FD_CLOEXEC != 0 {
continue;
}
fds.push(num);
}
}
for fd in fds {
unsafe {
libc::close(fd);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,190 @@
#![allow(clippy::unwrap_used)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use crate::win::psuedocon::PsuedoCon;
use anyhow::Error;
use filedescriptor::FileDescriptor;
use filedescriptor::Pipe;
use portable_pty::Child;
use portable_pty::MasterPty;
use portable_pty::PtyPair;
use portable_pty::PtySize;
use portable_pty::PtySystem;
use portable_pty::SlavePty;
use portable_pty::cmdbuilder::CommandBuilder;
use std::mem::ManuallyDrop;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::RawHandle;
use std::sync::Arc;
use std::sync::Mutex;
use winapi::um::wincon::COORD;
#[derive(Default)]
pub struct ConPtySystem {}
fn create_conpty_handles(
size: PtySize,
) -> anyhow::Result<(PsuedoCon, FileDescriptor, FileDescriptor)> {
let stdin = Pipe::new()?;
let stdout = Pipe::new()?;
let con = PsuedoCon::new(
COORD {
X: size.cols as i16,
Y: size.rows as i16,
},
stdin.read,
stdout.write,
)?;
Ok((con, stdin.write, stdout.read))
}
pub struct RawConPty {
con: PsuedoCon,
input_write: FileDescriptor,
output_read: FileDescriptor,
}
impl RawConPty {
pub fn new(cols: i16, rows: i16) -> anyhow::Result<Self> {
let (con, input_write, output_read) = create_conpty_handles(PtySize {
rows: rows as u16,
cols: cols as u16,
pixel_width: 0,
pixel_height: 0,
})?;
Ok(Self {
con,
input_write,
output_read,
})
}
pub fn pseudoconsole_handle(&self) -> RawHandle {
self.con.raw_handle()
}
pub fn into_raw_handles(self) -> (RawHandle, RawHandle, RawHandle) {
let me = ManuallyDrop::new(self);
(
me.con.raw_handle(),
me.input_write.as_raw_handle(),
me.output_read.as_raw_handle(),
)
}
}
impl PtySystem for ConPtySystem {
fn openpty(&self, size: PtySize) -> anyhow::Result<PtyPair> {
let (con, writable, readable) = create_conpty_handles(size)?;
let master = ConPtyMasterPty {
inner: Arc::new(Mutex::new(Inner {
con,
readable,
writable: Some(writable),
size,
})),
};
let slave = ConPtySlavePty {
inner: master.inner.clone(),
};
Ok(PtyPair {
master: Box::new(master),
slave: Box::new(slave),
})
}
}
struct Inner {
con: PsuedoCon,
readable: FileDescriptor,
writable: Option<FileDescriptor>,
size: PtySize,
}
impl Inner {
pub fn resize(
&mut self,
num_rows: u16,
num_cols: u16,
pixel_width: u16,
pixel_height: u16,
) -> Result<(), Error> {
self.con.resize(COORD {
X: num_cols as i16,
Y: num_rows as i16,
})?;
self.size = PtySize {
rows: num_rows,
cols: num_cols,
pixel_width,
pixel_height,
};
Ok(())
}
}
#[derive(Clone)]
pub struct ConPtyMasterPty {
inner: Arc<Mutex<Inner>>,
}
pub struct ConPtySlavePty {
inner: Arc<Mutex<Inner>>,
}
impl MasterPty for ConPtyMasterPty {
fn resize(&self, size: PtySize) -> anyhow::Result<()> {
let mut inner = self.inner.lock().unwrap();
inner.resize(size.rows, size.cols, size.pixel_width, size.pixel_height)
}
fn get_size(&self) -> Result<PtySize, Error> {
let inner = self.inner.lock().unwrap();
Ok(inner.size)
}
fn try_clone_reader(&self) -> anyhow::Result<Box<dyn std::io::Read + Send>> {
Ok(Box::new(self.inner.lock().unwrap().readable.try_clone()?))
}
fn take_writer(&self) -> anyhow::Result<Box<dyn std::io::Write + Send>> {
Ok(Box::new(
self.inner
.lock()
.unwrap()
.writable
.take()
.ok_or_else(|| anyhow::anyhow!("writer already taken"))?,
))
}
}
impl SlavePty for ConPtySlavePty {
fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<Box<dyn Child + Send + Sync>> {
let inner = self.inner.lock().unwrap();
let child = inner.con.spawn_command(cmd)?;
Ok(Box::new(child))
}
}

View file

@ -0,0 +1,174 @@
#![allow(clippy::unwrap_used)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Local modifications:
// - Fix Codex bug #13945 in the Windows PTY kill path. The vendored code treated
// `TerminateProcess`'s nonzero success return as failure and `0` as success,
// which inverts kill outcomes for both `WinChild::do_kill` and
// `WinChildKiller::kill`.
// - This bug still exists in the original WezTerm source as of 2026-03-08, so
// this is an intentional divergence from upstream.
use anyhow::Context as _;
use filedescriptor::OwnedHandle;
use portable_pty::Child;
use portable_pty::ChildKiller;
use portable_pty::ExitStatus;
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::os::windows::io::AsRawHandle;
use std::pin::Pin;
use std::sync::Mutex;
use std::task::Context;
use std::task::Poll;
use winapi::shared::minwindef::DWORD;
use winapi::um::minwinbase::STILL_ACTIVE;
use winapi::um::processthreadsapi::*;
use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winbase::INFINITE;
pub(crate) mod conpty;
mod procthreadattr;
mod psuedocon;
pub use conpty::ConPtySystem;
pub use psuedocon::conpty_supported;
#[derive(Debug)]
pub struct WinChild {
proc: Mutex<OwnedHandle>,
}
impl WinChild {
fn is_complete(&mut self) -> IoResult<Option<ExitStatus>> {
let mut status: DWORD = 0;
let proc = self.proc.lock().unwrap().try_clone().unwrap();
let res = unsafe { GetExitCodeProcess(proc.as_raw_handle() as _, &mut status) };
if res != 0 {
if status == STILL_ACTIVE {
Ok(None)
} else {
Ok(Some(ExitStatus::with_exit_code(status)))
}
} else {
Ok(None)
}
}
fn do_kill(&mut self) -> IoResult<()> {
let proc = self.proc.lock().unwrap().try_clone().unwrap();
let res = unsafe { TerminateProcess(proc.as_raw_handle() as _, 1) };
// Codex bug #13945: Win32 returns nonzero on success, so only `0` is an error.
if res == 0 {
Err(IoError::last_os_error())
} else {
Ok(())
}
}
}
impl ChildKiller for WinChild {
fn kill(&mut self) -> IoResult<()> {
self.do_kill().ok();
Ok(())
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
let proc = self.proc.lock().unwrap().try_clone().unwrap();
Box::new(WinChildKiller { proc })
}
}
#[derive(Debug)]
pub struct WinChildKiller {
proc: OwnedHandle,
}
impl ChildKiller for WinChildKiller {
fn kill(&mut self) -> IoResult<()> {
let res = unsafe { TerminateProcess(self.proc.as_raw_handle() as _, 1) };
// Codex bug #13945: Win32 returns nonzero on success, so only `0` is an error.
if res == 0 {
Err(IoError::last_os_error())
} else {
Ok(())
}
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
let proc = self.proc.try_clone().unwrap();
Box::new(WinChildKiller { proc })
}
}
impl Child for WinChild {
fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
self.is_complete()
}
fn wait(&mut self) -> IoResult<ExitStatus> {
if let Ok(Some(status)) = self.try_wait() {
return Ok(status);
}
let proc = self.proc.lock().unwrap().try_clone().unwrap();
unsafe {
WaitForSingleObject(proc.as_raw_handle() as _, INFINITE);
}
let mut status: DWORD = 0;
let res = unsafe { GetExitCodeProcess(proc.as_raw_handle() as _, &mut status) };
if res != 0 {
Ok(ExitStatus::with_exit_code(status))
} else {
Err(IoError::last_os_error())
}
}
fn process_id(&self) -> Option<u32> {
let res = unsafe { GetProcessId(self.proc.lock().unwrap().as_raw_handle() as _) };
if res == 0 { None } else { Some(res) }
}
fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
let proc = self.proc.lock().unwrap();
Some(proc.as_raw_handle())
}
}
impl std::future::Future for WinChild {
type Output = anyhow::Result<ExitStatus>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<anyhow::Result<ExitStatus>> {
match self.is_complete() {
Ok(Some(status)) => Poll::Ready(Ok(status)),
Err(err) => Poll::Ready(Err(err).context("Failed to retrieve process exit status")),
Ok(None) => {
let proc = self.proc.lock().unwrap().try_clone()?;
let waker = cx.waker().clone();
std::thread::spawn(move || {
unsafe {
WaitForSingleObject(proc.as_raw_handle() as _, INFINITE);
}
waker.wake();
});
Poll::Pending
}
}
}
}

View file

@ -0,0 +1,91 @@
#![allow(clippy::uninit_vec)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use super::psuedocon::HPCON;
use anyhow::Error;
use anyhow::ensure;
use std::io::Error as IoError;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::DWORD;
use winapi::um::processthreadsapi::*;
const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 0x00020016;
pub struct ProcThreadAttributeList {
data: Vec<u8>,
}
impl ProcThreadAttributeList {
pub fn with_capacity(num_attributes: DWORD) -> Result<Self, Error> {
let mut bytes_required: usize = 0;
unsafe {
InitializeProcThreadAttributeList(
ptr::null_mut(),
num_attributes,
0,
&mut bytes_required,
)
};
let mut data = Vec::with_capacity(bytes_required);
unsafe { data.set_len(bytes_required) };
let attr_ptr = data.as_mut_slice().as_mut_ptr() as *mut _;
let res = unsafe {
InitializeProcThreadAttributeList(attr_ptr, num_attributes, 0, &mut bytes_required)
};
ensure!(
res != 0,
"InitializeProcThreadAttributeList failed: {}",
IoError::last_os_error()
);
Ok(Self { data })
}
pub fn as_mut_ptr(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
self.data.as_mut_slice().as_mut_ptr() as *mut _
}
pub fn set_pty(&mut self, con: HPCON) -> Result<(), Error> {
let res = unsafe {
UpdateProcThreadAttribute(
self.as_mut_ptr(),
0,
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
con,
mem::size_of::<HPCON>(),
ptr::null_mut(),
ptr::null_mut(),
)
};
ensure!(
res != 0,
"UpdateProcThreadAttribute failed: {}",
IoError::last_os_error()
);
Ok(())
}
}
impl Drop for ProcThreadAttributeList {
fn drop(&mut self) {
unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
}
}

View file

@ -0,0 +1,377 @@
#![allow(clippy::expect_used)]
#![allow(clippy::upper_case_acronyms)]
// This file is copied from https://github.com/wezterm/wezterm (MIT license).
// Copyright (c) 2018-Present Wez Furlong
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use super::WinChild;
use crate::win::procthreadattr::ProcThreadAttributeList;
use anyhow::Error;
use anyhow::bail;
use anyhow::ensure;
use filedescriptor::FileDescriptor;
use filedescriptor::OwnedHandle;
use lazy_static::lazy_static;
use portable_pty::cmdbuilder::CommandBuilder;
use shared_library::shared_library;
use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::Error as IoError;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::path::Path;
use std::ptr;
use std::sync::Mutex;
use winapi::shared::minwindef::DWORD;
use winapi::shared::ntdef::NTSTATUS;
use winapi::shared::ntstatus::STATUS_SUCCESS;
use winapi::shared::winerror::HRESULT;
use winapi::shared::winerror::S_OK;
use winapi::um::handleapi::*;
use winapi::um::processthreadsapi::*;
use winapi::um::winbase::CREATE_UNICODE_ENVIRONMENT;
use winapi::um::winbase::EXTENDED_STARTUPINFO_PRESENT;
use winapi::um::winbase::STARTF_USESTDHANDLES;
use winapi::um::winbase::STARTUPINFOEXW;
use winapi::um::wincon::COORD;
use winapi::um::winnt::HANDLE;
use winapi::um::winnt::OSVERSIONINFOW;
pub type HPCON = HANDLE;
pub const PSEUDOCONSOLE_RESIZE_QUIRK: DWORD = 0x2;
#[allow(dead_code)]
pub const PSEUDOCONSOLE_PASSTHROUGH_MODE: DWORD = 0x8;
// https://learn.microsoft.com/en-gb/windows/console/createpseudoconsole
// https://learn.microsoft.com/en-gb/windows/release-health/release-information
const MIN_CONPTY_BUILD: u32 = 17_763;
shared_library!(ConPtyFuncs,
pub fn CreatePseudoConsole(
size: COORD,
hInput: HANDLE,
hOutput: HANDLE,
flags: DWORD,
hpc: *mut HPCON
) -> HRESULT,
pub fn ResizePseudoConsole(hpc: HPCON, size: COORD) -> HRESULT,
pub fn ClosePseudoConsole(hpc: HPCON),
);
shared_library!(Ntdll,
pub fn RtlGetVersion(
version_info: *mut OSVERSIONINFOW
) -> NTSTATUS,
);
fn load_conpty() -> ConPtyFuncs {
let kernel = ConPtyFuncs::open(Path::new("kernel32.dll")).expect(
"this system does not support conpty. Windows 10 October 2018 or newer is required",
);
if let Ok(sideloaded) = ConPtyFuncs::open(Path::new("conpty.dll")) {
sideloaded
} else {
kernel
}
}
lazy_static! {
static ref CONPTY: ConPtyFuncs = load_conpty();
}
pub fn conpty_supported() -> bool {
windows_build_number().is_some_and(|build| build >= MIN_CONPTY_BUILD)
}
fn windows_build_number() -> Option<u32> {
let ntdll = Ntdll::open(Path::new("ntdll.dll")).ok()?;
let mut info: OSVERSIONINFOW = unsafe { mem::zeroed() };
info.dwOSVersionInfoSize = mem::size_of::<OSVERSIONINFOW>() as u32;
let status = unsafe { (ntdll.RtlGetVersion)(&mut info) };
if status == STATUS_SUCCESS {
Some(info.dwBuildNumber)
} else {
None
}
}
pub struct PsuedoCon {
con: HPCON,
// CreatePseudoConsole borrows these pipe handles for the lifetime of the
// pseudoconsole, so we must keep owning them until ClosePseudoConsole.
_input: FileDescriptor,
_output: FileDescriptor,
}
unsafe impl Send for PsuedoCon {}
unsafe impl Sync for PsuedoCon {}
impl Drop for PsuedoCon {
fn drop(&mut self) {
unsafe { (CONPTY.ClosePseudoConsole)(self.con) };
}
}
impl PsuedoCon {
pub fn raw_handle(&self) -> HPCON {
self.con
}
pub fn new(size: COORD, input: FileDescriptor, output: FileDescriptor) -> Result<Self, Error> {
let mut con: HPCON = INVALID_HANDLE_VALUE;
let result = unsafe {
(CONPTY.CreatePseudoConsole)(
size,
input.as_raw_handle() as _,
output.as_raw_handle() as _,
PSEUDOCONSOLE_RESIZE_QUIRK,
&mut con,
)
};
ensure!(
result == S_OK,
"failed to create psuedo console: HRESULT {result}"
);
Ok(Self {
con,
_input: input,
_output: output,
})
}
pub fn resize(&self, size: COORD) -> Result<(), Error> {
let result = unsafe { (CONPTY.ResizePseudoConsole)(self.con, size) };
ensure!(
result == S_OK,
"failed to resize console to {}x{}: HRESULT: {}",
size.X,
size.Y,
result
);
Ok(())
}
pub fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<WinChild> {
let mut si: STARTUPINFOEXW = unsafe { mem::zeroed() };
si.StartupInfo.cb = mem::size_of::<STARTUPINFOEXW>() as u32;
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdError = INVALID_HANDLE_VALUE;
let mut attrs = ProcThreadAttributeList::with_capacity(/*num_attributes*/ 1)?;
attrs.set_pty(self.con)?;
si.lpAttributeList = attrs.as_mut_ptr();
let mut pi: PROCESS_INFORMATION = unsafe { mem::zeroed() };
let (mut exe, mut cmdline) = build_cmdline(&cmd)?;
let cmd_os = OsString::from_wide(&cmdline);
let cwd = resolve_current_directory(&cmd);
let mut env_block = build_environment_block(&cmd);
let res = unsafe {
CreateProcessW(
exe.as_mut_ptr(),
cmdline.as_mut_ptr(),
ptr::null_mut(),
ptr::null_mut(),
0,
EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,
env_block.as_mut_ptr() as *mut _,
cwd.as_ref().map_or(ptr::null(), std::vec::Vec::as_ptr),
&mut si.StartupInfo,
&mut pi,
)
};
if res == 0 {
let err = IoError::last_os_error();
let msg = format!(
"CreateProcessW `{:?}` in cwd `{:?}` failed: {}",
cmd_os,
cwd.as_ref().map(|c| OsString::from_wide(c)),
err
);
log::error!("{msg}");
bail!("{msg}");
}
let _main_thread = unsafe { OwnedHandle::from_raw_handle(pi.hThread as _) };
let proc = unsafe { OwnedHandle::from_raw_handle(pi.hProcess as _) };
Ok(WinChild {
proc: Mutex::new(proc),
})
}
}
fn resolve_current_directory(cmd: &CommandBuilder) -> Option<Vec<u16>> {
let home = cmd
.get_env("USERPROFILE")
.and_then(|path| Path::new(path).is_dir().then(|| path.to_owned()));
let cwd = cmd
.get_cwd()
.and_then(|path| Path::new(path).is_dir().then(|| path.to_owned()));
let dir = cwd.or(home)?;
let mut wide = Vec::new();
if Path::new(&dir).is_relative() {
if let Ok(current_dir) = env::current_dir() {
wide.extend(current_dir.join(&dir).as_os_str().encode_wide());
} else {
wide.extend(dir.encode_wide());
}
} else {
wide.extend(dir.encode_wide());
}
wide.push(0);
Some(wide)
}
fn build_environment_block(cmd: &CommandBuilder) -> Vec<u16> {
let mut block = Vec::new();
for (key, value) in cmd.iter_full_env_as_str() {
block.extend(OsStr::new(key).encode_wide());
block.push(b'=' as u16);
block.extend(OsStr::new(value).encode_wide());
block.push(0);
}
block.push(0);
block
}
fn build_cmdline(cmd: &CommandBuilder) -> anyhow::Result<(Vec<u16>, Vec<u16>)> {
let exe_os: OsString = if cmd.is_default_prog() {
cmd.get_env("ComSpec")
.unwrap_or(OsStr::new("cmd.exe"))
.to_os_string()
} else {
let argv = cmd.get_argv();
let Some(first) = argv.first() else {
anyhow::bail!("missing program name");
};
search_path(cmd, first)
};
let mut cmdline = Vec::new();
append_quoted(&exe_os, &mut cmdline);
for arg in cmd.get_argv().iter().skip(1) {
cmdline.push(' ' as u16);
ensure!(
!arg.encode_wide().any(|c| c == 0),
"invalid encoding for command line argument {arg:?}"
);
append_quoted(arg, &mut cmdline);
}
cmdline.push(0);
let mut exe: Vec<u16> = exe_os.encode_wide().collect();
exe.push(0);
Ok((exe, cmdline))
}
fn search_path(cmd: &CommandBuilder, exe: &OsStr) -> OsString {
if let Some(path) = cmd.get_env("PATH") {
let extensions = cmd.get_env("PATHEXT").unwrap_or(OsStr::new(".EXE"));
for path in env::split_paths(path) {
let candidate = path.join(exe);
if candidate.exists() {
return candidate.into_os_string();
}
for ext in env::split_paths(extensions) {
let ext = ext.to_str().unwrap_or("");
let path = path
.join(exe)
.with_extension(ext.strip_prefix('.').unwrap_or(ext));
if path.exists() {
return path.into_os_string();
}
}
}
}
exe.to_os_string()
}
fn append_quoted(arg: &OsStr, cmdline: &mut Vec<u16>) {
if !arg.is_empty()
&& !arg.encode_wide().any(|c| {
c == ' ' as u16
|| c == '\t' as u16
|| c == '\n' as u16
|| c == '\x0b' as u16
|| c == '\"' as u16
})
{
cmdline.extend(arg.encode_wide());
return;
}
cmdline.push('"' as u16);
let arg: Vec<_> = arg.encode_wide().collect();
let mut i = 0;
while i < arg.len() {
let mut num_backslashes = 0;
while i < arg.len() && arg[i] == '\\' as u16 {
i += 1;
num_backslashes += 1;
}
if i == arg.len() {
for _ in 0..num_backslashes * 2 {
cmdline.push('\\' as u16);
}
break;
} else if arg[i] == b'"' as u16 {
for _ in 0..num_backslashes * 2 + 1 {
cmdline.push('\\' as u16);
}
cmdline.push(arg[i]);
} else {
for _ in 0..num_backslashes {
cmdline.push('\\' as u16);
}
cmdline.push(arg[i]);
}
i += 1;
}
cmdline.push('"' as u16);
}
#[cfg(test)]
mod tests {
use super::MIN_CONPTY_BUILD;
use super::windows_build_number;
#[test]
fn windows_build_number_returns_value() {
// We can't stably check the version of the GH workers, but we can
// at least check that this.
let version = windows_build_number().unwrap();
assert!(version > MIN_CONPTY_BUILD);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "readiness",
crate_name = "codex_utils_readiness",
)

View file

@ -0,0 +1,18 @@
[package]
name = "codex-utils-readiness"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
async-trait = { workspace = true }
thiserror = { workspace = true }
time = { workspace = true }
tokio = { workspace = true, features = ["sync", "time"] }
[dev-dependencies]
assert_matches = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread"] }
[lints]
workspace = true

View file

@ -0,0 +1,333 @@
//! Readiness flag with token-based authorization and async waiting (Tokio).
use std::collections::HashSet;
use std::fmt;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::sync::watch;
use tokio::time;
/// Opaque subscription token returned by `subscribe()`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Token(i32);
const LOCK_TIMEOUT: Duration = Duration::from_millis(1000);
#[async_trait::async_trait]
pub trait Readiness: Send + Sync + 'static {
/// Returns true if the flag is currently marked ready. At least one token needs to be marked
/// as ready before.
/// `true` is not reversible.
fn is_ready(&self) -> bool;
/// Subscribe to readiness and receive an authorization token.
///
/// If the flag is already ready, returns `FlagAlreadyReady`.
async fn subscribe(&self) -> Result<Token, errors::ReadinessError>;
/// Attempt to mark the flag ready, validated by the provided token.
///
/// Returns `true` iff:
/// - `token` is currently subscribed, and
/// - the flag was not already ready.
async fn mark_ready(&self, token: Token) -> Result<bool, errors::ReadinessError>;
/// Asynchronously wait until the flag becomes ready.
async fn wait_ready(&self);
}
pub struct ReadinessFlag {
/// Atomic for cheap reads.
ready: AtomicBool,
/// Used to generate the next i32 token.
next_id: AtomicI32,
/// Set of active subscriptions.
tokens: Mutex<HashSet<Token>>,
/// Broadcasts readiness to async waiters.
tx: watch::Sender<bool>,
}
impl ReadinessFlag {
/// Create a new, not-yet-ready flag.
pub fn new() -> Self {
let (tx, _rx) = watch::channel(false);
Self {
ready: AtomicBool::new(false),
next_id: AtomicI32::new(1), // Reserve 0.
tokens: Mutex::new(HashSet::new()),
tx,
}
}
async fn with_tokens<R>(
&self,
f: impl FnOnce(&mut HashSet<Token>) -> R,
) -> Result<R, errors::ReadinessError> {
let mut guard = time::timeout(LOCK_TIMEOUT, self.tokens.lock())
.await
.map_err(|_| errors::ReadinessError::TokenLockFailed)?;
Ok(f(&mut guard))
}
fn load_ready(&self) -> bool {
self.ready.load(Ordering::Acquire)
}
}
impl Default for ReadinessFlag {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for ReadinessFlag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReadinessFlag")
.field("ready", &self.load_ready())
.finish()
}
}
#[async_trait::async_trait]
impl Readiness for ReadinessFlag {
fn is_ready(&self) -> bool {
if self.load_ready() {
return true;
}
if let Ok(tokens) = self.tokens.try_lock()
&& tokens.is_empty()
{
let was_ready = self.ready.swap(true, Ordering::AcqRel);
drop(tokens);
if !was_ready {
let _ = self.tx.send(true);
}
return true;
}
self.load_ready()
}
async fn subscribe(&self) -> Result<Token, errors::ReadinessError> {
if self.load_ready() {
return Err(errors::ReadinessError::FlagAlreadyReady);
}
// Recheck readiness while holding the lock so mark_ready can't flip the flag between the
// check above and inserting the token. Also ensure the token is non-zero and unique in
// the presence of `i32` wrap-around.
let token = self
.with_tokens(|tokens| {
if self.load_ready() {
return None;
}
loop {
let token = Token(self.next_id.fetch_add(1, Ordering::Relaxed));
if token.0 != 0 && tokens.insert(token) {
return Some(token);
}
}
})
.await?;
token.ok_or(errors::ReadinessError::FlagAlreadyReady)
}
async fn mark_ready(&self, token: Token) -> Result<bool, errors::ReadinessError> {
if self.load_ready() {
return Ok(false);
}
if token.0 == 0 {
return Ok(false); // Never authorize.
}
let marked = self
.with_tokens(|set| {
if !set.remove(&token) {
return false; // invalid or already used
}
self.ready.store(true, Ordering::Release);
set.clear(); // no further tokens needed once ready
true
})
.await?;
if !marked {
return Ok(false);
}
// Best-effort broadcast; ignore error if there are no receivers.
let _ = self.tx.send(true);
Ok(true)
}
async fn wait_ready(&self) {
if self.is_ready() {
return;
}
let mut rx = self.tx.subscribe();
// Fast-path check before awaiting.
if *rx.borrow() {
return;
}
// Await changes until true is observed.
while rx.changed().await.is_ok() {
if *rx.borrow() {
break;
}
}
}
}
mod errors {
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ReadinessError {
#[error("Failed to acquire readiness token lock")]
TokenLockFailed,
#[error("Flag is already ready. Impossible to subscribe")]
FlagAlreadyReady,
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::Ordering;
use super::Readiness;
use super::ReadinessFlag;
use super::Token;
use super::errors::ReadinessError;
use assert_matches::assert_matches;
#[tokio::test]
async fn subscribe_and_mark_ready_roundtrip() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
let token = flag.subscribe().await?;
assert!(flag.mark_ready(token).await?);
assert!(flag.is_ready());
Ok(())
}
#[tokio::test]
async fn subscribe_after_ready_returns_none() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
let token = flag.subscribe().await?;
assert!(flag.mark_ready(token).await?);
assert!(flag.subscribe().await.is_err());
Ok(())
}
#[tokio::test]
async fn mark_ready_rejects_unknown_token() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
assert!(!flag.mark_ready(Token(42)).await?);
assert!(!flag.load_ready());
assert!(flag.is_ready());
Ok(())
}
#[tokio::test]
async fn wait_ready_unblocks_after_mark_ready() -> Result<(), ReadinessError> {
let flag = Arc::new(ReadinessFlag::new());
let token = flag.subscribe().await?;
let waiter = {
let flag = Arc::clone(&flag);
tokio::spawn(async move {
flag.wait_ready().await;
})
};
assert!(flag.mark_ready(token).await?);
waiter.await.expect("waiting task should not panic");
Ok(())
}
#[tokio::test]
async fn mark_ready_twice_uses_single_token() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
let token = flag.subscribe().await?;
assert!(flag.mark_ready(token).await?);
assert!(!flag.mark_ready(token).await?);
Ok(())
}
#[tokio::test]
async fn is_ready_without_subscribers_marks_flag_ready() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
assert!(flag.is_ready());
assert!(flag.is_ready());
assert_matches!(
flag.subscribe().await,
Err(ReadinessError::FlagAlreadyReady)
);
Ok(())
}
#[tokio::test]
async fn subscribe_returns_error_when_lock_is_held() {
let flag = Arc::new(ReadinessFlag::new());
let (locked_tx, locked_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let lock_thread = {
let flag = Arc::clone(&flag);
std::thread::spawn(move || {
let _guard = flag.tokens.blocking_lock();
locked_tx
.send(())
.expect("test should receive lock acquisition notification");
release_rx
.recv()
.expect("test should release held readiness lock");
})
};
locked_rx
.recv()
.expect("test should observe held readiness lock");
let err = flag
.subscribe()
.await
.expect_err("contended subscribe should report a lock failure");
assert_matches!(err, ReadinessError::TokenLockFailed);
release_tx
.send(())
.expect("test should release readiness lock thread");
lock_thread
.join()
.expect("readiness lock thread should not panic");
}
#[tokio::test]
async fn subscribe_skips_zero_token() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
flag.next_id.store(0, Ordering::Relaxed);
let token = flag.subscribe().await?;
assert_ne!(token, Token(0));
assert!(flag.mark_ready(token).await?);
Ok(())
}
#[tokio::test]
async fn subscribe_avoids_duplicate_tokens() -> Result<(), ReadinessError> {
let flag = ReadinessFlag::new();
let token = flag.subscribe().await?;
flag.next_id.store(token.0, Ordering::Relaxed);
let token2 = flag.subscribe().await?;
assert_ne!(token2, token);
Ok(())
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "rustls-provider",
crate_name = "codex_utils_rustls_provider",
)

View file

@ -0,0 +1,11 @@
[package]
name = "codex-utils-rustls-provider"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
rustls = { workspace = true }

View file

@ -0,0 +1,12 @@
use std::sync::Once;
/// Ensures a process-wide rustls crypto provider is installed.
///
/// rustls cannot auto-select a provider when both `ring` and `aws-lc-rs`
/// features are enabled in the dependency graph.
pub fn ensure_rustls_crypto_provider() {
static RUSTLS_PROVIDER_INIT: Once = Once::new();
RUSTLS_PROVIDER_INIT.call_once(|| {
let _ = rustls::crypto::ring::default_provider().install_default();
});
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "sandbox-summary",
crate_name = "codex_utils_sandbox_summary",
)

View file

@ -0,0 +1,17 @@
[package]
name = "codex-utils-sandbox-summary"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
codex-core = { workspace = true }
codex-model-provider-info = { workspace = true }
codex-protocol = { workspace = true }
[dev-dependencies]
codex-utils-absolute-path = { workspace = true }
pretty_assertions = { workspace = true }

View file

@ -0,0 +1,39 @@
use codex_core::config::Config;
use codex_model_provider_info::WireApi;
use crate::sandbox_summary::summarize_sandbox_policy;
/// Build a list of key/value pairs summarizing the effective configuration.
pub fn create_config_summary_entries(config: &Config, model: &str) -> Vec<(&'static str, String)> {
let mut entries = vec![
("workdir", config.cwd.display().to_string()),
("model", model.to_string()),
("provider", config.model_provider_id.clone()),
(
"approval",
config.permissions.approval_policy.value().to_string(),
),
(
"sandbox",
summarize_sandbox_policy(config.permissions.sandbox_policy.get()),
),
];
if config.model_provider.wire_api == WireApi::Responses {
let reasoning_effort = config
.model_reasoning_effort
.map(|effort| effort.to_string());
entries.push((
"reasoning effort",
reasoning_effort.unwrap_or_else(|| "none".to_string()),
));
entries.push((
"reasoning summaries",
config
.model_reasoning_summary
.map(|summary| summary.to_string())
.unwrap_or_else(|| "none".to_string()),
));
}
entries
}

View file

@ -0,0 +1,5 @@
mod config_summary;
mod sandbox_summary;
pub use config_summary::create_config_summary_entries;
pub use sandbox_summary::summarize_sandbox_policy;

View file

@ -0,0 +1,103 @@
use codex_protocol::protocol::NetworkAccess;
use codex_protocol::protocol::SandboxPolicy;
pub fn summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String {
match sandbox_policy {
SandboxPolicy::DangerFullAccess => "danger-full-access".to_string(),
SandboxPolicy::ReadOnly { network_access, .. } => {
let mut summary = "read-only".to_string();
if *network_access {
summary.push_str(" (network access enabled)");
}
summary
}
SandboxPolicy::ExternalSandbox { network_access } => {
let mut summary = "external-sandbox".to_string();
if matches!(network_access, NetworkAccess::Enabled) {
summary.push_str(" (network access enabled)");
}
summary
}
SandboxPolicy::WorkspaceWrite {
writable_roots,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
read_only_access: _,
} => {
let mut summary = "workspace-write".to_string();
let mut writable_entries = Vec::<String>::new();
writable_entries.push("workdir".to_string());
if !*exclude_slash_tmp {
writable_entries.push("/tmp".to_string());
}
if !*exclude_tmpdir_env_var {
writable_entries.push("$TMPDIR".to_string());
}
writable_entries.extend(
writable_roots
.iter()
.map(|p| p.to_string_lossy().to_string()),
);
summary.push_str(&format!(" [{}]", writable_entries.join(", ")));
if *network_access {
summary.push_str(" (network access enabled)");
}
summary
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
#[test]
fn summarizes_external_sandbox_without_network_access_suffix() {
let summary = summarize_sandbox_policy(&SandboxPolicy::ExternalSandbox {
network_access: NetworkAccess::Restricted,
});
assert_eq!(summary, "external-sandbox");
}
#[test]
fn summarizes_external_sandbox_with_enabled_network() {
let summary = summarize_sandbox_policy(&SandboxPolicy::ExternalSandbox {
network_access: NetworkAccess::Enabled,
});
assert_eq!(summary, "external-sandbox (network access enabled)");
}
#[test]
fn summarizes_read_only_with_enabled_network() {
let summary = summarize_sandbox_policy(&SandboxPolicy::ReadOnly {
access: Default::default(),
network_access: true,
});
assert_eq!(summary, "read-only (network access enabled)");
}
#[test]
fn workspace_write_summary_still_includes_network_access() {
let root = if cfg!(windows) { "C:\\repo" } else { "/repo" };
let writable_root = AbsolutePathBuf::try_from(root).unwrap();
let summary = summarize_sandbox_policy(&SandboxPolicy::WorkspaceWrite {
writable_roots: vec![writable_root.clone()],
read_only_access: Default::default(),
network_access: true,
exclude_tmpdir_env_var: true,
exclude_slash_tmp: true,
});
assert_eq!(
summary,
format!(
"workspace-write [workdir, {}] (network access enabled)",
writable_root.to_string_lossy()
)
);
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "sleep-inhibitor",
crate_name = "codex_utils_sleep_inhibitor",
)

View file

@ -0,0 +1,25 @@
[package]
name = "codex-utils-sleep-inhibitor"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
tracing = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = "0.9"
[target.'cfg(target_os = "linux")'.dependencies]
libc = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_System_Power",
"Win32_System_SystemServices",
"Win32_System_Threading",
] }

View file

@ -0,0 +1,12 @@
#[derive(Debug, Default)]
pub(crate) struct SleepInhibitor;
impl SleepInhibitor {
pub(crate) fn new() -> Self {
Self
}
pub(crate) fn acquire(&mut self) {}
pub(crate) fn release(&mut self) {}
}

View file

@ -0,0 +1,27 @@
/* automatically generated by rust-bindgen 0.71.1 */
pub const kIOReturnSuccess: u32 = 0;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFString {
_unused: [u8; 0],
}
pub type CFStringRef = *const __CFString;
pub type kern_return_t = ::std::os::raw::c_int;
pub type IOReturn = kern_return_t;
pub type IOPMAssertionID = u32;
pub type IOPMAssertionLevel = u32;
pub const kIOPMAssertionLevelOff: _bindgen_ty_36 = 0;
pub const kIOPMAssertionLevelOn: _bindgen_ty_36 = 255;
pub type _bindgen_ty_36 = ::std::os::raw::c_uint;
unsafe extern "C" {
pub fn IOPMAssertionRelease(AssertionID: IOPMAssertionID) -> IOReturn;
}
unsafe extern "C" {
pub fn IOPMAssertionCreateWithName(
AssertionType: CFStringRef,
AssertionLevel: IOPMAssertionLevel,
AssertionName: CFStringRef,
AssertionID: *mut IOPMAssertionID,
) -> IOReturn;
}

View file

@ -0,0 +1,113 @@
//! Cross-platform helper for preventing idle sleep while a turn is running.
//!
//! Platform-specific behavior:
//! - macOS: Uses native IOKit power assertions instead of spawning `caffeinate`.
//! - Linux: Spawns `systemd-inhibit` or `gnome-session-inhibit` while active.
//! - Windows: Uses `PowerCreateRequest` + `PowerSetRequest` with
//! `PowerRequestSystemRequired`.
//! - Other platforms: No-op backend.
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
mod dummy;
#[cfg(target_os = "linux")]
mod linux_inhibitor;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows_inhibitor;
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
use dummy as imp;
#[cfg(target_os = "linux")]
use linux_inhibitor as imp;
#[cfg(target_os = "macos")]
use macos as imp;
#[cfg(target_os = "windows")]
use windows_inhibitor as imp;
/// Keeps the machine awake while a turn is in progress when enabled.
#[derive(Debug)]
pub struct SleepInhibitor {
enabled: bool,
turn_running: bool,
platform: imp::SleepInhibitor,
}
impl SleepInhibitor {
pub fn new(enabled: bool) -> Self {
Self {
enabled,
turn_running: false,
platform: imp::SleepInhibitor::new(),
}
}
/// Update the active turn state; turns sleep prevention on/off as needed.
pub fn set_turn_running(&mut self, turn_running: bool) {
self.turn_running = turn_running;
if !self.enabled {
self.release();
return;
}
if turn_running {
self.acquire();
} else {
self.release();
}
}
fn acquire(&mut self) {
self.platform.acquire();
}
fn release(&mut self) {
self.platform.release();
}
/// Return the latest turn-running state requested by the caller.
pub fn is_turn_running(&self) -> bool {
self.turn_running
}
}
#[cfg(test)]
mod tests {
use super::SleepInhibitor;
#[test]
fn sleep_inhibitor_toggles_without_panicking() {
let mut inhibitor = SleepInhibitor::new(/*enabled*/ true);
inhibitor.set_turn_running(/*turn_running*/ true);
assert!(inhibitor.is_turn_running());
inhibitor.set_turn_running(/*turn_running*/ false);
assert!(!inhibitor.is_turn_running());
}
#[test]
fn sleep_inhibitor_disabled_does_not_panic() {
let mut inhibitor = SleepInhibitor::new(/*enabled*/ false);
inhibitor.set_turn_running(/*turn_running*/ true);
assert!(inhibitor.is_turn_running());
inhibitor.set_turn_running(/*turn_running*/ false);
assert!(!inhibitor.is_turn_running());
}
#[test]
fn sleep_inhibitor_multiple_true_calls_are_idempotent() {
let mut inhibitor = SleepInhibitor::new(/*enabled*/ true);
inhibitor.set_turn_running(/*turn_running*/ true);
inhibitor.set_turn_running(/*turn_running*/ true);
inhibitor.set_turn_running(/*turn_running*/ true);
inhibitor.set_turn_running(/*turn_running*/ false);
}
#[test]
fn sleep_inhibitor_can_toggle_multiple_times() {
let mut inhibitor = SleepInhibitor::new(/*enabled*/ true);
inhibitor.set_turn_running(/*turn_running*/ true);
inhibitor.set_turn_running(/*turn_running*/ false);
inhibitor.set_turn_running(/*turn_running*/ true);
inhibitor.set_turn_running(/*turn_running*/ false);
}
}

View file

@ -0,0 +1,240 @@
use std::os::unix::process::CommandExt;
use std::process::Child;
use std::process::Command;
use std::process::Stdio;
use tracing::warn;
const ASSERTION_REASON: &str = "Codex is running an active turn";
const APP_ID: &str = "codex";
// Keep the blocker process alive "long enough" without needing restarts.
// This is `i32::MAX` seconds, which is accepted by common `sleep` implementations.
const BLOCKER_SLEEP_SECONDS: &str = "2147483647";
#[derive(Debug, Default)]
pub(crate) struct LinuxSleepInhibitor {
state: InhibitState,
preferred_backend: Option<LinuxBackend>,
missing_backend_logged: bool,
}
pub(crate) use LinuxSleepInhibitor as SleepInhibitor;
#[derive(Debug, Default)]
enum InhibitState {
#[default]
Inactive,
Active {
backend: LinuxBackend,
child: Child,
},
}
#[derive(Debug, Clone, Copy)]
enum LinuxBackend {
SystemdInhibit,
GnomeSessionInhibit,
}
impl LinuxSleepInhibitor {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn acquire(&mut self) {
if let InhibitState::Active { backend, child } = &mut self.state {
match child.try_wait() {
Ok(None) => return,
Ok(Some(status)) => {
warn!(
?backend,
?status,
"Linux sleep inhibitor backend exited unexpectedly; attempting fallback"
);
}
Err(error) => {
warn!(
?backend,
reason = %error,
"Failed to query Linux sleep inhibitor backend status; attempting restart"
);
}
}
}
self.state = InhibitState::Inactive;
let should_log_backend_failures = !self.missing_backend_logged;
let backends = match self.preferred_backend {
Some(LinuxBackend::SystemdInhibit) => [
LinuxBackend::SystemdInhibit,
LinuxBackend::GnomeSessionInhibit,
],
Some(LinuxBackend::GnomeSessionInhibit) => [
LinuxBackend::GnomeSessionInhibit,
LinuxBackend::SystemdInhibit,
],
None => [
LinuxBackend::SystemdInhibit,
LinuxBackend::GnomeSessionInhibit,
],
};
for backend in backends {
match spawn_backend(backend) {
Ok(mut child) => match child.try_wait() {
Ok(None) => {
self.state = InhibitState::Active { backend, child };
self.preferred_backend = Some(backend);
self.missing_backend_logged = false;
return;
}
Ok(Some(status)) => {
if should_log_backend_failures {
warn!(
?backend,
?status,
"Linux sleep inhibitor backend exited immediately"
);
}
}
Err(error) => {
if should_log_backend_failures {
warn!(
?backend,
reason = %error,
"Failed to query Linux sleep inhibitor backend status after spawn"
);
}
if let Err(kill_error) = child.kill()
&& !child_exited(&kill_error)
{
warn!(
?backend,
reason = %kill_error,
"Failed to stop Linux sleep inhibitor backend after status probe failure"
);
}
if let Err(wait_error) = child.wait()
&& !child_exited(&wait_error)
{
warn!(
?backend,
reason = %wait_error,
"Failed to reap Linux sleep inhibitor backend after status probe failure"
);
}
}
},
Err(error) => {
if should_log_backend_failures && error.kind() != std::io::ErrorKind::NotFound {
warn!(
?backend,
reason = %error,
"Failed to start Linux sleep inhibitor backend"
);
}
}
}
}
if should_log_backend_failures {
warn!("No Linux sleep inhibitor backend is available");
self.missing_backend_logged = true;
}
}
pub(crate) fn release(&mut self) {
match std::mem::take(&mut self.state) {
InhibitState::Inactive => {}
InhibitState::Active { backend, mut child } => {
if let Err(error) = child.kill()
&& !child_exited(&error)
{
warn!(?backend, reason = %error, "Failed to stop Linux sleep inhibitor backend");
}
if let Err(error) = child.wait()
&& !child_exited(&error)
{
warn!(?backend, reason = %error, "Failed to reap Linux sleep inhibitor backend");
}
}
}
}
}
impl Drop for LinuxSleepInhibitor {
fn drop(&mut self) {
self.release();
}
}
fn spawn_backend(backend: LinuxBackend) -> Result<Child, std::io::Error> {
// Ensure the helper receives SIGTERM when the original parent dies.
// `parent_pid` is captured before spawn and checked in `pre_exec` to avoid
// the fork/exec race where the parent exits before PDEATHSIG is armed.
// SAFETY: `getpid` has no preconditions and is safe to call here.
let parent_pid = unsafe { libc::getpid() };
let mut command = match backend {
LinuxBackend::SystemdInhibit => {
let mut command = Command::new("systemd-inhibit");
command.args([
"--what=idle",
"--mode=block",
"--who",
APP_ID,
"--why",
ASSERTION_REASON,
"--",
"sleep",
BLOCKER_SLEEP_SECONDS,
]);
command
}
LinuxBackend::GnomeSessionInhibit => {
let mut command = Command::new("gnome-session-inhibit");
command.args([
"--inhibit",
"idle",
"--reason",
ASSERTION_REASON,
"sleep",
BLOCKER_SLEEP_SECONDS,
]);
command
}
};
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// SAFETY: `pre_exec` must be registered before spawn. The closure only
// performs libc setup for the child process and returns an `io::Error`
// when parent-death signal setup fails.
unsafe {
command.pre_exec(move || {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() != parent_pid {
libc::raise(libc::SIGTERM);
}
Ok(())
});
}
command.spawn()
}
fn child_exited(error: &std::io::Error) -> bool {
matches!(error.kind(), std::io::ErrorKind::InvalidInput)
}
#[cfg(test)]
mod tests {
use super::BLOCKER_SLEEP_SECONDS;
#[test]
fn sleep_seconds_is_i32_max() {
assert_eq!(BLOCKER_SLEEP_SECONDS, format!("{}", i32::MAX));
}
}

View file

@ -0,0 +1,107 @@
use core_foundation::base::TCFType;
use core_foundation::string::CFString;
use tracing::warn;
#[allow(
dead_code,
non_camel_case_types,
non_snake_case,
non_upper_case_globals,
clippy::all
)]
mod iokit {
#[link(name = "IOKit", kind = "framework")]
unsafe extern "C" {}
include!("iokit_bindings.rs");
}
type IOPMAssertionID = iokit::IOPMAssertionID;
type IOPMAssertionLevel = iokit::IOPMAssertionLevel;
type IOReturn = iokit::IOReturn;
const ASSERTION_REASON: &str = "Codex is running an active turn";
// Apple exposes this assertion type as a `CFSTR(...)` macro, so bindgen cannot generate a
// reusable `CFStringRef` constant for it.
const ASSERTION_TYPE_PREVENT_USER_IDLE_SYSTEM_SLEEP: &str = "PreventUserIdleSystemSleep";
#[derive(Debug, Default)]
pub(crate) struct SleepInhibitor {
assertion: Option<MacSleepAssertion>,
}
impl SleepInhibitor {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn acquire(&mut self) {
if self.assertion.is_some() {
return;
}
match MacSleepAssertion::create(ASSERTION_REASON) {
Ok(assertion) => {
self.assertion = Some(assertion);
}
Err(error) => {
warn!(
iokit_error = error,
"Failed to create macOS sleep-prevention assertion"
);
}
}
}
pub(crate) fn release(&mut self) {
self.assertion = None;
}
}
#[derive(Debug)]
struct MacSleepAssertion {
id: IOPMAssertionID,
}
impl MacSleepAssertion {
fn create(name: &str) -> Result<Self, IOReturn> {
let assertion_type = CFString::new(ASSERTION_TYPE_PREVENT_USER_IDLE_SYSTEM_SLEEP);
let assertion_name = CFString::new(name);
let mut id: IOPMAssertionID = 0;
// `core-foundation` and the generated bindings each declare an opaque `__CFString` type,
// so we cast to the bindgen pointer aliases before crossing the FFI boundary.
let assertion_type_ref: iokit::CFStringRef = assertion_type.as_concrete_TypeRef().cast();
let assertion_name_ref: iokit::CFStringRef = assertion_name.as_concrete_TypeRef().cast();
let result = unsafe {
// SAFETY: `assertion_type_ref` and `assertion_name_ref` are valid `CFStringRef`s and
// `&mut id` is a valid out-pointer for `IOPMAssertionCreateWithName` to initialize.
iokit::IOPMAssertionCreateWithName(
assertion_type_ref,
iokit::kIOPMAssertionLevelOn as IOPMAssertionLevel,
assertion_name_ref,
&mut id,
)
};
if result == iokit::kIOReturnSuccess as IOReturn {
Ok(Self { id })
} else {
Err(result)
}
}
}
impl Drop for MacSleepAssertion {
fn drop(&mut self) {
let result = unsafe {
// SAFETY: `self.id` was returned by `IOPMAssertionCreateWithName` and this `Drop`
// implementation releases it exactly once when the owning assertion is dropped.
iokit::IOPMAssertionRelease(self.id)
};
if result != iokit::kIOReturnSuccess as IOReturn {
warn!(
iokit_error = result,
"Failed to release macOS sleep-prevention assertion"
);
}
}
}

View file

@ -0,0 +1,119 @@
use std::ffi::OsStr;
use std::iter::once;
use std::os::windows::ffi::OsStrExt;
use tracing::warn;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::System::Power::POWER_REQUEST_TYPE;
use windows_sys::Win32::System::Power::PowerClearRequest;
use windows_sys::Win32::System::Power::PowerCreateRequest;
use windows_sys::Win32::System::Power::PowerRequestSystemRequired;
use windows_sys::Win32::System::Power::PowerSetRequest;
use windows_sys::Win32::System::SystemServices::POWER_REQUEST_CONTEXT_VERSION;
use windows_sys::Win32::System::Threading::POWER_REQUEST_CONTEXT_SIMPLE_STRING;
use windows_sys::Win32::System::Threading::REASON_CONTEXT;
use windows_sys::Win32::System::Threading::REASON_CONTEXT_0;
const ASSERTION_REASON: &str = "Codex is running an active turn";
#[derive(Debug, Default)]
pub(crate) struct WindowsSleepInhibitor {
request: Option<PowerRequest>,
}
pub(crate) use WindowsSleepInhibitor as SleepInhibitor;
impl WindowsSleepInhibitor {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn acquire(&mut self) {
if self.request.is_some() {
return;
}
match PowerRequest::new_system_required(ASSERTION_REASON) {
Ok(request) => {
self.request = Some(request);
}
Err(error) => {
warn!(
reason = %error,
"Failed to acquire Windows sleep-prevention request"
);
}
}
}
pub(crate) fn release(&mut self) {
self.request = None;
}
}
#[derive(Debug)]
struct PowerRequest {
handle: windows_sys::Win32::Foundation::HANDLE,
request_type: POWER_REQUEST_TYPE,
}
impl PowerRequest {
fn new_system_required(reason: &str) -> Result<Self, String> {
let mut wide_reason: Vec<u16> = OsStr::new(reason).encode_wide().chain(once(0)).collect();
let context = REASON_CONTEXT {
Version: POWER_REQUEST_CONTEXT_VERSION,
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
Reason: REASON_CONTEXT_0 {
SimpleReasonString: wide_reason.as_mut_ptr(),
},
};
// SAFETY: `context` points to a valid `REASON_CONTEXT` for the duration
// of the call and Windows copies the relevant data before returning.
let handle = unsafe { PowerCreateRequest(&context) };
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
let error = std::io::Error::last_os_error();
return Err(format!("PowerCreateRequest failed: {error}"));
}
// Match macOS `PreventUserIdleSystemSleep`: prevent idle system sleep
// without forcing the display to stay on.
let request_type = PowerRequestSystemRequired;
// SAFETY: `handle` is a live power request handle and `request_type` is a
// valid power request enum value.
if unsafe { PowerSetRequest(handle, request_type) } == 0 {
let error = std::io::Error::last_os_error();
// SAFETY: `handle` was returned by `PowerCreateRequest` and has not
// been closed yet on this error path.
let _ = unsafe { CloseHandle(handle) };
return Err(format!("PowerSetRequest failed: {error}"));
}
Ok(Self {
handle,
request_type,
})
}
}
impl Drop for PowerRequest {
fn drop(&mut self) {
// SAFETY: `self.handle` is the handle owned by this `PowerRequest`, and
// `self.request_type` is the request type that was set on acquire.
if unsafe { PowerClearRequest(self.handle, self.request_type) } == 0 {
let error = std::io::Error::last_os_error();
warn!(
reason = %error,
"Failed to clear Windows sleep-prevention request"
);
}
// SAFETY: `self.handle` is owned by this struct and closed exactly once
// in `Drop`.
if unsafe { CloseHandle(self.handle) } == 0 {
let error = std::io::Error::last_os_error();
warn!(
reason = %error,
"Failed to close Windows sleep-prevention request handle"
);
}
}
}

View file

@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "stream-parser",
crate_name = "codex_utils_stream_parser",
)

View file

@ -0,0 +1,11 @@
[package]
name = "codex-utils-stream-parser"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dev-dependencies]
pretty_assertions = { workspace = true }

View file

@ -0,0 +1,97 @@
# codex-utils-stream-parser
Small, dependency-free utilities for parsing streamed text incrementally.
**Disclaimer**: This code is pretty complex and Codex did not manage to write it so before updating the code, make
sure to deeply understand it and don't blindly trust Codex on it. Feel free to update the documentation as you
modify the code
## What it provides
- `StreamTextParser`: trait for incremental parsers that consume string chunks
- `InlineHiddenTagParser<T>`: generic parser that hides inline tags and extracts their contents
- `CitationStreamParser`: convenience wrapper for `<oai-mem-citation>...</oai-mem-citation>`
- `strip_citations(...)`: one-shot helper for non-streamed strings
- `Utf8StreamParser<P>`: adapter for raw `&[u8]` streams that may split UTF-8 code points
## Why this exists
Some model outputs arrive as a stream and may contain hidden markup (for example
`<oai-mem-citation>...</oai-mem-citation>`) split across chunk boundaries. Parsing each chunk
independently is incorrect because tags can be split (`<oai-mem-` + `citation>`).
This crate keeps parser state across chunks, returns visible text safe to render
immediately, and extracts hidden payloads separately.
## Example: citation streaming
```rust
use codex_utils_stream_parser::CitationStreamParser;
use codex_utils_stream_parser::StreamTextParser;
let mut parser = CitationStreamParser::new();
let first = parser.push_str("Hello <oai-mem-");
assert_eq!(first.visible_text, "Hello ");
assert!(first.extracted.is_empty());
let second = parser.push_str("citation>doc A</oai-mem-citation> world");
assert_eq!(second.visible_text, " world");
assert_eq!(second.extracted, vec!["doc A".to_string()]);
let tail = parser.finish();
assert!(tail.visible_text.is_empty());
assert!(tail.extracted.is_empty());
```
## Example: raw byte streaming with split UTF-8 code points
```rust
use codex_utils_stream_parser::CitationStreamParser;
use codex_utils_stream_parser::Utf8StreamParser;
# fn demo() -> Result<(), codex_utils_stream_parser::Utf8StreamParserError> {
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
// "é" split across chunks: 0xC3 + 0xA9
let first = parser.push_bytes(&[b'H', 0xC3])?;
assert_eq!(first.visible_text, "H");
let second = parser.push_bytes(&[0xA9, b'!'])?;
assert_eq!(second.visible_text, "é!");
let tail = parser.finish()?;
assert!(tail.visible_text.is_empty());
# Ok(())
# }
```
## Example: custom hidden tags
```rust
use codex_utils_stream_parser::InlineHiddenTagParser;
use codex_utils_stream_parser::InlineTagSpec;
use codex_utils_stream_parser::StreamTextParser;
#[derive(Clone, Debug, PartialEq, Eq)]
enum Tag {
Secret,
}
let mut parser = InlineHiddenTagParser::new(vec![InlineTagSpec {
tag: Tag::Secret,
open: "<secret>",
close: "</secret>",
}]);
let out = parser.push_str("a<secret>x</secret>b");
assert_eq!(out.visible_text, "ab");
assert_eq!(out.extracted.len(), 1);
assert_eq!(out.extracted[0].content, "x");
```
## Known limitations
- Tags are matched literally and case-sensitively
- No nested tag support
- A stream can return empty objects.

View file

@ -0,0 +1,130 @@
use crate::CitationStreamParser;
use crate::ProposedPlanParser;
use crate::ProposedPlanSegment;
use crate::StreamTextChunk;
use crate::StreamTextParser;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AssistantTextChunk {
pub visible_text: String,
pub citations: Vec<String>,
pub plan_segments: Vec<ProposedPlanSegment>,
}
impl AssistantTextChunk {
pub fn is_empty(&self) -> bool {
self.visible_text.is_empty() && self.citations.is_empty() && self.plan_segments.is_empty()
}
}
/// Parses assistant text streaming markup in one pass:
/// - strips `<oai-mem-citation>` tags and extracts citation payloads
/// - in plan mode, also strips `<proposed_plan>` blocks and emits plan segments
#[derive(Debug, Default)]
pub struct AssistantTextStreamParser {
plan_mode: bool,
citations: CitationStreamParser,
plan: ProposedPlanParser,
}
impl AssistantTextStreamParser {
pub fn new(plan_mode: bool) -> Self {
Self {
plan_mode,
..Self::default()
}
}
pub fn push_str(&mut self, chunk: &str) -> AssistantTextChunk {
let citation_chunk = self.citations.push_str(chunk);
let mut out = self.parse_visible_text(citation_chunk.visible_text);
out.citations = citation_chunk.extracted;
out
}
pub fn finish(&mut self) -> AssistantTextChunk {
let citation_chunk = self.citations.finish();
let mut out = self.parse_visible_text(citation_chunk.visible_text);
if self.plan_mode {
let mut tail = self.plan.finish();
if !tail.is_empty() {
out.visible_text.push_str(&tail.visible_text);
out.plan_segments.append(&mut tail.extracted);
}
}
out.citations = citation_chunk.extracted;
out
}
fn parse_visible_text(&mut self, visible_text: String) -> AssistantTextChunk {
if !self.plan_mode {
return AssistantTextChunk {
visible_text,
..AssistantTextChunk::default()
};
}
let plan_chunk: StreamTextChunk<ProposedPlanSegment> = self.plan.push_str(&visible_text);
AssistantTextChunk {
visible_text: plan_chunk.visible_text,
plan_segments: plan_chunk.extracted,
..AssistantTextChunk::default()
}
}
}
#[cfg(test)]
mod tests {
use super::AssistantTextStreamParser;
use crate::ProposedPlanSegment;
use pretty_assertions::assert_eq;
#[test]
fn parses_citations_across_seed_and_delta_boundaries() {
let mut parser = AssistantTextStreamParser::new(/*plan_mode*/ false);
let seeded = parser.push_str("hello <oai-mem-citation>doc");
let parsed = parser.push_str("1</oai-mem-citation> world");
let tail = parser.finish();
assert_eq!(seeded.visible_text, "hello ");
assert_eq!(seeded.citations, Vec::<String>::new());
assert_eq!(parsed.visible_text, " world");
assert_eq!(parsed.citations, vec!["doc1".to_string()]);
assert_eq!(tail.visible_text, "");
assert_eq!(tail.citations, Vec::<String>::new());
}
#[test]
fn parses_plan_segments_after_citation_stripping() {
let mut parser = AssistantTextStreamParser::new(/*plan_mode*/ true);
let seeded = parser.push_str("Intro\n<proposed");
let parsed = parser.push_str("_plan>\n- step <oai-mem-citation>doc</oai-mem-citation>\n");
let tail = parser.push_str("</proposed_plan>\nOutro");
let finish = parser.finish();
assert_eq!(seeded.visible_text, "Intro\n");
assert_eq!(
seeded.plan_segments,
vec![ProposedPlanSegment::Normal("Intro\n".to_string())]
);
assert_eq!(parsed.visible_text, "");
assert_eq!(parsed.citations, vec!["doc".to_string()]);
assert_eq!(
parsed.plan_segments,
vec![
ProposedPlanSegment::ProposedPlanStart,
ProposedPlanSegment::ProposedPlanDelta("- step \n".to_string()),
]
);
assert_eq!(tail.visible_text, "Outro");
assert_eq!(
tail.plan_segments,
vec![
ProposedPlanSegment::ProposedPlanEnd,
ProposedPlanSegment::Normal("Outro".to_string()),
]
);
assert!(finish.is_empty());
}
}

View file

@ -0,0 +1,179 @@
use crate::InlineHiddenTagParser;
use crate::InlineTagSpec;
use crate::StreamTextChunk;
use crate::StreamTextParser;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CitationTag {
Citation,
}
const CITATION_OPEN: &str = "<oai-mem-citation>";
const CITATION_CLOSE: &str = "</oai-mem-citation>";
/// Stream parser for `<oai-mem-citation>...</oai-mem-citation>` tags.
///
/// This is a thin convenience wrapper around [`InlineHiddenTagParser`]. It returns citation bodies
/// as plain strings and omits the citation tags from visible text.
///
/// Matching is literal and non-nested. If EOF is reached before a closing
/// `</oai-mem-citation>`, the parser auto-closes the tag and returns the buffered body as an
/// extracted citation.
#[derive(Debug)]
pub struct CitationStreamParser {
inner: InlineHiddenTagParser<CitationTag>,
}
impl CitationStreamParser {
pub fn new() -> Self {
Self {
inner: InlineHiddenTagParser::new(vec![InlineTagSpec {
tag: CitationTag::Citation,
open: CITATION_OPEN,
close: CITATION_CLOSE,
}]),
}
}
}
impl Default for CitationStreamParser {
fn default() -> Self {
Self::new()
}
}
impl StreamTextParser for CitationStreamParser {
type Extracted = String;
fn push_str(&mut self, chunk: &str) -> StreamTextChunk<Self::Extracted> {
let inner = self.inner.push_str(chunk);
StreamTextChunk {
visible_text: inner.visible_text,
extracted: inner.extracted.into_iter().map(|tag| tag.content).collect(),
}
}
fn finish(&mut self) -> StreamTextChunk<Self::Extracted> {
let inner = self.inner.finish();
StreamTextChunk {
visible_text: inner.visible_text,
extracted: inner.extracted.into_iter().map(|tag| tag.content).collect(),
}
}
}
/// Strip citation tags from a complete string and return `(visible_text, citations)`.
///
/// This uses [`CitationStreamParser`] internally, so it inherits the same semantics:
/// literal, non-nested matching and auto-closing unterminated citations at EOF.
pub fn strip_citations(text: &str) -> (String, Vec<String>) {
let mut parser = CitationStreamParser::new();
let mut out = parser.push_str(text);
let tail = parser.finish();
out.visible_text.push_str(&tail.visible_text);
out.extracted.extend(tail.extracted);
(out.visible_text, out.extracted)
}
#[cfg(test)]
mod tests {
use super::CitationStreamParser;
use super::strip_citations;
use crate::StreamTextChunk;
use crate::StreamTextParser;
use pretty_assertions::assert_eq;
fn collect_chunks<P>(parser: &mut P, chunks: &[&str]) -> StreamTextChunk<P::Extracted>
where
P: StreamTextParser,
{
let mut all = StreamTextChunk::default();
for chunk in chunks {
let next = parser.push_str(chunk);
all.visible_text.push_str(&next.visible_text);
all.extracted.extend(next.extracted);
}
let tail = parser.finish();
all.visible_text.push_str(&tail.visible_text);
all.extracted.extend(tail.extracted);
all
}
#[test]
fn citation_parser_streams_across_chunk_boundaries() {
let mut parser = CitationStreamParser::new();
let out = collect_chunks(
&mut parser,
&[
"Hello <oai-mem-",
"citation>source A</oai-mem-",
"citation> world",
],
);
assert_eq!(out.visible_text, "Hello world");
assert_eq!(out.extracted, vec!["source A".to_string()]);
}
#[test]
fn citation_parser_buffers_partial_open_tag_prefix() {
let mut parser = CitationStreamParser::new();
let first = parser.push_str("abc <oai-mem-");
assert_eq!(first.visible_text, "abc ");
assert_eq!(first.extracted, Vec::<String>::new());
let second = parser.push_str("citation>x</oai-mem-citation>z");
let tail = parser.finish();
assert_eq!(second.visible_text, "z");
assert_eq!(second.extracted, vec!["x".to_string()]);
assert!(tail.is_empty());
}
#[test]
fn citation_parser_auto_closes_unterminated_tag_on_finish() {
let mut parser = CitationStreamParser::new();
let out = collect_chunks(&mut parser, &["x<oai-mem-citation>source"]);
assert_eq!(out.visible_text, "x");
assert_eq!(out.extracted, vec!["source".to_string()]);
}
#[test]
fn citation_parser_preserves_partial_open_tag_at_eof_if_not_a_full_tag() {
let mut parser = CitationStreamParser::new();
let out = collect_chunks(&mut parser, &["hello <oai-mem-"]);
assert_eq!(out.visible_text, "hello <oai-mem-");
assert_eq!(out.extracted, Vec::<String>::new());
}
#[test]
fn strip_citations_collects_all_citations() {
let (visible, citations) = strip_citations(
"a<oai-mem-citation>one</oai-mem-citation>b<oai-mem-citation>two</oai-mem-citation>c",
);
assert_eq!(visible, "abc");
assert_eq!(citations, vec!["one".to_string(), "two".to_string()]);
}
#[test]
fn strip_citations_auto_closes_unterminated_citation_at_eof() {
let (visible, citations) = strip_citations("x<oai-mem-citation>y");
assert_eq!(visible, "x");
assert_eq!(citations, vec!["y".to_string()]);
}
#[test]
fn citation_parser_does_not_support_nested_tags() {
let (visible, citations) = strip_citations(
"a<oai-mem-citation>x<oai-mem-citation>y</oai-mem-citation>z</oai-mem-citation>b",
);
assert_eq!(visible, "az</oai-mem-citation>b");
assert_eq!(citations, vec!["x<oai-mem-citation>y".to_string()]);
}
}

View file

@ -0,0 +1,323 @@
use crate::StreamTextChunk;
use crate::StreamTextParser;
/// One hidden inline tag extracted by [`InlineHiddenTagParser`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedInlineTag<T> {
pub tag: T,
pub content: String,
}
/// Literal tag specification used by [`InlineHiddenTagParser`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InlineTagSpec<T> {
pub tag: T,
pub open: &'static str,
pub close: &'static str,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ActiveTag<T> {
tag: T,
close: &'static str,
content: String,
}
/// Generic streaming parser that hides configured inline tags and extracts their contents.
///
/// Example:
/// - input: `hello <oai-mem-citation>doc A</oai-mem-citation> world`
/// - visible output: `hello world`
/// - extracted: `["doc A"]`
///
/// Matching is literal and non-nested. If EOF is reached while a tag is still open, the parser
/// auto-closes it and returns the buffered content as extracted data.
#[derive(Debug)]
pub struct InlineHiddenTagParser<T>
where
T: Clone + Eq,
{
specs: Vec<InlineTagSpec<T>>,
pending: String,
active: Option<ActiveTag<T>>,
}
impl<T> InlineHiddenTagParser<T>
where
T: Clone + Eq,
{
/// Create a parser for one or more hidden inline tags.
pub fn new(specs: Vec<InlineTagSpec<T>>) -> Self {
assert!(
!specs.is_empty(),
"InlineHiddenTagParser requires at least one tag spec"
);
for spec in &specs {
assert!(
!spec.open.is_empty(),
"InlineHiddenTagParser requires non-empty open delimiters"
);
assert!(
!spec.close.is_empty(),
"InlineHiddenTagParser requires non-empty close delimiters"
);
}
Self {
specs,
pending: String::new(),
active: None,
}
}
fn find_next_open(&self) -> Option<(usize, usize)> {
self.specs
.iter()
.enumerate()
.filter_map(|(idx, spec)| {
self.pending
.find(spec.open)
.map(|pos| (pos, spec.open.len(), idx))
})
.min_by(|(pos_a, len_a, idx_a), (pos_b, len_b, idx_b)| {
pos_a
.cmp(pos_b)
.then_with(|| len_b.cmp(len_a))
.then_with(|| idx_a.cmp(idx_b))
})
.map(|(pos, _len, idx)| (pos, idx))
}
fn max_open_prefix_suffix_len(&self) -> usize {
self.specs
.iter()
.map(|spec| longest_suffix_prefix_len(&self.pending, spec.open))
.max()
.map_or(0, std::convert::identity)
}
fn push_visible_prefix(out: &mut StreamTextChunk<ExtractedInlineTag<T>>, pending: &str) {
if !pending.is_empty() {
out.visible_text.push_str(pending);
}
}
fn drain_visible_to_suffix_match(
&mut self,
out: &mut StreamTextChunk<ExtractedInlineTag<T>>,
keep_suffix_len: usize,
) {
let take = self.pending.len().saturating_sub(keep_suffix_len);
if take == 0 {
return;
}
Self::push_visible_prefix(out, &self.pending[..take]);
self.pending.drain(..take);
}
}
impl<T> StreamTextParser for InlineHiddenTagParser<T>
where
T: Clone + Eq,
{
type Extracted = ExtractedInlineTag<T>;
fn push_str(&mut self, chunk: &str) -> StreamTextChunk<Self::Extracted> {
self.pending.push_str(chunk);
let mut out = StreamTextChunk::default();
loop {
if let Some(close) = self.active.as_ref().map(|active| active.close) {
if let Some(close_idx) = self.pending.find(close) {
let Some(mut active) = self.active.take() else {
continue;
};
active.content.push_str(&self.pending[..close_idx]);
out.extracted.push(ExtractedInlineTag {
tag: active.tag,
content: active.content,
});
let close_len = close.len();
self.pending.drain(..close_idx + close_len);
continue;
}
let keep = longest_suffix_prefix_len(&self.pending, close);
let take = self.pending.len().saturating_sub(keep);
if take > 0 {
if let Some(active) = self.active.as_mut() {
active.content.push_str(&self.pending[..take]);
}
self.pending.drain(..take);
}
break;
}
if let Some((open_idx, spec_idx)) = self.find_next_open() {
Self::push_visible_prefix(&mut out, &self.pending[..open_idx]);
let spec = &self.specs[spec_idx];
let open_len = spec.open.len();
self.pending.drain(..open_idx + open_len);
self.active = Some(ActiveTag {
tag: spec.tag.clone(),
close: spec.close,
content: String::new(),
});
continue;
}
let keep = self.max_open_prefix_suffix_len();
self.drain_visible_to_suffix_match(&mut out, keep);
break;
}
out
}
fn finish(&mut self) -> StreamTextChunk<Self::Extracted> {
let mut out = StreamTextChunk::default();
if let Some(mut active) = self.active.take() {
if !self.pending.is_empty() {
active.content.push_str(&self.pending);
self.pending.clear();
}
out.extracted.push(ExtractedInlineTag {
tag: active.tag,
content: active.content,
});
return out;
}
if !self.pending.is_empty() {
out.visible_text.push_str(&self.pending);
self.pending.clear();
}
out
}
}
fn longest_suffix_prefix_len(s: &str, needle: &str) -> usize {
let max = s.len().min(needle.len().saturating_sub(1));
for k in (1..=max).rev() {
if needle.is_char_boundary(k) && s.ends_with(&needle[..k]) {
return k;
}
}
0
}
#[cfg(test)]
mod tests {
use super::InlineHiddenTagParser;
use super::InlineTagSpec;
use crate::StreamTextChunk;
use crate::StreamTextParser;
use pretty_assertions::assert_eq;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tag {
A,
B,
}
fn collect_chunks<P>(parser: &mut P, chunks: &[&str]) -> StreamTextChunk<P::Extracted>
where
P: StreamTextParser,
{
let mut all = StreamTextChunk::default();
for chunk in chunks {
let next = parser.push_str(chunk);
all.visible_text.push_str(&next.visible_text);
all.extracted.extend(next.extracted);
}
let tail = parser.finish();
all.visible_text.push_str(&tail.visible_text);
all.extracted.extend(tail.extracted);
all
}
#[test]
fn generic_inline_parser_supports_multiple_tag_types() {
let mut parser = InlineHiddenTagParser::new(vec![
InlineTagSpec {
tag: Tag::A,
open: "<a>",
close: "</a>",
},
InlineTagSpec {
tag: Tag::B,
open: "<b>",
close: "</b>",
},
]);
let out = collect_chunks(&mut parser, &["1<a>x</a>2<b>y</b>3"]);
assert_eq!(out.visible_text, "123");
assert_eq!(out.extracted.len(), 2);
assert_eq!(out.extracted[0].tag, Tag::A);
assert_eq!(out.extracted[0].content, "x");
assert_eq!(out.extracted[1].tag, Tag::B);
assert_eq!(out.extracted[1].content, "y");
}
#[test]
fn generic_inline_parser_supports_non_ascii_tag_delimiters() {
let mut parser = InlineHiddenTagParser::new(vec![InlineTagSpec {
tag: Tag::A,
open: "<é>",
close: "</é>",
}]);
let out = collect_chunks(&mut parser, &["a<", "é>中</", "é>b"]);
assert_eq!(out.visible_text, "ab");
assert_eq!(out.extracted.len(), 1);
assert_eq!(out.extracted[0].tag, Tag::A);
assert_eq!(out.extracted[0].content, "中");
}
#[test]
fn generic_inline_parser_prefers_longest_opener_at_same_offset() {
let mut parser = InlineHiddenTagParser::new(vec![
InlineTagSpec {
tag: Tag::A,
open: "<a>",
close: "</a>",
},
InlineTagSpec {
tag: Tag::B,
open: "<ab>",
close: "</ab>",
},
]);
let out = collect_chunks(&mut parser, &["x<ab>y</ab>z"]);
assert_eq!(out.visible_text, "xz");
assert_eq!(out.extracted.len(), 1);
assert_eq!(out.extracted[0].tag, Tag::B);
assert_eq!(out.extracted[0].content, "y");
}
#[test]
#[should_panic(expected = "non-empty open delimiters")]
fn generic_inline_parser_rejects_empty_open_delimiter() {
let _ = InlineHiddenTagParser::new(vec![InlineTagSpec {
tag: Tag::A,
open: "",
close: "</a>",
}]);
}
#[test]
#[should_panic(expected = "non-empty close delimiters")]
fn generic_inline_parser_rejects_empty_close_delimiter() {
let _ = InlineHiddenTagParser::new(vec![InlineTagSpec {
tag: Tag::A,
open: "<a>",
close: "",
}]);
}
}

View file

@ -0,0 +1,23 @@
mod assistant_text;
mod citation;
mod inline_hidden_tag;
mod proposed_plan;
mod stream_text;
mod tagged_line_parser;
mod utf8_stream;
pub use assistant_text::AssistantTextChunk;
pub use assistant_text::AssistantTextStreamParser;
pub use citation::CitationStreamParser;
pub use citation::strip_citations;
pub use inline_hidden_tag::ExtractedInlineTag;
pub use inline_hidden_tag::InlineHiddenTagParser;
pub use inline_hidden_tag::InlineTagSpec;
pub use proposed_plan::ProposedPlanParser;
pub use proposed_plan::ProposedPlanSegment;
pub use proposed_plan::extract_proposed_plan_text;
pub use proposed_plan::strip_proposed_plan_blocks;
pub use stream_text::StreamTextChunk;
pub use stream_text::StreamTextParser;
pub use utf8_stream::Utf8StreamParser;
pub use utf8_stream::Utf8StreamParserError;

View file

@ -0,0 +1,212 @@
use crate::StreamTextChunk;
use crate::StreamTextParser;
use crate::tagged_line_parser::TagSpec;
use crate::tagged_line_parser::TaggedLineParser;
use crate::tagged_line_parser::TaggedLineSegment;
const OPEN_TAG: &str = "<proposed_plan>";
const CLOSE_TAG: &str = "</proposed_plan>";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PlanTag {
ProposedPlan,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProposedPlanSegment {
Normal(String),
ProposedPlanStart,
ProposedPlanDelta(String),
ProposedPlanEnd,
}
/// Parser for `<proposed_plan>` blocks emitted in plan mode.
///
/// Implements [`StreamTextParser`] so callers can consume:
/// - `visible_text`: normal assistant text with plan blocks removed
/// - `extracted`: ordered plan segments (includes `Normal(...)` segments for ordering fidelity)
#[derive(Debug)]
pub struct ProposedPlanParser {
parser: TaggedLineParser<PlanTag>,
}
impl ProposedPlanParser {
pub fn new() -> Self {
Self {
parser: TaggedLineParser::new(vec![TagSpec {
open: OPEN_TAG,
close: CLOSE_TAG,
tag: PlanTag::ProposedPlan,
}]),
}
}
}
impl Default for ProposedPlanParser {
fn default() -> Self {
Self::new()
}
}
impl StreamTextParser for ProposedPlanParser {
type Extracted = ProposedPlanSegment;
fn push_str(&mut self, chunk: &str) -> StreamTextChunk<Self::Extracted> {
map_segments(self.parser.parse(chunk))
}
fn finish(&mut self) -> StreamTextChunk<Self::Extracted> {
map_segments(self.parser.finish())
}
}
fn map_segments(segments: Vec<TaggedLineSegment<PlanTag>>) -> StreamTextChunk<ProposedPlanSegment> {
let mut out = StreamTextChunk::default();
for segment in segments {
let mapped = match segment {
TaggedLineSegment::Normal(text) => ProposedPlanSegment::Normal(text),
TaggedLineSegment::TagStart(PlanTag::ProposedPlan) => {
ProposedPlanSegment::ProposedPlanStart
}
TaggedLineSegment::TagDelta(PlanTag::ProposedPlan, text) => {
ProposedPlanSegment::ProposedPlanDelta(text)
}
TaggedLineSegment::TagEnd(PlanTag::ProposedPlan) => {
ProposedPlanSegment::ProposedPlanEnd
}
};
if let ProposedPlanSegment::Normal(text) = &mapped {
out.visible_text.push_str(text);
}
out.extracted.push(mapped);
}
out
}
pub fn strip_proposed_plan_blocks(text: &str) -> String {
let mut parser = ProposedPlanParser::new();
let mut out = parser.push_str(text).visible_text;
out.push_str(&parser.finish().visible_text);
out
}
pub fn extract_proposed_plan_text(text: &str) -> Option<String> {
let mut parser = ProposedPlanParser::new();
let mut plan_text = String::new();
let mut saw_plan_block = false;
for segment in parser
.push_str(text)
.extracted
.into_iter()
.chain(parser.finish().extracted)
{
match segment {
ProposedPlanSegment::ProposedPlanStart => {
saw_plan_block = true;
plan_text.clear();
}
ProposedPlanSegment::ProposedPlanDelta(delta) => {
plan_text.push_str(&delta);
}
ProposedPlanSegment::ProposedPlanEnd | ProposedPlanSegment::Normal(_) => {}
}
}
saw_plan_block.then_some(plan_text)
}
#[cfg(test)]
mod tests {
use super::ProposedPlanParser;
use super::ProposedPlanSegment;
use super::extract_proposed_plan_text;
use super::strip_proposed_plan_blocks;
use crate::StreamTextChunk;
use crate::StreamTextParser;
use pretty_assertions::assert_eq;
fn collect_chunks<P>(parser: &mut P, chunks: &[&str]) -> StreamTextChunk<P::Extracted>
where
P: StreamTextParser,
{
let mut all = StreamTextChunk::default();
for chunk in chunks {
let next = parser.push_str(chunk);
all.visible_text.push_str(&next.visible_text);
all.extracted.extend(next.extracted);
}
let tail = parser.finish();
all.visible_text.push_str(&tail.visible_text);
all.extracted.extend(tail.extracted);
all
}
#[test]
fn streams_proposed_plan_segments_and_visible_text() {
let mut parser = ProposedPlanParser::new();
let out = collect_chunks(
&mut parser,
&[
"Intro text\n<prop",
"osed_plan>\n- step 1\n",
"</proposed_plan>\nOutro",
],
);
assert_eq!(out.visible_text, "Intro text\nOutro");
assert_eq!(
out.extracted,
vec![
ProposedPlanSegment::Normal("Intro text\n".to_string()),
ProposedPlanSegment::ProposedPlanStart,
ProposedPlanSegment::ProposedPlanDelta("- step 1\n".to_string()),
ProposedPlanSegment::ProposedPlanEnd,
ProposedPlanSegment::Normal("Outro".to_string()),
]
);
}
#[test]
fn preserves_non_tag_lines() {
let mut parser = ProposedPlanParser::new();
let out = collect_chunks(&mut parser, &[" <proposed_plan> extra\n"]);
assert_eq!(out.visible_text, " <proposed_plan> extra\n");
assert_eq!(
out.extracted,
vec![ProposedPlanSegment::Normal(
" <proposed_plan> extra\n".to_string()
)]
);
}
#[test]
fn closes_unterminated_plan_block_on_finish() {
let mut parser = ProposedPlanParser::new();
let out = collect_chunks(&mut parser, &["<proposed_plan>\n- step 1\n"]);
assert_eq!(out.visible_text, "");
assert_eq!(
out.extracted,
vec![
ProposedPlanSegment::ProposedPlanStart,
ProposedPlanSegment::ProposedPlanDelta("- step 1\n".to_string()),
ProposedPlanSegment::ProposedPlanEnd,
]
);
}
#[test]
fn strips_proposed_plan_blocks_from_text() {
let text = "before\n<proposed_plan>\n- step\n</proposed_plan>\nafter";
assert_eq!(strip_proposed_plan_blocks(text), "before\nafter");
}
#[test]
fn extracts_proposed_plan_text() {
let text = "before\n<proposed_plan>\n- step\n</proposed_plan>\nafter";
assert_eq!(
extract_proposed_plan_text(text),
Some("- step\n".to_string())
);
}
}

View file

@ -0,0 +1,36 @@
/// Incremental parser result for one pushed chunk (or final flush).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamTextChunk<T> {
/// Text safe to render immediately.
pub visible_text: String,
/// Hidden payloads extracted from the chunk.
pub extracted: Vec<T>,
}
impl<T> Default for StreamTextChunk<T> {
fn default() -> Self {
Self {
visible_text: String::new(),
extracted: Vec::new(),
}
}
}
impl<T> StreamTextChunk<T> {
/// Returns true when no visible text or extracted payloads were produced.
pub fn is_empty(&self) -> bool {
self.visible_text.is_empty() && self.extracted.is_empty()
}
}
/// Trait for parsers that consume streamed text and emit visible text plus extracted payloads.
pub trait StreamTextParser {
/// Payload extracted by this parser (for example a citation body).
type Extracted;
/// Feed a new text chunk.
fn push_str(&mut self, chunk: &str) -> StreamTextChunk<Self::Extracted>;
/// Flush any buffered state at end-of-stream (or end-of-item).
fn finish(&mut self) -> StreamTextChunk<Self::Extracted>;
}

View file

@ -0,0 +1,249 @@
//! Line-based tag block parsing for streamed text.
//!
//! The parser buffers each line until it can disprove that the line is a tag,
//! which is required for tags that must appear alone on a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct TagSpec<T> {
pub(crate) open: &'static str,
pub(crate) close: &'static str,
pub(crate) tag: T,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TaggedLineSegment<T> {
Normal(String),
TagStart(T),
TagDelta(T, String),
TagEnd(T),
}
/// Stateful line parser that splits input into normal text vs tag blocks.
#[derive(Debug, Default)]
pub(crate) struct TaggedLineParser<T>
where
T: Copy + Eq,
{
specs: Vec<TagSpec<T>>,
active_tag: Option<T>,
detect_tag: bool,
line_buffer: String,
}
impl<T> TaggedLineParser<T>
where
T: Copy + Eq,
{
pub(crate) fn new(specs: Vec<TagSpec<T>>) -> Self {
Self {
specs,
active_tag: None,
detect_tag: true,
line_buffer: String::new(),
}
}
pub(crate) fn parse(&mut self, delta: &str) -> Vec<TaggedLineSegment<T>> {
let mut segments = Vec::new();
let mut run = String::new();
for ch in delta.chars() {
if self.detect_tag {
if !run.is_empty() {
self.push_text(std::mem::take(&mut run), &mut segments);
}
self.line_buffer.push(ch);
if ch == '\n' {
self.finish_line(&mut segments);
continue;
}
let slug = self.line_buffer.trim_start();
if slug.is_empty() || self.is_tag_prefix(slug) {
continue;
}
let buffered = std::mem::take(&mut self.line_buffer);
self.detect_tag = false;
self.push_text(buffered, &mut segments);
continue;
}
run.push(ch);
if ch == '\n' {
self.push_text(std::mem::take(&mut run), &mut segments);
self.detect_tag = true;
}
}
if !run.is_empty() {
self.push_text(run, &mut segments);
}
segments
}
pub(crate) fn finish(&mut self) -> Vec<TaggedLineSegment<T>> {
let mut segments = Vec::new();
if !self.line_buffer.is_empty() {
let buffered = std::mem::take(&mut self.line_buffer);
let without_newline = buffered.strip_suffix('\n').unwrap_or(&buffered);
let slug = without_newline.trim_start().trim_end();
if let Some(tag) = self.match_open(slug)
&& self.active_tag.is_none()
{
push_segment(&mut segments, TaggedLineSegment::TagStart(tag));
self.active_tag = Some(tag);
} else if let Some(tag) = self.match_close(slug)
&& self.active_tag == Some(tag)
{
push_segment(&mut segments, TaggedLineSegment::TagEnd(tag));
self.active_tag = None;
} else {
self.push_text(buffered, &mut segments);
}
}
if let Some(tag) = self.active_tag.take() {
push_segment(&mut segments, TaggedLineSegment::TagEnd(tag));
}
self.detect_tag = true;
segments
}
fn finish_line(&mut self, segments: &mut Vec<TaggedLineSegment<T>>) {
let line = std::mem::take(&mut self.line_buffer);
let without_newline = line.strip_suffix('\n').unwrap_or(&line);
let slug = without_newline.trim_start().trim_end();
if let Some(tag) = self.match_open(slug)
&& self.active_tag.is_none()
{
push_segment(segments, TaggedLineSegment::TagStart(tag));
self.active_tag = Some(tag);
self.detect_tag = true;
return;
}
if let Some(tag) = self.match_close(slug)
&& self.active_tag == Some(tag)
{
push_segment(segments, TaggedLineSegment::TagEnd(tag));
self.active_tag = None;
self.detect_tag = true;
return;
}
self.detect_tag = true;
self.push_text(line, segments);
}
fn push_text(&self, text: String, segments: &mut Vec<TaggedLineSegment<T>>) {
if let Some(tag) = self.active_tag {
push_segment(segments, TaggedLineSegment::TagDelta(tag, text));
} else {
push_segment(segments, TaggedLineSegment::Normal(text));
}
}
fn is_tag_prefix(&self, slug: &str) -> bool {
let slug = slug.trim_end();
self.specs
.iter()
.any(|spec| spec.open.starts_with(slug) || spec.close.starts_with(slug))
}
fn match_open(&self, slug: &str) -> Option<T> {
self.specs
.iter()
.find(|spec| spec.open == slug)
.map(|spec| spec.tag)
}
fn match_close(&self, slug: &str) -> Option<T> {
self.specs
.iter()
.find(|spec| spec.close == slug)
.map(|spec| spec.tag)
}
}
fn push_segment<T>(segments: &mut Vec<TaggedLineSegment<T>>, segment: TaggedLineSegment<T>)
where
T: Copy + Eq,
{
match segment {
TaggedLineSegment::Normal(delta) => {
if delta.is_empty() {
return;
}
if let Some(TaggedLineSegment::Normal(existing)) = segments.last_mut() {
existing.push_str(&delta);
return;
}
segments.push(TaggedLineSegment::Normal(delta));
}
TaggedLineSegment::TagDelta(tag, delta) => {
if delta.is_empty() {
return;
}
if let Some(TaggedLineSegment::TagDelta(existing_tag, existing)) = segments.last_mut()
&& *existing_tag == tag
{
existing.push_str(&delta);
return;
}
segments.push(TaggedLineSegment::TagDelta(tag, delta));
}
TaggedLineSegment::TagStart(tag) => segments.push(TaggedLineSegment::TagStart(tag)),
TaggedLineSegment::TagEnd(tag) => segments.push(TaggedLineSegment::TagEnd(tag)),
}
}
#[cfg(test)]
mod tests {
use super::TagSpec;
use super::TaggedLineParser;
use super::TaggedLineSegment;
use pretty_assertions::assert_eq;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tag {
Block,
}
fn parser() -> TaggedLineParser<Tag> {
TaggedLineParser::new(vec![TagSpec {
open: "<tag>",
close: "</tag>",
tag: Tag::Block,
}])
}
#[test]
fn buffers_prefix_until_tag_is_decided() {
let mut parser = parser();
let mut segments = parser.parse("<t");
segments.extend(parser.parse("ag>\nline\n</tag>\n"));
segments.extend(parser.finish());
assert_eq!(
segments,
vec![
TaggedLineSegment::TagStart(Tag::Block),
TaggedLineSegment::TagDelta(Tag::Block, "line\n".to_string()),
TaggedLineSegment::TagEnd(Tag::Block),
]
);
}
#[test]
fn rejects_tag_lines_with_extra_text() {
let mut parser = parser();
let mut segments = parser.parse("<tag> extra\n");
segments.extend(parser.finish());
assert_eq!(
segments,
vec![TaggedLineSegment::Normal("<tag> extra\n".to_string())]
);
}
}

View file

@ -0,0 +1,333 @@
use std::error::Error;
use std::fmt;
use crate::StreamTextChunk;
use crate::StreamTextParser;
/// Error returned by [`Utf8StreamParser`] when streamed bytes are not valid UTF-8.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Utf8StreamParserError {
/// The provided bytes contain an invalid UTF-8 sequence.
InvalidUtf8 {
/// Byte offset in the parser's buffered bytes where decoding failed.
valid_up_to: usize,
/// Length in bytes of the invalid sequence.
error_len: usize,
},
/// EOF was reached with a buffered partial UTF-8 code point.
IncompleteUtf8AtEof,
}
impl fmt::Display for Utf8StreamParserError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidUtf8 {
valid_up_to,
error_len,
} => write!(
f,
"invalid UTF-8 in streamed bytes at offset {valid_up_to} (error length {error_len})"
),
Self::IncompleteUtf8AtEof => {
write!(f, "incomplete UTF-8 code point at end of stream")
}
}
}
}
impl Error for Utf8StreamParserError {}
/// Wraps a [`StreamTextParser`] and accepts raw bytes, buffering partial UTF-8 code points.
///
/// This is useful when upstream data arrives as `&[u8]` and a code point may be split across
/// chunk boundaries (for example `0xC3` followed by `0xA9` for `é`).
#[derive(Debug)]
pub struct Utf8StreamParser<P> {
inner: P,
pending_utf8: Vec<u8>,
}
impl<P> Utf8StreamParser<P>
where
P: StreamTextParser,
{
pub fn new(inner: P) -> Self {
Self {
inner,
pending_utf8: Vec::new(),
}
}
/// Feed a raw byte chunk.
///
/// If the chunk contains invalid UTF-8, this returns an error and rolls back the entire
/// pushed chunk so callers can decide how to recover without the inner parser seeing a partial
/// prefix from that chunk.
pub fn push_bytes(
&mut self,
chunk: &[u8],
) -> Result<StreamTextChunk<P::Extracted>, Utf8StreamParserError> {
let old_len = self.pending_utf8.len();
self.pending_utf8.extend_from_slice(chunk);
match std::str::from_utf8(&self.pending_utf8) {
Ok(text) => {
let out = self.inner.push_str(text);
self.pending_utf8.clear();
Ok(out)
}
Err(err) => {
if let Some(error_len) = err.error_len() {
self.pending_utf8.truncate(old_len);
return Err(Utf8StreamParserError::InvalidUtf8 {
valid_up_to: err.valid_up_to(),
error_len,
});
}
let valid_up_to = err.valid_up_to();
if valid_up_to == 0 {
return Ok(StreamTextChunk::default());
}
let text = match std::str::from_utf8(&self.pending_utf8[..valid_up_to]) {
Ok(text) => text,
Err(prefix_err) => {
self.pending_utf8.truncate(old_len);
let error_len = prefix_err.error_len().unwrap_or(0);
return Err(Utf8StreamParserError::InvalidUtf8 {
valid_up_to: prefix_err.valid_up_to(),
error_len,
});
}
};
let out = self.inner.push_str(text);
self.pending_utf8.drain(..valid_up_to);
Ok(out)
}
}
}
pub fn finish(&mut self) -> Result<StreamTextChunk<P::Extracted>, Utf8StreamParserError> {
if !self.pending_utf8.is_empty() {
match std::str::from_utf8(&self.pending_utf8) {
Ok(_) => {}
Err(err) => {
if let Some(error_len) = err.error_len() {
return Err(Utf8StreamParserError::InvalidUtf8 {
valid_up_to: err.valid_up_to(),
error_len,
});
}
return Err(Utf8StreamParserError::IncompleteUtf8AtEof);
}
}
}
let mut out = if self.pending_utf8.is_empty() {
StreamTextChunk::default()
} else {
let text = match std::str::from_utf8(&self.pending_utf8) {
Ok(text) => text,
Err(err) => {
let error_len = err.error_len().unwrap_or(0);
return Err(Utf8StreamParserError::InvalidUtf8 {
valid_up_to: err.valid_up_to(),
error_len,
});
}
};
let out = self.inner.push_str(text);
self.pending_utf8.clear();
out
};
let mut tail = self.inner.finish();
out.visible_text.push_str(&tail.visible_text);
out.extracted.append(&mut tail.extracted);
Ok(out)
}
/// Return the wrapped parser if no undecoded UTF-8 bytes are buffered.
///
/// Use [`Self::finish`] first if you want to flush buffered text into the wrapped parser.
pub fn into_inner(self) -> Result<P, Utf8StreamParserError> {
if self.pending_utf8.is_empty() {
return Ok(self.inner);
}
match std::str::from_utf8(&self.pending_utf8) {
Ok(_) => Ok(self.inner),
Err(err) => {
if let Some(error_len) = err.error_len() {
return Err(Utf8StreamParserError::InvalidUtf8 {
valid_up_to: err.valid_up_to(),
error_len,
});
}
Err(Utf8StreamParserError::IncompleteUtf8AtEof)
}
}
}
/// Return the wrapped parser without validating or flushing buffered undecoded bytes.
///
/// This may drop a partial UTF-8 code point that was buffered across chunk boundaries.
pub fn into_inner_lossy(self) -> P {
self.inner
}
}
#[cfg(test)]
mod tests {
use super::Utf8StreamParser;
use super::Utf8StreamParserError;
use crate::CitationStreamParser;
use crate::StreamTextChunk;
use crate::StreamTextParser;
use pretty_assertions::assert_eq;
fn collect_bytes(
parser: &mut Utf8StreamParser<CitationStreamParser>,
chunks: &[&[u8]],
) -> Result<StreamTextChunk<String>, Utf8StreamParserError> {
let mut all = StreamTextChunk::default();
for chunk in chunks {
let next = parser.push_bytes(chunk)?;
all.visible_text.push_str(&next.visible_text);
all.extracted.extend(next.extracted);
}
let tail = parser.finish()?;
all.visible_text.push_str(&tail.visible_text);
all.extracted.extend(tail.extracted);
Ok(all)
}
#[test]
fn utf8_stream_parser_handles_split_code_points_across_chunks() {
let chunks: [&[u8]; 3] = [
b"A\xC3",
b"\xA9<oai-mem-citation>\xE4",
b"\xB8\xAD</oai-mem-citation>Z",
];
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
let out = match collect_bytes(&mut parser, &chunks) {
Ok(out) => out,
Err(err) => panic!("valid UTF-8 stream should parse: {err}"),
};
assert_eq!(out.visible_text, "AéZ");
assert_eq!(out.extracted, vec!["中".to_string()]);
}
#[test]
fn utf8_stream_parser_rolls_back_on_invalid_utf8_chunk() {
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
let first = match parser.push_bytes(&[0xC3]) {
Ok(out) => out,
Err(err) => panic!("leading byte may be buffered until next chunk: {err}"),
};
assert!(first.is_empty());
let err = match parser.push_bytes(&[0x28]) {
Ok(out) => panic!("invalid continuation byte should error, got output: {out:?}"),
Err(err) => err,
};
assert_eq!(
err,
Utf8StreamParserError::InvalidUtf8 {
valid_up_to: 0,
error_len: 1,
}
);
let second = match parser.push_bytes(&[0xA9, b'x']) {
Ok(out) => out,
Err(err) => panic!("state should still allow a valid continuation: {err}"),
};
let tail = match parser.finish() {
Ok(out) => out,
Err(err) => panic!("stream should finish: {err}"),
};
assert_eq!(second.visible_text, "éx");
assert!(second.extracted.is_empty());
assert!(tail.is_empty());
}
#[test]
fn utf8_stream_parser_rolls_back_entire_chunk_when_invalid_byte_follows_valid_prefix() {
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
let err = match parser.push_bytes(b"ok\xFF") {
Ok(out) => panic!("invalid byte should error, got output: {out:?}"),
Err(err) => err,
};
assert_eq!(
err,
Utf8StreamParserError::InvalidUtf8 {
valid_up_to: 2,
error_len: 1,
}
);
let next = match parser.push_bytes(b"!") {
Ok(out) => out,
Err(err) => panic!("parser should recover after rollback: {err}"),
};
assert_eq!(next.visible_text, "!");
assert!(next.extracted.is_empty());
}
#[test]
fn utf8_stream_parser_errors_on_incomplete_code_point_at_eof() {
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
let out = match parser.push_bytes(&[0xE2, 0x82]) {
Ok(out) => out,
Err(err) => panic!("partial code point should be buffered: {err}"),
};
assert!(out.is_empty());
let err = match parser.finish() {
Ok(out) => panic!("unfinished code point should error, got output: {out:?}"),
Err(err) => err,
};
assert_eq!(err, Utf8StreamParserError::IncompleteUtf8AtEof);
}
#[test]
fn utf8_stream_parser_into_inner_errors_when_partial_code_point_is_buffered() {
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
let out = match parser.push_bytes(&[0xC3]) {
Ok(out) => out,
Err(err) => panic!("partial code point should be buffered: {err}"),
};
assert!(out.is_empty());
let err = match parser.into_inner() {
Ok(_) => panic!("buffered partial code point should be rejected"),
Err(err) => err,
};
assert_eq!(err, Utf8StreamParserError::IncompleteUtf8AtEof);
}
#[test]
fn utf8_stream_parser_into_inner_lossy_drops_buffered_partial_code_point() {
let mut parser = Utf8StreamParser::new(CitationStreamParser::new());
let out = match parser.push_bytes(&[0xC3]) {
Ok(out) => out,
Err(err) => panic!("partial code point should be buffered: {err}"),
};
assert!(out.is_empty());
let mut inner = parser.into_inner_lossy();
let tail = inner.finish();
assert!(tail.is_empty());
}
}

Some files were not shown because too many files have changed in this diff Show more