Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Claude Code's Code Mode: 37% Fewer Tokens, But Why Is It Slower?

An analysis of Claude Code's experimental Code Mode showing how four lines of JavaScript chain search, edit, and test operations, reducing token usage by 37% but increasing latency, with practical examples from Stripe retry configuration and benchmark comparisons.

Claude Code v2.1.323 introduced an experimental Code Mode that lets the model write a short JavaScript snippet to chain search, edit, and test steps instead of making multiple round-trips. The official example uses four lines:

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

Search Returns Three Files — Which One Gets Edited?

The second line picks the first file from the rg -l output via [0]. In regular mode, search results return to the model, which then decides which file to edit. With Code Mode, the decision is baked into the script before search runs. If the repository contains three retry policies (payments, messaging, background sync) all defaulting to 3, and the payment team's request happens to match the messaging file first, the script will edit the wrong file. The diff shows only a number change, but the payment service remains unfixed.

The author prefers returning all three paths to the model, each annotated with a call site. The model can then trace from the payment initiation code to identify the correct policy. If payment and background tasks share a policy, further inspection is needed to see if the retry limit can be scoped to a single request.

If no files match, rg exits with code 1 (no match) or 2 (error). Code 1 suggests trying a different pattern; code 2 warrants passing stderr to the model to diagnose unreadable paths.

"Retry Up to Five Times" — What Number Goes in the Code?

A concrete example uses Stripe's Node SDK ( [email protected]). The requirement: "create payment request, on 503 retry up to five times total." Stripe's SDK has maxNetworkRetries at client level and per-request level; per-request takes precedence. The SDK's own tests set one to 0 and the other to 1, then swap.

The author simulated a local mock returning 503 for every attempt. With client-level retries at 2 and per-request at 4, four independent "create payment" calls were made. Results:

Default (client 2, per-request unset): 3 attempts

Per-request set to 4: 5 attempts (initial + 4 retries)

Next request reverts to client default: 3 attempts

Per-request set to 5: 6 attempts

All retries within a single request carry the same idempotency key, allowing Stripe to recognize them as one operation.

Adding a Stripe-Should-Retry: false header caused the SDK to stop after one attempt, confirming that the per-request value is a ceiling, not a guarantee. A test that only asserts "five attempts on 503" would fail if the service correctly honors the header.

Thus, understanding the caller's intent and how the retry count is calculated is essential before the model can write a correct edit-and-test script.

Why JavaScript Instead of Pure Bash?

George (Claude Code team) originally designed a task requiring docstrings for 24 files; both modes completed it in four shell calls, so the task was dropped. Li Tou (OpenCode author) showed independent queries (GitHub stars, npm version, CI status) that can run in parallel with Promise.all. In the four-line script, test must wait for edit to finish, preserving sequential dependencies.

Search and test run via shell, but editing uses Claude Code's built-in Edit tool, which requires exact old-text matching. If the same maxAttempts: 3 appears twice in the chosen file, the edit fails unless surrounding context distinguishes them. If the wrong file is picked but happens to have only one match, the edit succeeds silently.

JavaScript's value is bridging these two tool types: the search result flows directly into edit, and the terminal still shows the diff. If a directory has an Edit deny rule, the script's computed path still passes permission checks and pre-execution hooks. In auto mode, the auto-reviewer sees the whole script upfront but cannot know the final value of target.

This mirrors earlier patterns: log-filtering scripts that narrow 50 results to a few anomalies for the model, or Lance Martin's example of filtering 50 search results in code before handing them over. In the terminal, a search may return only three filenames — if they represent payment, messaging, and background tasks, the author prefers giving all three to the model.

What Should the Script Return After Tests Finish?

The official example ends with .nothrow() so test failures still return output. But a test report may span dozens of screens. The author modified the payment experiment: instead of setting retries per-request, set client-level to 4 so both the target request and a subsequent ordinary request inherit it. Same SDK, same 503 responses. Two runs:

Retry Config Location   | Target Request Attempts | Next Ordinary Request Attempts
Per-request only (4)    | 5                       | 3
Client-level (4)        | 5                       | 5

If the script only returns "target request sent 5 times," both edits look identical. The deciding factor was seeing the ordinary request also jump to 5. Independent verification (a single assertion locking the ordinary request at 3) would catch this. The author wants the model to receive: edited path, two test case names, and their attempt counts. Repeated 503 bodies stay in the script for counting. Humans can review the diff via Ctrl+O and expand Code to see how results were filtered.

Teams collecting OpenTelemetry events can also inspect tool calls: Edit then Bash each leave records with tool_use_id prefixed repl_ or toolu_cc_. Code Mode and event collection require v2.1.329+ with experimental tracing disabled. Counting tool actions vs model turns yields different numbers.

37% Fewer Tokens, Yet Seconds Slower

George published two benchmarks on X using Sonnet 5.5, medium reasoning. He initially miscounted turns by including tool-call records with zero model usage. After correction, the small task showed 5 turns both with and without Code Mode (regular mode already batches shell commands).

The larger task: find and fix three seeded issues in a 1,662-file Python repo, then write a report. Averages over two runs:

Metric                     | Regular Mode | Code Mode
Model Turns                | 8            | 6.5
Max Input Tokens per Turn  | 60,921       | 48,276
Total Tokens (incl. cache) | 465,875      | 291,471
Wall-clock Time            | 27.9 s       | 32.2 s

The 37% reduction is in cumulative tokens including cache. Code Mode averaged 4.3 seconds slower. One run fixed all three issues but miscounted test files in the report. In the payment example, the script saves the model's round-trip to read filenames and invoke edit, but the 503 backoff wait still occurs. Only two runs per mode per task; real-world savings depend on where time is spent.

Another evaluation (Bicameral, cited by AI Frontline's "up to 77% reduction") used an MCP service serving 120 tickets; models had to find 7 unclosed tickets for a specific product and sum refunds. All 16 runs (4 models × 2 modes × 2 runs) succeeded. Code Mode cut cumulative tokens 62–77% because the model no longer rereads each ticket. But the service still streams all 120 tickets.

A follow-up question — "Which customers were double-charged?" — had 9 true positives and 15 near-matches. Script effectiveness depended on ticket wording; models exploited synthetic data patterns. Real customer descriptions are unpredictable, just as returning only the first of three filenames hides the other paths.

bestagent.dev tested Opus 5.5 adding parameters and tests to a CLI tool (3 runs each): regular mode 10–13 model requests, Code Mode 6–8, average time 80s → 60s. Adding a version line to 20 files took 13s both ways (regular mode wrote a batch script). George's small task reduced total tokens ~19% but increased cache writes, raising estimated cost ~21%. The most portable metrics are: how much raw output the model avoids reading, and end-to-end time from request to usable result.

Try It in Your Own Terminal

Code Mode is off by default. With a native Claude Code install, supported model, and direct connection via Claude subscription or Console account, enable it with: CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude First launch prompts confirmation. Third-party gateways currently don't support this path. Resuming the next day requires claude --resume in the same Code Mode-enabled terminal.

The author's test: use a familiar repo, ask "change 3 to 5," then press Ctrl+O to inspect the second line of the generated script. If the model already traced the payment entry point to the correct request, the rest runs cleanly. If it only has three filenames, the author would rather wait an extra turn to see which file the payment initiation code actually uses.

References

Anthropic, Claude Code v2.1.323 release notes (https://github.com/anthropics/claude-code/releases/tag/v2.1.323)

Anthropic, Run tool calls from code with Code Mode (https://code.claude.com/docs/en/code-mode)

Anthropic, Configure permissions (https://code.claude.com/docs/en/permissions)

Anthropic, Tools reference · Edit tool behavior (https://code.claude.com/docs/en/tools-reference#edit-tool-behavior)

Stripe, stripe-node v23.2.0 request sending implementation (https://github.com/stripe/stripe-node/blob/v23.2.0/src/RequestSender.ts)

Stripe, per-request vs client retry settings test (https://github.com/stripe/stripe-node/blob/v23.2.0/test/RequestSender.spec.ts)

Stripe, Webhook automatic retries (https://docs.stripe.com/webhooks#automatic-retries)

Lance Martin, Give Claude a computer (https://x.com/RLanceMartin/status/2027450018513490419)

George, I tested Claude Code's Code Mode. It is cheaper, not faster. (https://x.com/bolyki/status/2123068346224509366)

Bicameral, six-task evaluation and detailed results (https://github.com/Bicameral-AI/claude-code-mode-benchmark/blob/deee7585b5ff8bcefd3dcc61d8e5873bff5896c5/results/README.md)

bestagent.dev, Claude Code's Code Mode, tested (https://bestagent.dev/claude-code-code-mode-cost-tested-2026/)

Anthropic, Monitoring · Tool result event (https://code.claude.com/docs/en/monitoring-usage#tool-result-event)

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

benchmarkdeveloper toolsClaude Codetoken optimizationAI coding agentsCode ModeStripe SDKtool chaining

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion