Codemode

Codemode

Panda enables Codemode by default in interactive, print, JSON and RPC sessions. In code mode, scripts can create files with tools.write({path, text}) and update them with tools.edit({path, old, new}). Plan mode exposes read-only helpers. For example, ask “Rank the five files with the most TODO lines.” The script can count matches across all search pages and return only the ranking. Use --no-codemode to disable JavaScript composition. Existing invocations with --codemode still work.

For print and JSON runs, --codemode-only makes codemode the sole tool the provider can call. Scripts use the helpers permitted by the session mode and tool selection. Use panda --print --codemode-only --tools read "Read version.txt" to allow just one nested helper, or panda --mode json --codemode-only --tools codemode,read,search "Rank TODOs by file" to allow two. Listing codemode is optional with this flag. An explicit --no-tools still disables all tools.

ALL_TOOLS lists the current script’s callable helpers as {name, description} entries. searchTools("find matching lines", {limit: 1}) ranks those entries by relevance. The default limit is eight. Pass a returned name to describeTool(name) for its description and typed signature, or to tools[name](args) to call it. Discovery runs synchronously inside the worker and uses no nested calls. With --tools codemode,read, the catalog contains only read, and describeTool("search") returns undefined.

Use --defer-tools NAME[,NAME...] to expose tools after the model calls tool_search with a matching query. Discovery follows the saved branch. --hide-tools removes names from direct calls, search results and Codemode. Both flags respect the current mode and selected tools. Within Codemode, describeNamespace("workspace") lists allowed workspace helpers. Inline helper descriptions use a 12,000-byte budget.

Concurrent reads run in groups of up to four. Mutations wait for earlier calls and complete before later calls begin. Results retain the provider’s order. --steering-mode one and --follow-up-mode one deliver one queued message at each eligible boundary in terminal and RPC sessions. Both default to all.

Use await Promise.allSettled([asyncTools.read({path:"a"}), asyncTools.read({path:"b"})]) to read concurrently and receive each outcome. A first-line // @options: {"async":true} gives the same Promise interface to tools. Up to four workers share slots across sessions for the current user, and each worker admits four nested reads at once. Waiting for a slot ends after three seconds or the script deadline, whichever comes first. An unresolved promise without pending work fails immediately. Cancelling a script stops active reads, and exiting discards unstarted reads.

Each invocation starts a fresh QuickJS worker under macOS Seatbelt. Read helpers are available in both modes. For example, tools.repo_map({glob: "**/*.rs"}) lists Rust files and tools.search({query: "^pub fn ", regex: true, glob: "src/**/*.rs"}) finds matching lines under src/. Search defaults to case-sensitive literal text. For example, tools.search({query: "todo", ignoreCase: true, context: 2}) finds mixed-case TODOs and returns up to two lines on each side. ignoreCase also works with regular expressions. Globs match workspace-relative paths: * stays within one path component and **/ matches zero or more directories.

tools.ls() lists the workspace root. Pass {path: "src"} to list the immediate entries in a directory. Each item contains its name and type (file, directory, symlink, or other). Listings include dotfiles and ignored names, report symlinks without following them, and return up to 50 entries in lexical order. Pass next_offset back as offset with the same path for the next page. An empty directory returns an empty page. A missing path produces an error.

Use tools.list_models({}) to inspect locally configured and cached models. Pass {model: "provider/model"} to check one model. The host reports credential availability and inference capabilities. Enable classification or image generation on a model in the personal models.json by adding "inference": ["classify"] or "inference": ["generate_image"]. These helpers use OpenAI-compatible structured Chat Completions and base64 PNG image generation respectively. For image classification also declare "input": ["text", "image"].

This code-mode script classifies the image it generates and displays it once.

// @options: {"timeout_ms":120000}
const labels = ["diagram", "photograph"];
const drawing = tools.generate_image({model: "studio/art", prompt: "Draw a circuit diagram"});
text(tools.classify({model: "studio/vision", labels, image: drawing}));
image(drawing);

For JSON classification, pass input in place of image. The host resolves credentials and records each request under classify or generate_image in :usage. The default script deadline is 10 seconds. Scripts with an enabled inference helper can request up to 180 seconds.

Use tools.shell_result({id}) to inspect a completed shell call on the active branch. The result includes output, exitCode, cancelled, truncated, and, when recorded, elapsedMs and fullOutputPath. For a truncated result, pass the log path to tools.read({path, offset, limit}) to retrieve specific lines. Older sessions can lack structured results.

Use the optional workspace-relative path on search and repo_map to select one directory or file. Returned paths and glob patterns are relative to the workspace root. Search and map honor workspace and nested .gitignore rules before returning up to 50 matching items per page. A later ! rule can re-include a file if its parent directories are visible. Pass next_offset back as offset with the same arguments until it is null. Search items contain path, one-based line, and text. A positive context adds before and after arrays of text in file order, clipped at file boundaries. Each line is limited to 500 characters. Only matching lines count toward the offset. A context-heavy page can end early to fit the 1 MiB tool-result limit. Map items are paths. Use text(value) to select the text included in the saved tool result and the next model request. Nested calls appear live in the terminal and as nested_call events in JSON and RPC.

Scripts run as async function bodies. For example, return tools.read({path: "version.txt"}) reads the file once and returns its text. A returned value is awaited and appended after earlier text() calls using the same serialization, preview, and total byte limit. A bare return or return undefined adds no output. Call exit() to finish the script immediately with the output and stored values accumulated so far. An uncaught error or rejected return rolls back pending store() writes. File writes and edits take effect when their helper succeeds. A batch containing either runs in submission order.

Use console.log("searched", offset) to record which pages a script visited. log, info, warn, error, and debug join their arguments with spaces. Their lines appear in call order in a single <console_output> block after the text and return value. On a throw, the diagnostic follows the block. The block and its delimiters count toward the same preview and output limits as other text.

Use store("rank", {cursor: page.next_offset, counts}) to checkpoint a paginated search and load("rank") to resume it in a later script. Values follow the active session branch through reopening, compaction, and Pi JSONL export/import. A load returns a fresh JSON copy, or undefined for a missing key. Pass undefined to delete a key. Writes take effect together when the script succeeds. One value can contain 262,144 UTF-16 code units of JSON, and the combined keys and values can contain 1,048,576.

Set a smaller preview or deadline on the first line of a script, for example // @options: {"max_output_tokens": 256, "timeout_ms": 2000}. The preview accepts 1–4,096 tokens at four UTF-8 bytes each. For very small budgets the truncation notice and log path can exceed the requested size. The deadline includes time spent in nested calls. A timeout discards pending store writes.

By default Codemode returns up to 16 KiB inline. For longer text, the preview includes the beginning, the end, and a workspace-relative path to the complete UTF-8 log under .panda/. Use read or tools.read({path, offset, limit}) to recover omitted lines, including after reopening a session. If a script throws, its tool error includes any text emitted before the failure, followed by the diagnostic. The same preview and full log apply, and pending store() writes are discarded. Emitting more than 1 MiB of text across a script fails the call and discards its pending store() writes. Newlines inserted between outputs count toward the limit.

A script has a 64 MiB JavaScript heap, up to 64 tool calls and 12 MiB of base64-encoded image URLs. Ctrl-C cancels the worker and its active host calls.