Skip to content

Agents and LLMsModels and local inferencereference

Model routing in a coding-agent harness

A harness that reaches both a metered cloud API (application programming interface) and a local GPU (graphics processing unit) picks a model for every request. A wrong pick costs money (a long background job on a metered API), time (a local model evicted mid-session) or correctness (a weak model running a deploy, a text-only model handed an image). The pi harness, the subject of the series whose hub is The pi harness journey, sets a default per kind of caller, overrides it by rule, and guards each provider path.

Its setup: a cloud default on OpenRouter, a local engine on one GPU behind the llmc proxy (Scheduling one GPU between LLM (large language model), image and training work), and frontier models as the top rungs of some loop ladders. The workers routed here are covered in Subagents, worktrees, and parallel agent work. The last section lists what applies to a different setup.

Every mechanism below is read from the harness source as of 2026-10-20; the vision backends, the image_ask tool and the interactive tier ladder were updated on 2026-11-07, the per-model rule files on 2026-11-15, and the worker defaults and tier ladder on 2026-12-04. Ladder counts are measured from the 24 loop manifests across the repos on the dev box on the same day. Incidents come from session history and carry their dates.

TL;DR:

  • The interactive session starts on the cloud default, deepseek/deepseek-v4-pro on OpenRouter at thinking high.
  • task and bg_task workers start on the worker default, PI_BG_DEFAULT_MODEL='anthropic/claude-sonnet-5-5', never on the session’s cheap default. An llmc/ worker errors at spawn when the llmc proxy is down.
  • Loops climb a models ladder, cheapest rung first. 11 of the 24 ladders start on a local rung, 5 on OpenRouter, 7 on Anthropic and 1 on pi’s default.
  • Deploys and infra mutations run on an -xhigh local preset or a cloud model, never on the local 27B at medium effort (2026-09-20 incident).
  • vision-fallback.ts replaces each image with a text description from the loaded local model if it has vision, otherwise a cheap cloud vision model, otherwise the whisper service’s image endpoint. Each description carries an image id, and the image_ask tool lets the text-only model ask follow-up questions about it.
  • Ctrl+P cycles an interactive tier ladder: a cheap default, a strong tier, a frontier tier, the cheap model through a second provider, a backup, and the local engine.
  • OpenRouter requests get a 131072-token output cap, and every session gets spend warnings. Local sessions get an automatic preset lock and a context-budget nudge.

who sends the requestcloud (metered)local (one GPU)interactive sessionOpenRouterdeepseek-v4-pro (default)settings.json defaulttask workerAnthropicno model param:worker defaultloop iterationcloud rungfrontier rungllmc proxyloaded presetlocal rung(11 of 24 ladders start here)bg_task workerPI_BG_DEFAULT_MODELmodel paramllmc/...pre-push review(public targets)loaded model only,skipped if nonevision-fallback(image in context)OpenRoutergemini-flash (vision)otherwiseif the loaded modelhas visionwhisper/api/imageif the cloud call fails

The pre-push review asks whichever model llmc has loaded and is skipped when none is. vision-fallback.ts uses the loaded llmc model if it has vision, then a cloud vision model, then the whisper service’s /api/image.


WorkModelSet byWhy
Interactive sessiondeepseek/deepseek-v4-pro, thinking highsettings.json defaultProvider, defaultModel, defaultThinkingLevelDefault for daily work. Text input only.
Side question (/btw)Same model as the sessionbtw.ts forks the session with ctx.modelThe fork carries the full history, so it answers from the same context.
task worker, no model givenanthropic/claude-sonnet-5-5PI_TASK_DEFAULT_MODEL, else PI_BG_DEFAULT_MODELWorkers do not run below Sonnet: cheaper workers cost more in redo rounds than they save (2026-11-23).
task worker for a reviewA different model family per reviewermodel parameterReviewers from one family share blind spots.
bg_task workeranthropic/claude-sonnet-5-5PI_BG_DEFAULT_MODEL in .zshrcSame floor as task. The local engine is a model parameter away.
bg_task with minimal: truepi’s startup defaultminimal skips the env defaultA minimal worker loads no extensions, so an llmc/ default would name a model it cannot resolve.
Loop iterationCurrent rung of the models ladder.pi/harness.jsonCheapest rung first; climb after stallPatience no-progress iterations.
Deploy, infra mutation, production-touching work-xhigh local preset or a cloud modelrule in tool-routing.md2026-09-20 incident (below).
Image-dependent workThe text-only model plus image_ask for details, a vision-capable model, or a parent that reads the image and writes a description into the worker promptrule in tool-routing.md, vision-fallback.tsdeepseek-v4-pro has input: ["text"] in pi’s model registry.
Harder interactive workThe next tier of the Ctrl+P ladderenabledModels in settings.json, “Model tiers” in tool-routing.mdClimb on evidence (two failed attempts at a step, a caught mistake, a high-stakes task), not by default.
Pre-push leak reviewWhatever llmc has loadedprepush-gate.tsNever triggers a model swap.

The session starts on deepseek/deepseek-v4-pro at thinking level high, served through OpenRouter with a host pin (DeepSeek’s own API from 2026-11-07, OpenRouter again since). The model registry lists it with a 1048576-token context window and text-only input. /model or Ctrl+P switches for the rest of the session; nothing switches it automatically except llmc-failover.ts when a fallback is configured (see Local-engine guards).

enabledModels limits the Ctrl+P cycle to a tier ladder, in order (2026-12-04):

TierModelUse
Cheap (default)openrouter/deepseek/deepseek-v4-pro, pinned to two fp8 hostsEverything by default
Strongopenrouter/google/gemini-4-argonHarder reasoning, long documents, images
Frontieropenrouter/moonshotai/kimi-k3.1-pro, pinned to the model’s own labTop tier
Backupanthropic/claude-sonnet-5-5When OpenRouter is down or out of credit; also the worker floor
Backup, topanthropic/claude-opus-5-5Only when asked
Localllmc/qwen38-swift-ninferFree, one lane, when the GPU is free

The deepseek pin exists because OpenRouter’s default routing, which weighs each host’s effective price against throughput, latency and reliability, sent 16 of 40 sampled calls to a host billing cached input at 0.25 USD (United States dollar) per million tokens, against about 0.055 at the pinned host; the same 40 calls billed 1.52 USD instead of 0.64. The sampling and pinning method is in Auditing which OpenRouter provider served your agent’s requests. Models outside the ladder stay reachable with --model.

local-model-rules.ts prepends rule files per model family. A local model behind llmc gets local-model-rules.md: no LaTeX in prose, batch independent tool calls, do not loop on a retry, prefer the native tools over bash. Kimi gets model-rules/kimi.md, three notes on reading the shared rules: reply-length rules never cut work short, run a step instead of proposing it, check state with a tool before asserting it. Every other model gets nothing beyond the shared rules.

The family split dates from 2026-11-15. From 2026-09-28 the local file went to every provider except Anthropic, so Kimi and DeepSeek received rules written for small local models (answer in under four lines, never commit unless asked, stop after one unsuccessful search) that contradicted the shared rules; Kimi quoted them in its reasoning and stopped early. Before 2026-09-28 the file applied only to llmc and to model ids matching gemma or qwen. Before 2026-08-25 it reached no model at all: it returned a system-role message from the context event, pi’s message union has no system role, and the message was dropped before the provider request. It now uses the same before_agent_start prepend as tool-routing.ts.

task.ts takes the model parameter if given, otherwise PI_TASK_DEFAULT_MODEL, otherwise PI_BG_DEFAULT_MODEL, and adds no flag only when none is set (taskWorkerModel in lib/task-guard-core.ts). An llmc/ default is skipped for the explore preset, which loads no extensions and so cannot resolve it. Neither preset changes the model otherwise: explore restricts the tools and loads only a few extensions, and general keeps the full tool set and every extension.

The model parameter exists for two cases: a worker that needs a capability the default lacks (vision), and a multi-model review, where each reviewer runs on a different model family.

Until 2026-12-04 a task with no model got no --model flag and started on the session’s startup default, the cheap interactive tier, while the rules said it inherited the parent’s model. A Sonnet worker that delegated got a DeepSeek leaf that way, below the worker floor. A headless run after the change put an explore task with no model on anthropic/claude-sonnet-5-5.

Incident, 2026-10-12: three parallel workers on openrouter/~deepseek/deepseek-flash-latest printed DSML (DeepSeek Markup Language) tool-call markup as plain text and ran zero tools. The rules now name that model as unfit for workers and say to check a worker’s tool count in bg_status before trusting a quiet result.

lib/bg-tool-task.ts resolves the model as: the model parameter if given; otherwise PI_BG_DEFAULT_MODEL, unless minimal is set; otherwise no flag. .zshrc sets PI_BG_DEFAULT_MODEL='anthropic/claude-sonnet-5-5'.

The env default first existed because omitting model used to inherit the cloud model: two delegations on 2026-09-25 that were meant for the local engine ran on the cloud that way, so the default became the local engine. On 2026-11-23 it moved to Sonnet, because local and cheap cloud workers needed more redo rounds than their lower price saved. The local engine stays reachable with model: "llmc/...".

Two behaviours apply to an llmc/ worker:

  • Fail fast when llmc is down. Before spawning an llmc/ worker, the extension checks that the proxy is reachable and returns an error if it is not. Before this check the spawned pi died about 16 s later with only a connection-refused banner. There is no silent fallback to a cloud model: that was the author’s stated preference on 2026-09-25.
  • Lean tool list. The local engine serves one request at a time and keeps one prompt-cache context. A worker’s first request used to carry about 77.5k prompt tokens (139 tool schemas, including every MCP (Model Context Protocol) server, plus the system prompt) before doing any work, and each cache miss re-prefilled all of it at about 4.3k tokens/s. llmc/ workers now get a 20-tool allowlist (LLMC_DEFAULT_TOOLS) and no MCP servers. An explicit tools parameter overrides it, and PI_BG_LLMC_TOOLS=all turns it off.

A loop manifest (.pi/harness.json) declares a models ladder, cheapest rung first; "" means pi’s default. The governor climbs one rung after stallPatience iterations with no progress. Each iteration is a fresh pi -p on the current rung, so a climb costs no context. The loop itself is covered in Loop or graph: a sensor-gated coding-agent loop.

The 24 manifests on the dev box on 2026-10-20:

Ladder propertyCount
First rung local (llmc/ or llama-server/, both served by the llmc proxy)11
First rung OpenRouter5
First rung Anthropic7
First rung "" (pi’s default)1
Local rungs only4
Contains an Anthropic rung12
Length 1 / 2 / 3 rungs6 / 15 / 3

A local-only ladder has no rung to climb to when the local model stalls: the governor stays on the top rung (driver/loop.workflow.js:141), so the loop keeps iterating on the same model until the sensors pass or the iteration budget runs out.

A loop on a local rung and an interactive session on a different local preset fight over the one GPU. On 2026-09-19 that swap war ran 13 minutes, with time to first token at 40-90 s per turn as each swap wiped the context cache. Loops and sessions share one preset, or the loop queues for the lock with llmc lock --wait. The interactive session never waits, and runs unlocked when another owner holds the preset.

Deploys, infra mutations and production-touching operations do not run on the local 27B model at medium effort. Interactive deploy work on llmc uses an -xhigh preset (qwen38-swift-ninfer-xhigh or qwen38-ninfer-xhigh), or moves to a cloud model. Medium effort stays for loops, unattended workers and quick questions, where its shorter reasoning traces cost nothing.

Incident, 2026-09-20: a session on the local model at medium effort created a stack through the compose management API without naming a host. The API defaulted to the wrong one. The repair attempts then collided with a live service stack on the intended host and took it down. The root cause had two parts: no host check on the deploy call, and a model too weak for a mutation with that blast radius. This rule covers the model half.

Two related rules for long local sessions:

  • Lock the preset for the session (llmc-session-guard.ts does this automatically, below).
  • Treat a compaction on a weak local model as unrecoverable. The summary is written by the same model and its errors carry into every later turn. Write working state to a file and start a fresh session instead.

deepseek-v4-pro cannot read images, so a pasted screenshot, a read of a PNG (Portable Network Graphics), or a tool that returns a contact sheet would be invisible to it. vision-fallback.ts hooks the context event and, when the current model lacks image input, replaces each image block in the outgoing request with a text description. Backends, in order:

  1. The model llmc has loaded, if its preset declares vision. Only the loaded model id is requested; naming any other id would trigger a model swap and evict another session’s preset.
  2. A cloud vision model, PI_VISION_MODEL (default openrouter/~google/gemini-flash-latest), called through pi’s own model registry and auth.
  3. The whisper service’s /api/image endpoint, which takes raw image bytes and returns a description plus OCR (optical character recognition) text.
  4. A one-line placeholder, so the model at least knows an image was there.

The description prompt asks for verbatim text and positions (labels, part markings, which wire goes where), because a one-paragraph summary drops exactly the detail a hardware or UI (user interface) task needs. A description is still lossy, so each one carries a short image id and the original bytes are kept on disk. The image_ask tool takes that id, or an image file path, plus one concrete question, and sends both to the cloud vision model (the loaded llmc model as fallback). The text-only session can ask “which pad is the yellow wire on” without switching models and losing its prompt cache.

The cloud default was picked on a spot check on 2026-11-07: two board photos, two runs per model, answers compared with the photos. gemini-flash read every marking in about 5 seconds for about 0.002 USD per call; kimi-k3.1-pro took 10-140 seconds at 0.02-0.04 USD, misread the main chip’s brand on a 4-bit host and returned one empty answer; deepseek-v4.1-flash named the wrong chip vendor. This was a spot check.

The transform is request-local: the original images stay in the session, so switching to a vision model later shows the real pixels. Descriptions are cached by image hash in memory and on disk; placeholders are not cached, so a backend that comes back is used on the next request.

For a worker, image_ask is available too; the alternatives are a vision-capable worker model, or a vision-capable parent that reads the image and puts a text description in the worker prompt.

For blurred or pixelated text, When blurred or pixelated text can be recovered separates OCR descriptions from inverse filtering, candidate matching and generative enhancement.

GuardWhat it doesWhy
max-tokens-cap.tsClamps max_tokens / max_completion_tokens on OpenRouter requests to 131072 by default; an env variable moves the ceiling or turns the guard offFrom pi 1.2.0, pi requests output up to the remaining context: 873436 tokens on deepseek v4 on 2026-10-13. OpenRouter reserves credit for the whole max_tokens before generating, so on a modest balance every request failed with a 402 even when the real cost was cents.
cost-guard.tsWarns at cumulative spend crossings (PI_COST_WARN_LADDER, default 5,10,20,35,50,75,100 dollars), on a single turn above 1 dollar, and when context passes 150000 tokens on a model priced at 3 dollars per million input tokens or more, listing cheaper models that fit the contextSessions on 2026-08-10/11 grew to 30M-140M input tokens and cost 45-370 dollars before the first signal, a 402 that killed the session mid-task. Warn-only: blocking an explicit /model choice is worse than the spend.
degenerate-stream-guard.tsAborts a turn whose output collapses into one short unit repeated, on one line or as a cycle of linesmoonshotai/kimi-k3 on OpenRouter streamed rows of ! twice on 2026-08-19, and a newline-separated loop for about 10 minutes, twice, on 2026-08-27. No auto-retry, because the same provider node may serve the same stream again.
Worker cap and resumeAt most 4 concurrent task workers (queued) and 4 bg_task pi workers per session tree (refused); a task worker hit by a transient error (a 402 on the in-flight credit budget, 429, 5xx) is resumed with backoffOne of six parallel workers hit the in-flight credit budget on 2026-10-19. Covered in Subagents, worktrees, and parallel agent work.
GuardWhat it doesWhy
llmc-session-guard.tsLocks the session’s preset with owner pi-<sessionId>, renews the 900 s lock every turn, unlocks on model change, shutdown or a termination signal. Warns once per crossing at 60% context that a written checkpoint beats compaction.Any other client’s request can otherwise evict the model mid-session; the eviction wipes the context cache and the next turn re-prefills everything (2026-09-18/19: 40-90 s time to first token at about 200k context). Contention is a warning, never a fight: the session runs unlocked.
llmc-dynamic.tsRegisters the local model list from the proxy’s live /v1/models at startup, with context window, reasoning flag, output cap and vision capability per presetA hand-maintained list drifted by 2026-08-27: 6 deleted presets still listed, 6 missing, and a context window listed at 196608 for a preset serving 262144. The static list is the fallback when the proxy is down.
llmc-failover.tsOn a transport error after pi’s own retries (connection refused, 502/503/504, a swap in progress), reads the proxy’s /mode and names the state and the recovery step. Switches to PI_LLMC_FAILOVER_FALLBACK for the turn, with a 300 s cooldown, only if that variable is set.The fallback variable is unset on the dev box, so a local failure is reported, not rerouted to the cloud.
local-provider-hints.tsNames the provider and URL (Uniform Resource Locator) when a local provider refuses the connectionOn 2026-08-26 the proxy had been dead for about 12 hours and pi showed only Connection error. four times.

The client-side pre-push gate asks a model whether a push to a public remote carries internal context. It reads the proxy’s /mode, and sends to whichever model is loaded only when the proxy is in LLM mode with no swap in progress. With no model loaded it prints skipped and the push continues on the mechanical checks (gitleaks, blocked terms, sensitive files, identifier shapes). It never asks for a specific model, so a push never evicts a running session’s preset. The gate is covered in Agent leak gates.


The model names, the ladder counts and the 131072 ceiling are specific to this setup.

  1. Route by caller. Interactive work, inline sub-tasks, background jobs and loops have different cost and latency budgets, so each gets its own default.
  2. Give a local default a fail-fast path. When the local engine is down, a silent fallback to the cloud turns a free job into a metered one that nobody chose. Error at spawn time.
  3. Shrink the prompt for a single-lane local engine. Tool schemas and MCP servers a worker will not use are prefilled on every cache miss.
  4. Tie effort to blast radius. A short deploy is high-stakes, a long refactor on a branch is not.
  5. Cap requested output on gateways that reserve credit up front. The reservation covers the requested maximum, so an uncapped request can fail on a balance that covers the real cost many times over.
  6. Give a text-only default an image path: describe images before the request, or route image work to a model that can see them. Without one, screenshots are dropped from the model’s view.
  7. Make a model-backed check use what is loaded. A gate that names a specific model can evict a running session on a single-GPU engine, so it skips when nothing is loaded.

New piece of agent workNeeds tosee images?Deploy orinfra mutation?novision-capable model,or parent describes the imageyesLong, and the parentneed not wait?no-xhigh local presetor cloud modelyesObjective sensorsdecide done?yestask on the worker default;other families for reviewnobg_task on the worker default(PI_BG_DEFAULT_MODEL)noloop: ladder cheapest first,with a cloud rung above localyes

The same decision as text:

  1. Work that must see images goes to a vision-capable model, or the parent reads the image and writes a description into the worker prompt.
  2. A deploy or infra mutation runs on an -xhigh local preset or a cloud model, never at medium effort on the local model.
  3. Work the parent reads before continuing runs as a task on the worker default (Sonnet); a review uses a different model family per reviewer.
  4. Long work with objective pass/fail sensors runs as a loop, with a ladder that starts cheap and has a cloud rung above any local one.
  5. Other long work runs as a bg_task on the worker default, or on the local engine when named.

ClaimHow it was checkedStatus
Session default deepseek/deepseek-v4-pro, thinking highsettings.json, 2026-11-07; a fresh pi -p reported provider deepseek and a 71,552-token cache read on its second turnread from config, observed
deepseek-v4-pro input is text only, 1048576-token contextpi’s model registry (models-store.json), 2026-10-20read from config
task worker default modeltaskWorkerModel and its unit tests; a headless explore task with no model ran on anthropic/claude-sonnet-5-5, 2026-12-04read from source, observed
bg_task model resolution, llmc fail-fast, LLMC_DEFAULT_TOOLSlib/bg-tool-task.ts, lib/bg-worker-config.ts; PI_BG_DEFAULT_MODEL in .zshrcread from source
77.5k-token first request, 4.3k tokens/s re-prefillcomment in lib/bg-worker-config.ts recording the measurementmeasured, recorded in source
Ladder counts (11 / 5 / 7 / 1 first rungs, 24 manifests)every .pi/harness.json in the repo checkouts on the dev box, parsed and classified by first rung, 2026-10-20measured
2026-09-20 wrong-host incidentsession history and the incident audit of 2026-10-16incident record
2026-10-12 DSML worker failurerule text in tool-routing.mdincident record
873436-token max_tokens request, 402 on low balancemax-tokens-cap.ts header, 2026-10-13incident record
Vision backends, request-local transform, image_askvision-fallback.ts, 2026-11-07; end-to-end run of a text-only session answering through image_askread from source, observed
Tier ladder and the deepseek / kimi host pinssettings.json enabledModels, models.json overrides, 2026-11-07 (a pi -p call per tier, provider confirmed with OpenRouter’s generation API); ladder re-read 2026-12-04read from config, observed
16 of 40 deepseek calls on the 0.25 host; 1.52 vs 0.64 USD40 random recent generations looked up one by one in OpenRouter’s generation API, 2026-11-06measured
Vision model choice2 photos x 2 runs per model, 2026-11-07spot check
Session lock, 900 s TTL (time to live), 60% context nudgellmc-session-guard.tsread from source
Failover reroute is off on the dev boxPI_LLMC_FAILOVER_FALLBACK absent from the shell configread from config
Pre-push review uses the loaded model and skips without oneprepush-gate.ts; a push on 2026-10-20 printed skipped (llmc unreachable ...)read from source, observed
llmc-failover.ts reroute behaviourunit tests of the pure helpers; not exercised live, because the fallback is unsetdesign-only