How Z Engine works
These pages explain Z Engine 2.0 for everyone: people who just use the app, people who are curious about what happens behind the screen, and people who want to change the code. Every section starts in plain words and goes deeper step by step, so you can stop reading as soon as you know enough. How to read these pages explains the layout, and the contents list every page.
To learn how to use the app, read the user guide instead. The engine's formal runtime contract is v2 engine architecture.
What an AI coding agent is
In plain words
An AI coding agent is a chat assistant that can do things, not only talk. Think of a capable new colleague sitting at your computer: they read your code, run commands and edit files, but they ask before touching anything important and tell you what they did.
How it works
- A model is a program that reads text and writes text. On its own it cannot open a file or run a command.
- The app tells the model which tools exist ("read a file", "search", "run a shell command", "edit a file"), each with a name and a description of its input.
- When the model wants to act, its reply contains a tool call: "run
Readonsrc/auth.ts". - The app runs the tool and sends the output back as a tool result.
- The model reads the result and decides the next step. This repeats until the model answers without asking for a tool.
That repeating cycle is called the agent loop. Almost everything else in Z Engine exists to make the loop safe, fast, and trustworthy.
For developers
- The loop is
AgentRunin run/agent.rs: rounds of request, stream, record, then either a tool batch or the stop boundary. - The engine reaches a model only through the
ModelClienttrait in client.rs, with adapters for OpenAI-compatible chat and Anthropic messages in the same crate. - Tools implement the
Tooltrait in tool.rs; the 22 built-in names are listed in names.rs.
The core idea: judgment versus authority
In plain words
The model supplies judgment; the engine supplies authority, execution, evidence and durability. Picture an expert giving instructions over the phone (the model) and a site manager who holds the keys, does the work, keeps the receipts and writes everything in the logbook (the engine).
How it works
The engine takes on four jobs the model is never trusted with:
- Authority: who may do what. Every tool call, hook, MCP tool and check goes through one permission gate. The gate decides allow, ask or deny from your permission mode and rules. An ask becomes an approval card. The model cannot skip the gate.
- Execution: the engine does the work. The engine, not the model, reads files, runs commands and fetches web pages. It runs safe calls in parallel, cancels work when you press stop, and can confine commands in a sandbox.
- Evidence: facts, not claims. Each check that runs is recorded with its exit code, its test counts and a fingerprint of your files. The verification badge comes from those records, never from what the model says.
- Durability: nothing gets lost. Every visible change is an event that is also written to the session log on disk. Before each of your messages a checkpoint snapshots your files, so you can rewind, and chats survive a crash.
For developers
- Authority: the gate in batch/gate.rs runs
PreToolUsehooks, then asks the pure policy engine (decide/pipeline.rs); asks wait in the broker (broker/approvals.rs). - Execution: only
z-engine-hosttouches the OS or the network (lib.rs); tools reach engine services through the capability traits in ports. - Evidence: the badge is computed from check records in assess.rs.
- Durability: the session log is written by z-engine-store; code snapshots live in a shadow git repository (checkpoint/shadow.rs).
- The app and the engine speak only through the typed protocol:
Commandvalues go in (commands.rs) andEventvalues come out (events.rs).
One turn at a glance
In plain words
A turn is everything between your message and the agent's final answer. It works like a cook with an order: check the pantry, cook a step, taste, repeat, and finally plate the dish with a quality stamp on it.
How it works
- You send a message. Before any tool may run, the engine takes a checkpoint of your files.
- The engine assembles the context: the system prompt (base instructions, your environment, instruction files, skills, the repo map), the list of tools, the conversation so far and short reminders. If the conversation is close to filling the context window, it is compacted first.
- The model streams its answer; text and thinking appear as they arrive. This single model response is one round.
- Each tool call passes the gate: hooks first, then the permission decision. All the calls that need your approval show their cards at once.
- Tools run in the order the model asked for them; neighbouring read-only calls run together. Every call gets exactly one result, even when it was denied, failed or cancelled.
- All results, plus any messages you typed meanwhile (steering), go back to the model in one message, and the next round starts at step 2.
- When the model answers without tool calls, the stop boundary decides whether the turn really ends: a
Stophook, a steering message or a failed check can send it back for another round. - The turn ends with an outcome (completed, cancelled, failed, stopped by a budget), its token usage and cost, and the badge.
For developers
- The session actor owns the command channel and never waits on the model or a tool, so steering, approvals and cancel stay responsive.
- session/turn.rs runs one user turn:
UserPromptSubmithooks,turnStarted, the checkpoint, the agent run, andturnFinishedwith its badge. - One round: budgets in run/budget.rs (
agents.max_turns, default 200 rounds, and the session cost cap), context pressure in run/pressure.rs, the request in run/request.rs, streaming in run/stream.rs, the batch in batch/execute.rs, and the stop boundary in run/stop.rs. - A typical event sequence:
turnStarted,assistantStarted,textDeltaandthinkingDelta,assistantFinished,toolStarted,toolProgress,toolFinished, thenverificationChangedandturnFinished(approvalRequestedandapprovalResolvedin between when a call asks). - Outcomes are
TurnOutcomein session.rs:Completed,Cancelled,Failed,BudgetExhausted, andInterruptedfor a turn the app closed on.
Walkthrough: "fix the failing test"
The same request, told at all three levels.
In plain words
You type "The login test fails. Please fix it." The agent runs the tests to see the failure, reads the code involved, shows you an edit to approve, runs the tests again, and explains what it changed. Under its answer the footer says Verified, because a passing test run happened after the last edit.
How it works
- Checkpoint. The engine snapshots your project, so Rewind can bring the files back later.
- Round 1: see the failure. The model calls
Verifyto run the project's test check, for examplenpm test. In Ask mode a test command is not read-only, so an approval card appears. You choose Always allow… then In this chat, which adds a rule such asBash(npm test:*)for the rest of the chat. The check fails; the engine records the exit code, the failed test count and the full output. - Round 2: investigate. The model calls
Grepfor the test name andReadon two files. Reading inside the project doesn't ask, and these calls are read-only, so they run at the same time. - Round 3: fix. The model calls
Editonsrc/auth/token.ts. The edit is accepted only because the file was read first and has not changed since. In Ask mode the card shows the diff; you click Allow once. The turn is now marked as having changed files. - Round 4: prove it. The model calls
Verifyagain. Your session rule allows it without a card. The check passes, and the engine stores a fingerprint of the files as they were when it ran. - Round 5: report. The model writes a summary without tool calls, so the stop boundary runs. No hook objects and no steering is waiting. In the default
reportverification mode the engine only computes the badge: a passing test newer than the last edit, with a matching fingerprint, gives Verified. - Footer. The turn records its outcome, duration, tokens and cost.
Had the model run a single test through Bash instead of Verify, the badge would read Unverified: plain shell runs are not recorded as evidence. Had you edited a file after the passing run, the check would be stale and the badge would say so.
For developers
- The webview calls the Tauri command
send_command(commands/session.rs) withCommand::Submit; the session actor starts the turn, and session/checkpoint.rs snapshots the tree. Verify(builtin/verify.rs) runs checks throughCheckPort(ports/checks.rs), which records aCheckRecordand emitscheckRecorded.Edit(builtin/edit.rs) checks read-before-edit with the file tracker (fs/tracker.rs).- Always allow… › In this chat arrives as
resolveApprovalwithApprovalDecision::AllowSession { rule }(permission.rs); the rule joins the session policy for the rest of the chat. - The stop boundary calls the verifier seam (verify/verdict.rs), which asks assess.rs for the badge;
verificationChangedandturnFinishedcarry it to the GUI. - Every event goes to the webview on one Tauri event,
engineEvent(events.rs), is received in listen.ts and reduced into the session view by sessionView/reduce.ts. - To reproduce a flow like this in a test, the dev-only
z-engine-testkitcrate provides aScriptedModel, aFixtureRepoand anEventRecorder(lib.rs).
How to read these pages
- Every feature section has three parts, always in this order:
- In plain words: one to three sentences with an everyday analogy and no jargon.
- How it works: the mechanism in simple steps. Technical terms link to the glossary.
- For developers: the crates and files involved, the key types and events, and how to extend the feature.
- Code links point into this repository, so they open the exact file.
- These pages describe what the code does today. When a page and the code disagree, the code wins; please report it.
- For step-by-step instructions, use the user guide. For the crate layout and the rules for changing code, read AGENTS.md.
Contents
| Page | What it explains |
|---|---|
| How Z Engine works | This page: the agent loop, the core idea, one turn, a worked example |
| Core features | Conversations, turns and rounds; tools and tool batches; permissions and approvals |
| Interaction features | Steering, interrupt and cancel; plan mode, questions and todos; hooks; slash commands, custom commands and skills |
| Agents and context | Subagents and background agents; what the model sees and how instruction files, memory, compaction and caching shape it |
| Integrations and safety | MCP and language servers, verification, checkpoints and rewind, sessions, providers, models and cost, settings layers and workspace trust, the sandbox |
| The desktop app | How the window follows the engine: events, many chats at once, the window's glass and title bar, self-updates |
| The desktop app's screens | Each screen and panel: home, Inbox, transcript, approvals in the composer, island, the side panel (Changes, Plan, Agents, Context), settings, composer and palette |
| The desktop pet | Where the pet goes and how it grows, how it is drawn in 3D (and when it falls back to flat), and the island's portrait of it while it roams |
| Experimental features and the decision layer | How a feature is tried (Off, Shadow, On) and becomes standard; the decision model, the seams where it may act, its sidecar or native runtime, and the decision trace |
| Decision uses | What each of the 21 decision features does: context and cost, task-scoped history and its log record, routing, safety, verification, suggestions, and how they are tested |
| Crates | What each crate does, its main modules, and how the crates depend on each other |
| Glossary | Short definitions of every term used on these pages |
See also: User guide · v2 engine architecture · Documentation contract