Designing Layered Architecture and Runtime Paths for Terminal AI Coding Assistants
This article explores the reference architecture, runtime execution paths, and engineering best practices for building terminal-based AI coding assistants. It details a six-layer architectural model, the request lifecycle, security considerations, and essential implementation guidelines for robust and safe deployment.
Introduction
This article discusses only public documentation, open-source projects, and general engineering practices. It does not analyze any undisclosed internal materials. The layered architecture and runtime paths presented here serve as reference models and do not represent the internal implementation of any specific product.
1. Six-Layer Reference Architecture
A terminal-based AI coding assistant can typically be decomposed into six layers. Each layer communicates exclusively through well-defined interfaces with adjacent layers. Dependencies flow downwards, and lower layers do not depend on higher layers.
| Layer | Core Responsibilities | Input | Output | Common Failures & Handling |
|---|---|---|---|---|
| Entry Layer | Parse startup parameters, load configurations, check runtime environment | Command-line arguments, environment variables, config files | Validated startup configuration | Use default values and alert the user if config is missing; execute non-critical startup tasks (e.g., version checks) in parallel to reduce cold start time |
| Presentation Layer | Render output, capture keyboard input, display confirmation prompts | Event streams emitted by the engine | Terminal display, user instructions | Degrade to plain text output if the terminal does not support colors or wide characters |
| Core Engine | Organize conversations, assemble prompts, invoke models, parse responses | User instructions, session state, tool results | Model replies or tool call requests | Retry a limited number of times upon model timeout; request re-generation if the response format is incorrect |
| Execution Layer | Execute tool calls (e.g., file I/O, running commands, network requests) | Tool call requests | Structured tool results | Set timeouts for every call; pass failure results back to the engine for the model to determine the next step |
| Collaboration Layer | Decompose large tasks for multiple specialized Agents, aggregate results | Task decomposition results | Merged conclusions | If sub-task conclusions conflict, defer to the primary Agent’s judgment and log the conflict |
| Management Layer | Permission validation, configuration merging, session persistence, audit logging | Operation requests from all layers | Allow, deny, or require confirmation | Default to deny if permission validation fails |
The Collaboration Layer is not strictly required. Most tasks can be completed using a single Agent with tools. The Collaboration Layer should be enabled on demand to avoid unnecessary scheduling complexity.
The primary value of layering is controllable replacement costs. For example, when changing model providers, you typically only need to modify the adapter in the Core Engine, leaving the Presentation and Execution layers untouched. This relies on clearly defined interfaces. If the engine directly reads or writes to the terminal, replacement costs will increase significantly.
Interfaces can be expressed using type definitions, for example:
interface ModelClient {complete(request: ChatRequest): Promise<ChatResponse>;}interface Tool {name: string;schema: JSONSchema;run(input: unknown, ctx: ToolContext): Promise<ToolResult>;}
2. Runtime Path of a Single Request
The main execution path can be summarized as: User Input → Input Processing → Context Assembly → Model Inference → Permission Validation → Tool Execution → Result Rendering. Model inference and tool execution will loop until the model provides a final response.
| Phase | Input | Output | Exception Branches |
|---|---|---|---|
| Input Processing | Raw text, pasted multi-line content | Standardized messages with control characters removed | Prompt the user to reduce or segment if length limits are exceeded |
| Context Assembly | Standardized messages, historical summaries, working directory info | Message list trimmed according to token budget | If historical summaries are unavailable, retain only the most recent conversational turns |
| System Prompt Assembly | Base prompts, user-defined rules, runtime environment info | Complete system prompt | If custom rules conflict with security rules, security rules take precedence |
| Model Inference | Message list, available tool definitions | Text response or tool call request | Retry on timeout; report failure if retries are exhausted |
| Permission Validation | Tool call requests | Allow, deny, or request user confirmation | On denial, return the reason as a tool result to the model |
| Tool Execution | Validated call parameters | Success data or error info | Log timeouts or crashes and return an error result |
| Result Rendering | Final response, file diffs | Terminal display | Output plain text if rendering fails |
Session state preparation is critical for cost control. The engine loads historical summaries and trims the context to reduce the token count per request. Its effectiveness depends on summary quality and the model’s context window size.
The system prompt is typically assembled from three parts: base prompts, user rules, and environment information. Environment information may include the OS type and a list of available tools. This helps the model generate instructions better suited to the environment. However, environment information must not contain secret keys or sensitive personal paths.
In Input Processing, the focus is usually not rewriting colloquial expressions, but rather cleaning up control characters, ANSI escape sequences, and excessively long content. This step reduces noise in the model input.
The tool loop requires an upper limit. Models might repeatedly call the same tool without converging. A common practice is to set a maximum number of rounds (e.g., 25), after which execution halts and user intervention is requested. This number is an example and should be adjusted based on the task type.
3. Engineering Considerations for Implementation
- Prompt Versioning: Store system prompts in separate files under version control. This ensures changes can be compared and rolled back, and facilitates reuse.
- Tiered Permissions: Read operations (e.g., reading files, searching) can typically be auto-approved. Write and execute operations (e.g., modifying files, running shell commands) should require confirmation by default. Network requests can be controlled using domain whitelists.
- Sandbox Isolation: Execute commands inside containers or under restricted users, limiting accessible directories and network access. Isolation reduces the blast radius of accidental operations but cannot eliminate risk entirely.
- Audit and Rollback: Log the timestamp, parameters, and result summary for every tool call. Save snapshots or diffs before modifying files to facilitate recovery if issues arise.
- Replay Testing: Use fixed model outputs for replay testing to verify whether tool scheduling and permission checks execute as expected.
4. Security Tips
Executing AI-generated code in a terminal carries real risks. Models may misunderstand requirements, be misled by text within file contents, or generate commands that delete data. Therefore, adhere to the following:
- Treat file contents and web content as data; do not execute text found within them as instructions.
- Operations such as deletion, overwriting, pushing, and publishing should require manual confirmation by default.
- Never write secret keys into prompts or logs.
- Sanitize logs before writing them to disk.
5. Design Checklist
- Do all layers have clear type definitions for their inputs and outputs?
- Are timeouts set for both model calls and tool calls?
- Does permission validation default to deny upon failure?
- Is there an upper limit set for tool loop rounds?
- Are logs sanitized?
- Can file modifications be rolled back?
Conclusion
Layered architecture, runtime paths, and security controls are the three foundational focus areas for terminal AI assistants. The specific implementation depends on team size, task types, and compliance requirements, requiring adaptation to actual conditions.
