Deep Dive · Agent Harnesses

Code Mode: When the Model Writes the Loop Instead of Calling the Tools

One tool instead of forty: the model writes a short piece of JavaScript that calls the tools, filters the results and returns only what it needs to read. Claude Code has it behind an environment variable, and it is the first harness change in a while that touches the shape of the loop rather than its parameters.

Code Mode in Claude Code — video thumbnail
Video: Ray Amjad 14:54 16 November 2026
Code Mode Claude Code MCP RLM

🔧 What changed 0:00

Anthropic added an experimental feature to Claude Code that replaces per-tool calls with code: Claude writes a short JavaScript program, the harness runs it in your session, and tool calls become function calls inside that program. Same model, fewer round trips, less of the conversation spent on intermediate results.

Without Code ModeWith Code Mode
Model asks for Read, waits, reads result, decides next callModel writes one program that makes several calls and returns what matters
Every tool result lands in the context windowIntermediate results stay inside the program
Loop drives the sequenceCode drives the sequence
Disclosure: this video carries no sponsor — the author says he does not accept them — but it does promote his own courses, newsletter and products. No links of any kind are reproduced here; the analysis is of the feature, not the funnel.

The framing he gives it is the correct one: this is an example of the model swallowing the harness. Instead of the harness presenting a fixed menu of actions, the model gets a general-purpose action — writing code — that can express all of them.

🚰 The problem: context as middleman 0:57

Each tool call's output goes into the context window; the next call requires the model to read the whole conversation again. Chain six MCP servers and you are paying to re-read intermediate data that existed only to be passed along.

SymptomCause
Large context growth on multi-tool tasksEvery intermediate result is persisted in the transcript
Cost that survives cachingCached tokens are cheaper, not free — you still pay to carry data you no longer need
Round-trip latencyEach call is a full model turn
Poor results from noisy MCP serversA tool returns 10,000 rows and the model must read them to filter
The deeper point is architectural: a tool call is a message; code is a computation. Anything you can do inside the computation — loop, filter, dedupe, join, parallelise — does not need to become part of the conversation at all. That is the whole of Code Mode, and it explains both the savings and the failure modes.

📉 Cloudflare's two steps 2:13

The idea is not Anthropic's. Cloudflare argued it in a piece he rightly calls the populariser, then demonstrated it on their own API — and the demonstration is the clearest number in the whole topic.

MeasureNative MCPCode Mode
Cloudflare API surface2,500+ endpointsTwo tools: search and execute
Tool definitions in context1.17 million tokens, measured with tiktokenRoughly 1,000 tokens
Where the work runsModel decides call by callTypeScript in an isolated sandbox, no internet access beyond the MCP APIs
The first post is about the mechanism; the second is about the bill. Cloudflare describes the saving as 99.9% of input tokens for a large API — and the reason it works is that a single search plus execute pair is a constant-size interface regardless of how many endpoints exist behind it.

His retelling rounds 2,500+ to "2,600" and 1.17 million to "1.1 million", which is close enough in spirit and worth stating exactly.

🌐 Server side, client side, gateway 3:20

FlavourSpansExample
Server-side code modeOne vendor's own toolsCloudflare's own MCP server; each vendor decides for itself
Gateway code modeMany servers, one proxyAn MCP gateway that exposes search and execute across everything you connect
Client-side code modeThe whole harnessClaude Code's version: all tools, including built-ins and sub-agents

He demonstrates the gateway middle ground with a self-hosted instance carrying a few dozen MCP servers, where you can also bundle connections so different team members get different tool sets — a genuinely useful pattern for teams, and the point at which "which tools does this agent have" stops being a per-machine question.

The progression is the interesting part: server side removes one vendor's duplication, the gateway removes duplication across vendors but adds a dependency, and client-side code mode removes it for everything at once — including the harness's own tools. Only the last one changes what the model can do inside a single computation.

🧰 Claude Code's version 5:25

The harness exposes essentially one tool that runs code — the REPL tool, which he pronounces as "ripple": read, evaluate, print, loop. Inside it, the old tools are functions.

Formerly a toolNow a function in the REPL
Bash / shellA tagged-template function for running commands
Read, Edit, WriteFunctions taking paths and content
WebFetchA function
MCP tool callsFunctions, so several servers can be combined in one program
Sub-agentsNot yet exposed programmatically — see the unreleased section

In the transcript you see the tool calls, not the code: pressing Ctrl+O opens the transcript viewer where each program appears as a collapsed code row. He also demonstrates the polling companion tool, which checks on a long-running program that has detached into the background.

Read the docs' example to see why this is not just batching. One program can search for a pattern, take the first hit, edit it, run the tests, and return only the file path and the test output. Four tool calls have collapsed into one turn, and the intermediate search results never entered the conversation — that is a different shape of interaction, not a faster version of the same one.

🔁 Why a persistent REPL differs 6:57

Server-side code mode runs one program and returns a result. Claude Code's REPL stays open for the session, so state accumulates.

BehaviourConsequence
Variables persist between programsStore a huge result once, inspect a slice, then process it further without re-reading it
Loops and parallelism inside one callHundreds of files or calls handled in one step
Filtering before returningA chatty MCP server becomes tolerable: assign to a variable, preview a little, keep going
State you cannot seeThe conversation no longer contains the data the model is reasoning over
The last row is the cost nobody advertises. When intermediate results live in variables instead of the transcript, your ability to audit what the model actually looked at moves into the REPL state and the code rows. This is the same trade as any abstraction — and it is why the docs tell you to inspect the code with Ctrl+O rather than trusting the summary.

He answers the obvious objection — could Claude not just write a shell script? — correctly: a script lacks access to the harness's own tools. The REPL is privileged in a way a script is not, which is exactly why its permission model matters.

🚧 Setup, and the limits the docs list 5:46

ItemDocumented value
EnableCLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude, or an env block in your settings
Versionv2.1.323 or later, any release channel
StatusExperimental and off by default; may change or be removed in any release
AccountA Claude subscription or Console account — not available on every surface
LimitDetail
ResumingOnly in the terminal, with Code Mode on
Waiting codeStops after ten minutes, including time spent at permission prompts
Background codeUp to two hours, and requires auto or bypass-permissions mode to start
Session portabilityCannot move to the desktop app or become a background session; /fork cannot start a background copy
Unavailable with itRemote Control, Claude in Chrome, computer use
Agent teamsCannot be used together with the agent-teams feature today
Permissions still apply, per tool call. Every call the code makes goes through your deny and ask rules and your PreToolUse hooks, and to inspect the code itself you hook the REPL tool and read the JavaScript from its input. The exception worth knowing: in auto mode the classifier reviews the code as a whole rather than each call — a wider unit of review, which is a weaker guarantee per action.
One documented caveat that matters more than it looks: Bash permission rules match command text, so a denied command can be expressed in a form the rule does not match — with or without Code Mode. If your safety depends on string-matching shell commands, generated code is exactly the mechanism that will find the gap.

📏 His measurement 8:38

He ran his own comparison on real issues in real open-source projects, with and without code mode, after noticing the feature appear in the binary about eleven days earlier.

MeasureResult
Input tokensAbout half
Total cost71% of normal mode, so roughly a 30% saving
Task successNot reported in the same terms — the comparison is on cost, not correctness
Treat this as a direction, not a benchmark: no task list, no scoring, no run count, no note on whether success rates matched. A 30% saving that comes with a silent drop in quality is not a saving — and the honest way to read his number is "worth measuring on your own workload", which is what he effectively says.

🧪 Browser Use and Prime Agent 8:58

ProjectClaimStatus
Browser Use 1.0Deleted about 90% of its old library; the agent now writes Python against the raw Chrome DevTools Protocol — up to 50% better, two to five times cheaper, fasterVendor announcement, not independently measured here
Prime AgentA Python REPL as the single tool; file ops, shell, sub-agents and context management all through codeConfirmed — PrimeIntellect-ai/prime-agent, 22.7k stars, Rust, self-described as a "self-improving RLM agent"
Terminal-Bench comparisonClaude Code 65% versus 71% with a single Python REPL, at slightly lower cost per taskA third-party post shown on screen; not in the repo README or the vendor's RLM write-up
The convergence is the signal, not any single number: a browser agent, a coding agent and a training lab have independently landed on "one tool that runs code" as the right harness shape. When three teams with different problems choose the same abstraction, the abstraction is probably load-bearing.

The report that Prime Agent's performance figures come from a screenshot rather than a published evaluation is a caution about all three: these are vendor-and-enthusiast numbers, gathered while the technique is new, and the technique changes the harness, the prompt and the cost curve simultaneously.

💡 The mismanaged geniuses 9:33

The article he recommends is real, and its thesis is a good frame for everything above.

"AI models are already good enough for the next leap in capabilities. The mismanaged geniuses hypothesis says frontier language models are severely underutilized, because each individual call is used poorly."
DetailValue
TitleThe Mismanaged Geniuses Hypothesis
AuthorsAlex L. Zhang, Zhening Li and Omar Khattab — the video credits only Zhang
Published9 April 2026
If the hypothesis is right, then most of the remaining gains are in the harness, not the weights — which is exactly what Code Mode looks like from the outside: the same model, used less wastefully. It also predicts where the gains stop: a badly managed model can be mismanaged in a new way in any new harness.

🧬 Three properties of an RLM 18:43

The interesting speculation in the video is that Claude Code is drifting toward a recursive language model — a model that manages its own context as data. Three properties are required:

PropertyPresent in Claude Code?
A REPL that persists between callsYes — variables defined in one program survive into the next
Sub-agents launched and managed from inside the REPLNot yet — three context tools appeared in the binary but are unreleased
The prompt itself living in a variableNo — a large pasted prompt still lands in the context window
Two of three is a fair reading of the trajectory, and the docs support the direction: the REPL is persistent, the permission model is per call, and the feature is explicitly experimental. But the third property is the one that changes the economics of long inputs, and it is nowhere in the shipped docs.

🧩 The missing third 19:42

What "prompt as a variable" would actually mean: a two-million-token prompt handed to the model as a reference, with the model writing code to slice it, summarise parts, hand sections to sub-agents, and read only what it needs.

TodayWith prompt-as-variable
A giant prompt fills the window and triggers compactionThe prompt is data; the model reads what it chooses
Compaction decides what to dropThe model decides what to drop, explicitly
Conversation history is append-onlyHistory becomes mutable state
His prediction — "maybe in 2027" — is honest about the obstacle, and the obstacle is billing. Every time the model edits its own context, the prompt prefix changes, and the cache that makes long conversations affordable is invalidated. That is not a research problem; it is an accounting one, and it explains why the API-level feature exists as a coarse tool (clear tool results, clear thinking) rather than a general one.

💳 The cache problem 22:10

He flags this correctly and points at the right place. Anthropic's context-editing documentation is explicit about the trade.

Documented behaviourConsequence
Clearing tool results invalidates cached prompt prefixesYou pay cache-write costs each time content is cleared
clear_at_least sets a minimum number of tokens per clearingThe feature refuses to clear a trickle that would not justify breaking the cache
Keeping thinking blocks preserves the cache; clearing them invalidates at that pointA per-workload choice between cache hits and window space
That single parameter is the whole tension in miniature: context management is now an optimisation problem where the objective is cost, not capability. Which is why Code Mode's value is that it avoids creating the tokens in the first place — it is cheaper than any strategy for removing them later.

🔮 What is not shipped 10:10

ClaimStatus
Three functions — spawn, list and release context — appeared in the binary alongside Code ModeHis strings-inspection; not in the documentation
They would let code fork the main conversation, explore branches, and return only the best resultsSpeculation built on those strings
Spawned contexts could message the coordinator backSpeculation
Code Mode and agent teams cannot be enabled together todayDocumented — an explicit current incompatibility
The documented incompatibility is the relevant fact here. If Code Mode and agent teams cannot coexist today, then the "contexts" he found are plausibly the path by which the two converge — but that is inference from a build artefact, and features found in binaries are frequently never shipped. Worth noting, not worth planning around.

✅ Claims checked

ClaimVerdictEvidence
Claude Code has an experimental Code ModeCorrectDocumented as "Run tool calls from code with Code Mode"; off by default
Enabled with CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1CorrectDocumented, including the settings-file variant
Requires v2.1.323 or laterCorrectStated in the requirements section
Claude writes JavaScript that makes several tool calls in one stepCorrectDocs example edits a file and runs tests in one program
The tool that runs the code is a REPL, followed by pollingCorrectDocs name the tool REPL and reference a poll event for background code
Tool calls inside the code still respect permissionsCorrectEach call goes through deny/ask rules and PreToolUse hooks
Auto mode reviews the code rather than each callCorrect — and it is a weaker per-action checkDocumented limitation
Long-running code detaches and can be polledPartlyWaiting stops at ten minutes; background runs up to two hours but requires auto or bypass-permissions mode
Cloudflare reduced 2,600 tools to twoFigures slightly offTheir own post says 2,500+ endpoints, 1.17M tokens, to two tools and about 1,000 tokens
Code Mode used half the input tokens and 71% of the costHis own measurementNo task list, scoring or run count published
Browser Use deleted ~90% of its library and gained 2–5× cheaperVendor claimAnnouncement material, not independently reproduced here
Prime Agent is an RLM harness with a persistent Python REPLCorrectRepo README: REPL as the built-in tool, programmatic sub-agents, prompt-as-a-variable
65% → 71% on Terminal-Bench with a REPLUnverifiable hereShown from a third-party post; absent from the repo and the vendor's RLM write-up
The mismanaged geniuses hypothesis says models are underutilised, not incapableCorrectPublished 9 April 2026 by Zhang, Li and Khattab
An RLM needs a persistent REPL, sub-agents from code, and prompt-as-variableConsistent with the framingTwo present in Claude Code, third absent
Context editing breaks the prompt cacheCorrect, and documentedTool-result clearing invalidates cached prefixes; clear_at_least exists to make it worthwhile
The Meta "context language models" paper on prefix/suffix cachingUnverifiedCould not confirm the paper as described; the cache trade-off itself is documented by Anthropic

Basis note. Built from the full 14:54 recording and checked against the Claude Code Code Mode documentation, Cloudflare's two code-mode posts, the Prime Agent repository and the mismanaged-geniuses post. Two corrections of substance: the tool is a documented REPL with a ten-minute/two-hour distinction he compresses, and Cloudflare's figures are 2,500+ endpoints and 1.17M tokens. His own cost measurement is reported as his, with its missing method stated.

🔑 Key takeaways

  • A tool call is a message; code is a computation. Everything done inside the computation — loops, filters, joins, parallelism — never enters the conversation.
  • The interface becomes constant-size: Cloudflare went from 2,500+ endpoints and 1.17M tokens to two tools and about 1,000 tokens.
  • Three flavours, increasing scope: one vendor's server, a gateway across vendors, then the whole harness. Claude Code ships the third.
  • Everything is behind one tool: bash, read, edit, fetch and MCP calls become functions inside the REPL.
  • Persistence is the difference from server-side code mode: variables survive between programs, so a huge result can be stored once and sliced.
  • That persistence has an audit cost: data the model reasons over may no longer be in the transcript. Read the code rows with Ctrl+O.
  • Permissions survive: each call inside the code goes through your deny/ask rules and hooks — but auto mode reviews the code as a unit, not each call.
  • Bash rules match text, so a denied command can be expressed in a form the rule misses. Generated code is the mechanism that finds that gap.
  • Long code is bounded: ten minutes when waiting, two hours in background, and background requires auto or bypass-permissions mode.
  • Code Mode and agent teams do not run together today — the likely reason the unreleased context functions matter.
  • It is experimental, off by default, and restricted: no Remote Control, no Claude in Chrome, no computer use, no portable sessions.
  • The RLM framing is two-thirds true: persistent REPL yes, sub-agents from code not yet, prompt-as-variable no.
  • The missing third is blocked by billing, not science: editing your own context invalidates the prompt cache, which is why context editing stays coarse.
  • Prevention beats curation: not creating the tokens is cheaper than any strategy for clearing them later.

🔗 Resources

Basis note. The documentation supplied the corrections that matter most: the REPL tool name, the ten-minute/two-hour distinction, the per-call permission model, the agent-teams incompatibility, and the fact that Code Mode is off by default and experimental. Third-party performance figures are labelled as such rather than repeated as measurements.

⏱ Timestamp index

0:00The harness change, and the trend behind it
0:57Why tool-heavy agents waste context
2:13Cloudflare's argument
2:502,500+ endpoints to two tools
3:20Server-side versus client-side code mode
4:22The gateway middle ground
5:25What Anthropic did differently
5:46Turning it on
6:17The two tools Claude then has
6:57What the REPL is, and variable persistence
8:10Why not just write a script
8:24Polling detached code
8:38His own cost measurement
8:58Browser Use deleted 90% of its library
9:20Prime Agent and the Terminal-Bench claim
9:33Mismanaged geniuses
10:10Three unreleased context functions
17:10Forking the conversation to explore options
18:43Recursive language models
19:42Prompt as a variable
22:10The cache problem and context editing
22:40Maybe in 2027
☰ View all