How Context Message Pipelines Work in Coding Agents
This article breaks down the context message pipeline of a coding agent from a neutral, general technical perspective. It explains the three parts sent to the model (system instructions, message history, and tool schemas), why internal message types are normalized into the two API roles, how content parts structure each message, how old tool results can be removed without breaking prompt caching, and which hidden injections add environment context and attachments beyond user input. Readers will also get a practical engineering checklist for keeping long sessions accurate and token-efficient.
How Context Message Pipelines Work in Coding Agents
In a coding tool, every time an agent completes a “think-act” cycle, it reassembles the full context and sends it to the model again. Only three parts typically consume tokens: identity and rule instructions, message history, and tool schemas. Message history takes the largest share (an industry rule of thumb is around 60%) and changes most frequently, since new content is appended every turn.
This article takes a neutral, general technical view of message history as a “message pipeline” and covers its key design points: mapping internal message types to API role types, the content-part structure inside each message, cleanup and normalization, non-destructive removal of tool results with cache-friendly editing, and two kinds of hidden injections that do not come from the user’s keyboard.
1. Three Pieces of Context and Where the Message Pipeline Fits
The parameters sent to the model can be understood as three parts:
| Part | Role | Typical Share |
|---|---|---|
| system | Defines “who you are, what rules you follow, and what environment you are in” | ~30% |
| messages | Records “what happened”: user input, model replies, tool calls and results | ~60% |
| tools | Declares “which capabilities you can call” via schemas | ~10% |
system answers “identity and environment,” tools answers “available capabilities,” and messages answers “process and facts.” The reason an agent appears to “look up files, run tests, and modify code on its own” is that it keeps appending paired records of “the model issues a call—the runtime returns a result” in messages, so the next reasoning step sees the latest facts.
Illustrative assembly logic:
params = params_from_context(ctx)# The three parts that actually go to the modelpayload = {"system": params["system"],"messages": params["messages"],"tools": params["tools"],}
2. Why There Are 5 Internal Message Types but Only 2 API Roles
Most message-based chat APIs distinguish only two roles: user and assistant. But an agent runtime needs to express more semantics: system-level reminders, tool execution results, expanded attachment content, internal debugging information, and so on. So internally a richer set of types is usually maintained (commonly 5: user input, model output, tool call, tool result, and system/environment injection), and before sending, a cleanup pipeline normalizes them into the two roles the API accepts.
The key mapping principle is “no loss of meaning, valid structure”:
- User input → user;
- Model output (including call intent) → assistant;
- Tool result → usually a dedicated content block carried by the user role (tool_result), with a call ID for pairing;
- System reminders and environment injections → folded into text blocks of a user message, or merged into the nearest user message per policy;
- Empty content, pure whitespace, orphaned results → dropped or filled in to avoid invalid messages.
Internal type API role Carried asUser input -> user text/image partsModel output -> assistant text + call intentTool call -> assistant call block (with ID and arguments)Tool result -> user result block (with matching ID)System/env inject -> user text block (mergeable)
The point of this step is that the internal model can freely extend semantics, while the external interface stays minimal and valid, lowering the cost of integrating with different model APIs.
3. Smaller Units Inside Each Message: Content Parts
A message’s content is not a single string but an array of content parts. Each part is an independent unit; common types include text, image, tool call, and tool result. The benefits are that multimodal inputs can be interleaved, tool calls and results can be paired precisely, and a single message can carry composite semantics such as “explanation + screenshot + pending action.”
{"role": "user","content": [{ "type": "text", "text": "Please fix the login failure" },{ "type": "image", "source": { "type": "base64", "data": "..." } },{ "type": "tool_result", "tool_use_id": "call_1", "content": "3 failed, 12 passed" }]}
The cleanup pipeline does three things here: first, filter invalid parts (empty text, oversized attachments, objects that cannot be serialized); second, order them so that call blocks and their result blocks are paired with matching IDs; third, compress and truncate by structurally trimming overly long tool output, keeping only the fragments relevant to the current task.
4. The Core Challenge: Removing Old Tool Results Without Breaking the Cache
In an agent’s long context, early tool results are often huge and already stale. The intuitive move is to delete them, but that changes the message sequence and invalidates the prefix cache (prompt cache)—caching matches by prefix, so any change at any position makes all subsequent tokens billable and recomputed again.
The clever part is introducing a “cache edit” abstraction (think of it as cache_edits): instead of physically deleting in place, replace the stale result with a tiny placeholder text and explicitly state that “the original content here has been removed.” The prefix structure stays unchanged, cache hits are unaffected, and token usage drops to a minimum.
Original: [u1][a1][tool_use_1][tool_result_1(8k tokens)][u2]...Edited: [u1][a1][tool_use_1][tool_result_1(removed)][u2]...^^^^^^^^^^^^ prefix unchanged, cache still hits
Key points:
- Prioritize prefix stability: evaluate the impact on the cached prefix before any edit;
- Placeholder instead of deletion: mark “removed” with short text, preserving position and pairing;
- Pair validation: call blocks and result blocks must both exist to avoid protocol violations;
- Traceability: placeholders can record a summary or reference so the content can be fetched again if needed.
5. Two Hidden Injection Points: User Context and Attachments
Besides keyboard input, messages usually contain two kinds of “silent injections”:
- User context (UserContext): environment facts such as the current working directory, branch status, open files, and a summary of recent command results. It is attached as a text block so the model can “see” the runtime environment.
- Attachments: files the user drags in, selected code snippets, logs, and so on, expanded into content parts inserted into the message stream.
Both must be clearly marked as distinct from explicit user input, so the model does not mistake environment descriptions for user instructions; they must also be included in cleanup and truncation policies to prevent a single injection from consuming too much of the budget.
6. Engineering Practice Checklist
- Build a type mapping table and cover all 5→2 branches with unit tests;
- Strictly validate content parts: ID pairing, order, and size limits;
- Structurally trim tool output, keeping only relevant lines and error summaries;
- Use placeholder-style cache edits, assessing prefix impact before acting;
- Add explicit markers and budget limits to hidden injections;
- Monitor the share of the three parts each turn and alert on abnormal growth.
Conclusion
The message pipeline may look like simply “sending an array,” but it is the hub of agent context engineering: type mapping keeps the protocol valid, content parts support multimodality and tool pairing, cache-friendly editing balances “slimming down” against “cache hits,” and hidden injections give the model environment awareness. Making this mechanism solid is what lets a coding agent stay both accurate and economical in long sessions.
