# The loop

> What one turn of zelk's loop does, how the reducer and the driver split the work, and the states a session moves through.

The loop is a small cycle that repeats until a run is done: decide what to
do next, do it, record it. zelk keeps the deciding and the doing in two
separate parts, and everything on this page follows from that split. It
starts with one turn of the cycle and ends with the states a session moves
through.

## The reducer and the driver

The **reducer**, [`loop.Step`](/reference/go/loop/), is a pure function. It
takes the session's state and one event from its log and returns the new
state. The state includes the **effects** it wants done next: call the
model, run these tools, ask a person. The reducer does no I/O, reads no
clock and draws no random number, so the same log always folds to the same
state and the same pending effects.

The **driver** does what the reducer asks. For each effect it checks that it
still holds the lease, appends that the effect started, does it, and appends
how it ended, with the results, in one batch. Then it folds what it appended
and looks at the new state. It keeps nothing of its own: whatever it does
next follows from the log.

The split pays off three ways.

- **Replay.** Folding a log needs no model, no tools and no workspace, so a
  session can be read back, inspected or rewound exactly as it happened.
- **Recovery.** The state lists every effect that started and hasn't ended.
  After a crash, that list is all the next process has to settle
  ([Durability and recovery](/concepts/durability/)).
- **Testing.** The reducer takes events and returns state, so its rules are
  tested without a provider or a disk. The driver is tested with fakes
  standing in for both.

A host that needs another way to run effects can write its own driver from
the public pieces and keep the same guarantees.

## One turn

A turn is one model call and the tool calls it asks for.

1. **The request.** The reducer builds the model's request from the session
   as folded: the system prompt and tools first, then project context, then
   the conversation, with any messages that arrived since the last call
   ([Context and compaction](/concepts/context/)).
2. **The model call.** The reducer asks for it. The driver records that the
   attempt started, calls the provider, and records the reply and its usage.
   A call that fails in a way worth retrying is tried again, each attempt
   recorded.
3. **The decisions.** If the reply asks for tool calls, the reducer decides
   each one in the order the model gave them, against the permission rules:
   allowed, sent to a person, or refused. A refused call gets a result that
   says so, and the model reads it on its next call
   ([Permissions](/concepts/permissions/)).
4. **The waves.** The reducer asks for the allowed calls in **waves**. A run
   of read-only calls shares one wave. Any other call waits for the calls
   before it and runs alone, and so does a call that needs a person's
   approval. The driver records the intent of a whole wave
   together, runs its calls in parallel (up to ten at a time), and records
   each result as that call ends.
5. **The next call.** Once every call has its result, the results join the
   conversation in the order the model asked for them, whichever ended
   first, and the reducer asks for the next model call. When a reply asks
   for no tool, the turn ends and the run goes to its ending
   ([Runs and completion](/concepts/runs/)).

A call counts as read-only only if its tool says so and zelk trusts the
claim, which it does for built-in tools. A tool from an MCP server or a
client never counts, and neither does a shell command: they run alone.
A write never races a read of the same file, and a crash while a slow call
runs loses none of the calls that finished beside it, because each result is
recorded as it ends.

The reducer folds the log and asks for effects. The driver records each effect’s start, does it, and appends how it ended. The log is all they share. Each scene is the log as it grows:

- **A turn with tool calls**. The fold decides the waves; the driver runs them. Read and Grep are read-only, so the fold asks for both at once and they run in parallel. Edit changes files, so it waits for them and runs alone. Grep ends first, but the results reach the model in the order it asked for the calls.
   1. `command_accepted` user_message: rename Count to Total
   2. `run_started` run 1 (a record the fold owes)
   3. `effect_started` call_provider
   4. `effect_finished` wants: Read a.go, Grep Count, Edit a.go
   5. `effect_started` run_tool Read a.go
   6. `effect_started` run_tool Grep Count
   7. `effect_finished` Grep Count → ok
   8. `effect_finished` Read a.go → ok
   9. `effect_started` run_tool Edit a.go
   10. `effect_finished` Edit a.go → ok
   11. `effect_started` call_provider
   12. `effect_finished` end_turn
   13. `run_finished` success
- **A steer mid-run**. A steer joins the run’s next model call. It arrives while the command runs and changes nothing yet: the fold only holds it. When the results are in, the next model call takes it, and the run can’t end before a model call has.
   1. `command_accepted` user_message: run the tests
   2. `run_started` run 1 (a record the fold owes)
   3. `effect_started` call_provider
   4. `effect_finished` wants: Bash go test
   5. `effect_started` run_tool Bash go test
   6. `command_accepted` steer: skip the slow package
   7. `steer_outcome` applied to run 1 (a record the fold owes)
   8. `effect_finished` Bash go test → ok
   9. `steers_taken` 1 steer joined the model call (a record the fold owes)
   10. `effect_started` call_provider
   11. `effect_finished` end_turn
   12. `run_finished` success
- **A mode change waits**. A mode change waits until no tool call is running. The first edit was decided and started under accept-edits, so it finishes under it. Once it has ended the fold applies plan mode, and the second edit, not yet decided, is decided under plan mode: refused.
   1. `command_accepted` user_message: update both config files
   2. `run_started` run 1 (a record the fold owes)
   3. `effect_started` call_provider
   4. `effect_finished` wants: Edit a.json, Edit b.json
   5. `effect_started` run_tool Edit a.json
   6. `command_accepted` set_permission_mode: plan
   7. `effect_finished` Edit a.json → ok
   8. `permission_decided` deny Edit b.json: plan mode allows only reads (a record the fold owes)
   9. `effect_started` call_provider
   10. `effect_finished` end_turn
   11. `run_finished` success

## The states

A session isn't in one state. The reducer keeps a few independent facts, and
a session is in one state of each at once:

- the **session**: unstarted, started or deleted;
- the **run**: none, admitting or active (admitting while hooks decide
  whether a prompt may start a run);
- the **ending**: none, held while Stop hooks decide, or asked of the driver;
- the **interrupt**: none, or under way;
- the **suspension**: whether the host let go of the process while a request
  waits;
- each pending **effect**: pending, running, waiting or retryable.

The contract lists more, such as the budget and background work. A fact
changes only when an event folds, and the contract lists every change each
one may make.

The facts and their states: Session (`unstarted`, `started`, `deleted`); Run (`none`, `admitting`, `active`); Ending (`none`, `held`, `asked`); Interrupt (`none`, `interrupting`); Suspension (`no`, `yes`); Effect (`pending`, `running`, `waiting`, `retryable`). Each scene is a run of events and the changes each makes:

- **A run**. A run is a stretch of work between two idle moments. One message starts it, effects come and go while it is active, and the ending is asked for and then recorded.
   1. `session_started`: session: unstarted → started. The session’s configuration is recorded.
   2. `command_accepted:user_message`: run: none → active; asks for a model call (pending). A message arrives while the session is idle: a run starts, and the fold asks for a model call.
   3. `effect_started`: effect: pending → running. The driver records that it is about to call the model.
   4. `effect_finished`: ending: none → asked; effect: running → ended. The model ends its turn with nothing more to do, so the fold asks for the run to end.
   5. `run_finished`: run: active → none; ending: asked → none. The driver records the end of the run. The session is idle again.
- **Hooks first**. A run can be admitting before it is active. While hooks decide whether the prompt may start a run, it is admitting. A hook that blocks it ends the run before the model is called.
   1. `command_accepted:user_message`: run: none → admitting; asks for a hook (pending). The session has a hook that runs before a prompt starts a run, so the run is only admitting.
   2. `effect_started`: effect: pending → running. The driver runs the hook.
   3. `effect_finished`: run: admitting → active; effect: running → ended; asks for a model call (pending). The hook let the prompt through: the run is active, and the fold asks for the first model call.
- **An interrupt**. An interrupt asks for an ending, and the run settles first. The effect in flight is ended, never abandoned, so the log shows how each effect ended before the run does.
   1. `command_accepted:interrupt`: interrupt: none → interrupting; ending: none → asked. The host or the user interrupts. The fold asks for the run to end as interrupted.
   2. `effect_cancelled`: effect: running → ended. The driver cancels the call in flight and records how it ended.
   3. `run_finished`: interrupt: interrupting → none; ending: asked → none; run: active → none. The run ends interrupted, and the session is idle.
- **Waiting for a person**. Waiting for a person is a state of an effect, not of the run. The run stays active. Suspension is a separate fact: an answer can arrive without resuming the session, and a session can suspend with the request still waiting.
   1. `effect_finished`: effect: running → ended; asks for a approval (pending). The model asked for a call that needs a person’s approval. The fold asks for the approval.
   2. `effect_started`: effect: pending → waiting. The request goes out. Nothing is in flight: the effect only waits for its answer.
   3. `suspended`: suspended: no → yes. The host chose not to hold a process open. The session is suspended, and the request stays waiting.
   4. `resumed`: suspended: yes → no. The next execution resumes the session and delivers the request again.
   5. `command_accepted:answer_input`: no change to these facts. The answer is folded. None of these facts changes yet: the effect ends when the driver records it.
   6. `effect_finished`: effect: waiting → ended. The request ends with the answer, and the run carries on.

In plain words, the states that matter for what a session accepts:

| The session is | It accepts | It refuses or ignores |
|---|---|---|
| idle | a message, which starts a run; a compaction; a rewind; deleting it | an interrupt, which is recorded and does nothing; a steer, which is rejected because no run is going |
| active | a steer; a message, which waits for the next model call; a permission-mode, rule or model change, which waits its turn; an interrupt; an answer | deleting it, rewinding it, restoring files and changing its configuration, until the run ends |
| ending | an interrupt | a steer, which is rejected because the run is ending |
| interrupting | the ends of the effects in flight | any new effect |
| waiting for a person, inside an active run | an answer, or the request's expiry, whichever folds first | a second answer to the same request, which is recorded and changes nothing |
| suspended | a resume, which the next execution records before anything else | a resume of a session that isn't suspended |

A rule that refuses an event refuses it with
[`loop.ErrInconsistent`](/reference/go/loop/). Two ignore it instead: an
interrupt while nothing runs, and an answer to a request already settled.
The [contract](/internals/loop-states/#admission) names every rule.

## Commands from outside

Everything that comes from outside the loop is a command. It is appended to
the log first, and the reducer folds it like any other event.

**A message while idle starts a run.** The reducer queues the message and
asks for a model call.

**A message mid-run is a steer.** In the terminal UI, what you send while a
run goes is a steer, and it shows as queued. In Go it is
[`Execution.Steer`](/reference/go/zelk/#executionsteer). The reducer holds it,
and the next model call takes it. The run can't end before a model call has
seen it. A steer can be taken back with
[`Execution.Withdraw`](/reference/go/zelk/#executionwithdraw) until a call
takes it. If no run is going when it is sent, Go returns `ErrNoRun` and the
terminal UI sends the text as a message instead. If the run ends before the steer folds, the steer is
rejected, and the log says so. A plain
[`UserMessage`](/reference/go/zelk/#usermessage) sent mid-run isn't a steer:
it waits in the queue, joins the next model call, and doesn't hold the run
open. If the run ends first, it starts the next one.

**An interrupt** is Esc in the terminal UI and
[`Execution.Interrupt`](/reference/go/zelk/#executioninterrupt) in Go. The
reducer asks for an interrupted ending at once and drops the effects that
never started. The driver cancels the ones in flight and records how each
ended. Then the run ends `interrupted`. An interrupt tells you only that the
intent is in the log; the effects may still be winding down.

**A mode change** is Shift+Tab in the terminal UI and
[`SetPermissionMode`](/reference/go/zelk/#setpermissionmode) in Go. It is
accepted at once and applied once no tool call is running or waiting on a
hook, so every call is decided and run under one policy. Calls of the turn
not yet decided are decided under the new mode.

## Budgets, deadlines and waiting for a person

Limits are part of the folded state, so they hold across crashes. A
turn limit ([`WithMaxTurns`](/reference/go/zelk/#withmaxturns), `-max-turns`)
ends it `max_turns`. A token budget
([`WithBudget`](/reference/go/zelk/#withbudget)) charges every attempt: a hard
limit refuses a call that would cross it, and a soft limit allows one wrap-up
turn. Either ends the run `max_budget`. A wall-time limit
([`WithMaxTime`](/reference/go/zelk/#withmaxtime)) is a deadline fixed when
the run starts, so the time a crashed process spent down counts. See
[Limits](/go/limits/) for how to set them.

An approval or a question is an effect like any other. The reducer asks for
it and the driver records that it went out, and then it waits: nothing is in
flight and no goroutine is busy. The host answers while the process runs, or
lets the session suspend and answers later. A host that can't ask has the
call refused, or the run ends `blocked`. [Approvals](/go/approvals/) covers
the three ways.

## Subagents

A subagent is a child session that a tool call starts. The parent's `Task`
call reserves the child's share of the budget and records the child's start
with its result. The child then runs its own loop over its own log, and the
parent records how it ended when a call collects it. The parent's log holds
the call and those two records that link the logs, not the child's events.
[Subagents](/concepts/subagents/) follows a child from the call to its
report, and [Extending zelk](/concepts/extending/) shows where a subagent, a
hook and an MCP server plug into the loop.

## Where to go deeper

- [Durability and recovery](/concepts/durability/): what each effect's
  record guarantees, and how recovery settles what a crash left open
- [Runs and completion](/concepts/runs/): how a run ends, and why
- [Permissions](/concepts/permissions/): how each tool call is decided
- [Context and compaction](/concepts/context/): what the model sees on each
  call
- [Subagents](/concepts/subagents/): a child session with its own log,
  lease and budget share
- [Loop states](/internals/loop-states/): the facts, every change each may
  make, and the rule each event is admitted by
- The [durability contract](/internals/durability/#c3) gives the driver's
  protocol for each attempt.
