Inside the Coding Agent Message Pipeline: Normalization, Hidden Injection, and Prompt Caching

    Every LLM call resolves to three structured inputs—system, messages, and tools—but only messages changes from turn to turn. This article walks through how a coding agent assembles that messages array: how internal multi-type messages collapse into the protocol's two roles through a normalization pipeline, why messages are built from addressable content parts, how hidden context such as UserContext and attachments gets injected, and how block-level edits can preserve prompt caching even when old tool results are cleared. It closes with a practical engineering checklist covering observability, budget tiers, and cache-friendly design.

    1. First, clarify: what the model actually reads in a single request

    Every model call ultimately turns into tokens from just three structured parameters:

    Field Purpose Typical share (empirical)
    system Role definition, behavior rules, environment constraints ~30%
    messages User input, model replies, tool calls and results, hidden injections ~60%
    tools List of callable tools and their parameter schemas ~10%

    Of the three, messages is the only part that changes every turn. system and tools stay relatively constant across the whole conversation, while messages keeps growing with each interaction—which makes it the main target for context cost, cache hit rate, and truncation strategy.

    More importantly, messages don’t contain only what the user typed. What really raises engineering complexity is the hidden injection: content the user never sees but the model sees every time. Understanding this is the key to the five questions below:

    1. Why do we need more than five internal message types when the external protocol recognizes only two?
    2. What validation and rewriting does the normalization pipeline actually perform?
    3. Why must a Content Part exist inside a single message?
    4. How do UserContext and Attachments get mixed into messages?
    5. Why can old tool results be “deleted” without breaking the cache?

    2. Internal multi-type to protocol’s two roles: the normalization pipeline design

    The external protocol usually has only two roles: user and assistant. But a usable coding agent needs to maintain at least five logical message types internally:

    1. User turn: real keyboard input, possibly carrying slash commands or mode-switch markers.
    2. Assistant turn: a text reply plus some number of tool calls (tool_use).
    3. Tool result turn: carries tool_result, semantically an “environment reply,” but at the protocol level it must hang under the user role.
    4. System injection turn: environment context, repository memory, attachment expansion, periodic reminders.
    5. Summary turn: the summary block generated after history compression, replacing the trimmed original conversation.

    The reason to distinguish these five internally is that their lifecycle, injection timing, truncation priority, and cache behavior are completely different. Once they are squashed into two classes before sending, this semantics can only be maintained through textual conventions, which is highly error-prone. So we need a purely functional normalization pipeline that translates the “internal semantic model” into a “protocol-legal message array.”

    1. ROLE_OF = {
    2. 'user_input': 'user',
    3. 'tool_result': 'user',
    4. 'injection': 'user',
    5. 'summary': 'user',
    6. 'assistant': 'assistant',
    7. }
    8. def to_api_messages(internal_msgs):
    9. out = []
    10. for m in internal_msgs:
    11. role = ROLE_OF[m.kind]
    12. parts = [p for p in (normalize_part(x) for x in m.parts) if p]
    13. if not parts: # drop empty messages entirely
    14. continue
    15. if out and out[-1]['role'] == role: # merge adjacent messages with the same role
    16. out[-1]['content'].extend(parts)
    17. else:
    18. out.append({'role': role, 'content': parts})
    19. validate(out) # assert invariants
    20. return out
    21. def validate(msgs):
    22. assert msgs and msgs[0]['role'] == 'user'
    23. uses = {p['id'] for m in msgs for p in m['content'] if p['type'] == 'tool_use'}
    24. results = [p['id'] for m in msgs for p in m['content'] if p['type'] == 'tool_result']
    25. assert set(results) == uses, 'tool calls and results must pair up'
    26. assert len(results) == len(set(results)), 'tool results must not duplicate'
    27. assert msgs[-1]['role'] != 'assistant' or has_tool_use(msgs[-1])

    The invariants the pipeline maintains come down to four: the first message must be a user message, tool calls and results must pair by id, adjacent same-role messages must merge, and the last message must not be a dangling assistant text. The most common production failure here is the “orphan tool call”: if truncation logic removes an old tool result but leaves the tool_use, the request is rejected outright. This also explains why truncation must be done by “block” rather than by “message.”


    3. Content Part: making a message the minimal addressable unit

    Each message’s content is not a string but a Part array. Common Part types include:

    • text: a text fragment, which can carry cache markers;
    • image: screenshots, UI images, charts;
    • tool_use: tool call intent, including id, tool name, arguments;
    • tool_result: tool execution result, which can be marked as an error and can carry sub-parts (for example, a code snippet embedded in an error message).

    Using a Part array brings three direct benefits:

    • Structured multimodality: a screenshot and its caption can align in order within the same user message, so the model correctly builds the “this image corresponds to this description” association.
    • Fine-grained truncation: when compressing old context, you replace the content of a single tool_result without rewriting the whole message.
    • Controllable injection: splitting one long text into multiple text blocks with cache markers lets the “stable part” and the “volatile part” naturally segment after serialization, serving cache breakpoints.

    During serialization, one more “downgrade” step is needed: when encountering an unrecognized Part type, you should not throw an exception and abort the request, but convert it to a text placeholder (for example, [unsupported content omitted]), ensuring that an anomalous tool output doesn’t take down the whole conversation.


    4. Hidden injection: context that doesn’t come from the keyboard

    4.1 UserContext: a one-time environment self-description

    At the start of a session (or when the context is rebuilt after compression), a block of environment description is injected. Typical contents include:

    • current working directory, whether it is inside a Git repository, current branch;
    • operating system and shell type;
    • directory structure overview (usually limited in depth and entry count);
    • content of the repository-level context file (project conventions, build and test commands, code style requirements);
    • today’s date.

    The key design points are “stability” and “budget.” The environment self-description barely changes, so it fits at a front position and can be retained long-term; but it is naturally large, so it must carry triple limits on entry count, character count, and depth, and must exclude binary and dependency directories.

    4.2 Attachments: dynamically injected per turn

    Attachments are the “environment-side input” of the current turn, which may come from:

    • a code snippet the user selected in the UI along with its file path and line numbers;
    • the currently open file, recently edited files;
    • diagnostics returned by the language service (type errors, unused variables);
    • terminal output, test failure logs;
    • file content the user explicitly references with @ syntax.

    4.3 Three key decisions in the injection strategy

    Position: UserContext suits first-message injection (once is enough), while Attachments suit being inserted as a standalone user message before the user input, forming an “environment facts to user intent” reading order.

    Budget: set a total byte cap and a per-attachment cap for attachments; when exceeded, downgrade to a reference form of “path + summary + read on demand,” leaving the actual reading to tool calls. This saves tokens and is naturally compatible with the caching strategy.

    Deduplication and stabilization: the same file content repeatedly appearing in a session (selected once, read once, edited once more) creates lots of duplicate tokens. A workable approach is to hash a fingerprint of the content; if it matches an already-injected version, return only a reference marker instead of the full text.


    5. Caching strategy: why deleting old results doesn’t break the cache

    5.1 The basic constraint of prefix caching

    The prompt caching of mainstream LLM APIs uses exact token-prefix matching as the key, and has minimum cacheable-length and time-to-live limits. This means:

    • an identical prefix can hit the cache;
    • any shift in the prefix (insertion, deletion, replacement, length change) causes everything from that point on to be re-billed.

    By this rule, “deleting old tool results” sounds like it must cause large-scale cache invalidation—because it changes the prefix.

    5.2 Working around rewrites with a “block-level edit list”

    The workable approach is to not rewrite the message text, but to submit an edit list (cache_edits) that declares operations on specific content blocks in the message array:

    1. # Schematic structure: perform a block-level replacement at blocks[N]
    2. {
    3. "blocks": [
    4. {"index": 3, "op": "replace_with",
    5. "content": [{"type": "text", "text": "[tool result cleared to free context]"}]}
    6. ],
    7. "cache_hint": "preserve_prefix" # signal intent: keep the prefix consistent as far as possible
    8. }

    This solves three problems at once:

    1. Prefix bytes stay consistent: the cleared block still occupies a fixed short text placeholder in the physical serialization, so the offset of subsequent blocks does not change and the cache continues;
    2. Structural invariants hold: the pairing between tool_use and tool_result is preserved, so the “orphan tool call” protocol error is not triggered;
    3. Model-side semantics still hold: the model can see that “there was a tool call here and its result has been released,” so it understands that the context was compressed rather than an interaction vanishing out of nowhere.

    It should be noted that block-level editing is a relatively new interface capability and not all platforms offer an identically named mechanism; the engineering equivalent is “placeholder replacement plus a trailing cache breakpoint”—that is, during truncation, replacing the original content with equal-length or fixed-length placeholder text rather than physically deleting the whole block.

    5.3 Four practical rules for protecting the cache

    • Put volatile content at the end: timestamps, the current git diff, temporary variables, and so on go at the tail of the message sequence to avoid polluting the long prefix.
    • Avoid embedding non-deterministic content: do not put runtime values, random ids, or request ids into the system prompt or UserContext unless truly necessary.
    • Stable serialization: fix the key order of tool argument JSON and keep array order stable, avoiding prefix drift from serialization differences.
    • Prefer appending over rewriting: new turns append only at the end; any operation that “reorders historical messages” must explicitly evaluate the cache cost.

    6. Engineering checklist

    1. Observability first: log each request’s message snapshot, the token estimate for each segment, and the reason for a cache hit or miss—otherwise caching problems are nearly impossible to locate.
    2. Budget tiers: reserve quotas for system / tool definitions / history / injection / reply, and when exceeded, compress from back to front by priority rather than truncating with a single cut.
    3. Make the normalization pipeline a pure function: input the internal message array, output a legal message array, with unit tests covering edge cases such as “missing tool result,” “first message is an assistant message,” and “empty message.”
    4. Put injection content under version control: the repository-level context file should go through code review—it is effectively part of the source that shapes model behavior.
    5. Do periodic context checkups: measure the token share and duplication rate of each content type to identify what can be made cacheable, referenceable, or removable.

    7. Conclusion

    Back to the opening question: “You type a sentence—how much information does the model actually receive?”

    The answer: your input is only a small part of messages. In between sit the environment self-description, attachment expansion, diagnostics, tool results, and compression summaries. What truly determines an agent’s performance and cost is not how strong the model is, but whether this assembly layer does three things: semantically correct (the normalization pipeline guarantees protocol legality), budget-controlled (tiered quotas and downgrade strategies), and cache-friendly (prefix stability and block-level editing).

    When these three are done well, the actual effect and bill differences of the same model under different engineering implementations are often larger than the difference that switching models brings.