DEV Community

Cover image for How Claude Code's Code Mode works
Arindam Majumder
Arindam Majumder Subscriber

Posted on Edited on Originally published at arindamm.dev

How Claude Code's Code Mode works

Normally, Claude Code works one tool call at a time. Claude asks for a search and reads the result. Then it asks for an edit and reads the diff. Then it asks for the tests and reads the output. Each step is a trip back to the model, and on each trip Claude reads the whole conversation again before it picks the next step.

Same three steps, two ways

Code Mode changes that. Claude writes a short JavaScript program that makes the tool calls itself, and Claude Code runs it. One trip can search, edit and test. The feature is experimental, off by default, and needs Claude Code v2.1.323 or later.

I wanted to see what actually happens under the hood, so I did two things. I read the Code Mode docs. Then I ran the same task twice on Claude Code 2.1.330, once with Code Mode off and once with it on, and took both session logs apart. Here's how it works, and what changed in a real run.

The short version

  • In Code Mode, Claude gets one tool, REPL. Bash, Read, Edit, Grep, WebFetch and MCP tools become JavaScript functions that Claude calls from inside a script.
  • The script runs inside Claude Code, in one JavaScript context that keeps its variables between calls. Only the script's last expression goes back to Claude.
  • Every tool call inside a script still goes through your permission rules and hooks, under the tool's usual name. The chat still shows each call and each diff.
  • In my run, requests to Claude went from 5 to 4. Code Mode made 18 tool calls from 3 scripts, each request was about 35k tokens instead of 53k, there were no permission prompts, and the cost was about the same. The biggest change wasn't speed. It was how Claude batched the work.

The normal loop: one trip per tool call

Without Code Mode, Claude asks for a tool call and Claude Code runs it. Claude Code then adds the result to the conversation and sends the whole conversation back to the model. Claude reads it all and decides what to do next. Prompt caching makes the re-reading cheaper, but every step is still a full request.

Claude Code can already cut some of those trips. It can ask for several independent tool calls in one turn, and it can fold steps into one shell command. But it can't do logic between steps without a trip. "Take the first file this search finds and edit it" needs Claude to see the search result first.

Code Mode: Claude writes the glue as code

This is the example from the docs:

const files = await $`rg -l "function retryPolicy" src`.text();
const target = files.trim().split("\n")[0];
await edit(target, "maxAttempts: 3", "maxAttempts: 5");
({ edited: target, tests: $`npm test -- retryPolicy`.nothrow() });
Enter fullscreen mode Exit fullscreen mode

$ runs a shell search. Plain JavaScript picks the first file. edit() changes one line, and $ runs the tests. The last line is an object, and that object is what Claude gets back. That's three tool calls and one trip.

Claude gets one tool: REPL

Claude gets one tool: REPL

The session logs show what each run's first model request contained. With Code Mode off, the request listed 13 tools. With Code Mode on, it listed 2: REPL, and advisor, which was in both runs. The REPL tool's description opens with:

Your one tool is REPL; there are no other tools.

The rest of the toolbox comes as TypeScript declarations for the script's globals:

Global What it does
$`cmd` Runs a shell command. .text(), .lines() and .json() read the output. .nothrow() returns a failure instead of throwing
file(path).text() Reads a file
edit(path, old, new) Exact-string edit. Throws if old matches zero times or more than once
write(path, content) Writes a whole file
Read({...}), Grep({...}), tools.X(...) Calls any tool by its usual name and input
searchTools(q), describeTool(name) Finds MCP and other tools, and gets their input schemas
preview(out), log(...) Keeps long output out of Claude's context

The same description sets the rules of the game. These come from Claude Code 2.1.330's own tool description, not from a documented API, so expect them to change while Code Mode is experimental:

  • One persistent context. Variables live from one REPL call to the next, but not across a restart, resume or fork.
  • Sealed. Scripts have no import, require or process, and they're always JavaScript, whatever language the repo uses. Tools like pytest or cargo run through $.
  • An explicit cost model. The description tells Claude that each REPL call is a full model round trip, while the work inside a script is "comparatively free" and runs concurrently with Promise.all. So Claude should gather what a decision needs in one script, and come back only when the next step depends on what it found.
  • Output limits. A script returns its last expression plus anything it log()s. Each part is cut to about 30,000 characters, keeping the head and tail.

One side effect shows up in every request. In my logs, the request's system prompt plus tool definitions was 36 KB in Code Mode and 78 KB without it. Each Code Mode request was about 35k tokens instead of about 53k.

Anatomy of a real script

Anatomy of one real script

This is the third of the three scripts Claude wrote in my run, as it appears in the session log. A few things stand out:

  • The loop is plain JavaScript. Eight edit() calls run one after another, and Claude isn't consulted between them.
  • The edit anchor spans two lines (export const retryPolicy = { plus maxAttempts: 3,). auth.js also has a loginLockout setting with maxAttempts: 3, and the two-line anchor can't match it. edit() throws on zero or several matches, so a sloppy anchor fails loudly instead of editing the wrong line.
  • Promise.all runs three checks at once: git diff, rg and npm test.
  • .nothrow() means a failing test suite comes back as data Claude can read, not as an exception.
  • The last line decides what Claude sees. It's a small object holding the edit results, the diff stat, the grep and the test log.

The two earlier scripts did the groundwork. Script 1 ran ls, rg and cat package.json in parallel. Script 2 read auth.js, one sample service and the test file. Claude read the results of each script before writing the next one. That's where its judgment came in: it spotted the security-reviewed lockout before touching anything.

Where each call goes

Where each call in a script goes

A script is new, but the checks on each tool call aren't:

  • Rules and hooks still apply per call. Each tool call inside a script goes through your deny and ask rules and your PreToolUse hooks, under its usual name (Bash, Edit, or an MCP tool's name). In manual and accept-edits mode, you're prompted for any call that would normally prompt.
  • The chat looks the same. The log records each call as its own entry, so each one gets its own row in the chat, edits included with their diffs. The script itself sits behind Ctrl+O, in a collapsed row. This one is from my run:
  ⏺ Code(Survey services and maxAttempts usages) · 6 lines (click to show)
Enter fullscreen mode Exit fullscreen mode
  • Auto mode reviews the script, not the calls. The opt-in screen says it plainly: "In auto mode, the safety check reads each piece of JavaScript once, before it runs. It doesn't check each tool call that the code then makes, so it can't see values that the code works out as it runs." A path taken from search output is one example. Keep rules or hooks for the calls you must control.
  • The sandbox covers shell commands only. The JavaScript itself, and its file, web and MCP calls, run outside it. If you need those isolated too, the docs suggest a container or VM.
  • Saying no stops the script. Answering No (or pressing Esc) at a prompt stops the code. Changes from calls that already finished stay in place. Answering No with a comment refuses only that call, and the script can carry on.

If you want to see every script before it runs, add an ask rule for REPL to ~/.claude/settings.json. The prompt doesn't include the code, so press Ctrl+O to read it first:

{ "permissions": { "ask": ["REPL"] } }
Enter fullscreen mode Exit fullscreen mode

Hooks can also check whole scripts. A PreToolUse hook that matches REPL gets the script in tool_input.code. A PostToolUse hook gets code, result, stdout, stderr and toolsUsed, and can hand Claude a redacted copy through updatedToolOutput.

One real run

To see the difference for myself, I built a tiny repo. It has eight services, each with retryPolicy: { maxAttempts: 3, ... }. One trap: auth.js also has a loginLockout.maxAttempts: 3, with a comment saying it's security-reviewed and must not change. There are nine tests, and eight of them fail at the start.

Both sessions got the same prompt:

Every service in src/services has a retryPolicy with maxAttempts: 3. Raise those to 5. Leave every other maxAttempts alone. Then run npm test and tell me the result.

Both ran Opus 5.5 at the same effort, in accept-edits mode with a small Bash allowlist. They were interactive terminal sessions, recorded with asciinema.

Both runs, as they happened

Both runs got it right. All 9 tests passed, and the lockout stayed at 3.

  • Code Mode off: 5 requests. The first Bash command failed (zsh couldn't match test*). Claude retried, then read two files in one turn. It then did all the edits and checks as one shell command: a sed loop over the eight files. Claude Code couldn't check that command in advance ("A variable in this command can't be checked before it runs"), so it asked me. Of the 54 seconds, 36 were me reading that prompt.
  • Code Mode on: 4 requests, 3 scripts, 18 tool calls, no prompts, done in 16 seconds.

What changed, in numbers

What I take from it:

  1. The request count barely moved. Claude Code already batches: it ran parallel reads, and it folded every edit into one shell command. The docs pitch Code Mode for bigger jobs (changes across many files, searches that need filtering, independent commands), and my 9-file task is too small to show a big gap. Don't expect a dramatic speed-up on small tasks.
  2. The real difference was how Claude batched. Without Code Mode, batching meant a shell one-liner. sed edits skip the Edit tool, so the chat shows no diffs, Claude Code's file history has no checkpoints, and the permission system can't check the command. With Code Mode, the loop calls edit(), so each change is a real Edit. That gave 8 diffs and 8 checkpoints, with no prompt in accept-edits mode.
  3. Smaller prompts, same bill (this time). Tokens read across all requests nearly halved (264k to 140k), but most of those were cheap cache reads. Claude Code's own estimate put the runs at $0.34 vs $0.35, because the first Code Mode request wrote 33k tokens to a cold cache. Over a longer session I'd expect the per-request saving to outweigh that one-time write, but one short run doesn't show it.
  4. Scripts are only as lean as what they return. The Code Mode run actually read more tool output (7.9k vs 6.0k characters), because script 3 returned the whole npm test log. preview() exists for exactly this.

Turning it on

You need Claude Code v2.1.323 or later (claude --version). Then set one environment variable:

CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude
Enter fullscreen mode Exit fullscreen mode

To keep it on, put the variable in your user settings (~/.claude/settings.json). Claude Code ignores it in a project's settings files, so a repo you clone can't turn Code Mode on for you:

{ "env": { "CLAUDE_CODE_EXPERIMENTAL_CODE_MODE": "1" } }
Enter fullscreen mode Exit fullscreen mode

Before the first session, Claude Code shows an opt-in screen. It warns that Code Mode is an early experiment, that Remote Control, Claude in Chrome and computer use are off, and that a Code Mode session can be resumed only with Code Mode on. Pick Yes, turn on Code Mode, and the session starts with:

⚠ Code Mode (experimental) is on · this session can be resumed only with Code Mode on
Enter fullscreen mode Exit fullscreen mode

It won't start unless all of these are true:

  • You use a Claude subscription or a Console account, talking to the Anthropic API directly. Amazon Bedrock, Google Cloud, Microsoft Foundry and gateways are out, and so is a custom ANTHROPIC_BASE_URL.
  • You're on Opus 5.5, Sonnet 5.5, Haiku 5.5 or Fable 5.2.
  • You're in an interactive claude session in a terminal, on the native build. The VS Code panel, the Desktop app and cloud sessions don't support it.
  • You have no API key helper, no OpenTelemetry export and no DISABLE_TELEMETRY. Your organization isn't on HIPAA or zero data retention.

If Code Mode can't start, the session says Code Mode (experimental) isn't available and gives the reason, and /status shows it too. To turn Code Mode off, remove the variable or set it to 0. A 0 anywhere wins. Admins can block it for a whole organization by setting 0 in managed settings.

Limits worth knowing

  • It's experimental. The docs say it may change or be removed in any release. Everything I quoted from the REPL tool's description comes from 2.1.330's session logs, not from a documented API.
  • Resuming. You can resume a Code Mode session only in the terminal, with Code Mode on. Sessions started without Code Mode resume without it.
  • Time limits. A script stops after 10 minutes while you wait on it, and time spent at permission prompts doesn't count. Background code can run for up to two hours if the session started in auto or bypass-permissions mode.
  • Turned off in Code Mode: Remote Control, Claude in Chrome and computer use. A Code Mode session also can't move to the Desktop app or become a background session, and /fork can't start a background copy.
  • Hooks that hang. If a PreToolUse hook doesn't finish (it times out, say), you'll see "tool calls refused".

When to reach for it

The docs list three good fits, and my run backs up the reasoning behind them:

  • The same change across many files. A loop over edit() keeps every change a real, reviewable Edit.
  • A search whose results need filtering before Claude reads them. Filter in JavaScript and return only what matters.
  • Several independent commands. Use Promise.all and pay for one trip.

For a one-file fix, Code Mode won't change much. Its value grows with the number of steps that don't need Claude's judgment in between.

How I measured

The demo repo has eight small services, each with a retryPolicy, plus one trap: a security-reviewed loginLockout with the same maxAttempts: 3. Both sessions were interactive Claude Code sessions in a terminal, recorded with asciinema. Every number above comes straight from Claude Code's own session logs: request times, tool calls, token usage, and its cost estimate. The figures are drawn with rough.js and Excalidraw's fonts.

Sources: Code Mode docs, the opt-in screen and the REPL tool description in Claude Code 2.1.330, and two session logs from 2026-11-21.

Top comments (0)