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#[derive(Debug, thiserror::Error)]
39pub enum CodeModeError {
40    #[error("not a Bun standalone binary: {0}")]
41    NotBunBinary(&'static str),
42    #[error("Code Mode module not found in the CLI binary")]
43    ModuleNotFound,
44    #[error("patch anchor `{0}` found {1} times (expected 1); this CLI version is not supported")]
45    Anchor(&'static str, usize),
46    #[error("io: {0}")]
47    Io(#[from] std::io::Error),
48    #[error("re-signing the patched CLI failed: {0}")]
49    Sign(String),
50    #[error("`settings` must be a JSON object (with an object `env`) to add the Code Mode env var")]
51    Settings,
52    #[error("Code Mode is supported on macOS and Linux only")]
53    UnsupportedPlatform,
54}
55
56// ─── Functional core ─────────────────────────────────────────────────────────
57
58/// Return `binary` with Code Mode forced on.
59pub fn patch(binary: &[u8]) -> Result<Vec<u8>, CodeModeError> {
60    let mut out = binary.to_vec();
61    let (entry, contents) = find_module(&out)?;
62
63    let module = &out[contents.clone()];
64    let gate_var = Regex::new(r#"var ([\w$]+)="tengu_rustling_blossom""#)
65        .ok()
66        .and_then(|re| re.captures(module))
67        .and_then(|c| c.get(1))
68        .map(|m| regex::escape(&String::from_utf8_lossy(m.as_bytes())))
69        .ok_or(CodeModeError::Anchor("gate variable", 0))?;
70
71    let edits: [(&'static str, String, &[u8]); 3] = [
72        ("eligibility", r#"(?:\{)(if\(![\w$]+\(\)\)return"runtime";)"#.into(), b"return;"),
73        (
74            "caveats",
75            r"([\w$]+\.codeModeCaveatsAcceptedV1===!0&&[\w$]+\.codeModeAutoModeCaveatAcceptedV1===!0)".into(),
76            b"!0",
77        ),
78        ("gate", format!(r"(return [\w$]+\({gate_var},!0\)!==!0)"), b"return!1"),
79    ];
80    for (name, pattern, replacement) in edits {
81        let span = unique_match(&out[contents.clone()], name, &pattern)?;
82        if span.len() < replacement.len() {
83            return Err(CodeModeError::Anchor(name, 1));
84        }
85        let start = contents.start + span.start;
86        overwrite_padded(&mut out[start..start + span.len()], replacement);
87    }
88
89    // Without bytecode Bun compiles the (patched) source of this module.
90    out.get_mut(entry + BYTECODE_PTR..entry + BYTECODE_PTR + 8)
91        .ok_or(CodeModeError::NotBunBinary("module table"))?
92        .fill(0);
93    Ok(out)
94}
95
96/// (entry offset, contents range) of the Code Mode opt-in module.
97fn find_module(data: &[u8]) -> Result<(usize, std::ops::Range<usize>), CodeModeError> {
98    let trailer = rfind(data, TRAILER).ok_or(CodeModeError::NotBunBinary("no trailer"))?;
99    let offsets = trailer.checked_sub(OFFSETS_SIZE).ok_or(CodeModeError::NotBunBinary("short file"))?;
100    let byte_count = usize::try_from(read_u64(data, offsets)?).map_err(|_| CodeModeError::NotBunBinary("size"))?;
101    let modules_off = read_u32(data, offsets + 8)?;
102    let modules_len = read_u32(data, offsets + 12)?;
103    let base = offsets.checked_sub(byte_count).ok_or(CodeModeError::NotBunBinary("graph size"))?;
104
105    for i in 0..modules_len / ENTRY_SIZE {
106        let entry = base + modules_off + i * ENTRY_SIZE;
107        let start = base + read_u32(data, entry + 8)?;
108        let end = start + read_u32(data, entry + 12)?;
109        let contents = data.get(start..end).ok_or(CodeModeError::NotBunBinary("module bounds"))?;
110        if contents.windows(MODULE_MARKER.len()).any(|w| w == MODULE_MARKER) {
111            return Ok((entry, start..end));
112        }
113    }
114    Err(CodeModeError::ModuleNotFound)
115}
116
117/// Range (within `haystack`) of capture group 1 of the only match.
118fn unique_match(haystack: &[u8], name: &'static str, pattern: &str) -> Result<std::ops::Range<usize>, CodeModeError> {
119    let re = Regex::new(pattern).map_err(|_| CodeModeError::Anchor(name, 0))?;
120    let found: Vec<_> = re.captures_iter(haystack).filter_map(|c| c.get(1)).map(|m| m.range()).collect();
121    match found.as_slice() {
122        [one] => Ok(one.clone()),
123        _ => Err(CodeModeError::Anchor(name, found.len())),
124    }
125}
126
127/// Write `with` into `slot`, padding with spaces (valid JS whitespace).
128fn overwrite_padded(slot: &mut [u8], with: &[u8]) {
129    slot.fill(b' ');
130    for (dst, src) in slot.iter_mut().zip(with) {
131        *dst = *src;
132    }
133}
134
135fn rfind(data: &[u8], needle: &[u8]) -> Option<usize> {
136    data.windows(needle.len()).rposition(|w| w == needle)
137}
138
139fn read_u32(data: &[u8], at: usize) -> Result<usize, CodeModeError> {
140    let bytes = data.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok());
141    bytes.map(|b| u32::from_le_bytes(b) as usize).ok_or(CodeModeError::NotBunBinary("truncated"))
142}
143
144fn read_u64(data: &[u8], at: usize) -> Result<u64, CodeModeError> {
145    let bytes = data.get(at..at + 8).and_then(|b| <[u8; 8]>::try_from(b).ok());
146    bytes.map(u64::from_le_bytes).ok_or(CodeModeError::NotBunBinary("truncated"))
147}
148
149// ─── Imperative shell ────────────────────────────────────────────────────────
150
151/// Serializes builds: a pool warming N sessions builds the copy once.
152static BUILD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
153
154/// Path of a patched copy of `binary` (resolved through `PATH`), built on
155/// first use and cached under `<cache>/claude-code-agent/code-mode/`. The cache key
156/// is the installed binary's name, size and mtime plus this SDK's version,
157/// so a CLI update or a new patch builds a new copy.
158pub async fn patched_binary(binary: &Path) -> Result<PathBuf, CodeModeError> {
159    if cfg!(windows) {
160        return Err(CodeModeError::UnsupportedPlatform);
161    }
162    let source = tokio::fs::canonicalize(resolve(binary)).await?;
163    let key = source_key(&source).await?;
164    let target = cache_dir().join(format!("{key}-sdk{}", env!("CARGO_PKG_VERSION"))).join("claude");
165
166    let _guard = BUILD.lock().await;
167    if tokio::fs::try_exists(&target).await? {
168        return Ok(target);
169    }
170    let dir = target.parent().ok_or(CodeModeError::NotBunBinary("cache path"))?;
171    tokio::fs::create_dir_all(dir).await?;
172    // Read by prune_stale_builds in any process: the build is stale once
173    // this source changes or disappears.
174    tokio::fs::write(dir.join(SOURCE_FILE), source.to_string_lossy().as_bytes()).await?;
175
176    let original = tokio::fs::read(&source).await?;
177    let patched = tokio::task::spawn_blocking(move || patch(&original))
178        .await
179        .map_err(|e| CodeModeError::Io(std::io::Error::other(e)))??;
180    // Write to a name unique to this build, then rename: neither a crash nor
181    // another process building at the same time leaves a half copy.
182    let nanos = std::time::SystemTime::now()
183        .duration_since(std::time::UNIX_EPOCH)
184        .map(|d| d.subsec_nanos())
185        .unwrap_or_default();
186    let partial = dir.join(format!("claude.{}.{nanos}.partial", std::process::id()));
187    tokio::fs::write(&partial, patched).await?;
188    #[cfg(unix)]
189    {
190        use std::os::unix::fs::PermissionsExt;
191        tokio::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o755)).await?;
192    }
193    if let Err(e) = sign(&partial, &source).await {
194        let _ = tokio::fs::remove_file(&partial).await;
195        return Err(e);
196    }
197    tokio::fs::rename(&partial, &target).await?;
198    prune_stale_builds(dir).await;
199    tracing::info!(source = %source.display(), patched = %target.display(), "built Code Mode CLI");
200    Ok(target)
201}
202
203/// Name of the file in each build directory holding the source CLI's path.
204const SOURCE_FILE: &str = "source";
205
206/// `<name>-<size>-<mtime>` of the installed CLI.
207async fn source_key(source: &Path) -> std::io::Result<String> {
208    let meta = tokio::fs::metadata(source).await?;
209    let mtime = meta
210        .modified()?
211        .duration_since(std::time::UNIX_EPOCH)
212        .map(|d| d.as_secs())
213        .unwrap_or_default();
214    let name = source.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "claude".into());
215    Ok(format!("{name}-{}-{mtime}", meta.len()))
216}
217
218/// Delete copies (about 230 MB each) whose source CLI was updated or
219/// removed. Copies of CLIs still installed stay, so programs using other
220/// CLI installs or SDK versions keep theirs. A session still running a
221/// deleted copy keeps working: unix unlinks open files lazily.
222async fn prune_stale_builds(current: &Path) {
223    let Some(root) = current.parent() else { return };
224    let Ok(mut entries) = tokio::fs::read_dir(root).await else { return };
225    while let Ok(Some(entry)) = entries.next_entry().await {
226        let path = entry.path();
227        if path != current && is_stale_build(&path).await && tokio::fs::remove_dir_all(&path).await.is_ok() {
228            tracing::debug!(path = %path.display(), "removed stale Code Mode CLI");
229        }
230    }
231}
232
233async fn is_stale_build(dir: &Path) -> bool {
234    match tokio::fs::read(dir.join(SOURCE_FILE)).await {
235        Ok(bytes) => {
236            let source = PathBuf::from(String::from_utf8_lossy(&bytes).into_owned());
237            let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
238            match source_key(&source).await {
239                Ok(key) => !name.starts_with(&format!("{key}-")),
240                Err(_) => true,
241            }
242        }
243        // No source file: a build being set up right now (no `claude` yet)
244        // is kept; a finished one without it predates source tracking.
245        Err(_) => tokio::fs::try_exists(dir.join("claude")).await.unwrap_or(false),
246    }
247}
248
249/// `binary` as given if it has a directory part, else the first match on `PATH`.
250fn resolve(binary: &Path) -> PathBuf {
251    if binary.components().count() > 1 {
252        return binary.to_path_buf();
253    }
254    std::env::var_os("PATH")
255        .into_iter()
256        .flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
257        .map(|dir| dir.join(binary))
258        .find(|candidate| candidate.is_file())
259        .unwrap_or_else(|| binary.to_path_buf())
260}
261
262fn cache_dir() -> PathBuf {
263    let base = std::env::var_os("XDG_CACHE_HOME")
264        .map(PathBuf::from)
265        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
266        .unwrap_or_else(std::env::temp_dir);
267    base.join("claude-code-agent").join("code-mode")
268}
269
270/// macOS kills a modified binary unless it is re-signed; the stock
271/// entitlements (JIT, unsigned executable memory) must carry over.
272#[cfg(target_os = "macos")]
273async fn sign(patched: &Path, source: &Path) -> Result<(), CodeModeError> {
274    use tokio::process::Command;
275    let ents = Command::new("codesign").args(["-d", "--entitlements", "-", "--xml"]).arg(source).output().await?;
276    if !ents.status.success() || !ents.stdout.starts_with(b"<?xml") {
277        return Err(CodeModeError::Sign(format!(
278            "could not read entitlements of {}: {}",
279            source.display(),
280            String::from_utf8_lossy(&ents.stderr).trim()
281        )));
282    }
283    let plist = patched.with_extension("entitlements.plist");
284    tokio::fs::write(&plist, &ents.stdout).await?;
285    let out = Command::new("codesign")
286        .args(["--force", "--sign", "-", "--timestamp=none", "--entitlements"])
287        .arg(&plist)
288        .arg(patched)
289        .output()
290        .await?;
291    let _ = tokio::fs::remove_file(&plist).await;
292    if out.status.success() {
293        Ok(())
294    } else {
295        Err(CodeModeError::Sign(String::from_utf8_lossy(&out.stderr).trim().to_string()))
296    }
297}
298
299#[cfg(not(target_os = "macos"))]
300async fn sign(_patched: &Path, _source: &Path) -> Result<(), CodeModeError> {
301    Ok(())
302}