use std::path::{Path, PathBuf};
use regex::bytes::Regex;
const TRAILER: &[u8] = b"\n---- Bun! ----\n";
const OFFSETS_SIZE: usize = 32;
const ENTRY_SIZE: usize = 52;
const BYTECODE_PTR: usize = 24;
const MODULE_MARKER: &[u8] = b"\"tengu_rustling_blossom\"";
#[cfg(target_os = "macos")]
const CODESIGN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CodeModeError {
#[error("not a Bun standalone binary: {0}")]
NotBunBinary(&'static str),
#[error("Code Mode module not found in the CLI binary")]
ModuleNotFound,
#[error("patch anchor `{name}` has an invalid pattern: {source}")]
PatternInvalid {
name: &'static str,
#[source]
source: regex::Error,
},
#[error("patch anchor `{name}` found {found} times (expected 1); this CLI version is not supported")]
AnchorCount {
name: &'static str,
found: usize,
},
#[error(
"patch anchor `{name}` matched {matched} bytes, fewer than its {replacement}-byte replacement; \
this CLI version is not supported"
)]
ReplacementTooShort {
name: &'static str,
matched: usize,
replacement: usize,
},
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("re-signing the patched CLI failed: {0}")]
Sign(String),
#[error("`settings` must be a JSON object (with an object `env`) to add the Code Mode env var")]
Settings,
#[error("Code Mode is supported on macOS and Linux only")]
UnsupportedPlatform,
#[error("no per-user cache directory for the Code Mode CLI: set HOME or XDG_CACHE_HOME to an absolute path")]
NoCacheDir,
#[error("refusing the Code Mode cache at {path}: {reason}")]
UnsafeCache {
path: PathBuf,
reason: &'static str,
},
}
pub fn patch(binary: &[u8]) -> Result<Vec<u8>, CodeModeError> {
let mut out = binary.to_vec();
let (entry, contents) = find_module(&out)?;
let module = &out[contents.clone()];
let gate_var = unique_match(module, "gate variable", r#"var ([\w$]+)="tengu_rustling_blossom""#)?;
let gate_var = regex::escape(&String::from_utf8_lossy(&module[gate_var]));
let edits: [(&'static str, String, &[u8]); 3] = [
("eligibility", r#"(?:\{)(if\(![\w$]+\(\)\)return"runtime";)"#.into(), b"return;"),
(
"caveats",
r"([\w$]+\.codeModeCaveatsAcceptedV1===!0&&[\w$]+\.codeModeAutoModeCaveatAcceptedV1===!0)".into(),
b"!0",
),
("gate", format!(r"(return [\w$]+\({gate_var},!0\)!==!0)"), b"return!1"),
];
for (name, pattern, replacement) in edits {
let span = unique_match(&out[contents.clone()], name, &pattern)?;
if span.len() < replacement.len() {
return Err(CodeModeError::ReplacementTooShort { name, matched: span.len(), replacement: replacement.len() });
}
let start = contents.start + span.start;
overwrite_padded(&mut out[start..start + span.len()], replacement);
}
out.get_mut(entry + BYTECODE_PTR..entry + BYTECODE_PTR + 8)
.ok_or(CodeModeError::NotBunBinary("module table"))?
.fill(0);
Ok(out)
}
fn find_module(data: &[u8]) -> Result<(usize, std::ops::Range<usize>), CodeModeError> {
let trailer = rfind(data, TRAILER).ok_or(CodeModeError::NotBunBinary("no trailer"))?;
let offsets = trailer.checked_sub(OFFSETS_SIZE).ok_or(CodeModeError::NotBunBinary("short file"))?;
let byte_count = usize::try_from(read_u64(data, offsets)?).map_err(|_| CodeModeError::NotBunBinary("size"))?;
let modules_off = read_u32(data, offsets + 8)?;
let modules_len = read_u32(data, offsets + 12)?;
let base = offsets.checked_sub(byte_count).ok_or(CodeModeError::NotBunBinary("graph size"))?;
for i in 0..modules_len / ENTRY_SIZE {
let entry = base + modules_off + i * ENTRY_SIZE;
let start = base + read_u32(data, entry + 8)?;
let end = start + read_u32(data, entry + 12)?;
let contents = data.get(start..end).ok_or(CodeModeError::NotBunBinary("module bounds"))?;
if contents.windows(MODULE_MARKER.len()).any(|w| w == MODULE_MARKER) {
return Ok((entry, start..end));
}
}
Err(CodeModeError::ModuleNotFound)
}
fn unique_match(haystack: &[u8], name: &'static str, pattern: &str) -> Result<std::ops::Range<usize>, CodeModeError> {
let re = Regex::new(pattern).map_err(|source| CodeModeError::PatternInvalid { name, source })?;
let found: Vec<_> = re.captures_iter(haystack).filter_map(|c| c.get(1)).map(|m| m.range()).collect();
match found.as_slice() {
[one] => Ok(one.clone()),
_ => Err(CodeModeError::AnchorCount { name, found: found.len() }),
}
}
fn overwrite_padded(slot: &mut [u8], with: &[u8]) {
slot.fill(b' ');
for (dst, src) in slot.iter_mut().zip(with) {
*dst = *src;
}
}
fn rfind(data: &[u8], needle: &[u8]) -> Option<usize> {
data.windows(needle.len()).rposition(|w| w == needle)
}
fn read_u32(data: &[u8], at: usize) -> Result<usize, CodeModeError> {
let bytes = data.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok());
bytes.map(|b| u32::from_le_bytes(b) as usize).ok_or(CodeModeError::NotBunBinary("truncated"))
}
fn read_u64(data: &[u8], at: usize) -> Result<u64, CodeModeError> {
let bytes = data.get(at..at + 8).and_then(|b| <[u8; 8]>::try_from(b).ok());
bytes.map(u64::from_le_bytes).ok_or(CodeModeError::NotBunBinary("truncated"))
}
static BUILD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
pub async fn patched_binary(binary: &Path) -> Result<PathBuf, CodeModeError> {
if cfg!(windows) {
return Err(CodeModeError::UnsupportedPlatform);
}
let source = tokio::fs::canonicalize(resolve(binary)).await?;
let key = source_key(&source).await?;
let base = cache_base()?;
let dir = base.join(CACHE_SUBDIR).join(format!("{key}-sdk{}", env!("CARGO_PKG_VERSION")));
let target = dir.join("claude");
let _guard = BUILD.lock().await;
secure_cache_dirs(&base, &dir).await?;
remove_dead_partials(&dir).await;
if tokio::fs::try_exists(&target).await? {
secure_cached_binary(&target).await?;
return Ok(target);
}
tokio::fs::write(dir.join(SOURCE_FILE), source.to_string_lossy().as_bytes()).await?;
let original = tokio::fs::read(&source).await?;
let patched = tokio::task::spawn_blocking(move || patch(&original))
.await
.map_err(|e| CodeModeError::Io(std::io::Error::other(e)))??;
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or_default();
let partial = dir.join(format!("claude.{}.{nanos}.partial", std::process::id()));
tokio::fs::write(&partial, patched).await?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
tokio::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o755)).await?;
}
if let Err(e) = sign(&partial, &source).await {
remove_leftover(&partial).await;
return Err(e);
}
tokio::fs::rename(&partial, &target).await?;
prune_stale_builds(&dir).await;
tracing::info!(source = %source.display(), patched = %target.display(), "built Code Mode CLI");
Ok(target)
}
const SOURCE_FILE: &str = "source";
async fn source_key(source: &Path) -> std::io::Result<String> {
let meta = tokio::fs::metadata(source).await?;
let mtime = meta
.modified()?
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or_default();
let name = source.file_name().map_or_else(|| "claude".into(), |n| n.to_string_lossy().into_owned());
Ok(format!("{name}-{}-{mtime}", meta.len()))
}
async fn prune_stale_builds(current: &Path) {
let Some(root) = current.parent() else { return };
let Ok(mut entries) = tokio::fs::read_dir(root).await else { return };
while let Ok(Some(entry)) = entries.next_entry().await {
let path = entry.path();
if path != current && is_stale_build(&path).await && tokio::fs::remove_dir_all(&path).await.is_ok() {
tracing::debug!(path = %path.display(), "removed stale Code Mode CLI");
}
}
}
async fn is_stale_build(dir: &Path) -> bool {
match tokio::fs::read(dir.join(SOURCE_FILE)).await {
Ok(bytes) => {
let source = PathBuf::from(String::from_utf8_lossy(&bytes).into_owned());
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
match source_key(&source).await {
Ok(key) => !name.starts_with(&format!("{key}-")),
Err(_) => true,
}
}
Err(_) => tokio::fs::try_exists(dir.join("claude")).await.unwrap_or(false),
}
}
fn resolve(binary: &Path) -> PathBuf {
if binary.components().count() > 1 {
return binary.to_path_buf();
}
std::env::var_os("PATH")
.into_iter()
.flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
.map(|dir| dir.join(binary))
.find(|candidate| candidate.is_file())
.unwrap_or_else(|| binary.to_path_buf())
}
async fn remove_leftover(path: &Path) {
if let Err(e) = tokio::fs::remove_file(path).await
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(path = %path.display(), error = %e, "could not remove temporary Code Mode file");
}
}
const CACHE_SUBDIR: &str = "claude-code-agent/code-mode";
fn cache_base() -> Result<PathBuf, CodeModeError> {
let absolute = |var| std::env::var_os(var).map(PathBuf::from).filter(|p| p.is_absolute());
absolute("XDG_CACHE_HOME").or_else(|| absolute("HOME").map(|h| h.join(".cache"))).ok_or(CodeModeError::NoCacheDir)
}
#[cfg(unix)]
async fn secure_cache_dirs(base: &Path, build: &Path) -> Result<(), CodeModeError> {
use std::os::unix::fs::PermissionsExt;
let mut private = tokio::fs::DirBuilder::new();
private.recursive(true).mode(0o700);
private.create(base).await?;
let base_meta = tokio::fs::metadata(base).await?;
owned_by_us(base, &base_meta)?;
if base_meta.permissions().mode() & 0o002 != 0 {
return Err(CodeModeError::UnsafeCache { path: base.into(), reason: "world writable" });
}
private.create(build).await?;
for dir in build.ancestors().take_while(|d| *d != base) {
let meta = tokio::fs::symlink_metadata(dir).await?;
if !meta.is_dir() {
return Err(CodeModeError::UnsafeCache { path: dir.into(), reason: "not a directory" });
}
owned_by_us(dir, &meta)?;
tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await?;
}
Ok(())
}
#[cfg(not(unix))]
async fn secure_cache_dirs(_base: &Path, build: &Path) -> Result<(), CodeModeError> {
Ok(tokio::fs::create_dir_all(build).await?)
}
#[cfg(unix)]
async fn secure_cached_binary(binary: &Path) -> Result<(), CodeModeError> {
use std::os::unix::fs::PermissionsExt;
let meta = tokio::fs::symlink_metadata(binary).await?;
if !meta.is_file() {
return Err(CodeModeError::UnsafeCache { path: binary.into(), reason: "not a regular file" });
}
owned_by_us(binary, &meta)?;
Ok(tokio::fs::set_permissions(binary, std::fs::Permissions::from_mode(0o755)).await?)
}
#[cfg(not(unix))]
async fn secure_cached_binary(_binary: &Path) -> Result<(), CodeModeError> {
Ok(())
}
#[cfg(unix)]
fn owned_by_us(path: &Path, meta: &std::fs::Metadata) -> Result<(), CodeModeError> {
use std::os::unix::fs::MetadataExt;
if meta.uid() == nix::unistd::geteuid().as_raw() {
Ok(())
} else {
Err(CodeModeError::UnsafeCache { path: path.into(), reason: "owned by another user" })
}
}
async fn remove_dead_partials(dir: &Path) {
let Ok(mut entries) = tokio::fs::read_dir(dir).await else { return };
let me = std::process::id();
while let Ok(Some(entry)) = entries.next_entry().await {
let Some(pid) = entry.file_name().to_str().and_then(builder_pid) else { continue };
if pid == me || !process_alive(pid) {
remove_leftover(&entry.path()).await;
}
}
}
fn builder_pid(name: &str) -> Option<u32> {
name.strip_prefix("claude.")?.split('.').next()?.parse().ok()
}
#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
use nix::{errno::Errno, sys::signal::kill, unistd::Pid};
match i32::try_from(pid) {
Ok(raw) if raw > 0 => kill(Pid::from_raw(raw), None) != Err(Errno::ESRCH),
_ => true,
}
}
#[cfg(not(unix))]
fn process_alive(_pid: u32) -> bool {
true
}
#[cfg(target_os = "macos")]
async fn sign(patched: &Path, source: &Path) -> Result<(), CodeModeError> {
let ents = codesign(|c| c.args(["-d", "--entitlements", "-", "--xml"]).arg(source)).await?;
if !ents.status.success() || !ents.stdout.starts_with(b"<?xml") {
return Err(CodeModeError::Sign(format!(
"could not read entitlements of {}: {}",
source.display(),
String::from_utf8_lossy(&ents.stderr).trim()
)));
}
let plist = patched.with_extension("entitlements.plist");
tokio::fs::write(&plist, &ents.stdout).await?;
let out = codesign(|c| {
c.args(["--force", "--sign", "-", "--timestamp=none", "--entitlements"]).arg(&plist).arg(patched)
})
.await;
remove_leftover(&plist).await;
let out = out?;
if out.status.success() {
Ok(())
} else {
Err(CodeModeError::Sign(String::from_utf8_lossy(&out.stderr).trim().to_string()))
}
}
#[cfg(target_os = "macos")]
async fn codesign(
args: impl FnOnce(&mut tokio::process::Command) -> &mut tokio::process::Command,
) -> Result<std::process::Output, CodeModeError> {
let mut cmd = tokio::process::Command::new("codesign");
args(&mut cmd).kill_on_drop(true);
tokio::time::timeout(CODESIGN_TIMEOUT, cmd.output()).await.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::TimedOut, format!("codesign timed out after {CODESIGN_TIMEOUT:?}"))
})?
.map_err(CodeModeError::from)
}
#[cfg(not(target_os = "macos"))]
async fn sign(_patched: &Path, _source: &Path) -> Result<(), CodeModeError> {
Ok(())
}