When a coding agent changes a file in your repo, the file is opened by ordinary code around the model, and the model only writes which file to open. I wrote nanoagent to see this out in the open. It's a small agent of a few hundred lines of Python that can read and change files and run commands in the shell, and it talks to the Anthropic API with no framework in between. The code is at github.com/AhmetErenLapanta/nanoagent, and according to the README it has three parts: a loop, a tool dispatch table and an event stream.
All you need to try it is Python 3.12, uv and an Anthropic API key:
git clone https://github.com/AhmetErenLapanta/nanoagent.git
cd nanoagent
uv sync
cp .env.example .env
Put your ANTHROPIC_API_KEY value in the .env file you copied. The bash tool runs every command the model asks for without asking you, so start nanoagent in an empty folder inside the repo:
mkdir scratch && cd scratch
uv run nanoagent
Relative paths land in this folder, but the tools also take absolute paths, and for bash every folder is one cd away.
The model never touches the disk
A language model is a function that takes text and gives back text, and on its own it can't even open a file. Part of the text it produces, though, is a tool request. The model writes that it wants to call the read_file tool with a certain file path, and the code that opens the file and adds the result to the conversation is mine. When a tool is requested, the API stops generating text and writes tool_use in the stop_reason field of the response. Nothing else happens until the code decides what to do, and what we call an agent is exactly the code that runs in that gap.
The loop looks at a single if
Every message you send means a new turn. run() in loop.py runs one turn, and this is its loop:
for _ in range(max_iterations):
yield Thinking()
response = client.messages.create(
model=model,
system=system,
max_tokens=4096,
tools=schemas,
messages=messages,
)
events, blocks, calls = _process_response(response)
yield from events
messages.append({"role": "assistant", "content": blocks})
if response.stop_reason != "tool_use":
yield TurnDone()
return
results = [dispatch(call) for call in calls]
yield from results
messages.append(
{"role": "user", "content": [_to_result_block(r) for r in results]}
)
In each iteration (each pass through the loop) the model is called with the conversation so far and the schemas of the six tools, and its answer is added to the conversation. The agent's whole control flow is in this if line. If the model didn't ask for a tool, the turn ends there. If it did, the result of each call is added as the next message and a new iteration starts.
One answer from the model can hold both text and more than one tool request. _process_response separates them, and the loop runs all the tool calls of that iteration in order. The model's only memory is the messages list that new messages are appended to. nanoagent doesn't touch old messages and never summarizes them. The list grows without limit. On a short task you won't notice, but when you try to have it write a whole application, that's the first wall you'll hit.
The loop doesn't write a single line to the screen. It sends everything that happens out as one of six event types: Thinking, AssistantText, ToolCall, ToolResult, TurnDone and AgentError. I think this separation is the best part of the design, because when you put a new interface in front of it, you don't have to touch the loop. render.py draws the screen in the terminal. When Thinking comes in, a spinner turns with a random word next to it like marinating or overthinking. Tool calls show in a separate style and the model's answer shows in a panel.
The model picks which tool gets called, and the loop only decides whether to go on or stop. The rest of the behavior is written in plain English sentences in the system prompt in cli.py, and tuning an agent mostly means writing this prose:
- For a multi-step job, a plan of 1-3 lines first.
- One summary at the end, without narrating each tool call.
edit_fileon an existing file.write_fileonly for a new file or a file that changes completely.- Shell commands that depend on each other in a single command, like
cd foo && pytest. - Before a destructive command like
rm -rforgit reset --hard, one line that says what is about to happen and why.
Half the tools only read
nanoagent has six tools: read_file, write_file, edit_file, ls, grep_files and bash. All six are hardcoded, and nanoagent can't connect to an MCP server that brings in ready-made tools from outside. Each tool has a Pydantic class that describes its arguments and a function that does the work. The smallest one is read_file:
class ReadFileInput(BaseModel):
path: str = Field(
description="Path to the file to read (relative to cwd or absolute)."
)
def _read_file(args: ReadFileInput) -> str:
return Path(args.path).read_text()
The class is converted to JSON Schema (the description of arguments the API understands) and sent along, and the model learns how to call the tool from there. For a seventh tool you also need to write a description next to the class and the function, and the three go into the TOOLS dictionary together as one _Tool record:
@dataclass(frozen=True, slots=True)
class _Tool:
description: str
input_model: type[BaseModel]
runner: Callable[[Any], str]
The description also tells the model when to pick the tool. The read_file description, for example, suggests grep_files for searching inside files and ls for listing a folder, so the reading work is split between these three tools. In the sample session in the README, the agent that's asked to summarize the project opens src/nanoagent/loop.py with read_file first. grep_files searches with a Python regex and a glob filter like *.py, and it returns at most 100 matches, with only a count for the rest. The model never sees the 101st match, and narrowing the search is up to it.
Editing has one condition
edit_file replaces a piece of the file with a new one, and the piece it looks for has to appear in the file exactly once. If it appears twice, the tool throws an error that starts with old_str appears 2 times and asks for a piece that appears only once. dispatch catches this error and turns it into a result marked is_error, and in the next iteration the model can try again with a longer piece that appears once. An unknown tool name or an argument that doesn't fit the schema reaches the model the same way. write_file, which writes the whole file from scratch, doesn't create the parent folder itself, and when the folder doesn't exist its error takes the same path. The program doesn't crash. The error enters the conversation as an ordinary message, and most of what makes an agent feel solid comes from here.
Every bash call starts from zero
The bash tool runs the command with /bin/sh and a 30-second timeout, and what goes back to the model is the exit code, stdout and stderr. If time runs out, the output collected up to that point goes back with an exit timeout (30s) line.
Every call opens a new shell, so a cd in one call is gone in the next, and that's why the && rule is in the prompt. Nothing in the code stops a command. _bash runs every command it gets. The destructive command rule in the prompt makes the model say one line before an rm -rf, and the loop carries on without waiting for your approval.
When it stops
A turn ends in two places. When the model stops asking for tools, TurnDone comes. If it still isn't done after 25 iterations, the loop exits with the max_iterations (25) exceeded error, so a confused model can't spin forever. You can stop it too. When you press Ctrl-C, the CLI cuts the conversation back to the length it noted before the turn, and it does the same on an unexpected error.
snapshot = len(messages)
messages.append({"role": "user", "content": line})
try:
for event in run(messages, client=client, model=MODEL, system=SYSTEM):
renderer.event(event)
except KeyboardInterrupt:
del messages[snapshot:]
renderer.interrupted()
del messages[snapshot:] deletes the half-finished turn from the conversation. Whatever write_file, edit_file or bash changed on disk in that turn stays where it is, but the model doesn't know about it anymore.
If you want to build your first app with an agent step by step, start with the /en/learn page.