Building and Advancing an Agentic CLI Coding Assistant: Setup, Configuration, Model Routing, and Engineering Practices

    This guide walks through building and operating an agentic coding assistant in the terminal, from setup through advanced engineering practices. It first explains how an agentic assistant differs from code completion and compares the CLI, desktop, editor-extension, and cloud forms. It then covers dependencies, layered configuration, and the project instruction file. On the model side, it discusses a multi-provider adapter layer, unified gateway routing, task-tiered model selection, and credential governance, and explains how to use free models responsibly. Advanced sections introduce Skills, the Model Context Protocol (MCP), and sub-agents, followed by non-interactive CI integration, cloud and containerized execution, a security and compliance checklist, and a three-phase rollout plan. The key takeaway is that precise context, clear permission boundaries, and an evaluation mechanism matter more than the model itself.

    一、From Code Completion to a Terminal Agent: Where the Shift Happens

    Traditional code completion predicts the next chunk of text. It responds passively inside the editor, with a context window limited to the current file and adjacent code. An agentic coding assistant solves a different class of problems: it takes a natural-language goal, breaks it into subtasks on its own, reads and edits multiple files, runs commands to verify results, and iterates on failures until the task is done or human input is needed.

    This leap depends less on the model itself than on three runtime capabilities given to the assistant:

    1. Read and write access to files and the codebase, so it sees the whole project rather than just the current line.
    2. Command execution and tool invocation, so it can run tests, install dependencies, and inspect errors, closing the feedback loop.
    3. Loop control and state management, which turn “generate → execute → observe → correct” into a repeatable cycle of rounds.

    With execution power comes inherent risk, and therefore a natural need for a sandbox. This explains why the CLI is the main form for this class of tools. The workspace is the code directory, so it fits naturally into version-control workflows. Processes run in a terminal, so they can be contained in a container or remote development environment to limit the blast radius of mistakes. The CLI is also not tied to any specific editor, so the same capabilities work through SSH sessions, CI jobs, and automation scripts.

    二、Four Delivery Forms and Their Trade-offs

    The same agent core is usually delivered in several forms. Knowing what each is for helps you avoid misusing it.

    Form Core capabilities Best-fit scenarios Main limitations
    CLI Full read/write, command execution, multi-turn tasks, scriptable The primary form: refactoring, cross-file changes, writing tests, generating scripts Requires basic terminal skills; interaction is text-based
    Desktop client Graphical chat, directory-level project management Non-power users; demos and teaching Often in early validation, with incomplete feature coverage and relatively concentrated defects
    Editor extension Chat panel, automatic attachment of the open file, quick review of a selection Everyday small changes, local code explanation and completion Essentially a bridge; capabilities are bounded by the underlying CLI
    Cloud/containerized Remote execution, pinned environments, shared access Long-running batch jobs, resource-constrained local machines, teams that need centralized auditing Requires self-built or rented infrastructure; higher setup and ops cost

    The common practical conclusion is to install the CLI first and build the other forms on top of it. Editor extensions typically do two things: automatically attach the currently open file to the conversation as context, and quickly send a selected code snippet to the input box. They do not reimplement the agent core, so evaluations of agent capability should use the CLI form as the benchmark.

    三、Environment Setup and Minimal Initialization

    3.1 Dependencies

    Most tools in this category are built on the JavaScript/TypeScript ecosystem. You need the corresponding runtime (preferably an LTS version) and its package manager installed. Then install the tool globally through the package manager. Running its main command brings you straight into the interactive interface.

    1. # Illustrative; refer to the official documentation for the exact command
    2. node --version # confirm the runtime is ready
    3. npm install -g <agent-cli>
    4. <agent-cli> # start an interactive session
    5. <agent-cli> --version # verify the installation

    In production or standardized team environments, pin the version. Lock the major version, record it in the dependency manifest, or bake it into an image. This prevents hard-to-diagnose issues such as behavior diverging after someone upgrades.

    3.2 Layered Configuration

    Mature implementations typically use three configuration layers, from lowest to highest priority:

    1. User-level global configuration
    2. Project-level configuration (committed to version control)
    3. Directory-level overrides

    The value of this layering is that team conventions live in the repository, while personal preferences stay local.

    1. // Illustrative snippet; refer to the implementation docs for actual keys
    2. {
    3. "$schema": "./config.schema.json",
    4. "model": {
    5. "default": "provider-alpha/medium-model",
    6. "small": "provider-alpha/small-model",
    7. "reasoning": "provider-beta/reasoning-model"
    8. },
    9. "permission": {
    10. "edit": "ask", // ask | allow | deny
    11. "bash": {
    12. "*": "ask",
    13. "git status": "allow",
    14. "git push *": "deny",
    15. "rm -rf *": "deny"
    16. }
    17. },
    18. "context": {
    19. "include": ["AGENTS.md", "docs/architecture.md"],
    20. "exclude": ["dist/**", "**/*.lock", "secrets/**"]
    21. },
    22. "mcp": { "servers": [] }
    23. }

    Key names and structures differ widely between implementations. The snippet only illustrates the semantics of the configuration. Do not copy it directly.

    3.3 The Project Instruction File

    Placing a project-level instruction file in the repository root (a common convention is a file such as AGENTS.md) offers the best return on effort. It acts as the agent’s onboarding document. Keep it to a few hundred lines and cover four areas:

    • Tech stack, directory conventions, and module boundaries;
    • The exact commands for building, testing, and linting, which agents most often guess wrong;
    • Code style, commit conventions, and which documentation must be updated;
    • Prohibitions: directories that must not change, files that must not be committed, and operations that require human confirmation.

    The anti-pattern is pasting in the entire README. The longer the instruction file, the more attention is diluted and the lower the compliance rate.

    四、Model Access: From a Single Provider to Routing

    4.1 Multi-Provider Adapter Layer

    These tools generally do not ship with a model. They provide a provider adapter layer where you declare the API endpoint, authentication details, and model identifier through environment variables or configuration to switch backends. This is central to an open ecosystem: the model can change without changing the workflow.

    A better approach is to put a unified gateway in between. The agent connects only to a single internal OpenAI-compatible endpoint. The gateway handles routing, rate limiting, caching, auditing, and usage billing. Switching models then becomes a configuration change, and every call leaves a trace.

    4.2 Task-Tiered Routing

    Different stages have very different model requirements. Using the strongest model for every task wastes money:

    • Drafts and boilerplate code: mid-size models suffice; prioritize throughput and low latency.
    • Cross-file refactoring and complex bug diagnosis: use models with stronger reasoning and tolerate higher latency.
    • Code review and security review: use a different model from the one used in implementation to avoid shared blind spots.
    • Summaries, commit messages, and documentation: handle in batches with lightweight models.

    4.3 Key and Credential Governance

    Never write API keys into configuration files and commit them to the repository. The convention is to inject them via environment variables or a local credential store that is never written to disk, and to exclude local config files in .gitignore:

    1. export AGENT_API_KEY="<from-secret-manager>" # injected by a secret management service

    For teams and CI, credentials should come from centralized secret management or pipeline variables. Pair them with least-privilege access keys and regular rotation.

    五、The Right Role for Free Tiers

    Out-of-the-box free models from the community lower the barrier to entry considerably. They are suitable for practicing task decomposition, learning how to write prompts, and batch-processing low-risk changes. Engineering decisions, however, must be based on their objective limitations rather than the enthusiasm of a trial:

    • Rate limits and quotas: free tiers usually impose request limits. When a long task is interrupted midway, context is lost, so session recovery in the tool must be available as a fallback.
    • Small context windows: they struggle to take in the whole of a large repository. Pair them with precise file retrieval rather than feeding in everything.
    • No service stability guarantee: free channels may change policies or go offline at any time. They should not be on the critical path.
    • Data compliance terms: before integrating a free service, confirm its terms of service and data processing agreement. This includes whether enterprise code is used for training, which region stores the data, and how long logs are retained.

    The recommended approach is to use free models for capability validation and learning, and use paid channels with clear SLAs and compliance guarantees in production. Both coexist behind a unified gateway, with routing policies switching between them.

    六、Advanced Mechanisms: Skills, Context Protocols, and Sub-Agents

    These three concepts set this class of tools apart from ordinary conversational assistants. They are also the main vehicle for teams to accumulate methodology.

    6.1 Skills

    A skill turns procedural knowledge of “how to do a class of task” into a reusable asset. It consists of a description document, plus optional scripts and template resources, and is loaded into context on demand. This moves team experience from personal memory into reviewable, versionable repository content.

    1. .skills/
    2. add-api-endpoint/
    3. SKILL.md # when to use, steps, verification
    4. templates/
    5. scripts/check.sh
    6. write-migration/
    7. SKILL.md

    Design principles:

    • One skill solves one type of task.
    • Put the trigger conditions first, or the model will not know when to use the skill.
    • Make steps specific down to the command level.
    • End with verifiable criteria for completion.

    6.2 Context Protocol (MCP)

    The Model Context Protocol is an open standard that connects models to external tools. It exposes external capabilities such as databases, internal systems, and monitoring platforms to models in a standard way. This avoids writing a custom integration for each tool. Security calls for extra caution:

    • Give each connection its own least-privilege credentials.
    • Prefer read-only tools. Write operations must go through human confirmation.
    • Mount only the servers needed for the current task, and unmount them when done.
    • Stay alert to the content tools return. External data may contain prompt injection that lures the model into unintended actions.

    6.3 Sub-Agents

    A sub-agent performs a constrained task in its own context. Examples include “locate call sites” or “run tests and summarize the causes of failures.” It returns only the conclusion to the main session. This has two direct benefits: it keeps the main context free of large amounts of intermediate output, and it enables parallel dispatch.

    1. ---
    2. name: test-runner
    3. description: Run tests and summarize failure causes without modifying code
    4. tools: [read, bash]
    5. model: provider-alpha/small-model
    6. permission:
    7. edit: deny
    8. bash: ["test *", "ls *"]
    9. ---
    10. You are a test executor. Run the test commands, summarize failing cases and the most likely root causes,
    11. and output results as "case → error → hypothesis → suggested next step". Modifying any file is forbidden.

    The most worth-stealing line here is edit: deny. Permission narrowing belongs in the sub-agent’s definition, not in runtime reminders.

    七、Engineering Integration: Bringing Agents into CI and Team Workflows

    Non-interactive (unattended) mode is a prerequisite for automation. It typically requires a one-shot prompt, structured output, and explicit exit codes:

    1. # Illustrative: draft a commit message in a pipeline for human review
    2. <agent-cli> run -m provider-alpha/small-model \
    3. "Generate a Conventional Commits style commit message from the staged diff, one line only" \
    4. > /tmp/commit-msg.txt

    Key practices:

    • Never grant write permissions in pipelines. Let the agent produce patches or reports and let code review act as the gatekeeper.
    • Set timeouts and a maximum number of turns so tasks cannot loop and burn through quota.
    • Archive session logs in centralized logging so you can trace what the AI changed.
    • Build a small evaluation suite. Select 20–50 real tasks, such as fixing bugs, adding endpoints, and writing tests. Rerun it after every change to the model, prompt, or configuration. Compare results using pass rates and human diff scoring. Without this step, any discussion of “which model is better” is just guesswork.
    • Keep PR gating independent of AI. Changes made by AI go through the same tests, static analysis, and security scans as human changes, with no exceptions.

    八、Cloud and Containerized Execution

    For long-running tasks, shared team use, or centralized auditing, moving the runtime to the cloud is a better fit:

    • Pinned environments: bake the runtime, agent version, project dependencies, and instruction files into a single image so results are reproducible.
    • Persistent state: mount the code workspace and credential directory on persistent volumes so an interrupted session does not lose everything.
    • Narrowed permissions: run as a non-root user, restrict writable paths and outbound network traffic, and allow only the necessary model endpoints and dependency sources.
    • Auditing and archiving: route session logs and artifacts to object storage. Use logging, monitoring, and alerting to catch quota overruns and abnormal calls.

    In mainland China, this infrastructure is typically provided by cloud platforms as general-purpose services. For example, Baidu AI Cloud offers container services, cloud development environments, object storage, logging, and monitoring. These can host development containers, centrally manage session artifacts, and meet audit-trail requirements. Choose services based on team size, data classification, and compliance needs rather than copying a template.

    九、Security and Compliance Checklist

    • Is sensitive code allowed to leave the intranet? Have data classification and masking been completed?
    • Are keys injected only through environment variables or a secret management service, and are the relevant files excluded from version control?
    • Do write operations default to “ask”? Are delete, push, and publish commands explicitly denied?
    • Have external extensions, skills, and MCP servers undergone source vetting? Third-party extensions are third-party code and carry supply-chain risks such as dependency poisoning and credential theft.
    • Is there any path by which unreviewed AI-generated dependencies could be introduced into the project?
    • Is there a clear policy for how long prompts and code snippets in session logs are retained and who can access them?

    Phase 1 (1–2 days): Install the CLI, set up one paid channel and one free channel, and write the project instruction file. Allow only read-only and “ask” mode, and observe how the tool performs on your own project.

    Phase 2 (1–2 weeks): Connect a gateway for unified model routing. Narrow the permission allowlist. Build 3–5 high-frequency skills for adding endpoints, writing tests, updating migrations, checking dependencies, and writing docs. Establish an evaluation suite and baseline data.

    Phase 3 (ongoing): Use sub-agents and context protocols for cross-system tasks. Get the cloud-containerized form working. Bring instruction files and skills into code review so that “AI collaboration conventions” become part of the engineering assets.

    Overall, the real barrier to adopting these tools is not installation. It is whether context is supplied precisely, permission boundaries are clear, and an evaluation mechanism exists. Get those three right, and the model becomes a replaceable component. Get them wrong, and even the strongest model only produces changes that look plausible.