AI Coding Assistants: A Practical Layered Architecture

    A terminal-based AI coding assistant needs more than a chat interface: it must manage context, tool execution, permissions, task delegation, and recoverable state. This article outlines a six-layer architecture and explains how clear boundaries, structured events, centralized side effects, and enforceable policies make agent systems easier to replace, test, and audit.

    Putting an AI coding assistant into a developer’s everyday terminal is not simply a matter of adding another chat window. The assistant must handle environment discovery, long conversations, tool side effects, permission requests, and coordinated task delegation.

    When source code is available for review, the most valuable lesson is rarely a particular prompt. It is whether the architecture makes these responsibilities independently replaceable, testable, and auditable. The following engineering approach provides a practical reference for developers building their own agent systems.

    1. Start with the Execution Loop, Not the Model

    A mature design typically separates the system into six layers:

    • Entry: Starts the process and prepares the environment.
    • Presentation: Turns system state into a readable terminal interface.
    • Conversation engine: Exchanges messages with the language model, maintains context, and determines the next step.
    • Execution: Converts intended actions into tools or commands whose execution can be inspected.
    • Collaboration: Handles subtask delegation and remote handoffs.
    • Management: Governs permissions, configuration, and runtime state across the system.

    The criteria for these boundaries are concrete. Higher layers may depend on lower-layer abstractions, but lower layers should not know about interface wording or the tone of a particular user message. When a layer fails, logs should identify the boundary involved. Debugging should not require editing prompts, assembling commands, and refreshing the screen inside one enormous function.

    Loose coupling is not about splitting code into as many files as possible. It is about keeping code with different reasons to change from being tied to the same release.

    2. Entry Layer: Treat Startup as a Contract

    The entry layer generally has two responsibilities: starting the main workflow and initializing the environment before conversation begins.

    Initialization should answer a set of deterministic questions:

    • What is the working directory?
    • Where are identity information and credentials read from?
    • Which paths may the assistant access?
    • What are the default model and timeout?
    • Is the session running in read-only or dry-run mode?

    These answers should become an explicit configuration object rather than scattered environment-variable reads.

    A sound startup sequence fails early and delays side effects. First, validate configuration and dependencies. Next, initialize logging and tracing identifiers. Only then enable capabilities that can modify the workspace.

    Initialization failures should provide actionable explanations, such as a missing credential or an unwritable directory. They should not surface as vague errors after the model has already begun planning.

    For most developers, implementing this environment contract with pure functions and a few adapters matters more than introducing a complex framework early.

    3. Presentation Layer: The Terminal Is a Projection of State

    A terminal interface can offer streaming output, collapsible tool calls, highlighted diffs, and confirmation prompts. The important boundary is that the interface presents state; it does not make business decisions.

    A useful data flow is:

    1. The engine emits structured events, such as text deltas, tool starts, tool results, authorization requests, and task completion.
    2. The interface renders those events and collects user input.
    3. User input is passed back to the engine.

    This separation has three benefits. The same event stream can drive the terminal, logs, and a future graphical interface. Rendering slowdowns do not corrupt the conversation state machine. Tests can assert event sequences without launching a real terminal.

    Components should be organized around responsibilities such as the message list, input area, permission dialog, and progress indicator. Avoid a single rendering function that reads global mutable objects.

    4. Conversation Engine: Large, but Decomposable

    The conversation engine often contains the most code because it handles context trimming, tool selection, retries, streaming parsing, and stopping conditions. Its size does not justify turning it into a god object.

    Break the engine into stages:

    1. Assemble context.
    2. Call the model.
    3. Parse model output.
    4. Dispatch tool calls.
    5. Write tool results back into context.
    6. Decide whether to continue.

    Each stage should have explicit input and output structures rather than an indefinitely growing dictionary.

    Context management needs a budget. Conversation history, tool results, and system constraints compete for the context window, so their priorities must be defined. Safety and permission constraints must not be dropped. Recent tool results should take precedence over early casual conversation. Very large file contents should be replaced with summaries and references.

    Retries must distinguish transient failures from deterministic ones. Permission denials and invalid arguments should not trigger pointless retry loops.

    Stopping logic should account for three conditions: the model declaring completion, the iteration limit being reached, and the user interrupting the task. Any one of these should cause a clean exit while preserving the current execution state.

    The stage interfaces can remain lightweight:

    1. assemble(context) -> model_request
    2. interpret(model_stream) -> events
    3. dispatch(tool_call, policy) -> tool_result
    4. reduce(context, tool_result) -> context

    The engine should not execute operating-system commands directly. It should only express tool-call intent. This is the first structural safeguard against treating model output as executable code.

    5. Execution Layer: Separate Tools from Commands

    Tools represent capabilities, such as reading files, applying patches, searching symbols, and running tests. Commands represent reusable user actions, such as clearing a session, exporting a transcript, or switching modes.

    Both need a name, parameter schema, side-effect classification, and human-readable description. Their lifecycles, however, differ. The model invokes tools when policy permits. Users usually trigger commands explicitly; the model should not simulate user commands to bypass confirmation.

    Each tool should declare:

    • Whether it is read-only.
    • Whether it can modify the workspace.
    • Whether it accesses the network.
    • Its timeout and output-size limits.

    The executor is responsible for argument validation, path normalization, terminating timed-out operations, output truncation, and error classification.

    The model should receive stable error codes and summaries, not an unfiltered dump of environment details.

    Patch tools should calculate the diff, apply it, and then validate the result. If the operation fails, they should roll back to the state before that tool invocation, avoiding partial writes.

    6. Collaboration Layer: Multi-Agent Work Is Orchestration

    Complex tasks naturally divide into subtasks such as exploration, modification, and verification. The central engineering question in multi-agent collaboration is what to share and what to isolate.

    Agents should share task goals, constraints, and confirmed facts. Their draft contexts and tool quotas should remain separate so that one subtask’s lengthy logs do not overwhelm the main conversation.

    Remote handoffs—for example, moving a long-running task to a persistent compute environment—should transfer only the task description, input artifacts, and callback identifiers. Local secrets should not be copied into the remote environment unchanged.

    Delegation requires observable parent-child relationships: who initiated the subtask, what budget it received, and how its results will be merged.

    Merging should rely on verifiable artifacts, such as whether tests pass or a diff can be applied, rather than an agent’s assessment of its own work. Calling another model for help without audit identifiers quickly creates a black box that cannot be reproduced.

    7. Management Layer: Permissions, Configuration, and State

    The permission system should deny high-risk actions by default. Reading a public workspace, writing files, executing commands, and accessing the network have different risk levels and should require different levels of confirmation.

    Session-scoped grants, directory-scoped grants, and command-pattern grants can coexist. All must be revocable, and the interface should display their currently effective scope.

    Policy checks belong before execution. They should not depend on the model remembering an instruction to avoid dangerous actions.

    Configuration should have three layers: defaults, project settings, and user overrides. Merge rules must be stable and printable so that different modules do not interpret the same configuration key differently.

    Runtime state includes session identifiers, message logs, pending approval queues, and unfinished tool operations. Persistence should answer a practical question: after a process crash, can the system recover to its last consistent point?

    Using an immutable event log as the source of truth and deriving the current interface from it is generally more reliable than directly serializing a collection of mutable objects.

    Teams that need long-term conversation traces and audit records can store event logs in object storage and use logging, monitoring, and alerts to track timeouts, permission-denial rates, and tool failure categories.

    General-purpose object storage, logging, and monitoring capabilities offered by Baidu AI Cloud can serve as infrastructure for this purpose, where available. They should not replace application-level permission and state design. The application must still define its own event schemas and retention periods, avoiding tight coupling between business semantics and a particular storage interface.

    8. What to Learn When Reviewing Source Code

    The most transferable lessons are engineering habits:

    1. Connect layers with events, not strings. Strings belong at presentation and model boundaries.
    2. Centralize side effects in the executor. Every operation should be subject to policy and timeout controls.
    3. Give large modules narrow stage interfaces. Tests should be able to substitute models and tools.
    4. Make safety policies executable. Rules should exist in code, not only in system prompts.
    5. Assign a trace identifier to every user request. Carry it through model calls and tool logs.
    6. Control extension points. Add tools through a registry rather than modifying the engine’s main loop.

    These practices do not depend on any particular terminal assistant. They determine whether an agent can progress from a demonstration to everyday engineering use.

    Establishing the six-layer boundaries before filling in models and tools makes later changes less expensive—whether that means replacing the interface, tightening permissions, or delegating parts of a task to other agents.