---
title: Sync protocol
description: >-
  Version vectors, conflict resolution, and offline-first sync for
  sessions
tags:
  - sessions
  - sync
  - version-vectors
---
This endpoint reconciles changes made to the same session from more than one place — for example an offline client that edited messages while the server moved on. Reach for it when you support offline-first or multi-device editing and need to push accumulated changes, pull what you missed, and let the server detect and resolve any conflicts. It builds on the sessions you create in [Manage sessions](/docs/api/sessions-manage); if a sync goes the wrong way, [Checkpoints](/docs/api/sessions-checkpoints) let you roll back.

  advanced
  15 min
  [Sessions overview](/docs/api/sessions-overview), [Manage sessions](/docs/api/sessions-manage)

## Sync Protocol

---

## Request

`POST /api/v1/sessions/:sessionId/sync`.

- `clientId` (string) —
Client identifier for version vector attribution

- `localVersion` (number) —
The session `version` the client last saw

- `localVector` (VersionVector) —
The client's current version vector

- `localChanges` (SessionChange[]) —
Changes made on the client since the last sync

- `mode` (string) —
Sync strategy: `merge` (default), `force_local`, or `force_remote`

A request missing `clientId`, `localVersion` or `localVector` returns `400`.

### Example Request

**cURL**

```bash
curl -X POST "https://www.ivybiosciences.com/api/v1/sessions/$SESSION_ID/sync" \
  -H "Authorization: Bearer ivy_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "merge",
    "clientId": "web_1709856000000",
    "localVersion": 3,
    "localVector": {"web_1709856000000": 3},
    "localChanges": [
      {
        "id": "msg_003",
        "type": "message",
        "operation": "add",
        "path": "messages",
        "value": {
          "id": "msg_003",
          "role": "user",
          "content": [{"type": "text", "text": "Follow up question"}]
        },
        "timestamp": {"wallTime": 1709856400000, "logical": 0, "clientId": "web_1709856000000"}
      }
    ]
  }'
```

**TypeScript**

```ts
const response = await fetch(`/api/v1/sessions/${sessionId}/sync`, {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    mode: "merge",
    clientId: "web_1709856000000",
    localVersion,
    localVector,
    localChanges: pendingChanges,
  }),
})

const { status, newVersion, newVector, conflicts, fullState } = await response.json()
```

---

## Response

Every successful call returns `200` with a `SyncResponse`:

| Field | Meaning |
|-------|---------|
| `status` | `success` or `conflict` |
| `newVersion` | The session version after the sync |
| `newVector` | The server's version vector after the sync |
| `remoteChanges` | Changes for the client to apply (currently always `[]`) |
| `conflicts` | Present when `status` is `conflict` |
| `fullState` | The server's full `SessionState` when the client should replace its copy |

**200 OK (Applied)**

```json
{
  "status": "success",
  "newVersion": 4,
  "newVector": { "web_1709856000000": 4, "api_1709856100000": 2 },
  "remoteChanges": []
}
```

**200 OK (Conflict)**

```json
{
  "status": "conflict",
  "newVersion": 5,
  "newVector": { "web_1709856000000": 3, "api_1709856100000": 3 },
  "remoteChanges": [],
  "conflicts": [
    {
      "id": "c0a8...",
      "path": "messages.msg_002",
      "localValue": { "...": "..." },
      "remoteValue": { "...": "..." }
    }
  ]
}
```

**404 Not Found**

```json
{
  "success": false,
  "code": "NOT_FOUND",
  "message": "Session not found"
}
```

---

## Version Vectors

Each session carries a version vector: a map from `clientId` to the latest version that client wrote. Comparing two vectors shows whether one side has changes the other has not seen.

```ts
type VersionVector = Record<string, number>

interface HybridTimestamp {
  wallTime: number   // Milliseconds since epoch
  logical: number    // Counter for same-millisecond ordering
  clientId: string   // Client that produced the timestamp
}
```

### Comparison

`compareVectors` returns the relationship between two vectors, and the route branches on it:

```ts
import { compareVectors } from "@pleach/core/sync"

const result = compareVectors(localVector, serverVector)
// Returns: "equal" | "a_dominates" | "b_dominates" | "concurrent"
```

| Result | Meaning | What the route does |
|--------|---------|---------------------|
| `equal` | Neither side has unseen changes | Returns `success` with no changes |
| `a_dominates` | The client is ahead | Applies `localChanges` |
| `b_dominates` | The server is ahead | Returns `fullState` for the client to adopt |
| `concurrent` | Both sides have unseen changes | Checks for conflicts, then applies last-writer-wins |

### Available Sync Functions

```ts
import {
  compareVectors,    // Compare two version vectors
  mergeVectors,      // Merge two vectors (max of each component)
  incrementVersion,  // Increment a client's entry
  hasSeen,           // Has vector A seen everything in vector B?
  getMissing,        // Entries B has that A lacks
  emptyVector,       // An empty vector
  createVector,      // An initial vector for a new client
  HybridLogicalClock,
  SyncCoordinator,   // Client-side sync loop with an outbox
} from "@pleach/core/sync"
```

---

## SessionChange

Changes are the units of sync. Each change targets one entity type with one operation.

```ts
interface SessionChange {
  id?: string
  type: "message" | "tool_call" | "job" | "artifact" | "config"
  operation: "add" | "update" | "delete"
  path: string
  value?: unknown
  timestamp: HybridTimestamp
}
```

---

## Conflict Resolution

Conflict detection covers `message` changes with `operation: "update"` only, and runs when the vectors are `concurrent`.

- If an updated message differs between client and server, the route returns `status: "conflict"` with the conflicting paths and applies nothing. Resolve on the client and sync again.
- Otherwise the route applies last-writer-wins on time: if the client's first change is newer than the session's `updatedAt`, the client's changes are applied and the vectors merged; if not, the server wins and the response carries `fullState`.

### Sync Modes

| Mode | Behavior |
|------|----------|
| `merge` | Default. Compare vectors and act as described above |
| `force_local` | Apply the client's changes over the server state |
| `force_remote` | Discard the client's changes and return the server state |

---

## Offline Workflow

1. The client works offline, recording changes with local timestamps.
2. On reconnect, it calls `POST /sync` with `localVector` and `localChanges`.
3. The server compares vectors to find concurrent edits.
4. A conflicting message edit comes back as `status: "conflict"`; otherwise the newer side wins.
5. The client adopts `newVector`, and `fullState` when it is present.

## Read next

- [Manage sessions](/docs/api/sessions-manage) — session management
- [Message execution](/docs/api/sessions-execute) — SSE streaming
- [Checkpoints](/docs/api/sessions-checkpoints) — rollback if sync goes wrong
