--- slug: durable-agent-session type: pattern summary: "Keep an agent run's identity and event history outside replaceable processes so it can pause, recover, and fork without losing its past." created: 2026-10-20 updated: 2026-10-21 related: source-of-truth: relation: depends-on note: "A durable session makes one event stream authoritative when process memory, transcripts, and sandboxes disagree." externalized-state: relation: uses note: "Externalized state preserves authored plans and artifacts; a durable session also preserves the runtime events that connect them." agent-trace: relation: produces note: "A durable session's event stream can produce the trace used for debugging, evaluation, and cost analysis." ephemeral-environment: relation: enables note: "Durable session state lets the execution environment be destroyed and replaced without ending the run." harness-engineering: relation: implemented-by note: "Harness engineering defines how sessions are stored, restored, steered, and forked." checkpoint: relation: depends-on note: "Checkpoints give a resumed or forked session a verified position from which to continue." idempotency: relation: uses note: "Idempotency keys let a recovering harness confirm or safely retry an operation whose outcome the session never recorded." event: relation: uses note: "A durable session applies event sourcing to an agent run: the ordered event log is the record, and current state is derived from it." context-offloading: relation: uses note: "Context offloading selects a workable slice of durable history for the model's bounded context window." --- # Durable Agent Session > **Pattern:** A named solution to a recurring problem. *Keep an agent run's identity and event history outside replaceable processes so it can pause, recover, and fork without losing its past.* Your coding agent is halfway through a migration when its container disappears. The files may still exist, but the run also needs its requests, tool calls, approvals, failures, and current position. If those lived only inside the dead process, the next harness can inspect the workspace but can't safely continue the same run. A durable agent session keeps that history elsewhere, where another process can pick it up. ## Understand This First - [Source of Truth](source-of-truth.md) — the rule that identifies which record wins when copies disagree. - [Checkpoint](checkpoint.md) — a verified position from which a session can resume or fork. - [Ephemeral Environment](ephemeral-environment.md) — the disposable runtime this pattern allows you to replace. ## Context At the **agentic** and **operational** level, long-running agents outlive the processes that serve them. A run may pause for approval, wait in a queue, cross a deployment, exhaust a context window, or move to a fresh sandbox. The harness process and execution environment are replaceable. The session can't be, because it carries the causal history of the work. A durable session is more than a saved chat transcript. It has a stable identity and an ordered event stream: user requests, model responses, tool calls and results, steering messages, approvals, checkpoints, and terminal outcomes. The current harness reads that stream, derives the state it needs, and continues from a known position. [Context Offloading](context-offloading.md) then chooses which parts of the full history belong in the model's bounded working context. ## Problem How do you let an agent run survive replacement of its harness or sandbox without losing history, replaying side effects, or pretending that a new run is the old one? Process memory is quick but fragile. A serialized conversation is durable but incomplete if tool results, approvals, and execution outcomes live elsewhere. Restoring either one without a clear event order can make the agent repeat a database write, run a migration twice, or resume before the human decision that originally unblocked it. Forking makes the ambiguity worse: two descendants may share the same past while producing different futures. ## Forces - **Recovery needs fidelity.** The more history you retain, the more accurately a new harness can reconstruct the run, but storage and replay costs grow with every event. - **History should be append-only, while privacy duties may require deletion.** You need a deletion and redaction policy that doesn't silently rewrite the run's meaning. - **The model needs a small working set.** The full record is too large to feed into every model call, yet anything left out of context must stay retrievable. - **External effects aren't replay-safe by default.** Restoring a session must not repeat a payment, deployment, message, or migration whose first result was already accepted. - **Forks share a past but not an identity.** A branch must retain its parentage while receiving its own event sequence and side effects. ## Solution **Store each run as a durable, append-oriented session outside the harness process and execution sandbox.** Give the session a stable identifier, record every state-changing interaction as an ordered event, and make the event store the source of truth for recovery. Separate the session from the machines that use it. A harness may crash and restart. A sandbox may be destroyed after a task and replaced with a clean one. Neither event ends the session. The replacement harness opens the same session, finds the last accepted checkpoint, reconstructs derived state from the event stream, and creates or attaches an environment for the next step. Treat restoration as a protocol, not as deserialization. Recovery reads the results it already has; it doesn't re-run an action whose result is on record. This is event sourcing applied to an agent run (see [Event](event.md)). Durable-execution workflow engines recover the same way: they log each external call's result and hand back the logged result when the workflow restarts. The hard case is a tool call whose request was recorded but whose outcome wasn't. Give side-effecting operations stable [idempotency](idempotency.md) keys, which let a service recognize a repeated request and return the first result instead of acting again. If the outcome still can't be established, stop at that event and ask for resolution. Don't assume the call failed merely because its response is missing. A recorded action is a fact, not a plan step. If the resumed agent picks a different approach, its new plan starts from what already happened, including a half-applied migration or a message already sent. An agent that replans without reading the log may re-create a table the first run already migrated, or revert a change it no longer remembers making. Keep full history and active context distinct. The session retains the complete event stream for recovery and audit. The harness selects a smaller working view for the next model call: recent turns, the current plan, unresolved tool results, and summaries or references for older material. This lets retention policy and context policy evolve independently. Model forks explicitly. A fork points to a parent session and a checkpoint, then writes to a new event stream. It doesn't append competing futures to the parent's history. The lineage makes comparison and audit possible, while distinct identities prevent one branch's approvals or side effects from silently authorizing another. > **⚠️ Warning:** A session is not durable merely because its transcript is stored. If approval decisions, tool outcomes, or side-effect receipts live only in process memory, recovery can still repeat work or skip a required gate. ## How It Plays Out A hosted coding agent starts upgrading a monorepo and records each request, tool call, test result, and checkpoint in its session store. Its microVM is reclaimed after an hour of inactivity. When the developer returns the next morning, the service starts a new environment and checks out the saved revision. The harness rebuilds session state through the last verified checkpoint and loads only the current plan plus recent events into context. The run continues with the next package instead of starting over. An agent requests a production deployment just before its harness loses its network connection. The session contains the deployment request but no result. On recovery, the new harness queries the deployment service with the original idempotency key. The service reports that the deployment already succeeded, so the harness records that outcome and moves on. Reissuing the operation blindly could have created a second release or sent duplicate notifications. A developer wants to compare two repair strategies after a failing integration test. They fork the session from the last clean checkpoint. Both branches inherit the same evidence and workspace revision, but each receives a new session identity and a separate sandbox. One branch changes the database adapter; the other changes the retry policy. Their histories remain comparable without mixing approvals, tool results, or commits between them. ## Consequences **Benefits.** Runs can pause for minutes or days, survive process failure, and move between clean environments without losing their causal history. Recovery becomes an inspectable protocol. Forks become first-class experiments rather than copied transcripts with uncertain lineage. [Agent Trace](agent-trace.md) data can be derived from the same record, while [Externalized State](externalized-state.md) remains available for human-readable plans and artifacts. **Liabilities.** The session store becomes sensitive infrastructure. It may contain source code, secrets captured in tool output, human messages, and a detailed record of privileged actions. Retention, access control, encryption, redaction, and deletion all need explicit policies. Append-only design makes tampering harder but complicates legal deletion duties. A common answer keeps event metadata immutable and stores payloads separately, sometimes encrypted under per-record keys so that destroying a key erases the payload without rewriting the log. Durability also increases implementation cost. You need event ordering, schema evolution, checkpoint compatibility, idempotency across external systems, and recovery tests that kill processes at awkward moments. A short interactive task doesn't need this machinery. It earns its cost when runs are asynchronous, long-lived, expensive to repeat, or allowed to affect systems outside the workspace. ## Sources - Lance Martin, Gabe Cemaj, and Michael Cohen's [*Scaling Managed Agents: Decoupling the brain from the hands*](https://www.anthropic.com/engineering/managed-agents) (Anthropic, 2026) describes an append-only session log kept outside both the agent harness and its sandbox, so either can be replaced independently. It also separates the session's job (durable, queryable history) from the harness's job (choosing what enters the context window). - DigitalOcean's [Managed Agents documentation](https://docs.digitalocean.com/products/managed-agents/) documents sessions that can be paused, resumed with their history and working state intact, or forked from a checkpoint. - OpenAI's [Agents API overview](https://developers.openai.com/api/docs/guides/agents-api/overview) defines a session as a durable agent instance whose state the platform retains across turns and asynchronous work, with recovery and resumption handled by the service. - Temporal's [Events and Event History](https://docs.temporal.io/workflow-execution/event) documentation describes the append-only history that lets a durable workflow recover from a crash, and notes that a recorded side effect returns its stored result on replay instead of running again. --- - [Next: Task Horizon](task-horizon.md) - [Previous: Externalized State](externalized-state.md)