Code Mode: Let Models Orchestrate Tools with Scripts
Code mode moves tool orchestration out of multi-turn conversation and into a script the model writes itself, running tool calls in parallel, passing values between processes, and returning only a compact summary to the context. This article explains why step-by-step tool calling is expensive, walks through the core mechanism with a pseudocode example, lists the scenarios that actually benefit (and those that don't), covers visibility, auditing and safe-usage practices, and provides the compatibility checklist and the environment variable needed to enable the feature. It closes with a transferable rule for deciding when to let a model write code and when to let it think.
1. The real bottleneck: why one-step-at-a-time tool calls slow everything down
When you use an AI coding assistant for real engineering work, its ceiling usually isn’t set by reasoning quality. It’s set by how the model interacts with its environment. Most tool calling follows a simple pattern: the model emits a tool request, the runtime executes it, the result is appended back to the context, and the model reasons again. That pattern carries three structural costs.
Serial waiting. A loop of “search → locate → edit → verify” typically takes four to six round trips. Each round trip includes network transfer, inference latency, and context reshuffling — and it’s the accumulation of these that users actually perceive as lag.
Context pollution. This one is less visible but more damaging. Search results easily run to hundreds of lines; test output can run to thousands; compiler logs, stack traces, and dependency installation output all get dumped into the context window verbatim. The model needs three or four key facts from that block, but it pays token cost for the entire thing — and the noise dilutes its attention while raising the probability of a wrong call.
Retry amplification. If any single step produces output in an unexpected format, the whole chain has to be replanned. The more complex the task, the worse this gets: thirty confirmation-style round trips means thirty chances to go wrong.
The conclusion is straightforward: anything that is deterministic and orchestrable shouldn’t be driven round by round by the model in the first place.
2. The core mechanism: pushing orchestration from conversation turns down to a local script
The basic idea of code mode is to lift the orchestration layer out of the model’s multi-turn dialogue and hand it to a script the model writes itself. The runtime’s role shifts from “forward each call one by one” to “execute the script and inject results where needed.”
Concretely, once a user states a requirement, the model no longer produces a single tool request. It produces complete logic:
- Parallel dispatch. Multiple independent commands run within the same turn instead of queuing behind each other.
- Local value passing. The standard output of one step can feed directly into the next as input. Data moves between processes and never passes through the model’s context.
- Local convergence. Filtering, deduplication, truncation, and aggregation happen locally. Only the final structured summary goes back into the conversation.
- Background long-running tasks. Expensive commands can be moved to the background. The script returns a job handle immediately, the main conversation stays unblocked, and the user can keep talking to the assistant about other things.
A pseudocode sketch:
// Goal: bulk-rename a symbol across files, then run verification in the backgroundconst hitList = await search({ pattern: "parseConfig", filesOnly: true });const files = hitList.stdout.trim().split("\n").filter(Boolean);const changed = [];for (const f of files) {await applyEdit({ file: f, find: "parseConfig(", replace: "loadConfig(" });changed.push(f);}// Long-running command goes to the background; it won't block the main conversationconst job = await runCommand({ cmd: "run-test-suite --silent", background: true });// Return only the information that actually matters to the contextreturn { modifiedCount: changed.length, modified: changed, jobId: job.id };
Pay attention to that return line. It decides how much information enters the context: not the full diff of thirty files, but a file list; not the complete test log, but a task ID you can poll. This is exactly what separates code mode from ordinary “parallel multi-tool calls” — the latter just makes round trips faster, while the former keeps the data local.
3. Typical scenarios: the full loop for a cross-file batch change
Take “replace all call sites of a function and make sure the tests still pass.” In the traditional flow, the model has to bounce back and forth between searching, confirming paths, editing file by file, and running tests — and it has to read every output word for word.
In code mode, that logic collapses into a single script execution: locate all matching files in the codebase, narrow down to the paths that need work, apply the replacement in bulk, trigger the test command, and finally return only “which files changed” and “did the tests pass.” There is no redundant context injection anywhere in the middle.
From this we can generalize three categories of tasks that genuinely fit:
- Large-scale repetitive changes. When more than ten files are involved and the modification pattern is highly consistent, the benefit scales linearly with size.
- Search results that need upfront filtering. Log triage, dependency reference counts, cross-repository search — cases where raw output volume vastly exceeds the amount of useful information, and the trimming has to happen locally.
- Several independent commands that can run in parallel. Read-only probing, environment checks, multi-dimensional scanning: these don’t depend on each other, and the speedup from parallelism is close to the number of commands.
Conversely, if a task is fundamentally an open-ended decision requiring repeated trade-offs — architecture selection, locating a vague defect — scripting brings no benefit. The value of those tasks lies precisely in the process of watching output step by step and revising hypotheses.
4. Visibility and auditability: scripts don’t bury the conversation
A fair question: if the model writes code and runs it locally, does the process become opaque?
The design answer is layered visibility rather than disclosure by default. In everyday conversation, the UI shows only the normal activity log and the diffs. The script itself is collapsed by default — it doesn’t flood the screen or break your reading rhythm. When you need to audit, open the session transcript view with its expand shortcut (usually a Ctrl+O-style key combination), find the collapsed code entry, expand it, and you’ll see the complete script the model generated along with its execution trace.
Two practical takeaways follow. First, review has to be active: collapsed doesn’t mean no review is needed, especially for operations that write in bulk. Second, code is a better audit target: compared with reading tool calls one at a time, reading one complete script makes it much easier to see what it actually did — loop boundaries, write scope, and error handling are all visible at a glance.
Good safety habits matter just as much:
- On the first run, keep the blast radius minimal — validate the script’s logic against a subdirectory or a single module first.
- Have the script print a plan before making changes, treating “which files will be touched” as its own step, so you can confirm the list before anything is written to disk.
- Make sure the workspace is in a rollback-capable state, with a clean version control tree and a commit you can return to.
- For destructive commands (recursive deletes, force pushes, database schema changes), require them to appear explicitly in the script so a human can intercept them.
5. Enabling conditions and compatibility: a checklist to verify item by item
For an experimental capability like this, the constraints usually matter more to adoption than the feature itself. Confirm each of these before you start.
Model side. Only newer-generation models support script-based orchestration, across the flagship, balanced, and lightweight tiers in their current versions. Older models lack the required output capability; turning the switch on won’t help.
Client side. You need a recent version of the native install with support for this experimental feature. Earlier versions have neither the corresponding toggle nor the runtime support.
Platform side. On certain operating systems you must install the full command-line distribution of the version control tool in advance, otherwise the search and change commands inside the script can’t run.
Account and organization policy side. The account must be an official subscription account with the provider or a direct console account. Requests routed through third-party platforms, cloud marketplace hosting services, or various gateways generally can’t be enabled. In addition, organization environments with healthcare-data compliance settings or zero-data-retention policies are disabled by default — those policies require the request path to be fully controlled, and script execution introduces extra behavior on the local side.
Interface form side. For now, this mode targets interactive terminal sessions. Editor extensions, desktop clients, cloud-hosted sessions, one-shot invocations that pass a single prompt parameter, and developer kit APIs are all outside the supported scope.
Multi-agent collaboration side. When working with multi-agent teams, the client version requirement is higher, and it can only run in the default same-process mode; isolated run modes such as split-pane automatically degrade to an unsupported state.
6. How to enable it: one environment variable, two scopes
Turning it on is lightweight. The core is a single experimental switch variable, where 1 means enabled.
Per-session scope, exported temporarily in your terminal — a good fit for the evaluation phase:
export CODE_MODE_EXPERIMENTAL=1start-assistant
Persistent global scope, by adding the same variable to the env section of the config file in your home directory, so every new session inherits it:
{"env": {"CODE_MODE_EXPERIMENTAL": "1"}}
Which scope to choose depends on your purpose. During evaluation, prefer the per-session approach so you don’t accidentally leave it on. Once you’ve confirmed the benefit is stable, write it into the config file and fold it into the team’s standard development-environment setup script so behavior stays consistent across members.
7. Recommendations for rolling it out
If you plan to promote this style of orchestration within a team, a few easily overlooked points are worth designing for up front.
Govern scripts like code. Orchestration scripts generated by the model have real execution power, so they deserve the same standards as production code: clear naming, comments explaining intent, avoidance of surprising side effects, and explicit handling of failure paths. When it makes sense, save them into the repository as reusable automation recipes instead of throwing them away after one use.
Prefer read-only; be careful with writes. Build trust in the script’s behavior in read-only scenarios first (search, statistics, health checks), then gradually open it up to write scenarios. That path lets a team calibrate where its trust boundary for automated results actually sits.
Instrument cost. A drop in context injection shows up directly as lower token consumption and shorter response latency. Compare data for comparable tasks before and after enabling the switch, evaluate the benefit with real metrics rather than gut feel, and use that to decide which task types are most worth scripting.
Keep a human confirmation gate. The value of automation is fewer round trips, not the elimination of judgment. Retaining a single confirmation at high-impact checkpoints usually still gives meaningfully better overall throughput than step-by-step interaction, at far lower risk exposure.
8. The broader principle: when to let the model write code, and when to let it think
Stepping back from the specific feature, code mode reflects a main thread in how AI coding tools are evolving: the model handles decisions and generation; the runtime handles deterministic execution and convergence. This division of labor follows the same logic as the familiar engineering practice of “declare the intent, let tooling do the work,” and it aligns with the direction the industry has broadly taken for code-execution-style tool calling.
From this we can distill one transferable criterion: when a step’s output serves only the next step — not the user’s reading and not the model’s reasoning — it belongs in a script, executed locally, and kept out of the context. Conversely, when a step’s output needs to trigger a change in strategy, a revision of assumptions, or a choice between options, it has to come back into the conversation where the model can see it.
Apply that criterion to your own daily work and you’ll usually find a few high-frequency, script-friendly steps that are still being handled one interaction at a time. Hand those to scripts, and spend the context budget you save on the parts that genuinely require judgment. That is the most concrete structural benefit this paradigm offers.
