# Integrator guide — the workbook.run public API

Companion to [`public-api.md`](./public-api.md) (the contract-driven reference) and
[`admin-api.md`](./admin-api.md) (control-plane gating). Those docs are the source of
truth — pinned down by `packages/contracts/src`; this guide adds **flows and runnable
examples, zero new claims**. Every endpoint, field, limit, and error below was
cross-checked against those docs and the contracts at the time of writing; where the
contracts and this guide ever disagree, the contracts win.

Status: docs-only · Verifies criterion API-03 (open half — the surfaces outside the
control plane) · Sample checker: `node scripts/check-doc-samples.mjs` (runs as part of
`pnpm lint`). For the 30-minute zero-to-embed path, see [the quickstart](./quickstart.md).

## The three surfaces, and where to send requests

```
control plane            POST https://api.workbook.run/v1/…              (edge)
workbook API             https://{workbook}.vms.workbook.run              (each workbook's VM)
  /api/…                 tables, rows, search, forks, dashboards, …
  /e/<path>              endpoint + action invocation
  /api/events            the event stream (WebSocket, or plain-HTTP polling)
published surface        https://api.workbook.run/p/{workbookId}/…        (edge proxy)
```

`{workbook}` in a host is the workbook id lowercased, with underscores turned into
hyphens (`wb_ABC` → `wb-abc`). Staging uses the same shape with `staging` inserted
(`api.staging.workbook.run`, `{workbook}.vms.staging.workbook.run`). The CLI and MCP
use production unless `WB_ENV=staging`.

- The **control plane** is served by the edge worker; it answers `/v1` for holders of
  bearer credentials and session cookies, and it is where every credential is minted or
  exchanged. Workbook hosts use the `WORKBOOK_VM_ORIGIN` template —
  `https://{workbook}.vms.workbook.run` in production.
- The **workbook API** is the full surface each workbook VM serves. It never sees raw
  token secrets — only edge-signed claims (see [Authentication](#authentication)).
- The **published surface** is a method + path allowlist of read-only workbook-API
  routes, rate-limited at the edge and gated to `published` workbooks. Custom domains
  are rewritten onto this path.

## Quickstart: workbook without an account

Anonymous create is the product's front door for agents: a create call with no
credentials provisions an unclaimed workbook and returns its `agentToken` and `claimUrl`
exactly once. The claim URL is the handoff: a human who opens it gets the full
workbook immediately — full read/write access, no account — and signing in
redeems ownership (which is what makes the workbook durable and joins their
list). Until the workbook is claimed, anyone who holds the link has the same
write access to `main` as its eventual owner — the link is itself a credential,
so hand it over a private channel, never a ticket, log, or shared one. Opening
never consumes the link; the claim link expires with the
workbook's 72-hour TTL.

```bash
set -euo pipefail

# Production control plane. Staging is https://api.staging.workbook.run.
CONTROL_PLANE="https://api.workbook.run"

# 1. Anonymous create — no credentials. agentToken and claimUrl come back ONCE.
CREATE=$(curl -s -X POST "$CONTROL_PLANE/v1/workbooks")
WORKBOOK_ID=$(echo "$CREATE" | jq -r .workbook.id)
AGENT_TOKEN=$(echo "$CREATE" | jq -r .agentToken)
CLAIM_URL=$(echo "$CREATE" | jq -r .claimUrl)   # the handoff — full access from first open, write on main until claimed; expires in 72 h

# 2. Exchange the agent token for a signed claims envelope (300 s TTL).
EXCHANGE=$(curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/claims" \
  -H "Authorization: Bearer $AGENT_TOKEN")
CLAIMS=$(echo "$EXCHANGE" | jq -r .claims)

# 3. Address the workbook's VM host directly with the claims header.
#    The host label is the id lowercased, with underscores turned into hyphens.
VM_HOST="$(printf '%s' "$WORKBOOK_ID" | tr '[:upper:]' '[:lower:]' | tr '_' '-').vms.workbook.run"

# 4. Create a table (column types: string, number, boolean, date, json, enum, vector).
curl -s -X POST "https://$VM_HOST/api/tables" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{
        "name": "tasks",
        "columns": [
          { "key": "title", "type": "string", "searchable": true },
          { "key": "done", "type": "boolean" }
        ]
      }'

# 5. Insert rows — clientOpId makes the write idempotent (retries return the
#    stored result instead of applying twice).
curl -s -X POST "https://$VM_HOST/api/tables/tasks/rows" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "rows": [ { "title": "Ship the guide", "done": false } ],
        "clientOpId": "seed-001" }'

# 6. Query it back.
curl -s -X POST "https://$VM_HOST/api/tables/tasks/rows/query" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "limit": 100 }'
```

The claims response is `{ "claims": "<envelope>", "expiresInSeconds": 300 }`. The
`claims` string is exactly what you put in the `X-WB-Claims` header — a base64 JSON
envelope `{payload, sig}`, Ed25519-signed by the edge, with a 300 s TTL. Re-exchange
before `exp`: a workbook-API request arriving with an expired envelope is
`401 unauthenticated`.

## Exchange keys (connect, claim, invite)

Bootstrap and handoff use one edge primitive: **`exchange_key`**. An opaque `exk_…`
code is short-lived; redeem yields a long-lived private token, ownership, or membership.
**URLs must never carry a durable `wbt_` / `wbk_` secret** — only opaque exchange codes.

| Intent | Product flow | Redeemer | Outcome |
| --- | --- | --- | --- |
| `mint-credential` | Connect (MCP / agent) | Anyone with the code | Private `wbt_` (same scopes as mint; single-use) |
| `grant-ownership` | Claim | Signed-in session | Workbook ownership |
| `grant-membership` | Invite | Signed-in session | Member at role (`maxUses` may be >1) |

```bash
# Owner mints a connect link for an agent (editor, review-first).
CONNECT=$(curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/exchange-keys" \
  -H "Authorization: Bearer $SESSION_OR_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"intent":"mint-credential","scopes":{"role":"editor","forks":"own","mergeMode":"review"}}')
echo "$CONNECT" | jq -r .url   # https://…/connect/exk_… — paste to the agent / MCP

# Agent or MCP redeems once into a private token (never log or echo it).
REDEEM=$(curl -s -X POST "$CONTROL_PLANE/v1/exchange-keys/redeem" \
  -H 'Content-Type: application/json' \
  -d "{\"code\":\"$(echo "$CONNECT" | jq -r .code)\"}")
export WB_TOKEN=$(echo "$REDEEM" | jq -r .token.token)
export WB_WORKBOOK=$(echo "$REDEEM" | jq -r .workbookId)
```

MCP accepts `WB_CONNECT_URL` (or a bare `exk_` code) and redeems at process start into
an in-memory `WB_TOKEN`. Anonymous create’s `claimUrl` is also an exchange code
(`grant-ownership`); share URLs use an opaque code that aliases the share token
server-side.

### Claim resolve (full access from first open, no consumption)

A live claim key is itself a full-access credential. Presenting it to

```bash
RESOLVE=$(curl -s -X POST "$CONTROL_PLANE/v1/exchange-keys/claim-resolve/$CODE")
WORKBOOK=$(echo "$RESOLVE" | jq -r .workbook.id)
CLAIMS=$(echo "$RESOLVE" | jq -r .claims)
```

requires **no session** and returns `{ "workbook": …, "claims": "<envelope>",
"expiresInSeconds": 300, "claimable": true }` — the claims envelope carries
full read/write grants (every artifact, write; the same capability surface the
owner has, no ACL ceiling). This is the route the claim page (`/claim/:token`)
mounts: the workbook renders in full before anyone signs in.

**Resolve never consumes the key.** A stray reload or a forwarded copy of the
link resolves again, every time. Consumption is reserved exclusively for
ownership redemption (`POST /v1/exchange-keys/redeem`, session-only), which is
what makes ownership durable. The redeeming session's own credential is
unaffected — resolving and later claiming both leave the agent's token intact.

Error semantics are uniform: an unknown, expired, or non-claim key answers
`404 not_found` with no distinguishing detail; a claim key whose workbook
already has an owner answers `409 conflict` ("Workbook already claimed"). A
consumed key on an owned workbook answers `409`; on an unowned one, `404`.

## Authentication

Four credential forms exist. Three reach the workbook API — always as claims; the raw
secret never travels past the edge.

| Credential | Shape | Get it | Accepted by |
| --- | --- | --- | --- |
| Workbook token | `wbt_<tok_…>_<secret>` — kinds `session`, `agent`, `endpoint`, `share`, `claim` | `POST /v1/workbooks/:id/tokens` (owner or `admin: [tokens]`); mint returns the secret once | Control plane (bearer); workbook API and event stream (as edge-verified claims) |
| User API key | `wbk_…` | `POST /v1/keys` (session only) | Control plane (bearer), acting as its owning user across every reachable workbook |
| Share token | a `wbt_` token of kind `share` | `POST /v1/workbooks/:id/shares` (editor+) | Workbook reads scoped to the target; `/v1/shares/resolve` |
| Public claims | edge-minted, never stored | automatic on the published surface | `/p/:workbookId/*` forwards, public endpoint invocation |

Bearer precedence at the control plane is fixed: `wbt_` token → `wbk_` key → session
cookie. With no credential you are an anonymous actor, and exactly one route accepts
you: `POST /v1/workbooks`.

### Session claims (the exchange)

Every client exchanges its credential at `POST /v1/workbooks/:id/claims` and talks to
workbook VMs with the signed envelope:

```bash
EXCHANGE=$(curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/claims" \
  -H "Authorization: Bearer $AGENT_TOKEN")     # or a wbk_ key, or a browser session
CLAIMS=$(echo "$EXCHANGE" | jq -r .claims)      # base64 {payload, sig} — opaque to you
curl -s "https://$VM_HOST/api/tables" -H "X-WB-Claims: $CLAIMS"
```

The exchange is **scope-faithful**: a token mints its own stored scope (re-signed per
exchange, so revocation is honored on every VM-bound request); a session mints its
membership-resolved role (owner → a `schema` preset, editor → `write`, viewer/`custom`
→ an explicit read-only table map); an API key mints its owner's membership capped by
the key's scope. The claims payload itself carries the scope — `role`
(`owner|editor|viewer|custom`), per-table `tables` map (`read`/`write`/`schema`),
`forks` (`none|own|all`), `mergeMode` (`review|direct`), plus identity (`tokenId`,
`kind`, `actor`) and `exp`. You treat the envelope as opaque; the VM verifies the
signature, the expiry, and the schema.

Hosts the edge does not proxy answer **only** to `X-WB-Claims` — that is why every
client, agents included, exchanges first. On the WebSocket you cannot set headers
reliably, so the same envelope rides `?claims=` (see [Realtime](#realtime)).

### wbk_ user API keys and scopes

Keys are user-scoped credentials minted by their owner — not bound to any one
workbook. Management is session-only (a key that could mint keys would have no
ceiling at all):

```bash
# Mint (session cookie required — bearer credentials are refused here).
curl -s -X POST "$CONTROL_PLANE/v1/keys" -b cookies.txt \
  -H 'Content-Type: application/json' -d '{ "name": "ci", "scope": "read-write" }'
# → the raw wbk_ credential, exactly once. List (GET /v1/keys) shows metadata only.
```

On workbook surfaces a key acts as its owning user with a scope ceiling:

- **`read`** — reads resolve at viewer: workbook list and reads for workbooks the
  owner can see. Writes are `403`.
- **`read-write`** — reads and writes resolve at editor. Admin-gated routes (delete,
  publish, tokens, members) still refuse: keys never carry admin scopes.

Keys are rejected once revoked or expired (`401`), and a failed key never reveals
whether a workbook exists — the request dies at authentication.

### Share links

A share link is a minimum-scope read credential, constructed **server-side** — the
generic token-mint route refuses kind `share`, and you cannot supply caller-chosen
scopes. A dashboard target must name its source tables or the mint is refused.

```bash
curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/shares" \
  -H "Authorization: Bearer $OWNER_TOKEN" -H 'Content-Type: application/json' \
  -d '{ "target": { "kind": "table", "table": "tasks" }, "label": "field team" }'
# → { "token": "wbt_…", "url": "…/s/…", … } — credential and link, exactly once.
```

Consumers resolve the link anonymously (`POST /v1/shares/resolve` — revoked and expired
answer the same `404`), and a signed-in human can convert a live link into a viewer
membership (`POST /v1/shares/claim` — session only, `409` when already a member).
Share tokens read only what the target exposes: they cannot invoke endpoints (`/e/*`
answers them `403`), and events they receive are scope-redacted
([Realtime](#realtime)).

### Embed and public credentials

Published workbooks hand anonymous viewers a public identity without any stored token:
on every `/p/:workbookId/…` request the edge mints public claims (`kind: 'public'`,
`role: 'custom'`, read on all tables, `forks: 'none'`, 300 s TTL) and forwards them
with the request. Under public claims a published workbook's dashboards render entirely
through the allowlisted read routes, and `auth: 'public'` endpoints are invocable;
anything else is a `404` with no existence leak.

Page-kind dashboards mint their own short-lived credential — a `wbp_` page token, VM
side, described under [Dashboards](#dashboards-including-page-kind-html-pages).

## Hosted MCP: wire an agent client

Agents that speak MCP do not need the claims exchange at all: the hosted MCP
endpoint speaks streamable-HTTP, verifies the bearer `wbt_` token on every request,
and performs the exchange server-side. One endpoint serves every client — the
workbook id goes in the path, lowercased with underscores turned into hyphens:

```
https://mcp.workbook.run/w/{workbook}/mcp          (production)
https://mcp.staging.workbook.run/w/{workbook}/mcp  (staging — same shape)
```

Setup has two steps, and the app's **Connect dialog → Plugins tab** does both for
you (per-client payloads with the token filled in, a "Create token" button, copy
buttons). By hand:

1. **Mint a durable agent token** — `POST /v1/workbooks/:id/tokens` with
   `kind: "agent"` (owner session, or a token with `admin: [tokens]`; see
   [Authentication](#authentication) and [`admin-api.md`](./admin-api.md)):

   ```bash
   curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/tokens" \
     -H "Authorization: Bearer $OWNER_TOKEN" -H 'Content-Type: application/json' \
     -d '{ "kind": "agent", "label": "cursor" }'
   # → 201 with the raw `wbt_` secret in `token` — shown exactly once.
   ```

   The token is durable: paste it into the client's config file (never into a
   chat), and revoke + re-mint it on the Keys tab (`DELETE …/tokens/:tokenId`) if
   it ever leaves your control.

2. **Configure the client.** The per-client config files, exactly as the Connect
   dialog hands them out (substitute your workbook id and token):

   **Cursor** — add to `~/.cursor/mcp.json`:

   ```json
   {
     "mcpServers": {
       "workbook": {
         "url": "https://mcp.workbook.run/w/wb-YOUR-ID/mcp",
         "headers": { "Authorization": "Bearer wbt_…" }
       }
     }
   }
   ```

   **Obvious.ai** — the same remote `mcpServers` shape (a hosted URL plus the
   Authorization header the per-request bearer check verifies) in its MCP client
   settings. Obvious.ai is a first-class client: every workbook's Connect dialog
   carries a ready-made payload for it.

   **Claude Desktop** — remote connectors are sign-in based with no custom-header
   facility, so the bearer rides the documented `mcp-remote` bridge (Node
   required). Add to `claude_desktop_config.json` (Settings → Developer → Edit
   Config):

   ```json
   {
     "mcpServers": {
       "workbook": {
         "command": "npx",
         "args": [
           "-y",
           "mcp-remote",
           "https://mcp.workbook.run/w/wb-YOUR-ID/mcp",
           "--header",
           "Authorization: Bearer wbt_…"
         ]
       }
     }
   }
   ```

   **Codex** — a streamable-HTTP server block. Add to `~/.codex/config.toml`:

   ```toml
   [mcp_servers.workbook]
   url = "https://mcp.workbook.run/w/wb-YOUR-ID/mcp"
   http_headers = { "Authorization" = "Bearer wbt_…" }
   ```

   **ChatGPT** (and claude.ai) — their remote-MCP setup is sign-in (OAuth) based
   with no custom-header facility, so bearer-token setup is not supported yet;
   the Connect dialog says so in place of a payload.

Against staging, set the URL's host to `mcp.staging.workbook.run` — same path
shape. Verify the setup by asking the client to list the workbook's tables
(`run-wb tables` is the CLI equivalent).

## Core CRUD: tables, rows, queries

All of the below lives on the workbook VM host with a claims header. Reads require
`read` on the table; writes require `write`.

**Tables** — list `GET /api/tables`, read one `GET /api/tables/:table` (the
`TableContract`), create `POST /api/tables` (`{name, columns}` — names are unquoted
MySQL-identifier-shaped, ≤ 64 chars; columns carry `key`, `type`
(`string|number|boolean|date|json|enum|vector`), optional `required`, `enumValues`,
`searchable`, `embed`), patch `PATCH /api/tables/:table` (`addColumns`, `dropColumns`,
`renameColumn`, `changeType`, `updateColumns`), and `DELETE /api/tables/:table`.

**Rows** are batch routes keyed by the hidden `_wb_id` ULID (assigned on insert when
omitted), all idempotent under `clientOpId`:

```bash
# Update two cells and delete one row — one round trip each.
curl -s -X PATCH "https://$VM_HOST/api/tables/tasks/rows" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "changes": [ { "id": "01J…", "values": { "done": true } } ],
        "clientOpId": "op-042" }'
curl -s -X DELETE "https://$VM_HOST/api/tables/tasks/rows" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "ids": ["01J…"], "clientOpId": "op-043" }'
```

Writes apply to the working set immediately — readers see them at once — and land as
durable Dolt commits through the human commit batcher (2 s of quiet or 10 s after the
batch's first write; a batch never mixes authors). The write response reports
`pendingBatch`; fork-scoped writes return `forkId` alongside.

**Queries** — `POST /api/tables/:table/rows/query`:

```json
{
  "filter": {
    "and": [
      { "col": "done", "op": "eq", "value": false },
      { "or": [
        { "col": "title", "op": "contains", "value": "guide" },
        { "col": "title", "op": "starts", "value": "Ship" }
      ] }
    ]
  },
  "sort": [{ "key": "title", "dir": "asc" }],
  "limit": 100,
  "cursor": "eyJ…",
  "columns": ["_wb_id", "title", "done"],
  "asOf": "2026-09-29T12:00:00Z"
}
```

The filter grammar is recursive `and` / `or` / `not` over conditions
`{col, op, value}`; operators are `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in`, `nin`,
`contains`, `starts`, `ends`, `is_null`, `not_null`, `between`, `tagged`. Identifiers
are validated against `information_schema` and compiled to parameterized SQL — never
interpolated. Paging is keyset: prefer `cursor` (from the response's `cursor`) over
`offset`; `limit` caps at 1000. `fork` scopes the read to a fork branch (field or
`?fork=`), and `asOf` time-travels to a Dolt commit hash or ISO timestamp. The response
is `{ "rows": […], "total": …?, "cursor": …? }`.

Dashboard-grade reads ride the same surface:
`POST /api/tables/:t/aggregate` (`{fn, column?, filter?}` → `{value}`) and
`POST /api/tables/:t/group` (`{by, filter?, aggregates?, summaryOnly?}` → `{groups}`,
or `{rows}` with `summaryOnly`). Raw SQL is `POST /api/sql` — `maxRows` ≤ 10,000,
`timeoutMs` ≤ 30,000. Every row carries a hidden `_wb_id` key: a plain `INSERT`
must include it in the column list as a 26-character ULID — the row commands and
import mint it for you when you don't.

## The fork write path

Fork/merge is the only agent edit path. A fork is a Dolt branch; merges land as change
sets that are reviewable, reversible, and diffed. Forks run in `review` or `direct`
mode; open and proposed forks accept writes, merged/dropped/conflicted forks reject
them (`409`).

```bash
# 1. Open a fork.
FORK_ID=$(curl -s -X POST "https://$VM_HOST/api/forks" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "mode": "review", "label": "cleanup pass", "table": "tasks" }' \
  | jq -r .fork.id)

# 2. Write on it — the same row routes, scoped with ?fork=.
curl -s -X PATCH "https://$VM_HOST/api/tables/tasks/rows?fork=$FORK_ID" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "changes": [ { "id": "01J…", "values": { "done": true } } ],
        "clientOpId": "fk-1" }'

# 3. Propose (review mode): computes the change set and waits for review.
#    Re-proposing after adjustments updates the diff instead of 409.
CHANGE_SET_ID=$(curl -s -X POST "https://$VM_HOST/api/forks/$FORK_ID/propose" \
  -H "X-WB-Claims: $CLAIMS" | jq -r .changeSet.id)

# 4. Review the diff (first 50 rows per table: added rows carry full data,
#    removed rows the pre-diff data, modified rows cell → {from, to}).
curl -s "https://$VM_HOST/api/change-sets/$CHANGE_SET_ID/diff" -H "X-WB-Claims: $CLAIMS"

# 5. A different actor — a human, or another token with the grant — approves, or
#    rejects, the change set. The proposer cannot approve its own: the door answers
#    403 naming the author. If nobody is available to review, write main directly
#    (the proposer's own branch choice) instead of proposing.
curl -s -X POST "https://$VM_HOST/api/change-sets/$CHANGE_SET_ID/approve" \
  -H "X-WB-Claims: $APPROVER_CLAIMS"
```

In `direct` mode you skip the review gate: `POST /api/forks/:id/merge` returns either
`{ "status": "merged", "commit": "…", "changeSet": {…} }` or
`{ "status": "conflict", "conflicts": […] }`. Conflicts are detected at propose
time too — a proposed change set carries its conflicts in the response — and resolved
**on the fork**, per cell. `GET /api/forks/:id/conflicts` lists `{table, rowId, column,
base, current, draft}` (`current` is main's value, `draft` the fork's), then
`POST /api/forks/:id/conflicts/resolve` with `{rowId, column, take, value?}` where
`take` is `current` | `draft` | `value` (legacy `ours`/`theirs` accepted; bulk form:
omit `rowId`/`column` to apply one take to every unresolved cell, optionally
restricted to one `table`). Resolving the last conflicted cell returns the change set
to `proposed` for a different approver — it does not merge in the same call.

History is append-only. `GET /api/history` pages keyset-style (opaque `cursor`,
`limit` ≤ 500 default 100, filters `table` / `author` / `changeSetId` / `since` /
`until`); row-level lineage is `GET /api/tables/:t/rows/:id/history`; `POST /api/revert`
(`{hash}`) rolls back to before a commit **as a new commit**. A fork idle for 24 h
shows `stale: true` (proposed forks also show stale). Abandon one with
`DELETE /api/forks/:id`.

## Search

Hybrid search composes full-text and vector predicates against the same table through
one route; ranking fuses both sides with reciprocal-rank fusion over the DuckDB mirror
(BM25 + cosine over unit-normalized vectors).

```bash
curl -s -X POST "https://$VM_HOST/api/search" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{
        "table": "tasks",
        "text": "shipping checklist",
        "vector": { "column": "title", "query": "release notes" },
        "filter": { "col": "done", "op": "eq", "value": false },
        "limit": 20
      }'
```

- `text`, `vector` (`{column, query? | embedding?}`), or both (hybrid) — at least one
  is required.
- `limit` ≤ 100, default 20.
- Response: `{ "hits": [{ "rowId", "column", "snippet", "score", "rowIndex"? }] }` —
  `score` is the BM25 score (text), cosine similarity (vector), or the fused RRF score.

Vector columns are embedded at write time when created with `embed: true`; rebuild and
backfill explicitly with `POST /api/search/index` (`{table}` — needs `write`), which
returns `{index: {synced, embedded, model, dims}}`.

## Realtime

One event stream per workbook, served by the workbook's Durable Object behind the
edge. Everything below is the same over WebSocket or the plain-HTTP polling fallback.

```
GET /api/events?after=<seq>&token=<wbt_…>        # on the workbook's host
Upgrade: websocket
```

Auth on the upgrade (a WS upgrade cannot carry custom headers): `?token=<wbt_…>`,
`Authorization: Bearer <wbt_…>`, or the claims envelope via `?claims=`. A presented
token that fails verification is final — the envelope path only opens when no token was
offered. No credential → `401 unauthenticated`.

**Replay-or-resync handshake.** Connect with `?after=<seq>` — the last seq you
processed. At connect time the server sends one of:

- `{"kind": "hello", "latest": <seq>}` — your cursor is inside the replay window;
  buffered events follow immediately as `event` messages, then live events.
- `{"kind": "resync", "latest": <seq>}` — your cursor predates the replay window
  (the ring, bounded at 10,000 events, has advanced past it). No events follow;
  refetch state (a full `rows/query`) and resume from `latest`.

`after=0` (or omitted) is always answerable: it replays the whole current ring.

**Wire protocol.** Every server message is exactly one of `hello`, `resync`, `event`,
`pong` (discriminated on `kind`); the only client message is
`{"kind": "ping"}` → `{"kind": "pong"}` (answered without waking the DO). The event
envelope:

```json
{
  "seq": 1284,
  "commit": "<dolt hash>",
  "at": "<iso>",
  "type": "rows.changed",
  "actor": "agent:tok_…",
  "data": {}
}
```

`seq` is the per-workbook monotonic cursor and doubles as the resume token
(`?after=<seq>`); the Dolt commit hash is the consistency marker. Event types:
`rows.changed`, `commit.created`, `schema.changed`, `fork.opened`, `fork.proposed`,
`fork.merged`, `fork.conflicted`, `fork.dropped`, `change_set.approved`,
`change_set.rejected`, `endpoint.deployed`, `endpoint.deleted`, `validation.updated`,
`dashboard.updated`, `job.progress`, `job.finished`, `backup.finished`,
`restore.drilled`, `backup.restored_in_place`, `presence.updated`, `comment.added`,
`workbook.sleeping`, `workbook.waking`, `workbook.awake`,
`workbook.deletion_scheduled`.

**Scope redaction at fan-out.** Every event is filtered per socket against that
socket's scope: an event referencing a table the token cannot read arrives reduced to
`{"table": "<name>", "count": <n>}` (or `{"tables": […], "count": <n>}`) — row payload
fields are dropped, never merely hidden. `_wb_*` system tables are readable by every
token. The same filter is applied identically on the HTTP resume path.

A client that keeps the cursor and resumes is fully caught-up after restarts and
network drops:

```ts
// Minimal resilient event-stream client. Runs anywhere the WHATWG WebSocket
// global exists (browsers, Node 22+, Bun, Deno).
type ServerMessage =
  | { kind: 'hello'; latest: number }
  | { kind: 'resync'; latest: number }
  | { kind: 'pong' }
  | { kind: 'event'; event: WbEvent };

interface WbEvent {
  seq: number; // per-workbook monotonic cursor — the resume token
  commit: string; // Dolt commit hash — the consistency marker
  at: string;
  type: string;
  actor: string;
  data: Record<string, unknown>;
}

export async function followWorkbook(
  workbookHost: string,
  token: string,
  onEvent: (event: WbEvent) => void,
  onResync: () => Promise<void>,
): Promise<never> {
  let cursor = 0; // last seq processed; sent back as ?after= on every connect
  for (;;) {
    const socket = new WebSocket(
      `wss://${workbookHost}/api/events?after=${cursor}&token=${encodeURIComponent(token)}`,
    );
    try {
      await new Promise<void>((resolve, reject) => {
        socket.onopen = () => resolve();
        socket.onerror = () => reject(new Error('unavailable'));
      });
      const ping = setInterval(() => socket.send('{"kind":"ping"}'), 30_000);
      try {
        for (;;) {
          const message = await new Promise<MessageEvent>((resolve, reject) => {
            socket.onmessage = (m) => resolve(m);
            socket.onclose = () => reject(new Error('closed'));
            socket.onerror = () => reject(new Error('errored'));
          });
          const msg: ServerMessage = JSON.parse(String(message.data));
          if (msg.kind === 'event') {
            cursor = msg.event.seq;
            onEvent(msg.event);
          } else if (msg.kind === 'resync') {
            // Ring moved past the cursor: refetch state, resume from latest.
            cursor = msg.latest;
            await onResync();
          }
          // 'hello': replay events follow immediately — nothing to do.
          // 'pong': keepalive answer — nothing to do.
        }
      } finally {
        clearInterval(ping);
      }
    } catch {
      // Unavailable or closed — brief backoff, reconnect from the last cursor.
      await new Promise((resolve) => setTimeout(resolve, 1_000));
    }
  }
}
```

**Polling fallback.** The same path answers plain HTTP when you cannot hold a socket
open (omit the `Upgrade` header):

```bash
curl -s "https://$VM_HOST/api/events?after=$LAST_SEQ&token=$AGENT_TOKEN"
# → { "events": […], "resync": false }
```

Resume from the last seen `seq`; when the response carries `"resync": true` your cursor
predates the ring — refetch state and start over from the latest.

## Endpoints and actions

Endpoints are Python functions or saved parameterized SQL, deployed from the `/work`
directory and pinned to a code commit SHA.

```bash
# Deploy a Python endpoint — the path MUST begin with / (the /e address and the
# runner follow the record): /rollups/hourly-shape, ≤ 200 chars.
curl -s -X POST "https://$VM_HOST/api/endpoints" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{
        "path": "/rollups/hourly",
        "kind": "python",
        "source": "def handler(req):\n    return [{\"total\": 1}]\n",
        "contract": { "shape": "table" },
        "auth": "token"
      }'

# Invoke it: POST with a params body, or GET for parameter-free reads.
curl -s -X POST "https://$VM_HOST/e/rollups/hourly" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "params": { "minimum": 10 } }'
# → { "contract": {…}, "rows": [ … ] }
```

Rules the contracts enforce at deploy time:

- `path` — leading slash, no trailing slash, URL-path safe (`/rollups/monthly`
  shape), ≤ 200 chars.
- `kind` — `python` (requires `source`) or `sql` (requires `sql`; `:name` parameter
  placeholders).
- `contract` — `shape: 'table' | 'json' | 'html'` (default `table`), optional declared
  `columns`.
- `auth` — `token` (default) or `public`; `public` invocation is gated by the edge to
  published workbooks and rate-limited there.
- `entry` — named function to call; defaults to `handler`, then the `@endpoint`
  registry.

**Invocation responses are rows-array shaped.** The VM normalizes every result to
`{contract, rows}` for table reads: whatever the handler returns must be an array of
row objects, an object with a `rows` array, or the SQL result shape
`{result: {rows}}` — anything else is a `500` (`endpoint returned a non-tabular
result`). With `GET /e/<path>?html=1` the VM returns `{contract, rows: [], html}` —
and `409` when the endpoint did not return an HTML page.

Python endpoints run on a warm worker pool (two workers per endpoint by default, 30 s
invocation budget, 10 MB response ceiling, idle expiry), one virtualenv per source SHA
(uv or venv+pip when `requirements.txt` is present), as a dedicated OS user — handler
code never runs inside wb-api itself. The worker calls your `handler(req)` with the
invocation body; `print()` output lands in the endpoint log ring
(`GET /api/endpoints/:path/logs`); module state is cached per file so consecutive
invocations reuse warm state, while a redeploy materializes under a new SHA and
imports fresh.

```python
# Deployed with POST /api/endpoints: kind "python", path "/rollups/hourly".
# The VM calls handler() with the invocation body — {"params": {...}} for a
# POST /e/<path> — and the return must be tabular: a list of row objects or
# {"rows": [...]}. Non-tabular results are a 500.
def handler(req):
    params = req.get("params", {})
    minimum = params.get("minimum", 0)

    # Workbook tables are reachable from endpoint code through the injected
    # `workbook` client (`from workbook import db`); print() goes to the
    # endpoint log ring, never to the protocol channel.
    rows = [
        {"hour": "2026-09-29T10:00", "total": 42},
        {"hour": "2026-09-29T11:00", "total": 57},
    ]
    return {"rows": [row for row in rows if row["total"] >= minimum]}
```

Endpoints update in place via `PATCH /api/endpoints/:path` (replacement `source` /
`sql`, `contract`, `auth`, or `entry` — path and kind are fixed; an empty patch is a
client error; blank content is refused) and `DELETE /api/endpoints/:path`. SQL
endpoints are invoked the same way — the body's `params` fill the saved query's
`:name` placeholders.

**Actions** bind an endpoint to a table so it can run against selected rows:

```bash
curl -s -X POST "https://$VM_HOST/api/actions" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "table": "tasks", "name": "Normalize titles", "endpoint": "/rollups/hourly", "bulk": false }'

# Run against chosen rows (all rows when rowIds is omitted); the action executes
# in the caller's merge mode, so a fork-scoped caller proposes like any write.
curl -s -X POST "https://$VM_HOST/api/actions/$ACTION_ID/run" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "rowIds": ["01J…"] }'
```

Endpoint code that needs credentials reads them from the secrets API —
`POST /api/secrets` (`{name, value}`; write-only, names only out of
`GET /api/secrets`).

## Dashboards, including page-kind HTML pages

A dashboard spec is a discriminated union on top-level `kind`; specs without `kind`
parse as `'widgets'`, so legacy clients and stored rows keep working.

**Widget specs** (`kind: 'widgets'`) are declarative JSON: a 12-column `layout` plus
typed widgets — `metric`, `chart`, `table`, `map`, `markdown`, and the `html` widget
(agent-authored HTML in a sandboxed iframe). Widget data flows through the same
read routes as everything else — `aggregate` and `group` for table-backed widgets,
`rows/query` for tables — which is exactly why a published dashboard renders entirely
through `/p/…`.

**Page specs** (`kind: 'page'`) are the agent-authored escape hatch: one hand-written
HTML page served by an endpoint, for bespoke layouts and data stories the widget
vocabulary cannot express.

```bash
# The page document is endpoint-served: GET /e/<path>?html=1 returns the HTML.
# Declare the tables the page renders from — the mint intersects this list with
# the viewer's grants, so an empty declaration can never mint a token.
curl -s -X POST "https://$VM_HOST/api/dashboards" \
  -H "X-WB-Claims: $CLAIMS" -H 'Content-Type: application/json' \
  -d '{ "name": "Ops page", "spec": { "kind": "page", "endpoint": "/rollups/hourly",
        "tables": ["tasks"] } }'

# Any verified viewer mints a short-lived page token for rendering.
curl -s -X POST "https://$VM_HOST/api/dashboards/$DASHBOARD_ID/page-token" \
  -H "X-WB-Claims: $CLAIMS"
# → { "token": "wbp_…", "expiresAt": "…" } — TTL ≤ 300 s.
```

What the page token guarantees:

- **Bound to viewer claims** — its scope is the page's declared tables ∩ the viewer's
  own read grants; a viewer who can read nothing gets `403`, and the dashboard renders
  an error card rather than a silent blank.
- **Read-allowlisted** — only `aggregate`, `group`, `rows/query`, and `search`; every
  other route class is `403` before handlers run. There is no write path reachable
  from a page token, and no fork/admin/import surface.
- **Short-lived and non-human** — HMAC-signed, TTL ≤ 300 s, `kind: 'page'` (no
  imports, no undo, no presence writes).
- **Never inside the page** — the SPA renders page HTML in a sandboxed iframe
  (`allow-scripts`, opaque origin) and the *parent* validates each data request
  against the token's allowlist and relays rows in; a compromised page has no
  credential to steal.

Dashboard CRUD: `GET`/`POST /api/dashboards`, `GET`/`PATCH`/`DELETE
/api/dashboards/:id`, plus `POST /api/dashboards/generate`. Creating requires the
owner/editor role and read on every sourced table — persisting a spec is also a data
channel — and reads are gated by the spec's source tables against your grants (a
`403` names nothing). Specs live in `_wb_dashboards` and fork/merge with the workbook.

## Publishing and embedding

Publishing flips a workbook onto the public read-only surface. The gates: the workbook
must be **claimed** (claim is session-only, within the 72-hour window) and a **payment
method on file** (publishing bills; a misconfigured billing gateway fails closed).

```bash
# Owner session or a token with admin: [publish].
curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/publish" \
  -H "Authorization: Bearer $OWNER_TOKEN"
# … and back off the public surface again:
curl -s -X POST "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/unpublish" \
  -H "Authorization: Bearer $OWNER_TOKEN"
```

Once published, anonymous viewers read through `/p/{workbookId}` — an exact method +
path allowlist; any other pair is a generic `404` (`missing`, `deleted`, and
unpublished workbooks are indistinguishable — whether a workbook exists is not public
information):

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/api/tables` | List tables — `{tables}`. |
| GET | `/api/tables/:table` | One table's schema (`TableContract`). |
| POST | `/api/tables/:table/rows/query` | Grid page query → `{rows, total?, cursor?}`. |
| POST | `/api/tables/:table/aggregate` | `{fn, column?, filter?}` → `{value}`. |
| POST | `/api/tables/:table/group` | `{by, filter?, aggregates?, summaryOnly?}` → `{groups}` (or `{rows}`). |
| GET | `/api/dashboards` | List dashboards. |
| GET | `/api/dashboards/:id` | One `DashboardSpec`. |
| GET | `/e/<path>` | Invoke a `public` endpoint (`html=1` requests the HTML rendering). |
| POST | `/e/<path>` | Invoke a `public` endpoint with `{params?}`. |

Edge order on every published request: rate limit → published gate → allowlist → sign
public claims → forward. A sleeping workbook is woken by any traffic; a caller held
during the wake gets `503` with `{"error": {"code": "waking", …}}` and a `Retry-After`
(the hold window is 25 s) — retry once the workbook is up; the published surface
forwards this as-is.

**Embedding** is iframing the published URL. Embed responses carry
`Content-Security-Policy: frame-ancestors …` from the `WORKBOOK_EMBED_FRAME_ANCESTORS`
env var (unset/`*` → `*` — a published workbook is public read-only data and embedding
it is the feature; `none` is the kill switch; otherwise a comma-separated origin
allowlist) — and never an `X-Frame-Options` header, which cannot express an allowlist.
Verified custom domains are rewritten onto the same `/p/` path.

## Branding

A brand makes every `/p` embed of a workbook look like the site it sits on: one font,
light or dark, a background, the status shades and one primary colour. There is one
brand per workbook, stored on the workbook and not in the iframe URL, so changing it
never means re-pasting a snippet. Editors and owners can read and set it (the same rule
as minting an embed), before or after publishing. Every write is audited as
`workbook.brand`.

```bash
# Read the brand ({"brand": null} means the workbook.run look).
curl -s "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/brand" \
  -H "Authorization: Bearer $OWNER_TOKEN"
# Replace it. Fields left out take their defaults.
curl -s -X PUT "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/brand" \
  -H "Authorization: Bearer $OWNER_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"mode": "system", "font": "Lora", "primary": "#345f58",
       "light": {"surface": 1, "good": 5, "warning": 5, "problem": 4},
       "dark": {"surface": 9, "good": 2, "warning": 2, "problem": 3}}'
# Reset to the workbook.run look.
curl -s -X DELETE "$CONTROL_PLANE/v1/workbooks/$WORKBOOK_ID/brand" \
  -H "Authorization: Bearer $OWNER_TOKEN"
# The CLI changes only the options given and keeps the rest.
run-wb brand set --font Lora --primary '#345f58' --dark surface=9,good=2
```

The same actions exist as `getBrand` / `setBrand` / `resetBrand` in the TypeScript SDK,
`get_brand` / `set_brand` / `reset_brand` in the Python SDK, `run-wb brand
show|set|reset`, and the MCP tools `brand_get`, `brand_set` and `brand_reset`.

| Field | Values | What it does |
| --- | --- | --- |
| `mode` | `system` (default), `light`, `dark` | `system` follows the viewer's OS. `light` and `dark` lock the embed to that mode, over any preference the viewer saved. |
| `font` | A family from the curated list (`BRAND_FONTS` in `@workbook-run/contracts`); default `Inter` | Text and the grid draw in it. |
| `primary` | `#rrggbb`; default `#6fb3a6` | The main button, focus ring, selected-cell outline, agent proposal mark and default chart colour. Its label is black or white, whichever reads better. Under 3:1 against the background the button also gets an outline. |
| `light`, `dark` | `surface` 0-10, `good` / `warning` / `problem` 0-6 | `surface` is a step on a white-to-black scale; cards, borders and text follow from it. The status steps change only how light a status colour is, never its hue. A step that would be unreadable on the surface is moved to the nearest readable one when the embed renders. |

A refused brand answers `422 validation_failed` naming the field ("Pick a font from the
list", "Use a colour like #345f58") and stores nothing. A caller without editor rights
gets `403`.

What an embed viewer gets:

- **Painted before first paint.** The edge writes the brand into the `/p` page it
  serves: one `<style id="wb-brand">` built only from fixed role names and validated
  colours, and, for a locked mode, `data-wb-theme-lock` on `<html>`. An unbranded
  workbook's page is unchanged. `GET /p/{workbookId}/meta` returns
  `{"workbook": …, "brand": …}`, where `brand` is the resolved brand or `null`.
- **Fonts from the embed's own origin.** The font is served through
  `/fonts/css2?family=<family>` and `/fonts/files/…` on the host the embed loads from,
  verified custom domains included, so a viewer's browser never contacts Google. Families outside the list are `404`.
- **Never blank.** The grid waits up to 1.5 s for the font, then draws in the system
  font stack.
- **What a brand never changes:** the `frame-ancestors` policy, the read-only and
  attribution labels, the review notice on edit grants, and the status hues.

## Rate limits and budgets

| Limit | Value | Where |
| --- | --- | --- |
| Published-surface rate limit | 60 requests/min per IP per workbook; over-limit is `429` with `Retry-After` | edge, `public.routes.ts` |
| Anonymous workbook-create throttle | server-side fixed window | edge admin router |
| Event replay window | 10,000 events per workbook; older cursors get `resync` | DO lifecycle |
| Claims envelope TTL | 300 s (re-exchange before `exp`) | edge admin claims |
| Rows query page size | `limit` ≤ 1000 | contracts `query.ts` |
| SQL `maxRows` / `timeoutMs` | ≤ 10,000 rows / ≤ 30,000 ms | contracts `query.ts` |
| Search `limit` | ≤ 100, default 20 | contracts `search.ts` |
| Import payload | 2 GiB cap (2147483648 bytes) | contracts `imports.ts` |
| Upload signing TTL | `expiresInSec` 30–3600, default 900 | contracts `uploads.ts` |
| Table / column names | MySQL unquoted-identifier shape; table ≤ 64 chars | contracts `api.ts` |
| Endpoint path | ≤ 200 chars, `/rollups/monthly` shape | contracts `endpoints.ts` |
| Share / token labels | ≤ 120 chars | contracts `shares.ts`, `admin.ts` |

## Errors

Every failure on every surface is one shape:

```json
{ "error": { "code": "rate_limited", "message": "…", "requestId": "…" } }
```

`code` is the `ApiErrorCode` union: `unauthenticated`, `forbidden`, `not_found`,
`conflict`, `merge_conflict`, `validation_failed`, `rate_limited`, `quota_exceeded`,
`payment_required`, `query_timeout`, `result_too_large`, `waking`, `unavailable`,
`workbook_deleted`, `sql_error`, `internal`.

The two availability behaviors to build against:

- **`429 rate_limited`** carries `Retry-After` — wait the indicated interval and retry.
- **`503 waking`** also carries `Retry-After` — the wake continues in the background;
  the same request succeeds once the workbook is up.

Access denials are `404` where they would leak existence (unpublished or missing
workbooks, non-public endpoints under public claims, another user's API key) and `403`
where the caller demonstrably has context. Validation failures are
`422 validation_failed` with the contract's issue list in `details`; a non-tabular
endpoint result is a `500` naming the problem.

## Provenance

Every claim above traces to the reference docs or the contracts they are generated
from — nothing in this guide is sourced from live probes:

| Section | Sources |
| --- | --- |
| Surfaces, quickstart, publish gates | `docs/public-api.md`, `docs/admin-api.md`, `contracts/src/admin.ts` (anonymous create, claim), `.github/workflows/ci.yml` (`WORKBOOK_VM_ORIGIN` template) |
| Claims exchange and envelope | `apps/edge/src/admin/index.ts`, `contracts/src/claims.ts`, `services/vm/src/claims.ts` |
| wbk_ keys, share links, credential precedence | `docs/admin-api.md`, `contracts/src/{api-keys,shares}.ts`, `apps/edge/src/api-keys/format.ts` |
| Tables / rows / queries / SQL | `services/vm/src/app.ts` (route registrations), `contracts/src/{api,query}.ts`, `services/vm/src/batcher.ts` |
| Forks, change sets, history | `contracts/src/forks.ts`, `services/vm/src/forks.ts`, `services/vm/src/rows.ts` |
| Search | `contracts/src/search.ts`, `services/vm/src/app.ts` |
| Realtime | `docs/public-api.md` (event stream), `services/vm/src/app.ts`, `apps/edge/src/do/workbook-do.ts` |
| Endpoints, actions, invocation shapes | `contracts/src/endpoints.ts`, `services/vm/src/app.ts` (`normalizeInvocationResponse`), `services/vm/src/endpoint-runner.ts`, `services/vm/python/endpoint_worker.py` |
| Dashboards and page tokens | `contracts/src/dashboards.ts`, `services/vm/src/page-token.ts`, `services/vm/src/app.ts`, `docs/internal/page-kind-dashboards.md` |
| Published surface, embed CSP | `docs/public-api.md`, `apps/edge/src/public/{public.routes,embed,rate-limit}.ts` |
| Limits and error shapes | `docs/public-api.md` §Limits / §Error shape, `contracts/src/api.ts` |
