# An agent's determinism comes from its state machine

Date: 2026-01-28
Category: Tech Topics
Tags: Agent, State Machines, Engineering Architecture
Summary: Why do prompts keep getting longer while the Agent still fails at the same place? Starting from a piece of source code, break down the state machine, streaming rendering, background processes, and permission boundaries to explain where determinism should be sought

The first Agent I ever built was only a dozen or so lines: a while loop, call the model, parse the tool call, execute it, stuff the result back into context. It ran fine locally.

Then I took it to organize a repository of tens of thousands of lines, and the problems started. At some point a file read failed, and it began repeating the same call, with identical arguments and identical errors, burning through a large chunk of quota in four minutes and finally blowing up the context. Staring at the logs, I thought: this isn't the model's problem, it's that I never left it a place to go "after failure."

I read that leaked source code twice. What I got out of it wasn't in the prompts, it was in the state.

## Locking uncertainty into a finite number of states

Its lifecycle is cut into several segments: building context, orchestrating tools, streaming execution, checkpointing and recovery. The segmentation itself isn't novel; what's novel is that every failure path has an explicit landing spot.

When arguments can't be parsed, it doesn't throw an exception and let the upper layer catch it; it enters a dedicated state for handling parse errors, letting the model replan once with the error information. The retry counter distinguishes "first failure" from "retry failed again," because the causes of these two are often different. When a tool fails consecutively up to a threshold, the circuit breaker cuts it off directly, no longer letting the model try, and the state hangs pending human intervention.

In pseudocode, it looks roughly like this:

```ts
while (state !== 'End' && state !== 'Error') {
  switch (state) {
    case 'Plan':    state = plan(ctx); break;
    case 'Execute': state = await exec(ctx); break;   // 失败时 attempt += 1
    case 'Recover': state = recover(ctx); break;      // 回滚到最近的健康快照
    case 'Checkpoint': save(ctx); state = 'Plan'; break;
  }
  if (ctx.attempt > 3) state = 'WaitingForUser';
}
```

What actually does the work isn't this loop, it's that every branch can be exhaustively enumerated. When writing business code I'm used to trusting that "exceptions will be handled by the upper layer." In an Agent this assumption doesn't hold, because the upper layer is also probabilistic: the model sees an error message and may correct itself, or may make the same mistake in a different way.

```mermaid
stateDiagram-v2
  [*] --> 构建上下文
  构建上下文 --> 计划
  计划 --> 执行
  执行 --> 检查点: 成功
  执行 --> 错误翻译: 参数或工具失败
  错误翻译 --> 计划: 带错误重规划
  错误翻译 --> 熔断: 连续失败到阈值
  熔断 --> 等待人工
  检查点 --> 计划: 未完成
  检查点 --> [*]: 完成
  等待人工 --> 计划: 确认后继续
```

The state on the session engine side shows the same orientation. The message queue, interrupt controller, permission-denial records, token usage, file-read cache—all explicitly hung on one object rather than scattered across closures. At first I thought this was Java-style verbosity; by the third tool I realized that as long as one tool secretly mutates a global variable, rollback stops working. State must be enumerable to be saved, restored, and compared.

I didn't do the checkpoint layer at first, thinking it was heavy. Later I found it solves a different problem: error stack traces pollute the context. Feed back dozens of lines of exception information and the model often doesn't get smarter—it gets led astray, then goes further and further down the wrong branch. Rolling back to the snapshot before the mistake and injecting a much shorter compensating instruction—"this path doesn't exist, list the directory first and then decide"—makes the success rate noticeably different.

The cost is memory and implementation complexity. Every healthy node requires a deep copy of the context, token statistics, and the state tree; in long sessions these aren't small. My current approach is to save snapshots only when crossing boundaries like "plan to execution," not at every step. The saved overhead buys coarser recovery granularity, which is acceptable.

One more detail: tools running in parallel fight over state. Multiple calls read and write the same file at the same time, append to the same log at the same time—when rolling back, who comes first and who comes after is unclear. Its approach is to merge independent calls into batches and run them in parallel, strictly serialize dependent ones, and wait for each batch to finish before moving on. This rule is simple enough to write in a piece of code, but it turns "concurrency" from a probabilistic problem into an ordering problem.

Timeouts also need layering. Tools have their own timeouts, the state machine has an overall timeout, and users have a patience limit. If you only do one of the three layers, the most common phenomenon is: the tool is running, the interface doesn't respond, the user thinks it's frozen, presses Ctrl-C twice, and in the end nobody can say what state was left behind.

## The real difficulty of streaming output is state

At first I thought the terminal UI part was over-engineering: a command-line tool, rendered with React, with a custom reconciler to boot.

After writing my own streaming-print CLI, I stopped thinking that. Outputting character by character, showing the execution progress of three tools, preparing a diff preview, and ensuring the user can interject and interrupt at any time—maintaining these partial refreshes with imperative cursor control, and the code turns into a mess by the second week.

Its approach is to split state into two layers: session-level stuff—message history, overall state, checkpoints—updates infrequently; the segment currently being streamed is kept separately, updates frequently. The top-level component subscribes only to the former; the child component responsible for the typewriter effect subscribes to the latter with fine-grained selectors.

This distinction isn't an aesthetic issue. The pit I fell into was updating global state on every token, so the entire component tree re-rendered, the interface started lagging, and in severe cases characters got swallowed. After changing to updating only the current node plus a throttling layer, the problem disappeared. Extremely high-frequency output even gets accumulated in a buffer first and flushed to the screen at a fixed frame rate.

Interruption is another easily overlooked spot. After the user presses Ctrl-C, the interface must stop immediately, but the background tool can't be hard-killed—the file being written will be left half-done. My later approach is two steps: first switch the state to "stopping," stop rendering new tokens, then give the tool a brief wrap-up window, and force-kill only on timeout. This intermediate state looks ugly in the UI, but it's better than data corruption.

Its rendering works like this: write a custom React reconciler, hook it up to Yoga for flexbox layout, diff the virtual nodes, then translate them into ANSI escape sequences and spit them to the terminal. When I first saw it I also thought it was over-engineering; only later did I realize the difficulty is in "partial repaint": the terminal has no browser compositing layers, and a full screen clear flickers. Tracking styles, text attributes, and event handlers separately is to keep event-handle changes from triggering repaints. Optimizations like this only occur to you after writing a few thousand lines of terminal UI.

The trade-offs are obvious too: introducing the React runtime slows cold start, and the state tree, buffers, and dependent processes all pile up in one terminal process, so memory usage won't be low—the community has complained about this all along. I lean toward accepting it, because the state complexity is already close to a single-page application, and the maintenance cost of toughing it out with imperative code is higher. If it were just a small tool that prints logs, this whole thing would be pure burden. In the end, this transfers complexity from "user understanding" to "runtime"; things in the terminal look simple, but the bill is in places you can't see.

## Beyond the foreground there's also a background

In the source there's a daemon called KAIROS, hidden behind a feature flag. What it does isn't mysterious: write interaction logs by day, organize memory when idle, and support hanging a session into the background to keep running.

A few constraints are worth noting: background tasks have a 15-second blocking budget, and beyond that they're detached from the main flow; merging memory adds a file lock to prevent multiple instances from writing the same file at once; the background process is restricted to read-only, can only touch its own memory directory, and doesn't touch the user's project source code.

These three constraints together say one thing: it isn't a "smarter assistant," it's a maintenance process with strictly limited permissions. This positioning is very restrained, and it's also why I find it credible.

The accompanying commands are also interesting—`ps`, `logs`, `attach`, `kill`—almost transplanting the intuition of container orchestration into the terminal. For people used to tmux this is natural: a session isn't a one-off Q&A, it's something that can be suspended, reconnected, killed and restarted. I don't need it for now, but it points in a direction: the interaction form of an Agent may be more like a service than a dialog box.

The memory organization mechanism works on the opposite principle to RAG (Retrieval-Augmented Generation). RAG chunks, vectorizes, and recalls by similarity; the upside is that capacity can be offloaded externally, the downside is that it severs temporal order—it recalls a pile of relevant fragments but loses "why we chose this approach in the first place." This approach instead compresses within the original context: trimming thousands of lines of grep output down to just the conclusion; folding multiple rounds of trial and error into one sentence like "changing component A didn't help, it turned out to be a version conflict in dependency B"; pinning the paths and decisions strongly relevant to the current task at the top of the prompt.

The advantage of this approach is that it doesn't depend on an external vector store, and the reasoning chain stays intact; the disadvantage is that it consumes background compute—compression itself requires calling the model, which is a hidden cost—and the ultimate capacity is still limited by the window.

These three actions have different costs. Pruning is the safest: information is lost but can be re-run; semantic compaction introduces judgment, and one wrong compression means all subsequent reasoning is built on a false premise; entity persistence is the least effort, but it pins the context down, and you have to remember to clear it when switching tasks. If I were building it myself, I'd do the first one, observe for a while, then consider the second.

This also explains why I don't quite believe in "infinite memory." Each layer of compression introduces a judgment, and judgments err; the more layers, the earlier the error occurs and the harder it is to find.

For now I don't plan to replicate this in my own project. For conversations under ten turns, a sliding window is enough; and once you add a background compression process, the race condition between it and a user suddenly interjecting immediately becomes a new source of bugs. This kind of mechanism suits long-cycle tasks where the context inevitably balloons—it's not suitable as a default configuration.

## Permission boundaries are the last line of defense

Everything above is a performance and maintainability issue; this section is about whether something goes wrong.

Once an Agent can read files, run a shell, and connect to MCP (Model Context Protocol) services, its attack surface shifts from "the model says the wrong thing" to "executing arbitrary commands on the local machine." The typical path goes like this: the Agent reads a repository's README or a web page with instructions hidden inside; the context is poisoned, and the model treats it as a task; the state machine enters the execution phase and calls the shell tool with concatenated arguments; there's no sandbox on the local machine, so the command runs.

Any link in the chain can be intercepted. Argument whitelists, path validation, read-only mounts, outbound traffic restrictions—all are achievable in engineering. One spot I prefer is inserting a suspended state between planning and execution: for operations involving deletion, writing to system directories, or sending network requests, don't execute directly—first surface the intent to the user and wait for explicit confirmation.

This sacrifices smoothness, especially in batch tasks where confirmation pop-ups get annoying. My judgment is that it's worth it on the core path, while edge operations can be let through. As for "absolute security," I don't believe in it—as long as the model can touch the environment, there's a possibility of bypassing the sandbox. What you can do is assume it will go out of control, and think ahead about where to cut losses when it does.

If I'm going to run someone else's code, I treat the whole environment as untrusted: use a disposable container or VM, don't run on a machine with real credentials; don't give root inside the container; cut outbound traffic if the debugging doesn't need network; put fake keys in environment variables; disable scripts like `postinstall` in the repo before looking at them. These are all crude measures, but they block the most common class of accident: running someone else's code like a tutorial and handing over your local config and keys along the way.

After reading that source code, my changes to my own project were minimal: added an explicit failure state, added a retry limit, and ran tool-call arguments through a whitelist. The UI is untouched, no background process added. It's not that those designs are bad—it's that at my scale they're unnecessary; building a daemon setup for a ten-turn chatbot would only make debugging harder.
