Harness Tricks for Coding Agents on Local Models with Small Context Windows
In many regulated environments, sending code or data to a cloud API isn’t allowed. On air-gapped networks, it isn’t even possible. The only option is a model running on hardware you already have, and that hardware can often be modest: a workstation with a mid-range GPU, a laptop with 6GB of VRAM, or a shared server that several teams use. You can’t rent a bigger GPU or switch to a frontier model when a task gets hard. You have to make the best of what you have.
Many coding agent harnesses can connect to local models. But connecting to a local model isn’t the same as being designed around its limits. Their defaults are usually tuned for frontier models, with context windows of 200K tokens or more and the ability to recover from their own mistakes. On local hardware, both assumptions fail. Keeping a small model responsive on a small GPU usually means a window of 32K or less, and small models make mistakes that frontier models rarely do.
Defaults that work well in a large window don’t always scale down. One Pi user running a local model with a 48K window found that sessions eventually got stuck, with compactions coming closer and closer together until there was no room left to reply. The cause was compaction defaults that are sensible in a 200K window but take up most of a 48K one.
This post collects the harness-level techniques that PatchPal, a coding agent harness designed for regulated and air-gapped environments, uses to work within those limits. They change what the harness sends to the model and how it handles what comes back. Several are adapted from NVIDIA’s You don’t need long context (Belcak et al., 2026), and the rest came from watching small models fail. Most are simple enough to add to any harness.
Why the Window Has to Stay Small
A long context is slow on a small GPU even when it fits. On an RTX A1000 with 6GB of VRAM, Gemma 4 E4B generates about 50 tokens per second in a 32K window, even when the window is mostly full. Once a 100K-token prompt fills a 128K window, it generates under 5 tokens per second, after spending more than a minute and a half just reading the prompt. Other models don’t fit a long window at all: Qwen3.5 4B starts running partly on the CPU above about 32K. An agent takes dozens of steps per task, so these slowdowns quickly make it unusable.
So the window stays small, typically 16K to 32K (and as low as 8K), and the harness has to make that window go as far as possible.
Techniques for Small Context Windows
1. Tell the Harness the Real Window Size
This first one sounds obvious, but it’s easy to get wrong. Harnesses usually look up the context limit from the model name, and most local models are listed at 128K or more. The server, though, may be configured with a much smaller window (OLLAMA_CONTEXT_LENGTH, vLLM’s --max-model-len), and the harness can’t see that setting. If the harness thinks it has 128K and the server has 32K, compaction never triggers, and requests either fail or get truncated by the server, depending on the engine.
PatchPal can’t see the server’s setting either, so you set the window explicitly, and PatchPal uses it to decide everything that follows:
1
2
3
4
export OLLAMA_CONTEXT_LENGTH=32768 # what the server provides
export PATCHPAL_CONTEXT_LIMIT=32768 # what the harness plans around
patchpal --model ollama_chat/gemma4:e4b
# 🔧 Tiny agent (context window 32,768 ≤ 65,536): handoff compaction, selective reading
At 64K or less, PatchPal switches to TinyAgent, a version of its agent that applies the rest of the techniques in this section.
2. Cut the Fixed Overhead
Every request carries the system prompt, the tool definitions, and space reserved for the reply before any conversation is included. With PatchPal’s full tool set, the tool definitions alone take about 5,900 tokens, over a third of a 16K window.
TinyAgent enables only the core tools by default: read_file, read_lines, edit_file, write_file and run_shell, plus web tools if web access is on. That brings the tool definitions down to about 1,100 tokens (about 1,400 with web tools). Anything else, like searching or listing files, goes through run_shell. Fewer tools also helps small models, which are more likely to pick the wrong tool when there are many to choose from.
It’s worth measuring this overhead in your own harness. A fresh 32K session in TinyAgent (with web tools on) already uses about 23% of the window before the first message. Most of that is the reply reserve: PatchPal sets aside 16% of the window for the model’s response, which is 5,242 tokens at 32K.
3. Cap Tool Output Relative to the Window
A single file read or command can easily return more text than a small window holds. TinyAgent limits each tool result to about 15% of the window (with a minimum of 2,000 characters), so the cap grows and shrinks with the window size instead of being a fixed number.
When the output is truncated, the harness doesn’t just cut it off. It tells the model where it stopped and exactly how to continue. In a 16K window, for example:
1
2
3
[Truncated after line 168 (limit: ~7,372 characters). To continue, call
read_lines(path='./patchpal/agent/tiny.py', start_line=169, end_line=315).
Read only the parts you need.]
This idea comes from the NVIDIA paper’s bounded document reader, which includes the command for the next window in each read’s header. It matters more for small models than for large ones. A small model doesn’t have to work out which ranges it has seen. It can just follow the hint.
4. Teach the Model to Read Selectively
Capping output keeps a single read from flooding the window, but the model still has to read the right things. TinyAgent’s system prompt tells it to find what it needs first, using grep, wc -l or head through run_shell, and then read only small ranges with read_lines. It also tells the model not to dump whole files, not to reread ranges it has already seen, and to summarize or ask the user what to focus on when a request needs more than fits.
This is the paper’s second main finding: large inputs don’t need to be loaded into the context, as long as the model can fetch pieces of them on demand.
5. Compact to a Handoff Note, Not a Summary
Standard compaction summarizes older messages and keeps the last few turns word for word. In a 16K window, the last two turns can be the whole conversation, so this barely frees any space.
TinyAgent uses handoff compaction instead, following the paper. When the context reaches 80% full (this threshold is configurable), the model writes a structured note for the work still ahead:
- The objective, and any instructions or preferences the user gave
- Established facts: exact paths, commands, values and errors
- Changes made, and whether they were verified
- Checks that were run, and their results
- Dead ends that shouldn’t be repeated
- The remaining plan and the immediate next step
- Files and line ranges already read, and what they contained
The entire conversation is then replaced with the project memory (MEMORY.md or AGENTS.md), the current request with the note attached, and the model’s last reply if the turn had just ended. Keeping the last reply means a follow-up like “yes, do that” still makes sense after a compaction.
The note is capped at about 10% of the window, so compaction always shrinks the context, however large the recent turns were. If the conversation has already overflowed the window, PatchPal first truncates large tool outputs so that the request for the note fits. If generating the note fails, PatchPal falls back to pruning old tool outputs. If the note wouldn’t be smaller than the history, it keeps the history.
The difference from a summary is the direction. A summary looks back at what happened. A handoff note looks forward at what a fresh instance needs in order to continue. The paper found that the compactions that kept accuracy best were briefs for the remaining work, not narratives of the history.
6. Keep the Full History Searchable
Compaction loses information by design. To make that loss recoverable, TinyAgent saves the full conversation to a file under ~/.patchpal/ before each compaction, and the handoff note includes its path. If the model later needs an exact error message or a value it saw earlier, it can grep that file instead of redoing the work. The 100 most recent files are kept.
The paper suggests this approach but doesn’t test it. In practice, it means compacting often isn’t risky, because nothing is lost permanently.
Techniques for Small Models
7. Spell Things Out in the Prompt
Small models take instructions literally and fill gaps with plausible guesses. TinyAgent’s system prompt states things a larger model would infer:
- The working directory, so the model knows where the project is
- Exact tool names: “use
run_shellwith grep”, not “use grep”, since there’s nogreptool - The window size and read limit, so the model knows how much one read can return
- Local files first: questions about the project are answered from its files, not from web search
8. Repair Malformed Tool Calls
Tool arguments sometimes arrive as invalid JSON, either because the model produced them or because something between the model and the harness mangled them (see item 11). PatchPal doesn’t run the call. It shows the error along with the raw arguments, tells the model how to fix it (for example, read_file reads one file per call, so make a separate call for each), and repairs the stored call to valid JSON. That last step matters more than it looks: LiteLLM’s Ollama adapter re-reads every past tool call on each request, so a single invalid call left in the history made every later request fail until the session was cleared.
9. Retry Empty Responses
Local models occasionally return nothing at all: no text and no tool call. This is usually a parsing or template bug in the inference engine, not the model, and newer engine versions often fix it. But a harness that treats an empty response as “task complete” will report success on work that never happened.
PatchPal retries empty responses up to twice, dropping the empty reply so it doesn’t clutter the history. If the retries run out, it returns a NO_RESPONSE: message instead of a misleading “done.”
10. Fall Back to Text-Based Tool Calls
Some small models don’t support native function calling, or support it poorly. For these, PatchPal has a ReAct mode, where the model writes tool calls as plain text in a simple, fixed format and the harness parses them. Small models often follow a short text format more reliably than a JSON schema.
1
PATCHPAL_REACT_MODE=true patchpal --model ollama_chat/llama3.1:8b
11. Check the Harness Before Blaming the Model
Some failures that look like small-model mistakes come from the harness or its libraries. With Ollama, LiteLLM used to number every streamed tool call 0, so when a model asked to read several files at once, any harness that groups streamed calls by number merged them into one invalid call. The request then failed a turn later with a confusing APIConnectionError. It’s a known LiteLLM issue that’s fixed in recent releases. PatchPal handles it regardless of LiteLLM version by starting a new call whenever the call ID changes.
Similarly, older LiteLLM versions dropped tool calls sent to Ollama, so the model appeared to repeat the same call in a loop. When you’re evaluating small models, it may be wise to update the inference engine and the client libraries before drawing conclusions.
What Didn’t Make the Cut
The NVIDIA paper also tests single-action compaction, where the model rewrites its state note after every action and each action starts in a fresh context. Peak context drops to 7–9K tokens, and frontier models stay close to their full-history accuracy.
On a small local GPU, though, it’s too slow. Each action needs a second generation to rewrite the note, and decode speed is the bottleneck on small hardware. Even at 50 tokens per second, rewriting a short note adds several seconds to every step. Compacting only when the window fills keeps handoffs rare, and that turned out to be the better trade-off here. If you want to try single-action compaction, short-context-agent reproduces the paper’s methods for Claude Code.
Limits
These techniques make a small window usable. They don’t make a small model smarter. Each compaction keeps only what the model writes in its note, and a 4B model writes looser notes than a frontier model, so some detail is lost each time. Small models also tend to guess specifics they haven’t read. In one test, a 4B model confidently stated two configuration values from a file it never opened. Trust what the model read, and verify what it didn’t.
The paper’s results also don’t carry over fully to small models. Its frontier models lost little or nothing at 16K, but its open-weight models varied more, and one dropped from 53.0% to 3.6% on SWE-bench Verified at its tightest setting. Tinier models (e.g., 4B) do best on focused tasks: questions about specific code, fixing reported errors, small edits, and writing new files.
Trying It
TinyAgent is selected automatically when PATCHPAL_CONTEXT_LIMIT is 64K or less. Set it to match the window your server provides. For air-gapped use, disable web tools as well.
Terminal UI with Ollama
1
2
3
4
5
6
7
8
# Terminal 1: serve the model with a 32K window
export OLLAMA_CONTEXT_LENGTH=32768
ollama serve
# Terminal 2: tell PatchPal the window size and run it
export PATCHPAL_CONTEXT_LIMIT=32768
export PATCHPAL_ENABLE_WEB=false
patchpal --model ollama_chat/gemma4:e4b
Terminal UI with PolyStrata
PolyStrata serves larger MoE models on a single consumer GPU by keeping part of the model in system RAM. It exposes an OpenAI-compatible API, so PatchPal connects to it with the openai/ prefix:
1
2
3
4
5
export OPENAI_API_BASE=http://127.0.0.1:8080/v1
export OPENAI_API_KEY=dummy # placeholder; any non-empty value
export PATCHPAL_CONTEXT_LIMIT=32768 # match the server's context window
export PATCHPAL_ENABLE_WEB=false
patchpal --model openai/inkling-2-mini
Python SDK
1
2
3
4
5
6
7
import os
os.environ["PATCHPAL_CONTEXT_LIMIT"] = "32768" # match the server's window
from patchpal.agent import create_tiny_agent
agent = create_tiny_agent(model_id="ollama_chat/qwen3.5:4b")
agent.run("Fix the failing test in tests/test_utils.py")
On a 6GB GPU, 32K has been the best balance between room to work and speed.
Conclusion
When you’re limited to the hardware in front of you, the harness has to do work that a larger model and a larger window would otherwise do. Tell it the real window size, keep the overhead small, cap what each tool can return and say how to get the rest, compact forward-looking notes instead of summaries, keep the full history on disk, and expect small models to fail in small, predictable ways.
None of these techniques are specific to PatchPal, and most would be straightforward to add to another harness. For details and the code: