# How the AgentConnection Client Handles Session Replay in PrimeIntellect-ai/prime-agent

> Discover how the AgentConnection client in PrimeIntellect-ai/prime-agent restores session history. Learn about session replay payloads and event re-emission for accurate state recreation.

- Repository: [Prime Intellect/prime-agent](https://github.com/PrimeIntellect-ai/prime-agent)
- Tags: internals
- Published: 2026-09-06

---

**The `DaemonAgentConnection` client restores session history by receiving a `DaemonSessionSnapshot` containing a replay payload, then re-emitting stored `AgentConnectionEvent` objects through its internal event emitter to recreate the exact live session state.**

The PrimeIntellect-ai/prime-agent codebase implements robust **session replay** capabilities that allow UI components and extensions to reconstruct agent conversation history after reconnections, session switches, or daemon restarts. When an interactive client attaches to a running daemon, the `AgentConnection` client automatically restores buffered events to present a seamless, consistent view of the agent's state.

## The Session Replay Architecture

### Snapshot Acquisition and Structure

When a client first attaches to the daemon, the system transmits a `DaemonSessionSnapshot` containing the current `AgentConnectionState` alongside a `replay` field of type `DaemonReplayInfo`. This snapshot serves as the authoritative foundation for session restoration, capturing not just the current state but the historical event sequence needed to reconstruct the session timeline.

### Mapping Daemon DTOs to Public Types

The transformation logic resides in `mapDaemonSessionSnapshot`, located in [`packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts). This function performs the critical conversion from the daemon's internal DTO to the public `AgentConnectionSnapshot` type, explicitly preserving replay information by copying the `DaemonReplayInfo` into the snapshot's `replay` property.

### Event Replay Mechanism

The `applyReplacementSnapshot` method orchestrates the actual restoration. After storing the mapped snapshot as `latestSnapshot`, the method checks for the presence of a `replay` object. If found, it iterates over the list of buffered events using the `lastEventCursor` to maintain proper sequencing, dispatching each `AgentConnectionEvent` to registered listeners via the `connection.subscribe` API. This process transparently restores messages, tool calls, and side-questions so that UI components cannot distinguish between replayed history and live events.

## Core Implementation Files

The session replay flow spans three critical files in the PrimeIntellect-ai/prime-agent repository:

- **[`packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts)** – Implements the `DaemonAgentConnection` class, handles snapshot reception, and executes the replay logic through `applyReplacementSnapshot`.
- **[`packages/coding-agent/src/modes/agent-connection/types.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/agent-connection/types.ts)** – Defines the `AgentConnectionSnapshot` and `AgentConnectionReplayInfo` interfaces that structure the replay data.
- **[`packages/coding-agent/src/modes/agent-connection/snapshot.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/agent-connection/snapshot.ts)** – Provides snapshot construction utilities used when the daemon creates the initial payload to send.

## Practical Usage Examples

When attaching to an active daemon session, the client automatically handles replay without manual intervention:

```typescript
// Attach to an active daemon session and let the client handle replay automatically.
const conn = await DaemonAgentConnection.attach(
  daemonClient,
  activeSessionId,
  { recoverDaemon: async () => /* … */ }
);

// After attachment, the connection already contains the replayed history.
await conn.getInitialSnapshot();            // snapshot includes replayed events
await conn.waitForIdle();                  // ensures all replayed events are processed

// Subscribe to events – you will receive both replayed and live events.
const unsub = conn.subscribe((ev: AgentConnectionEvent) => {
  console.log("event:", ev.type, ev);
});

```

Session switching also leverages the same replay infrastructure to restore history:

```typescript
// Switching to a different session – the client fetches a new snapshot that may carry replay data.
await conn.switchSession("/tmp/other-session.jsonl");

// The connection internally calls `applyReplacementSnapshot`, which:
//   1️⃣ maps the daemon snapshot → AgentConnectionSnapshot
//   2️⃣ stores it as `latestSnapshot`
//   3️⃣ re‑emits any buffered events from `snapshot.replay`

```

## Summary

- **Snapshot reception**: The client receives `DaemonSessionSnapshot` objects containing both current state and historical replay data when connecting or switching sessions.
- **Type conversion**: `mapDaemonSessionSnapshot` in [`daemon-agent-connection.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-agent-connection.ts) bridges the daemon's internal format to the public API while preserving replay information.
- **Transparent replay**: The `applyReplacementSnapshot` method re-emits buffered events through the standard subscription interface, making historical events indistinguishable from live ones.
- **Consistent API**: Consumer code uses `getState`, `getMessages`, and `subscribe` identically regardless of whether events are replayed or real-time.

## Frequently Asked Questions

### What triggers a session replay in AgentConnection?

A session replay triggers when `DaemonAgentConnection` receives a snapshot containing a `replay` object, which occurs during initial attachment to a daemon, session switching via `switchSession()`, or daemon recovery scenarios. The `applyReplacementSnapshot` method detects the presence of replay data and initiates the event re-emission process.

### How does the client distinguish between replayed and live events?

From the caller's perspective, the client makes no distinction. Both replayed historical events and new live events flow through the same `connection.subscribe` channel with identical `AgentConnectionEvent` types. The transparency ensures UI components and extensions process session history uniformly without conditional logic for replayed content.

### Where is the replay data structured in the PrimeIntellect-ai/prime-agent codebase?

The data structures defining replay payloads reside in [`packages/coding-agent/src/modes/agent-connection/types.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/agent-connection/types.ts), which exports `AgentConnectionSnapshot` and `AgentConnectionReplayInfo`. The conversion logic from daemon-specific formats to these public types lives in [`packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts).

### Can developers control which events are replayed?

Developers cannot selectively filter replayed events through the public API. The replay content is determined by the daemon's `DaemonReplayInfo` payload, which includes a complete `AgentConnectionEvent` list and `lastEventCursor`. Consumers receive the full historical buffer that the daemon deems necessary for session continuity.