> ## Documentation Index
> Fetch the complete documentation index at: https://docs.restate.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions

> Keep conversation history between runs in a Virtual Object, and read it from shared handlers.

A run starts without history unless you pass one. To continue a conversation across requests, run the agent in a [Virtual Object](https://docs.restate.dev/foundations/services.md#virtual-object) and store the conversation under the object's key. To decide whether an agent needs a conversation, see [Choose a service or a Virtual Object](https://docs.restate.dev/harness/agents.md#choose-a-service-or-a-virtual-object).
To keep a long conversation within the model's context window, see [Context and compaction](https://docs.restate.dev/harness/compaction.md).

## Conversation history

Pass a `Conversation` to `run`. The run loads the conversation from the object's state when it starts, and saves its new messages while it runs and when it ends:

```typescript {"CODE_LOAD::harness/src/sessions.ts#conversation"}  theme={null}
export const chatSession = restate.object({
  name: "ChatSession",
  handlers: {
    *ask(message: string) {
      const result = yield* assistant.run(message, {conversation: new Conversation()});
      if (result.status !== "completed") return result.output ?? result.reason;
      return result.output;
    },
    *history({from, limit}: {from?: number; limit?: number}) {
      return yield* new Conversation().page(from, limit);
    },
  },
  options: {
    // Fetch the conversation chunks when they are read
    state: {preload: ["conversation/meta", "conversation/summary"]},
    handlers: {history: {shared: true}},
  },
});
```

* Each object key has its own conversation, so `ChatSession/bob` and `ChatSession/alice` are separate.
* Restate runs one exclusive handler per key at a time, so the runs of a session never interleave.
* A shared handler such as `history` can read the turn that is running. See [Saving progress](#saving-progress).
* Read the history from a shared handler with `page(from, limit)`, which returns up to `limit` messages (default 100, at most 1000) and `next`, the offset of the following page. For a `from` that isn't a nonnegative integer, or a `limit` that isn't an integer from 1 to 1000, `page` throws a `TypeError`, which Restate retries, so reject invalid values from clients with a `TerminalError` before you call `page`. Call `history` with `{}` for the first page, then pass `next` as `from` in subsequent requests until the page is empty.
* `state.preload` keeps Restate from sending the whole conversation to each invocation. See [Lazy state](#lazy-state).

## Saving progress

A run saves to its conversation at these points:

* **After each model call that requests tool calls.** The run saves the calls before they run, together with the results of the previous calls. While the tools run, the saved history ends with calls that have no results yet.
* **After each accepted steering message.** A message that arrives while tool calls run is saved with the next save, after the results of those calls.
* **When the run ends**, with the final answer. A stopped or interrupted run saves its messages too.

Tool results are saved with the next save, so `page` returns the history as of the last save. To show tool results as they happen, use [progress events](https://docs.restate.dev/harness/progress-and-streaming.md#progress-events).
Error notes and answers that `afterRun` rejects are never saved.

### Failed runs

When a terminal error fails the run, including a cancellation of the invocation, the run saves what it recorded before it rethrows the error:

* Each unfinished tool call gets a `cancelled` result with the reason.
* A note follows the turn and gives the next run's model the reason:

  ```json theme={null}
  {"source": "agent-runtime", "type": "run-failed", "message": "The model is unavailable"}
  ```

  For a cancelled invocation, the type is `run-cancelled`.

The run saves no note when:

* **The error is retryable.** Restate retries the invocation, and the run continues from its journal.
* **The run ends before `beforeRun` accepts its input**, for example because `beforeRun` throws `AgentTerminalError`, or because the invocation is cancelled while `beforeRun` runs. The run saves nothing, not even its input.
* **The run fails with `ConversationConflictError`.** Another run changed the conversation, so another save would fail too.

The run saves its input with its first save. If a client sends the same request again after a failure, the conversation gets a new turn after the failed one. To retry a request without adding a turn, send it with an idempotency key. See [Long runs](https://docs.restate.dev/harness/clients.md#long-runs).

A [killed](https://docs.restate.dev/services/invocation/managing-invocations.md#kill) invocation runs no more code, so tool calls that it saved can stay without results. The next run gives each of them a `cancelled` result, which says that the call was interrupted and may have taken effect. Cancel instead of killing when you can: a cancelled run closes its calls itself, with the reason.

## Storage layout

`Conversation` stores the messages in the object's state in chunks of 8, each under its own key, next to a metadata entry and, after compaction, the summary. With the default keys, a conversation of 20 messages is stored like this:

| Key | Value |
| - | - |
| `conversation/meta` | `{count: 20}` |
| `conversation/summary` | `{through, text}`, after compaction |
| `conversation/0` | Messages 0 to 7 |
| `conversation/1` | Messages 8 to 15 |
| `conversation/2` | Messages 16 to 19 |

* A run writes only the chunk that it extends, the new chunks, and the metadata, so the size of each write depends on the new messages, not on the length of the conversation.
* `count` is the number of stored messages and serves as the conversation's version. Before each save, a run checks that `count` hasn't changed since it loaded the conversation or saved last. If another run saved in the meantime, the run throws `ConversationConflictError`, a `TerminalError`.
* Within one invocation, `Conversation` reads each state key at most once and keeps the values that it read and wrote, so the saves of a run don't read the chunks again. A shared handler that calls `page` twice in one invocation receives the values from its first read, so call it once per invocation.
* [Compaction](https://docs.restate.dev/harness/compaction.md#compaction-in-conversations) writes the summary's `text` to `conversation/summary`, together with `through`, the number of messages that the summary replaces. A run then receives the summary instead of the messages before `through`, and reads only the chunks that hold messages from `through` on. A save writes the summary only when the run has a new summary to store. The messages stay in state, so `page` still returns every message.
* `Conversation` reads with shared state and writes with exclusive state. A shared handler can read the conversation while a run is in progress, but only an exclusive handler can save to it.

### Several conversations

To keep several conversations in one object, give each `Conversation` its own `stateKey`, for example `new Conversation({stateKey: "conversation/flights"})`. The chunk keys then start with `conversation/flights/`, and the metadata and summary keys are `conversation/flights/meta` and `conversation/flights/summary`. Preload the metadata and summary keys of each conversation. Set `metaKey` only to match a layout that already exists in state. It doesn't change the summary key.

Runs that save to the same conversation must run one after the other. To run agents in parallel or race them in one handler, see [Agents in workflows](https://docs.restate.dev/harness/workflows.md#conversations).

## Lazy state

By default, Restate sends all of an object's state, up to the eager state size limit, to each invocation when it starts, including invocations of shared handlers such as `history` or `steer`. Compaction doesn't remove messages from the state, so every invocation of the session would receive the whole conversation, although a run reads only the chunks after the last summary.

In each object that uses `Conversation`, preload only the conversation's metadata and summary keys in the object's `options`. Each invocation then fetches a chunk when it reads it:

```typescript {"CODE_LOAD::harness/src/sessions.ts#lazy_state"}  theme={null}
export const aiSession = restate.object({
  name: "AiSession",
  handlers: {doTurn, history, steer, interrupt},
  options: {
    // Fetch the conversation chunks when they are read
    state: {preload: ["conversation/meta", "conversation/summary", "active"]},
    handlers: {history: {shared: true}, steer: {shared: true}, interrupt: {shared: true}},
  },
});
```

* Each load, save, and `page` call reads `conversation/meta` first, and each load also reads `conversation/summary`, so preload both.
* Add other small keys that the handlers read on most invocations, such as `active`, which the `steer` and `interrupt` handlers read on the [steering page](https://docs.restate.dev/harness/steering.md).
* With a list of keys to preload, reads of several keys in one handler can return values from different moments. A shared handler that reads related keys must read them in an order that keeps them consistent, or store them in one key. The [AG-UI example](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/18_ag_ui.ts) does both.
* Each chunk read is a round trip to Restate.
* On AWS Lambda and other platforms without bidirectional streaming, each read of a key that isn't preloaded suspends the invocation, which replays when Restate sends the requested state.

A list of keys to preload requires Restate 1.8 or later. You can also set `state` per handler in `options.handlers`. `state: {preload: false}` preloads no keys. See [State](https://docs.restate.dev/services/configuration.md#state) in the service configuration.

## Manual storage

To control how and where the history is stored, pass `messages` to `run` and store `result.messages` yourself:

```typescript {"CODE_LOAD::harness/src/sessions.ts#messages"}  theme={null}
export const manualChat = restate.object({
  name: "ManualChat",
  handlers: {
    *ask(message: string) {
      const messages = (yield* restate.state().get<Message[]>("messages")) ?? [];
      try {
        const result = yield* assistant.run(message, {messages});
        restate.state().set("messages", result.messages);
        if (result.status !== "completed") return result.output ?? result.reason;
        return result.output;
      } catch (error) {
        // Keep the failed turn, with a note on why it failed. Restate retries other errors.
        const failed = messagesOf(error);
        if (failed && error instanceof TerminalError) restate.state().set("messages", failed);
        throw error;
      }
    },
  },
});
```

A run that throws returns no result. `messagesOf(error)` returns its history up to the failure, with the [note](#failed-runs) on why it failed. Save it only for a `TerminalError`, because Restate retries other errors.

This approach doesn't chunk the history, save progress during the run, or store summaries: each run loads and writes the whole history as one state value. [Tool result previews, compaction, and `contextWindow`](https://docs.restate.dev/harness/compaction) still apply, because they're agent options, but each run whose request exceeds `maxTokens` summarizes the history again.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.