# Kovlet: full reference > Kovlet syncs typed tables and files ("Data Spaces") live between many small apps: web, mobile, desktop and server. Apps declare their tables in code and hold no API keys. Users sign in and consent on first run. Access is Users × Machines × Applications: an app sees a space only if the signed-in user and the app both have a role on it. SDKs: `@kovlet/client` (any JS runtime, optionally over your own store), `@kovlet/react` (hooks), `@kovlet/react-native` (Expo / React Native), `@kovlet/vue`, `@kovlet/svelte`, the `kovlet` Rust crate with `tauri-plugin-kovlet`, a Swift package and an Android library, all over one documented protocol that any language can speak with plain REST + WebSocket. This is the complete Kovlet reference for AI coding agents, followed by complete, runnable examples (Node script, React app, file sync, schema proposals, plain REST, WebSocket) and the list of guides. Follow it exactly: names, option keys and types below are the real API. Table and column names in the examples (`expenses`, `vendor`, …) are illustrations. In real code, declare exactly the tables and columns the live space has (see below), because a misspelled column is not an error: it adds a new optional column. The short index of the Kovlet docs is [/llms.txt](https://kovlet.com/llms.txt). Every guide is also Markdown with a `.md` suffix or `Accept: text/markdown`; the full list is under "Guides" at the end of this file. The hosted service at kovlet.com is covered by its [Terms](https://kovlet.com/legal/terms), [Privacy Policy](https://kovlet.com/legal/privacy) and [Data Processing Agreement](https://kovlet.com/legal/dpa). ## Start here: pick your platform Each quickstart covers install → sign in → pick or create a space → sync a table → files, with copy-pasteable code. Fetch the `.md` URL for Markdown. | Project (what you see in it) | SDK | Quickstart | | --- | --- | --- | | Web app, React (`package.json` with react, vue, svelte, next, vite, …) | `@kovlet/client` + `@kovlet/react` | https://kovlet.com/docs/quickstart-web.md | | Web app, Vue or Svelte (`package.json` with vue / svelte) | `@kovlet/client` + `@kovlet/vue` or `@kovlet/svelte` | the web quickstart, with the "@kovlet/vue" / "@kovlet/svelte" sections below | | Expo / React Native (`app.json`, `package.json` with expo or react-native) | `@kovlet/client` + `@kovlet/react-native` | the "@kovlet/react-native" section below | | Next.js / Nuxt / SvelteKit server rendering | `@kovlet/client/server` (Machine Auth Key, server-only) | https://kovlet.com/docs/ssr.md | | Node, Electron, servers (`package.json`) | `@kovlet/client` (optionally `@kovlet/client/sqlite`) | https://kovlet.com/docs/quickstart-node.md | | Tauri or Rust (`Cargo.toml`, `src-tauri/tauri.conf.json`) | `kovlet` crate + `tauri-plugin-kovlet` | https://kovlet.com/docs/quickstart-tauri.md | | iOS, macOS (`*.xcodeproj`, `Package.swift`) | `Kovlet` Swift package | https://kovlet.com/docs/quickstart-ios.md | | Android (`build.gradle(.kts)` with `com.android`) | `com.kovlet:kovlet-android` | https://kovlet.com/docs/quickstart-android.md | | Any language: Python, Go, Rust, Swift, Kotlin, … | none: HTTPS + WebSocket | https://kovlet.com/docs/quickstart-rest.md | Install the SDK for your platform from its registry: `@kovlet/*` from npm, the `kovlet` and `tauri-plugin-kovlet` crates from crates.io, the `Kovlet` Swift package with Swift Package Manager, `com.kovlet:kovlet-android` from Maven Central. A language without an SDK uses the REST + WebSocket quickstart: device-code sign-in, `GET`/`POST /v1/spaces`, then `hello` / `mutate` / `ack` on `wss://api.kovlet.com/v1/sync`. It is one dependency-free script, and the rules a hand-written client must follow are in "Building a client without the SDK" below. Don't guess package names, versions or URLs that aren't listed here. A multi-device app (for example a desktop app and its mobile companion) connects every instance to the same Data Space: each device signs in once as the same user, finds the space by name (`find_or_create` in the native SDKs, `GET /v1/spaces` then `POST /v1/spaces` over REST), and every edit syncs to the others live. ## Before you write code: discover the live schema If the Kovlet MCP server is connected (tools `list_spaces`, `inspect_space_schema`, …): 1. `list_spaces`: find the Data Space and your role on it. 2. `inspect_space_schema` with `{"space": ""}`: the exact table names, column names, types and optionality, file paths, and pending proposals. Reuse these names verbatim. Never invent a column that "probably" exists. 3. `generate_app_connection` with `{"space": "...", "app_name": "My App", "target": "client" | "react" | "node"}`: typed `src/kovlet.ts`. Write the returned files into the project. 4. Need a new table or column? Call `propose_schema_addition`, or declare it in `kovlet.ts` as a new table or an `.optional()` column. Destructive changes (required column on an existing table, type change, rename, drop) are never applied by apps. They become proposals an owner approves in the console. 5. `create_space` only when no existing space fits. 6. Several spaces can share a name. Pass the `id` from `list_spaces` (tools also accept a unique slug or name). Without the MCP server, read the schema over REST (`GET /v1/spaces/{space}/tables`, see below) or declare the tables your app needs. New tables and optional columns are created on connect. ## URLs | What | Production | Local dev (`kovletd --dev`) | | --- | --- | --- | | kovletd API + sync (`url`) | `https://api.kovlet.com` | `http://127.0.0.1:8080` | | Console: sign-in, consent, `/activate` (`consoleUrl`) | `https://kovlet.com` | `http://localhost:5173` | | MCP endpoint (Streamable HTTP) | `https://api.kovlet.com/mcp` | `http://127.0.0.1:8080/mcp` | | This file (`/llms-full.txt`); the short index is `/llms.txt` | `https://api.kovlet.com/llms-full.txt` (also `https://kovlet.com/llms-full.txt`) | `http://127.0.0.1:8080/llms-full.txt` | | OpenAPI 3.1 spec of every REST route (also `.yaml`) | `https://api.kovlet.com/openapi.json` (also `https://kovlet.com/openapi.json`) | `http://127.0.0.1:8080/openapi.json` | ## Concepts - **Data Space**: a named container of typed tables plus a file tree. It is the unit of sharing, sync and rollback. IDs look like `0192f3a4-5b6c-7d8e-9f01-23456789abcd`. - **Slot**: the logical name an app uses for a space in code (e.g. `finance`). At consent the user maps the slot to a real space. Set `spaceId` to pin it. - **Roles**: `viewer` (read), `editor` (read, write rows and files, add tables and optional columns), `owner` (sharing, approving destructive schema changes, rollback; console only). An app's effective role is `min(user's role, app's grant)`. Apps cap at `editor`. - **Rows**: every row has a string `id`. The client generates it (UUIDv7) so offline-created rows are stable, or the app passes its own: a row id is any 1-256 bytes of UTF-8 text with no control characters (U+0000-U+001F, U+007F-U+009F), so ids like `table:abc`, `ada@example.com` or `notes/2026/01.md` work as they are. Space, file and mutation ids are 1-128 characters from `A-Z a-z 0-9 - _`. Fields merge per field: concurrent edits to different fields both survive, and for the same field the later write wins. - **Trash**: deleting a row or file soft-deletes it. Owners restore it, or roll back an app's changes, in the console. ## Column types | Builder | Wire `type` | JS value (read) | Write accepts | | --- | --- | --- | --- | | `t.string()` | `string` | `string` | string | | `t.number()` | `number` | `number` | finite number | | `t.boolean()` | `boolean` | `boolean` | boolean | | `t.datetime()` | `datetime` | ISO 8601 `string` | `Date` or RFC 3339 string | | `t.json()` | `json` | any JSON value | any JSON value | | `t.ref("table")` | `ref` (+ `ref_table`) | row id `string` | row id | | `t.fileRef()` | `file_ref` | file id `string` | file id (from `files.upload`) | Append `.optional()` to allow `null` or a missing value. Append `.unique()` to make the server reject a write that gives two live rows the same non-null value (`unique_violation`; values up to 512 bytes; the Trash releases a value), and `.indexed()` to let queries compare and order on the column (ref and unique columns are indexed already). Neither is allowed on `t.json()`. Adding `.unique()` to an existing column needs an owner's approval; `.indexed()` is applied at once. Table and column names match `^[A-Za-z][A-Za-z0-9_]{0,62}$`. A leading `_` is reserved. `id` is implicit, so never declare it. ## @kovlet/client ```sh npm i @kovlet/client ``` ```ts import { createKovletClient, t } from "@kovlet/client"; export const kovlet = createKovletClient({ appName: "Receipt Scanner", // shown on the consent screen and in the console url: "http://127.0.0.1:8080", // kovletd; default https://api.kovlet.com consoleUrl: "http://localhost:5173", // default https://kovlet.com spaces: { finance: { // slot name role: "editor", // "viewer" | "editor"; default "editor" spaceId: "0192f3a4-...", // optional pin; required for headless auth tables: { expenses: { vendor: t.string(), amount: t.number(), spentAt: t.datetime(), category: t.string().optional(), receiptFile: t.fileRef().optional(), }, }, files: true, // the app uses the space's files; default false }, }, }); const finance = kovlet.space("finance"); // typed Space const expenses = finance.table("expenses"); // typed Table ``` ### createKovletClient options | Option | Type | Default | | --- | --- | --- | | `appName` | `string` (required) | — | | `spaces` | `Record` (required); `sync: "query"` syncs only what the app's queries cover | — | | `url` | `string` | `"https://api.kovlet.com"` | | `consoleUrl` | `string` | `"https://kovlet.com"` | | `auth` | see Sign-in | popup in browsers, `device` in Node | | `storage` | `"indexeddb" \| "memory" \| KovletStorage` | IndexedDB in browsers, memory elsewhere | | `storageName` | `string` | `"kovlet"` | | `autoConnect` | `boolean` | `true`: sign in and sync immediately | | `protocol` | `1 \| 2` | `2`, falling back to `1` against an older server | | `onError` | `(err: KovletError) => void` | — | | `fetch`, `WebSocket` | custom implementations | globals | ### Tables All reads are synchronous over the local replica. Writes apply locally at once, queue offline, and sync. ```ts expenses.all(); // Row[] (trashed rows excluded) expenses.get(id); // Row | undefined expenses.query({ where: (e) => e.amount > 3, orderBy: "spentAt", desc: true, limit: 50 }); const unsubscribe = expenses.subscribe((rows) => render(rows)); // called on every change, local or remote const row = expenses.insert({ vendor: "Cafe", amount: 4.5, spentAt: new Date() }); // returns the row with its new id expenses.insert({ id: "my-id", vendor: "X", amount: 1, spentAt: new Date() }); // explicit id (any 1-256 bytes of UTF-8, no control characters) expenses.update(row.id, { amount: 4.8 }); // patch: only the given fields expenses.delete(row.id); // to the Trash expenses.restore(row.id); // out of the Trash ``` Writes that must succeed together, across tables, go in one atomic batch: all apply or none does. ```ts await kovlet.space("main").transact((tx) => { const team = tx.table("teams").insert({ name: "Core" }); tx.table("members").insert({ team: team.id, user: userId }); }); ``` - The callback is synchronous and holds at most 500 writes. The writes show up locally at once and queue offline as one unit. - If the server rejects any write (e.g. `unique_violation`), the whole batch rolls back locally, `onError` gets a `TransactionRejectedError` (`batchId`, `index`, `code`, `details`), and the promise rejects. Queued writes to rows the batch created are dropped too (`dependency_rejected`). - Fields still merge last-writer-wins, so a transaction is not serializable. - Needs sync protocol 2, which the client speaks by default. Against a server without it the batch rolls back with `unsupported_protocol`. Servers can always use `POST /v1/spaces/{space}/transact`. ### Queries (nested, like InstantDB's InstaQL) A query is a tree keyed by table. Nested keys follow `ref` columns forward (`author`, declared `t.ref("users")`: the linked row or `null`) and back (`comments` under `posts`, through `comments.post`: a list). `$` takes `where`, `order` (one field; nulls last), `limit`, `after`/`before` (cursors from `pageInfo`), `fields` and `via`. Results are fully typed. ```ts const q = { posts: { $: { where: { published: true, "author.email": { $ilike: "%@acme.com" } }, order: { createdAt: "desc" }, limit: 20 }, author: {}, comments: { $: { order: { createdAt: "asc" } }, author: {} }, }, } as const; const { data, pageInfo } = await blog.query(q); // one shot: from the full replica, or POST /v1/spaces/{space}/query data.posts[0]?.author?.name; // typed: string | undefined const live = blog.liveQuery(q); // { subscribe(cb), get() → { data, pageInfo, isLoading, error } } const next = await blog.query({ posts: { $: { ...q.posts.$, after: pageInfo.posts?.endCursor } } }); ``` - `where` operators: equality, `$ne`, `$in`, `$gt`, `$gte`, `$lt`, `$lte`, `$like` / `$ilike` (`%` wildcards), `$isNull`, `and`, `or`, `$not`; keys may be link paths like `"author.team.name"` (3 hops). A null or missing value never compares (`$ne` matches it). - Only top-level keys take `limit` and cursors. A query follows at most 3 links and reads at most 8 tables. - On a table past 10,000 rows, comparisons, `$like` and `order` need an indexed column (`.indexed()`, `.unique()` or any `ref`), else the query fails with `index_required`. - End users' profiles: a `t.ref("_users")` column nests like any ref (`{ todos: { owner: {} } }` → `owner` is `{ id, email, is_guest, created_at }` or `null`), `"owner.email"` works in `where`, and `_users` can be a top-level key. For end users the `_users` view rule decides whose profile arrives (default: only their own; others are `null`), live too. `_users` columns have no index, so past 10,000 end users only equality filters work on them. - Default sync keeps a full offline replica, so queries answer locally. With `sync: "query"` on a slot, the client holds only what its live queries, `useTable` tables and files subscribe to: use it for large spaces. - Every required column must be present on `insert`. A wrong type or an unknown column throws `KovletValidationError` synchronously. - Rows include columns other apps added, even when your types don't list them. - Type a row: `type Expense = ReturnType[number];` ### Files ```ts const files = finance.files; // needs files: true const entry = await files.upload("receipts/cafe.jpg", blob, { mimeType: "image/jpeg" }); // Blob | ArrayBuffer | typed array | string; mimeType optional // entry: FileEntry { id, path, sha256, sizeBytes, mimeType, version, pending } files.list("receipts/"); // live FileEntry[] under a prefix, sorted by path files.get("receipts/cafe.jpg"); // by id or path: FileEntry | undefined files.subscribe((all) => {}); // returns an unsubscribe function const bytes = await files.download("receipts/cafe.jpg"); // Blob, sha256-verified, cached const src = await files.url("receipts/cafe.jpg"); // short-lived presigned URL (for ) files.move("receipts/cafe.jpg", "archive/cafe.jpg"); files.moveFolder("receipts", "archive/2026"); files.delete("archive/cafe.jpg"); // to the Trash; files.restore(id) undoes it // move/moveFolder/delete/restore/download/url accept an id or a path ``` Store a file in a row with a `t.fileRef()` column holding `entry.id`. File ids survive moves, and paths do not. Paths are relative, `/`-separated, at most 1024 bytes, and have no empty, `.` or `..` segments. Uploading to an existing path writes a new version. ### Rooms: presence and topics Who's online, live cursors, typing indicators and fire-and-forget events. Rooms are ephemeral: nothing is stored, and a peer's presence clears when its session ends (within a second of closing a tab, 20 s on a dropped network). Any reader of the space (viewers too) can join any room in it. ```ts const room = finance.room<{ name: string; cursor?: { x: number; y: number }; typing?: boolean }>("doc:42", { presence: { name: "Ada" }, // initial presence: put display names here (peers get no profile data) }); room.setPresence({ cursor: { x, y } }); // shallow merge; sent as the full object, at most once per 50 ms room.presence(); // { status, self?, peers: Peer[] }; Peer { peerId, userId?, machineId?, appId?, data } room.onPresence(({ self, peers }) => {}); // returns an unsubscribe function room.publish("emoji", { emoji: "🎉" }); // to the other peers; never echoed back; at most once room.onTopic("emoji", (data, peer) => {}); // returns an unsubscribe function room.status; // "joining" | "joined" | "unsupported" | "error" room.leave(); // space.room(id) returns one shared handle: leave once per call ``` Room ids are 1-256 bytes and don't start with `_` (e.g. `doc:${id}`). Limits (server defaults): 10 rooms per session, 50 peers per room, 4 KiB of presence or topic data. `peerId` changes on reconnect: use `userId` or your own presence field for a stable identity. The client rejoins after reconnects. On a server without rooms, `status` is `"unsupported"` and every call does nothing. ### Bring your own store (headless mode) Apps that already keep their data (SQLite in Node, Electron or Tauri, a React Native store, Postgres on a server) pass `store`. The client then keeps no copy of the rows: it merges every change against its own clocks and hands your store only the fields that won, in the same transaction as its bookkeeping. ```ts import { DatabaseSync } from "node:sqlite"; // or better-sqlite3 import { createKovletClient, t } from "@kovlet/client"; import { SqliteStore } from "@kovlet/client/sqlite"; const db = new DatabaseSync("app.db"); const kovlet = createKovletClient({ appName: "Importer", spaces: { main: { spaceId: process.env.SPACE_ID, tables: { tasks: { title: t.string(), done: t.boolean() } } } }, store: new SqliteStore(db, { apply: (db, c) => { // c.kind: "upsert" (c.fields is a patch; c.deleted is the trash flag), "delete" / "restore" // (move to or out of your trash), "purge" (drop the row), "file", "schema" }, }), }); await kovlet.space("main").table("tasks").insert({ title: "From Node", done: false }); // a promise in this mode ``` - In headless mode `kovlet.space(slot)` only writes. Read from your own store. Files: metadata reaches `apply` as `file` changes; `space.files.download(id)` and `files.url(id)` fetch bytes. Uploads need the replica mode (no `store`) or the REST upload. - Node sign-in (device code) needs no `spaceId`: after approval each unpinned slot picks the space named after the app, else the only one shared, else creates one (`GET`/`POST /v1/spaces`). Choose yourself with `auth: { type: "device", pickSpace: (ctx) => ({ spaceId }) | ({ create: { name } }) | ({ request: true }) }`; `ctx.spaces` lists the usable ones. Several candidates and no `pickSpace` → `space_choice_required`. Returning a space from `ctx.all` that still waits for an admin (role `""`) throws `SpaceNotUsableError` (`space_not_usable`; `reason`: `app_not_approved`, `machine_not_approved` or `no_role`) before the slot is mapped. After each token refresh the SDK re-reads `GET /v1/spaces` in the background (never delaying the refresh; a failed or slow read changes nothing): a slot whose space is no longer listed (grant removed) is dropped and stops syncing, `kovlet.on("revoked", (e) => …)` gets `e.slots: [{ slot, spaceId, role, pinned }]`, and the next `connect()` picks a space for it again (pinned slots keep their mapping and are only signalled). `machine-key` sign-in still needs `spaceId` pinned. - Record mode: write your own rows in your own transaction and call `table.record(id, fields)` inside it. - Any other store: `store: { dataStore, syncStore }`, where `dataStore` has one method, `apply(batch)`, and `syncStore` is `MemorySyncStore`, `IndexedDBSyncStore` or `SqliteStore`. ### Status and lifecycle ```ts kovlet.status; // { state, pending, spaces } // state: "signed-out" | "authorizing" | "idle" | "connecting" | "syncing" | "live" | "offline" | "error" kovlet.onStatus((s) => {}); // returns an unsubscribe function kovlet.onError((e) => {}); // rejected writes, schema approvals, sync failures await kovlet.whenSynced(); // resolves when live with nothing pending (this includes waiting through sign-in); rejects after 30 s: whenSynced(ms) to change await kovlet.connect(); // sign in if needed, then sync. Safe to call while autoConnect is already signing in (it joins). Call it from a click when autoConnect: false. kovlet.disconnect(); // close the socket (writes keep queuing locally). Scripts call it at the end so Node can exit. await kovlet.signOut(); ``` ### Sign-in (`auth`) | `auth` | Use for | | --- | --- | | `{ type: "browser", mode?: "auto" \| "popup" \| "redirect", redirectUri? }` | Browsers (default). Opens the consent popup and falls back to a redirect if the popup is blocked. | | `{ type: "device", onCode?: (info) => void, machineName?, deviceKey?, spaceName? }` | CLIs and Node (default there). Prints an `/activate` URL and code, then waits. Needs `spaceId` on every slot. Sends a device key, so the session acts as the approving user on this device and refreshes itself; `deviceKey: false` enrolls a keyless headless machine (90-day token, no refresh). `spaceName` is the suggested name of the new space a first-time user gets at approval (default: `appName`). | | `{ type: "machine-key", machineKey, clientId }` | Unattended servers. The key (`kvm_...`) is created in the console under Machines. Needs `spaceId`. | | `{ type: "pkce", redirectUri, authorize: (consentUrl) => Promise, onApproveLink? }` | Custom consent UI (Electron, webviews, tests). | In Node the default storage is memory, so a script asks for device approval on every run. Pass a persistent `KovletStorage` to keep the session. Node 22+ is required (global `fetch` and `WebSocket`). Use ESM (`"type": "module"`) for top-level await. The default device message goes to stdout as `[kovlet] To connect , open and confirm code `. Browsers block popups not triggered by a click. Use `autoConnect: false` and call `kovlet.connect()` from a button. With `autoConnect: false` nothing reconnects on its own, so resume a stored session on load: `kovlet.ready.then(() => kovlet.session && kovlet.connect())` (no popup). Browser sessions are bound to a non-exportable WebCrypto key in IndexedDB, and the SDK signs every request. ### Spaces for apps A signed-in app can see and grow its own set of Data Spaces without the console and without signing in again: ```ts const { spaces, requestable, can_create } = await kovlet.listSpaces(); // spaces: [{ id, name, slug, role: "viewer" | "editor" | "", reason?: "app_not_approved" | "machine_not_approved", ... }] // requestable: how many more of the user's spaces it could ask for (names stay on Kovlet's page) const space = await kovlet.createSpace({ name: "Trips", slug: "trips" }); // owned by the user; this app gets Editor // Optional `slot`: a slot declared in `spaces` (e.g. slot: "main") then syncs the new space. An undeclared name maps nothing. const res = await kovlet.requestSpaces({ asks: [{ role: "editor", slot: "archive", suggestedName: "Archive" }] }); // res.status: "approved" | "denied" | "expired"; res.spaces: [{ space_id, name, role, slot?, created }] ``` `requestSpaces` opens Kovlet's approve page in a popup in browsers (call it from a click); in Node pass `onLink` to show the link (printed by default). The user picks existing spaces or creates new ones and presses Approve; the grants are added to the same session and machine. A stored session that lacks a newly declared slot does this by itself on `connect()` instead of a fresh consent. On a first sign-in, a user with no spaces only presses Approve: Kovlet suggests a new space named after the app. ### Schema evolution from code On connect the SDK sends the declared tables. A new table, or a new `.optional()` column, is added automatically (editor role), and other apps see it live. A destructive difference (new required column on an existing table, type change, tighter nullability) is not applied. The server records a proposal, and the SDK emits `SchemaApprovalRequiredError` (`proposalIds`, `tables`) through `onError` while sync continues. To add a column to an existing table without approval, make it optional. There is no per-write promise: `insert`/`update` return synchronously, and `await kovlet.whenSynced()` waits until every queued write is acknowledged. A write the server rejects (e.g. `schema_violation`) is reported to `onError` as `MutationRejectedError` and dropped from the queue. ### Errors All extend `KovletError` and have a stable `code`, a `message` and a `hint`: the next step that fixes it (e.g. the existing column names and the schema tool for an unknown column, the expected and received type for a mismatch, the activation step for a missing approval). Read `err.hint` and retry once instead of asking the user to debug. Classes: `KovletValidationError` (`table`, `field`, `reason`: `unknown_column` | `type_mismatch` | `required_missing` | `null_not_allowed`, `expected`, `received`, `columns`), `SchemaApprovalRequiredError`, `MutationRejectedError` (subtypes `PathConflictError`, `BlobMissingError`, `QuotaExceededError`, `TransactionRejectedError`; code `unique_violation` with `details.table` and `details.column` when a unique value is taken), `KovletAuthError` (`access_denied`, `consent_cancelled`, `popup_blocked`), `KovletConfigError`, `KovletHttpError` (`status`, `details`; code `server_unreachable` with status 0 when the URL does not answer). Every error code (WebSocket, REST, MCP) with its HTTP status or close code and the fix, and every limit and plan quota, is in the errors and limits reference: https://kovlet.com/docs/errors-and-limits. Plan limits: free workspaces cap new rows, file storage, Data Spaces, headless machines, personal devices and guests. A write past a limit is rejected with code `quota_exceeded` (`QuotaExceededError`: `metric`, `used`, `limit`, `upgradeUrl`); existing data stays readable, editable and deletable. `isQuotaExceeded(err)` matches it from either path (rejected write or HTTP 402). Point the user to `/upgrade`. Usage signals let an app warn before writes fail. The free plan includes 100,000 live rows, and new rows are refused only at 110,000 (a 10% grace buffer); trashed rows don't count. `kovlet.on("quota", (e) => …)` fires when a write crosses 80%, 90% or 100% of a limit (`e`: `metric`, `used`, `limit` (the hard stop), `softLimit`, `threshold`, `slot`). `await kovlet.usage()` returns `{ plan, metrics: [{ metric, used, limit, soft_limit?, state: "ok" | "near" | "over" }], upgradeUrl }`, and `kovlet.lastUsage` holds the latest copy (it arrives on connect). In React, `useUsage()` returns it live. `QuotaExceededError` stays the final hard stop. ## @kovlet/react ```sh npm i @kovlet/client @kovlet/react ``` ```tsx import { KovletProvider, useFiles, useKovlet, useQuery, useSpace, useSyncStatus, useTable, useUsage } from "@kovlet/react"; import { kovlet } from "./kovlet"; // createKovletClient({ ..., autoConnect: false }) export function App() { return ( ); } function Expenses() { const status = useSyncStatus(); // ClientStatus; useSyncStatus("finance") for one slot const finance = useSpace("finance"); // typed Space; re-renders on mapping/schema/file changes const expenses = useTable(finance.table("expenses"), { orderBy: "spentAt", desc: true }); // live typed rows const receipts = useFiles(finance, { prefix: "receipts/" }); // live file entries const { data } = useQuery(finance, { expenses: { $: { where: { amount: { $gt: 100 } } } } }); // live query; nests links too const rows = useUsage()?.metrics.find((m) => m.metric === "rows"); // plan usage; state "near" from 80% if (status.state === "signed-out") return ; return (
    {expenses.map((e) => (
  • finance.table("expenses").update(e.id, { amount: e.amount + 1 })}> {e.vendor}: {e.amount}
  • ))}
); } ``` Presence and topics (see "Rooms" above): ```tsx import { usePresence, usePublishTopic, useRoom, useTopic } from "@kovlet/react"; function Cursors() { const finance = useSpace("finance"); const room = useRoom<{ name: string; cursor?: { x: number; y: number }; typing?: boolean }>(finance, "doc:42", { presence: { name: "Ada" }, }); // joins on mount, leaves on unmount const { self, peers, setPresence } = usePresence(room); // live; setPresence({ typing: true }) for typing indicators const sendEmoji = usePublishTopic(room, "emoji"); useTopic(room, "emoji", (data, peer) => console.log(peer.data.name, data)); return
setPresence({ cursor: { x: e.clientX, y: e.clientY } })}>{peers.length} here
; } ``` `useTable(table, { where?, orderBy?, desc?, limit? })`. `useQuery(space, q)` → `{ data, pageInfo, isLoading, error }` (nested queries, above); `@kovlet/vue` and `@kovlet/svelte` have `useQuery` too. Write through the client directly (`table.insert/update/delete`, `space.files.upload`). Hooks re-render on the same tick. Supports React 18 and 19. ## Native apps: Rust, Tauri, Swift, Kotlin One Rust core (sign-in, sync, merge, outbox, files) with bindings. The app's database stays the source of truth: implement `DataStore::apply` or use the built-in store. The device key lives in the OS keychain, Secure Enclave or Android Keystore, and the session refreshes itself, so the user signs in once. | | Rust / Tauri | Swift | Kotlin | | --- | --- | --- | --- | | Client | `Client::builder("Todos").data_dir(dir).build()?` (Tauri: `tauri_plugin_kovlet::init("Todos")`) | `KovletClient(appName: "Todos")` | `Kovlet.client(context, appName = "Todos")` | | Sign in | `SignIn::device(...)`, PKCE with a loopback redirect | `.webAuthentication(callbackScheme:)`, device flow | `SignIn.customTab(...)`, `SignIn.device { }` | | Space | `spaces().find_or_create("Todos")` | `spaces.findOrCreate(name:)` | `spaces.findOrCreate("Todos")` | | Tables | `open` / `open_builtin` + `Tables::new().table(...)`; `space.write("todos").upsert(id, json!({..}))` | `space.table("todos", as: Todo.self)`: `upsert`, `observe()` | `space.table("todos")`: `upsert`, `observe(): Flow` | | Live queries | `space.subscribe(json!({"todos": {"$": {"where": {..}}}}))?` → `rows()`, `observe(..)`; `open_query` for a partial replica | `space.subscribe([...])` → `results()` `AsyncStream`; `openQuery` | `space.subscribe(json).results(): Flow`; `openQuery` | | Atomic writes | `space.transact([LocalWrite::upsert(..), ..])?.settled().await` | `try space.transact([.upsert(...)]).settled()` | `space.transact(listOf(Write.Upsert(...))).settled()` | | End users | `kovlet.end_users(space, app).sign_in_with_magic_code(..)`; Tauri webview: `end_user_*` commands | `kovlet.endUsers(spaceId:appId:).signIn(email:code:)` | `kovlet.endUsers(spaceId, appId).signInWithMagicCode(..)` | The native SDKs speak sync protocol 2 (one socket per space, many subscriptions), falling back to protocol 1 for a day when a server refuses it. Queries use the same JSON language and matcher as `@kovlet/client`. End users always sync over protocol 2 with query subscriptions, filtered by the space's rules; signing out forgets their synced rows on the device. Details, files and lifecycle: https://kovlet.com/docs/quickstart-tauri.md, https://kovlet.com/docs/quickstart-ios.md, https://kovlet.com/docs/quickstart-android.md. ## @kovlet/react-native Expo (SDK 52+, development builds; not Expo Go) and bare React Native with Expo modules. The `@kovlet/react` hooks, plus SQLite storage (expo-sqlite), the device key in the keychain (expo-secure-store), sign-in in the system browser back through a deep link (expo-web-browser), and background pause / foreground reconnect. ```sh npx expo install @kovlet/client @kovlet/react-native expo-sqlite expo-secure-store expo-web-browser expo-crypto ``` ```tsx // kovlet.ts import { createKovletClient, nativeClient, t } from "@kovlet/react-native"; export const kovlet = createKovletClient({ appName: "Todos", spaces: { main: { role: "editor", tables: { todos: { title: t.string(), done: t.boolean() } }, files: true } }, autoConnect: false, ...nativeClient({ redirectUri: "com.example.todos:/kovlet/callback" }), // storage, deviceKeyStore, auth, WebSocket }); void kovlet.ready.then(() => kovlet.session && kovlet.connect().catch(() => {})); // resume a stored session // App.tsx: KovletProvider (React Native's: lifecycle-aware) + the same hooks as @kovlet/react import { KovletProvider, useSpace, useSyncStatus, useTable } from "@kovlet/react-native"; ``` The redirect scheme must be reverse-DNS (`com.example.todos`, registered as `scheme` in app.json) or an https App Link; `myapp://` is refused. Files: `main.files.upload(path, uint8Array, { mimeType })`. Writes queue in SQLite while offline and survive restarts. ## @kovlet/vue ```sh npm i @kovlet/client @kovlet/vue ``` ```ts import { createKovlet, useFiles, useSpace, useSyncStatus, useTable } from "@kovlet/vue"; app.use(createKovlet(kovlet)); // or provideKovlet(kovlet) in a root setup() // in {#each $expenses as e (e.id)}

{e.vendor}: {e.amount}

{/each} ``` Readable Svelte stores (Svelte 4 and 5); `useFiles(space, { prefix })` too. Outside components pass the client: `useSpace("finance", kovlet)`. ## Server rendering (Next.js, Nuxt, SvelteKit) Live data is client-only: create the client and use the hooks in client components (Next.js `dynamic(..., { ssr: false })`, Nuxt ``, SvelteKit `ssr = false`). Server-rendered data uses a Machine Auth Key from a server-only env variable (never `NEXT_PUBLIC_`/`VITE_`/`PUBLIC_`): ```ts import "server-only"; import { createServerReader } from "@kovlet/client/server"; const reader = createServerReader({ machineKey: process.env.KOVLET_MACHINE_KEY!, clientId: process.env.KOVLET_CLIENT_ID! }); const rows = await reader.rows<{ vendor: string; amount: number }>(spaceId, "expenses"); // also files(), fileUrl(), request() ``` Read-only; it refuses to run in a browser, and browser bundles get a stub that throws. Guide: https://kovlet.com/docs/ssr.md ## End users: sign-in for an app's own users A public app can let people without a Kovlet account sign in to one Data Space: email code, Google, Apple, GitHub, LinkedIn, a Clerk/Firebase/Auth0/OIDC ID token, or guest. Each space has its own directory, listed in the system table `_users` (link to it with `t.ref("_users")`). An owner turns sign-in on per app in the console (Access → End users); the app must be approved with pinned origins or redirect URIs. **Closed by default:** an end user can't use a table until the space's rules allow it. Rules have the shape of `instant.perms.ts` and are CEL, as in InstantDB: per table `bind` and `allow` with `view`/`create`/`update`/`delete` (`_users`: `view`; `_files`: the four over `data.path`/`data.size`; `_rooms`: `join` over `data.id`). They read `auth.id`/`auth.email`/`auth.is_guest`, `data` (the stored row), `newData` (the row after the write), `params` (client values, untrusted) and `data.ref('link.link.column')` (ref columns forward, or a table that points back; at most 3 links; on the right of `in`). The server enforces them on every subscription, REST read, query and write; rows a user may not view never leave the server. View rules compare columns with values only (no `newData`, no column vs column). Errors deny. Rules bind end users only, never members or Machine Auth Keys. ```json {"todos": {"bind": ["isOwner", "auth.id == data.owner"], "allow": {"view": "isOwner", "create": "auth.id == newData.owner", "update": "isOwner && newData.owner == data.owner", "delete": "isOwner"}}, "posts": {"allow": {"view": "data.published || auth.id in data.ref('team.memberships.user')"}}} ``` ```ts const kovlet = createKovletClient({ spaceId: "spc_…", appId: "app_…", schema }); // both public ids, no key await kovlet.auth.sendMagicCode({ email }); const { user } = await kovlet.auth.signInWithMagicCode({ email, code }); // user: { id, email, isGuest, createdAt } await kovlet.auth.signInAsGuest(); await kovlet.auth.signInWithOAuth({ provider: "google", redirectUri: location.origin + "/auth/callback" }); // then kovlet.auth.completeOAuth() on the callback page await kovlet.auth.signInWithIdToken({ provider: "clerk", idToken }); kovlet.auth.user; kovlet.auth.onChange((user) => {}); await kovlet.auth.signOut(); const { data } = useQuery(kovlet.space("main"), { todos: {} }); // live, as the signed-in end user: only the rows the rules allow const todos = await kovlet.auth.records("todos"); // one-shot REST read, same filter await kovlet.auth.transact([{ op: "upsert", table: "todos", id, fields: { owner: user.id, title } }]); // checked against the rules; a denied write rejects the batch (TransactionRejectedError, code forbidden, details.rule) ``` React: `useAuth()` → `{ user, isLoading, error }`. REST (`app_id` on every call; browsers send a pinned `Origin`; token calls carry the SDK's device key): | Method and path | Body → answer | | --- | --- | | `GET /v1/eu/{space}/config?app_id=` | → `{enabled, providers: [{name, kind}]}` | | `POST /v1/eu/{space}/codes` | `{app_id, email}` → 202 `{sent, expires_in}` | | `POST /v1/eu/{space}/guest` | `{app_id, device_key}` → token | | `GET /v1/eu/{space}/oauth/{provider}/start?app_id=&redirect_uri=&state=&code_challenge=` | → 302 to the provider, back to `redirect_uri?code=&state=` | | `POST /v1/eu/{space}/token` | `grant_type` `magic_code` (`email`, `code`), `authorization_code` (`code`, `code_verifier`, `redirect_uri`), `id_token` (`provider`, `id_token`), `sign_in_code` (`code`), `refresh_token` → `{access_token: "kvu_…", refresh_token: "kvur_…", expires_in, user, guest_id?}` | | `GET /v1/eu/{space}/me`, `POST /v1/eu/{space}/sign-out` | → `{user}`, 204 | | `GET /v1/spaces/{space}/tables`, `GET /v1/spaces/{space}/records?table=`, `POST /v1/spaces/{space}/query`, `POST /v1/spaces/{space}/transact` | end-user sessions: only what the rules allow (writes: `forbidden` with `details.rule`, e.g. `todos.update`); every other `/v1/spaces/…` route is `403 end_user_forbidden` | | `GET\|POST /v1/spaces/{space}/end-users`, `GET\|PATCH\|DELETE …/end-users/{id}` | directory management (console, or a machine grant with `impersonate`); `PATCH {blocked}`; DELETE erases | | `POST /v1/spaces/{space}/end-users/{id}/sign-in-codes` | `{app_id}` → `{code, expires_at}`: a server-minted one-time sign-in (InstantDB `auth.createToken`) | | `GET\|PUT /v1/spaces/{space}/rules` | owner, console: `{document}` → `{version, document}`; `422 rules_invalid` with `errors` per rule | | `POST /v1/spaces/{space}/rules/proposals` | apps, CLI (editor), and the MCP tool `propose_rules`: `{document}` → `{proposal}`, pending until an owner approves (`POST …/schema/proposals/{id}/approve`) | | `POST /v1/spaces/{space}/rules/test` | owner: `{email\|end_user_id, table, action?, record_id?, fields?, document?}` → `{allowed, rule?, rows?, visible, total, filter?}`, read-only | Server code with a Machine Auth Key bypasses rules; it acts as an end user with the header `Kovlet-As-End-User: ` (or `email:
`) once an owner sets `impersonate` on its machine grant. An end-user token in a `protocol: 1` sync `hello` gets `unsupported_protocol` with `details.supported: [2]`. Live reads: while an end user is signed in, `useQuery`/`liveQuery`/`useTable` sync as them over protocol 2, filtered by the rules ([protocol §17.9](https://kovlet.com/docs/protocol.md)); sign-out clears their rows from the device, a token refresh keeps the subscriptions, and denied writes reach `onError` (`forbidden`, `details.rule`). A Machine Auth Key client syncs as an end user with `asEndUser: ""` (needs `impersonate`). Not supported: password or SMS sign-in, OAuth clients shared by Kovlet (register your own), linking end users to Kovlet accounts. Guide: https://kovlet.com/docs/end-users.md ## Plain REST For languages without an SDK, or server scripts. JSON bodies, `snake_case` fields. The machine-readable contract of every route (auth scheme, console-only vs. app-callable, request/response schemas, error codes) is the OpenAPI 3.1 spec at `/openapi.json` (or `/openapi.yaml`): generate a client from it with `openapi-generator`. Routes marked `x-kovlet-session: console` (space settings and members such as `GET`/`PATCH`/`DELETE /v1/spaces/{id}` and `/v1/spaces/{id}/members`, and workspace, machine and app administration) answer app sessions with `403 console_required`. `GET /v1/spaces` and `POST /v1/spaces` are `x-kovlet-session: any`: an app lists the spaces it can use and creates new ones with them (see "Spaces for apps" below). Errors look like `{"error": {"code": "...", "message": "...", "hint": "..."}}`, where `hint` is the next step (OAuth endpoints use `{"error": "...", "error_description": "..."}`). A plan limit answers `402` with `{"error": {"code": "quota_exceeded", "message", "metric", "used", "limit", "upgrade_url"}}`. ### Get a token (headless) Device code flow (RFC 8628). The user approves in the console and picks spaces: ```http POST /v1/oauth/device_authorization Content-Type: application/x-www-form-urlencoded client_name=Nightly+Export&machine_name=build-box ``` → `{"device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in": 600, "interval": 5}`. Show `verification_uri_complete` to the user, then poll every `interval` seconds: ```http POST /v1/oauth/token Content-Type: application/x-www-form-urlencoded grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=kvc_... ``` The poll answers 400 with `authorization_pending` or `slow_down` until the user decides, then `access_denied` or `expired_token` on failure. On success it returns `{"access_token": "kvs_...", "token_type": "Bearer", "expires_in", "machine_id", "workspace_id", "client_id"}`. Add `scope=agent` to the device authorization for an AI agent acting as the user (what `@kovlet/mcp` does). Add `space_ids` (space-separated) with the spaces the app pinned, so `/activate` preselects them. Native apps and CLIs that sign in as the user add `device_public_key` (a P-256 public JWK): the poll that redeems the code then needs a device proof over the device code, and the answer adds `user_id`, `refresh_token` and `refresh_token_expires_in`. Every auth step, including PKCE redirects for mobile apps (loopback on any port, `com.example.app:/callback` schemes), refresh and `reason: "device_revoked"`, is in [protocol §2](https://kovlet.com/docs/protocol.md). Add `space_name=` to suggest the name of the new space a first-time user gets at approval (default: the app's name). Machine Auth Key: `POST /v1/oauth/token` with `grant_type=urn:kovlet:params:oauth:grant-type:machine_key&machine_key=kvm_...&client_id=`. Send `Authorization: Bearer kvs_...` on every request. Keyless device-code and Machine Auth Key tokens need nothing else. Device-bound sessions (PKCE, and device codes started with `device_public_key`) also need `Kovlet-Device-Proof` on every request (the SDK handles it). ### Endpoints (all `/v1/spaces/{space}/...` need at least viewer) | Method and path | Role | Purpose | | --- | --- | --- | | `GET /v1/me` | any | The session: user, machine, app, workspace | | `GET /v1/spaces/{space}/access` | any | `{role, read, write, manage}` for this session | | `GET /v1/spaces/{space}/tables` | viewer | `{"tables": {name: {"version", "columns": {col: {"type", "optional"?, "ref_table"?, "unique"?, "indexed"?}}, "order"?: [col, ...]}}}` | | `POST /v1/spaces/{space}/schema/changes` | editor | `{"changes": [{"op": "create_table", "table", "columns", "order"?} \| {"op": "add_column", "table", "column", "def"} \| destructive ops]}` → 200 applied, 202 when some became proposals | | `GET /v1/spaces/{space}/schema/proposals?status=pending` | viewer | Proposals | | `GET /v1/spaces/{space}/records?table=&trashed=exclude\|include\|only&after_seq=&limit=` | viewer | `{"records": [{"table", "id", "fields", "hlcs", "seq", "deleted"?}], "next_after_seq"?}` (limit ≤ 5000, default 500) | | `POST /v1/spaces/{space}/tables/{table}/records/{id}/restore` | editor | Restore a trashed row (409 `unique_violation` when another live row took one of its unique values) | | `POST /v1/spaces/{space}/query` | viewer | `{"query": {...}}` (a nested query, see "Queries" above) → `{"data": {"posts": [{"id", ...fields, "author": {...} \| null, "comments": [...]}]}, "page_info": {"posts": {"start_cursor", "end_cursor", "has_more"}}, "through_seq"}`. 400 `invalid_query` / `index_required`, 422 `query_too_large` (over 10,000 rows). | | `POST /v1/spaces/{space}/transact` | editor | `{"batch_id"?, "mutations": [mutation, ...]}` (1-500, the `mutate` frame's mutation shape) → 200 `{"space_id", "batch": {"id", "status": "applied" \| "duplicate"}, "results", "head_seq"}`. All or nothing: 409 with `batch.status: "rejected"`, `batch.failed_index` and `batch.error` when one write fails; that result is `rejected`, the others `aborted`. Retrying with the same IDs is safe. | | `GET /v1/spaces/{space}/files?prefix=&dir=&trashed=&after_seq=&limit=` | viewer | File metadata (`dir=` lists one folder level) | | `GET /v1/spaces/{space}/files/{id}` | viewer | One file | | `GET /v1/spaces/{space}/files/{id}/download[?version=]` | viewer | `{"method": "GET", "url", "headers"?, "expires_at"}` presigned download | | `POST /v1/spaces/{space}/files/uploads` | editor | `{"sha256", "size_bytes", "mime_type"?}` → `{"exists", "upload"?: {"method": "PUT", "url", "headers"?}}`. PUT the bytes to `upload.url` (unless `exists`), then commit a file `put` mutation over the WebSocket. | | `POST /v1/spaces/{space}/files/move-folder` | editor | `{"from": "a/", "to": "b/"}` → `{"from", "to", "moved", "head_seq"}`. Renames a folder in one transaction: all live files move or none (409 `path_conflict`). | | `GET /v1/spaces/{space}/activity?app=&user=&table=&since=&limit=` | viewer | Change feed, newest first | | `GET /v1/usage[?space_id=]` | any | `{"workspace_id", "plan", "metrics": [{"metric", "used", "limit" (hard stop, null = unlimited), "soft_limit"?, "state": "ok" \| "near" \| "over"}], "upgrade_url"}`. Works for app and machine sessions. | ### Spaces for apps (app sessions) | Method and path | Purpose | | --- | --- | | `GET /v1/spaces` | `{"spaces": [{"id", "name", "slug", "role", "reason"?, "guest", "head_seq", ...}], "requestable": n, "can_create": bool, "create_blocked"?: {"code", "message"}}`. `role` is `""` and `reason` is `app_not_approved`/`machine_not_approved` while an admin must approve. | | `POST /v1/spaces` | `{"name", "slug"?, "icon"?, "slot"?}` → 201 `{"space": {...}}`. Owned by the signed-in user (a headless machine's owner); this app gets editor. 402 `quota_exceeded`, 403 `app_not_approved`/`machine_not_approved`/`not_a_member`, 409 `slug_taken` (send a `slug` so a retry can't duplicate). | | `POST /v1/grant-requests` | `{"asks": [{"role", "slot"?, "space_id"?, "suggested_name"?}], "redirect_uri"?, "state"?}` → 201 `{"request": "kvg_...", "approve_url", "expires_in": 600, "interval": 2}`. Show `approve_url` (popup, system browser sheet, or print it). `redirect_uri` must be one the app registered; the browser returns there with `?state=&result=approved|denied`. | | `GET /v1/grant-requests/{request}` | `{"status": "pending" \| "approved" \| "denied" \| "expired", "spaces": [{"space_id", "name", "role", "slot"?, "created"}]}`. Poll every `interval` seconds. Only the same user, machine and app can read it. | Only the signed-in user can open an approve link (anyone else gets 404). Approving adds grants to the same session and machine; named slots appear in `/v1/me`. Writes to rows and file metadata go through the WebSocket `mutate` frame. There is no REST row write. ## WebSocket sync protocol (v1) `GET /v1/sync` upgrades to a WebSocket. Every frame is one JSON text message with a `type`. Each connection covers one space. Writing your own client (any language, no SDK)? Read "Building a client without the SDK" below. The full normative reference is [kovlet.com/docs/protocol](https://kovlet.com/docs/protocol) (Markdown: [/docs/protocol.md](https://kovlet.com/docs/protocol.md)), and JSON Schemas for every frame are at [kovlet.com/protocol/schema](https://kovlet.com/protocol/schema). 1. Client → `hello`: ```json {"type": "hello", "protocol": 1, "space_id": "", "since_seq": 0, "token": "kvs_...", "schema": {"expenses": {"columns": {"vendor": {"type": "string"}, "amount": {"type": "number"}, "note": {"type": "string", "optional": true}}, "order": ["vendor", "amount", "note"]}}} ``` `since_seq: 0` requests a full snapshot. Otherwise send the last seq you saw. `schema` is optional; it declares tables and adds new tables and optional columns. `order` (optional) lists every column once, in the order you want them shown; kovletd keeps it, and `toTableSchema` sends it for you. Browser sessions add `device_proof`. 2. Server → `snapshot` frames `{"type": "snapshot", "space_id", "head_seq", "tables", "records": [{"table", "id", "fields", "hlcs"}], "files": [...], "complete": bool}` (the last chunk has `complete: true`), or `delta` frames `{"type": "delta", "ops": [...], "head_seq", "complete"}`. The first of these frames also carries `usage` (the same `metrics` as `GET /v1/usage`). 3. Client → `mutate` (at most 500 per frame): ```json {"type": "mutate", "space_id": "", "mutations": [ {"mutation_id": "", "hlc": "1764314700123:00000:node-1", "kind": "record", "op": "upsert", "table": "expenses", "id": "", "fields": {"vendor": "Tartine", "amount": 12, "spentAt": "2026-11-28T09:00:00Z"}}, {"mutation_id": "", "hlc": "1764314700124:00000:node-1", "kind": "record", "op": "delete", "table": "expenses", "id": ""}, {"mutation_id": "", "hlc": "1764314700125:00000:node-1", "kind": "file", "op": "put", "id": "", "file": {"path": "receipts/tartine.png", "sha256": "<64 hex>", "size_bytes": 1024, "mime_type": "image/png"}} ]} ``` Record ops are `upsert` (partial `fields`; an insert must include every required column), `delete` and `restore`. File ops are `put`, `move` (`file.path` only), `delete` and `restore`. `hlc` is `wall_ms:counter:node_id`: a 13-digit ms timestamp, a zero-padded 5-digit counter from 00000 to 65535 (not 99999: on overflow, advance the ms instead) and `[A-Za-z0-9_-]{1,64}`. Keep it monotonic per client, and no more than 5 minutes ahead of server time. `mutation_id` makes a resend idempotent. A record `id` is 1-256 bytes of UTF-8 text with no control characters; `space_id`, `mutation_id` and file ids are 1-128 characters from `[A-Za-z0-9_-]`. Escape a record id in a REST path (`encodeURIComponent`). Each mutation is checked and applied on its own: a malformed one is rejected in the `ack` and the rest of the frame still applies. Only a frame that cannot be answered (not JSON, a bad `space_id` or `mutation_id`, no mutations or more than 500) is an `invalid_frame` error. 4. Server → `ack` with `{"results": [{"mutation_id", "status": "applied" | "duplicate" | "rejected", "seq"?, "error"?: {"code", "message", "details"?, "hint"?}}], "head_seq", "warnings"?}`. `warnings` is present only when the commit crossed 80/90/100% of a limit: `[{"code": "quota_near", "metric", "used", "limit", "soft_limit"?, "threshold"}]`. Other connections get a `broadcast` with `{"ops": [...], "head_seq"}`. Each op has `seq`, `mutation_id`, `hlc`, `at`, `by` (`user_id`, `machine_id`, `app_id`), `kind`, `op` and a payload (`table`, `id`, `fields` for records; `id`, `file` for files; `table`, `schema` for schema). Error frame: `{"type": "error", "code", "message", "retryable", "details"?, "hint"?}`. Fatal codes close the socket: `unauthenticated` (4401), `forbidden` (4403), `space_not_found` (4404), `invalid_frame` (4400), `unsupported_protocol` (4426). Per-mutation rejections arrive in `ack` with these codes: `invalid_id` (the record or file id breaks the id rule; the message states it), `invalid_mutation` (a bad op, table, field name or HLC), `schema_violation`, `forbidden`, `clock_drift`, `path_conflict`, `blob_missing`, `quota_exceeded` (a new row past the workspace's plan limit; `details`: `metric`, `used`, `limit`, `upgrade_url`), `unique_violation` (another live row holds the value in a unique column; `details`: `table`, `column`, `id`, `holder_id`). v1 has no atomic batches: a `mutate` with `"atomic": true` is rejected whole with `unsupported_protocol`. `schema_proposal_required` (non-fatal) means a declared schema needs owner approval. Merge rule: each field is a last-writer-wins register ordered by HLC. Delete is a register too, so an upsert never resurrects a trashed row; use `restore`. Rooms (optional, presence and topics): when the first catch-up frame carries `features.rooms`, a client may send `room_join` / `presence_set` (full object) / `topic_publish` / `room_leave` with `space_id` and `room`, and receives `room_state` / `presence` (`join`, `update`, `leave`) / `topic` / `room_error` for rooms it joined. Room frames are never fatal (`room_error` is room-scoped). Never send them when `features.rooms` is absent. Details: protocol reference §16. ## Building a client without the SDK A complete, runnable starting point (sign-in, spaces, a table and a file in one dependency-free script) is the REST + WebSocket quickstart: https://kovlet.com/docs/quickstart-rest.md. The rules a hand-written client (Rust, Swift, Kotlin, Go, Python, ...) must follow. The full spec is [/docs/protocol.md](https://kovlet.com/docs/protocol.md). Schemas: [/protocol/schema](https://kovlet.com/protocol/schema) lists one JSON Schema per frame, and each schema's `$id` is its URL. **Frames.** Client → server: `hello`, `mutate`, `ping`. Server → client: `snapshot`, `delta`, `broadcast`, `ack`, `error`, `pong`. Ignore unknown properties. **Protocol 2 (optional).** `hello` with `"protocol": 2` and no `space_id` gets a `welcome`; then `subscribe` (`{"sub", "space_id", "query"}`, where `query` is a nested query object or `"*"` for the whole space) gets `result` pages and live `changes` (`ops` for rows it holds, `added`, `removed`), and `unsubscribe` ends one. `mutate`/`ack` are unchanged; `"atomic": true` with a `batch_id` applies all or nothing. See [protocol §17](https://kovlet.com/docs/protocol.md). - Snapshot record: `{"table", "id", "fields", "hlcs": {field: hlc}, "seq", "deleted"?, "deleted_hlc"?}`. The snapshot is split over frames: only the first carries `tables`, the last has `complete: true`. Treat a completed snapshot as the whole server state. - Op (in `delta` and `broadcast`): `{"seq", "mutation_id", "hlc", "at", "by", "kind", "op", "table"?, "id"?, "fields"?, "file"?, "schema"?}`. Record upserts carry only the fields that op **won**, not the merged row. - Ack result: `{"mutation_id", "status": "applied" | "duplicate" | "rejected", "seq"?, "error"?}`. One per mutation, in order. `applied` without `seq` means it changed nothing (a newer write already won). Treat `duplicate` like `applied`. - Your own ops are never broadcast back to you, but a `delta` replays them. Ops committed by others before yours arrive as a `broadcast` just before your `ack`. - Cursor (`since_seq` on reconnect): the last op seq you applied, or `head_seq` of a complete snapshot. Never take it from `ack.head_seq`. - A `schema` op that drops a column or table: reconnect with `since_seq: 0`. **Merging and deleted rows.** - Each field is last-writer-wins by HLC. The deleted flag is a separate register stamped by `deleted_hlc`. - An upsert on a trashed row is accepted and merges its fields, but the row **stays deleted**. Only `restore` brings it back. - `delete` or `restore` of a row the space never had is rejected with `not_found`. - `null` appears only in optional columns: the server never writes `null` to a required column. Approving `make_required`, `change_type` or a new required column is refused with 409 `rows_violate_schema` (`count`, up to 5 `examples` row ids) while any row, trashed ones included, would break it; fix those rows and approve again. So every row fits the current schema. - No column may be named `id` (it is the row id): declaring or creating one is rejected. **HLC.** `wall_ms:counter:node_id`: a 13-digit ms timestamp, a 5-digit zero-padded counter **00000–65535**, and a node id of 1–64 characters from `[A-Za-z0-9_-]`. - When the counter would pass 65535, advance `wall_ms` by 1 and reset the counter to 0. - Keep stamps strictly increasing per client, and merge every stamp you receive into your clock. - A stamp more than 5 minutes ahead of server time is rejected (`clock_drift`). - A malformed stamp (counter 65536–99999, wrong width) gets that mutation rejected with `invalid_mutation`; the rest of the frame still applies. **IDs.** - Row ids: 1–256 bytes of UTF-8 text with no control characters (U+0000–U+001F, U+007F–U+009F), so an app's own ids (`table:abc`, emails, URLs, paths) work as they are. Compared byte for byte; escape them in REST paths. With no id of your own, use UUIDv7. - Space ids, file ids, mutation ids and ping nonces: 1–128 characters from `[A-Za-z0-9_-]`. - A bad id is rejected alone with `invalid_id`, and other malformed mutations with `invalid_mutation`; the rest of the frame still applies. Only an unanswerable frame (not JSON, wrong `space_id`, a missing or bad `mutation_id`, 0 or more than 500 mutations) is `invalid_frame` (4400). Validate before sending anyway. - Table and column names: `^[A-Za-z][A-Za-z0-9_]{0,62}$`. A leading `_` is reserved. Never declare an `id` column. - `mutation_id` makes a write idempotent: resending after a reconnect returns `duplicate`. **Liveness and size limits.** - The server sends WebSocket ping control frames every 30 s and closes the socket if the pong doesn't arrive within 10 s. Each server write times out after 10 s. - **Never block the read loop**, for example during a file upload: run uploads elsewhere. - `hello` must arrive within 10 s of the upgrade. - Messages are capped at **8 MiB** in both directions (the server splits large snapshots and deltas). Set your WebSocket's maximum incoming message size to at least 8 MiB. - A `mutate` frame holds at most 500 mutations. A row (fields plus stamps) is capped at 8 MiB − 64 KiB. - Uploads: presigned PUT, up to 5 GiB. Send every returned header (S3 needs `x-amz-checksum-sha256`). The URL is valid for 15 min. To confirm an upload, `POST .../files/uploads` again and look for `exists: true`. **Quotas (free plan, per workspace).** - Limits: 100,000 live rows included, with new rows refused only at the hard stop of 110,000 (a 10% grace buffer; trashed rows don't count); 1 GiB of files; 3 Data Spaces; 2 headless machines; 10 personal devices; 3 guests per space. - Only growth is blocked: a new row past the hard stop is rejected with `quota_exceeded`, and an upload URL answers 402. Reads, edits and deletes keep working. - Both carry `metric`, `used`, `limit` (the hard stop), `soft_limit` (rows), `upgrade_url` and `reads_open`. - Warn before that happens: the first `snapshot`/`delta` after `hello` carries `usage` (`[{metric, used, limit, soft_limit?, state: "ok" | "near" | "over"}]`), an `ack` may carry `warnings` (`quota_near` at 80/90/100% crossings), and `GET /v1/usage[?space_id=]` works for app sessions. See [protocol §15](https://kovlet.com/docs/protocol.md). **Tokens.** Send `Authorization: Bearer kvs_...` on REST, and put the token in `hello.token` on the socket. | Grant | Lifetime | Refresh | | --- | --- | --- | | Device code without a key (headless app) | 90 days | none: sign in again | | Device code with `device_public_key` (native app or CLI on the user's device) | 30 days | `grant_type=refresh_token`, with a device proof signed over the refresh token | | Device code with `scope=agent` | 30 days | none | | Machine Auth Key | 90 days | exchange the key again | | PKCE consent (`authorization_code` + `device_public_key`) | 30 days | `grant_type=refresh_token`, with a device proof signed over the refresh token | - A refresh token (`kvr_...`) lasts 60 days and works **once**. Each refresh returns a new pair, and reusing an old refresh token revokes the session. Store the new pair atomically. - Device-bound sessions (PKCE, and device codes started with `device_public_key`) must send a fresh single-use P-256 device proof on every request (`Kovlet-Device-Proof` header) and in `hello.device_proof`. Redeeming a keyed device code also needs a proof over the `device_code`. Keyless device-code and machine-key sessions don't need proofs. - On `invalid_grant`, sign in again with the same device key (the machine and its grants are kept). Make a new key only when the error has `reason: "device_revoked"`. - Read `expires_in` instead of hard-coding these lifetimes. **Which endpoints an app can call.** The OpenAPI spec (`/openapi.json`) says this per route in `x-kovlet-session` (`none`, `any` or `console`). - **App-callable:** `GET /v1/me`, `GET`/`POST /v1/spaces` (the app's own spaces; see Spaces for apps), `POST`/`GET /v1/grant-requests`, `GET /v1/spaces/{space}/access`, everything under `/v1/spaces/{space}/` that is listed in the Plain REST section above (tables, schema changes and proposals, records, restore, files, activity), `GET /v1/usage[?space_id=]`, `GET /v1/sync`, `/v1/oauth/device_authorization`, `/v1/oauth/token`, and `POST /mcp`. - **Console-only** (apps get 403 `console_required`): `GET`/`PATCH`/`DELETE /v1/spaces/{id}`, space members, app grants, machine grants and access events, grant request review and decision, `/v1/workspaces/...`, `/v1/machines/...`, `/v1/apps/...`, `/v1/workspace/usage` (apps use `GET /v1/usage`) and `/v1/invites`. - **Owner-only, through the console:** approving or rejecting schema proposals, and rollback. **Errors.** - Fatal codes close the socket: `invalid_frame` 4400 (client bug: don't reconnect in a loop), `unauthenticated` 4401 (refresh or sign in again), `forbidden` 4403 (stop and show `hint`), `space_not_found` 4404, `unsupported_protocol` 4426, `internal` 4500 (reconnect with backoff). - 1001 means the server is redeploying: reconnect. - Every error carries a `hint` with the next step. ## Kovlet MCP server Tools: `list_spaces`, `inspect_space_schema` (tables, files, pending proposals and the current end-user `rules`), `create_space`, `request_space_access`, `propose_schema_addition`, `propose_rules` (a whole end-user rules document; pending until an owner approves it in the console), `list_connected_apps` and `generate_app_connection`. When `list_spaces` reports `not_shared_with_agent`, `request_space_access` returns an approve link for the user: no new sign-in. Every tool goes through the same access policy as apps, so an agent never sees a space its user couldn't. Connect a coding agent (stdio bridge, signs in through the device flow on the first tool call; needs Node.js 22.12 or newer). `init` registers the server and the Kovlet agent skill with Claude Code, Cursor, Windsurf and Codex: ```sh npx -y @kovlet/mcp init # every agent on this machine, hosted Kovlet npx -y @kovlet/mcp init --url http://127.0.0.1:8080 # against a local kovletd --dev claude mcp add kovlet -- npx -y @kovlet/mcp --url https://api.kovlet.com # or by hand, any MCP client: npx -y @kovlet/mcp --url ``` The first tool call answers `sign_in_required` with an approval link and code: the user opens it, picks the Data Spaces the agent may use and approves, then the agent calls the tool again. `npx -y @kovlet/mcp login` signs in ahead of time. Or connect over HTTP directly. A standard MCP client needs only the URL `https://api.kovlet.com/mcp`: on the first 401 it follows `WWW-Authenticate` to `/.well-known/oauth-protected-resource/mcp` and `/.well-known/oauth-authorization-server`, registers at `POST /v1/oauth/register` (RFC 7591, public client, `kvo_...` id), opens `GET /v1/oauth/authorize` (code + PKCE S256, `resource=/mcp`) where the user approves at `/activate`, and redeems the code at `/v1/oauth/token` with `resource`. That token works only on `/mcp`. Every such sign-in is an agent acting as the user; approving the same agent again reuses its machine. RFC 8628 clients can use the device grant with the registered `client_id` instead. Clients that take a static header: get a token with the device code flow above (add `scope=agent`) or `npx -y @kovlet/mcp login` then `npx -y @kovlet/mcp token`, and send `POST /mcp` with `Authorization: Bearer `, e.g. `claude mcp add --transport http kovlet https://api.kovlet.com/mcp --header 'Authorization: Bearer ${KOVLET_TOKEN}'` (`npx -y @kovlet/mcp init --http` writes the entry for every agent). `initialize` and `tools/list` work without a token; tool calls answer 401 `unauthenticated` without a valid one. A session lasts 30 days; sign in again when it expires. Setup for every client, troubleshooting and a first prompt: https://kovlet.com/docs/connect-coding-agent.md ## Migrating from InstantDB To move an InstantDB app to Kovlet, run one command from the app's folder. It needs the InstantDB admin token in `INSTANT_APP_ADMIN_TOKEN` (or `--admin-token`) and never writes it to disk: ```sh npx @kovlet/mcp migrate instantdb --dry-run # plan and counts, writes nothing npx @kovlet/mcp migrate instantdb --yes # copy; safe to re-run, resumes without duplicates ``` The command maps entities to tables (`date` → `datetime`, has-one links → `