README
¶
Codehalter
An ACP-compatible AI coding agent that connects Zed, and any other Agent Client Protocol editor, to any OpenAI-compatible LLM server. Devcontainer-first and local-LLM-first: built around running inside a devcontainer, Alpine, Arch, Debian, Fedora, or Ubuntu, against llama.cpp (or Ollama / vLLM) on the host. Your real .git and identity are available inside the container, but the agent is instructed never to commit, push, or rewrite history on its own, only when you explicitly ask. Targets small-to-medium repositories.
Highlights
- Small and auditable: about 20k lines of Go (SLOC, tests excluded; ~23k with comments and blank lines), two small dependencies, one static binary.
- Local-LLM-first: designed and tuned for small/medium models on your own llama.cpp / Ollama / vLLM box, and works with hosted OpenAI-compatible APIs too.
- Spec-driven development (
/spec): point it at a directory of specification documents and it implements them one item per round, unattended, for as long as you let it run. An item is done only when a test names it and the whole suite passes; each one is its own commit. The bookkeeping is code, not model memory: a ledger of items, a coverage scan of your tests, and a fingerprint of the spec text each item was built from. The spec is the master: edit a section later and the next run redoes exactly that item, showing the model thegit diffof your edit; delete a section and the loop removes its code and tests by itself, but refuses when most of the spec disappears at once. The spec can be any markdown: headings become items, no id scheme required. First run just asks where the spec is and what to build from it. - One protocol, two front ends: codehalter speaks the Agent Client Protocol over stdio, so the editor is the UI. Native in Zed; usable from JetBrains and VS Code through their ACP integrations. No editor at hand?
codehalter --cliruns the client half in-process over a real pipe and gives you an inline TUI in the terminal, same agent, same protocol, no extra dependencies. - Prefix-cache consistency as a first principle: the rendered prompt stays byte- and position-stable turn over turn, so the server's KV cache keeps ~90%+ warm. The only deliberate cache break is a new MCP server's tools coming online; skills added mid-session ride as user messages until the next compaction folds them into the cached system prompt. At session open codehalter pre-warms the cache with a background 1-token call, so your first turn skips the prompt-processing wait (
prewarm = falseto disable). - Smart background compaction: after every turn, a separate LLM slot condenses the whole turn into a structured note in the background while you read the reply, so the notes are ready before they're needed. A large turn is one user prompt and everything codehalter does to answer it; a small turn is a single model call plus its tool results (no user involved). Compaction is purely reactive, with no token estimate. It's triggered by the server's context-full refusal (see History compression) and escalates: first keep the unfinished small turn plus the most recent ~10k tokens of completed small turns (folding everything older into the summary); if that still overflows, keep only the unfinished small turn. Then retry. With ≥2 parallel LLM slots the summariser runs beside the foreground turn; on a single slot it appends its instruction to the conversation itself (a prefix-extension), reusing the warm cache instead of evicting it; it just serialises briefly with your next prompt, so
parallel = 1works fully. - Lightweight plan → execute → document loop: each prompt is planned, executed with per-subtask self-verification, and documented only when the change is user-visible, no heavyweight agent framework.
- Devcontainer-first: on the first session codehalter scaffolds a throwaway devcontainer from your pick of Alpine, Arch, Debian, Fedora, or Ubuntu, installs itself via
curl+ the toolchain, and runs entirely inside it. Edits and build/test commands are sandboxed to the container. It works with your real.git, but is instructed never to commit, push, or rewrite history on its own, that stays your call. - Project onboarding: detects your stack, loads the skills for it and for your container, and bootstraps empty repositories. When a formatter is missing, its style is unpinned, or the project has no
AGENT.md, it offers a one-click "fix it?" card rather than just failing. - Reusable prompt macros: type
/<name> <args>to expand aTEMPLATE-<name>.mdinto a full prompt. Ships/grill-me(the agent interviews you about a plan until the whole design tree is resolved),/commit(drafts a commit message from your diff plus the conversation's intent, then commits, never pushes unless asked),/clean(deletes session log files from.codehalter/), and/settings(names thesettings.tomlin force, the ones it shadows, and re-probes every configured model); drop your ownTEMPLATE-*.mdfor project- or team-specific workflows. - Steer a running turn: type while it works and send it (in Zed that is Send Now, since Zed's own queue otherwise holds a message until the turn ends, which for a
/specloop is the whole loop); your message is queued by codehalter, not a cancellation: the turn picks it up before its next model call and carries on, so "also update the README" costs one round instead of the whole turn (a/specround can be an hour). It arrives as an ordinary user message, which is an append, so the prefix cache is untouched. The editor's stop button still interrupts. - Commit on request, message included: ask for a commit (or type
/commit) and the agent drafts the message fromgit status+git diff HEAD, using the conversation for the why, writes it to.codehalter/.git_commit, and runsgit commit -F …itself (or hands you the command). It never commits or pushes on its own. - Per-turn usage stats: every reply ends with a server-measured line such as
Done · ◷ 47m43s · ⚙ 28m12s · ↑ 193k · ↓ 106k · ≡ 152 · ⌨ 2 · 1.0k pp/s · 65 tg/s: ◷ the turn's time (waiting on you left out), ⚙ the part spent in tools and in waiting for their background jobs (builds, test suites, renders), ↑ the prompt tokens the server had to read (the cached prefix not counted again), ↓ the tokens generated, ≡ the model's replies, ⌨ what you typed or answered during the turn (left out when you typed nothing, as in a/specround), then prompt and generation throughput; Zed's context-window ring tracks the session via ACPusage_update. - The tool's name on every card: each tool card in the editor carries the programmatic name of the tool (
edit_file,run_command, an MCP tool's<server>__<tool>) beside its title, through ACP's tool callname, so a thread shows which tool ran and a client can count them. Cards that no tool opened (a clarification, a fix card) carry none. - External-change detection: codehalter remembers the exact bytes it wrote to each file, so when the next read finds something else (an editor's format-on-save is the usual cause), the tool result says so instead of leaving the model to work out on its own why its
old_textstopped matching. - Writes are checked before they land: a write or edit is refused when the file parsed before the change but does not after, with the parser's own error quoted and nothing written. The check runs the language's own parse-only tool (
gofmt,rustfmt,bash -n,python3for Python/JSON/TOML,node --checkon.mjs/.cjs,zig ast-check,ruby -c,php -l) and falls back to the project's formatter where there is none; a style-only tool like prettier never refuses anything, and a missing tool never blocks a write (plain.jsis left unprobed: node picks its module kind from the project'spackage.json, which a temp copy cannot carry). A file that does not exist yet is never refused for its content, so a new scratch or partial file can still be created; the first edit to it is judged. One scrambled region therefore costs a retry instead of a full test run to notice. - Missing syntax tools are offered at startup: when the tree holds a language whose parser isn't installed, one card names the tools and, on your yes, installs them with the container's own package manager (pacman, apt, dnf, apk, zypper), re-checks that each answers, and adds it to
.devcontainer/Dockerfileso the next rebuild has it. No model turn is involved, nothing is installed without your yes, and a run nobody is watching only prints the commands. Declining is remembered in.codehalter/checks.done.
Features
- Devcontainer scaffolding (5 base distros): the first session prompts
Alpine / Arch / Debian / Fedora / Ubuntuand writes.devcontainer/Dockerfile+devcontainer.jsonfor the chosen base. Each image installs a minimal toolchain (git, curl, sudo, Firefox) and installs codehalter into~/.local/bin(added to the containerPATH) under a passwordlessdevsudo user; for community-repo installs (the last resort in the skills' install order) the Arch variant adds theyayAUR helper, Fedora the COPR plugin, Ubuntuadd-apt-repository, and Debian pre-enables backports. Language toolchains (go, node, clang, …) are added per project on demand..gitis writable through the normal workspace mount; the scaffold asks whether to make it read-only, mount the host's~/.gitconfig(so the agent's git sees your identity) and forward the host SSH agent (both opt-in mounts list No first, so a scripted run leaves them off). The agent works with real git but is instructed never to commit, push, or rewrite history on its own, only when you explicitly ask. - Commit workflow: the agent never commits or pushes on its own. When you ask (or type
/commit), it drafts the message fromgit status --porcelain+git diff HEADwith the conversation as intent, writes it to.codehalter/.git_commit, and runsgit commit -F .codehalter/.git_commit(andgit pushif asked) itself, falling back to handing you the host command on an older read-only container. - Bring-your-own MCP:
.codehalter/mcp.tomldeclares each[[server]]as a child process to spawn (name,command,args,env); tools it advertises are registered as<name>__<tool>. The seeded file declares no servers. Reconciled when the next prompt starts (never mid-turn, since the tool list is part of the prompt prefix): add or remove a[[server]]and the change applies at the next prompt without restarting; failed startups surface as a red tool-call card and mtime-gate so they don't re-emit until you edit the file. - One slot is enough: one
[[llm]]entry works fully, even atparallel = 1: the background summariser rides the foreground context as a prefix-extension, so the KV cache stays warm.llm[0]owns the foreground KV cache; a second entry markedpurpose = "summary"hosts the per-turn summariser andweb_read's page reader instead (falling back tollm[0]when it is unreachable or keeps failing). Each entry'sparallel = Ncaps concurrent requests to match its server's capacity. - Plan → Execute → Verify → Document pipeline: every prompt is routed through a planning pass, an execution pass, and a self-verification pass. Failed verifications re-plan with the failure context; up to 5 attempts, and it gives up at the third time the same failure comes back (fuzzy detection, Jaccard similarity over issue words), so rephrasing a problem does not buy another round. A step that only ran out of tool calls does not count toward that: "tool loop exceeded 150 iterations" is the same sentence for any step, and three different steps that ran long had ended a turn as "the same failure 3 times" while the third had its round-trip test passing; the 5 attempts still bound them. Turns that wrote files end with a documentation pass that updates (or creates) the README when the change is user-visible.
- Red before green: a green test is only proof of a fix if it was red without the fix. So when a subtask changed test files and other files and its last test command (a
run_commandnamingtest,pytest,jest,vitestand the like) passed, codehalter takes the subtask's changes to the other files out, keeps its test changes, runs that command again as a card of its own (Checking without the fix: …), and puts every file back afterwards, whatever happened. A test that fails then shows the fault, and the subtask counts. A test that still passes does not: the subtask fails and goes back to planning with a note to reproduce the fault first, a test that fails on the code as it was, then the fix that turns it green (a model once rebuilt the release packaging for tab icons the code never set, and wrote a test that passed before and after). Test files are told apart by name and directory (_test,test_,.spec,tests/,__tests__/), documentation (.md,.txt,.rst,.adoc) is neither, a file over 4 MB is not copied for it, and the check is skipped when a change cannot be taken out cleanly./specrounds skip it: they have their own gates, and the check would run a round's tests twice. - Big-task decomposition: when the planner splits a request into multiple subtasks, the numbered plan is posted to the thread and execution starts, with no "Execute?" gate: the devcontainer is the approval, and every subtask is confined to it. A mid-run revision is re-posted as Plan updated, and each subtask gets its own full plan → execute → verify cycle.
- Agentic tool loop: the LLM can read, edit, search, and run tasks iteratively with file edits surfaced as diffs.
- Built-in tools:
write_file,edit_file(an exact snippet, a whole block between astartand anendline fragment, or several of either to one file as aneditslist, applied in order, all or none; anendthat only closes (},end,fi) means the block's own closing line, found by its braces or its indentation, and so does anendthat is on no line at all when a block opens on thestartline, since one model invented end markers for every whole-function edit),run_command(in-container only; listing isgit ls-filesand searching isgrep -n -Cthere, each doing in one call what a tool would, so there is neither; a command still running after two minutes is not killed but continues as a background job, the model gets what it printed so far and its exit later (when that is nothing because the command sends its output to a file of its own, the answer names the file and its size, and adds that Python buffers output to a file until it ends,python3 -u: an empty "output so far" was read as hung. Only a file the command could have written counts, one modified since the job started, which a>does when it truncates, so a redirect guessed from text that never ran names nothing), and a turn that ends onrespondwhile such a job runs is parked, not finished: the user can interject, and the job's exit or itswake_afterresumes the turn where it stood; a handed-over command with no output and no log growth for ten minutes is killed as hung; whatever a command leaves running when it exits is swept, by process group and, under a pty, by session, so atimeout-wrapped run cannot escape it: two greenxvfb-runsuites had each left an Xvfb behind; every stop, codehalter's or the one it tells the model (kill -TERM -<pid>; sleep 3; kill -KILL -<pid>), sends SIGTERM to the whole process group and SIGKILL 3 seconds later, since Zed's terminals start commands with SIGTERM ignored and four hung test runs sat out every polite stop for up to 32 hours; and at startup codehalter stops the jobs an earlier codehalter process left running, recognised by their pid files),run_background(a long run that ends on its own, a test suite or an experiment: the process outlives the tool call and the turn, the chat stays usable, and codehalter reports the exit code and last output by itself when it finishes: to the model before its next step when a turn is running, so it can start a test suite, keep editing, and find the result waiting, in one message with anything you typed in the same step; when it finished after the turn's last step, or while the chat is idle, a follow-up turn looks at the result and tells you, never an interruption; after you stop a turn, reports wait for your next message instead; a render of the project'ssnapshotrecipe is refused here and sent torun_command, since only a render there attaches its picture and counts as a look (one/specround started its render in the background, ended five seconds before it finished, and failed as never looked); a foregroundsleepis refused while a job runs, since the job wakes the model itself, and a job that does not exit can be givenwake_afterseconds to be looked at with its log tail while it still runs; a turn that ends with a new job still running says so once, and that the work resumes when it exits; arespondwaits for every job its step started, whatever the command is (a test run ending in; echo "exit=$?"once ended a/specround mid-run); waiting for a job by hand is refused, since its exit arrives by itself: apgrep -forpkill -fwhose pattern is in the command's own text is turned away at once, because the shell running the command carries that text, so a wait on it never ends and apkillkills the command (pgrep -xand a bracketed pattern such as[j]ustdo not match themselves), and a loop that polls a process (while pgrep …,until ! kill -0 $pid) is turned away while a job of the session runs, throughrun_commandandrun_backgroundalike; a second copy of a running job, the same command or another one writing a file the job writes, is refused with the job's name and how to stop it (a suite started again into the same log while the first still ran left that log reading 196 failed files, and the first run's result was gone; the files are the command's>andteetargets, read with here-document bodies left out, since a Pythonwhile step>=1:in one was taken for a write to a file=1and refused unrelated jobs); a step that stops its own jobs before they finish, by the pid codehalter gave for them, is warned at the second (and moved to the thinking sampler) and ended at the third, with that as the reason the replan sees: each restart is a new command with a new job number, so the repeat ladder never saw one, and a minimiser stopped at every two-minute handover and started again with a new seed burned a 100-call step that way, 40 times; input that arrives while the model writes arespond(a job's exit, text you typed) goes to it first and it answers again, since one step once ended on "the suite is still running" after the suite had finished; and a job whose processes use under 5% of a core and write no output for 5 minutes is stuck (a deadlock, a prompt for input, a loop polling for something that never comes:while pgrep -f "just test"; do sleep 5; donematched its own command line and held a/specround for six hours, because the reapedpgrepandsleepstill add a few CPU ticks every time) and is stopped with a note saying so, whether or not a step waits for it: a test that hung in an earlier step of a /spec round once sat in the container for seven hours, holding the turn-end line "running in the background"; the check reads/proc, so a silent build that computes keeps running, a job waiting for a file lock (cargo's build directory, apt's) counts as moving while the lock's holder works, a stopped process (state T) is stopped at once, since only a SIGCONT would let it go on; a job from an earlier turn never holds a step; jobs die with the session),run_server(a process that never ends on its own: a dev server, a watcher; withportthe call returns once something accepts connections there, up to 60 s, refused when the port is already taken; nothing waits for a server and it is never stopped as idle;{"stop": <job id>}stops it. Servers have their own tool because codehalter cannot tell one from a test run: guessed from a listening socket, a suite whose tests start fake servers was taken for a server and stopped being waited for, 19 times in one session, each time sending the model off to poll the suite),view_image(when the active model has vision),screenshot(a local HTML, SVG or image file rendered with headless Firefox, to check a rendering; a picture already in view, pixel for pixel, comes back as a note naming it instead of a second copy, and so does asnapshotrender codehalter attaches by itself: of 186 renders attached in one/specrun only 111 were distinct, and the copies pushed requests past Halogen's 64-picture limit),ask_user(a pick-one list, a free-text box, or both, sent as an ACP elicitation form),web_search,web_read(the page's text, paged from a cached body),respond,submit_plan. An output too large for the context is cut to head and tail with a hint on how to narrow the call; there is no tool to page a cached output. Plus any MCP-server tool, registered as<server-name>__<tool>. - Synthetic
respondterminal tool: the execute phase exposes arespond(message)tool that captures the model's final user-facing reply. The turn ends only whenrespondis called, so small local models stay inside the tool-calling grammar they handle best instead of having to decide "tool call vs free text" at exit time. Inspired by forge'srespond_tool. - Stuck-tool-loop detection: a model that re-issues the same call gets nudged once, then the next attempt escalates to a thinking-sampler retry instead of spinning indefinitely. When the step is ended for repeating, the calls it repeated are remembered for the rest of the turn: the replanned step that opens with the same call (a model copies its own call from the history; one
/specitem lost five steps to onegrepthis way) gets that call's output back with a note instead of a run, and a varied call that brings the same answer runs once and is told that changing the command does not change the answer; both until the step changes the project, after which a call is a re-check. A repeat is judged by what came back, not by what the model typed: the same answer with nothing changed since is no new information, whether the call was the same or varied (a newecholabel, a counter or a letter in a log name; one screen was rendered 98 times intosnap1.log,snap2.log, …, and a replay of 58 stored sessions found 620 such renders the old command-keyed check missed). "Nothing changed" is looked at, not guessed from the command: after each shell or MCP call codehalter fingerprints the files git lists as changed or new, by content, so a redirect to a log or a render that writes the same picture again is no change and an in-placesed -ior a Python heredoc is. A change makes a command's answer new again (a re-check after an edit), but not a read's (re-reading a file the edit did not touch still says nothing new). Across different calls only a substantial answer counts and only clock times are folded, since a count can be the news ("3 passed", "5 passed"); a failing edit's message and a job's launch note repeat only as the same call. An execution step that only reads for 20 calls in a row is nudged to act and moved to the thinking sampler; at 40 it ends, and the replan is told in numbers what the step spent its calls on (reads, edits, commands, the most repeated call). A step still editing and building at the 100-call cap gets 50 more, once, to finish. - Shell reads are served whole: a
run_commandthat only reads or searches (sed -n,awk,cat,grep,git show, ...) gets a 32 KB allowance instead of being cut to its first and last 600 characters, which made the model re-read the same file window by window. There is no tool for reading or searching files: models read through the shell whatever they are told. Left free to choose, Qwen3.8 flash read through the shell 101 times against 21 tool reads, and in replays a note on the shell result asking for the read tool moved none of 24 choices, a user message 6 of 24. So the shell reads are served well instead. Changes still go throughedit_fileandwrite_file, which are checked and shown as a diff; a change through the shell is neither. - Phase contract: each phase says how it may end (the executor with
respond, the planner with a usablesubmit_plan, the documenter also in prose). The executor's calls are not forced (tool_choice: "auto", not"required"): a forced call is named before the model weighs what it was just told, and Halogen starts the call for the model, so the name that came out was the last one called. Replayed 8 times each, the request right after a refused edit ("read it withread_filefirst") resent the refused edit 8/8 underrequired, also with the refusal reworded or a user message added, and calledread_file8/8 without forcing, reasoning off in both; underrequiredthe executor had made noread_filecall in 12 runs and edit loops of 90 to 299 calls. Not forcing also lets Halogen take the closed-think prefill, which it refuses beside a forced choice. Halogen resumes its cache after a continued assistant turn only from its last checkpoint, though, so every executor call re-read a median 5,360 tokens;thinking_off = "enable_thinking"on a server entry sendsenable_thinking: falseinstead of the prefill, and the next call re-read 106 to 306. Under Qwen3.8's default effort (xhigh, whose sentence opens the system block only while reasoning is on) planner and executor then render differently from the first token; Halogen keeps an entry for each, so a role switch re-reads what the other role added since its last call, and one executor call per session starts cold. A reply that misses it gets one corrective naming what is missing, which matters on servers that ignoretool_choice(Ollama) where a small model can answer in prose; a second miss in a row ends the step as a failure. A plan whosesubtasksarrive as a string holding the list is read too, including one missing its closing bracket (a habit of the model: five/specrounds in a row once failed twice each on it). The same goes for every tool, built-in or MCP: an argument its schema declares a list or an object that arrives as a string holding one is decoded before the tool runs, at any depth the schema describes (read_filehad taken"reads": "[...]"for a call without a path and answered "is a directory"); a string that is not exactly the declared JSON, or where the schema allows text, stays a string, and the history keeps the call as sent, so its wire bytes never change. Areadsstring cut off inside an item (the one seen was) serves the whole items before the cut and says where it was cut; aneditsstring cut off writes nothing, since a list of edits is all or none. - Skills for what the model cannot know: there are no per-language skills. A capable model knows its languages; the skills cover the environment instead.
SKILL-base.mdalways applies: containerised execution, the install order and install/persist policy, toolchain rules (patch vs minor version gaps, one package manager per JS project), how to read a "failed on line N" wrapper error, how to pin a formatter config that matches the code, plus the house code style (early return over nesting, named constants, short names, no bool parameters, comments that say why, private by default) and reply tone (no praise, no superlatives). OneSKILL-<distro>.mdfollows the container's/etc/os-release(Alpine/Arch/Debian/Fedora/Ubuntu),SKILL-justfile.mdfollows ajustfilein the tree, andSKILL-layout.md(check a rendered page withscreenshot, measure before editing) applies when the project has stylesheets or HTML. The rule that the agent never commits, pushes or rewrites the project's git on its own, only when you ask, lives inEXECUTE.md. They are read out of the binary, never copied into your project, so a skill improved upstream reaches every project at once; a file of the same name in.codehalter/overrides one, and aSKILL-*.mdof your own is added to the set. Every applicable skill rides in the system prompt (they total a few KB, cached once). One that becomes applicable mid-session arrives as a user message until the next compaction folds it into the prompt, so the cached prefix never moves. AGENT.mdin the system prompt: a project brief (AGENT.md,AGENTS.mdand the lowercase spellings, project root only) is folded into the cached prefix at session start, so every session begins already knowing what the project is, what it is built with and how it is tested, instead of spending its first turns finding out. A project without one is offered a card that writes it, but only once there is something to read (five files, ignoring.git,.codehalterandnode_modules): the model reads the tree, puts its draft understanding to you in a singleask_userbox to correct, and saves the answer. That check is live, so a directory you scaffold during a session is asked at the end of that turn rather than at the next session. It holds only what stays true between sessions, so nothing in it expires, and the prompt tells the model to update it in the same task that makes one of its lines wrong. While/specruns the brief is read-only (every round had planned a bullet for its item); otherwise, over its 12 KB budget, it may shrink but not grow: an edit that makes it longer is refused (in one day of/specrounds it had grown from 73 to 179 lines while the over-budget note sat in the prompt). There is no task-runner detection to go with it: the model reads yourjustfilelike any other file and runsjust testthroughrun_commandlike any other command.- Empty-project bootstrap: fresh directories are flagged; the LLM asks on the first turn which language/runner to scaffold before writing anything.
- Proactive fix / setup cards: before each turn codehalter audits the environment and, when something's missing, shows a single yes/no card instead of failing mid-task: every formatter the container is missing is folded into one card whose accepted turn installs and wires all of it, plus separate cards for an
mcp.tomlparse/start error and for a project with noAGENT.md. A project with no formatter config gets its own card, offered once per project (the ones that ask for work a project only ever needs once are recorded in.codehalter/checks.done, so declining is not re-asked at every session start; delete a line there to be asked again): the accepted turn measures the style the code is already written in (indent width, quotes, semicolons, line width), writes the config that encodes exactly that, and formats the tree in one formatting-only commit. This matters beyond tidiness, since an editor's format-on-save reindenting a file after a write invalidates the text the model just read and costs it failed edits. Accepting a card dispatches a synthetic fix turn; declining (or editing the file) dismisses it without re-nagging. - Slash-command prompt macros: a message of the form
/<name> <args>expands the matchingTEMPLATE-<name>.md(your copy in.codehalter/, else the embedded default) into a full prompt and runs it as a normal turn. Ships/grill-me(relentless plan interview) and/clean(deletes session log files from.codehalter/); macros that take an argument use{{}}and stop with a note if it's missing./cleanand/settingsare code-level commands rather than templates:/settingsprints whichsettings.tomlis being read and which candidate it shadows, then re-probes every[[llm]]so "which models work" is answered live rather than from the probe cached at session start. Drop your ownTEMPLATE-*.mdto add reusable workflows. - Spec loop (
/spec): plain/specin a project that has no loop yet asks three questions, each with up to three options read off the project (which directory holds the spec; where to build, the entry page's own answer first and then any directory that already holds a manifest; and with what, the page's answer, what that directory already is, and the keyword table's reading); the answers go to.codehalter/spec.toml, and editing that file is how they change./spec stop, sent while the loop runs, ends it after the round in flight: that round finishes, runs its tests and commits, the status is printed, and a later/specresumes from the ledger./spec abortstops it at once instead; what the round did so far stays in the project and the next/speccontinues from it. An abort also stops every background job the run started and drops their queued notes, and names them, so nothing it started wakes the model later (an aborted round's suite once reported three minutes after the abort and resumed the aborted work as a plain turn, which a second/spec abortcould no longer reach). Zed sends a message typed during a turn as a cancel first and the text only once the turn has ended, so the cancel itself already asks the loop to stop after its round, says so, and ends Zed's request; the loop goes on in the background holding the turn, and the text that follows,/spec abortincluded, reaches it there. The stop button alone does the same as/spec stop. Either way it implements a specification item by item until every requirement has a passing test. The bookkeeping is code, not model memory:- Ledger: requirement ids (flows
F2.3, parametersP.policy.x, toolstool:x, patterns configurable) are read from the spec by regex, and every headed section that defines no id (a file format, a screen, a rules list) becomes an item of its own. So does the text of a section above its first flow heading, when it holds at least 20 words (images and HTML comments not counted): a window's header bar and tab row described aboveF0.1had gone to no round. That item ends at the first flow, its round is shown the flows below as related sections, and its fingerprint covers only that text, so an edit to a flow does not reopen it. - Done: an item counts as done when a test the round added or changed is named after it (
f2_3_…in a test function's name, or in a test call's title such asit("f2_3 …"); a comment or a string that mentions the id does not count) and the project's test command passes. An item that starts with a user action also needs a test that fires the real widget and checks the effect: the logic test proves the rule, the widget test proves the wire, so a program of tested rules that no click reaches cannot pass. Codehalter checks both after every round and commits each item that passes. A directory git does not ignore that holds aCACHEDIR.TAG, the mark build tools put in their output, is left out of that commit and said, and the next item round is asked first to make git ignore it, or to delete it whole when nothing uses the project it was built from (a round had built a scratch project undertests/and committed its 556 MiBtarget/, 1161 files, which every latergrep -rof the tests then read). Its own run of the test command shows as a card whose last lines follow the run, and when it is cut short (/spec abort, the time limit) it is stopped with everything it started; it is registered like a job, so one cut off by codehalter's own end (a restart) is stopped at the next start; a round whose own full run passed after its last change is not run again. Any job codehalter stops goes with its whole process tree, read from/procbefore the first signal, so a helper a test started in a session of its own (a virtual display, a database) does not outlive it. - Gates on what a round wrote, for any language (comment syntax and the shape of a definition come from the file extension, the round's lines from
git diff): every free function the round adds to the program must be called by the program, not only by a test (a helper that exists only for tests says so in its name); the program may not stand in for the work: a line it adds that asks a for-test helper for its answer, or says the work is not built (todo!(),unimplemented!(),NotImplementedError, a "not implemented" or "stub" message), fails the round (naivepost counted its LLM, translation, speech and image calls done while the program only askedreply_for_test()and otherwise answered "no llm server here"); the project's linter (alintrecipe, elsecargo clippy,go vet, an npmlintscript orruff, set withlint_cmd) must find nothing in the lines the round wrote (a line it moved, deleted in one place and added in another, keeps its old findings: a refactor that moved one function out of an 11,000-line file had been held to deprecated calls that stayed unflagged in the file it came from; a file moved and not yet added to git counts as moved too, since the round's diff marks new files intent-to-add in a temporary copy of the index, never the repository's own, and lets git find renames: 481 test files moved intotests/suite/had counted as new code, old findings and all); a program file over the size budget (max_file_lines, 1500) may grow by at most 20 lines, so new code goes into a new file; and where the item's own section has a screenshot and the project has asnapshotrecipe, the round must have rendered that screen under the picture's own name: codehalter attaches the render beside the spec's picture (shots/04-prepare.pngbesidespec/img/04-prepare.png, scaled to the same height) and asks for every difference in arrangement, whether or not the round touched the UI (naivepost's Prepare screen passed on a test of its tooltips while the page was stacked where its picture is split left and right). Of the files a render writes, the one named like a spec picture is attached, so a page shot written after it as a sidecar does not take its place. Being shown the picture is not matching it, so once the rest of a round passes, codehalter renders each of the item's pictures itself withjust snapshot <name>, from the code as it stands, and asks a fresh call with no stake in the round to compare the two (SPEC-PICTURE.md), with the item's whole chapter, the sections it links in other chapters, the spec's standing-rules files that fit whole in what is left (every screen's picture shows the prototype's window frame, and what the rewrite dropped from it is said once there; one spec's prototype readme of 92 KB stays out) and the user's answers to its questions (the Cut screen's chapter does not link the shell's, and the check listed the run bar's "I'm feeling lucky", which replaces the prototype's chain, as a difference; the Prepare screen's source rows are specified in the shell's chapter, whose "prototype: ✂ … not reused" the check had not been sent, so it listed the ✂ the rewrite replaces as missing): only the arrangement counts, not the data, and not a control the spec text says the program dropped or replaced (the picture may be of a prototype). AMISMATCHfails the round with the named differences as its reason; a snapshot that writes no<name>.pngcounts as one; a look that cannot be had (the call fails, the reply does not parse) is said and logged and costs the item nothing. A render that matches is remembered by its bytes in the ledger ([pictures]), and the same final check renders the pictures of the items already done: one whose render still has those bytes costs a render and no call, one that changed is looked at again, and a done screen that no longer matches fails the round with its differences, named with the item it belongs to (overnight, rounds on the Cut page had lost the Prepare rows' ✂ and the Cut form's Thumbnails row, and each break was only seen when that screen's own item came round again, whose fix then broke the next). The note that comes with a picture failure says the fix is in the program, not in how the snapshot stages the screen, with one exception: a menu, popover or dialog open over the window is a surface of its own, so the snapshot has to draw the window and then that surface on top where it opens (two screens rendered the open menu alone, stretched over the whole window, and the rounds held back from the snapshot fix the note forbade). Before a render is looked at, codehalter renders the same screen once more: when two renders of the same code differ, the screen is not looked at and the item is not held to it, and the next item round is asked first to make the snapshot deterministic, the way a flaky test is handled; the note stays until a round's own renders agree (a snapshot taken 300 ms after start caught the Cut page's form column scrolled in one run and at its top in the next, so a done screen counted as broken in rounds that never touched it). The setup round is asked for a snapshot taken at an event the app raises itself once no shown widget still owes a setup step, confirmed by one more frame in which nothing moved, with animations off and each run in a fresh directory of its own. A round whose commit changes more than 50 files that no edit in it touched is said with the count andgit show --stat, not judged: one round rancargo fmtover the whole project and committed 859 files, every line of which the lint gate then took for the round's own; the round rules ask to format only the files a round changed. A round had looked at a page cut off at the top, an empty band under the run bar and labels drawn over each other, called the differences "content, not layout", and passed. The tests a round wrote get the same kind of independent look before it counts (SPEC-TESTS.md): a fresh call is shown the round's test diff, the item's text and the names of the other test files, and reports a test that checks another item's fact or the shared screen frame, repeats another test, waits a guessed amount instead of for the event, or uses a fixed path, port or display; what it reports goes back to the round as one more turn, never an attempt (one project had grown 537 test files, 354 of them named after no item, and one layout change broke 13 that each measured the same divider). A green round's changes must each be needed by a test: once everything else passes, codehalter takes each of the round's largest program changes back out alone (up tomutation_hunks, 6; a test file, an inline test module, a new file, moved lines and a change only to comments or string text are not put back), runs the tests named after the item (mutation_cmd, with{filter}the item's test token: derived asjust test {filter}for atestrecipe that takes an argument,cargo test {filter}, orgo test ./... -v -run '(?i){filter}', and none for a project with its owntest_cmduntil spec.toml gives one), and fails the round with every change those tests still pass without (in naivepost, putting each fix back by hand found five green tests that proved nothing, among them a wheel test that fired 50 where a notch is 1 and so agreed with the bug). The filtered command must first pass on the code as it is and show the filter in its output, else the check says so and stands down; the file is always put back, and one left changed by a codehalter stopped mid-check is put back at the next/spec. These checks also run once before a round is judged: what they find goes back to the model as one more turn of the same round, so a leftover uncalled function costs a turn, not an attempt. An item whose second attempt fails differently from its first gets a third. A round refused for growing an over-size file is not the item's failure but the code's shape: unless that was its only failure it still counts as an attempt, and either way the next round implements nothing and splits the files that blocked it, then the item goes on. A file split since an item last passed is not split again; its next refusal counts like any other, so a split that does not help cannot loop. Once a run, before the final pass, one more such round cleans up what the gates let through: the files over the budget, the functions nothing calls and the test helpers copied into several test files. A refactor round counts when one of those numbers went down, none went up, and the suite still passes. (A counted cadence, one refactor every ten finished items, used to schedule these rounds; it measured ledger size, and when the completion check reopened items the ledger shrank and no refactor came for two weeks while one file blocked round after round.) - Per round: the model gets only its item's section, the rows of the parameters it cites and the sections it links to.
- Pre-flight: the loop refuses to start while the spec has open
REVIEW/TBDmarkers or while git would ignore the files the rewrite creates. - Guards: the spec dir is read-only to the file tools while the loop runs. A planner question blocks its item instead of being guessed.
- The spec is the master: every finished item is recorded with a fingerprint of the spec text it was built from, plus when it was recorded and by which codehalter (tag, build date and commit); a parameter or tool row a test is named after is adopted the same way, minus the commit, while a flow or a section is done only by a round of its own. An item recorded under the test-name rule that no test is named after any more is open again; items recorded before that rule, which a comment may have carried, stay done and are listed so
/spec redocan rebuild them. Edit that section later and the next run redoes the item, showing the model thegit diffof the edit rather than the section again, from the commit the item was built at to the working tree, so an edit you have not committed counts the same (a diff toHEADhad shown an uncommitted edit as nothing, and the round built another bullet of the section instead); the loop reads the spec again before every round, so an edit made while it runs is picked up at the next one; delete the section and the run removes its code and tests by itself, in a round of its own, before changed and new items. When more than half of the recorded items vanish in one scan (all of them, for fewer than four) it deletes nothing and says the spec looks missing or unreadable (directory moved or deleted, or ids no longer recognised). A section that moves to another file or is retitled keeps its record instead of looking like one deletion plus one new item. - Only you start it, and chat stays chat: the loop runs when you type
/spec, never because a chat request looked big. A chat request is done as asked, without looking at the spec. /spec verify: goes over the chat sessions since the last check, and compares each request's file edits with the spec. It reports each contradiction with the spec line quoted and changes nothing; you decide which side wins. Too much for one round is checked in several, oldest first, and the check counts as done only after the last. A reported contradiction is not reported again by the next check.- Completion check: a test named after an item and a green suite do not say the program does what the spec says (naivepost counted its LLM calls done while they only ever answered "no llm server here", and its Prepare screen with the panels swapped). So once every item is done, blocked in this run or waiting on a question, every done item not checked since it was built is checked against its spec text, a few items of one spec file per round, pictures or not: find the code from where a user starts it (the UI,
main), follow the calls, and confirm every step, branch, widget, file and service call the text names, and that failures are handled; where the item's own section shows a screenshot (png, jpg, webp; an svg is a drawing), render the screen and compare what sits where. The answer is one line per item,DONEorMISSINGwith what is missing. A missing item is open again and its rounds are told exactly what is missing; a done one is markedcheckedin the ledger, so the next run looks only at what was built since, and a rebuilt item is checked again. Parameter and tool rows are checked through the flows that cite them. It runs once per/specrun, so an item still missing after its rounds is found by the next run, not in a loop. - Final pass: once every item is covered, one more round builds the program the way a user would, runs it, compares each screen with the spec's image, looks for the seams between items, and writes
<out dir>/README.mdwith how to build, run and test it and what is not done; it is committed when the test command passes, recorded in the ledger, and redone when the number of items done or not done moves. A failed round never counts as done just because its test exists: the item stays open until the suite passes. When codehalter's own test run fails, it runs the suite once more, unchanged: a pass then is a flaky test, not the round's failure, so the round counts, the failure is shown and kept in the ledger, and the next item round is asked to make that test deterministic first (two flaky widget tests had failed thirteen rounds that never touched them, and turned two items into questions). The same holds for a suite that is not isolated: codehalter runs the test command with a fresh$TMPDIRand compares the project's files (build and dot directories aside) and the top of the system temp directory before and after; whatever the run wrote outside its own temp directory is named, the round is not held to it, and the next item round makes those tests write into their own temporary directories first, since a test on a fixed path collides with itself when test files run in parallel (two suites at once into one tree had failed 196 test files). The prompts name the usual cause, for any language: a test that waits a guessed amount (a fixed sleep, a fixed number of event-loop turns, "until nothing is pending") instead of for its condition against a wall-clock deadline, which holds on a quiet machine and fails under load or when test programs run in parallel; the setup round puts one such wait helper into the shared test module and, for a compiled language, builds tests with line tables only (backtraces keep file and line; nobody attaches a debugger here, and full debug info made every test binary 160 MB and every link slow). Where a language builds every test file into a program of its own (Rust'stests/*.rs), the setup round makes one test program with the test files as its modules (tests/all.rsandtests/suite/) and every round adds its test there, and GUI tests run on the toolkit's own thread through its test helper (gtk4-rs#[gtk::test]) instead of each starting the application: one project had grown 476 test programs, 27 GB relinked after every change. What the next round, and a question to the user, see of a failed run is its end, with every long stack trace shortened to one line first, in any language (Rust frames,at …lines, Python'sFile "…", line N, Go'sfile.go:N): a Rust panic's backtrace alone had filled the last 4,000 bytes, and the assertion that said what failed was cut off. - Questions go into the spec: a round that needs a decision the spec does not make writes the question into the spec directory's
QUESTIONS.mdand the item waits there; the loop goes on with the others. The next/specputs the open questions to you as cards before its first round (the spec text and the options in the chat, the options and a text field on the card) and writes your answer after**Answer:**as if you had typed it there, an option by its number; a question you dismiss stays open and its item skipped. Answering in the file by hand works as before. A question must be answerable without opening the code, and code checks that before it is written: one sentence naming what to decide, the spec text that comes closest (codehalter finds it in the spec files and records where; an invented quote is refused), and two or three options, each with an example of what you would see (a label, a layout, a value). A question that misses any of that goes back to the planner once, with the note that a layout or order the spec states anywhere is no question; if the second try misses too, nothing is written and the item is blocked for the run. Each question names the codehalter version that asked it, and/spec statusflags those another version asked: three questions once came from a codehalter bug, and after the fix they only asked for a retry. Questions are separated by---lines. You answer after Answer: in the file, in your own words or with an option's number, and run/spec: the answer is spec from then on: every round of the item reads it until the item is built with it, and then codehalter takes the question out of the file, with the item's fingerprint taken without it, so its going is no change to the spec. An answer given in chat instead would be gone for the item's next round. - A stuck item becomes a question: an item that does not pass its attempts (two, three when the second failed differently) is not blocked in the ledger; codehalter writes a question for it into
QUESTIONS.mditself, so it does not hang on the model asking well: the item's spec line, what stopped the last attempt (the failure, the end of the test output), and three options with examples: try again as the spec says (the cause is gone: a bug fixed, a tool installed), change what the spec asks, or tell the rounds how to get past it. The item waits there like any question; the answer reaches every later round of the item. Only the project setup, which every item needs, is blocked for the run instead and stops the loop. Ledgers with the old[[blocked]]entries still load, and those entries are dropped, so their items get fresh attempts. - A failed model call is not the item's: when the LLM request itself fails (the server refuses it, or stays unreachable), the round does not count as an attempt and writes no question; the loop pauses and says why, and
/specresumes with the same item. Three items had become questions about a picture limit and stopped the loop as if they were stuck. - Stop and resume: a run ends when nothing is left but items waiting on a question, after the completion check and the final pass; it stops early after three items in a row that did not pass their attempts, which usually means one shared problem (a question the planner asked is no failure and does not count).
/specresumes and/spec statusshows coverage per chapter plus anything that changed in the spec since; state lives in.codehalter/spec.toml./spec redoalone has the model audit the program against the spec, build, run and look at every screen, and name the finished items that do not deliver; the list is shown and the loop starts on it at once, one item per round. A reopened item leaves the ledger, its tests no longer count until a round passes, and the round is told why, so work that passed its tests but missed the spec (a screen without its widgets) is redone without editing the spec.
- Ledger: requirement ids (flows
- Web tools:
web_search(DuckDuckGo) returns a list of result titles/URLs/snippets for the LLM to triage;web_readthen opens a chosen URL in headless Firefox and returns its text, paged from a cached body. Restricted to the planning phase so execution stays offline. - Image support: when the active LLM advertises vision, prompt images are passed through as OpenAI-style content blocks.
- Session persistence: conversations are saved as TOML files under
.codehalter/and can be resumed across editor restarts. - History compression: older turns are summarised to stay within token budgets. The unit of work is a large turn (one user-or-synthetic prompt plus every assistant step and tool call that answers it); within it, each model call plus its tool results is a small turn. After every large turn a background goroutine condenses the whole turn (not just the last reply) into a seven-section structured note (Goal / Constraints / Tasks / Progress / Decisions / Next Steps / Critical Context) on the
purpose = "summary"slot. The notes accumulate one per completed large turn in a shadow buffer that is persisted in the session TOML, so they survive a restart. Compaction is purely reactive, with no token estimate at all. It is driven by the server's context-full refusal and escalates in two steps. What counts as one is read off the server's own wording, whichever server it is: a 400 or 413 that names the context (llama.cpp'sexceed_context_size_error, the "maximum context length" of vLLM and SGLang, Halogen's "the prompt does not fit" and its limit on pictures per request), TGI's 422 forinputsandmax_new_tokens, or a reply that stops short of its token limit with the window full (Halogen 0.18.4 shrinks a budget to the room left instead of refusing it). A refusal about the budget alone, amax_tokensover the server's cap or over the whole window, is not one: folding would not help, so it surfaces. Ollama never refuses; it cuts the oldest part of the prompt silently, which codehalter cannot see. Step 1: keep the unfinished small turn plus the most recent ~10k tokens of completed small turns verbatim, and fold everything older (the completed large turns, instantly from their ready shadow notes, plus a synchronous summary of the older completed small turns) into the rolling summary, rotating it into an archive file; retry. A small in-flight turn (under the budget) is kept whole. Step 2 (only if the retry still 400s: the unfinished small turn alone is huge): keep only the unfinished small turn, retry. Each step strictly shrinks the context, so it terminates: once only the unfinished small turn is left, the 400 surfaces as a normal failure. If the summariser's call fails, the slice still leaves a clipped raw note, so nothing is rotated out unsummarised. With ≥2 slots the summariser runs on its own slot; on a single slot (parallel = 1, one[[llm]]entry) it extends the foreground context as a prefix-extension: cache-safe, just briefly serialised with your next prompt. - Standalone terminal client (
--cli): the same agent driven from a terminal instead of an editor.--clistarts the ACP client half in-process and connects it to the agent over anio.Pipepair, so the wire carries the identical JSON-RPC an editor would send, and there is no shortcut path that could drift from it. The TUI is inline: the transcript is append-only ordinary output (scrollback, selection and copy all keep working, no alternate screen) while a redrawn live region at the bottom holds the streaming reply, the current plan, in-flight tool cards and the tail of a running command. It advertises theterminalandelicitationcapabilities (sorun_commandandask_userwork) and deliberately notfs, so the agent reads and writes the disk directly.Ctrl+Ccancels the running turn rather than the process,Ctrl+Dor/quitleaves, and logs are redirected to.codehalter/cli.logso they never fight the screen. Piped or redirected output carries no escape sequences, so it doubles as a plain transcript. Started on the host in a project that has a.devcontainer/devcontainer.json, it also starts that container itself: the config is translated into a compose file on the fly (no devcontainer CLI, no new dependency),dockerorpodmancomposebrings it up, and the CLI re-runs itself inside with your terminal attached, printing which runtime it uses and which folder is mounted where. A key it cannot translate faithfully (features, lifecycle commands) is refused by name with thedevcontainer upcommand to use instead, never silently dropped. See Standalone CLI. - Update check that covers the container too: on every start
codehalter --cliasks the GitHub releases API whether a newer release exists (a conditional request, so an unchanged answer is not counted against the rate limit) and, if so, asks you before doing anything: yes downloads the binary for your platform, replaces the running one and restarts into it. The answer and the resolved tag then travel into the devcontainer, so the copy in there (baked into the image, otherwise stale until the next rebuild) updates itself in the same run without a second question or a second API call. A run with nobody watching (-p, redirected stdin) is told rather than asked. An editor session installs it in place: the banner names the release and a card offers to install it into the running container, with no shell in there and no image rebuild. The process you are talking to keeps running the old binary (its inode survives the replace); restart Zed and the same thread comes back on the new one. A downloaded binary must run and report the release tag that was asked for before it is allowed to replace anything, so a truncated file or a wrong-architecture build cannot break the install. Off withupdate_check = falseorCODEHALTER_UPDATE=skip. See Updating. - No modes; who answers depends on who is there: a chat request that is unclear gets a clarification card, setup asks before writing
.devcontainer/or.gitignore, andask_userasks you directly, since you started it and are watching (to have it decide on its own, say so in the prompt or in the card's text field). A/specloop never waits on you: its questions go into the spec'sQUESTIONS.md,ask_userinside a round is turned to that path, and the open questions are put to you as cards the next time you type/spec. Only when nobody can answer, a scripted--clirun with no terminal on stdin, the first option is taken, and the output says so. There was an Interactive/Autopilot switch; it went, because the context already says which applies, and Interactive could stall an unattended/specloop on oneask_usercard for hours. - Configurable LLM endpoints: one
[[llm]]entry per server and model; the two roles (thinking,execute) are the same entry with their ownparams_thinkingandparams_execute, and a second entry markedpurpose = "summary"takes the background work (see Configuration).
Prerequisites
- Go 1.26+, only to build from source; Install uses prebuilt binaries and needs no toolchain
- An OpenAI-compatible LLM server (e.g. llama.cpp, Ollama, vLLM)
- Firefox, if you want
web_search/web_readto work
Install
Prebuilt binaries, no toolchain needed. The script detects your OS/arch, downloads the matching binary from the latest release, and installs it.
Linux & macOS (Intel and Apple Silicon) installs to /usr/local/bin, or ~/.local/bin when that isn't writable:
curl -sL https://raw.githubusercontent.com/tbocek/codehalter/main/install.sh | bash
Windows: codehalter runs inside a Linux devcontainer, so install it under WSL: run wsl --install (once), open your WSL distro, and run the same Linux command above inside it. Native Windows isn't supported: the devcontainer's host-path bind mounts resolve ${localEnv:HOME}, which WSL provides and native Windows does not.
Updating
Releases are numbered v1, v2, ..., and an installed binary knows which one it is (codehalter --version; a build from source says dev and is left alone by everything below).
codehalter --cli checks at most once a day whether a newer release exists, and asks before doing anything about it:
codehalter v42 is available (running v41). Update now? [Y/n]
Answer yes and it downloads the binary for your platform, replaces the one you are running, and restarts into it, so the session you asked for starts on the new version. There is nothing to reinstall and no package manager involved. A run that nobody is watching is told rather than asked: with -p or with stdin redirected it prints the same line, adds Run codehalter --update to install it, and carries on.
One answer covers the container too. When the launcher starts a devcontainer for you, it hands the resolved release tag and your answer to the copy of codehalter inside it, so that one updates itself in the same run without asking a second question or spending a second API call. This matters because the container's binary was baked into the image and does not otherwise change until the image is rebuilt.
The other ways in:
codehalter --update |
check and install, no question asked, for a run nobody is watching |
codehalter --version |
the release tag this binary was built from, one line, which the updater of every installed release compares against before replacing itself |
codehalter --build |
the tag with the commit date and hash it was built at, as the banner shows it: codehalter v78 (2026-09-24, 73b7d58) |
update_check = false |
in settings.toml: never contact GitHub about releases |
CODEHALTER_UPDATE=skip |
the same for one run (CI); =yes updates without asking |
The check is one unauthenticated call to the GitHub releases API, cached in ~/.cache/codehalter/update.json for a day, so an unreachable network, a rate limit or an unwritable install directory each cost a line of output and nothing else: codehalter starts on the version you already have. A download is only allowed to replace your binary once it has been run and has reported the release tag that was asked for, so a truncated file, an error page or a wrong-architecture build never lands on top of a working install.
Build
To build from source instead (requires Go 1.26+):
just build
Or directly:
go build -o codehalter .
Configuration
Codehalter looks for settings in two places, in this order:
<project>/.codehalter/settings.toml(project-local, preferred)~/.config/codehalter/settings.toml(global fallback, used across every project that has no local file)
On first run with neither file present, codehalter prompts to write a commented skeleton into <project>/.codehalter/settings.toml. Edit it, then move it to ~/.config/codehalter/ to share across projects (a project-local file always wins over the global one, so delete it if you want the project to use the shared config).
Interactive setup
Alternatively, run the --setup flag to configure the LLM connection interactively:
codehalter --setup
This walks through server URL, model name, and API key (optional), validates the connection, and writes ~/.config/codehalter/settings.toml automatically.
Example settings
One [[llm]] array. Order matters: the first entry is the main connection, the rest are extras. Logs, the status line and the banner number slots, not entries, so each label is one place a call can run: a first entry with parallel = 4 is llm[0-3] (the foreground on llm[0], background work on it shows as llm[1]), and the second entry starts at llm[4].
- The first entry,
llm[0], owns the foreground session's KV cache, so its prefix stays warm across turns. Every plan/execute/verify/document call on the main session lands here. Typically a smaller/faster model. - A second entry, optional, marked
purpose = "summary": hosts the background work (the compaction summariser, and one-off side questions such as/spec's target suggestion) off the first, so its prefix cache isn't evicted. The banner says which entry carries what. Without it the summariser extendsllm[0]'s own context as a prefix-extension: cache-safe, just serialised.
parallel = N per entry caps how many concurrent LLM calls that entry accepts. The token is held for the duration of one LLM round-trip only, so between calls the slot is free for another caller, and pool size 1 simply serialises everything.
params is forwarded verbatim as the OpenAI request's extra body, put samplers and any model-specific knobs (enable_thinking, reasoning_mode, …) there. Core fields (model, messages, stream, tools) always win over params.
Keep params_thinking and params_execute identical in everything that is not a sampler. Samplers (temperature, top_p, max_tokens, …) never enter the KV cache key, so they can differ per role for free. Anything the server feeds to its chat template does not: chat_template_kwargs changes the rendering, and the server keeps a separate prompt state per rendering, so a role switch mid-turn (plan → execute) re-evaluates everything the other role appended since this one last ran (why). That is why codehalter turns reasoning off for the execute phase by appending an already-closed <think></think> for the model to continue, which is a pure extension of the prompt, instead of with enable_thinking = false. logy flags this class of change as ⚠ params CHANGED.
server is the base URL of your OpenAI-compatible server, the host root only (e.g. http://localhost:8080). codehalter appends the API paths itself: /v1/chat/completions for completions, plus /v1/models and /props for probing. Don't include a path.
Optional top-level keys (they must appear above the [[llm]] tables): prewarm = true (default on) fires a background 1-token call at session open so the server tokenizes and caches the prompt prefix before your first message; update_check = false stops the daily release check.
[[llm]]
server = "http://localhost:8080"
model = "qwen3.6-27b"
parallel = 1
params_thinking = { temperature = 1.0, top_p = 0.95, top_k = 20, min_p = 0.0 }
params_execute = { temperature = 0.6, top_p = 0.95, top_k = 20, min_p = 0.0 }
[[llm]]
server = "http://other-host:9001"
model = "qwen3.5-122b"
purpose = "summary"
parallel = 1
params_thinking = { temperature = 1.0, top_p = 0.95, top_k = 20, min_p = 0.0 }
params_execute = { temperature = 0.6, top_p = 0.8, top_k = 20, min_p = 0.0 }
Recommendation: a single
[[llm]]entry withparallel = 1works fully: the per-turn summariser rides the foreground prefix, so nothing is evicted and the one slot gets the whole context window. Useparallel = 2(or a second entry markedpurpose = "summary") if you want the summariser to run beside your typing instead of briefly serialising with it.
| Role | Purpose | Suggested temperature |
|---|---|---|
thinking |
Planning, document, history compaction | ~1.0 (diverse hypotheses, edge-case exploration) |
execute |
Tool loop, verify, web-page summarisation | ~0.6 (precise, faithful) |
Prompt files
The phase prompts live in the binary. Nothing is copied into your project, so a prompt improved upstream reaches every project on its next session instead of only the ones created after the change:
| File | Role |
|---|---|
PLAN.md |
Planning-phase instructions (clarity check, info retrieval, subtask JSON schema with per-subtask verify recipe) |
EXECUTE.md |
Execution-phase directives prepended to the user message; instructs the executor to run the verify recipe itself before calling respond |
DOCUMENT.md |
Decides when the change is user-visible enough to update the README, then edits it minimally |
SUMMARISE.md |
The per-turn note format the background summariser distils each turn into (feeds compaction) |
Plus SPEC.md, SPEC-SETUP.md and SPEC-REMOVE.md for the three kinds of /spec round, SPEC-PICTURE.md for the look at a screen beside its spec picture, SPEC-TESTS.md for the review of a round's tests, and the skills: SKILL-base.md (container, install order, toolchains, formatter config), one SKILL-<distro>.md for the container's OS, SKILL-justfile.md when the project has a justfile, and SKILL-layout.md (check a rendered page with screenshot, measure before editing) when it has stylesheets or HTML templates. There are no per-language skills: a capable model knows its languages, and the skills cover what it cannot know.
To change one for a project, put a file of that name in .codehalter/ and it replaces the built-in text; delete it and the built-in comes back. The startup banner names every such override (and the codehalter version doing the reading), so a stale copy can never take over unnoticed. That is the only reason one of these names exists on disk, so an override is something you chose rather than a copy you forgot. A SKILL-<anything>.md of your own is added to the set rather than replacing anything, and the same rule covers TEMPLATE-*.md macros. Only settings.toml and mcp.toml are written for you, because they are configuration rather than prompts and their comments are the schema.
Running the LLM server
With llama.cpp:
llama-server -m your-model.gguf --port 8080
With Ollama:
ollama serve
Then adjust server in your settings to match.
Example: a single 24 GB GPU
My setup: AMD Radeon RX 7900 XTX (24 GB VRAM), 128 GB system RAM, llama.cpp, running Qwopus3.6 27B (Q5_K_S) at 80k context per slot. The config below is a llama.cpp router config (each key maps to a llama-server flag), curated to the settings that actually matter for codehalter on this hardware. I left out a couple of cosmetic startup flags (no-mmap, no-warmup).
# Global defaults for every hosted model:
[*]
n-gpu-layers = 99 # offload all layers to the GPU
flash-attn = on # smaller KV cache, faster attention
cache-type-k = q8_0 # quantize the KV cache so a long context fits in 24 GB
cache-type-v = q5_1
cache-reuse = 64 # reuse a cached prefix down to 64-token chunks
cache-ram = 65536 # host-RAM prompt cache, 64 GiB ceiling (see below)
batch-size = 1024 # prefill (prompt-processing) batch
ubatch-size = 512
jinja = true # use the model's chat template (correct tool-call format)
threads = 8
threads-batch = 8
# The model codehalter points at:
[Qwopus3.6-27B]
# url = https://huggingface.co/Jackrong/Qwopus3.6-27B-v2-MTP-GGUF
model = /mnt/models/Qwopus3.6-27B-v2-MTP-Q5_K_S.gguf
parallel = 2 # two slots: foreground turn + concurrent summariser (1 works too, see below)
ctx-size = 160000 # total across slots, so 80k per slot at parallel = 2
spec-type = draft-mtp # speculative decoding via the model's MTP head
spec-draft-n-max = 3
cache-type-k-draft = q8_0 # KV quant for the speculative draft
cache-type-v-draft = q8_0
Why these matter for codehalter specifically:
parallel = 2,ctx-size = 160000. Two slots let the per-turn background summariser run beside the foreground turn; they split a 160k context into 80k each.parallel = 1also works: the summariser then extends the foreground prefix (cache-safe, briefly serialised) and the single slot gets the full 160k.cache-reuse = 64. Lets the server reuse a cached prefix even when a chunk changes, down to 64-token granularity. This pairs directly with codehalter keeping the rendered prompt byte-stable turn over turn, so most turns hit the cache instead of reprefilling.cache-type-k = q8_0/cache-type-v = q5_1/flash-attn = on. Quantizing the KV cache plus flash attention are what let an 80k context sit in 24 GB alongside the Q5 weights.spec-type = draft-mtp,spec-draft-n-max = 3. The model ships a Multi-Token-Prediction head; speculative decoding with it drafts a few tokens per step and lifts generation throughput.
Does 64 GiB of cache-ram make sense for one user?
cache-ram is llama.cpp host-memory prompt caching: the server keeps computed KV states of past prompts in system RAM, so a request sharing a prefix with a cached one restores it instead of recomputing. It is a ceiling, not a reservation (default 8192 MiB; -1 unlimited, 0 off), so it only uses what it actually caches.
The common advice is to skip it for single-user chat, where every prompt is unique and nothing hits the cache. codehalter is the opposite workload: it keeps the prompt byte-stable across turns, so prefix reuse is the norm (for example, restoring the foreground prefix after another request churned the slot). So enabling it is right here.
64 GiB specifically is more than one user needs, but harmless. A single user's working set is a few states (the growing foreground context plus a couple of side ones), which stays well under 64 GiB, and because the value is only a ceiling it never costs RAM it is not using. On 128 GiB there is no downside to the high cap. If you want the headroom back, something in the low tens of GiB covers one user with margin. Keep it finite rather than 0: there is an open bug where the ceiling can be ineffective on Linux and OOM the server when caching image prompts, and a finite cap with free RAM (your 64 of 128 GiB) stays on the safe side of it.
Standalone CLI
No editor required. --cli runs codehalter's own ACP client in the same process and drives the agent over a pipe, so what reaches the agent is byte-for-byte the protocol Zed would speak:
codehalter --cli [--cwd DIR] [--resume [SESSION_ID]] [--list] [-p PROMPT] [--rebuild]
--cli run the standalone terminal client instead of an ACP server
--cwd DIR project directory (default: current directory)
--resume [ID] continue a stored session; without an ID, the most recent
one for this directory
--list print the stored session IDs for this directory (newest
first) and exit
-p PROMPT run one turn and exit, instead of opening a prompt. The
exit status is 0 only when the turn finished normally,
so a script can branch on it.
--rebuild rebuild the devcontainer image before starting it
Other flags: --version prints the release tag, --build its build date and
hash, --update installs the newest release over this binary, --setup
reconfigures the LLM connection.
Like every other codehalter run this one is devcontainer-first: it refuses to start outside a container. Starting that container is its own job, though.
The launcher. Run codehalter --cli on the host in a project that has .devcontainer/devcontainer.json and it does not start the agent at all. It reads that file, translates it into a compose file, brings it up with docker compose (or podman compose), and re-runs itself inside the container with your terminal attached:
$ codehalter --cli
codehalter cli
no container here, so docker compose starts one: project myproject-1c881a, from Dockerfile
/home/you/src/myproject → /workspaces/myproject (bind mount, read-write: edits inside are edits here)
building the image first, which takes a while; later runs reuse it
When an editor already started a container for the project (Zed, VS Code and the devcontainer CLI label theirs with devcontainer.local_folder), the launcher uses that one instead of composing a second beside it: it starts it if it is stopped and runs the CLI in it with the same user, working directory and environment, and leaves it as it found it on exit. A second container would split the build cache and the jobs, and a project whose runArgs give the container a fixed --name could not start at all. --rebuild is refused there, since it would build that second container; rebuild from the editor instead.
Inside a container it skips all that and just starts, so the same command works in both places. Ctrl+C still belongs to the agent inside; the launcher ignores it and passes the child's exit status back, which keeps -p scriptable from the host.
The container is left running when you leave, so the next codehalter --cli is one compose exec away, a tenth of a second rather than a start. Set "shutdownAction": "stopContainer" in the devcontainer file to have it stopped instead. Compose recreates the container by itself when the translated service changes, an image built from a Dockerfile is rebuilt when that Dockerfile changes, and --rebuild forces a rebuild.
This is a launcher, not a devcontainer implementation. It reads the config from any of the three places the spec allows (.devcontainer/devcontainer.json, .devcontainer.json, or a single .devcontainer/<name>/devcontainer.json) and translates the keys that have a compose equivalent (image, build, runArgs, containerEnv, remoteEnv, containerUser, remoteUser, mounts, workspaceFolder, workspaceMount, forwardPorts, overrideCommand, init, privileged, capAdd, securityOpt, shutdownAction, and a dockerComposeFile project it hands through). It expands ${localEnv:NAME}, ${localWorkspaceFolder}, ${containerWorkspaceFolder}, ${devcontainerId} and their basename forms, plus ${containerEnv:NAME} in remoteEnv, which is read out of the container once it is up. Forwarded ports are published on 127.0.0.1, as the editors do. Editor-only keys are ignored without being expanded, so the ${workspaceFolder} and ${env:HOME} that live in customizations.vscode.settings are left alone. Anything else it refuses by name, rather than quietly starting a container that is not the one you asked for:
$ codehalter --cli
.devcontainer/devcontainer.json uses features, postCreateCommand, which the built-in launcher does not implement
Start it with the devcontainer CLI instead:
npm i -g @devcontainers/cli
devcontainer up --workspace-folder /home/you/src/myproject
devcontainer exec --workspace-folder /home/you/src/myproject codehalter --cli
Four things differ from devcontainer up even for a config it accepts, and the first two print a note: line when they apply:
updateRemoteUserUIDis not honoured: the container user keeps the uid baked into the image, so files written in the workspace can come back owned by someone else.userEnvProbeis not honoured: commands run with the image's environment, not with one probed from a login shell.${devcontainerId}is derived from the workspace path, so it does not match the id the devcontainer CLI computes for the same project.shutdownActiondefaults to leaving the container running, where the spec's default is to stop it. Write it down explicitly to get the other behaviour.
None of this is required: devcontainer up yourself and run devcontainer exec --workspace-folder . codehalter --cli, and the launcher never runs.
The interface is an inline TUI, not a full-screen one. The transcript is plain append-only output, so your scrollback, mouse selection and copy behave exactly as they do for any other command, while a small live region at the bottom is redrawn in place with the streaming reply, the current plan, running tool cards and the last few lines of any command in flight. Redirect the output to a file and the escape sequences vanish, leaving a readable log. The input row is part of that live region and stays usable while a turn runs: a line typed then goes to the agent at once and steers the running turn (/spec stop included), as typing does in Zed; Backspace, Ctrl+U, Ctrl+W and pasting work, Ctrl+V attaches the picture on the clipboard (macOS through the system's osascript; Linux on Wayland through wl-paste from wl-clipboard; it shows as [image 1] in the line, and deleting that marker leaves the picture out; only when the model takes images), Ctrl+C interrupts the turn (not the background jobs, which run in process groups of their own), Ctrl+D on an empty line leaves. A /spec loop is one turn that runs for hours, and with input read only between turns nothing could be typed during it. The status line above it is one row: the turn's time, what the model is doing right now, the context in use, the last call's prompt and generation speed, and the phase last (67m12s · llm[0] ↑426kb ↓37 tok · 124k/262k ctx · 812 pp/s · 51 tg/s · executing), refreshed every second and after every call. A running tool shows as its own card, so the status line does not repeat it. In Zed the phase entry of the plan card carries the same (Executing · 67m12s · llm[0] ↑426kb ↓37 tok · 812 pp/s · 51 tg/s), less the context, which Zed's ring shows.
Client-side commands:
| Command | Effect |
|---|---|
/help |
client commands, then the agent's own commands and TEMPLATE-*.md macros |
/sessions |
stored sessions for this directory, newest first |
/new |
start a fresh session in this directory |
/resume [id] |
switch to a stored session, or pick one from the list |
/cwd |
project directory and current session id |
/quit, /exit |
leave (same as Ctrl+D); a bare exit or quit does too |
Anything else starting with / is handed to the agent, so /commit, /clean, /settings, /grill-me and your own macros work unchanged.
Ctrl+C cancels the turn, not the process: the agent stops where it is and reports why, so the conversation survives an interrupt. While idle it says so instead of exiting; a second Ctrl+C within two seconds does leave, as does Ctrl+D. Permission cards and ask_user forms are rendered as numbered lists, with an empty line to dismiss. Diagnostics go to .codehalter/cli.log instead of the screen (tail -f it in another pane when you want to watch the protocol); the file is truncated on every run.
One turn, no prompt. -p runs a single turn and exits, which is the form to reach for in a script, a git hook or CI:
codehalter --cli -p "run the tests and fix what fails" || echo "turn did not finish"
It prints the same transcript, opens no prompt row, and exits 0 only when the turn ended normally. A cancellation, a refusal or a protocol error exits 1, so the shell can branch on it. Questions still read from stdin, so a script can pipe its answers in (yes 2 | codehalter --cli -p …). Without a terminal on stdin, a card the script does not answer with a valid number (input ended or < /dev/null, an empty line, anything else) takes its first option and the output says so; a question with only a text box is left unanswered. Fix cards found during setup are offered after the turn, not before it. With piped input to the repl, the turn in flight when the input ends still finishes before the CLI exits.
At startup it also checks, at most once a day, whether a newer release exists, and offers to install it before anything else happens (see Updating). The answer travels into the container with the launcher, so one yes updates both.
Terminal geometry is read with stty size, keeping the binary dependency-free and platform-neutral: at startup, at each turn and, on Unix systems, whenever the terminal changes size (SIGWINCH), which redraws the live region at the new size at once, since a /spec loop is one turn that runs for hours. Elsewhere the next turn picks up the new size.
Zed setup
Add to your Zed settings (~/.config/zed/settings.json):
{
"agent_servers": {
"Codehalter": {
"type": "custom",
"command": "codehalter"
}
}
}
Open the agent panel (Cmd+? / Ctrl+?), click +, and select "Codehalter".
Sandboxing with a devcontainer
Codehalter edits files and runs build/test commands. Running it inside a devcontainer sandboxes those actions to a throwaway environment, keeps the project's toolchain pinned, and means the same setup works on every machine. Zed launches ACP servers inside the container when you open the project in one (Ctrl-Shift-P, then type "open dev container"), so codehalter, Firefox, and the LLM endpoint must be reachable from there. The startup banner reports Container: devcontainer when this is wired up correctly. From a terminal there is nothing to wire up: codehalter --cli starts the container itself (see Standalone CLI).
Codehalter scaffolds the devcontainer for you. On the first session in a project without a .devcontainer/ directory, it prompts for a base distro, Alpine / Arch / Debian / Fedora / Ubuntu, and writes the chosen Dockerfile + devcontainer.json:
| Distro | Base image |
|---|---|
| Alpine | alpine:3.24 |
| Arch | quay.io/archlinux/archlinux:base-devel (+ yay AUR helper) |
| Debian | debian:trixie |
| Fedora | fedora:44 |
| Ubuntu | ubuntu:26.04 |
Each image installs a minimal toolchain (git, curl, sudo, openssh, Firefox), creates a passwordless dev sudo user, and installs codehalter into ~/.local/bin (added to PATH). Language toolchains (go, node, clang, rust, …) are added per project on demand, codehalter's skills and fix-cards offer to install what a given repo needs rather than baking everything into the base. All five seed a devcontainer.json that:
- Bind-mounts
~/.config/codehalterread-only sosettings.tomlis shared across every project as the global fallback (a project-local.codehalter/settings.tomlstill wins when present). - Sets
containerEnv.DEVCONTAINER=trueso codehalter's startup banner showsContainer: devcontainerand therun_commandtool is registered. - Adds
--add-host host.docker.internal:host-gateway, so the container can reach services on the host (e.g. a local LLM server) on Linux too, where Docker does not define that name by itself.
.git comes in with the workspace mount, read-write, so the agent can run git fully, including git commit / git push, but it is instructed to do so only when you explicitly ask, never on its own initiative or as a side effect. The scaffold then asks about three optional mounts, each added only when you say yes (and only when its source exists on the host, since a missing bind source fails the container start):
- Read-only
.git:source=${localWorkspaceFolder}/.git,target=${containerWorkspaceFolder}/.git,type=bind,readonlyshadows the writable copy, for a hard guarantee rather than an instruction; the agent then falls back to handing you the commit command. Default: no (listed first, so a scripted run takes it),.gitstays writable and no line is added. ~/.gitconfig(read-only), so the in-containergitsees your realuser.name/user.email/ signing key without any per-project setup.- Host SSH agent: binds
$SSH_AUTH_SOCKto/ssh-agentand setsSSH_AUTH_SOCK, sogit push/sshcan use your host keys. This gives the container every key loaded in your agent, so it is opt-in: No is listed first, so a scripted run leaves it off.
After the container is built, point Zed at the in-container codehalter binary:
"Codehalter": { "type": "custom", "command": "codehalter", "args": [], "env": {} }
If your LLM server runs on the host, change server in ~/.config/codehalter/settings.toml to http://host.docker.internal:8080. For an existing language-stack devcontainer (e.g. mcr.microsoft.com/devcontainers/go:1), copy the mounts above into its devcontainer.json and run curl -sL https://raw.githubusercontent.com/tbocek/codehalter/main/install.sh | bash in its image, no need to start from one of the scaffolded bases.
Commits and pushes from inside the container
The agent never commits or pushes on its own, only when you explicitly ask. When you do (a plain request, or the /commit macro):
-
It drafts the commit message from
git status --porcelain+git diff HEAD, using the conversation for the why, and writes it to.codehalter/.git_commit. -
It runs the commit (and push, if you asked) itself, with that message:
git commit -F .codehalter/.git_commit && git push -
It reports the commit subject (and branch, if pushed) in its reply.
Fallback: on a container that mounts .git read-only (the scaffold's opt-in), or where git push lacks SSH auth, the agent doesn't fight it, it suggests the exact host-side git commit … && git push for you to run instead.
.codehalter/ is gitignored on first bootstrap, so the draft file never accidentally gets staged.
Glossary
These words mean one specific thing each. The code uses them in comments; this is the reference.
Session: one Zed thread. Persisted to .codehalter/session_<id>.toml and reloaded on restart. One user, one project, one conversation.
Large turn (also "user turn"): one user prompt until the ✅ Done line, i.e. until you can type again. One orchestrate() call. It contains the whole pipeline: plan, every subtask, every replan, document. Elsewhere in this README the word "prompt" means this.
Small turn (also "harness turn"): one LLM request/response plus the tool results it triggered. Stored as one assistant message, stamped with its phase and with that call's prompt_tokens. A large turn is typically tens of small turns.
In-flight turn: the large turn currently running, and inside it the small turn not yet answered. Compaction always keeps the in-flight small turn; that is the one thing it can never fold away.
Phase: which stage of the pipeline a small turn belongs to: plan, execute or document. Recorded per message.
Role: which params table a call is sent with: thinking (plan and replan) or execute (subtasks, document, web page reading). Both roles are the same [[llm]] entry, i.e. the same server and the same model. Only params_thinking vs params_execute differ.
LLM call: one HTTP request to the server. This is the unit the prefix cache sees. One small turn is one LLM call.
Rendering: the flat token sequence the server's chat template produces from (messages, tools, chat_template_kwargs). You send JSON; the server caches tokens. The same conversation sent with two different chat_template_kwargs produces two different renderings.
Prefix cache / KV slot: the server-side KV cache holding one rendering. parallel = N gives the server N slots. Reuse is longest-common-prefix from token 0: position 40,000 is reusable only if tokens 0 to 39,999 are identical to last time.
Rewind: an LLM call whose cached count came back below the previous call's prompt count, meaning the server re-read tokens it already had. Logged as CACHE lines in the session log and counted on the ✅ Done line.
Compaction: the reactive fold triggered by the server's context-full refusal (see History compression), which includes Halogen refusing a request with more than 64 pictures (it says so in the stream: a render loop had attached 98, and every later request of the session was refused until a fold dropped the older ones; the summary keeps their ids). Keeps the in-flight small turn (plus recent completed small turns on the first step) and folds everything older into the Summary.
Turn note: a seven-section structured note the background LLM writes about each completed large turn.
Shadow buffer: where turn notes accumulate between compactions. Persisted, so it survives a restart.
Summary: the rolling prose that leads the context after a compaction. Folded summary is a shorter rewrite of it, produced in the background and used as the base of the next compaction, so summaries do not grow without bound.
Background LLM: the purpose = "summary" entry. Runs turn notes and the git-commit drafter off the foreground slot. With only one slot available it rides the foreground context as a prefix extension instead.
Why a role switch can cost a full re-prefill
Inside a single large turn the role changes at least once: plan runs on thinking, then the first subtask switches to execute. Every replan switches back to thinking and forward again, so a turn that replans twice switches five times. If params_thinking and params_execute differ in anything that reaches the chat template (chat_template_kwargs above all), those calls ask the server for two different renderings of the same conversation. A rendering the server has never held costs a full prefill; after that it may keep both and serve either, in which case a switch costs only what was appended under the other rendering since you last used this one. Probed against llama.cpp on a 13,972-token prompt: adding enable_thinking = false returned cached = 0, and the same request repeated returned cached = 13,932. So the floor is one full re-prefill per rendering and the running cost is roughly double the prefill work of a single rendering, since each switch re-reads what the other role wrote. Samplers (temperature, top_p, max_tokens, …) never enter the rendering and may differ freely.
Measured on one 11.6 h session against a single-slot 27B: 436 LLM calls on the foreground connection, 35 role switches, one every ~12 calls. With both roles rendering identically those switches re-read 121,748 tokens in total (median 1,526 each, 97.4 % cached), which is 4.2 min at the server's measured 483 tok/s. The same 35 calls carried 2,414,262 prompt tokens between them, so re-prefilling each from scratch is 83.3 min. Six calls in that session did lose a prefix, and only one was a rendering change: the stuck-in-<think> retry, which then flipped enable_thinking. Entering that window cost 71,997 tokens at cached = 0 and leaving it 27,585 more, the span generated while the flag was on. The other four losses were idle evictions and noise.
codehalter no longer does that. Every call that wants reasoning off, the whole execute role (subtasks, document), appends an already-closed <think></think> as a trailing assistant message and asks the server to continue it, which is exactly what the template emits for enable_thinking = false but reached by extension rather than re-rendering. Same suppression, no divergence: probed on that server with a tools array attached, the prefill returned cached = 14,263 of 14,273 and still emitted its tool call, where the kwargs flip returned cached = 0. The detector above stays because a settings.toml whose two roles disagree reproduces the old cost exactly. res/settings.toml carries the same note next to the params tables.
How it works
- Zed spawns
codehalteras a subprocess and communicates via JSON-RPC 2.0 over stdio. - On session start, the agent indexes project files, probes image support on the configured LLM, folds the project's
AGENT.mdand the applicable skills into the system prompt, and reports what the container has and is missing. - Each prompt runs through the pipeline:
- Plan, the
thinkingLLM analyzes the request with read-only tools and gathers external info via web tools if needed. It gathers what it needs to decide and names files for the executor rather than reading everything on its behalf: a planning round reasons for ~900 tokens, an execute round for ~90, so reading belongs in the cheap role. Past 20 rounds it is asked to submit with what it has, and past 6,000 generated tokens without a plan it is asked to name what blocks it and then either say the request rules itself out, plan a subtask that runs what it was working out, or take a different approach: on an impossible request this turned a 13k-token hunt for workarounds into a refusal, and a JDK upgrade plan went from 13 minutes to 4. A plan that is only ananswergoes back once, asking whether the request was a question: the planner had written "planned a subtask that runs it" intoanswerand sent no subtasks, and in replays the check turned each such reply into subtasks while every real answer was kept. If the request is ambiguous it asks you a multiple-choice clarification first instead of guessing (at most three per planning phase, then it goes on with its last plan); if it's a pure question it answers directly with no execution pass (report_only). Otherwise it emits an array ofsubtasks, each with its ownverifyrecipe, which are posted to the thread as a numbered plan and then run. - Work, for each subtask the
executeLLM runs a single bounded tool-calling loop where it edits, runs commands, and then runs the verify recipe itself before callingrespond. Mid-run it can callsubmit_planto revise the remaining subtasks in place (a plan-upsert) when execution reveals the plan needs adjusting, no full replan. A stuck subtask bounces back to replanning after 8 failed rounds, with a 100-iteration backstop against runaways. File edits are shown as diffs. - Replan on failure, if a subtask bounces, the executor returns without calling
respond, a tool exits non-zero, or the subtask's test command still passes with its code changes taken out and its test changes kept (red before green, outside/spec), the orchestrator records the failure reason and re-plans (up to 20 replans per prompt). When the same failure recurs (Jaccard over issue words ≥ 0.6), the replan note escalates to "the prior fix didn't work; propose a structurally different approach." - Document, fires once at the end of a successful prompt: the
executeLLM (the same connection the subtasks just ran on, so it inherits their warm prefix) checks againstDOCUMENT.mdwhether the change is user-visible (new feature/flag/API/dep, install or config change) and, if so, updates or creates the project README. Routine refactors and bug fixes are skipped.
- Plan, the
- Prior subtasks' assistant replies stay in history so later subtasks have context.
- Conversation history is persisted to
.codehalter/session_<id>.toml, written atomically (a temp file beside it, synced, renamed over it), like the/specledger andQUESTIONS.md: a crash leaves the old file or the new one, never half of either. After every turn a background goroutine on thepurpose = "summary"slot condenses the whole turn into a seven-section structured note that accumulates in a shadow buffer (itself persisted in the session TOML, so it survives a restart). Compaction is purely reactive: driven by the server's context-full refusal and escalates in two steps. Step 1: keep the unfinished small turn plus the most recent ~10k tokens of completed small turns verbatim, and fold everything older into the rolling summary; retry. Step 2 (only if the retry still 400s): keep only the unfinished small turn; retry. Each step strictly shrinks the context, so it terminates. With only one[[llm]]entry (orparallel = 1) the summariser extends the foreground context as a prefix-extension on the same slot: cache-safe, briefly serialised with the next prompt.
Compared to other harnesses
Codehalter borrows two ideas: the synthetic respond terminal tool from forge, and explicit terminal tools from pi/coding-agent, though codehalter declares which tools end the loop per phase (a phasePolicy: plan exits on submit_plan, execute on respond) rather than with a per-tool flag.
Where the field stands (September 2026)
- Language servers are being removed, not added. opencode v2 "does not run language servers, expose LSP tools, or produce LSP diagnostics"; pi, hermes and Claude Code never shipped them. Crush is the exception, and it does the opposite of a tool: diagnostics and symbols are fed into the context rather than offered for the model to call. Codehalter dropped its LSP tools for the reason that shape addresses: the model kept reaching for
grepinstead. - Model-visible todo lists are being withdrawn. Claude Code stopped offering todo tools to current models, opencode v2 deleted
todowrite, Codex shipsupdate_planoff by default; Cline went the other way and reinjects a Focus Chain every few messages. Codehalter has no todo tool: the plan is asubmit_plantable the executor revises in place. - Compaction has converged on a token threshold with a reserve buffer, a summary with required headings, and a retained tail whose tool outputs are clipped. Codehalter's trigger is the odd one out: it compacts on the server's context-full refusal rather than on an estimate, and writes one structured note per completed turn as it goes.
- Local models are table stakes. opencode v2 auto-discovers Ollama, LM Studio and vLLM; hermes ships a managed llama.cpp runtime that sizes the quant to your GPU; pi drives
llama-serverrouter mode and manages GGUFs from the CLI. Codehalter assumes that world instead of adapting to it: router-mode probes per model id, per-connection slot semaphores, and a prefix-cache rewind detector that names the cause. Keeping an idle prefix alive is a shared answer: opencode haswarming, pi gates a refresh on expected savings, and codehalter re-sends its 1-token warm call while the session is idle and while a long tool runs. - Typing during a turn queues rather than cancels. pi polls for steering messages between iterations and Claude Code queues them; codehalter now does the same, with the stop button as the way to interrupt. It used to replace the turn in flight, which during a long
/specround threw the round away. - Sandboxing is mostly left to the user. opencode states plainly that its shell "runs with the host user's filesystem, process, and network authority". Codehalter refuses to run outside a container at all.
- ACP is winning as the editor surface. Goose ships a native ACP server, opencode has
opencode acp, Codex and Claude Code integrate through external adapters, and Amp deleted its VS Code and Cursor extensions outright. Codehalter speaks ACP natively and nothing else.
The harnesses compared
Surveyed September 2026. "Local" means what the harness does for a self-hosted model beyond accepting an OpenAI-compatible base URL.
| Harness | Local models | Editor integration | Context strategy | Stance |
|---|---|---|---|---|
| codehalter | llama.cpp router probed per model id, slot semaphores, rewind detector, keeps an idle prefix warm | ACP, and nothing else | Reactive on the server's 400, one structured note per completed turn | Refuses to run outside a container |
| opencode v2 | Auto-discovers Ollama, LM Studio, vLLM (vLLM starts with tools off: no capability metadata) | opencode acp, plus its own server with TUI/desktop/web clients |
Threshold with reserve buffer, required-heading summary with one retry, provider checkpoints | Deleted language servers and todo tools in v2; no sandbox by design |
| pi | llama-server router mode first class, loads and downloads GGUFs from the CLI |
None: RPC, SDK and TypeScript extensions | Auto-compact on a reserve threshold, fixed-template summary, cost-gated cache warming | Ships no MCP, subagents, permission popups, plan mode or todos on purpose |
| forge | A reliability proxy in front of any local server, 26 per-model sampling profiles | None: it is an OpenAI and Anthropic proxy other harnesses point at | Tiered compaction that drops nudges, then tool results, then reasoning | One tool, respond, so a small model never picks between text and tool call |
| hermes-agent | Managed llama.cpp runtime: sizes the quant to the GPU, grows the window, spills experts before KV | ACP adapter, plus CLI, TUI, desktop and chat gateways | Phased batch compression, plus opt-in per-turn micro-compaction that never compacts user turns | Deterministic guardrails (repeat streaks, cycle detection) over prompt wording |
| Goose | Explicit roadmap to tune the loop and tool schemas for small open models | Native ACP server, installable from Zed's registry | Auto-compact at 80%, summarises older tool outputs while recent ones stay verbatim | YAML recipes and sub-recipe subagents with isolated context |
| Crush | Auto-discovers Ollama, llama.cpp and LM Studio | No first-party ACP, only a third-party bridge | LSP diagnostics and symbols fed into context generation | The one harness still betting on LSP, and not as a tool |
| Claude Code | None: frontier models only | ACP through an adapter | Auto-compaction plus a system-prompt boundary marker so the stable prefix caches | Withdrew todo tools from current models; subagent fan-out is the default unit of work |
| Codex CLI | --oss mode against Ollama, LM Studio and MLX |
ACP through an external server | Full-history handoff summary at a threshold capped below the advertised window | update_plan off by default; deleted its MCP-server subcommands |
| Cline / Roo | Any OpenAI-compatible endpoint | VS Code extension, no ACP | Focus Chain: a todo list reinjected every few messages, surviving compaction | The loudest argument that weak models need a visible task list |
| Aider | Any endpoint; last release Feb 2026 | None | Repo map plus SEARCH/REPLACE retries | Architect and editor split: one model plans, a cheaper one applies the edit |
What codehalter adds
- Devcontainer-first sandboxing posture: auto-scaffolded
.devcontainer/from any of five base distros (Alpine/Arch/Debian/Fedora/Ubuntu), host.gitconfigmounted read-only on request, plus an on-request commit flow (/commit) and a standing instruction never to commit or push on its own, so a commit is always your explicit call. - Native MCP client:
.codehalter/mcp.tomlspawns each[[server]]as a long-lived child, registers its tools under<name>__<tool>, and reconciles when the next prompt starts. Dual-era: each server is probed viaserver/discoverand spoken to with the stateless 2026-07-28 revision ("MCP 2", per-request_meta+ mirroredMcp-Method/Mcp-Name/Mcp-Param-*headers, no sessions) when it supports it, with automatic fallback to the 2025-06-18 initialize/session handshake for everything else. - Slot-aware LLM routing for local servers: per-conn
parallel = Nsemaphores, and the per-turn summariser routed off the foreground KV-cache slot (or, on a single slot, riding it as a prefix-extension), so the main session's prefix cache stays warm. - Plan → per-subtask self-verifying loop → Document pipeline built in, not delegated to an extension: the planner decomposes into subtasks each carrying its own verify recipe; the executor runs the recipe itself before declaring done; failed subtasks trigger a replan (≤20 per prompt) with fuzzy duplicate-failure detection (Jaccard over issue words) escalating the note when the same problem recurs; the document pass updates the README only when the change is user-visible.
- Spec mode (
/spec): a deterministic ledger over a spec directory, one item per turn, each item committed only once a test that names it passes, and each recorded with the spec text it was built from, so editing the spec later re-opens exactly the items that changed. Goose's recipes and Cline's Focus Chain are the nearest things elsewhere, and neither ties completion to a passing test. - Web tools restricted to the planning phase (
web_searchvia DuckDuckGo +web_readvia headless Firefox) so execution stays offline. - Empty-project bootstrap, stuck-tool-loop detection, reactive 400-driven two-tier compaction (keep unfinished turn plus recent completed small turns, then keep only the unfinished turn if that still overflows).
What codehalter does not have
forge's published 26-scenario eval suite with ablation studies. pi's session branching, 30+ provider adapters, TypeScript extensions and @-mention file references. opencode's durable server-side sessions that survive a disconnected client, its browser tool namespace, and Code Mode (the model writes a confined program over the tools instead of calling them one at a time). hermes's managed llama.cpp runtime and FTS5 search across past sessions. Goose's YAML recipes and sub-recipe subagents. Cline's Focus Chain. No subagents, no LSP, no embedding index: all three were removed or never added on purpose.
Credits
- forge by Antoine Zambelli, the synthetic
respondterminal tool used in execute is borrowed from forge's playbook for keeping small local models inside structured tool-calling grammar. - pi/coding-agent by earendil-works, codehalter's explicit terminal tools (which tool ends the loop is declared per phase via
phasePolicy) are inspired by pi'sterminate: truetool-result signal. - Code harness idea exchanging with Clemens
Source Files
¶
- acp.go
- bootstrap.go
- cli.go
- cli_clipboard.go
- cli_resize_unix.go
- cli_ui.go
- format.go
- history.go
- image.go
- launcher.go
- llm.go
- loop.go
- main.go
- mcp.go
- pkginstall.go
- plan_table.go
- prepare.go
- process_unix.go
- prompt.go
- rpc.go
- session.go
- settings.go
- setup.go
- skills.go
- spec.go
- spec_gates.go
- spec_isolation.go
- spec_loop.go
- spec_mutants.go
- spec_picture.go
- spec_questions.go
- spec_testreview.go
- syntax.go
- templates.go
- terminal.go
- tool_alias.go
- tool_ask.go
- tool_background.go
- tool_files.go
- tool_phase_end.go
- tool_run.go
- tool_screenshot.go
- tool_view_image.go
- tool_web.go
- tools.go
- turn.go
- utils.go
- version.go