The loop is 30 lines. The transcript is the hard part.
The first time I called a chat-completion API, I printed the reply and felt nothing in particular. Then I read about
tool calling, and that changed how I thought about “agents.” The model never runs anything. It returns a structured
request (“call read_file with this path”), my code runs it, appends the result to the conversation, and asks
again. The first version of MiniBot was basically this:
messages = [{"role": "system", "content": SYSTEM_PROMPT}, *history,
{"role": "user", "content": user_input}]
for iteration in range(1, max_iterations + 1):
resp = llm.chat(messages, tools)
messages.append(to_message(resp))
if not resp.tool_calls:
return resp.content # final answer
for tc in resp.tool_calls:
result = execute_tool(tc.name, parse_args(tc.arguments))
messages.append({"role": "tool", "tool_call_id": tc.id,
"name": tc.name, "content": str(result)})
return "Too many tool rounds."
That’s the whole idea of an agent: a loop. I spent the next six months (67 commits, then a rewrite in TypeScript) on everything around it, and it took me a while to see what all of that work had in common.
The model knows nothing about the world except the transcript. It doesn’t see your disk, your clock, or the fact that the user hit Ctrl+C halfway through a tool call. It sees a list of messages. So an agent runtime is really a system for keeping that list true while the world changes underneath it: tools fail, runs get cancelled, a human takes five minutes to approve something, the context window fills up, the process crashes.
Each section below is one way the transcript can lie to the model, what MiniBot does about it, and where it still falls short. The code is from the Python version.
1. “This is everything that happened”
My first sessions were a JSONL file that got rewritten in full on every save. When the conversation got too long, I
summarized the old part and saved [summary, *recent_turns]. It worked, but every compaction destroyed history.
The fix (ad4ca56) was to separate two things I’d been treating as one:
- The log (
messages.jsonl) is append-only. It holdsmessageentries andcompactionentries. A compaction entry stores a summary and a pointer,first_kept_entry_id, to the first message it didn’t summarize. - The projection is what the model actually receives: a synthetic summary from the latest compaction, then the kept messages, then everything after. It’s rebuilt from the log and never stored.
log (append-only) projection (sent to model)
m1 user "fix the failing test" ┐
m2 assistant → read_file a.py │ summarized
… │
m6 tool read_file result ┘
m7 user "now run it" [summary of m1–m6] ← c1
m8 assistant → exec pytest m7 user
m9 tool exec result m8 assistant → exec
c1 compaction first_kept=m7 m9 tool
m10 assistant → delete tmp/ m10 assistant → delete
(cancelled, no result) ·· tool: interrupted ← added
m11 user "ok, try again" m11 user
If you’ve seen event sourcing, this is the same shape: the log is the source of truth, a compaction is a snapshot,
and the model’s context is a read model. Nothing is lost on disk, so search_history, MiniBot’s episodic memory, can
search the raw text of past sessions, summaries included. There’s no vector database: for one user, searching the
source of truth directly is simpler and easier to debug.
It isn’t free. The projection is recomputed on every append, so a session costs O(n²) over its lifetime. The Python
loader also can’t handle a half-written last line after a crash; the TypeScript rewrite skips a torn final line.
And search_history deliberately skips the current session, so the model can’t yet dig up a detail that was
compacted out of the conversation it’s in.
2. “That delete never happened”
The model asks to delete a directory. The user cancels while the tool is running. What should the next request show?
My original projection dropped any tool call that didn’t have a matching result, which seemed tidy. It meant the model never learned that a delete had been issued, so on the next turn it could simply issue it again (23bd87a).
Two rules fix this. First, the loop persists the assistant message carrying tool_calls before running any tool:
intent is logged before effect. (Like a write-ahead log, minus the fsync, so it survives a process crash but not a
power cut.) Second, the projection decides what to do with a call that has no result based on where it sits:
if expected_ids and len(expected_ids) == len(actual_ids) and set(expected_ids) == set(actual_ids):
projected.append(message) # complete: pass through
projected.extend(tool_messages)
elif cursor < len(messages): # something came after it: that run is over
projected.append(message)
projected.extend(cls._results_with_interruptions(message, tool_messages))
# else: it's at the tail and may still be running, so hide it for now
A missing result gets a synthetic interrupted result that says, in effect: this may not have run, may have partly
run, or may have finished; side effects unknown; check before retrying. In database terms it’s an in-doubt
transaction, and I chose “presumed unknown” over “presumed aborted,” because only one of those can make the model
delete something twice. It also keeps a protocol invariant: every tool_call id in a request has a matching tool
message, which OpenAI-compatible APIs expect.
Still wrong: results are appended only after the whole set of tool calls in a step finishes. If a run is cancelled during the second batch, an edit that succeeded in the first batch is reported as “interrupted.” That’s safe, but it throws away something the runtime knew. Appending each result as its tool returns would fix it.
3. “The file is what I read”
Models like to issue several tool calls at once, and running read-only ones in parallel is an easy speedup. Tools
declare their properties (read_only, exclusive, requires_approval), and the loop never special-cases a tool by
name. But “run all the reads in parallel” is subtly wrong. The loop only batches consecutive concurrency-safe calls:
for planned in planned_tool_calls:
if planned.tool and planned.tool.concurrency_safe:
current_batch.append(planned)
continue
if current_batch:
batches.append(current_batch)
current_batch = []
batches.append([planned]) # anything else runs alone, in order
Every non-safe call acts like a memory fence. If the model sends [read a, edit a, read a], grouping the two reads
would let the second one run before the edit and return stale content. read_only also isn’t the same as
concurrency_safe: web_search and fetch_url change nothing locally but are marked exclusive, so they run one at a
time. Every MCP tool is exclusive too, because I can’t verify what a third-party server does.
One side effect of this design I hadn’t planned for: only batches of two or more go to the thread pool, so a tool
with side effects never runs on a worker thread. On cancel, the loop can abandon the pool with
shutdown(wait=False, cancel_futures=True), because the only threads that can outlive a cancelled run are read-only.
The flip side is that a long exec runs on the loop thread with no cancel hook, so Ctrl+C waits for the command’s timeout.
The other half of “the file is what I read” is time. Between the model reading a file and editing it, there’s model
thinking time and, worse, unbounded human approval time. Someone may have saved the file in the meantime. So
read_file returns a SHA-256 of the content, and edit_file requires it:
current_sha = sha256_text(original)
if expected_sha256 != current_sha:
return ToolOutput.failure(
"conflict", "文件已被修改,sha256 不匹配。请重新 read_file 再 edit。", # "file changed, re-read first"
data={"path": path, "expected_sha256": expected_sha256,
"current_sha256": current_sha})
It’s the same idea as an HTTP ETag with If-Match. The hash survives even when a large file was only shown to
the model as a preview plus paged reads, because the artifact store carries it along. Edits are applied bottom-up so
line numbers stay valid, then written via temp file, fsync and os.replace.
Still wrong: check-then-write isn’t atomic (there’s no file lock), editing a CRLF file normalizes it to LF, and
the temp-file write doesn’t preserve the original file mode, so an executable script comes back as 0600. I found
that last one while writing this post.
4. “The user said yes”
My first safety layer was a regex denylist for things like rm -rf, mkfs and curl | sh. It’s still there as a
seatbelt, but it took me too long to admit it can’t be the policy: you can’t enumerate dangerous commands, and
find . -delete walks right past it. The real question was never “is this command dangerous?” but “should a human
see this before it runs?”
So tools that write or execute declare requires_approval, and the loop asks an approval policy before running them.
A denial isn’t an exception. It goes back to the model as a tool result, so the model can explain or try another way.
Here’s what I wrote the next day:
def _approve(self, tool_name, args):
if self.approval_handler is None:
return True
return self.approval_handler(tool_name, args)
No real caller ever hit that branch, because every frontend wired up a handler. But the default was fail-open, and
when I refactored the core in July, I wrote a unit test called test_missing_handler_approves_in_ask_mode asserting
exactly that behavior. I had turned the bug into a spec. The core of the fix is one line, return False, plus a
denial the model can relay. A safety check has to fail closed: “nobody answered” must mean no.
Approval turned out to have more ordering problems than I expected:
- Validate, then approve. At first, approval ran before argument validation, so a human could approve a call that
was then rejected as malformed. Now
registry.preparevalidates against the JSON Schema, binds the arguments into an immutablePreparedToolCall, and then asks. The human approves exactly the call that will run. - Never ask from worker threads. Approval happens on the loop thread. Otherwise you get several prompts at once, prompts out of order, and denied calls that have already started.
- Decisions can arrive before the question. In the web UI, the
approval.requiredevent goes out over SSE before the loop starts waiting, so a fast click can POST its decision first. The broker keeps these “early decisions.” After a cancel it leaves a tombstone, so a late click is rejected instead of being parked as an early decision that nothing will ever consume.
Still wrong:
- The scheduler inherits the global approval mode. If you set it to
always, unattended runs auto-approve shell commands. - The MCP client treats any non-timeout error during a call as a connection failure, reconnects, and calls the
tool again. For an untrusted server’s
mail_send_message, that’s at-least-once delivery under one approval. A retry is only safe when the request definitely never reached the server. Otherwise the call needs an idempotency key that the server deduplicates on.
5. “This summary is the conversation”
The context window is a budget, and the budget needs a number. The provider’s token count is exact but arrives after the request. A local tokenizer is instant but wrong for most models. MiniBot uses both: the last observed input count as a baseline, plus a local estimate of only the messages added since.
previous_count = self._request_message_counts.get(session.session_id)
if previous_count is None or previous_count > len(session.messages):
return max(observed_input_tokens, self.estimate(built)) # compaction shrank things
added_messages = session.messages[previous_count:]
...
return observed_input_tokens + added_tokens
When the budget runs out, compaction has to choose a cut point. It walks back about 16K tokens of recent context, then moves forward to the first position that is not a tool result and not the start of an incomplete tool block:
for index in range(threshold_index, len(messages)):
if messages[index].role == "tool":
continue
if not _starts_with_incomplete_tool_transaction(messages, index):
return index
The invariant is that the kept slice never begins with a tool result whose call was summarized away. If a single turn is bigger than the budget, it’s split, and the first half is summarized separately. The previous summary is passed in explicitly, so a summary is never re-summarized as if it were conversation.
Compaction can also fail, and each fallback has to stay honest:
-
Summarize with the model.
-
If the summarizer errors, use the previous summary, a failure note, and a truncated digest of the raw text.
-
If there’s no safe cut at all (say, one enormous tool result at the end), drop that tool block, but only if every tool in it was read-only, and tell the model so:
[Omitted oversized read-only tool transaction] tools: read_file reason: tool results exceeded the model input budget before the model could consume them. The raw tool call and results remain in the session log.A read can be re-run with narrower arguments. A write’s result can’t be dropped without hiding a side effect, so in that case the turn stops with an error the user can act on.
Still wrong: the first request of each turn falls back to the local estimate, because the observed baseline isn’t carried across turns. With the compaction trigger at the model’s hard input limit, there’s no headroom for estimation error.
6. “That string is just metadata”
Everything in the prompt is content. I learned this from two bugs.
Memory IDs were generated from timestamps, like m_20260417_010203. The model started reading the ID as the date
the fact happened, which broke anything involving “today” or “tomorrow”
(c045c38). Now the IDs are sequential (mem_1, mem_2). They
are never reused, so a stale reference can’t point at a different fact, and the current date comes before memory in the prompt.
The system prompt also carried the current time down to the second. Because the system prompt leads every request,
the provider’s prefix cache missed on every call
(3b6f419). Now the system prompt only has the date, and the
minute-level time is appended to the latest user message in the request, not in the log. A moving clock costs at most
the current turn’s tail, and cached_input_tokens is recorded per run so the hit rate can be checked. Memory still
lives in the system prompt, though, so every remember invalidates the whole cached prefix. That’s next.
7. Lies the runtime told me
The worst bugs were the ones where every component reported success.
In the TypeScript rewrite, I rebuilt the system message before each request and accidentally dropped the tool declarations (1c0c7c0). DeepSeek started writing tool calls as plain text. Since “no tool calls” is exactly how the loop recognizes a final answer, a missing tool declaration looks identical to a finished turn. Nothing errored, and the agent just seemed lazier.
Two smaller versions of the same problem:
pytest ... | tail“succeeded” with pytest not installed, because a pipeline returns the exit code of its last command.execnow runs underbash -o pipefail, and treats exit code 141 (SIGPIPE from| headclosing early) as success with a note.- Retrying a failed model call is invisible only until the first text delta reaches the user. After that, a
silent retry would print the answer twice, so the retry condition starts with
if emitted_delta or ...: raise.
8. What made this fixable
By early summer the Python core had become hard to change. My test for whether I understood it was simple: can I read one whole turn in one function? I couldn’t. The loop was split across two classes that called back into each other through closures, and facts about a turn left the core through five paths: UI events, callbacks, return values, an exception that smuggled token usage out on failure, and a recorder object. Every fix in this post would have had to happen in several places.
The core rewrite made run_turn read top to bottom (budget,
build request, call model, run tools, persist) and made a single event stream the only way out. The CLI renders it,
the web UI forwards it over SSE, the run log folds it into one row per run, and Langfuse tracing later became one more
subscriber. The usage-smuggling exception disappeared, because usage now leaves the loop as an event the moment it’s
known. With one deliberate exception: session persistence is not a subscriber. The loop writes the log in the same
call that produces the message, because persistence must succeed and a UI is allowed to drop events.
The rewrite removed about 890 lines net and kept all 178 tests passing. It also deleted an eight-hook plugin system whose only real user was approval. An abstraction with one consumer is usually the wrong shape, because there’s no second example to check it against.
Then, in October, I rewrote MiniBot in TypeScript as minibot-ts on
pi’s pi-agent-core, and let the library own the loop: streaming, tool
execution, cancellation, provider adapters. I didn’t miss it. Everything I kept was about the transcript: the
append-only log and its projection, rebuilding the request before every call, compaction, approval, retries, and
closing turns that didn’t finish.
If I started over
One thing I’d do the same: write the loop by hand before touching a framework. It’s 30 lines, and it’s the reason
I could tell exactly what pi-agent-core was doing for me when I switched. What I’d do differently:
- Separate the log from the projection on day one. Rewriting the session file on every compaction cost me history I can’t get back.
- Log intent before effect. When you don’t know whether a side effect happened, tell the model exactly that.
- Make safety fail closed, and test the default. My test suite was happily asserting the opposite.
The code is on GitHub: minibot (Python, full history) and minibot-ts (TypeScript).