Skip to content

Codemode ​

Parent: Tools and workspace.

The codemode tool lets the model chain other tools in a short Starlark script instead of making one tool call per model turn. Scripts can call native tools such as read_file, grep, and bash, and tools from connected MCP servers. The script reduces the results and returns only what the model needs, so large intermediate output stays out of the context.

codemode and its companion tool_search are available in every session that has tools enabled.

Modes ​

[codemode] mode controls which tools the model sees directly. It does not change what scripts can call.

Toolson (default)only
codemode, tool_searchdeclareddeclared
Native toolsdeclaredscript-only until loaded by tool_search
MCP toolsscript-only until loaded by tool_searchscript-only until loaded by tool_search
  • on: the model can call native tools directly or through a script.
  • only: other tools are hidden by default, so the model reaches them through codemode unless it explicitly loads them with top-level tool_search. Calling an undeclared tool directly returns an unavailable-tool error.

Top-level tool_search finds tools and loads its returned matches for direct calls on the next model request, in either mode. The search result includes a loading notice and compact names, descriptions, and top-level parameter names, with optional ones marked ?. Loaded tools' full argument schemas are declared on subsequent requests; other tools stay deferred. Wait for search to finish before issuing a direct call, rather than batching search and that call together. Loading belongs to the selected conversation branch: /new starts unloaded, and resume/tree navigation restores the destination's saved loadout. Rebuilding the runtime for the same conversation does not clear loaded tools.

Both tool_search and script search_tools rank tools locally with weighted BM25, without model or network calls. A match in the tool name counts most, then the description's first paragraph, then the rest of the description and parameter names, and rarer words count more than common ones such as get or list. A query that is exactly a tool's name ranks that tool first. Queries and tools are compared as lowercase words: snake_case, camelCase, kebab-case, dotted, and slashed names split into words, and light stemming lets creating issues find create_issue. The mcp__ and openapi__ name prefixes count only as low-weight words, so they do not crowd out the tool's own name; MCP descriptions also start with MCP server <name>, so mcp or a server name lists that server's tools.

Use focused queries and small result limits: every returned tool adds its full schema to subsequent requests. For broad catalog browsing or large inventories, prefer script-side discovery and execution so those schemas stay out of context.

Script-side search_tools, list_tools, and describe_tool are read-only: they never change the direct tool list. Scripts can discover and call MCP tools immediately with call_tool or call_tools, without loading their direct schemas into the model's context. search_tools and list_tools return compact name-and-description summaries; describe_tool returns complete schemas.

Set the mode in configuration or with /codemode on|only in the interactive TUI. The command applies to the next model request and saves the preference. /codemode status (or bare /codemode) shows the current mode in the status bar.

Permissions ​

Codemode is not a permission level. Each nested call goes through the same permission mode, hooks, and approval session as a direct call. A call that needs approval pauses the script until you allow or deny it, and approvals you already gave apply to nested calls too. Questions from a nested tool reach you through the parent codemode call. Cancelling the parent call cancels the nested call that is running.

A script cannot call codemode or tool_search. Rho rejects either name as an unknown tool.

Script API ​

Scripts use standard Starlark: def, for, if, comprehensions, and f-strings. There is no while, try, import, or exception handling. To loop until a condition holds, iterate over range(N) and break; the cap bounds the loop like the script's tick and nested-call limits already do:

python
pid = call_tool("process", {"action": "start", "command": "make test"})["data"]["process_id"]
for _ in range(20):
    polled = call_tool("process", {"action": "poll", "process_id": pid, "wait_seconds": 5})
    if polled["is_error"] or polled["data"] == None:
        break
    if polled["data"]["state"] not in ("running", "starting"):
        break
FunctionReturns
call_tool(name, args=None)One result dictionary
call_tools([(name, args), ...])Result dictionaries in input order
search_tools(query, limit=10)[{name, description}] rows
list_tools(limit=50)[{name, description}] rows
describe_tool(name)Full catalog entry: the parameters schema and the returns schema of a successful result's data (None for text-only tools)
print(...)Captures a line of output

Pass the exact tool name and an argument dictionary to call_tool, or batch independent calls with call_tools. There is no tools.<name> namespace. call_tool, call_tools, and describe_tool also accept another harness's spelling of an MCP tool name, such as T3 Code's mcp__t3_code__task_status for mcp__t3-code__task_status, when it names exactly one tool. See MCP tool names.

Each result is a native Starlark dictionary with three string keys. Use bracket indexing, not dot access:

  • "is_error": True for a completed tool failure, such as a shell command that exited nonzero or an MCP isError response, and for invocation errors returned by call_tools, such as denial or invalid arguments.
  • "content": the text the model would have seen from a direct call.
  • "data": the tool's structured result, or None when the tool returns text only or the value exceeds the tool output limit. See Structured output for built-in result shapes.

call_tool returns completed failures as values, so the script can branch on response["is_error"] when the result is named response. Invocation errors, including denial, invalid arguments, and errors that prevent a completed output, raise a script error instead.

call_tools runs independent calls concurrently, up to 4 at once. That is the same limit Rho applies to a parallel tool batch from the model. A script must make dependent calls in order itself. Invocation errors in a batch become per-item dictionaries with "is_error": True, error text in "content", and "data": None; sibling calls keep going and results stay in input order. Parent cancellation and rejection of the whole batch for exceeding the nested-call budget fail the script instead. Check every returned dictionary before using its data, including batch results. A non-error result can still have "data": None for text-only or oversized results.

Result dictionaries support normal dictionary operations such as dict(), get, update, and equality. JSON objects in data and discovery entries are also native dictionaries; JSON arrays are lists.

Assign result = ... to return a JSON value. On success, the model receives the printed lines followed by result. A value that cannot be represented as JSON fails the script instead of becoming null. Other variable names, such as hits below, are chosen by the script; only result is the output convention.

python
hits = call_tool("grep", {"pattern": "TODO", "path": "src"})
files = []
if not hits["is_error"] and hits["data"] != None:
    files = [entry["path"] for entry in hits["data"]["files"]]
print(f"{len(files)} files with TODOs")
result = files[:20]

Waiting for a process ​

Scripts do not receive process-exit notifications. To wait within a script, check each process result dictionary, then read its "data" dictionary and poll with data["process_id"] and cursor: data["next_cursor"] while data["state"] is "starting" or "running". Use wait_seconds to wait for output or completion rather than busy-polling. If you also need all output, continue polling while data["output_pending"] is true, even after the state becomes terminal.

Oversized structured snapshots return a smaller page of data["chunks"] while keeping their control fields. data["next_cursor"] points to the first deferred chunk; the next poll retrieves it while it remains retained. An optional data["output_budget"] notice reports max_output_bytes, the original received_bytes, and counts of deferred_chunks and omitted_chunks. A chunk that cannot fit by itself is omitted and its cursor consumed, matching the process poll budget policy; model-facing text is unchanged by this JSON paging step. Ordinary retention loss still appears as data["truncated"]. If even the control fields exceed the limit, the existing truncation notice appears in content and data is None; stop and report that result rather than polling without a cursor.

Limits ​

LimitValue
Nested tool calls per script64
Interpreter steps100,000
Heap8 MiB
Call stack depth64 frames
Output (prints plus result)Native tool output limit

A call_tools batch counts toward the 64-call limit before any call in it starts. There is no separate wall-clock limit for scripts; each nested tool keeps its own timeout. A script that fails retains its captured prints and call log. The model-facing text shows prints first, then the failure diagnostic. If that output exceeds the limit, prints are truncated with a notice so the failure block survives. The structured codemode result includes an error string with the full multi-line Starlark diagnostic on failure; that field is omitted on success.

In the TUI ​

The codemode card streams the literal script with syntax highlighting while the model generates the script argument, before the argument JSON closes or the script executes. This is decoded source, not escaped JSON or nested-call execution progress. A collapsed generating card follows the newest source rows within the tool-card display budget; expand it with Ctrl+O to inspect all source received so far. Earlier rows remain available rather than being discarded.

The card keeps its source shape during execution and after it finishes, when the header gains the nested-call count. Completed and resumed cards use the normal collapsed view from the beginning of the script; resumed sessions omit the count.

Scripts use Python-style highlighting. Source lines up to 4 KiB keep their colors when wrapped across terminal rows. Longer lines remain readable as plain text, with a notice showing the line size and highlighting budget. Splitting a long batch across source lines avoids this limit; it does not affect whether the script can run.