# Architecture Design and Engineering Practices for Terminal AI Coding Agents

    A terminal-based AI coding agent forms a closed loop: understanding tasks, reading code, planning steps, invoking tools, observing results, and refining its approach. This article breaks down the five-layer architecture behind such agents—interaction, session, orchestration, model adaptation, and tools—along with a two-phase plan-then-execute workflow, session persistence, permission boundaries, language server integration, file change tracking, and practical engineering guidelines for building controllable, production-ready coding agents.

    1. Why Coding Agents Are Moving into the Terminal

    Much of software development happens in the terminal: building, testing, version control, and service deployment. Editor plugins excel at local code completion, but they lack full context and execution capability when it comes to cross-file modifications, running commands, and iterating based on command output. Wrapping a large language model into an agent that runs in the terminal has therefore become a common engineering direction.

    The value of such an agent lies in forming a closed loop: understand the task, read the code, plan the steps, invoke tools, observe results, and refine the approach. Unlike a single question-and-answer exchange, the model’s output is not just text—it drives real operations. As efficiency improves, so does risk, so architecture design must be built around controllability from the very beginning.

    2. Core Architecture Layers

    A maintainable terminal coding agent is typically divided into five layers:

    1. Interaction layer: handles terminal UI rendering, keyboard input, streaming output, and approval prompts. The UI needs to display the model’s reasoning summary, tool call progress, and pending operations awaiting confirmation.
    2. Session layer: manages creation, switching, resumption, and archiving of multiple sessions, recording each round of messages and tool results.
    3. Agent orchestration layer: decides when to call the model, when to execute tools, and when to request user confirmation, while maintaining a task state machine.
    4. Model adaptation layer: abstracts away differences in request formats, authentication, and response structures across model services, decoupling upper-level logic from specific providers.
    5. Tool layer: provides capabilities such as reading and writing files, searching code, and executing commands. Each tool has a clearly defined parameter schema and permission level.

    The core benefit of layering is low replacement cost. When a model API changes or a new provider is added, only the adaptation layer needs modification—orchestration logic and UI remain untouched.

    A representative directory structure:

    1. agent-cli/
    2. ├── ui/ # Terminal UI and input handling
    3. ├── session/ # Session creation, switching, and persistence
    4. ├── orchestrator/ # Task state machine and scheduling
    5. ├── providers/ # Model adapters, one module per provider
    6. └── tools/ # File, search, and command tool implementations

    3. A Two-Phase Workflow: Planning and Execution

    Letting the model think and modify simultaneously often leads to drifting goals and uncontrolled scope. Splitting work into planning and execution phases is a more reliable approach.

    The planning phase is read-only. The agent reads the relevant files, lists the locations that need changes, the expected modifications, and how to verify them, then produces a reviewable plan. Writing files and running side-effecting commands are forbidden in this phase, and users can correct the direction here.

    The execution phase proceeds step by step according to the plan. After each step, the agent should run relevant checks—compilation, unit tests, or static analysis—and decide whether to continue, correct, or roll back based on the results. If a step’s outcome deviates from the plan, the orchestration layer should pause and return to the planning phase rather than pushing forward blindly.

    This design offers two direct benefits. First, users can review intent before any changes are made, reducing rework. Second, the plan itself becomes a traceable record, useful for post-mortems.

    An illustrative control flow (function and parameter names are for demonstration only):

    1. def run_task(task, session):
    2. plan = agent.plan(task, context=session.context(), tools=READ_ONLY_TOOLS)
    3. if not user_approves(plan):
    4. return session.record("Plan rejected, task terminated")
    5. for step in plan.steps:
    6. result = agent.execute(step, tools=ALL_TOOLS)
    7. check = run_verification(step)
    8. session.record(step, result, check)
    9. if not check.passed:
    10. return agent.replan(task, session)
    11. return session.record("Task completed")

    4. Session Management and State Persistence

    Coding tasks often span hours or even days. If sessions live only in memory, context is lost when the process exits—so persistence is required.

    Persisted data typically includes message history, tool call records, file change snapshots, and the current plan and task state. A relational database is a common storage choice, making it easy to query by session, time, and task type. The schema can be designed around three entities: a sessions table for metadata, a messages table storing conversations in order, and a tool-calls table recording parameters, outputs, and durations.

    When resuming a session, watch out for context window limits. The model cannot receive the entire history, so the system should apply strategies such as summary compression, retaining key decisions, and loading only relevant file fragments. This step directly affects output quality for long-running tasks.

    5. Tool Invocation and Permission Boundaries

    Tools are the agent’s only channel to the real environment, and their design determines the system’s security ceiling.

    Tools should be grouped into three categories:

    • Read-only: reading files, listing directories, searching text—allowed by default.
    • Write: creating or modifying files—should be confirmed by the user after showing a diff, or executed automatically within controlled boundaries.
    • Execution: running commands—should be restricted to a working directory, filtered against dangerous commands, and subject to timeouts.

    Command execution is the highest-risk area. The model may generate commands that delete directories, change permissions, or access the network. Reasonable safeguards include allowlist mechanisms, sandbox isolation, output length limits, and masking of sensitive information. Content coming from files or web pages should be treated strictly as data and never executed as instructions, to guard against prompt injection.

    6. Code Understanding and Language Server Integration

    The model’s understanding of code depends on context. The Language Server Protocol can supply more precise structural information—symbol definitions, reference locations, type information, and diagnostics. With this information, an agent that modifies a function signature can automatically locate all call sites, reducing omissions.

    A common integration approach: launch a language server process for each language, have the agent send queries through the standard protocol, then condense the returned results into concise context fragments for the model. The amount of diagnostic information must be controlled to prevent noise from flooding the context window.

    7. File Change Tracking

    When the agent modifies code, visibility into changes is critical. The system should save file snapshots before and after every write and present them in a unified diff format. Users can accept or reject modifications block by block, or roll back to the pre-task state with a single action.

    In practice, change records can be combined with version control. Each task runs in a separate branch or temporary worktree; once complete, changes are reviewed manually and merged. This preserves the agent’s efficiency while keeping unreviewed code out of the main branch.

    8. Designing the Model Adaptation Layer

    Multi-model support is a common requirement for terminal agents. The adaptation layer should provide a unified interface and encapsulate provider-specific differences in individual implementations.

    1. from abc import ABC, abstractmethod
    2. class ModelProvider(ABC):
    3. @abstractmethod
    4. def complete(self, messages: list[dict], tools: list[dict]) -> dict:
    5. """Send a conversation and return the model output,
    6. including text and tool call requests."""
    7. class ProviderRegistry:
    8. def __init__(self):
    9. self._providers = {}
    10. def register(self, name: str, provider: ModelProvider):
    11. self._providers[name] = provider
    12. def get(self, name: str) -> ModelProvider:
    13. if name not in self._providers:
    14. raise KeyError(f"Unregistered model provider: {name}")
    15. return self._providers[name]

    This abstraction lets configuration simply declare which provider to use, and supports local and cloud models side by side. For models that do not support tool calling, the adapter can degrade to a plain-text mode, with the orchestration layer informing the user that capabilities are limited.

    9. Engineering Practice Guidelines

    1. Split configuration into global and project-level settings, with project-level values overriding global ones. Secrets must be read from environment variables or a dedicated secrets management service—never written into config files committed to the repository.
    2. Set timeouts and output limits for every tool to prevent a single call from blocking the entire task.
    3. Keep complete audit logs, including model request summaries, tool parameters, and execution results, to facilitate incident investigation.
    4. For team use, standardize permission policies—for example, forbidding agents from accessing production credentials and deployment scripts.
    5. When evaluating effectiveness, don’t just look at generation speed. Track one-shot task success rate, rollback count, and manual correction time as well.

    10. Conclusion

    The key to terminal coding agents is constraining model capabilities within clear workflows and permission boundaries. A layered architecture makes models replaceable, separating planning from execution makes changes reviewable, session persistence makes long tasks resumable, and strict tool permissions keep the system controllable. Teams adopting this approach can start with read-only assistance and plan generation, gradually opening up write and execution capabilities, and validating the benefit of each step with quantifiable metrics.