Skip to content

Durable Agent Loop

The analyst's request for Alice's churn question runs a query, waits for her approval, runs another query, and writes a chart. Halfway through, the host is redeployed and the analyst's process is killed. When it comes back, the request continues from the step it was on. The first query doesn't run again, and the approval Alice already gave still counts.

This post covers the loop a request runs and the event log that makes it recoverable.

The loop

Each request runs a think, act, observe cycle. In the think phase the model gets the current context and returns an action: tool calls to run, or a final answer. In the act phase the tool calls run. In the observe phase their results fold back into the context. The loop continues while the model returns tool calls, up to the agent's max_steps.

# src/mash/core/agent.py: Agent.run() (trimmed)
for step in range(self.config.max_steps):
    plan = await self.plan_step(context)      # think: one LLM call → an Action
    results = await self.act(plan.action)     # act: execute tool calls, or [] if none
    commit = self.commit_step(                # observe: fold results into context,
        context, plan.action, results,        # decide whether we're done
        step_index=step,
    )
    context = commit.context
    if commit.done:
        break

Almost everything an agent does is a tool call: run_query, run_code, the browser tools, read_board, a skill, a remote MCP tool. The loop runs them the same way. Tool calls the model emits together run concurrently unless a tool sets parallel_safe = False; approval-gated tools and AskUser always run alone.

Accepted before it runs

When the companion starts the analyst's request, the runtime appends invoke_agent.start to the log before execution begins, with the request's trace id already on it:

# src/mash/runtime/requests.py (trimmed)
accepted_event = await append_runtime_event(
    self,
    RuntimeEvent(
        request_id=request_id,
        trace_id=str(uuid.uuid4()),
        event_type=RuntimeEventType.INVOKE_AGENT_START.value,
        dedupe_key="request.accepted",
        ...
    ),
)
await self.engine.start_request(request_id=request_id, ...)

The dedupe key makes the accept idempotent: submitting the same request id again lands on this row and keeps its trace id. Once this row exists, the request exists, even if the process dies before the first model call.

The event log

Each request is an ordered stream of rows in runtime_event_log. Every event type is the OpenTelemetry span it starts or ends:

# src/mash/runtime/events/types.py
class RuntimeEventType(str, Enum):
    INVOKE_AGENT_START   = "invoke_agent.start"
    INVOKE_AGENT_END     = "invoke_agent.end"
    CONTEXT_LOAD_START   = "mash.context_load.start"
    CONTEXT_LOAD_END     = "mash.context_load.end"
    CHAT_START           = "chat.start"
    CHAT_DELTA           = "chat.delta"
    CHAT_END             = "chat.end"
    EXECUTE_TOOL_START   = "execute_tool.start"
    EXECUTE_TOOL_END     = "execute_tool.end"
    STEP_END             = "mash.step.end"
    INTERACTION_START    = "mash.interaction.start"
    INTERACTION_END      = "mash.interaction.end"

A span ends once, and how it ended is its status: ok, error or cancelled. A request that completes, fails or is cancelled writes the same invoke_agent.end with a different status. Each row carries the request_id, its per-request seq, the agent_id, session_id and trace_id, the loop_index of the step that wrote it, and a JSONB payload. Rows are appended and never updated.

Each step appends its output with a dedupe key: chat.end for the model call, with the assistant's blocks and tool calls; execute_tool.end for each tool call, with its full result; and mash.step.end for the commit. The loop holds its state in memory while it runs and writes nothing else. The event log is the request's only record in flight.

Recovery

When the analyst's process starts again, it rebuilds each running request's state from its events and continues it:

# src/mash/runtime/engine/loop.py: RequestRun._run (trimmed)
state = await rebuild_request_state(runtime, ..., events=await store.list_request_events(request_id))
if state is None:                           # no context load recorded yet
    state = await load_request_context(...)
while not state.get("done"):
    if state.get("action") is None:        # no chat.end for this step
        state = await retry_transient(lambda: plan_request_step(...))
    state = await self._act(state)          # runs the calls with no execute_tool.end
    state = await commit_request_step(...)

The rebuild applies the events with the same functions the running loop uses, apply_plan for a chat.end and commit_state for a committed step, so it arrives at the state the loop held. mash.context_load.end records the system prompt as rendered, including the app's Cortex profile, and the board position the request read, so the rebuilt context is the one the request first saw.

flowchart TD
    L["context load\n(mash.context_load.end)"] --> P["plan N: one model call\n(chat.end)"]
    P --> T0["tool call N.0\n(execute_tool.end)"]
    T0 --> T1["tool call N.1 …\n(execute_tool.end)"]
    T1 --> C["commit N\n(mash.step.end)"]
    C -- "not done" --> P
    C -- "done" --> F["board entry,\ninvoke_agent.end"]

Each box ends with an event, and a crash between two of them resumes at the boundary. Re-running a plan costs one extra model call. A tool call that has its execute_tool.end does not run again, so the analyst's first query, with its result in the log, is never sent to the replica twice. In a parallel batch each call has its own execute_tool.end, and only the calls without one run again. An open interaction is found again by its derived id, and an answer that arrived while the process was down is read from the log.

When the loop finishes, the request writes its board entry, then invoke_agent.end. Nothing reaches memory_turns before that. A request recovered more than 10 times fails.

Streaming is a read of the log

A client's stream is a cursor over the log. The server reads everything after the cursor, and when there is nothing new, waits for the store's LISTEN/NOTIFY signal on the runtime_events channel. Frames are written before they are streamed, so a client that reconnects with ?after= gets the same frames it would have seen connected.

to_public_event maps each internal row to a public frame. Lifecycle events get their own names (request.accepted, request.started, request.interaction.create, request.interaction.ack, and one of request.completed, request.error or request.cancelled, picked by the status on invoke_agent.end). Everything else arrives as agent.trace with the internal event_type in its data. Clients match on the public names, and the internal vocabulary can grow under them.

The analyst's request for Alice, annotated:

event: request.accepted        ← invoke_agent.start: the request exists
event: request.started         ← execution began
event: agent.trace             ← mash.context_load.end: board up_to 0, APP MEMORY
event: agent.trace             ← chat.start, loop_index 0
event: agent.trace             ← chat.end: the model calls run_query(sql=…)
event: request.interaction.create  ← approval for run_query; the event is waiting
event: request.interaction.ack     ← Alice approved
event: agent.trace             ← execute_tool.start, then execute_tool.end with rows
event: agent.trace             ← mash.step.end: step 0 committed
event: agent.trace             ← chat.start, chat.delta …, chat.end: the answer
event: agent.trace             ← mash.step.end
event: request.completed       ← invoke_agent.end, status ok, with the response text

Each model and tool frame carries its duration, the model and provider, token usage, and the tool's arguments and result. A slow request shows whether the model or a tool took the time. chat.delta frames carry streamed text chunks; the authoritative text arrives on request.completed.

Cancel

POST /sessions/{sid}/events/{eid}/cancel cancels the event's requests on the companion and on the agent it routed to. A request stops at its next step boundary: the step in flight finishes and appends its events first, so a tool call that already started completes and its result is recorded. A request waiting on an interaction has it closed as cancelled.

One request's log, cancelled while the model call after the seventh tool call was in flight:

seq  event_type                     detail
40   execute_tool.start             sleep 3 && echo step-7
41   execute_tool.end               ok
42   mash.step.end
43   chat.start
44   invoke_agent.end               cancelled
45   chat.end

The model call that was already running recorded its result after the cancel. Terminality reads the last lifecycle event, so the trailing chat.end leaves the request cancelled and its stream closes.

Failures

Failure Handled by The app does
Transient error (rate limit, timeout, network) retry_transient(): three retries with exponential backoff and jitter nothing
Retries exhausted, or a terminal error (bad key, context overflow) request.error with error_code and retryable posts the message again as a new event
Process crash (OOM, kill -9) the restarted process rebuilds running requests from their events nothing

Errors are classified by pattern in src/mash/runtime/errors.py, and unknown errors default to retryable. A failed request leaves a <failed_request> entry on the board, so the next event in the session can retry it.

The events are the same whichever provider ran the think step. Every adapter implements one send(LLMRequest) -> LLMResponse contract, covered in One LLM Contract, and chat.end names the provider and model in its attributes.

The loop pauses in three places: before an approval-gated tool, at AskUser, and at a browser handoff. All three are one mechanism, and that's the next post.

Next: Human-in-the-Loop.