A Unified Shell for CLI AI Coding Agents: Architecture and Practice

    CLI AI coding agents are fast to adopt but hard to manage: sessions stay isolated, outputs are hard to inspect, file changes are scattered, and skills are often loaded all at once. This article explains a three-layer shell that wraps those agents through stdin/stdout and the filesystem, covering CLI adapters, on-demand skills, SQLite session storage, and live previews.

    1. Why a Unified Shell: Real Pain Points of CLI AI Tools

    Over the past two years, large-model coding assistants that run in the terminal have become everyday tools for engineers. The core interaction is simple: the user types a natural-language instruction, and the agent reads the codebase, runs commands, edits files, and prints results. This form is easy to build and quick to iterate, but real engineering work exposes several structural problems.

    1. Isolated sessions. Most CLI agents run as one terminal process per session. When a developer works on several tasks at once—for example, refactoring one module while investigating a defect in another service—they often need multiple terminal windows. Sessions do not see each other, context cannot be shared, and switching is costly.

    2. Interaction that is hard to see. A terminal is a good fit for text streams, but a poor fit for structured artifacts. Markdown documents, tables, code diffs, and even PDF reports generated by the agent scroll past as raw text. It is hard for a developer to judge quality quickly.

    3. Fragmented file operations. Which files the agent changed, what those changes were, and whether unexpected edits were introduced are scattered between the conversation log and the filesystem. There is no single place to observe them. Developers often have to run diff commands afterward just to audit what happened.

    4. Coarse capability injection. Many agents can be extended with skill files or prompt templates, but a common approach is to load everything at startup. That slows initialization and can pollute the context.

    These problems point to the same conclusion: what CLI agents lack is not model capability, but a surrounding system that contains them. That is the value of a unified shell. It does not build a model and does not replace the agent. It provides a unified wrapper at the architecture level.

    2. Overall Architecture: A Three-Layer Decoupled Shell

    A well-designed unified shell is usually split into three layers:

    1. ┌─────────────────────────────────────┐
    2. │ Interaction: multi-session UI / │
    3. │ preview panel / editor │
    4. ├─────────────────────────────────────┤
    5. │ Orchestration: CLI adapters / │
    6. │ capability manager / storage │
    7. ├─────────────────────────────────────┤
    8. │ Execution: CLI agent processes │
    9. └─────────────────────────────────────┘

    The execution layer stays as it is. CLI agents from different vendors keep doing their own work, and the shell does not enter their internal logic. The orchestration layer is the core. It manages processes, schedules capabilities, and persists data. The interaction layer turns what is invisible in the terminal into a visual interface.

    The key to this split is that the shell and the agent interact only through process stdin/stdout and the filesystem. That is an important architectural decision. It lets the shell adapt to any agent that follows a command-line protocol, without depending on private interfaces.

    3. Key Technical Modules

    1. CLI Auto-Detection and the Adapter Pattern

    Agents differ in startup commands, argument styles, and output formats. The shell needs a detection mechanism: scan the system PATH, identify installed agent executables, and attach the matching adapter for each type.

    1. interface AgentAdapter {
    2. detect(): Promise<boolean>; // Check whether the CLI is available
    3. buildCommand(task: string): string[]; // Build the startup command
    4. parseOutput(chunk: string): AgentEvent; // Parse the output stream into structured events
    5. }
    6. class AdapterRegistry {
    7. private adapters = new Map<string, AgentAdapter>();
    8. async scanAll() {
    9. for (const adapter of this.registered) {
    10. if (await adapter.detect()) {
    11. this.adapters.set(adapter.name, adapter);
    12. }
    13. }
    14. }
    15. }

    Detection results should also be version-cached and health-checked. After an agent upgrade, its arguments may change. Adapters need fault tolerance and graceful degradation so that a change in one CLI does not take down the whole shell.

    2. On-Demand Capability Loading (SkillManager)

    A skill is essentially a preset prompt template, tool description, or workflow definition. Loading every skill at once fills the model context with unrelated content, which both increases token use and can distract the model from the task.

    A better approach is lazy loading plus task matching:

    • The shell keeps a skill index (name, description, trigger keywords, and file path).
    • When the user starts a task, the shell first matches the task description lightly (by keywords or vector similarity) and injects only the skills that hit into the current session.
    • The skill directory is kept separate from the configuration directory so users can add their own extensions.
    1. class SkillManager {
    2. private index: SkillMeta[] = [];
    3. async loadForTask(taskDesc: string, topK = 3): Promise<Skill[]> {
    4. const scored = this.index
    5. .map(s => ({ s, score: matchScore(taskDesc, s.keywords) }))
    6. .sort((a, b) => b.score - a.score)
    7. .slice(0, topK);
    8. return Promise.all(scored.map(x => readSkillFile(x.s.path)));
    9. }
    10. }

    This pattern matches the widely accepted idea of retrieval augmentation: do not stuff the knowledge base into the context; retrieve precisely when it is needed.

    3. Local Persistence for Multiple Sessions: SQLite Is the Practical Choice

    Persisting session data requires a balance. The store must support structured queries (filter by project, time, or status) while remaining usable offline and under the user’s own control. An embedded relational database is the most practical choice. It needs no separate server process, stores data in a single file, and provides full transactions, which fits a desktop-class shell.

    A useful table granularity is:

    1. CREATE TABLE sessions (
    2. id TEXT PRIMARY KEY,
    3. agent_type TEXT, -- Agent type in use
    4. project_path TEXT, -- Associated codebase path
    5. status TEXT, -- running / finished / failed
    6. created_at INTEGER
    7. );
    8. CREATE TABLE messages (
    9. session_id TEXT,
    10. role TEXT, -- user / agent / tool
    11. content TEXT,
    12. tool_calls TEXT, -- Tool-call records (JSON)
    13. ts INTEGER
    14. );

    Storing tool-call records as structured data is valuable for later audits. It can answer questions such as which commands the agent ran in a session and which files it changed, instead of forcing someone to scroll through the chat log.

    4. Preview Panel: Turning Generated Output into Readable Artifacts

    The preview panel is where the shell’s experience differs most. Design points include:

    • Format routing: Dispatch by file extension or MIME type to the matching renderer. Render Markdown as rich text, CSV and tables as sortable tables, PDFs in an embedded viewer, and code diffs in a side-by-side view.
    • Live watching: Use filesystem watching (the file-watch capability provided by each platform) to monitor the agent’s working directory. Refresh the preview as soon as an artifact is written, without a manual refresh.
    • A read-only boundary: The preview panel is read-only by default. Editing is directed back to the editor so the two do not write the same file at once.
    1. const watcher = watch(workspaceDir, { recursive: true });
    2. watcher.on('change', async (path) => {
    3. if (isPreviewable(path)) {
    4. const rendered = await renderRoute(path);
    5. pushToPanel(rendered); // Incrementally push to the UI
    6. }
    7. });

    The diff view matters especially. Each file change by the agent should automatically capture before-and-after snapshots and produce a diff for the developer to confirm. That turns after-the-fact auditing into live review, which is the largest source of confidence.

    4. Engineering Practice

    1. Process lifecycle management. The shell must be able to stop, restart, and monitor agent child processes reliably. If a process exits unexpectedly, the session state should be kept so the conversation can resume.
    2. Permission gating. File writes and command execution should pass through a confirmation gateway in the shell. High-risk operations such as deletion and network requests should be blocked by default.
    3. Data under local control. Session data should be stored entirely on the local machine. Engineering context should not be uploaded to a third-party service. For enterprise users, this is a hard requirement.
    4. An adapter ecosystem. Treat adapters as pluggable modules. When a new agent appears, add an adapter. The shell core stays unchanged.

    5. Conclusion

    A unified shell fills the engineering gaps around CLI agents: visibility, manageability, and auditability. The architectural lesson goes beyond any single tool. When you have a set of capable CLI tools whose interaction model is still primitive, do not rush to rebuild the tools themselves. First organize them with a decoupled shell: process adaptation, capability scheduling, local persistence, and artifact visualization. Once those four pieces are in place, the development experience improves in a fundamental way. For teams that already rely heavily on CLI AI coding tools, this surrounding-system approach is worth adopting directly.