AI Coding Agent Architecture: Layered Design, Parallel Startup, and Permission Governance

    This article explains the architectural design of terminal-based AI coding agents, covering a six-layer layered structure, a parallelized startup pipeline, the main inference loop with budget controls, multi-level permission governance for tool execution, and context compression with long-term memory. It also provides practical engineering checklists for building similar systems, applicable to any AI application that executes actions in a local environment.

    Why Terminal Agents Deserve Dedicated Study

    A terminal agent is a program that runs in a developer’s local command-line environment. It can read code, execute commands, call external tools, and interact with a large language model over multiple turns. Unlike a simple Q&A interface, it has the ability to operate on local files and processes, while still needing to guarantee response speed, operational safety, and controllable context. These three constraints pull against each other, making terminal agents a classic test case for AI application engineering.

    The value of studying such systems is that they force model capability, systems engineering, and security governance to be considered together within a single runtime. Developers building similar products commonly run into problems such as slow startup, context overflow, tool misuse, and state confusion. The analysis below uses these problems as a thread and explains workable solutions layer by layer.

    A Six-Layer Architecture

    A maintainable agent system is typically divided into six layers by responsibility. Each layer depends only on the interface of the layer directly below it, avoiding cross-layer calls.

    1. Entry and startup layer: parses command-line arguments, initializes the runtime environment, and decides whether to enter interactive mode or batch mode.
    2. Interaction and presentation layer: handles terminal UI rendering, input editing, progress feedback, and permission confirmation dialogs. Presentation logic is separated from business logic so the rendering approach can be swapped out.
    3. Core inference engine layer: maintains session state, assembles prompts, drives the conversation loop with the model, and handles streaming output and stop conditions.
    4. Tool execution layer: encapsulates concrete actions such as file reads and writes, code search, command execution, and external protocol tools, exposing a unified invocation interface to upper layers.
    5. Collaboration and extension layer: manages subtasks, division of work among multiple agents, and connections to external services or remote sessions.
    6. Governance and state layer: centrally manages permission rules, configuration items, feature flags, and persistent state, providing read-only or controlled access to other layers.

    The core benefit of layering is change isolation. Replacing the UI framework does not require changes to the inference engine; adding a new tool only requires adding entries to the permission rules in the governance layer.

    The Main Execution Pipeline

    The full processing of one user request can be summarized as: input handling, context building, model inference, tool dispatch, and result rendering. The order of these stages is clear, which makes it easy to locate problems.

    1. function handleTurn(userInput, session):
    2. message = normalizeInput(userInput) // strip control characters, resolve references and attachments
    3. context = buildContext(session, message) // merge system instructions, project notes, and history
    4. loop:
    5. response = model.generate(context) // streaming request to the model
    6. if response.hasToolCalls():
    7. for call in response.toolCalls:
    8. decision = permissionCheck(call, session.policy)
    9. if decision == DENY: record(call, "rejected")
    10. else: result = executeTool(call); context.append(result)
    11. continue
    12. break
    13. render(response, session)

    The input handling stage performs normalization, including removing invisible characters, expanding file references, and recognizing slash commands. The context building stage determines what the model can see, which directly affects both answer quality and token consumption. The loop stage feeds tool results back into the context until the model no longer requests tools.

    Parallelizing the Startup Phase

    Terminal tools are highly sensitive to first-screen response time. If all initialization steps run serially, users feel a noticeable wait. A common practice is to split mutually independent tasks into several parallel stages:

    • Stage 1: While loading core modules, asynchronously read access tokens from the system credential store and pre-establish a network connection to the model service, eliminating the handshake latency of the first request.
    • Stage 2: Parse command-line arguments to determine the session type while fetching remote feature flags. Feature flags need a local cache and a timeout fallback so network failures do not block startup.
    • Stage 3: Switch to the terminal’s alternate screen and show the trust confirmation or onboarding flow. This step must complete before any permission decision, otherwise the user cannot confirm whether the directory is trustworthy.
    • Stage 4: Establish external tool protocol connections, load project-level instruction files, and then render the interactive interface.

    Two points require attention when parallelizing. First, every task needs a timeout and a failure degradation strategy—the failure of a single task must not cause the entire startup to fail. Second, tasks with dependencies must be explicitly ordered; for example, permission configuration must finish loading before any tool executes.

    The Query Loop and State Transitions

    The inference loop is the part of an agent most prone to running out of control. It needs explicit termination conditions and budget constraints. Common control dimensions include a maximum number of turns, a token budget, a per-tool-call time limit, and cumulative cost.

    1. state = RUNNING
    2. while state == RUNNING:
    3. if turns >= maxTurns or tokensUsed >= tokenBudget:
    4. state = STOP_BUDGET
    5. elif context.size > compactThreshold:
    6. context = compact(context) // compress history, keep key decisions
    7. else:
    8. response = model.generate(context)
    9. state = nextState(response)

    Every state transition should be logged to support post-hoc review. For example, when a loop stops because the budget is exhausted, the logs should make clear which tools were executed and which steps remain unfinished.

    The Tool System and Permission Adjudication

    Tools are the agent’s only way to affect the outside world, so permission design is critical to safety. A robust approach is multi-level adjudication, where a rejection at any level terminates the operation.

    1. Tool level: Each tool declares its own risk level, such as read-only, write, command execution, or network access. A tool can validate parameters internally and reject out-of-bounds paths or dangerous parameter combinations.
    2. Rule level: Pattern-based allow or deny rules are matched against paths, command prefixes, domain names, and so on. Rules follow a default-deny policy; operations that match no rule require user confirmation.
    3. Mode level: Different operating modes are offered, such as ask every time, auto-allow reads, or auto-execute within a restricted directory. The mode determines how often the user is interrupted, but it cannot bypass the hard limits enforced at the tool level.

    Permission outcomes should be auditable. Every adjudication records the request content, the rule that was matched, and the final decision, which helps both troubleshooting and enterprise compliance review.

    Context Compression and Long-Term Memory

    Long conversations exhaust the context window, so compression is a necessary mechanism. A common strategy is that when the context approaches a threshold, earlier dialogue and tool outputs are summarized into a short digest, while unfinished tasks, key constraints, and explicit user preferences are preserved. The original records should be retained before compression so they can be traced back when needed.

    Information that must span sessions should not rely on the context itself but be handed to an independent memory system. Memory can be stored by category—for example, project conventions, user preferences, and task progress—and retrieved and injected on demand when a new session starts. Memory content needs periodic cleanup to prevent outdated information from misleading the model.

    Practical Engineering Recommendations

    When building a similar system, the following checklist can serve as a reference:

    • Are the input and output interfaces of each layer clearly defined, and can each layer be tested independently?
    • Do startup tasks have timeouts and degradation paths?
    • Does the loop have budget, turn-count, and cancellation mechanisms?
    • Do tools declare risk levels, and do permission rules default to deny?
    • Are compression and memory traceable and cleanable?
    • Do key decisions produce structured logs that support auditing and reproduction?

    These principles do not depend on any specific product; they apply to any AI application that needs to perform actions locally. In implementation, start with a minimal viable inference loop and permission mechanism, then gradually add parallelization optimizations, memory, and multi-agent collaboration—avoid expanding features prematurely before the boundaries have stabilized.