跪拜 Guibai
← Back to the summary

Inside a Homebuilt DeepSeek Coding Agent: It's Just a while(true) Loop

Agents Have No Magic, Only a Loop: I Wrote My Own DeepSeek Coding Assistant and Broke Down How It Works

banner.png

Preface

Many people have used Claude Code, Codex, and Cursor, but few can explain their underlying principles.

Ask one to fix a bug, and it reads files, edits code, runs tests—all in one smooth motion. It looks like magic.

But under the hood, there is no magic, only a loop.

Over the past few months, I wrote DeepSeeker-Code in my spare time: a DeepSeek-driven, local coding agent with both CLI and VSCode interfaces. The architecture is written from scratch, not wrapped around a framework. This article breaks it apart to explain exactly how an Agent does its work—every tool name and structure mentioned here really exists in this project. Here's the quick overview:

# Stage One-liner
1 Main loop A while(true), a dozen lines
2 Architecture Four layers, the model is just one of them
3 Tool system The model's hands, delegated at three levels
4 Context The Agent's short-term memory; when full, it loses memory
5 Extension trio Hooks / Skills / MCP
6 Sub-agents One person becomes a team, each doing their own thing
7 Interface What it looks like and how costs are calculated

1. The Entire Secret of an Agent: A while(true) Loop

Many articles describe Agents in vague terms: emergence, planning, reflection, multi-agent collaboration... a pile of jargon.

Strip away that shell, and the core is just a dozen lines:

fig10-loop-code.png The model decides which tool to call, the engine executes it and feeds the result back, and the model sees the result and decides the next step. Loop until the model decides the job is done and stops initiating tool calls.

This is a real execution animation from my project; the tool names and loop structure are real:

fig2-agent-loop.gif Each round has three fixed steps:

First, window management—is the context nearly full? Compress it first, details later.

Second, streaming inference—conversation history plus the tool table is sent to DeepSeek, generating tokens as it streams.

Third, tool execution—the model initiates a call, the engine checks the safety level, shows an approval prompt, executes, and feeds the result back.

In the animation, fixing a null pointer takes 4 rounds: read file → locate → edit → run tests. On round 4, it no longer calls tools, outputs a summary, and the loop ends.

Understand this loop, and you understand all Agent products. The Agent modes of Claude Code, Codex, and Cursor all share this core; the difference is only in the richness of the toolset and engineering details.

2. Full Architecture: Four Layers

Zoom out, and the whole project looks like this:

fig3-arch-overview.png From top to bottom: entry layer (CLI / VSCode / local HTTP, three skins one soul), Agent kernel (main loop + context management + sub-agents + budget), tool layer (25+ built-in tools + MCP + Hooks + Skills), model base (DeepSeek API).

One insight worth calling out: the model does only one thing in the entire system—reads the context and decides whether to "speak" or "call a tool."

It doesn't know what the file system looks like, doesn't know how the command line executes, doesn't even know whether the last command ran successfully. All of that "perception" is fed to it by the kernel as text from tool results.

The model is the brain; everything else is the body we build for it.

3. Tool System: The Model's Hands

How does the model "call a tool"? Through function calling: the engine sends each tool's name, parameters, and description along with the request. The model outputs a structured call for the tool it wants, and the engine parses and executes it.

The built-in tools cover the complete coding workflow:

Category Tools
File read/write read_file edit_file create_file list_dir
Search search_grep glob recall
Execution run_command run_in_background
Git git_status git_diff git_commit
Memory/Tasks memory_save todo
Clone spawn_agent

But tools cannot all be let through without restriction—the model occasionally misbehaves. Every tool carries a safety-level declaration, managed in three tiers:

fig5-safety.png safe (read-only): viewing files, searching code—no approval needed, keeps things smooth.

mutation (write to disk): editing files, committing git—by default shows an approval prompt with the diff; can be bypassed with --yes.

danger (high-risk): arbitrary commands, deletions, external requests—forced manual confirmation, no negotiation.

The approval popup shows red/green diffs at a glance; you just nod or shake your head. Reading is green-light all the way, writing is step-by-step confirmation until you trust it enough to relax.

Delegating power and feeling safe are not mutually exclusive; they are sold in tiers.

4. Memory Management: The Context Window Is the Agent's Lifeline

Anyone who has run long tasks knows: an Agent gradually "gets dumber" mid-task—forgetting what it changed, re-reading the same file, even forgetting the original task.

The cause is almost always the same: the context window is full, and early information gets squeezed out.

Context is the Agent's short-term memory. The longer the task and the more tool results, the fuller the memory. Most products simply truncate—dropping the oldest messages. That's like making a worker lose memory mid-job.

My approach is compression with archiving plus on-demand recall:

fig4-context.png When the window is nearly full, early messages are packed into a two-part "summary slot": entity indices are extracted deterministically with regex—deduplicated but not rewritten, lossless indexing is required; narrative summaries are allowed to converge by the model itself. Long tool results are desensitized first, then saved to disk, without losing a single character.

The key is the second half: summaries lose detail, but the model has a recall tool—if it feels something is missing, it can search it back. When a hit is found in the archive, the diff and test output from that time are pulled back into context, and it also checks on the spot whether the file has been modified again (marks it stale, trust the disk).

Analogy: it's not tearing up old papers; it's filing them in a drawer, labeling the drawer, and reaching in when needed.

The window always has room, and information is always traceable—that's called memory, not cache.

5. Extension Trio: Hooks, Skills, MCP

The kernel is just a chassis; an Agent's playability comes from extensions. Three entry points, none requiring changes to kernel code:

fig6-extensions.png Hooks are quality inspectors on the pipeline. 11 types of lifecycle events, and you can attach your own scripts at every checkpoint: intercept dangerous commands, auto-run lint after edits, desktop notifications on task completion. Write a shell script in settings.json and it takes effect.

Skills are instruction manuals opened on demand. A directory with a SKILL.md is a skill: company release processes, private troubleshooting techniques. The beauty is they don't occupy context—normally you only see the directory, and only when needed does load_skill open the specific one.

MCP is a USB peripheral. Configure an external server (GitHub, database, browser...), and its tools automatically appear in the tool table as mcp__*. Plug-and-play like USB; the model will create issues, query databases, and screenshot web pages on its own the next day.

The loop is the engine; the trio is the steering wheel—you decide where to turn.

6. Clone Technique: Sub-agents in Parallel

A single loop is still one thread. Big tasks need splitting—the main Agent assigns subtasks to "sub-agents":

fig7-subagent.png Three details determine whether this works well:

Independent brains—each sub-agent has its own context and loop. The 100 files it reads in the middle don't occupy a single character of the main Agent's window; the main Agent only receives the final result.

Independent workspaces—git worktree isolates disk workspaces. A is breaking dependencies while B is editing code; they don't overwrite each other's half-finished work.

Budget has a tripwire—subtasks inherit the budget, and if spending exceeds the limit, it automatically circuit-breaks at the round boundary. No "clone out of control, bill explodes."

Speaking of money, let me add a few words. This tool also has a design I'm quite proud of: the cost trust chain. Each round's cost is settled in real-time and displayed in the status bar ("This session ¥0.041 / Budget ¥5.00"), you can set a budget cap for a task, and it stops automatically when exceeded.

When AI works for you, the bill can't be a black box.

7. What It Looks Like

CLI side (the VSCode side has a sidebar that supports pasting images):

fig8-terminal.png Streaming output, collapsible thinking, tools expanded individually, red/green diffs, and a bottom status bar showing real-time context level / cache hits / costs.

There's also an unattended mode: write a task ticket and acceptance commands, and it automatically works serially in an isolated worktree at night; see the report in the morning. The agent saying it's done doesn't count; only the acceptance command passing counts.

Conclusion

Back to the opening line: under the hood there is no magic. Whether Claude Code, Codex, or mine, the core is the same loop—the difference is in the craftsmanship of each link in the loop: what to do when the window is full, how to tier tools, how to isolate subtasks, how to calculate bills.

These questions that textbooks gloss over are all real skills. Writing one from scratch, the biggest takeaway isn't reinventing the wheel itself; it's forcing yourself to think through every detail clearly.

The project is fully open source. Feel free to dig into the code, file issues, and throw bricks:

fig-cta.png

If this article made you a bit clearer on "what an Agent really is," a like is the biggest encouragement for me.

Comments

Top 2 of 6 from juejin.cn, machine-translated. The original thread is authoritative.

蝎子辣椒

Watery post.

樊小肆

[Grinning] If it's not water, it won't make trending. No idea how it gets recommended. Solid articles usually go unnoticed, but one watery piece gets pushed straight away.

樊小肆

If you want substance, check out the open-source project on GitHub.

badhope

This post breaks down the Agent loop clearly. I've been adding something similar: every step in the loop must persist state, otherwise you have to replay from the start after an interruption. My state table now has run_id / step / tool_call_hash / result, and on resume I verify the hash before continuing. When you wrote your DeepSeek coding assistant, did you keep state in memory or in a database?

樊小肆

Persisted it, but I don't have a database. I write it directly into the trace.