Skip to main content

claude_code_agent/
code_mode.rs

1//! Force Code Mode (the `REPL` tool) on for SDK sessions.
2//!
3//! The stock CLI (verified 2.1.329) refuses Code Mode for every
4//! non-interactive session (`-p` / stream-json), so no SDK gets it. With
5//! `SessionOptions::code_mode` the SDK runs a patched copy of the CLI
6//! instead; the installed binary is never modified.
7//!
8//! The patch touches only the Code Mode opt-in module of Bun's embedded
9//! module graph:
10//!   1. local eligibility check (`entrypoint`, `unattended`, provider, …) passes
11//!   2. the one-time caveats dialog counts as accepted
12//!   3. the server gate `tengu_rustling_blossom` counts as open
13//!   4. the module's precompiled bytecode is dropped, so Bun compiles the
14//!      patched source (the bytecode would otherwise run unchanged)
15//!
16//! Every edit keeps the byte length, so no offset in the binary moves. An
17//! anchor that is missing or ambiguous (a CLI version this patch does not
18//! know) is an error, never a silent partial patch.
19//!
20//! Layout of Bun's standalone module graph (Format B, Claude Code 2.1.280+):
21//! trailer `"\n---- Bun! ----\n"` preceded by a 32-byte offsets struct
22//! (`byte_count: u64, modules: (u32 offset, u32 len), …`); the module list
23//! is 52-byte entries of six `(u32 offset, u32 len)` pointers (name,
24//! contents, sourcemap, bytecode, `module_info`, `bytecode_origin_path`) plus
25//! four flag bytes; offsets are relative to `trailer - 32 - byte_count`.
26use std::path::{Path, PathBuf};
27
28use regex::bytes::Regex;
29
30const TRAILER: &[u8] = b"\n---- Bun! ----\n";
31const OFFSETS_SIZE: usize = 32;
32const ENTRY_SIZE: usize = 52;
33/// Byte offset of the bytecode pointer inside a module entry.
34const BYTECODE_PTR: usize = 24;
35/// Present only in the Code Mode opt-in module.
36const MODULE_MARKER: &[u8] = b"\"tengu_rustling_blossom\"";
37
38/// How long one `codesign` run may take before the build is abandoned.
39#[cfg(target_os = "macos")]
40const CODESIGN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
41
42/// Error building the Code Mode binary.
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum CodeModeError {
46    /// The CLI binary is not a Bun standalone executable this patch can
47    /// read; the payload names the check that failed.
48    #[error("not a Bun standalone binary: {0}")]
49    NotBunBinary(&'static str),
50    /// No module contains the Code Mode opt-in marker.
51    #[error("Code Mode module not found in the CLI binary")]
52    ModuleNotFound,
53    /// A patch anchor's regex does not compile.
54    #[error("patch anchor `{name}` has an invalid pattern: {source}")]
55    PatternInvalid {
56        /// Anchor name.
57        name: &'static str,
58        /// The regex error.
59        #[source]
60        source: regex::Error,
61    },
62    /// A patch anchor did not match exactly once.
63    #[error("patch anchor `{name}` found {found} times (expected 1); this CLI version is not supported")]
64    AnchorCount {
65        /// Anchor name.
66        name: &'static str,
67        /// Number of matches.
68        found: usize,
69    },
70    /// A patch anchor matched fewer bytes than its replacement needs.
71    #[error(
72        "patch anchor `{name}` matched {matched} bytes, fewer than its {replacement}-byte replacement; \
73         this CLI version is not supported"
74    )]
75    ReplacementTooShort {
76        /// Anchor name.
77        name: &'static str,
78        /// Length of the match, in bytes.
79        matched: usize,
80        /// Length of the replacement, in bytes.
81        replacement: usize,
82    },
83    /// A filesystem operation on the CLI binary or its patched copy failed,
84    /// or `codesign` could not run or timed out.
85    #[error("io: {0}")]
86    Io(#[from] std::io::Error),
87    /// `codesign` failed on the patched binary (macOS).
88    #[error("re-signing the patched CLI failed: {0}")]
89    Sign(String),
90    /// `SessionOptions::settings` (or its `env`) is not a JSON object.
91    #[error("`settings` must be a JSON object (with an object `env`) to add the Code Mode env var")]
92    Settings,
93    /// Code Mode was requested on a platform other than macOS or Linux.
94    #[error("Code Mode is supported on macOS and Linux only")]
95    UnsupportedPlatform,
96    /// Neither `XDG_CACHE_HOME` nor `HOME` is an absolute path, so there is
97    /// no per-user directory to cache the patched CLI in.
98    #[error("no per-user cache directory for the Code Mode CLI: set HOME or XDG_CACHE_HOME to an absolute path")]
99    NoCacheDir,
100    /// Another user could write the cache directory or the cached CLI, so
101    /// the SDK refuses to run it.
102    #[error("refusing the Code Mode cache at {path}: {reason}")]
103    UnsafeCache {
104        /// The directory or file that failed the check.
105        path: PathBuf,
106        /// What is wrong with it.
107        reason: &'static str,
108    },
109}
110
111// ─── Functional core ─────────────────────────────────────────────────────────
112
113/// Return `binary` with Code Mode forced on.
114pub fn patch(binary: &[u8]) -> Result<Vec<u8>, CodeModeError> {
115    let mut out = binary.to_vec();
116    let (entry, contents) = find_module(&out)?;
117
118    let module = &out[contents.clone()];
119    let gate_var = unique_match(module, "gate variable", r#"var ([\w$]+)="tengu_rustling_blossom""#)?;
120    let gate_var = regex::escape(&String::from_utf8_lossy(&module[gate_var]));
121
122    let edits: [(&'static str, String, &[u8]); 3] = [
123        ("eligibility", r#"(?:\{)(if\(![\w$]+\(\)\)return"runtime";)"#.into(), b"return;"),
124        (
125            "caveats",
126            r"([\w$]+\.codeModeCaveatsAcceptedV1===!0&&[\w$]+\.codeModeAutoModeCaveatAcceptedV1===!0)".into(),
127            b"!0",
128        ),
129        ("gate", format!(r"(return [\w$]+\({gate_var},!0\)!==!0)"), b"return!1"),
130    ];
131    for (name, pattern, replacement) in edits {
132        let span = unique_match(&out[contents.clone()], name, &pattern)?;
133        if span.len() < replacement.len() {
134            return Err(CodeModeError::ReplacementTooShort { name, matched: span.len(), replacement: replacement.len() });
135        }
136        let start = contents.start + span.start;
137        overwrite_padded(&mut out[start..start + span.len()], replacement);
138    }
139
140    // Without bytecode Bun compiles the (patched) source of this module.
141    out.get_mut(entry + BYTECODE_PTR..entry + BYTECODE_PTR + 8)
142        .ok_or(CodeModeError::NotBunBinary("module table"))?
143        .fill(0);
144    Ok(out)
145}
146
147/// (entry offset, contents range) of the Code Mode opt-in module.
148fn find_module(data: &[u8]) -> Result<(usize, std::ops::Range<usize>), CodeModeError> {
149    let trailer = rfind(data, TRAILER).ok_or(CodeModeError::NotBunBinary("no trailer"))?;
150    let offsets = trailer.checked_sub(OFFSETS_SIZE).ok_or(CodeModeError::NotBunBinary("short file"))?;
151    let byte_count = usize::try_from(read_u64(data, offsets)?).map_err(|_| CodeModeError::NotBunBinary("size"))?;
152    let modules_off = read_u32(data, offsets + 8)?;
153    let modules_len = read_u32(data, offsets + 12)?;
154    let base = offsets.checked_sub(byte_count).ok_or(CodeModeError::NotBunBinary("graph size"))?;
155
156    for i in 0..modules_len / ENTRY_SIZE {
157        let entry = base + modules_off + i * ENTRY_SIZE;
158        let start = base + read_u32(data, entry + 8)?;
159        let end = start + read_u32(data, entry + 12)?;
160        let contents = data.get(start..end).ok_or(CodeModeError::NotBunBinary("module bounds"))?;
161        if contents.windows(MODULE_MARKER.len()).any(|w| w == MODULE_MARKER) {
162            return Ok((entry, start..end));
163        }
164    }
165    Err(CodeModeError::ModuleNotFound)
166}
167
168/// Range (within `haystack`) of capture group 1 of the only match.
169fn unique_match(haystack: &[u8], name: &'static str, pattern: &str) -> Result<std::ops::Range<usize>, CodeModeError> {
170    let re = Regex::new(pattern).map_err(|source| CodeModeError::PatternInvalid { name, source })?;
171    let found: Vec<_> = re.captures_iter(haystack).filter_map(|c| c.get(1)).map(|m| m.range()).collect();
172    match found.as_slice() {
173        [one] => Ok(one.clone()),
174        _ => Err(CodeModeError::AnchorCount { name, found: found.len() }),
175    }
176}
177
178/// Write `with` into `slot`, padding with spaces (valid JS whitespace).
179fn overwrite_padded(slot: &mut [u8], with: &[u8]) {
180    slot.fill(b' ');
181    for (dst, src) in slot.iter_mut().zip(with) {
182        *dst = *src;
183    }
184}
185
186fn rfind(data: &[u8], needle: &[u8]) -> Option<usize> {
187    data.windows(needle.len()).rposition(|w| w == needle)
188}
189
190fn read_u32(data: &[u8], at: usize) -> Result<usize, CodeModeError> {
191    let bytes = data.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok());
192    bytes.map(|b| u32::from_le_bytes(b) as usize).ok_or(CodeModeError::NotBunBinary("truncated"))
193}
194
195fn read_u64(data: &[u8], at: usize) -> Result<u64, CodeModeError> {
196    let bytes = data.get(at..at + 8).and_then(|b| <[u8; 8]>::try_from(b).ok());
197    bytes.map(u64::from_le_bytes).ok_or(CodeModeError::NotBunBinary("truncated"))
198}
199
200// ─── Imperative shell ────────────────────────────────────────────────────────
201
202/// Serializes builds: a pool warming N sessions builds the copy once.
203static BUILD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
204
205/// Path of a patched copy of `binary` (resolved through `PATH`), built on
206/// first use and cached under `<cache>/claude-code-agent/code-mode/`. The cache key
207/// is the installed binary's name, size and mtime plus this SDK's version,
208/// so a CLI update or a new patch builds a new copy. The cache must be
209/// private to the current user (see [`CodeModeError::UnsafeCache`]).
210pub async fn patched_binary(binary: &Path) -> Result<PathBuf, CodeModeError> {
211    if cfg!(windows) {
212        return Err(CodeModeError::UnsupportedPlatform);
213    }
214    let source = tokio::fs::canonicalize(resolve(binary)).await?;
215    let key = source_key(&source).await?;
216    let base = cache_base()?;
217    let dir = base.join(CACHE_SUBDIR).join(format!("{key}-sdk{}", env!("CARGO_PKG_VERSION")));
218    let target = dir.join("claude");
219
220    let _guard = BUILD.lock().await;
221    secure_cache_dirs(&base, &dir).await?;
222    remove_dead_partials(&dir).await;
223    if tokio::fs::try_exists(&target).await? {
224        secure_cached_binary(&target).await?;
225        return Ok(target);
226    }
227    // Read by prune_stale_builds in any process: the build is stale once
228    // this source changes or disappears.
229    tokio::fs::write(dir.join(SOURCE_FILE), source.to_string_lossy().as_bytes()).await?;
230
231    let original = tokio::fs::read(&source).await?;
232    let patched = tokio::task::spawn_blocking(move || patch(&original))
233        .await
234        .map_err(|e| CodeModeError::Io(std::io::Error::other(e)))??;
235    // Write to a name unique to this build (pid first, for
236    // remove_dead_partials), then rename: neither a crash nor another process
237    // building at the same time leaves a half copy at `target`.
238    let nanos = std::time::SystemTime::now()
239        .duration_since(std::time::UNIX_EPOCH)
240        .map(|d| d.subsec_nanos())
241        .unwrap_or_default();
242    let partial = dir.join(format!("claude.{}.{nanos}.partial", std::process::id()));
243    tokio::fs::write(&partial, patched).await?;
244    #[cfg(unix)]
245    {
246        use std::os::unix::fs::PermissionsExt;
247        tokio::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o755)).await?;
248    }
249    if let Err(e) = sign(&partial, &source).await {
250        remove_leftover(&partial).await;
251        return Err(e);
252    }
253    tokio::fs::rename(&partial, &target).await?;
254    prune_stale_builds(&dir).await;
255    tracing::info!(source = %source.display(), patched = %target.display(), "built Code Mode CLI");
256    Ok(target)
257}
258
259/// Name of the file in each build directory holding the source CLI's path.
260const SOURCE_FILE: &str = "source";
261
262/// `<name>-<size>-<mtime>` of the installed CLI.
263async fn source_key(source: &Path) -> std::io::Result<String> {
264    let meta = tokio::fs::metadata(source).await?;
265    let mtime = meta
266        .modified()?
267        .duration_since(std::time::UNIX_EPOCH)
268        .map(|d| d.as_secs())
269        .unwrap_or_default();
270    let name = source.file_name().map_or_else(|| "claude".into(), |n| n.to_string_lossy().into_owned());
271    Ok(format!("{name}-{}-{mtime}", meta.len()))
272}
273
274/// Delete copies (about 230 MB each) whose source CLI was updated or
275/// removed. Copies of CLIs still installed stay, so programs using other
276/// CLI installs or SDK versions keep theirs. A session still running a
277/// deleted copy keeps working: unix unlinks open files lazily.
278async fn prune_stale_builds(current: &Path) {
279    let Some(root) = current.parent() else { return };
280    let Ok(mut entries) = tokio::fs::read_dir(root).await else { return };
281    while let Ok(Some(entry)) = entries.next_entry().await {
282        let path = entry.path();
283        if path != current && is_stale_build(&path).await && tokio::fs::remove_dir_all(&path).await.is_ok() {
284            tracing::debug!(path = %path.display(), "removed stale Code Mode CLI");
285        }
286    }
287}
288
289async fn is_stale_build(dir: &Path) -> bool {
290    match tokio::fs::read(dir.join(SOURCE_FILE)).await {
291        Ok(bytes) => {
292            let source = PathBuf::from(String::from_utf8_lossy(&bytes).into_owned());
293            let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
294            match source_key(&source).await {
295                Ok(key) => !name.starts_with(&format!("{key}-")),
296                Err(_) => true,
297            }
298        }
299        // No source file: a build being set up right now (no `claude` yet)
300        // is kept; a finished one without it predates source tracking.
301        Err(_) => tokio::fs::try_exists(dir.join("claude")).await.unwrap_or(false),
302    }
303}
304
305/// `binary` as given if it has a directory part, else the first match on `PATH`.
306fn resolve(binary: &Path) -> PathBuf {
307    if binary.components().count() > 1 {
308        return binary.to_path_buf();
309    }
310    std::env::var_os("PATH")
311        .into_iter()
312        .flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
313        .map(|dir| dir.join(binary))
314        .find(|candidate| candidate.is_file())
315        .unwrap_or_else(|| binary.to_path_buf())
316}
317
318/// Best-effort delete of a temporary file; a failure only leaves litter.
319async fn remove_leftover(path: &Path) {
320    if let Err(e) = tokio::fs::remove_file(path).await
321        && e.kind() != std::io::ErrorKind::NotFound
322    {
323        tracing::warn!(path = %path.display(), error = %e, "could not remove temporary Code Mode file");
324    }
325}
326
327/// Builds live in `<cache base>/claude-code-agent/code-mode/<build>/`.
328const CACHE_SUBDIR: &str = "claude-code-agent/code-mode";
329
330/// `$XDG_CACHE_HOME`, else `$HOME/.cache`; relative values are ignored, as
331/// the XDG spec requires. There is no shared fallback such as `/tmp`: another
332/// local user could plant a binary there that the host would then run.
333fn cache_base() -> Result<PathBuf, CodeModeError> {
334    let absolute = |var| std::env::var_os(var).map(PathBuf::from).filter(|p| p.is_absolute());
335    absolute("XDG_CACHE_HOME").or_else(|| absolute("HOME").map(|h| h.join(".cache"))).ok_or(CodeModeError::NoCacheDir)
336}
337
338/// Create `build` (mode 0700) and make sure no other user can write any
339/// directory from `base` down to it, so a cached binary there is ours.
340/// `base` must be ours; it may be group writable (the norm with per-user
341/// groups, umask 002) but not world writable (like `/tmp`), where any user
342/// could swap the SDK's directories. Those must be ours too; they are set
343/// to 0700.
344#[cfg(unix)]
345async fn secure_cache_dirs(base: &Path, build: &Path) -> Result<(), CodeModeError> {
346    use std::os::unix::fs::PermissionsExt;
347    let mut private = tokio::fs::DirBuilder::new();
348    private.recursive(true).mode(0o700);
349    private.create(base).await?;
350    // Followed if a symlink: the directory it names must be ours.
351    let base_meta = tokio::fs::metadata(base).await?;
352    owned_by_us(base, &base_meta)?;
353    if base_meta.permissions().mode() & 0o002 != 0 {
354        return Err(CodeModeError::UnsafeCache { path: base.into(), reason: "world writable" });
355    }
356    private.create(build).await?;
357    for dir in build.ancestors().take_while(|d| *d != base) {
358        let meta = tokio::fs::symlink_metadata(dir).await?;
359        if !meta.is_dir() {
360            return Err(CodeModeError::UnsafeCache { path: dir.into(), reason: "not a directory" });
361        }
362        owned_by_us(dir, &meta)?;
363        tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await?;
364    }
365    Ok(())
366}
367
368#[cfg(not(unix))]
369async fn secure_cache_dirs(_base: &Path, build: &Path) -> Result<(), CodeModeError> {
370    Ok(tokio::fs::create_dir_all(build).await?)
371}
372
373/// Refuse a cached binary that is a symlink or that we do not own.
374#[cfg(unix)]
375async fn secure_cached_binary(binary: &Path) -> Result<(), CodeModeError> {
376    use std::os::unix::fs::PermissionsExt;
377    let meta = tokio::fs::symlink_metadata(binary).await?;
378    if !meta.is_file() {
379        return Err(CodeModeError::UnsafeCache { path: binary.into(), reason: "not a regular file" });
380    }
381    owned_by_us(binary, &meta)?;
382    Ok(tokio::fs::set_permissions(binary, std::fs::Permissions::from_mode(0o755)).await?)
383}
384
385#[cfg(not(unix))]
386async fn secure_cached_binary(_binary: &Path) -> Result<(), CodeModeError> {
387    Ok(())
388}
389
390#[cfg(unix)]
391fn owned_by_us(path: &Path, meta: &std::fs::Metadata) -> Result<(), CodeModeError> {
392    use std::os::unix::fs::MetadataExt;
393    if meta.uid() == nix::unistd::geteuid().as_raw() {
394        Ok(())
395    } else {
396        Err(CodeModeError::UnsafeCache { path: path.into(), reason: "owned by another user" })
397    }
398}
399
400/// Delete temporary files (`claude.<pid>.…`) left in `dir` by a build that
401/// died mid-way. The caller holds [`BUILD`], so this process's own files are
402/// leftovers; another process's are leftovers once that pid is gone. A live
403/// pid's files stay, since that process may be building right now; a reused
404/// pid only delays the cleanup to a later build.
405async fn remove_dead_partials(dir: &Path) {
406    let Ok(mut entries) = tokio::fs::read_dir(dir).await else { return };
407    let me = std::process::id();
408    while let Ok(Some(entry)) = entries.next_entry().await {
409        let Some(pid) = entry.file_name().to_str().and_then(builder_pid) else { continue };
410        if pid == me || !process_alive(pid) {
411            remove_leftover(&entry.path()).await;
412        }
413    }
414}
415
416/// The builder pid in a temporary file name `claude.<pid>.<nanos>.…`.
417fn builder_pid(name: &str) -> Option<u32> {
418    name.strip_prefix("claude.")?.split('.').next()?.parse().ok()
419}
420
421#[cfg(unix)]
422fn process_alive(pid: u32) -> bool {
423    use nix::{errno::Errno, sys::signal::kill, unistd::Pid};
424    match i32::try_from(pid) {
425        Ok(raw) if raw > 0 => kill(Pid::from_raw(raw), None) != Err(Errno::ESRCH),
426        _ => true,
427    }
428}
429
430#[cfg(not(unix))]
431fn process_alive(_pid: u32) -> bool {
432    true
433}
434
435/// macOS kills a modified binary unless it is re-signed; the stock
436/// entitlements (JIT, unsigned executable memory) must carry over.
437#[cfg(target_os = "macos")]
438async fn sign(patched: &Path, source: &Path) -> Result<(), CodeModeError> {
439    let ents = codesign(|c| c.args(["-d", "--entitlements", "-", "--xml"]).arg(source)).await?;
440    if !ents.status.success() || !ents.stdout.starts_with(b"<?xml") {
441        return Err(CodeModeError::Sign(format!(
442            "could not read entitlements of {}: {}",
443            source.display(),
444            String::from_utf8_lossy(&ents.stderr).trim()
445        )));
446    }
447    let plist = patched.with_extension("entitlements.plist");
448    tokio::fs::write(&plist, &ents.stdout).await?;
449    let out = codesign(|c| {
450        c.args(["--force", "--sign", "-", "--timestamp=none", "--entitlements"]).arg(&plist).arg(patched)
451    })
452    .await;
453    remove_leftover(&plist).await;
454    let out = out?;
455    if out.status.success() {
456        Ok(())
457    } else {
458        Err(CodeModeError::Sign(String::from_utf8_lossy(&out.stderr).trim().to_string()))
459    }
460}
461
462/// Run `codesign` with the arguments `args` adds, killed after [`CODESIGN_TIMEOUT`]
463/// (the caller holds the build lock).
464#[cfg(target_os = "macos")]
465async fn codesign(
466    args: impl FnOnce(&mut tokio::process::Command) -> &mut tokio::process::Command,
467) -> Result<std::process::Output, CodeModeError> {
468    let mut cmd = tokio::process::Command::new("codesign");
469    args(&mut cmd).kill_on_drop(true);
470    tokio::time::timeout(CODESIGN_TIMEOUT, cmd.output()).await.map_err(|_| {
471        std::io::Error::new(std::io::ErrorKind::TimedOut, format!("codesign timed out after {CODESIGN_TIMEOUT:?}"))
472    })?
473    .map_err(CodeModeError::from)
474}
475
476#[cfg(not(target_os = "macos"))]
477async fn sign(_patched: &Path, _source: &Path) -> Result<(), CodeModeError> {
478    Ok(())
479}