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:

    1. User input → Session management → Context building → Model call → Tool parsing → Execution loop → Output result
    2. ↑ │
    3. └────────── 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_file
    • grep_search / find_symbols
    • run_shell / run_tests
    • list_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):

    1. terminal_agent/
    2. ├── main.py # CLI entry point, handles user input
    3. ├── session.py # Conversation state and context management
    4. ├── context/
    5. │ ├── repo_map.py # Generate the project tree structure
    6. │ ├── grep_search.py # Symbol search based on ripgrep
    7. │ └── relevance.py # Sort by modification time / call relationships
    8. ├── tools/
    9. │ ├── base.py # Tool base class (unified interface)
    10. │ ├── file_ops.py # read, write, edit file operations
    11. │ ├── shell.py # Execute shell commands
    12. │ └── approve.py # Safety approval mechanism
    13. └── llm/
    14. ├── client.py # Model API wrapper
    15. └── 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:

    1. from pathlib import Path
    2. def get_repo_tree(root: Path, max_depth: int = 3, ignore_dirs=None):
    3. """Recursively generate the project file tree, controlling depth to avoid overly long output"""
    4. if ignore_dirs is None:
    5. ignore_dirs = {".git", "__pycache__", "node_modules", ".venv"}
    6. tree = []
    7. def _walk(path: Path, depth: int):
    8. if depth > max_depth:
    9. return
    10. for item in sorted(path.iterdir()):
    11. if item.name in ignore_dirs:
    12. continue
    13. indent = " " * (max_depth - depth)
    14. if item.is_dir():
    15. tree.append(f"{indent}📁 {item.name}/")
    16. _walk(item, depth + 1)
    17. else:
    18. tree.append(f"{indent}📄 {item.name}")
    19. _walk(root, 0)
    20. 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:

    1. Serialize the tool descriptions (name, parameter schema, functionality description) into JSON and send them along with the user message to the model;
    2. The model returns structured tool-call intent (tool_call), containing the tool name and parameters;
    3. The executor parses and runs the corresponding function to get the return result;
    4. The tool execution result is sent as new context to the model again, entering the next round.

    Simplified loop pseudocode:

    1. def agent_loop(user_input, session, llm_client, executor):
    2. messages = session.build_context(user_input)
    3. while True:
    4. response = llm_client.chat(
    5. messages=messages,
    6. tools=executor.get_tool_schemas()
    7. )
    8. if response.tool_calls:
    9. for call in response.tool_calls:
    10. result = executor.run(call.name, call.arguments)
    11. messages.append({
    12. "role": "tool",
    13. "tool_call_id": call.id,
    14. "content": str(result)
    15. })
    16. # Continue to the next round so the model can see the tool results
    17. continue
    18. # No tool call means the model has given the final answer
    19. return 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

    1. DANGEROUS_PATTERNS = [
    2. r"rm\s+-rf",
    3. r"git\s+push\s+--force",
    4. r">\s*/dev/",
    5. r"chmod\s+777",
    6. r"curl\s+.*\|\s*(ba)?sh",
    7. r"eval\s*\(",
    8. ]
    9. def is_dangerous(command: str) -> bool:
    10. for pattern in DANGEROUS_PATTERNS:
    11. if re.search(pattern, command, re.IGNORECASE):
    12. return True
    13. return 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_string and new_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):

    1. def edit_file(path: str, old_string: str, new_string: str) -> str:
    2. with open(path, "r", encoding="utf-8") as f:
    3. content = f.read()
    4. if content.count(old_string) != 1:
    5. return f"Error: '{old_string[:50]}...' appears {content.count(old_string)} times in the file, cannot determine the modification location."
    6. new_content = content.replace(old_string, new_string, 1)
    7. with open(path, "w", encoding="utf-8") as f:
    8. f.write(new_content)
    9. 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:

    1. You are a terminal coding assistant. You can:
    2. 1. Read and modify files in the code repository
    3. 2. Search code (via grep / symbol search)
    4. 3. Execute shell commands (such as running tests, installing dependencies)
    5. Working principles:
    6. - Understand the existing code structure and conventions before modifying
    7. - Prefer existing utility functions; don't reinvent the wheel
    8. - Proactively run relevant tests to verify after modifications
    9. - When uncertain, ask the user rather than guessing
    10. - Don't perform dangerous operations (deletion, force push, formatting disks, etc.)
    11. Current project structure:
    12. {repo_tree}
    13. 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:

    1. import json, os, subprocess
    2. from pathlib import Path
    3. def main():
    4. # 1. Initialize session
    5. work_dir = Path.cwd()
    6. # 2. Register tools
    7. tools = [
    8. {
    9. "name": "read_file",
    10. "description": "Read file contents",
    11. "parameters": {
    12. "type": "object",
    13. "properties": {
    14. "path": {"type": "string", "description": "File path"}
    15. },
    16. "required": ["path"]
    17. }
    18. },
    19. {
    20. "name": "run_shell",
    21. "description": "Execute a shell command",
    22. "parameters": {
    23. "type": "object",
    24. "properties": {
    25. "command": {"type": "string"}
    26. },
    27. "required": ["command"]
    28. }
    29. }
    30. ]
    31. # 3. Main loop
    32. messages = [{"role": "user", "content": "Fix all lint errors in the project"}]
    33. while True:
    34. # Call the model (represented here as pseudocode)
    35. response = call_llm(messages, tools)
    36. if response.get("tool_calls"):
    37. for tc in response["tool_calls"]:
    38. name = tc["function"]["name"]
    39. args = json.loads(tc["function"]["arguments"])
    40. if name == "read_file":
    41. result = open(args["path"]).read()
    42. elif name == "run_shell":
    43. if is_dangerous(args["command"]):
    44. result = "Execution refused: dangerous command"
    45. else:
    46. result = subprocess.run(
    47. args["command"], shell=True,
    48. capture_output=True, text=True
    49. ).stdout
    50. messages.append({
    51. "role": "tool",
    52. "content": str(result)[:5000] # Truncate to prevent overly long content
    53. })
    54. else:
    55. print(response["content"])
    56. break
    57. if __name__ == "__main__":
    58. 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:

    1. Context is a scarce resource: precise retrieval > full-volume injection; relevance ranking determines the agent’s upper bound;
    2. Tools are the agent’s hands and feet: designing good tool granularity and descriptions matters more than piling on more tools;
    3. Safety is the production bottom line: operation tiering, command review, and sandbox isolation are all indispensable;
    4. 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.