AI Agent Terminal Interaction Framework: Design and Practice

    This article explains how to design an AI agent framework for terminal interaction, where the agent does not just answer questions but actually modifies code, runs tests, and resolves issues. It covers a five-layer architecture, the core agent loop, context management strategies, tool orchestration principles, permission and security boundaries, observability and cost control, common anti-patterns, and a practical implementation checklist. The content is intended for developers building reliable, controllable, and auditable terminal-based agents.

    1. From Formula to Engineering: Why Agents Need a Framework Layer

    The industry is converging on a common abstraction: an AI agent = a model + an orchestration framework (harness). The value of this formula is not the concept itself, but the clear separation of two concerns. The model handles language understanding, reasoning, and generation. The orchestration framework turns a one-off question-and-answer exchange into a sustainable, verifiable, and rollback-capable workflow. This separation matters especially in terminal interaction scenarios, where developers expect not a polished explanation but code that is actually modified, tests that are actually executed, and problems that are actually narrowed down.

    An orchestration framework must solve at least four things: organizing and compressing context, registering and invoking tools, enforcing permissions and auditing the execution process, and recovering from failures. If any of these is missing, the agent degrades into a “chatty completion engine.”

    2. Layered Architecture: How to Build a Terminal Interaction Agent

    A maintainable implementation is typically divided into five layers:

    1. Interaction layer: responsible for terminal rendering, streaming output, interruption and recovery, and session history management. Terminal width is limited, so output must be structured (diffs, tables, progress bars) rather than long paragraphs.
    2. Orchestration layer: the core loop. It breaks user intent into steps and decides which tool to call at each step and whether user confirmation is needed.
    3. Capability layer: the tool set, such as file read/write, retrieval, command execution, test running, and static checks.
    4. Context layer: responsible for retrieval, summarization, trimming, and prioritization, ensuring the most relevant information is retained within a limited window.
    5. Support layer: logging, metrics, tracing, secret management, and policy configuration.

    The main loop logic is shown below (pseudocode, structure only):

    1. while not done:
    2. ctx = context.build(goal, history, workspace_state)
    3. action = model.plan(ctx, tools_schema)
    4. if action.type == "tool":
    5. result = policy.guard(action).execute()
    6. context.append(action, result)
    7. elif action.type == "ask":
    8. return user_input()
    9. else:
    10. done = True

    The key point is that the output of model.plan must be a constrained structured object, not free text. Defining tool parameters with a strict schema significantly reduces the probability of “hallucinated calls.”

    3. Context Management: The Real Bottleneck That Sets the Agent’s Ceiling

    More context is not always better. Three engineering approaches are more effective:

    • Layered retrieval: first locate candidate files and symbols, then expand snippets on demand, avoiding loading the entire repository at once.
    • Rolling summarization: compress completed historical steps, keeping only three elements: conclusions, modification points, and open questions.
    • Externalized state: write intermediate artifacts to workspace files or structured storage, leaving only pointers in the context. Even if the session is interrupted, the scene can be restored from disk.

    A practical trade-off is to make the context window serve the “current decision” rather than “complete memory.” Memory should be handled jointly by external storage and retrieval.

    4. Tool Invocation Orchestration: From Callable to Called Correctly

    The quality of tool design directly determines the success rate. Follow these principles:

    • Moderate granularity: tools that are too fine cause step explosion; tools that are too coarse are hard for the model to compose. Use “one tool completes one verifiable thing” as the boundary.
    • Discriminable return values: each tool returns a structured status (success, retry needed, user confirmation needed, failure reason) so the orchestration layer can branch.
    • Idempotence and rollback: write operations should support preview and undo where possible, for example generating a diff first and then having the user or policy confirm before writing to disk.
    • Parallelism and dependencies: read-only tools with no dependencies can run concurrently; write operations run serially with locks to avoid overwriting each other.

    An example tool declaration:

    1. {
    2. "name": "apply_patch",
    3. "parameters": {
    4. "path": "string",
    5. "diff": "string",
    6. "dry_run": "boolean"
    7. },
    8. "returns": ["applied", "conflict", "rejected"]
    9. }

    5. Permissions, Security, and Compliance Boundaries

    The terminal has real execution capability, so security design must be built in from the start rather than patched on afterward:

    • Least privilege by default: read-only by default; write and execution must be explicitly enabled; sensitive directories and credential paths are blacklisted.
    • Policy engine pre-check: intercept uniformly before tool execution instead of relying on the model’s self-discipline.
    • Full audit: record input digests, tool names, parameter hashes, and output status for traceability and accountability.
    • Sandboxing and resource limits: set timeouts, output length limits, and resource caps for command execution to prevent blocking the terminal.
    • Credential isolation: secrets are injected by an external secret management service, never entering the context or being written to logs.

    6. Observability and Cost Governance

    Debugging agent systems is harder than debugging ordinary services because they are nondeterministic. Collect at least three types of signals: distribution of steps and tool calls, per-task latency and failure reason categories, and context usage with the number of compression triggers. These metrics help identify typical problems such as “repeated retries,” “context thrashing,” and “wrong tool selection.”

    For cost governance, common approaches include using lightweight models for small tasks, caching repeated retrieval results, and summarizing long histories before passing them as input. If deployed in the cloud, container platforms can host execution sandboxes, object storage can hold intermediate artifacts, and logging and monitoring services can handle observability. These are general capability categories that can be selected according to your own environment.

    7. Common Anti-Patterns

    • Treating prompts as architecture: constraining behavior only by lengthening prompts cannot replace a policy layer and state management.
    • Tools without return value specifications: the model cannot tell success from failure and can only guess, leading to idle loops.
    • No context eviction strategy: the window is filled with low-value information and key constraints are pushed out.
    • No interruption recovery: a single mistake forces a restart, damaging both user experience and trust.

    8. Implementation Checklist

    1. Define tool contracts and the return state machine first, then connect the model.
    2. Minimize context for the “current decision” and externalize memory.
    3. Make write operations preview by default, explicitly confirmed, and rollback-capable.
    4. Put policy checks and audit logs in place before shipping features.
    5. Drive iteration with metrics rather than tweaking prompts by feel.

    When deploying in cloud environments such as Baidu AI Cloud, the layers above can be mapped to general product categories: container platforms provide isolated execution environments, object storage holds artifacts, and logging and monitoring systems handle tracing. This allows building a stable, controllable, and auditable terminal interaction framework for AI agents without binding to a specific implementation.