Skip to content

coding-agents

1 post with the tag “coding-agents”

How Cline Engineers Context

Every AI coding tool wants your attention. Most of them are autocomplete with better marketing. Cline is a different class of tool. It is an open-source agent that reads your files, runs commands, and edits code without hand-holding (DeployHQ, 2026).

The interesting part is not the model. The interesting part is the context around the model. We mapped the public codebase end to end (github.com/cline/cline). This post walks the full architecture, the harness-to-model exchange, and why the design works.

Cline is a loop. The harness builds a prompt, sends it to a model, receives a streaming answer, executes any tool calls, appends the results, and repeats. The system prompt is rebuilt from parts on every turn, not stored as one document.

┌──────────────────────────── HARNESS ────────────────────────────┐
│ │
│ PromptRegistry (singleton) │
│ ├─ loadVariants() → 12 model variants │
│ │ each: { config, overrides, template, matcher } │
│ └─ loadComponents() → 13 component functions (fixed order) │
│ │
│ getSystemPrompt(context) │
│ ├─ getModelFamily(context) → iterate matchers, first wins │
│ └─ PromptBuilder(variant, context) │
│ ├─ buildComponents() → sections[] (each gated) │
│ ├─ preparePlaceholders() → {{CWD}}, {{IDE_NAME}}... │
│ ├─ TemplateEngine.resolve() │
│ └─ postProcess() → final prompt (~500 lines) │
└──────────────────────────────┬─────────────────────────────────┘
┌─────────────────────────────┐
│ API Transform Layer │
│ ANTHROPIC_CHAT, GEMINI, │
│ OPENAI_CHAT, R1, RESPONSES │
│ internal format → wire │
└──────────────┬──────────────┘
┌──────────────────┐
│ THE MODEL │
└────────┬─────────┘
streaming response stream
text / tools / thinking / usage
┌─────────────────────────────┐
│ Transform back to internal │
│ format (content blocks) │
└──────────────┬──────────────┘
┌─────────────────────────────┐
│ Harness executes tool │
│ call → result appended │
│ to conversation history │
│ ContextManager: │
│ dedup → truncate if over │
│ token budget │
└──────────────┬──────────────┘
└── loop back to the API call

The loop is the product. Every piece below exists to make that loop cheap, sharp, and crash-free.

Cline does not ship one giant system prompt. It ships a registry. The registry holds 12 model variants and 13 component functions. Each component covers one concern, and the builder runs them in a fixed order (source):

1 AGENT_ROLE always rendered
2 SYSTEM_INFO always — {{PLATFORM}}, {{CURRENT_DATE}}, {{CWD}}
3 MCP only if MCP servers are connected
4 USER_INSTRUCTIONS only if .clinerules / .cursorrules exist
5 TOOL_USE always — 24 tools, each individually gated
6 EDITING_FILES always
7 CAPABILITIES always — browser / web / MCP placeholders resolved
8 SKILLS only if skills are loaded
9 RULES always — yolo / browser / CLI branches resolved
10 OBJECTIVE always — yolo branch selected
11 ACT_VS_PLAN always — yolo branch selected
12 FEEDBACK only if focus chain is enabled
13 TASK_PROGRESS varies — focus chain / variant template gating

Order matters. Role comes first so the model knows who it is before it reads anything else. Task progress comes last because it is the least stable content. A real Claude-class snapshot lands around 500 lines and 8,000 characters.

Principle 1: Gate every section on real context

Section titled “Principle 1: Gate every section on real context”

Each component receives the session state and decides whether to render. No MCP servers connected? The MCP section disappears. No skills loaded? The skills section disappears. Browser use disabled? The browser rules vanish. YOLO mode off? The objective stays on the conservative branch.

The same gating runs at the tool level. Every tool declares a contextRequirements check. A false return hides the tool from the model completely:

browser_action → browser configured + enabled
use_mcp_tool → MCP hub exists
access_mcp_resource → MCP hub exists
ask_followup_question → NOT in yolo mode
new_task → NOT in yolo mode
use_subagents → subagents on, not already a subagent
focus_chain → focus chain flag on
use_skill → skills loaded
generate_explanation → NOT the CLI
web_search → MCP has no web search tool
execute_command → always
read_file → always
write_to_file → always
replace_in_file → always
search_files → always
attempt_completion → always

This is a compile-time filter on the tool list, not a runtime guard. A tool that fails its check never reaches the prompt. The model cannot call what it cannot see. That keeps the prompt lean and stops the model from inventing capabilities.

The registry holds 12 variants, one per model family. A matcher walks the variants and picks the first match. No match? The generic variant applies.

Tool calling is where the variants differ most:

Native tool calling (GPT-5, GPT-5.1, Gemini 3):
structured JSON tool definitions passed as a separate API parameter
model returns tool_calls natively
XML tool calling (Claude, Hermes, Generic, GLM, Trinity):
tools described as XML inside the system prompt
model answers with XML tool call syntax

Same behavior, correct dialect per model. Claude-class prompts run ~500 lines with XML tools. Hermes and Gemini variants run leaner at ~400 lines. The content is the same. The encoding follows the model.

Principle 3: Treat tokens like a hard budget

Section titled “Principle 3: Treat tokens like a hard budget”

A context window is a finite resource. Cline does not hope it fits. It computes the budget per model:

ModelRaw windowSafety bufferEffective window
DeepSeek64,00027,00037,000
Most models128,00030,00098,000
Claude200,00040,000160,000

The safety buffer reserves room for tool results and the next user message. When the history passes the effective window, the ContextManager acts in two phases:

Phase 1 — dedup:
scan user messages for repeated file reads
replace duplicates with a duplicate-read notice
if savings ≥ 30% → stop here, keep everything else
Phase 2 — truncation (only if dedup was not enough):
remove last 2 message pairs, or half, or a quarter
always keep the first user-assistant pair
inject a truncation notice into the first assistant message
serialize the change log to disk (undo + crash recovery)

The change log is a durable JSON map. A checkpoint restore can undo every truncation after a timestamp. A crash reinitializes from the saved state. The budget is managed like a database transaction, not a best-effort trim.

Principle 4: Inject context at three layers

Section titled “Principle 4: Inject context at three layers”

Context does not only live in the system prompt. Cline injects it in three places:

  1. The system prompt appendix carries user custom instructions, cline rules, cursor rules, and preferred language.
  2. Conversation history is mutated before send. Duplicates are removed and the budget is enforced in place.
  3. The next user message warns about files that changed outside the agent.

Each layer has one job. The appendix sets standing rules. History management keeps the budget. File warnings keep the model honest about drift.

The exchange: what the harness picks up, sends, and receives

Section titled “The exchange: what the harness picks up, sends, and receives”

This is the part most write-ups skip. Here is one full turn, item by item.

WHAT THE HARNESS PICKS UP BEFORE THE API CALL
CWD, platform, IDE, current date → resolved into placeholders
.clinerules / .cursorrules files → USER_INSTRUCTIONS section
MCP hub state → MCP section + MCP tools
loaded skills → SKILLS section + use_skill tool
browser configuration → browser_action tool + capabilities
yolo mode toggle → hides ask_followup_question / new_task
focus chain flag → FEEDBACK section + task_progress
recently modified files → file-change warning (next user msg)
conversation history → deduped, budget-checked, truncated
WHAT GOES OVER THE WIRE (the request)
system: the assembled ~500-line prompt, sections already gated
tools: JSON definitions (native models) or XML (everyone else)
messages: deduped + truncated history
cache: cache_control on the system prompt + last 2 user messages
(Anthropic — 90% discount on cached input tokens)

The transform layer is the last step before the wire. It speaks six canonical API formats: Anthropic, Gemini, OpenAI chat, DeepSeek R1, OpenAI Responses, and Responses over WebSocket. Anthropic content blocks are the internal lingua franca. Every converter translates the internal format to the provider’s wire format, then translates the response back.

WHAT COMES BACK (the streaming response)
text → TextDelta model prose, token by token
tools → ToolCall[] tool invocations the model wants
thinking → ThinkingDelta chain-of-thought, where supported
usage → TokenUsage token accounting per call
WHAT THE HARNESS DOES WITH IT
tool calls execute for real (read_file, execute_command, ...)
results append to history as tool_result content blocks
budget re-checked → dedup or truncate if needed
loop continues until the model returns attempt_completion

The response is not one JSON blob. It is a live stream of four event types, normalized back to content blocks as they arrive. Tool calls are executed immediately. Their results feed the next turn. That is the whole agent loop, and every layer above exists to keep that loop inside its token budget.

Four properties do the heavy lifting:

  1. Gating is compile-time, not behavioral. The model only sees tools and sections its session actually supports. A lean prompt is a cheap prompt, and a cheap prompt is a fast one. It also removes the failure mode where a model hallucinates a tool that does not exist.

  2. The budget is enforced, not hoped for. Dedup first, truncate second, keep the first pair, log every mutation. Long sessions survive because the history is actively managed, and the durable change log makes the management reversible.

  3. One dialect per model. XML and JSON tool calling are different encodings of the same contract. Shipping both means one harness serves every major provider without degrading the ones that need native calls.

  4. Caching is applied where reuse is real. The system prompt and the last two user messages carry cache markers. On Anthropic that is a 90 percent discount on cached input tokens. The 500-line prompt stops being a cost center and becomes a fixed cost per session.

  1. Build prompts from components. A prompt assembled from single-concern parts is easier to test and cheaper to run.
  2. Gate every section on real context. If the session lacks a thing, the section for that thing should not render.
  3. Keep a variant per model family. Models differ in dialect, not in intent. Ship both.
  4. Budget tokens with a safety margin. Reserve room for tool results. Dedupe before you delete.
  5. Inject context at the layer where it belongs. Standing rules go in the system prompt. Budget lives in history. Drift warnings go in the message.

The model is the commodity. The context is the product. Cline understands that, and the architecture shows it.