Understanding the Source Code of Terminal-Based AI Coding Agents
This article breaks down the architecture and core mechanisms of terminal-level intelligent coding agents—AI systems that can read repositories, run commands, edit files, and execute tests through an observe–think–act loop. It explains the four core modules (session management, context builder, tool executor, and safety guard), typical project structure, dynamic context injection strategies, the tool-calling loop, safety tiers and command screening, precise file-editing techniques, and system prompt design. A minimal reproducible demo is also included to help you build your own coding assistant.
Understanding the Source Code of Terminal-Based AI Coding Agents
Why study the source code of these tools?
Terminal-level intelligent coding tools are one of the most typical scenarios for AI application deployment today. Unlike traditional code-completion plugins, their core capabilities lie in understanding the entire code repository, executing commands, modifying files, and running tests, forming a complete “observe–think–act” loop.
From an engineering perspective, the technical complexity of these tools does not lie in a single model call, but in the entire systems engineering built around the model:
- Full-project awareness: Automatically building file trees, dependency relationships, and symbol indexes so the model can retrieve context on demand;
- Tool loops: Atomic capabilities such as reading/writing files, searching code, and executing commands, with support for multiple iterations;
- Safety constraints: Approval or confirmation mechanisms for dangerous operations (such as deletion, overwriting, and remote pushes).
If you want to build your own intelligent coding assistant, or integrate similar capabilities on a cloud platform such as Baidu AI Cloud, understanding the architecture design, module division, and engineering tradeoffs of such systems is critical. This article combines publicly available technical approaches with typical open-source reproduction implementations to break down the source-code logic and provides a minimal reproducible demo.
1. Overall architecture: from terminal input to code changes
The data flow of a typical terminal-level intelligent coding agent looks roughly like this:
User input → Session management → Context building → Model call → Tool parsing → Execution loop → Output result↑ │└────────── History messages + tool results fed back ──────────────┘
The entire loop can be broken down into four core modules:
1.1 Session (session management)
Responsible for maintaining the conversation history, repository root path, current working directory, tool whitelist, and accumulated file snapshots. It serves as the “short-term memory” of the whole agent.
1.2 Context Builder
This is the key to whether the agent is “smart.” Before each model call, it needs to dynamically collect:
- The project directory structure (file tree)
- The contents of recently modified files
- Symbol definitions and references mentioned in user messages
- Search results (grep / symbol search)
- The return results of the previous tool call
1.3 Tool Executor
Parses the structured tool calls (tool calls) output by the model and routes them to the corresponding execution functions. Typical supported tools include:
read_file/write_file/edit_filegrep_search/find_symbolsrun_shell/run_testslist_dir
1.4 Safety Guard
Intercepts high-risk operations. For example, deleting files, overwriting existing content, executing rm -rf, or pushing to a remote branch must all be released only after explicit user confirmation.
2. Source code structure: a typical Python reproduction
Below is a common directory organization (illustrative):
terminal_agent/├── main.py # CLI entry point, handles user input├── session.py # Conversation state and context management├── context/│ ├── repo_map.py # Generate the project tree structure│ ├── grep_search.py # Symbol search based on ripgrep│ └── relevance.py # Sort by modification time / call relationships├── tools/│ ├── base.py # Tool base class (unified interface)│ ├── file_ops.py # read, write, edit file operations│ ├── shell.py # Execute shell commands│ └── approve.py # Safety approval mechanism└── llm/├── client.py # Model API wrapper└── tool_formatter.py # Convert tools to function calling schema
Each module has a single responsibility and can be tested independently; the whole design follows the “pipeline + event loop” paradigm.
3. In-depth analysis of core mechanisms
3.1 Dynamic context building: don’t “dump everything to the model”
A common misconception among beginners is concatenating all the files in an entire project into one big prompt and handing it to the model. This leads to:
- Exploding token counts that exceed the context window
- Diluted model attention, with key code drowned out
- Sharply rising costs and latency
The right approach is on-demand injection. Sample code:
from pathlib import Pathdef get_repo_tree(root: Path, max_depth: int = 3, ignore_dirs=None):"""Recursively generate the project file tree, controlling depth to avoid overly long output"""if ignore_dirs is None:ignore_dirs = {".git", "__pycache__", "node_modules", ".venv"}tree = []def _walk(path: Path, depth: int):if depth > max_depth:returnfor item in sorted(path.iterdir()):if item.name in ignore_dirs:continueindent = " " * (max_depth - depth)if item.is_dir():tree.append(f"{indent}📁 {item.name}/")_walk(item, depth + 1)else:tree.append(f"{indent}📄 {item.name}")_walk(root, 0)return "\n".join(tree)
After building the file tree, the Context Builder also needs relevance filtering based on user intent. Common strategies:
| Strategy | Description |
|---|---|
| Recency principle | Prioritize injecting recently modified files |
| Exact symbol match | When users mention a function/class name, use symbol search to locate the definition |
| Dependency-graph priority | If file A is modified, prioritize injecting files that import A |
| Test-result driven | After a test fails, automatically inject the failing test and related source code |
On Baidu AI Cloud’s Qianfan large-model platform, developers can achieve similar dynamic context assembly through prompt templates + variable injection, combining retrieval results with user intent before sending them to the model.
3.2 Tool-call loop: the “hands and feet” of the agent
Tool use / function calling is the core capability that distinguishes an agent from an ordinary chatbot. The basic flow:
- Serialize the tool descriptions (name, parameter schema, functionality description) into JSON and send them along with the user message to the model;
- The model returns structured tool-call intent (tool_call), containing the tool name and parameters;
- The executor parses and runs the corresponding function to get the return result;
- The tool execution result is sent as new context to the model again, entering the next round.
Simplified loop pseudocode:
def agent_loop(user_input, session, llm_client, executor):messages = session.build_context(user_input)while True:response = llm_client.chat(messages=messages,tools=executor.get_tool_schemas())if response.tool_calls:for call in response.tool_calls:result = executor.run(call.name, call.arguments)messages.append({"role": "tool","tool_call_id": call.id,"content": str(result)})# Continue to the next round so the model can see the tool resultscontinue# No tool call means the model has given the final answerreturn response.content
Engineering considerations:
- Maximum iteration limit: Set
max_iterations(usually 10–30 rounds) to prevent the model from getting stuck in an infinite loop; - Timeout and retries: Tool execution needs timeouts, especially important for shell commands;
- Tool granularity control: Too coarse (e.g.
execute_any_code) is hard to manage securely; too fine (e.g.read_line_5_of_file_a) increases interaction rounds. In practice, the three basic groups “read/write files + search + execute commands” are usually enough.
3.3 Safety guardrails: you can’t auto-execute everything
Intelligent coding agents have real file system and terminal permissions, so security is the bottom line. Typical protective measures:
(1) Operation tiering
| Level | Examples | Strategy |
|---|---|---|
| Safe | Read files, grep, list directories | Execute directly |
| Needs confirmation | Edit files, create new files | Show a diff popup for user confirmation |
| Dangerous | rm, git push, curl download-and-execute | Mandatory manual approval + logging |
(2) Command whitelist/blacklist
DANGEROUS_PATTERNS = [r"rm\s+-rf",r"git\s+push\s+--force",r">\s*/dev/",r"chmod\s+777",r"curl\s+.*\|\s*(ba)?sh",r"eval\s*\(",]def is_dangerous(command: str) -> bool:for pattern in DANGEROUS_PATTERNS:if re.search(pattern, command, re.IGNORECASE):return Truereturn False
(3) Sandboxed execution
On cloud platforms such as Baidu AI Cloud, you can use container services (such as CCE) or function compute (such as CFC) to provide an isolated execution environment for the agent, restricting its access scope to host machine resources.
3.4 File editing strategy: precise modification rather than full overwrite
A simple write_file(path, content) is expensive in long-file scenarios (the model has to output the entire file). A better approach:
- Diff-based editing: The model outputs only the changed lines before and after, and the tool side applies the patch;
- Anchor replacement: The model specifies
old_stringandnew_string, and the tool finds and replaces them precisely in the file; - Line-range editing: The model specifies the start and end lines and replaces the specified interval.
Sample implementation (anchor replacement method):
def edit_file(path: str, old_string: str, new_string: str) -> str:with open(path, "r", encoding="utf-8") as f:content = f.read()if content.count(old_string) != 1:return f"Error: '{old_string[:50]}...' appears {content.count(old_string)} times in the file, cannot determine the modification location."new_content = content.replace(old_string, new_string, 1)with open(path, "w", encoding="utf-8") as f:f.write(new_content)return f"Successfully modified {path}, replaced {len(old_string)} characters with {len(new_string)} characters"
4. Prompt design: making the model “think like an engineer”
The quality of the system prompt directly determines the agent’s performance. A good system prompt should include:
You are a terminal coding assistant. You can:1. Read and modify files in the code repository2. Search code (via grep / symbol search)3. Execute shell commands (such as running tests, installing dependencies)Working principles:- Understand the existing code structure and conventions before modifying- Prefer existing utility functions; don't reinvent the wheel- Proactively run relevant tests to verify after modifications- When uncertain, ask the user rather than guessing- Don't perform dangerous operations (deletion, force push, formatting disks, etc.)Current project structure:{repo_tree}User request: {user_input}
Key design points:
- Role setting: Clearly state “you are a coding assistant” rather than a generalized AI;
- Capability boundaries: List available tools and their use cases;
- Behavioral norms: Emphasize understanding first, then modifying, and verifying after modifications;
- Safety reminders: Hard constraints prohibiting dangerous operations.
5. Minimal reproducible demo: get an agent running in 30 minutes
Below is a streamlined main loop to help you understand the full picture:
import json, os, subprocessfrom pathlib import Pathdef main():# 1. Initialize sessionwork_dir = Path.cwd()# 2. Register toolstools = [{"name": "read_file","description": "Read file contents","parameters": {"type": "object","properties": {"path": {"type": "string", "description": "File path"}},"required": ["path"]}},{"name": "run_shell","description": "Execute a shell command","parameters": {"type": "object","properties": {"command": {"type": "string"}},"required": ["command"]}}]# 3. Main loopmessages = [{"role": "user", "content": "Fix all lint errors in the project"}]while True:# Call the model (represented here as pseudocode)response = call_llm(messages, tools)if response.get("tool_calls"):for tc in response["tool_calls"]:name = tc["function"]["name"]args = json.loads(tc["function"]["arguments"])if name == "read_file":result = open(args["path"]).read()elif name == "run_shell":if is_dangerous(args["command"]):result = "Execution refused: dangerous command"else:result = subprocess.run(args["command"], shell=True,capture_output=True, text=True).stdoutmessages.append({"role": "tool","content": str(result)[:5000] # Truncate to prevent overly long content})else:print(response["content"])breakif __name__ == "__main__":main()
Although this demo is simple, it already has the complete skeleton of file reading, command execution, safety interception, and multi-round looping. On this basis, you can gradually add capabilities such as diff editing, symbol search, and test-driven workflows.
6. Summary and further directions
The core design philosophy of terminal-level intelligent coding agents can be summarized as:
- Context is a scarce resource: precise retrieval > full-volume injection; relevance ranking determines the agent’s upper bound;
- Tools are the agent’s hands and feet: designing good tool granularity and descriptions matters more than piling on more tools;
- Safety is the production bottom line: operation tiering, command review, and sandbox isolation are all indispensable;
- The loop is the soul of the agent: without a multi-round “observe–act–feedback” closed loop of tool calls, it is just an advanced Q&A bot.
For developers who want to build similar capabilities on Baidu AI Cloud, the following directions are worth attention:
- Use the function calling capabilities of the Qianfan large-model platform to reduce the integration cost of tool calls;
- Combine object storage (BOS) and log service (BLS) to persist the agent’s execution history and audit logs;
- Use container services (CCE) to provide an isolated code-execution environment for the agent, ensuring host security;
- Use monitoring and alerting (BCM) to build observability for the agent’s tool-call chains.
A terminal-level intelligent coding agent is a comprehensive topic that combines large-model reasoning, systems engineering, and security engineering. Understanding its core mechanisms not only helps you use such tools to improve development efficiency, but also lays a solid foundation for building custom intelligent applications.
