Coding Agent Architecture Review: Entry, REPL, Tooling, Context, Memory, and Prompting

    This article outlines a general architecture for coding agents, covering entry routing, the REPL loop, command and tool systems, context compression, persistent memory, and prompt engineering. It also examines practical risks, validation ideas, and an architecture checklist for designing or assessing such systems.

    Coding Agent Architecture Review: Entry, REPL, Tooling, Context, Memory, and Prompting

    This article summarizes common design patterns for this class of system. It does not focus on the source code of any specific product. Implementations vary by product, and the parameters and code shown here are examples. They should be validated against your own models and tasks before use.

    1. Startup and Entry Routing

    A coding agent usually has multiple entry points. Terminal command-line arguments, standard input pipes, and RPC requests from IDE plugins can all trigger a session. The entry layer’s job is to normalize these inputs into internal events so that downstream modules only need to handle one data structure.

    A common approach is to define an enum of input types, such as cli_prompt, pipe_input, rpc_request, and resume_session. Each entry point first produces an event of the corresponding type, and a dispatcher calls the initialization handler based on that type. The dispatcher can be implemented as a mapping table or as strategy objects; either approach keeps entry-specific logic isolated at the boundary.

    Permission checks should happen before entering the core engine. Non-interactive sources such as pipe input often need stricter checks than terminal interaction because no human is confirming in real time. If an IDE RPC interface listens only on a local port without authentication, other processes on the same machine may be able to call it. It should therefore bind to the local loopback address and use a session token.

    There should be a clear fallback path on failure. When arguments are invalid, the program should print usage information and return a non-zero exit code. When an RPC connection drops, unsubmitted input drafts should be preserved so the user does not have to re-enter them.

    2. The REPL Interaction Loop

    The read, evaluate, print, and loop stages of a REPL differ noticeably from ordinary command-line tools in an agent setting. Ordinary tools usually map one request to one response, while an agent session must maintain long-lived state.

    The read stage needs to handle multi-line input, keyboard shortcuts, and pending confirmations. The evaluate stage passes input to the core engine, which may initiate multiple rounds of model calls and tool calls. The print stage not only outputs text but also renders syntax highlighting and code diffs.

    Session state should include at least the following fields: session_id, the message history, an unsubmitted input buffer, the current working directory, and a queue of operations waiting for user confirmation. State can be written to disk before and after each tool-call round so that if the process is interrupted, the session can resume from the most recent complete step.

    When the user presses the interrupt key, the system needs to determine what operation is currently in progress. Canceling a model request is usually safe. If the interruption occurs during a file write, the system should check whether the file has already been partially written and decide whether to roll back or keep the change based on the result.

    Memory growth is a common issue in long sessions. Message history, large logs, and full diff output all consume space. Very long output should be truncated or replaced with file path references. Child processes and event subscriptions should also be explicitly closed after a task ends; otherwise, they will continue to accumulate.

    Memory behavior can be tested with a simple stress test: send 50 consecutive rounds of requests and record the process’s resident set size (RSS) for each round. If the interrupt key is pressed mid-session and the process is restarted, check whether the session can recover to the most recent complete step. This test only shows behavior in a specific scenario; it does not prove that there are no leaks during long-term operation.

    3. Command System and Tool System

    The command system handles user meta-operations such as viewing history, switching workspaces, and changing configuration. Commands usually start with a fixed prefix, and parsing often uses lexical splitting or regular expression matching. A full abstract syntax tree is worth introducing only when command syntax becomes complex.

    Commands should go through argument validation and permission checks before execution. A plugin mechanism allows third parties to register commands, but it should limit the resources plugins can access and record which commands each plugin registers so conflicts can be diagnosed.

    The tool system is the interface through which the agent interacts with the external environment, such as reading files, searching code, and running tests. Tools usually describe input parameters and side effects with JSON Schema. Below is an example definition:

    1. {
    2. "name": "read_file",
    3. "description": "Read a text file within the workspace",
    4. "input_schema": {
    5. "type": "object",
    6. "properties": {
    7. "path": {"type": "string"},
    8. "max_bytes": {"type": "integer", "maximum": 200000}
    9. },
    10. "required": ["path"]
    11. },
    12. "side_effects": "none"
    13. }

    When executing a tool, the scheduler needs to handle timeouts and exceptions. Pseudocode:

    1. result = dispatch(tool, args, timeout=30s)
    2. if timeout:
    3. return {error: "timeout"} to model
    4. # Do not automatically retry write operations to avoid duplicate changes
    5. if exception:
    6. wrap error, redact secrets, return to model

    The tool layer has three common risks. The first is path traversal, where a path in the arguments points outside the workspace; this should be checked inside the tool using a normalized path. The second is accidental invocation: the model may call a write-operation tool at an inappropriate time, so write operations should have a confirmation step. The third is output leakage: tool responses may contain secrets, so they should be redacted before being returned to the model.

    4. Context Management and Compression

    The model itself has no memory; every call depends on the context passed in. As a session grows longer, the context approaches the model’s window limit.

    One feasible approach is to set two thresholds. For example, start compression when window usage reaches 70%, and force compression when it reaches 90%. These numbers are only examples and should be adjusted based on the model’s window size and the task type.

    Retention policy matters more than the eviction algorithm alone. LRU (least recently used) works well for caches, but session messages have dependencies, and an early agreement may still be valid later. A common practice combines time and importance: keep the most recent N rounds of raw text (for example, 6 rounds), system instructions, and the state of unfinished tasks, then summarize older content.

    There are three main compression methods. Summary extraction condenses early multi-round conversations into short paragraphs. Code block folding replaces long code that has already been executed with a summary, keeping only the file path, exit code, and key error lines. Redundant whitespace cleanup directly removes extra blank lines and indentation.

    Compression effectiveness should be measured with data. You can count tokens with the same tokenizer before and after compression, record task success rates, and prepare a set of questions to test whether the model can answer content from early agreements, then calculate the retention rate of key facts. Without this data, it is impossible to judge whether compression harms task quality.

    The biggest risk in compression is losing constraints. For example, if the user previously said “do not modify a certain configuration file” and that rule is lost during summarization, later operations may violate the user’s intent. Constraints explicitly given by the user should be marked as non-summarizable items and retained in their original form.

    5. Persistent Memory

    Information that spans sessions is usually stored in local files, such as project build commands, code style conventions, and user preferences. At session startup, the system reads these files and injects them into the system prompt.

    This mechanism can be compared to an operating system’s swap partition, but the purpose and cost differ. A swap partition handles memory paging, while memory files inject semantic information into the model input. The analogy is only for intuition and does not imply the same implementation.

    Memory files have several issues to watch. First, content may become outdated. If project build commands change, old memory may still be injected, so write timestamps should be recorded and users should be allowed to update or delete entries. Second, content may contain sensitive information; keys and tokens should not be written to memory files. Third, size can grow. Injecting too much memory consumes the context window, so limits and relevance-based filtering should be applied.

    Users should be able to view and edit memory files. When incorrect memory appears, users can then correct it directly instead of relying on the model to judge it on its own.

    6. Prompt Engineering

    Prompts serve as control logic in an agent system, but their enforcing power is limited.

    Negative instructions are a common pattern, such as “do not modify unmentioned files without confirmation.” The model may not follow them every time, so such instructions should be paired with permission allowlists at the tool layer. Rules must be enforced at the tool layer; writing them only in the prompt is not enough.

    A structured meta-prompt can help the model distinguish different parts of the content more clearly. One common partitioning approach is shown below:

    1. <role>You are a code modification assistant and only handle files within the current workspace</role>
    2. <task>Fix the specified test based on the user's description</task>
    3. <tools>read_file, search_code, run_tests, write_file (requires confirmation)</tools>
    4. <constraints>Do not modify unmentioned files without confirmation; do not commit code</constraints>
    5. <output_format>First provide a plan, then provide a summary of changes</output_format>

    A validation agent reviews the main agent’s output. Its activation conditions should be explicit, for example, only when code has been modified and a test command exists. The number of loops should also have a limit, such as at most 3 rounds, after which it stops and returns the result to the user. Each validation adds token consumption and response time, so it can be enabled only for high-risk changes rather than for every operation.

    7. Architecture Checklist

    The analogy from tools to operating systems helps explain which resources an agent needs to manage: token budget, task flow, files and memory, and a unified invocation interface. This analogy is only for building intuition and does not describe a specific implementation.

    When designing or evaluating an agent system, start by checking the following points:

    1. Does each module have clear input and output types?
    2. Are permission checks enforced at the tool layer rather than relying only on prompts?
    3. Does context compression have before-and-after evaluation data?
    4. Can write operations be undone, or do they require user confirmation?
    5. Can memory content be viewed, modified, and deleted by users?

    8. Conclusion

    When reading the source code of this kind of system or building a similar agent from scratch, it is reasonable to start with the entry layer and the tool layer. The boundaries of these two areas often determine permissions, security, and the complexity of subsequent modules.