Your agent loop should forget the conversation.

An agent loop that keeps no conversation or tenant state moves complexity into two places: the contract and your backend. Here is what that costs, and what it gives up.

You're shipping an assistant inside a product used by hundreds of customers. Each has its own system prompt, its own tools, its own model, sometimes its own provider key. The assistant doesn't just answer: it reads orders and requests bookings or refunds. All of it runs through the same loop: model, tools, model, until there's a final answer.

The loop needs the conversation, so the obvious move is to let it store the conversation. But your product backend already stores conversations, along with users, tenants and permissions. Put a second copy inside the loop and you have two owners for the same data, and every disagreement between them is a bug.

I went the other way. The engine owns no durable conversation or tenant state. One HTTP request is one run, and the request carries everything: provider, model, key, system prompt, the full history, the tools (an endpoint and a JSON schema each) and the limits. The engine runs the loop, streams text and hands back the result with per-attempt usage.

That's not the same as "no state at all". While a run is alive, and for a while after it ends, the engine holds its execution state, its result, a session lock and an idempotency mapping in memory. What it never holds is anything that has to survive: no conversations, no assistant configs, no tenant records. Those stay in your backend, and they come back with every request.

This trade isn't free, and it isn't right for everyone. Here's where the complexity went. The examples come from theloop, an open-source engine I maintain, where each of these decisions is written down in the contract.

Who owns what

  • The harness is your backend, a low-code platform or a workflow tool. It owns durable product state and business decisions: conversation history, assistant and tool configs, business operations, approvals, billing, authorization.
  • The engine owns bounded run execution and the temporary state it needs: steps, retries, limits, streaming, cancellation, token accounting, result delivery.

Per-request configuration means the engine can serve many tenants without storing a tenant record. It does not mean multi-tenancy is solved. The harness still owns authorization, quotas and fairness, and tool endpoints must scope data by identity the harness passes through the loop, never by ids the model wrote into the arguments.

The same split decides what a retry is allowed to do. Write tools in theloop don't execute anything: they register an intent and answer deferred, and the harness executes after approval, with its own idempotency key. That's why "retry a lost run" never means "refund twice". I wrote that pattern up separately, as a prompt-injected agent can ask for a refund.

Cost #1: the history goes over the wire, every run

The first objection is the right one. Every run uploads the full history from the harness to the engine: serialization, transfer, parsing, memory. The default request ceiling is 1 MB. Provider prompt caching does nothing about that hop. I haven't measured where that overhead starts to matter; a long-running agent with large tool results will hit it before a short chat does.

The second cost is the provider's prompt cache. The model gets the whole prompt on every step anyway, and a cache hit makes that cheap. But if anything near the start of the prompt changes between turns, the provider recomputes everything after it. So the rule is: between turns, the history is append-only, and nothing that changes from turn to turn may sit in front of it.

  • Time goes into user messages, not the system prompt. Models need the date for anything with deadlines, but a "current time" line in the system prompt breaks the cache on every turn. A user message that carries created_at gets its own timestamp line, which never changes once written. Without created_at, the last user message gets a temporary current-time line that's gone on the next turn, so that prefix breaks. Harnesses should send it.
  • Tools are sorted by name. Anthropic and GLM put tool definitions at the very top of the prompt, and harnesses often send tools in arbitrary order. One reshuffle and the whole cache is gone.
  • The engine never rewrites history. On newer Claude models a changed prefix also invalidates the signed thinking blocks after it, and the provider answers with an error. Where the engine has to change the prefix itself, trimming to fit the context window, it asks the provider to drop the stale blocks instead.

A stable prefix makes a request cache-friendly; it doesn't guarantee a hit. Cache lifetime and eligibility are still the provider's rules.

Cost #2: you have to hand the result back

An engine that doesn't keep results forever has to deliver them, and delivery has more edges than it looks.

  • A callback with retries: five attempts, pauses of 2, 4, 8 and 16 seconds, about 80 seconds in total. Duplicates are possible; the harness dedupes by run_id.
  • If the callback fails while the process is alive, the result stays readable at GET /runs/{id}. Default retention, counted from the end of the run, is 10 minutes once the harness acknowledges the result and an hour if it never does. Acknowledged results can be evicted earlier under memory pressure.
  • If the process dies, the result dies with it. GET is not crash recovery. The harness has a deadline, the run's timeout plus 120 seconds; no callback by then, it calls GET, and only a 404 means the run is lost.
  • "Lost" is not final. A late callback, say from an old container that finished its run after a deploy switched traffic, must overwrite lost with the real result.

Late results have their own trap. While the run was considered lost, the user may have kept talking, and you can't insert old messages into the middle of a newer history. So the request carries a history_revision, a number the engine doesn't interpret and simply echoes back. Same revision: insert as usual. Different: keep it for audit and show it as an event in the conversation, not as an assistant reply written into the past.

The race that decides when a lock is released

  1. Run A finishes, and the client gets done over the stream.
  2. The callback is delayed.
  3. The user sends the next message.
  4. Run B starts with the old history, without A's answer.

The fix: for requests that carry a session id, the engine holds the session lock until the harness acknowledges the result, not until the run ends. A 2xx on the callback counts as acknowledgment, so the harness must answer 2xx only after the result is durably written, not after it's queued.

While a run is active, a second run for the session gets 409 session_busy. Once the run has ended but its result isn't acknowledged, it gets 409 result_pending with the id of that run: fetch it, record it, acknowledge, retry. An identical request with the same idempotency key returns the existing run instead of a conflict. If acknowledgment never comes, retention expiry eventually releases the lock.

The same race forces idempotent writes. The callback, a GET and a cancel response can all arrive at once, so everything is an upsert keyed by deterministic ids: a run by run_id, a message by run and sequence number, a tool result by call_id.

And there's no atomic "interrupt and restart". When the user types while the model is still answering, the harness cancels. Cancel normally waits for the run to stop and returns the result with the partial answer; if a tool holds the connection longer than five seconds, it returns 202 cancelling and the result arrives by callback or GET. The cancel can also lose the race to a normal finish. Only after recording and acknowledging that result does the harness start the next run. An atomic preempt would need the new request to contain a partial answer that doesn't exist yet when the request is built.

Retries that don't splice text

You can't always retry a provider call. If the model has already streamed half an answer and the connection drops, a "transparent" retry glues a second answer onto the first, and the user has already seen the first.

  • Retries (network, 5xx, 429) happen only before the attempt's first content event: a text delta, a reasoning part or a tool call. After that, the run fails as interrupted and keeps the partial answer.
  • Tools run only after the model's step finished cleanly, not as calls appear in the stream. A dropped stream must not leave a half-executed batch. This is also why the engine drives the loop step by step itself instead of using an SDK's built-in loop.
  • Loops get brakes. A call that repeats the previous one with the same arguments isn't executed again; by default the second repeat, or a second empty result from the same tool, turns tools off for the rest of the run.
  • The last allowed step goes without tools by default, with a short note to answer with what the model has. If it answers, the run completes with a limit_reached flag; if it can't, the engine supplies a fixed fallback text and the run ends stopped_limit. The user sees an answer instead of an empty error.

The same "first content event" line decides model fallbacks. A request can list up to five model configurations, all validated before the run starts. If an attempt fails before its first content event (auth, rate limit, 5xx, network, even "context too large", with the prompt rebuilt for the next model's window), the run moves to the next entry immediately, without retrying the failed one; ordinary retries apply only to the last entry. After a content event there's no fallback, for the same reason there's no retry. The switch is sticky for the rest of the run, and limits are shared across models.

Usage records for billing and reconciliation

If you resell model access, you need an audit trail for every provider attempt, including the ones that failed or may have been billed anyway.

  • One usage record per real provider attempt, including failed and interrupted ones. SDK retries are off; the engine retries itself and records every attempt.
  • Status and accuracy are separate. ok usually carries the provider's numbers, but if the provider doesn't report usage it's an estimate flagged estimated. failed means a refusal before processing, zero tokens. unknown covers network errors, timeouts, 5xx and dropped streams, where the provider may have processed the request and billed for it.
  • Input tokens are always uncached input. Providers disagree on whether cached tokens are included; the engine normalizes, and cache reads and writes get their own fields because they have their own prices.
  • Budgets are checked before every attempt, conservatively. The input side is a heuristic estimate, the output side is the full max_tokens allowance, and an unknown attempt keeps its reserve for the rest of the run. That can stop a run that produced little visible output, and it still can't guarantee the provider's final charge.

A crashed run can leave no usage record at all. Reconciling with the provider's bill is the harness's job; the contract sets a gap of up to 2% as the operational target, not as an accuracy guarantee.

What this design gives up

  • One instance. The session lock is an in-process mutex, so v1 is one always-on process: 32 concurrent runs by default, 429 overloaded beyond that, and unacknowledged results also hold capacity. There's no active-active deployment and no crash failover. Coordinating several instances is on the roadmap, and even then it's coordination, not durable execution.
  • Runs live in memory. A crash loses the runs in flight. The harness learns about it from the 404 at its deadline and can retry from the history it had already stored. The lost run's intermediate steps may be gone, so the retry can repeat model and tool calls and cost money again.
  • Deploys are best-effort. On shutdown the engine waits up to its grace period, seven seconds by default, then cancels unfinished runs, keeping their partial results, and makes one last delivery attempt. Traffic switching can make old runs briefly unreachable, so the harness must accept late callbacks.
  • No step-level durable execution, by design. If your workflows run for minutes, call expensive tools and must resume from the middle after a crash, you want durable execution with persisted intermediate results, and this design is the wrong tool. It fits short runs where restarting a lost one is acceptable.

What you get for it: the engine adds no conversation database to migrate, back up or keep in sync, and any language or low-code platform can drive it over HTTP. The harness still needs durable history, idempotent result ingestion, operation tracking and recovery logic. The trade makes sense when those already belong to your backend.

The full contract, including the list of obligations on the harness side, is in the spec.

If you've built an agent loop: where did you put the state, and what bit you? Tell me.

Written with the help of AI and reviewed by the author; every claim is checked against the theloop spec as of v1.4.1.