12. Code Mode and the Other Tools
Code mode gives the model two tools in place of many:
exec runs model-written JavaScript in a fresh V8 isolate
inside a separate host process, and wait resumes a script
that outlived its time slice. Every tool the script calls comes back to
core and takes the normal tool path, with the same hooks, approvals, and
sandbox. The other tools in this chapter are small, and each answers one
need: a plan, an image, a question, a search, or a function the client
supplies.
Chapters 9 to 11 covered the tool router, commands, and file edits. Code mode comes next, because it changes how the model sees every other tool and because 13 of the 14 bundled models use it. The second half compares the remaining tools: the plan, images, questions to the user, web search, file search, MCP resources, and dynamic tools.
The picture
Two processes split the work. Core keeps every capability, including
the tool handlers with their approvals and sandbox. The host child
process keeps only computation: a gRPC server and one V8 isolate per
running cell. When a script calls
await tools.exec_command(...), the call crosses back to
core as a ToolCall message, and core runs it exactly as it
would run a direct call, tagged with
ToolCallSource::CodeMode. The script never touches a file,
a socket, or a process on its own.
Code mode
What the model sees
exec is a freeform tool, like apply_patch
(see Chapter 11). Its grammar,
defined in create_code_mode_tool in
codex-rs/core/src/tools/code_mode/execute_spec.rs, accepts
any source text with an optional first-line pragma:
start: pragma_source | plain_source
pragma_source: PRAGMA_LINE NEWLINE SOURCE
plain_source: SOURCE
PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/
NEWLINE: /\r?\n/
SOURCE: /[\s\S]+/
The description, built in
codex-rs/code-mode-protocol/src/description.rs, sets the
contract. Each call is evaluated “in a fresh V8 isolate as an async
module”, with “no Node, no file system, no network access, no console”.
Nested tools hang off a global tools object under
normalized JavaScript names, for example
tools.mcp__ologs__get_profile. Helpers include
text() and image() to append output,
store() and load() to keep values across
calls, notify(), yield_control(),
exit(), setTimeout(), and
ALL_TOOLS for metadata. The pragma can set
yield_time_ms and max_output_tokens. Core
fills a missing yield_time_ms from
CodeModeConfig, whose default is 30,000 ms, and the
description states that value; max_output_tokens defaults
to 10,000.
wait is an ordinary function tool with
cell_id, yield_time_ms,
max_tokens, and terminate. The model uses it
only after exec answers
Script running with cell ID .... It returns only the output
produced since the last yield, or the final result.
Three tool modes
ToolMode has three values: Direct,
CodeMode, and CodeModeOnly.
requested_tool_mode in
codex-rs/core/src/tools/mod.rs takes the model catalog’s
tool_mode first, then the code_mode_only flag,
then the code_mode flag, and falls back to
Direct. Because the catalog wins, the 13 bundled models
that set code_mode_only run in code mode whatever the flags
say.
In CodeMode, exec and wait
join the tool list and every other tool stays directly callable. In
CodeModeOnly, every tool with Direct exposure
leaves the direct list and is reachable only as
tools.<name> inside a script. Tools exposed as
DirectModelOnly, such as request_user_input,
stay direct, and the direct_only_tool_namespaces setting
keeps chosen namespaces that way. The plan step also removes any other
registered tool named exec or wait and records
it as a name collision, because code mode owns both names.
The two modes fail differently. When the host is unavailable,
effective_tool_mode downgrades CodeMode to
Direct, unless disable_in_process_fallback is
set. CodeModeOnly never downgrades: exec stays
the only route to most tools, a session cannot open, and the user sees a
warning that ends “Code mode will fail closed; enable
features.code_mode_host and install
codex-code-mode-host.”
A worked example
A test in codex-rs/core/tests/suite/code_mode.rs runs a
script in three phases. Trimmed to its core, the model’s
exec input is:
text((await tools.exec_command({cmd: "printf 'phase 1'"})).output);
yield_control();
// waits for a test gate here
text((await tools.exec_command({cmd: "printf 'phase 2'"})).output);
yield_control();
// waits for a second gate here
text((await tools.exec_command({cmd: "printf 'phase 3'"})).output);
The first custom_tool_call_output holds two items: a
header matching
Script running with cell ID \d+\nWall time \d+\.\d seconds\nOutput:\n,
then the text phase 1. The model then calls
wait with
{"cell_id": "<id>", "yield_time_ms": 10000} and
receives the same header with phase 2. A second
wait returns Script completed with
phase 3, and the cell closes. Each nested
exec_command result reaches the script as JSON with
chunk_id, wall_time_seconds,
exit_code, session_id,
original_token_count, and output, so
.output works directly.
The host process and the tool bridge
At startup, ThreadManager builds a
ProcessOwnedGrpcCodeModeSessionProvider when the
code_mode_host flag is on or
disable_in_process_fallback is set; otherwise it installs
DisabledCodeModeSessionProvider. The host program path
comes from the install layout. HostConnection::spawn in
codex-rs/core/src/code_mode_host.rs starts it as
codex-code-mode-host --listen grpc+stdio://, with piped
standard input and output, Codex-internal secrets removed from its
environment, its own process group on Unix, and kill-on-drop. Sessions
share one lazy HTTP/2 connection over those pipes. A doc comment adds
that only session admission can replace a dead host, and that an idle
host is kept briefly for reuse; HOST_IDLE_GRACE is 5
seconds.
The wire contract is the CodeModeHost service in
codex-rs/code-mode-protocol/src/grpc/codex.code_mode.v1.proto.
OpenSession leases a session. Execute streams
ExecutionStarted and then one outcome when the cell yields,
completes, or is terminated; Wait and
Terminate act on a running cell. The tool bridge is a pair
of calls. SubscribeToToolCalls is a stream on which the
host sends core one ToolCall per nested invocation, and
CompleteToolCall returns each result. A proto comment
explains why each result gets its own call: every result rides its own
HTTP/2 stream, “preventing a large response from blocking unrelated tool
completions”.
On the core side, submit_nested_tool in
codex-rs/core/src/tools/code_mode/mod.rs turns the message
into a normal ToolCall. A function tool takes an object,
which becomes a Function payload; a freeform tool takes a
string, which becomes a Custom payload. So
tools.apply_patch("*** Begin Patch\n...") reaches the patch
handler of Chapter 11. A call to
exec itself is refused with
exec cannot invoke itself. The call then goes through
handle_tool_call_with_source with
ToolCallSource::CodeMode { cell_id, runtime_tool_call_id },
so hooks, approvals, and the sandbox apply as they do for a direct
call.
Inside the host, code-mode-runtime starts each cell on
its own thread with a new v8::Isolate, passes in the stored
values, and parks a promise resolver for every pending tool call until
core answers. The crate links V8 with its v8_enable_sandbox
feature. Core starts the host as a plain child process; the isolation
this chapter can show comes from V8 and from the missing file, network,
and console APIs. The host limits itself to 2,048 active cells, and the
protocol allows 4,096 pending delegate calls; a comment notes that one
host “is shared by independent chats and all their subagents”.
Five crates carry code mode. The table names each one’s role.
| Crate | Role | Key item |
|---|---|---|
code-mode |
Core’s client side of the gRPC protocol | GrpcCodeModeSessionProvider |
code-mode-host |
Host binary and gRPC server | MAX_ACTIVE_CELLS |
code-mode-runtime |
V8 cells, timers, stored values | InProcessCodeModeSession |
code-mode-protocol |
Proto, tool names, descriptions | PUBLIC_TOOL_NAME |
v8-poc |
Proof of concept, “reserved for future V8 experiments” | embedded_v8_version |
Why a harness wants code execution as a mode
The exec description states the purpose: “Run JavaScript
code to orchestrate/compose tool calls”. What follows is the book’s
reading of that design, not a measurement. With direct tools, each call
costs a round trip through the model. A script can call ten tools in a
loop, await several at once, filter the results, and return only what
text() prints; unprinted output never enters the context
window. store() and load() keep state between
calls, and a long job yields and resumes with wait instead
of holding the turn.
The costs are concrete. Code mode adds a process, a gRPC hop, and a
V8 build to the install. exec and wait keep
the default supports_parallel_tool_calls of
false, so each takes the exclusive side of the tool lock
(see Chapter 9). And in
CodeModeOnly, a missing host binary leaves the model with
no route to most of its tools.
The other tools
Comparison
The table compares the remaining tools by wire kind, parallel safety,
and gate. “Parallel-safe” means the handler returns true
from supports_parallel_tool_calls, so the call takes the
shared side of the tool lock.
| Tool | Wire kind | Parallel-safe | Gate |
|---|---|---|---|
exec, wait |
custom, function | No | Catalog tool_mode, or code_mode flags |
update_plan |
function | No | [tools.update_plan], off by default |
view_image |
function | Yes | view_image flag; image-capable model |
request_user_input |
function, direct only | No | On by default; Plan mode by default |
web_search |
hosted web_search |
Runs on server | Provider capability; not Responses Lite |
web.run |
namespace function | Yes | standalone_web_search, or Responses Lite |
| MCP resource tools | function | Yes | MCP servers, or CodeModeOnly |
| Dynamic tools | function or namespace | Yes | Client sends dynamicTools |
update_plan
The plan tool is a checklist the model keeps for the user.
create_update_plan_tool in plan_spec.rs takes
a required plan, a list of items with step and
status (pending, in_progress, or
completed), and an optional explanation; the
description adds “At most one step can be in_progress at a time.” The
handler emits EventMsg::PlanUpdate, which clients render,
and answers the model with “Plan updated”. It refuses in Plan mode:
“update_plan is a TODO/checklist tool and is not allowed in Plan mode”.
At this commit the tool is opt-in.
resolve_update_plan_enabled returns true only for
[tools.update_plan] with enabled = true, and a
config test checks that an empty file yields false.
view_image
view_image loads a local image into the conversation. It
requires path, adds environment_id for
multi-environment turns, and offers detail
(high or original) only when the model
supports original detail and the unified image budget is off. The
handler refuses when the model’s input modalities lack images, reads the
file through the environment’s filesystem with a sandbox context, and
returns an input_image content item holding a data URL. The
view_image flag is STABLE and on by default.
request_user_input
This tool asks the user structured questions and waits for answers.
Its schema in request_user_input_spec.rs takes
questions (“Prefer 1 and do not exceed 3”), each with an
id, a header of 12 characters or fewer, a
question, and two or three options with a
label and a description; the client adds a
free-form “Other” choice. It is registered as
DirectModelOnly, so code mode never sees it, and only a
root thread may call it. By default it works only in Plan mode; in
Default mode it also needs the
default_mode_request_user_input flag. The handler calls
prompt_user and returns the response as JSON text. The
configuration key [tools.experimental_request_user_input]
defaults to enabled.
Web search: hosted tool or extension
Codex has two web search paths. The hosted path adds a
ToolSpec::WebSearch to the request, and the server runs the
search; create_web_search_tool maps the
web_search setting (disabled,
cached, indexed, or live, with
cached the default) to external_web_access and
indexed_web_access. Codex never executes a hosted search.
codex-rs/core/src/web_search.rs only formats the returned
actions (Search, OpenPage,
FindInPage) for display.
The extension path is a client-executed tool, web.run,
from codex-rs/ext/web-search.
hosted_model_tool_specs emits no hosted tools for a model
that uses Responses Lite, and omits hosted search when the
standalone_web_search flag is on and web.run
is registered. Because 13 bundled models use Responses Lite, they search
only through the extension, when it is installed and the provider
supports search. Chapter 19 covers
extensions, including this one and image generation.
File search is not a model tool
The file-search crate matches paths fuzzily with
nucleo over an ignore walk;
FileSearchOptions defaults to 20 results, 2 threads, and
respect_gitignore on. No tool handler calls it. Its
consumers are the TUI’s file popup and mention picker, the app server’s
fuzzyFileSearch method with its experimental session
variants, and the rollout crate, which uses it as a fallback to find a
thread’s file by ID.
MCP resource tools
list_mcp_resources,
list_mcp_resource_templates, and
read_mcp_resource let the model browse resources that MCP
servers publish. They are registered when at least one MCP server is
configured, or whenever the tool mode is CodeModeOnly, and
all three are parallel-safe. Chapter 17
covers MCP.
Dynamic tools
A dynamic tool is a function the client defines and serves. The app
server accepts a dynamicTools list on
thread/start, a field marked experimental. A test in
codex-rs/app-server/tests/suite/v2/dynamic_tools.rs sends
this entry, among others:
{
"dynamicTools": [
{
"name": "lookup_ticket",
"description": "Look up a ticket",
"inputSchema": {
"type": "object",
"properties": { "ticket_id": { "type": "string" } },
"required": ["ticket_id"],
"additionalProperties": false
}
}
]
}Each spec becomes a DynamicToolHandler, as a
Function or inside a Namespace;
defer_loading makes it Deferred, discoverable
through tool search. When the model calls one, the handler parks a
oneshot sender in turn state, emits an in-progress
DynamicToolCall item, and waits. The app server sends the
client an item/tool/call request and submits the answer as
Op::DynamicToolResult, which resolves the parked sender; an
older Op::DynamicToolResponse carries plain content items.
The handler is parallel-safe, runs to completion even when the turn is
cancelled, and counts as a third-party tool.
Status at commit 081295be9d.
code_mode and code_mode_only: UNDER
DEVELOPMENT, off by default; turning on code_mode_only also
turns on code_mode. These flags matter little for bundled
models: 13 of 14 set tool_mode to
code_mode_only in the catalog, which takes precedence.
code_mode_host: STABLE, on by default.
view_image: STABLE, on. standalone_web_search
and default_mode_request_user_input: UNDER DEVELOPMENT,
off. update_plan: off unless configured.
thread/start.dynamicTools: experimental API field. Read in
code, not run.
What breaks
| Symptom | Cause | Check |
|---|---|---|
| Warning “Code mode will fail closed” | Host binary missing or code_mode_host off |
codex-rs/core/src/tools/code_mode/mod.rs; install
layout |
exec cannot invoke itself |
Script called tools.exec |
submit_nested_tool |
tool ... expects a string input |
Script passed an object to a freeform tool such as
apply_patch |
build_freeform_tool_payload |
| An MCP or extension tool is missing from the direct list | CodeModeOnly hides it; call it as
tools.<name> |
is_hidden_by_code_mode_only |
| Model never shows a plan | update_plan is opt-in at this commit |
[tools.update_plan] enabled = true |
update_plan is a TODO/checklist tool and is not allowed in Plan mode |
Called in Plan mode | plan.rs |
request_user_input refused in Default mode |
Allowed only in Plan mode by default | default_mode_request_user_input flag |
No hosted web_search in the request |
Model uses Responses Lite, or standalone web.run is
active |
hosted_model_tool_specs |
Code map
| What it is | Where | Identifier |
|---|---|---|
| Tool mode selection and fallback | codex:codex-rs/core/src/tools/mod.rs |
effective_tool_mode |
exec freeform spec |
codex:codex-rs/core/src/tools/code_mode/execute_spec.rs |
create_code_mode_tool |
| Nested call into the tool runtime | codex:codex-rs/core/src/tools/code_mode/mod.rs |
submit_nested_tool |
| Host process spawn | codex:codex-rs/core/src/code_mode_host.rs |
HostConnection |
| gRPC contract | codex:codex-rs/code-mode-protocol/src/grpc/codex.code_mode.v1.proto |
SubscribeToToolCalls |
| Utility tool registration | codex:codex-rs/core/src/tools/spec_plan.rs |
add_core_utility_tools |
| Hosted web search spec | codex:codex-rs/core/src/tools/hosted_spec.rs |
create_web_search_tool |
| Dynamic tool handler | codex:codex-rs/core/src/tools/handlers/dynamic.rs |
DynamicToolHandler |
Recall check
Which tools does the model see in code mode, and how do they
differ?
exec, a freeform tool that takes JavaScript, and
wait, a function tool that resumes a yielded cell by
cell_id.
Why do most bundled models run in code mode even though the
code_mode flag is off?
requested_tool_mode reads the catalog’s
tool_mode first, and 13 of 14 bundled models set
code_mode_only.
How does a script’s
await tools.exec_command(...) reach the
shell?
The host streams a ToolCall to core, which dispatches it
through the normal tool runtime with
ToolCallSource::CodeMode, under the usual approvals and
sandbox.
What happens in CodeModeOnly when
codex-code-mode-host is missing?
Nothing falls back to direct tools; code mode fails closed and the user
sees a warning.
Is fuzzy file search a tool the model can
call?
No; the file-search crate serves the TUI, the app server’s
fuzzyFileSearch, and rollout lookup.