Skip to content
Source on GitHub (opens in a new tab)

The semantics and bounds of the built-in tools. Every tool declares its bounds, so no tool is ever unbounded.

One pattern language serves the Glob tool, Grep’s Include filter and .gitignore files (core/internal/glob). It is defined here, not by any one backend, so every environment means the same thing by a pattern.

  • A pattern is relative, slash-separated, and matched against the whole path relative to the search directory: *.go matches main.go but not cmd/main.go; **/*.go matches both.
  • * matches any run of characters within one name, ? one character, [abc], [a-z] a class and [!abc] (or [^abc]) its negation, and inside a class the POSIX names [:alpha:], [:digit:], [:alnum:], [:upper:], [:lower:], [:space:], [:blank:], [:punct:], [:xdigit:], [:cntrl:], [:print:] and [:graph:] (ASCII) work as in .gitignore; \ escapes the next character.
  • {a,b} gives alternatives and may nest: src/**/*.{ts,tsx}. A pattern is at most 4096 bytes, and its braces nest at most 32 deep and expand to at most 1024 alternatives, 64 KiB in all.
  • A ** segment matches zero or more whole names: a/**/b matches a/b and a/x/y/b.
  • Hidden names, starting with a dot, are matched only by a segment that starts with a dot: * doesn’t match .env, **/.env does, and ** never enters .github/ unless the pattern names it (.github/**).
  • . segments and repeated slashes are ignored. An absolute pattern or a .. segment is refused.

Grep’s results must not depend on which backend produced them (the Go one, or ripgrep where installed), so the portable subset is defined here and both backends are tested against it.

  • Patterns are RE2 (Go’s regexp/syntax, which ripgrep’s default engine also follows for this subset). CaseInsensitive is (?i). A pattern is matched against each line without its \n; a \r before it stays part of the line. A pattern never matches across lines.
  • One match per matching line, however many times the pattern occurs in it.
  • Context: each match carries up to Context lines before and after it, cut at the start and end of the file. Every match has its own context, so a line near two matches appears in both.
  • Include filters files with a glob: a pattern without a slash is matched against the file’s name, at any depth (*.go); one with a slash against its path relative to Dir (cmd/**/*.go). Without Include, hidden files and directories are skipped.
  • Binary files, those with a NUL byte in their first 8 KiB, are not searched.
  • Long lines: only the first 1 MiB of a line is searched, and what is returned of a line, matched or context, is cut at MaxLineBytes (on a UTF-8 boundary) with Cut set.
  • Backends. The local environment’s Go backend implements these rules directly. With local.WithRipgrep(path), ripgrep only matches lines: the environment still chooses the files (walk, ignores, binary probe), opens each one inside the workspace itself and hands ripgrep the open descriptor (/dev/fd on Unix, standard input one file at a time on Windows), gives ripgrep the pattern re-spelled from Go’s parse (so \d, \w, \s stay ASCII and \b becomes (?-u:\b)), and turns off ripgrep’s own encoding detection. A file that isn’t valid UTF-8, where the two engines read invalid bytes differently, a file with a line over the 1 MiB searched, the file that would take the search past GrepScanBytes, a line too long to report within 1 MiB, and any ripgrep run that fails are all searched by the Go backend instead, so results never depend on the backend. The CLI discovers ripgrep on the host PATH outside the workspace. A conformance suite (make test-rg) checks the Unix backend in CI. The native Windows integration test checks the standard-input backend, including CRLF and fallback for invalid UTF-8.
  • Order: files in the order a depth-first walk visits them, each directory’s entries in byte order of their names (a/b before a.txt); lines in order within a file. Path is relative to the workspace.

Glob and Grep walk the search directory and skip the entries below listed here. The search directory itself is searched as the query names it, even if it is ignored, hidden or reached through a link inside the workspace, as ripgrep searches a path it is given: naming node_modules/pkg is a request to look there. Grep’s target may also be a regular file, which is searched alone, whatever its name and Include, and the result says so (GrepResult.File).

  • .git directories, always.
  • Ignored paths: every .gitignore file found in the walk applies to its directory and below, with gitignore(5) semantics (core/internal/ignore), whether or not the workspace is a git repository. An ignored directory isn’t entered, so nothing inside it can be re-included. When the workspace is a repository’s top, with its .git directory in it, .git/info/exclude applies too, beneath every .gitignore, as git and ripgrep rank it: Claude Code lists its .claude/worktrees there, and a nested checkout unread filled the workspace baseline’s bound with another branch’s files. A linked worktree’s excludes, in its main repository, and the user’s global excludes file lie outside the workspace and are not read, so a search there can show more than git does, never less. Matching is case-sensitive on every file system, as ripgrep’s is by default, so on a case-insensitive one (typical on macOS), where git ignores case, a search can show a file git ignores. Ignore rules decide what a search shows; they are not access control.
  • Hidden names that the pattern doesn’t name, as the glob rules above say. Grep with no Include skips hidden files and directories.
  • Symbolic links, which are neither followed nor listed, so a walk can’t loop or leave the workspace. Devices, FIFOs and sockets are skipped too; only regular files are listed or searched.

Every bound is enforced while reading or streaming, never by trimming a result that was read in full. Hosts change the environment’s bounds with local.WithBounds; a zero field keeps its default.

Bound Default What happens past it
Bounds.FileBytes: largest file read or written 64 MiB env.ErrTooLarge, decided before reading or writing anything. A revision hashes the whole file, so a larger file can’t be read in part.
Bounds.ReadBytes: page returned by a read without MaxBytes, and by one read of process output 1 MiB the page ends there and Truncated is set, or Next points past it; the caller reads on from there.
Bounds.KeepHead, Bounds.KeepTail: process output kept when Cmd.KeepHead and Cmd.KeepTail are zero 1 MiB each output after the head and before the latest tail bytes is dropped as it arrives and counted in Output.Dropped.
Bounds.KeepBytes: most a Cmd may ask to keep, head and tail together 16 MiB Start refuses with env.ErrTooLarge (not dispatched).
Bounds.WalkEntries: directory entries one Glob or Grep visits 200,000 the walk stops and the result is Truncated.
Bounds.GlobLimit: paths Glob returns when the query gives no Limit 1,000 the newest paths are returned and the result is Truncated.
.gitignore read by a walk 1 MiB the rules after the cut are not read.
Bounds.GrepLimit: matches Grep returns when the query gives no Limit 1,000 the search stops and the result is Truncated; the last match still gets its context.
Bounds.GrepLineBytes: what Grep returns of a line when the query gives no MaxLineBytes 2,000 bytes the line is cut on a UTF-8 boundary and Cut is set.
Bounds.GrepScanBytes: bytes one Grep reads 512 MiB the search stops and the result is Truncated.
Bounds.GrepResultBytes: line text one Grep returns, matches and context 8 MiB the search stops and the result is Truncated.
Grep line searched first 1 MiB the rest of the line isn’t searched.
Grep Context 100 lines a larger Context is refused.
Bound Default What happens past it
ReadLines: lines returned when the call gives no limit 2,000 the result stops and says which offset reads on.
ReadLineBytes: bytes shown of one line 2,000 the line is cut on a UTF-8 boundary and the cut is marked with the number of bytes left out.
ReadResultBytes: text one Read returns 75,000 bytes (about 25,000 tokens, Claude Code’s bound) the result stops at a whole line and says which offset reads on.
Page asked of the environment 4 MiB the next page is read; every page must have the first page’s revision, or the Read is refused.
Binary probe first 8 KiB a NUL byte in it refuses the file as binary.

A file whose last line has no newline says so after its last row, and Write’s result says so of the content it wrote: numbered rows read the same either way, and a task asking for “exactly one line” turns on it. A free model in the pilot wrote the line without its newline, read the file back to check, saw nothing wrong and reported success.

Bound Default What happens past it
BashTimeout: how long a command runs in the foreground when the call gives no timeout 2 minutes the command moves to the session’s background processes and the result gives its handle; with none to take it, its process group is killed and the result says it timed out.
BashMaxTimeout: the longest timeout a call may give 10 minutes the command runs with the longest, and the result says so: a refusal cost the model a turn to send the same command again.
BashOutputBytes: output a result shows whole 30,000 bytes the whole output the environment kept is saved as a blob that Read pages through, and the result shows a preview around a note, as Claude Code does: the first and last 1,000 bytes (BashPreviewBytes), or for a failed command the first 2,500 and last 7,500 (BashFailurePreviewBytes), where the error usually is.
Output kept by the environment Bounds.KeepHead + Bounds.KeepTail the middle is dropped and the saved output says how many bytes.
Reading output still held by a process outside the command’s group 1 second reading stops and the result says later output isn’t shown.

Bash on Windows. The shell is Git for Windows’ bash.exe, found beside git.exe or at the host’s explicit path, never inside the workspace and never Windows’ own bash.exe, which starts WSL. The wrapper reports the working directories in the workspace’s own spelling (C:/Users/me/work), not Git Bash’s (/c/Users/me/work); what the command prints, and the path conversion MSYS2 does for the programs it runs, are left as they are, so a command’s output reaches the model unchanged, CRLF from Windows programs included. A command’s process group, for the processes it left running, is MSYS2’s: what bash started, native programs among them, but not what a native program started in turn, nor a program that detached itself.

Output encoding on Windows. What the model reads is UTF-8: bytes that aren’t are shown as U+FFFD. A native Windows program writes text in its console’s code page, the OEM one (437, 850, …) in a console as Windows makes it, while Git Bash’s own programs write UTF-8, so one stream could hold both and every character above 0x7F of the first would be lost. A command’s console is its own, one nobody sees, so each shell switches it to UTF-8 before the command runs, as chcp 65001 does, input and output: Bash’s launch runs chcp.com, named through SystemRoot so a file in the workspace can’t stand in for it, in the foreground wrapper and in a background command alike, and the PowerShell wrapper sets [Console]::OutputEncoding and [Console]::InputEncoding. The programs that follow the console’s code page, cmd.exe’s built-ins, dir and echo among them, then write UTF-8 at the source, so nothing is decoded a second time and text that is UTF-8 already, MSYS2’s or PowerShell’s own, passes through as it was written. A program that writes in the ANSI code page (1252, …) whatever the console says, tree.com and the file names in findstr’s messages among those measured, still writes bytes that aren’t UTF-8, and the model sees U+FFFD for them; so does a program that passes on bytes of a file in another encoding. Linux and macOS are not touched.

PowerShell tool (core/internal/builtin/shell)

Section titled “PowerShell tool (core/internal/builtin/shell)”

Hosts configure PowerShell with an absolute path to pwsh.exe (PowerShell 7+) or powershell.exe (Windows PowerShell 5.1). Discovery prefers pwsh.exe on PATH or under ProgramFiles, then 5.1. A PowerShell 7 from the Microsoft Store is on PATH only as an App Execution Alias, a stub in the user-writable %LOCALAPPDATA%\Microsoft\WindowsApps; discovery reads it without running it and uses the Microsoft.PowerShell package’s pwsh.exe that it names under ProgramFiles\WindowsApps, where only the system writes, and refuses an alias that leads anywhere else. Zero-config Windows runs give a session both shells when both are found, else whichever is (Bash and PowerShell together). PowerShell uses the same command, timeout, run_in_background and lifetime inputs, output bounds and session cwd handling as Bash. Use PowerShell syntax and Windows tools. Native exit codes can have program-specific meanings, such as robocopy codes 1–7.

The wrapper starts with -NoProfile -NonInteractive -ExecutionPolicy Bypass. The execution policy flag applies to the process and Group Policy still takes precedence. The wrapper runs through -Command: a short bootstrap decodes it from base64 and dot-sources it, and the command arrives as base64 data as well, so quoting never alters it. -EncodedCommand is not used, because a host started with it writes its error, warning and information streams to a redirected stderr as CLIXML (#< CLIXML, then XML with _x000D__x000A_ for each line break), in both editions, and in Windows PowerShell 5.1 whatever -OutputFormat says; with -Command they are text. PowerShell 7 would also colour table headers and errors with ANSI escapes into a pipe, so the wrapper sets $PSStyle.OutputRendering to PlainText. The wrapper sends a NUL-delimited cwd report on stdout, using Windows slash-form filesystem paths such as C:/Users/me/work. It uses UTF-8 for the console’s output and input code pages, strings piped to native programs, and PowerShell’s Out-File redirection default (see Output encoding on Windows, above). Output preserves CRLF. The editions differ in one visible way that the wrapper leaves alone: > and Out-File write UTF-8 in both, with a byte order mark in Windows PowerShell 5.1 and without one in PowerShell 7, and Set-Content and Add-Content keep each edition’s own default (the ANSI code page in 5.1, UTF-8 in 7) because giving 5.1 -Encoding utf8 would put a byte order mark on every file it writes. The tool says which edition runs, so the model knows && and || are available only in 7. Errors read as each edition formats them: NormalView in 5.1, ConciseView in 7.

An uncaught terminating error exits with 1. Otherwise the last native exit code is retained when nonzero, including after a later successful cmdlet. With a zero native code or no native call, a false final $? exits with 1. If the status capture is bypassed by an early return or a script with named blocks, a new PowerShell error record also yields 1. An explicit exit N uses the process’s exit status.

Explicit background starts and moves use the same handles and process controls as Bash. The wrapper reports leftover process presence as unknown. The Windows Job Object tracks the whole tree, so a foreground call waits for the job to empty and can move at its timeout. There is no early adoption from the PowerShell report. Stopping the handle terminates the whole job.

A host gives a session both shells with WithShell and WithPowerShell, each with its own executable and environment; neither replaces the other. On Windows this is the normal case, as Claude Code’s is: PowerShell is the primary shell, and Bash stays for POSIX scripts and tools.

  • Order and words. The model sees PowerShell before Bash. Each description says that PowerShell is the primary shell of this Windows machine, that Bash is for POSIX scripts and tools, and that the two share a working directory. The system prompt’s line on commands says the same, and the session’s context lists both shells, primary first. With one shell none of this is said and nothing else changes; on Unix there is only Bash.
  • One working directory. A session has one working directory, not one per shell. A call of either tool starts in it and, however it ends, reports where it ended in the workspace’s spelling (C:/Users/me/work, which both wrappers use), and the session records CwdChanged as before. So a cd in Bash is where the next PowerShell call starts, and the reverse. Separate directories would make “run it in the folder I just made” depend on which shell made it, and the model would need to track two. What doesn’t carry between the shells is anything a shell keeps for itself: variables, aliases, functions.
  • What the session records. Config.Shells lists the shell tools the session’s host runs, primary first (["PowerShell", "Bash"]), in place of a single PowerShell flag. A driver declares the same list (driver.WithShells); a driver that offers other shells can’t continue the session, because what it decided about a command was decided in those dialects. Each ProcessStarted records the Shell whose dialect its command is in, and ProcessList shows it. Changing either raised the log’s format generation.
  • Who runs in which. A call of Bash or PowerShell runs in that tool’s shell and is decided as its command (a Bash(...) rule and the Bash parser; a PowerShell(...) rule and PowerShell’s own parser, through the host’s analyser, without which PowerShell commands are opaque). Watch, Verify and a skill’s ! command lines run in Bash where the session has it, which such commands are written for, as Claude Code runs its Monitor and hooks there, and otherwise in the only shell: a watch’s command, a check the model registers and the host’s checks run in it and are decided as its commands; the PreToolUse hooks that run before them are those matching that tool’s name. Hooks match a call by its tool name, so a hook for Bash doesn’t see PowerShell calls: a hook for both shells lists both names.
  • Background processes. Either tool starts a background process with the same handles and controls. ProcessOutput, ProcessInput and ProcessKill take the handle whichever shell started it; what a handle’s process does when stopped is the environment’s (a Windows job object, or the group).
Bound Default What happens past it
GrepContentLimit: matching lines a content search returns when the call gives no limit 200 the search stops and the result says so; other modes use the environment’s GrepLimit.
GrepLineBytes: what a content search shows of a line 2,000 bytes the line is cut and marked.
GrepOutputBytes: text one Grep returns 64 KiB the result stops at a whole line and says so.
Bound Default What happens past it
EditResultBytes: the largest file Edit makes 64 MiB the edit is refused, checked before the new content is built.
Lines of a near match shown 20 the rest are counted, not shown.
Places listed for repeated text or a near match 5 the rest are counted, not listed.
Line comparisons searching for a near match 10,000,000 the search gives up, and the error says only that the text wasn’t found.

The built-in file tools record every revision they read or write as FileObserved: the whole file, a range of lines, or, for a file that doesn’t exist, its absence. Write replaces a file only after a Read of the whole file and Edit only after a Read of any part, both at the file’s current revision; otherwise they refuse and tell the model to read it again. A write or edit records the revision it wrote, with the extent of the observation before it, so consecutive edits need no re-read. A relative path resolves against the session’s working directory; when it lands somewhere other than it reads, Write’s result names the workspace path it wrote and the directory it resolved from, so neither the model nor the auto-mode reviewer mistakes a stray copy for the file meant.

Writes are conditional on the revision the caller read. The local environment serializes its own writes, so two can’t pass the same check, but it only detects a writer in another process: one that writes between the check and the rename is overwritten. Reads done through the shell aren’t tracked.

The scratch directory. A session given one (zelk.WithScratch) has Read, Write, Edit, Glob and Grep reach it by absolute path, through the environment’s env.ScratchOpener: a second confined root, made private to the user if missing, with the workspace’s bounds. Its files are observed under their absolute names, so a scratch notes.txt is never taken for the workspace’s, and edit-before-read holds there as in the workspace. They record no FileChanged: they are temporary, so a checkpoint or a turn diff of them would make a cleanup look like a change to the workspace, and they aren’t in the workspace fingerprint. Searches there name what they find by its absolute path, and load no project instructions; commands may write the directory by its path. Their TMPDIR is not it: it stays the shell’s (or a sandbox’s own), so tests and tools build their paths from the temporary root they have outside zelk, whose length (a Unix socket’s path fails past about 100 bytes) and words they may depend on. An environment without the capability, such as a client’s, refuses the paths as outside the workspace.

The built-in file tools (Read, Edit, Write, Glob, Grep) discover project instruction files from the workspace’s top down to the directory each call touches. In each directory the first of AGENTS.override.md, AGENTS.md, CLAUDE.md and the host’s WithInstructionFallbacks names wins. The top directory’s file is read when a session starts and is part of its context; others reach the model as a note before its next call, framed as repository guidance with less authority than the user and host. Each load, reload (a changed revision) or removal is recorded as InstructionsLoaded, so replay never reads the files again.

Bound Default Past it
Combined size of loaded instructions 32 KiB (WithInstructionLimit) the file is recorded as omitted, with a warning, and the model is told it wasn’t loaded

Files created through Bash are picked up only when a built-in tool next touches their directory, and shell commands never trigger discovery. WithoutProjectInstructions turns discovery off.

TodoWrite{todos: [{content, status, key?}]} replaces the session’s task list. Statuses are pending, in_progress and completed; key is a short stable task name that attempt tracking counts failures against. At most 100 items; a blank item or an unknown status refuses the whole list. The list is recorded as TodosUpdated, so it survives a crash and is re-injected after compaction. The tool changes nothing outside the session: it is read-only and runs in plan mode. Failed tool actions are counted against the sole keyed in-progress task captured when each action is scheduled; ambiguous plans remain unattributed. Counts persist for the run and trigger a reminder at the configured failure threshold, independently of identical-action termination limits.

Skill{name} loads a skill from the session’s index (skills.md). The result is the skill’s instructions framed by the trust of its source, the skill://<name>/<path> names of its files, where its scripts run (or that they can’t), and the tools it allows while active. Unknown and explicit-only names are error results. A skill’s bundle holds at most 1,000 files and 16 MiB; the index lists at most 16 KiB of names and descriptions.

Read takes skill://<name>/<path> for a loaded skill’s files, served from the recorded bundle. Bash checks a loaded skill’s script against its recorded SHA-256 before running a command that names it.

Bash{run_in_background: true} and PowerShell{run_in_background: true} start the command with the configured shell in the session’s working directory, its input open, and returns at once with a handle named after the call (bg-<seq>-<index>, stable on replay). The start is recorded as ProcessStarted with the environment’s process ID, which carries a generation, never a bare PID. A session runs at most 16 background processes.

Tool Behaviour
ProcessOutput{handle, wait_ms, until_exit?} The output since the last read, up to 30 KiB, waiting up to wait_ms (default 2 s, at most 270 s, which stays under a prompt cache’s five minutes; a longer one waits the most and says so) for some, or with until_exit for the process to end, gathering what it writes meanwhile, so a model that needs a chatty command’s result waits in one call. Once the process has ended and its output is read, the result gives its exit status or signal, ProcessEnded is recorded and the handle is closed. Read-only.
ProcessInput{handle, input} Writes to the process’s standard input.
ProcessKill{handle} Kills the process group, waits for it and records ProcessEnded.

Watch{command, description, min_interval?, stop_after?} starts a background process the same way, under its own handle, whose output lines wake the session instead of waiting to be read (wakes, Watch). It is decided as a command of the shell it runs in, Bash where the session has it, records a monitor source and is killed with ProcessKill. It lives as long as the host that started it. Its standard error goes to a file in the session’s scratch directory. It is offered wherever a shell is and the store keeps an inbox.

Background processes belong to the execution that started them: when it ends they are killed and ProcessEnded{killed} is recorded, so the session’s status and a later ProcessList say they ended, unless the environment can find processes again (env.ProcessReconciler), in which case they keep running and a later execution reaches them by their recorded ID. A backend that confirms the process is gone can record ProcessEnded{lost} when no ending was recorded. A process this host cannot observe stays pending and inspection reports it as unreachable. Shell cd in a background command doesn’t move the session’s working directory.

A foreground command can move to the background while it runs, when the user asks, as Claude Code’s ctrl+b does (BackgroundCalls). The same process moves: the call ends with a result naming its handle, and ProcessStarted is recorded with it, with the mark of the wrapper’s report and the command’s deadline. It keeps what it had in the foreground: its timeout, the earlier of timeout and the tool’s deadline, after which it is killed and ProcessOutput says so; its closed input; and the directory it started in, as the session doesn’t take the one it ends in. ProcessOutput reads it from the start, without the wrapper’s report, and when it ends the run is told so, unasked, as for a subagent moved there, so the model doesn’t poll for it; the notice is dropped once the model has read it to its end or the run has ended. It belongs to the execution, like any background process. When the session already runs 16, the command stays in the foreground.

A command also moves by itself, with no deadline: when it is still running at its timeout, it belongs to the execution; when it ends leaving processes in its group that are still running half a second later, such as a server started with &, they move as one background process that lives as long as the conversation, as such children outlive the call in Claude Code. A child that ends within that half second isn’t handed over. Where no one can take them, they are killed and the result says so.

WebFetch{url, prompt?} is present when the host passes a fetch.Fetcher (WithFetcher; zelk.Run and the CLI use fetch.New). The default fetcher refuses non-public addresses when it connects, re-checks every redirect, follows at most 5, never reads proxy settings from the process, and bounds bodies after decompression (fetch). HTML becomes markdown (scripts, styles, navigation and hidden content dropped; links resolved against the page); text, JSON and XML are returned as they are; other types are refused. A result shows at most 100 KiB of page; the whole page is saved as a blob Read pages through. With an extractor (WithExtractor), a call with a prompt is answered by its model instead: the call reserves the extractor’s limit from the session’s budget, runs alone, and its tokens are settled in the ledger. WebFetch is read-only and runs in plan mode.

WebSearch{query, allowed_domains?, blocked_domains?} is present only when the host passes a search.Backend (WithSearch); it returns up to 10 results as title, URL and snippet. A model-backed backend implements search.Limiter: each call reserves its full input and output bound before dispatch, runs alone, and settles its reported usage. Resolver-backed searches declare it per route (tool.WithRouteReservation), so the session records the selected route’s bound in Config.ToolReserves, including after model switches. Hard budgets refuse insufficient or unknown bounds before the backend spends tokens.

  • Images (.png, .jpg, .jpeg, .gif, .webp, checked by their first bytes) are returned as an image part when the session’s model takes images (Capabilities.Images); otherwise the result says it can’t. An image over 3.5 MB, or over 2,000 pixels on a side, is scaled down first (core/imagefit), as Claude Code’s Read does: a provider refuses a larger one, and a model looks no closer. The result says so, since the part may be of another type than the file. A file over 32 MiB, an image of more than 64 million pixels and a file that doesn’t decode as its image type (an animated WebP among them) are refused.
  • PDFs up to 32 MiB are converted by the host’s WithPDFConverter, at most 20 pages per call (pages: "3" or "1-5"); without a converter the result says how else to get the text.
  • Notebooks (.ipynb) are rendered cell by cell with their text outputs, each output cut at 4 KiB.

A media read records the file’s revision as a partial observation, so it never lets Write replace the file.

Edit and Write record each change as FileChanged: the revisions before and after and a unified patch of the changed region with three lines of context, cut at 16 KiB. When a run ends, the driver records TurnDiff with its ending: per file, the revision before its first change and after its last, the tools that changed it and their patches. Changes made through Bash, by background processes or outside zelk aren’t in it; the workspace-wide delta is v1.x.

AskUserQuestion, EnterPlanMode and ExitPlanMode

Section titled “AskUserQuestion, EnterPlanMode and ExitPlanMode”

These are control requests the loop handles itself (origin harness); the plan-mode ceiling doesn’t apply to them, and each waits alone. AskUserQuestion takes 1 to 4 questions, each with 2 to 4 options, multi_select and a category (authorization, correctness, preference; unmarked counts as correctness). ExitPlanMode{plan} exists when plan mode is among the authorized modes and someone can answer (the input policy isn’t deny), and works only in plan mode; approval switches to the mode the answer names, which must be authorized and not plan.

EnterPlanMode{reason?} is offered alongside ExitPlanMode in every current mode whenever plan is authorized. Headless agents (input policy deny) offer neither to new sessions: no one could approve leaving plan mode, so a plan session presents its plan as the final answer. Every agent can still run both, so a host takes up a session that recorded them, such as one a person started in the TUI. It queues read-only plan mode without approval, through the same safe boundaries as a host mode command. Already in plan succeeds without a change; unauthorized plan returns an error. The optional reason appears in the transcript. Later undecided calls see plan mode, and the next request gets its instructions. The model cannot select any other mode: only a host command or a person’s approval of ExitPlanMode may do that.

Input policy Question Plan
WithInputCallback the callback answers; an error, panic or timeout fails closed the callback approves or rejects
WithInputSuspend suspend; answer with zelk.Answer at the next Start suspend; ApprovePlan or RejectPlan
default (deny) authorization and correctness: the run ends blocked; preference: proceed on a stated assumption rejected; stay in plan mode

WithInputTimeout expires an unanswered request; the first of its answer or expiry wins, and an answer given at resume beats a deadline that passed while suspended.

Task{description, prompt, subagent_type, run_in_background?} runs a subagent (subagent) in a session of its own and returns its report, framed with its ID, outcome and whether it is partial, with control-tag imitations neutralized and its session named as evidence. The subagent’s tools and permissions are the parent’s or fewer; it can’t spawn subagents. At most 5 run at once. In the background, the call returns the agent ID; TaskOutput{agent_id, wait_ms} waits up to 270 seconds for the report (a longer wait_ms waits that and says so), and TaskStop{agent_id} interrupts it. Background subagents are stopped when the parent’s execution ends. A subagent running in the foreground moves to the background when the user asks (BackgroundCalls): the call returns its agent ID as if it had started there, its ChildStarted says it runs in the background, and the parent’s run is told when it finishes. It keeps its slot; when the parent already retains 128 results, it stays in the foreground.

StructuredOutput exists only in a session with an output contract (WithOutputSchema, WithOutputType[T], RunSchema, RunTyped[T] or a subagent’s OutputSchema); its input schema is the contract’s, recorded in Config.Output. One tool serves every session and validates against the recorded contract, so a parent and its subagents can have different schemas and a resumed session keeps the schema it started with (core/internal/builtin/output).

Bound Default What happens past it
Failed attempts: rejected calls and turns that end without a standing value 3 (WithOutputAttempts) the run ends invalid_structured_output; the report lists the last problems.
Problems listed per rejection 100 the rest are counted in one closing entry.

A rejection lists every schema problem with its JSON Pointer path, then every failed host validator by name. A value stands until an action that may change the workspace starts; then it is withdrawn and the model must call again.

Bash and Task support lifetime: "execution" (default) or "conversation" for background work, and each tells its agent when it ends, a conversation job by waking the session (completion wakeups). ProcessList and TaskList inspect states across messages; TaskMessage sends instructions to an active/waiting child. ProcessOutput/Input/Kill and TaskOutput/Stop retain their controls. See background ownership for lifetimes, limits, recovery and completion semantics.

On a model that loads tools natively, every MCP tool is deferred by default, as Claude Code defers them: a found tool is called by name and costs the cached prefix nothing. Elsewhere, where a deferred tool goes through CallTool, MCP tools are deferred when their schemas would take more than a share of the context window (10% by default, as Claude Code’s auto mode). An explicit WithDeferredToolThreshold applies on every model. A deferred tool is left out of the request, and the context lists it by name only. Built-in tools are never deferred, and a host can keep chosen MCP tools loaded (alwaysLoad).

A host’s own Go tool marked tool.WithDeferred is always deferred, on every model and whatever the threshold, and doesn’t count toward it: for a tool set too large to send whole whose tools most sessions use few of, such as the browser’s (docs/design/browser.md). The mark is recorded in the tool’s spec (deferred), so a subagent defers it too. WithoutDeferredTools sends it like any other tool. The loop’s own controls are never deferred, marked or not.

One search, every provider. ToolSearch is zelk’s own: it runs in the reducer from the recorded tools (select:a,b, an exact name, or the best 5 by the query’s words), so its answer is recorded and replays the same whichever provider is used, and a session that switches provider keeps its loaded tools. What differs by provider is only how that answer is sent.

Loading natively. A provider whose API loads deferred tool definitions mid-conversation without breaking the prompt cache says so with Capabilities.DeferredTools, recorded with the model like every other capability, so a request renders the same on replay. A ToolSearch result records the names of the tools it loaded (history.ToolResult.Loaded), and provider.Request.Deferred carries every deferred tool’s definition. Then:

  • Anthropic Messages: deferred tools are sent in tools with defer_loading: true, after the loaded ones so the cache breakpoint stays on a loaded tool (a deferred tool may not carry one). A ToolSearch result is a tool_result of tool_reference blocks, which the API expands into the definitions without touching the cached prefix (client-side tool search, documented by Anthropic).
  • OpenAI Responses: ToolSearch is sent as a client-executed tool_search tool with ToolSearch’s own parameters; the model’s tool_search_call becomes a ToolSearch call, and its result a tool_search_output whose tools are the loaded definitions, appended at the end of the context so the cached prefix holds (documented by OpenAI). Deferred tools aren’t sent up front: the output carries them. A search that loaded nothing is followed by a developer message with its text, since the output has no field for it.
  • The model then calls a loaded tool by its real name, as an ordinary function, which the loop already runs through the full action pipeline. CallTool isn’t offered.

Everywhere else (Gemini, Chat Completions servers, models without the feature) the result is the tools’ schemas as text and the model calls them through CallTool{name, arguments_json}, as before. A call by real name to a deferred tool is accepted on every provider, so a session that switches between the two keeps working. Gemini documents no equivalent: only restricting which tools are callable, with every definition still sent.

Which models. The adapter’s capability comes from what each API documents: Anthropic’s tool search on Claude Haiku 4.5, Sonnet 4.5, Opus 4.5 and later; OpenAI’s on gpt-5.4 and later. The CLI and TUI set it for those models on the vendors’ own endpoints only, since gateways and compatible servers may reject the fields; a library host sets it with WithModels or WithCapabilities.

The canonical subset is an authoring rule for zelk’s own tools. MCP schemas are foreign contracts whose server is authoritative. If existing harmless narrowing fits the canonical subset, the strict path is unchanged. Otherwise DefineOpenSchema preserves the original object-root schema with SchemaKind=open, stable key order and full local 2020-12/draft-07 validation. Invalid schemas or unresolved/nonlocal refs produce mcp_tool_skipped; supported schema features do not cause tool loss. MCP origins remain untrusted and permission-gated.

The validator is santhosh-tekuri/jsonschema/v6, chosen because google/jsonschema-go v0.4.3 misclassifies exact JSON numbers, and converting arguments to float64 would weaken integer constraints. Format constraints are asserted; content keywords remain annotations. The loader refuses external resources. Local refs, nullable unions, nested models, typed maps and untyped properties retain their server semantics. Errors reach the model as normal invalid-argument failures with instance paths. Open arguments pass through unchanged, including nulls. Providers render open tools non-strict, with explicit strict:false for OpenAI APIs and the JSON Schema field for Anthropic/Gemini. Looser provider decoding guidance never changes local validation.

The schema kind is part of the recorded spec and compatibility checks, not a property inferred anew on replay. ToolSearch returns it with the full contract; CallTool dispatches the same target validator and action pipeline. Child configuration and protocol/UI views carry the spec as ordinary data. Structured-output contracts remain canonical.