Skip to main content

Codemode

The codemode tool lets the model write a JavaScript script that calls Atomic’s other tools and runs non-LLM models, such as classifiers and image models. Only the script’s output reaches the model, so a script can run calls in parallel and filter large results before the model sees them. To turn it on, see codemode in Built-in tools. The sandbox is the @bastani/atomic-codemode library, which you can also use in your own apps.

Scripts

The tool input is raw JavaScript source, not JSON and not a markdown code fence. It runs as the body of an async function in a QuickJS sandbox, so top-level await and return work. The sandbox has no Node APIs, file system, network, or timers; scripts reach the outside world only through tools and models. A script may start with an options line. It must be the first line; an options line anywhere else fails the call before the script runs:
  • max_output_tokens (default 10000) limits the output. Longer output keeps its start and end, and the full text is written to a temp file whose path is included in the result.
  • timeout_ms is a hard deadline for the whole script, including any wait for a free worker. It is unset by default. Image generation can take minutes, so do not set a short deadline for scripts that generate images.
The result starts with Script completed or Script failed, the wall time, and the output. Text and image items appear in order. When output has multiple text items (from text() or return), each starts with a ==> text N/M <== line. Console calls follow the other output in one <console_output> block, with one line per call. A failed script keeps its partial output, followed by Script error: and the error. Tool calls are real: calls made before a failure are not undone. Calls still running when the script ends are cancelled, and unawaited promises are discarded.

Globals

Call tools

Every script-callable tool in the session is a method of tools, named by its identifier: characters that are not valid in a JavaScript identifier become _, so the MCP tool mcp__dev-docs__search is tools.mcp__dev_docs__search. Each method takes one object with the tool’s arguments. What a call resolves to depends on the tool:
  • Tools with an output schema resolve to a structured value. bash resolves to { output, truncated, full_output_path?, exit_code, wall_time_seconds }, also for non-zero exit codes. Its output is not limited to what the model sees directly: it holds up to 1 MiB, and longer output keeps its first and last 512 KiB around an omission marker, with truncated set and the full output in full_output_path.
  • MCP tools resolve to their CallToolResult, including isError and structuredContent. Their declarations spell out content, isError, and structuredContent typed from the server’s output schema.
  • read resolves to the returned text (including path headers and line numbers unless :raw is used), or for an image to an image block { type: "image", data, mimeType, note } that image() shows. data is the base64 image the model would see and note the accompanying text, such as resize hints.
  • Other tools, such as edit and write, resolve to their text output.
A call that fails, is blocked, or gets invalid arguments rejects with an Error that carries the tool’s error text, except that a tool with an output schema also resolves on failure when it returned its structured value (for example bash with a non-zero exit code), so check its fields. Use Promise.allSettled() to keep the results of the calls that succeed. Reading a tool that does not exist throws an error that names the close matches, so tools.Bash suggests tools.bash; check for a tool with "name" in tools. The codemode description lists tools with their TypeScript declarations, grouped by namespace (for example one MCP server). Tools with deferred exposure are not listed, so the description stays the same while they register. Listed declarations share a budget of 3000 estimated tokens (codemode.inlineBudget in settings). Scripts find the other tools with searchTools(), describeTool(), describeNamespace(), or by filtering ALL_TOOLS. While codemode is active, codemode.mode in settings decides how the other tools are presented. With on (default) declared tools stay declared, and their descriptions say in one line how scripts call them and what the call resolves to. With only ordinary direct tools are hidden from the model and listed in the codemode description instead, so the model calls them through scripts; active model-only tools such as subagent and workflow stay declared as top-level tools. Tool declarations in the codemode description, describeTool(), and ALL_TOOLS carry the tools’ prompt guidelines, since the system prompt rules only cover declared tools.

Model-only tools

Model-only tools, such as subagent, workflow, and ask_user_question, are not in tools or ALL_TOOLS, and searchTools() never ranks them as matches. They cannot be called from inside a codemode script; when one is needed and available in the session, the model calls that separate top-level tool directly instead of trying to reach it through codemode, so a missing entry in tools does not mean the tool is unavailable. While such a tool is active, searchTools() and describeTool() answer its exact name, such as searchTools("subagent") or describeTool("workflow"), with a hint to call it directly as a top-level tool, not from a script. The hint does not make the tool callable from scripts. Some model-only tools let scripts use part of them. intercom is in tools with list, status, pending, and send to an exact target, each resolving to a structured value; its other actions, and sends to globs or subagents: targets, fail with a message to call the tool directly. See Intercom from codemode scripts.

Store values

store(key, value) keeps a JSON value under a string key for later codemode calls; storing undefined deletes the key. load(key) returns the value, or undefined. Writes are kept only when the script succeeds: each successful script that stores values appends a codemode-store custom entry to the session, so resumed sessions keep the values and each branch sees only the values written on its path. The store is for small state such as IDs, cursors, or summaries. One value may have at most 262144 characters of JSON and all values together at most 1048576. Do not store image data; show images with image(), which also saves them to a temp file.

Models

models reaches the model catalog and runs non-LLM models with the session’s credentials: classifiers, which answer typed questions about JSON state and, for some models, images, and image models, which generate images. Chat models are listed but cannot be run from scripts. Classifier models include TypeSafe Jev, OpenAI GPT-6 Luna, and local llama.cpp models; image models include OpenRouter’s, such as google/gemini-2.5-flash-image and black-forest-labs/flux.2-pro, which use the same OPENROUTER_API_KEY or /login credential as its chat models, and OpenAI’s GPT Image models under openai-images, such as gpt-image-2.6-flare, which reuse your OpenAI API key. Neither kind appears in /model.
classify() and generateImages() use only the provider and id of model, so { provider, id } works as well, and a script-supplied baseUrl or headers never receive the credentials. They do not throw on provider errors: check stopReason and errorMessage; generateImages() also sets error for a classified failure. A malformed model or context does throw, with the expected shape in the message; an unknown or mistyped model points to models.getAvailableOfType(). At most four such calls run at once per script; more calls wait for a free slot, so Promise.all() over many items is fine. Their usage is added to the codemode tool result and counts toward the session cost. Model IDs differ between providers. Use models.getAvailableOfType(type) to find the IDs that work with the current credentials.

Classify

Classify several items by calling classify() once per item. This script sorts feedback messages, for example ones a tool returned earlier in the script:
Classifiers whose input includes "image" can judge images alongside the state. tools.read() returns image blocks that images accepts. Text-only classifiers and APIs that cannot send images return an error result for nonempty images.

Generate images

The options are those of OpenAI’s GPT Image models under openai-images; OpenRouter image models ignore them. The first image without a role is the base image to edit and the others are references. An image with role: "markup" is a transparent PNG with annotations, sent as markup and applied to the first image, which it must match in size; one with role: "mask" is an alpha-channel mask for the first image. They cannot be combined. outputFormat: "gif" returns an animation (frameCount 2-16, frameDurationMs 20-2000) and "svg" returns SVG; both need a GPT Image 2.6 model and generation without images. A request that cannot succeed does not throw: before anything is sent it returns stopReason: "error" with error.code invalid-option and error.fields.field naming the option. error.code is also moderation-blocked, user-error, quota-exceeded, rate-limited, server-error, timeout or api-error; branch on it, and on error.retryable, not on the message. See Image generation for each code. SVG output needs no other option: { outputFormat: "svg" } works on every account. Some accounts must name the model that writes the SVG. When the API answers that svg.model is required and the call set no svg, Atomic retries once with gpt-6.1-sol and result.svgModel reports the model used. OpenAI’s API reference lists no authoring models and no default, so gpt-6.1-sol is a value that worked in testing, not a documented default. Pass svg: { model, reasoning } to choose another model; an svg you pass is always sent as given and never retried or replaced. If the API rejects the retry’s svg as unsupported, Atomic retries once more without it. A rejected svg.model or svg returns error.code invalid-option with error.fields.field svg.model or svg, and error.fields.reason required-by-api, rejected-by-api or unsupported-by-api. SVG authoring takes tens of seconds (plain requests took 12 to 46 seconds in testing, and OpenAI says complex prompts can take up to 2 minutes), and Atomic sets no request timeout shorter than 10 minutes, so a script that sets timeout_ms should allow at least 180000. Show generated images with image(block). Do not print data with text(), console, or return: it is large and the model cannot read it as text. A script that generates images without showing any gets a note saying so. image() accepts PNG, JPEG, GIF and WebP, so show an animated GIF with image(block). It does not accept SVG: Atomic saves each SVG that models.generateImages() returns to a private temp .svg file and names its path in the result, as [SVG saved to <path> (image/svg+xml, <size>)]. An SVG block (image/svg+xml) holds XML text, which a script can read with atob(block.data). image() also saves each image to a private temp file and puts its path in the result, so a later turn can copy or move the file.
A plain SVG request, which Atomic recovers when the account needs svg.model, and a four-frame GIF:
Extensions call classifiers and image models through ctx.modelRegistry.classify() and ctx.modelRegistry.generateImages(), without codemode.

Limits

  • A script’s VM has 256 MB of memory. Running out throws InternalError: out of memory; filter or aggregate large data instead of accumulating it.
  • Stopping a script or reaching its deadline ends the call promptly. In the standalone atomic binary (Bun), a built-in that does not check for interruption, such as a long string search, can keep computing in its worker until it returns.
  • At most two codemode workers may be alive across all sessions in one Atomic process; ATOMIC_CODEMODE_MAX_WORKERS changes the limit. A cancelled worker occupies its slot until it exits. At capacity, new scripts wait for a free worker in arrival order. A script that gets no worker within 60 seconds, or before its timeout_ms, fails without running.
  • A script that waits on a promise that can never settle (no tool call pending) fails immediately, since there are no timers.
  • Scripts cannot start other codemode scripts.