7. Code Agents
How AI coding assistants actually work
Every technique in this series converges in the code agent: an LLM-powered system that can read a codebase, understand it, plan changes, edit files, run tests, and iterate until the task is done. Tools like Claude Code, Cursor, Opencode, and Aider all follow the same fundamental architecture. They differ in UX, model choice, and specific tool design, but the bones are the same.
This article breaks down exactly how these systems work — from the system prompt to the tool definitions to the edit-test loop that makes them reliable.
Architecture Overview
A code agent is an agentic loop (as described in the previous article) specialized for software engineering:
┌──────────────────────────────────────────────────────┐
│ Host Application │
│ │
│ ┌────────────┐ ┌──────────┐ ┌─────────────────┐ │
│ │ Terminal │ │ File │ │ Permission │ │
│ │ UI / IDE │ │ System │ │ Manager │ │
│ └──────┬─────┘ └────┬─────┘ └───────┬─────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Tool Execution Layer │ │
│ │ read_file | edit_file | glob | grep | bash │ │
│ └────────────────────┬────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ LLM API Client │ │
│ │ system prompt + tools + messages → response │ │
│ └─────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
The host application manages the UI, filesystem access, and permissions. The LLM never touches the filesystem directly — it produces structured tool calls that the host validates and executes.
The System Prompt
A code agent's system prompt is typically the largest and most carefully engineered piece of the system. It covers:
Identity and role
You are an expert software engineer. You help users with software
engineering tasks: fixing bugs, adding features, refactoring code,
explaining code, and more.
Behavioral rules
- Read files before modifying them. Never guess at file contents.
- Make minimal changes. Don't refactor code you weren't asked to change.
- Don't add features, comments, or type annotations beyond what was asked.
- If a task is ambiguous, ask for clarification.
- When you encounter an error, explain what went wrong.
Tool usage guidance
- Use the read_file tool to examine files, not bash cat/head/tail.
- Use the edit tool for modifications, not bash sed/awk.
- Use the grep tool for content search, not bash grep/rg.
- Use bash only for commands that require shell execution.
Safety constraints
- Do not delete files without explicit user approval.
- Do not run destructive commands (rm -rf, git reset --hard) without asking.
- Do not push to remote repositories unless asked.
- Do not modify files outside the project directory.
Output style
- Be concise. Lead with the answer, not the reasoning.
- Use markdown for formatting.
- Include file paths with line numbers when referencing code.
These instructions shape every decision the model makes. The difference between a helpful code agent and an annoying one is often in the system prompt, not the model.
The Tool Set
Code agents typically provide 5-10 tools. Here's the core set that most implementations share:
File reading
{
name: "read_file",
description: "Read a file's contents. Can read specific line ranges.",
input_schema: {
properties: {
path: { type: "string" },
offset: { type: "integer", description: "Starting line number" },
limit: { type: "integer", description: "Number of lines to read" }
},
required: ["path"]
}
}
This is the most-called tool in any code agent session. The model reads 5-10x more than it writes. Efficient file reading — with line ranges, so you don't load 5,000 lines when you need 50 — is critical for context management.
File editing
{
name: "edit_file",
description: "Replace a specific string in a file with a new string.",
input_schema: {
properties: {
path: { type: "string" },
old_string: { type: "string", description: "Exact text to find" },
new_string: { type: "string", description: "Replacement text" }
},
required: ["path", "old_string", "new_string"]
}
}
The edit tool uses exact string matching, not line numbers. This is a deliberate design choice:
- Line numbers shift as edits are made — an edit targeting line 42 might hit the wrong line after a previous edit inserted a line above it
- String matching is unambiguous — the old string either exists in the file or it doesn't
- Diffs are human-readable — the user can see exactly what's changing
The tradeoff: the old string must be unique in the file. If it appears multiple times, the tool rejects the edit and asks for more surrounding context to disambiguate.
Code search
{
name: "grep",
description: "Search file contents using regex patterns.",
input_schema: {
properties: {
pattern: { type: "string" },
path: { type: "string", description: "Directory to search in" },
glob: { type: "string", description: "File pattern filter" }
},
required: ["pattern"]
}
}
{
name: "glob",
description: "Find files matching a glob pattern.",
input_schema: {
properties: {
pattern: { type: "string", description: "Glob like **/*.ts" }
},
required: ["pattern"]
}
}
Two search tools: grep for content search, glob for file name search. Separating
them gives the model clear semantics — "find files named X" vs "find files containing Y."
Shell execution
{
name: "bash",
description: "Execute a shell command. Use for running tests, git " +
"operations, installing packages, and other terminal tasks.",
input_schema: {
properties: {
command: { type: "string" },
timeout: { type: "integer" }
},
required: ["command"]
}
}
The most powerful and most dangerous tool. With bash, the agent can do anything: run
tests, check git status, install packages, start servers. The permission layer is
critical here — most code agents auto-allow read-only commands and prompt for anything
that modifies state.
File creation
{
name: "write_file",
description: "Create a new file or completely overwrite an existing file.",
input_schema: {
properties: {
path: { type: "string" },
content: { type: "string" }
},
required: ["path", "content"]
}
}
Separate from edit_file because the semantics are different. edit_file modifies an
existing file surgically. write_file creates a new file from scratch. The system prompt
typically instructs the model to prefer edit_file for existing files and only use
write_file for new files.
The Edit-Test Loop
The most important pattern in code agents isn't any single tool — it's the loop of editing code and running tests until the change is correct.
read files → understand the problem → make an edit → run tests
│
tests pass? ──yes──→ done
│
no
│
read error output
│
make another edit → run tests
│
...
This loop is powerful because it gives the model feedback from the real system. The model doesn't just guess whether its code is correct — it runs it and finds out. Test output is some of the highest-signal information you can feed back into the context.
// Simplified edit-test loop
async function editTestLoop(
task: string,
testCommand: string,
maxAttempts: number = 5
): Promise<boolean> {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const testResult = await runCommand(testCommand);
if (testResult.exitCode === 0) {
return true; // Tests pass!
}
// Feed test failure back to the model
await chat([
{
role: "user",
content: `Tests failed (attempt ${attempt + 1}/${maxAttempts}):\n` +
`${testResult.stderr}\n\n` +
`Fix the issue and try again.`
}
]);
}
return false; // Couldn't fix it
}
Codebase Understanding
Before an agent can modify code effectively, it needs to understand the codebase. This happens through a pattern of progressive exploration:
1. Orientation
The agent starts by reading high-level files to understand the project structure:
read_file("package.json") → dependencies, scripts, project type
read_file("tsconfig.json") → TypeScript configuration
glob("src/**") → directory structure
read_file("README.md") → project overview
2. Targeted search
Based on the user's request, the agent searches for relevant code:
grep("handleAuth", "src/") → find where auth is handled
read_file("src/auth/index.ts") → read the main auth module
grep("import.*auth", "src/") → find what depends on auth
3. Deep reading
The agent reads the specific files and functions it needs to modify:
read_file("src/auth/middleware.ts", offset=45, limit=30) → the exact function
read_file("src/auth/types.ts") → type definitions
read_file("test/auth.test.ts") → existing tests
4. Modification
Only after this exploration does the agent make changes. It has the context to make precise edits rather than broad rewrites.
This exploration pattern is why code agents spend most of their time reading, not writing. A typical task — "fix this bug" — might involve reading 8-10 files and editing 1-2.
Diff-Based Editing
Some code agents show edits as unified diffs rather than search-and-replace operations:
--- a/src/auth/middleware.ts
+++ b/src/auth/middleware.ts
@@ -47,7 +47,7 @@
if (token.isExpired()) {
- return res.status(403).json({ error: "FORBIDDEN" });
+ return res.status(401).json({ error: "TOKEN_EXPIRED" });
}
Advantages of diff-based editing:
- Familiar format for developers
- Easy to review and approve/reject
- Git-native representation
- Can show multiple edits in one view
Advantages of search-and-replace:
- Simpler for the model to produce correctly
- No ambiguity about line numbers
- Works even after previous edits shift line numbers
- Easier to validate programmatically
Most production code agents use search-and-replace internally (the model produces the edit) and render a diff in the UI (the user sees the change).
LSP Integration
Advanced code agents integrate with the Language Server Protocol to get IDE-level intelligence:
- Go-to-definition — follow a function call to its implementation
- Find references — find everywhere a symbol is used
- Diagnostics — type errors, unused imports, missing fields
- Completions — type-aware code suggestions
LSP integration means the agent can ask "where is this function defined?" and get an exact file and line number, rather than grep-searching through the codebase. It can also check for type errors before running the full test suite, catching mistakes faster.
// Using LSP to find all references to a function
const refs = await lsp.findReferences("src/auth.ts", line=47, column=10);
// Returns: [
// { file: "src/routes/login.ts", line: 23 },
// { file: "src/routes/refresh.ts", line: 45 },
// { file: "test/auth.test.ts", line: 12 }
// ]
Sub-Agents and Parallel Exploration
For complex tasks, some code agents spawn sub-agents that explore the codebase in parallel:
Main agent: "I need to understand the auth system, the database schema,
and the API routes. Let me research each in parallel."
Sub-agent 1: [explores auth module, returns summary]
Sub-agent 2: [explores database models, returns summary]
Sub-agent 3: [explores API routes, returns summary]
Main agent: [synthesizes all three summaries, plans the change]
This is faster than sequential exploration and keeps the main agent's context window clean. Each sub-agent works in its own context, processes a focused query, and returns a concise summary rather than raw file contents.
The tradeoff is cost — three sub-agent calls cost 3x as much as one. But for large codebases where the main agent would otherwise burn through its context window just reading files, sub-agents pay for themselves in quality.
Permission and Safety
Code agents have access to your filesystem and shell. The permission model is critical:
Tiered permissions
| Tier | Operations | User interaction |
|---|---|---|
| Auto-allow | Read files, search, glob, git log | Silent |
| Prompt once | Write files, create files | Ask once per type |
| Always prompt | Shell commands, delete, git push | Ask every time |
| Deny | rm -rf, sudo, outside project dir | Block silently |
Sandboxing
Some agents run in sandboxed environments:
- Container-based — the agent runs inside a Docker container with only the project mounted
- Directory-scoped — filesystem access is restricted to the project directory
- Network-restricted — no outbound network access except to the LLM API
Audit trail
Every tool call is logged with:
- What tool was called
- What arguments were passed
- What the result was
- Whether the user approved it
- Timestamp and token cost
This audit trail is essential for debugging ("why did the agent delete that file?") and for building trust ("I can see exactly what it did").
The Conversation as UI
Code agents are conversational. The user describes what they want in natural language, the agent works, and the user can intervene, redirect, or ask questions at any point.
Streaming is critical for UX. The user sees the agent's thinking, tool calls, and results in real time. Without streaming, the user stares at a blank screen for 30 seconds and then gets a wall of text.
Progressive disclosure — show the high-level plan first, then expand into details as the agent works:
Agent: I'll fix this by updating the auth middleware. Let me read the
relevant files first.
Reading src/auth/middleware.ts...
Reading test/auth.test.ts...
Found the issue: the middleware returns 403 for expired tokens
but should return 401.
Editing src/auth/middleware.ts...
Running tests...
All tests passing.
The user can see what's happening and intervene if the agent heads in the wrong direction. This is fundamentally different from a batch system that runs to completion and shows the final result.
What Makes a Good Code Agent
After all the engineering, what actually matters for a code agent to be good?
Read before writing. The agent should always understand the existing code before modifying it. Agents that guess at file contents produce wrong edits.
Minimal changes. A good edit changes exactly what needs to change and nothing else. Agents that "improve" surrounding code or add unsolicited refactoring lose the user's trust.
Test-driven feedback. Running tests after every edit is the single highest-value pattern. The agent that runs tests catches its own mistakes before the user sees them.
Know when to stop. An agent that says "I'm not sure how to proceed — here's what I've found so far" is more useful than one that makes increasingly wild guesses.
Transparency. Show the user what you're doing and why. Every file read, every edit, every test run should be visible. The user should never wonder "what is it doing?"
Respect boundaries. Don't push code, don't delete branches, don't modify config files outside the project without explicit permission. The agent works for the user, not autonomously.
These principles aren't about the model — they're about the system around it. A mediocre model with great tooling, permissions, and feedback loops outperforms a brilliant model with poor engineering.
Try It — Edit-Test Loop Simulator
Watch a code agent work through a real scenario: reading files, analyzing code, making edits, running tests, handling failures, and iterating until tests pass. The file view on the right updates as the agent modifies code.
The Bigger Picture
Code agents are one application of the general agentic pattern. The same architecture — LLM + tools + loop + permissions — powers research agents, data analysis agents, DevOps agents, and more. What makes code agents special is the tight feedback loop: write code → run it → see if it works → fix it. That loop is what makes autonomous software engineering possible.
The techniques in this series — prompt engineering, structured output, tool use, context management, RAG, agentic loops — are the building blocks. Code agents are what you get when you assemble them all into a coherent system and point it at a codebase.