The world’s first unified interface for agent harnessesOpen Source4.7kPowered by UHP

InsightsDec 6, 202612 min read

Agent Session Management: Lifecycle, Storage and Scale

How to manage AI agent sessions in production: create, resume and end them, store state, log turns, and keep sessions alive across models and harnesses.

An ivory execution head lifts away from a graphite cradle that retains a cobalt session cartridge, ordered records and a file folder.
The execution head can stop while retained session records and files remain. This physical metaphor illustrates separating worker lifetime from stored state; recovery still requires retained data and a compatible runtime.

Agent session management is the work of creating, identifying, persisting, resuming and ending the running instances of an AI agent, so that a task survives across turns, crashes and model changes. Model inference alone does not maintain an application's session state. The session holds the agent's working context: the message history, the working files, the tools and permissions granted for the run, and an identifier that ties them together. Teams that integrate several models or harnesses into one product find that this layer, not the model, decides whether the product is reliable and what it costs. HarnessRouter's open-source unified interface and cloud platform include agent session management behind one API, across harnesses such as Codex, Claude Code, Hermes, DeepSeek and Pi.

TL;DR

  • A session is one running agent instance with its own history, files, tools, permissions, a start and an end; the model itself is stateless.
  • Give every session a unique ID, an explicit create, resume and close path, and a retention rule, so that abandoned sessions do not accumulate cost.
  • Write each state transition durably before a worker moves on, so a compatible worker can restore retained session state after a crash.
  • Store hot state in a TTL-bound store such as Redis, and keep the full log separately for tracing, evaluation and audit.
  • With several harnesses and models, a single session interface avoids rewriting lifecycle code for each provider.

What a session holds

Picture one request to a coding agent: "fix the failing test in the billing service." The agent reads files, runs a shell command, reads the output, edits a file, runs the tests again. None of that is held by the model between calls. The surrounding system must supply the relevant context, either by passing history or by using provider-managed conversation state. That surrounding state is the session.

A session normally contains four things:

  • the ordered history of user messages, model turns, tool calls and tool results;
  • working files, such as the checked-out repository or generated artifacts;
  • the tools, plugins and permissions granted for this run;
  • an identifier that links the transcript, files, billing records and log lines to the same piece of work.

The identifier matters more than it looks. Without it, a cost spike cannot be traced to a task, and a user who returns an hour later cannot be reconnected to the work in progress. Conversation history and a session are also different objects: history is only the transcript, whereas the session also carries the environment the agent acted in. Teams that store only the transcript can replay what was said but cannot reproduce what was done.

The session lifecycle: create, resume, close

The most precise public description of the lifecycle comes from the Agent Client Protocol, which is an open protocol between clients and coding agents. Under its v2 Preview session setup specification, a client creates a session with session/new and receives a unique session ID. Agents advertising capabilities.session support session/resume, optionally replaying retained history with a supported replayFrom cursor, and session/close, which cancels ongoing work and frees active resources without discarding the retained session. Retention belongs to the agent: it may skip storing sessions that were never prompted, expire old ones, or remove them with session/delete when it advertises session.delete, and resuming a discarded session fails with the error code -32002.

That last detail is where integrations usually go wrong. Resume is not guaranteed to succeed, so the calling application needs a defined fallback: start a new session seeded with a separately retained summary, if one exists and policy permits it, or tell the user that the earlier work has expired. An application that assumes resume always works fails the first time a retention window passes.

A workable lifecycle contract for a production product has five parts:

  1. Create. Issue the session ID on the server side and bind it to a user, a tenant and a task. Never let a client choose an ID that could collide with another user's.
  2. Run. Mark the session as running while it executes work, and distinguish active work, model wait and idle time according to the host's billing meters.
  3. Idle. Define an idle timeout after which compute is released while the state stays recoverable.
  4. Resume. Rehydrate history and files from durable storage, and handle the case where they no longer exist.
  5. Close and retire. Cancel in-flight tool calls, release the sandbox, and apply the retention rule to the stored data.

The agent lifecycle guide covers the stages from provisioning through session runtime to retirement in more detail. The practical point for a team is that the lifecycle contract should be consistent across supported harnesses, with harness-specific compatibility checked. Each harness has its own notion of a session, its own file layout and its own way of reporting that a run has finished. Writing and maintaining a lifecycle adapter per harness is the part of the work that grows linearly with every harness added. HarnessRouter exposes agent session management, file handling, plugin support, environment provisioning and serverless agent runtime lifecycle features through one API, and its open Unified Harness Protocol (UHP) provides a common integration contract for supported harnesses, while session and model compatibility still need to be checked.

Where to store session state

Storage choices decide how quickly a session resumes, how much the fleet costs and where sensitive data lands. Two tiers cover most products.

The hot tier holds state for sessions that are active or recently active. Redis is the common choice for distributed deployments. A Redis session store analysis from Zylos Research recommends TTLs on every session key and volatile eviction policies (volatile-lru or volatile-ttl), and warns against allkeys-lru or allkeys-lfu, because those can evict a session that is still in use. The volatile policies can also evict an active session with a TTL under memory pressure; keep authoritative state in the durable tier and make cache eviction recoverable. Its sizing model puts a 50-turn session at roughly 50 KB, which works out to about 50 to 100 MB for 1,000 concurrent sessions. Treat that as a planning estimate: tool outputs such as file contents or long command logs can make real sessions much larger, so measure your own average before provisioning.

The durable tier holds the complete record. It can be a relational table, an object store or a log, as long as it is append-only and keyed by session ID. Keeping it separate from the hot tier means that evicting a cache entry never destroys history, and that tracing, evaluation and audit read from a store that was never optimized for latency.

An ivory cache tray, a graphite record tray and a cobalt file folder sit separately, each marked by an orange identity dot.
The small upper-left tray represents a recoverable cache, the foreground tray a durable session log, and the right-hand folder the workspace files. Matching dots associate the stores with one session; they do not transfer permissions. The arrangement is conceptual, without measured capacities or retention guarantees.

Files need their own decision. A repository checkout or generated document is not something to serialize into a key-value store. It belongs in the session's workspace, tied to the session ID, with the same retention rule as the transcript. When the two are retired at different times, the result is a transcript that references files that no longer exist.

The session log as the system of record

A design that has gained ground is to treat the session log, rather than the worker process, as the agent. Pixeltable's argument is that if every state transition is written durably before the worker moves on, a crashed process can be replaced by another one that reads the same history and continues. Workers can become stateless when a compatible replacement can restore the retained log, versioned configuration, files and runtime dependencies; sticky routing is then unnecessary. Context compaction then becomes a lossy projection of a log that stays intact, so a summary can be regenerated differently later without losing the original. The log alone does not make external actions exactly once: if a worker crashes after an action succeeds but before its result is saved, reconcile the outcome or retry with a downstream idempotency key.

What the log should capture follows from what you will need to do with it:

EntryWhy it is needed
User inputReplay and intent reconstruction
Model outputReplay, evaluation, cost attribution
Tool call with argumentsDebugging and audit of what the agent attempted
Tool result with latencyDetecting slow or failing tools
System events (timeouts, retries, failovers)Explaining why a run behaved as it did
Session definition versionReproducing the exact configuration of the run

Two limits on logs deserve attention before they are used as evidence. First, SpecStory's analysis of coding-agent transcripts points out that a transcript records what the agent claimed, not what happened: a reply can say the tests pass when no test run appears in the file. Pair the transcript with the actual tool results and exit codes. Second, anything a tool returns lands in the log, including a secret read from a .env file. Redact at write time, and apply access controls to the log store as you would to a credentials store.

For the observability side, the AI agent observability guide describes what to trace, measure and audit over the same data. HarnessRouter's pricing page lists tracing as a $50-per-month beta add-on, included with Scale.

Cost and expiry

Sessions cost money in two different ways: compute while they run, and storage while they exist. Hosted platforms differ: some meter provisioned session time, while HarnessRouter meters active Agent work by the second at plan-specific per-minute rates and charges model usage separately. Check how idle compute and retained state are billed before choosing timeouts. On platforms that meter provisioned time, a session that sits idle for a day with its sandbox still provisioned can produce an unexpected invoice.

A sound default policy is short idle timeouts for compute (minutes), a longer retention window for state (days to weeks, depending on how users return), and an explicit delete path for privacy requests. Document these values in the product, because they define what a user can expect when they come back. For teams planning resource and inactivity handling in more depth, an overview of agent session lifecycle and protocol behavior places these decisions within the wider design of business agents.

Memory is a related but separate cost. Session state is scoped to one piece of work, while long-term agent memory can persist across sessions. HarnessRouter lists short-term memory (Beta) at $0.0000840 per GB-hour on Free/top-up rates, with lower rates on paid plans; long-term memory is $0.0019 per operation with storage included, and the agent memory guide explains the tiers from naive retrieval to knowledge graphs. Keeping the two concepts apart in your schema prevents session retention rules from deleting memory that should live longer, and the reverse.

Sessions across models, users and harnesses

The log design supports horizontal scaling, but concurrent turns in one session still need serialized ownership or atomic version checks. Use leases with fencing or transactional coordination so a stale worker cannot commit after another takes over; adding workers alone does not solve concurrency. The harder case is changing the model or harness mid-session. A provider outage, a rate limit or a cost rule can require moving a running task from one model to another. That only works if the session's state is held in a form the next harness can read, not in the first harness's private format.

This is the problem agent failover addresses: keeping a session alive when the component under it fails. It is also why a shared protocol is useful. When history, files and tool definitions follow a common schema and the destination supports the required models, tools, permissions and continuation state, the harness can become a replaceable part, and the choice between models can be made per task for quality, latency or cost. The agent state management guide covers the same ground for production systems, and the AI agents in production overview sets out the surrounding architecture and controls.

A short checklist for multi-model session design:

  • Keep the transcript in a provider-neutral format and translate at the edge.
  • Store tool definitions and permissions as part of the versioned session definition.
  • Record which model served each turn, so that cost and quality can be attributed per turn.
  • Run each session in an isolated sandbox with tenant-scoped storage, credentials and server-side authorization.

A worked example

Take a product that lets customers ask an agent to refactor a repository. A user submits a task, and the server creates a session, issues ID s_4821 bound to the user's tenant, and provisions a sandbox with the repository. The agent runs for six minutes and each turn is appended to the log before the next begins. The user closes the browser. After the idle timeout, the sandbox is released and the hot state expires, while the log and workspace remain under the retention rule.

Two days later the user returns. The application calls resume with s_4821, the history is replayed into a fresh worker, the files are restored, and any external action with an uncertain outcome is reconciled before the agent continues from the last confirmed tool result. If the retention window had passed, resume would fail, and the product would start a new session from a separately retained, policy-permitted summary if one exists, or ask the user to provide the task context again. Each step in that story is a decision to make explicitly, and an integration that has made them can be tested.

Perspective

We built HarnessRouter on the view that the agent harness is infrastructure, in the same way that the model provider is infrastructure. Sessions are where that view meets practice. If every harness defines its own session format, lifecycle and file layout, a product that wants to use two of them ends up maintaining two integrations, and switching a harness becomes a migration project.

The Unified Harness Protocol was started to remove that cost. With one interface for sessions, files, plugins, environments and benchmarking, a team can choose the harness, model and modules per task for quality, latency or cost, and run them in an isolated sandbox. Our aim is that managing sessions across 30+ harnesses looks the same to your code as managing one.

The open-source edition exists so that teams can inspect and self-host this layer, while the cloud platform covers the serverless runtime lifecycle for those who would rather not operate it.

Getting started with HarnessRouter

Teams that want session management without building a lifecycle adapter per harness can start on the Free plan at $0 per month. The Developer plan is $20 per month, Production is $200 per month and Scale is $1000 per month, with Enterprise available on request; the pricing page also lists the agent work fee and the 5.5% top-up credit processing fee (minimum $0.80). Routing your own API keys carries no fee up to $25,000 a month of Model usage at listed prices; above that volume, a separate routing fee of 5% of that value applies. Your provider bills model usage directly, while Agent work and applicable memory charges still apply. Teams that prefer to run the layer themselves can use the open-source Community Edition.

HarnessRouter

For the integration side, the AI agent API guide and the coding agent API guide show how to run harnesses behind your own product.

FAQ

What does session management do in an AI agent system?

It creates and identifies each running agent instance, stores its history and files, resumes it on request and releases its resources when it ends. It also applies retention and expiry rules, so that stored data and compute do not accumulate without limit.

What is the difference between a session and a trace?

A session is the live and stored state an agent needs to continue its work. A trace is a read-only view over the events of that work, used for debugging, evaluation and audit. When the session log is the system of record, traces are simply another way of reading it.

How long should an agent session be kept?

Release compute within minutes of inactivity and keep stored state for as long as users realistically return, typically days to weeks. Provide an explicit delete operation for privacy requests, and make the retention window visible to users.

Can a session move between models or harnesses?

Yes, when the destination supports the required context, tools, permissions and model configuration, the retained history and files can be restored, and the application reconciles pending external actions. A neutral format and a shared protocol such as UHP help provide a common integration contract; they do not by themselves guarantee native session portability or continuation of arbitrary in-flight work.

Sources

→Next

Manage Agent Sessions Across Harnesses

HarnessRouter provides agent session management behind one API across supported harnesses and compatible models, providers and tools.