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}
97
98// ─── Functional core ─────────────────────────────────────────────────────────
99
100/// Return `binary` with Code Mode forced on.
101pub fn patch(binary: &[u8]) -> Result<Vec<u8>, CodeModeError> {
102    let mut out = binary.to_vec();
103    let (entry, contents) = find_module(&out)?;
104
105    let module = &out[contents.clone()];
106    let gate_var = unique_match(module, "gate variable", r#"var ([\w$]+)="tengu_rustling_blossom""#)?;
107    let gate_var = regex::escape(&String::from_utf8_lossy(&module[gate_var]));
108
109    let edits: [(&'static str, String, &[u8]); 3] = [
110        ("eligibility", r#"(?:\{)(if\(![\w$]+\(\)\)return"runtime";)"#.into(), b"return;"),
111        (
112            "caveats",
113            r"([\w$]+\.codeModeCaveatsAcceptedV1===!0&&[\w$]+\.codeModeAutoModeCaveatAcceptedV1===!0)".into(),
114            b"!0",
115        ),
116        ("gate", format!(r"(return [\w$]+\({gate_var},!0\)!==!0)"), b"return!1"),
117    ];
118    for (name, pattern, replacement) in edits {
119        let span = unique_match(&out[contents.clone()], name, &pattern)?;
120        if span.len() < replacement.len() {
121            return Err(CodeModeError::ReplacementTooShort { name, matched: span.len(), replacement: replacement.len() });
122        }
123        let start = contents.start + span.start;
124        overwrite_padded(&mut out[start..start + span.len()], replacement);
125    }
126
127    // Without bytecode Bun compiles the (patched) source of this module.
128    out.get_mut(entry + BYTECODE_PTR..entry + BYTECODE_PTR + 8)
129        .ok_or(CodeModeError::NotBunBinary("module table"))?
130        .fill(0);
131    Ok(out)
132}
133
134/// (entry offset, contents range) of the Code Mode opt-in module.
135fn find_module(data: &[u8]) -> Result<(usize, std::ops::Range<usize>), CodeModeError> {
136    let trailer = rfind(data, TRAILER).ok_or(CodeModeError::NotBunBinary("no trailer"))?;
137    let offsets = trailer.checked_sub(OFFSETS_SIZE).ok_or(CodeModeError::NotBunBinary("short file"))?;
138    let byte_count = usize::try_from(read_u64(data, offsets)?).map_err(|_| CodeModeError::NotBunBinary("size"))?;
139    let modules_off = read_u32(data, offsets + 8)?;
140    let modules_len = read_u32(data, offsets + 12)?;
141    let base = offsets.checked_sub(byte_count).ok_or(CodeModeError::NotBunBinary("graph size"))?;
142
143    for i in 0..modules_len / ENTRY_SIZE {
144        let entry = base + modules_off + i * ENTRY_SIZE;
145        let start = base + read_u32(data, entry + 8)?;
146        let end = start + read_u32(data, entry + 12)?;
147        let contents = data.get(start..end).ok_or(CodeModeError::NotBunBinary("module bounds"))?;
148        if contents.windows(MODULE_MARKER.len()).any(|w| w == MODULE_MARKER) {
149            return Ok((entry, start..end));
150        }
151    }
152    Err(CodeModeError::ModuleNotFound)
153}
154
155/// Range (within `haystack`) of capture group 1 of the only match.
156fn unique_match(haystack: &[u8], name: &'static str, pattern: &str) -> Result<std::ops::Range<usize>, CodeModeError> {
157    let re = Regex::new(pattern).map_err(|source| CodeModeError::PatternInvalid { name, source })?;
158    let found: Vec<_> = re.captures_iter(haystack).filter_map(|c| c.get(1)).map(|m| m.range()).collect();
159    match found.as_slice() {
160        [one] => Ok(one.clone()),
161        _ => Err(CodeModeError::AnchorCount { name, found: found.len() }),
162    }
163}
164
165/// Write `with` into `slot`, padding with spaces (valid JS whitespace).
166fn overwrite_padded(slot: &mut [u8], with: &[u8]) {
167    slot.fill(b' ');
168    for (dst, src) in slot.iter_mut().zip(with) {
169        *dst = *src;
170    }
171}
172
173fn rfind(data: &[u8], needle: &[u8]) -> Option<usize> {
174    data.windows(needle.len()).rposition(|w| w == needle)
175}
176
177fn read_u32(data: &[u8], at: usize) -> Result<usize, CodeModeError> {
178    let bytes = data.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok());
179    bytes.map(|b| u32::from_le_bytes(b) as usize).ok_or(CodeModeError::NotBunBinary("truncated"))
180}
181
182fn read_u64(data: &[u8], at: usize) -> Result<u64, CodeModeError> {
183    let bytes = data.get(at..at + 8).and_then(|b| <[u8; 8]>::try_from(b).ok());
184    bytes.map(u64::from_le_bytes).ok_or(CodeModeError::NotBunBinary("truncated"))
185}
186
187// ─── Imperative shell ────────────────────────────────────────────────────────
188
189/// Serializes builds: a pool warming N sessions builds the copy once.
190static BUILD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
191
192/// Path of a patched copy of `binary` (resolved through `PATH`), built on
193/// first use and cached under `<cache>/claude-code-agent/code-mode/`. The cache key
194/// is the installed binary's name, size and mtime plus this SDK's version,
195/// so a CLI update or a new patch builds a new copy.
196pub async fn patched_binary(binary: &Path) -> Result<PathBuf, CodeModeError> {
197    if cfg!(windows) {
198        return Err(CodeModeError::UnsupportedPlatform);
199    }
200    let source = tokio::fs::canonicalize(resolve(binary)).await?;
201    let key = source_key(&source).await?;
202    let target = cache_dir().join(format!("{key}-sdk{}", env!("CARGO_PKG_VERSION"))).join("claude");
203
204    let _guard = BUILD.lock().await;
205    if tokio::fs::try_exists(&target).await? {
206        return Ok(target);
207    }
208    let dir = target.parent().ok_or(CodeModeError::NotBunBinary("cache path"))?;
209    tokio::fs::create_dir_all(dir).await?;
210    // Read by prune_stale_builds in any process: the build is stale once
211    // this source changes or disappears.
212    tokio::fs::write(dir.join(SOURCE_FILE), source.to_string_lossy().as_bytes()).await?;
213
214    let original = tokio::fs::read(&source).await?;
215    let patched = tokio::task::spawn_blocking(move || patch(&original))
216        .await
217        .map_err(|e| CodeModeError::Io(std::io::Error::other(e)))??;
218    // Write to a name unique to this build, then rename: neither a crash nor
219    // another process building at the same time leaves a half copy.
220    let nanos = std::time::SystemTime::now()
221        .duration_since(std::time::UNIX_EPOCH)
222        .map(|d| d.subsec_nanos())
223        .unwrap_or_default();
224    let partial = dir.join(format!("claude.{}.{nanos}.partial", std::process::id()));
225    tokio::fs::write(&partial, patched).await?;
226    #[cfg(unix)]
227    {
228        use std::os::unix::fs::PermissionsExt;
229        tokio::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o755)).await?;
230    }
231    if let Err(e) = sign(&partial, &source).await {
232        remove_leftover(&partial).await;
233        return Err(e);
234    }
235    tokio::fs::rename(&partial, &target).await?;
236    prune_stale_builds(dir).await;
237    tracing::info!(source = %source.display(), patched = %target.display(), "built Code Mode CLI");
238    Ok(target)
239}
240
241/// Name of the file in each build directory holding the source CLI's path.
242const SOURCE_FILE: &str = "source";
243
244/// `<name>-<size>-<mtime>` of the installed CLI.
245async fn source_key(source: &Path) -> std::io::Result<String> {
246    let meta = tokio::fs::metadata(source).await?;
247    let mtime = meta
248        .modified()?
249        .duration_since(std::time::UNIX_EPOCH)
250        .map(|d| d.as_secs())
251        .unwrap_or_default();
252    let name = source.file_name().map_or_else(|| "claude".into(), |n| n.to_string_lossy().into_owned());
253    Ok(format!("{name}-{}-{mtime}", meta.len()))
254}
255
256/// Delete copies (about 230 MB each) whose source CLI was updated or
257/// removed. Copies of CLIs still installed stay, so programs using other
258/// CLI installs or SDK versions keep theirs. A session still running a
259/// deleted copy keeps working: unix unlinks open files lazily.
260async fn prune_stale_builds(current: &Path) {
261    let Some(root) = current.parent() else { return };
262    let Ok(mut entries) = tokio::fs::read_dir(root).await else { return };
263    while let Ok(Some(entry)) = entries.next_entry().await {
264        let path = entry.path();
265        if path != current && is_stale_build(&path).await && tokio::fs::remove_dir_all(&path).await.is_ok() {
266            tracing::debug!(path = %path.display(), "removed stale Code Mode CLI");
267        }
268    }
269}
270
271async fn is_stale_build(dir: &Path) -> bool {
272    match tokio::fs::read(dir.join(SOURCE_FILE)).await {
273        Ok(bytes) => {
274            let source = PathBuf::from(String::from_utf8_lossy(&bytes).into_owned());
275            let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
276            match source_key(&source).await {
277                Ok(key) => !name.starts_with(&format!("{key}-")),
278                Err(_) => true,
279            }
280        }
281        // No source file: a build being set up right now (no `claude` yet)
282        // is kept; a finished one without it predates source tracking.
283        Err(_) => tokio::fs::try_exists(dir.join("claude")).await.unwrap_or(false),
284    }
285}
286
287/// `binary` as given if it has a directory part, else the first match on `PATH`.
288fn resolve(binary: &Path) -> PathBuf {
289    if binary.components().count() > 1 {
290        return binary.to_path_buf();
291    }
292    std::env::var_os("PATH")
293        .into_iter()
294        .flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
295        .map(|dir| dir.join(binary))
296        .find(|candidate| candidate.is_file())
297        .unwrap_or_else(|| binary.to_path_buf())
298}
299
300/// Best-effort delete of a temporary file; a failure only leaves litter.
301async fn remove_leftover(path: &Path) {
302    if let Err(e) = tokio::fs::remove_file(path).await
303        && e.kind() != std::io::ErrorKind::NotFound
304    {
305        tracing::warn!(path = %path.display(), error = %e, "could not remove temporary Code Mode file");
306    }
307}
308
309fn cache_dir() -> PathBuf {
310    let base = std::env::var_os("XDG_CACHE_HOME")
311        .map(PathBuf::from)
312        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
313        .unwrap_or_else(std::env::temp_dir);
314    base.join("claude-code-agent").join("code-mode")
315}
316
317/// macOS kills a modified binary unless it is re-signed; the stock
318/// entitlements (JIT, unsigned executable memory) must carry over.
319#[cfg(target_os = "macos")]
320async fn sign(patched: &Path, source: &Path) -> Result<(), CodeModeError> {
321    let ents = codesign(|c| c.args(["-d", "--entitlements", "-", "--xml"]).arg(source)).await?;
322    if !ents.status.success() || !ents.stdout.starts_with(b"<?xml") {
323        return Err(CodeModeError::Sign(format!(
324            "could not read entitlements of {}: {}",
325            source.display(),
326            String::from_utf8_lossy(&ents.stderr).trim()
327        )));
328    }
329    let plist = patched.with_extension("entitlements.plist");
330    tokio::fs::write(&plist, &ents.stdout).await?;
331    let out = codesign(|c| {
332        c.args(["--force", "--sign", "-", "--timestamp=none", "--entitlements"]).arg(&plist).arg(patched)
333    })
334    .await;
335    remove_leftover(&plist).await;
336    let out = out?;
337    if out.status.success() {
338        Ok(())
339    } else {
340        Err(CodeModeError::Sign(String::from_utf8_lossy(&out.stderr).trim().to_string()))
341    }
342}
343
344/// Run `codesign` with the arguments `args` adds, killed after [`CODESIGN_TIMEOUT`]
345/// (the caller holds the build lock).
346#[cfg(target_os = "macos")]
347async fn codesign(
348    args: impl FnOnce(&mut tokio::process::Command) -> &mut tokio::process::Command,
349) -> Result<std::process::Output, CodeModeError> {
350    let mut cmd = tokio::process::Command::new("codesign");
351    args(&mut cmd).kill_on_drop(true);
352    tokio::time::timeout(CODESIGN_TIMEOUT, cmd.output()).await.map_err(|_| {
353        std::io::Error::new(std::io::ErrorKind::TimedOut, format!("codesign timed out after {CODESIGN_TIMEOUT:?}"))
354    })?
355    .map_err(CodeModeError::from)
356}
357
358#[cfg(not(target_os = "macos"))]
359async fn sign(_patched: &Path, _source: &Path) -> Result<(), CodeModeError> {
360    Ok(())
361}