SDK

Every page on OpenBelt can import /sdk.js (from the root, so the same line works in a page in any folder). It works on the app the page belongs to (the first segment of the page's path), with no keys or setup:

<script type="module">
  import { db } from "/sdk.js"

  const cards = db.collection("cards")
  const card = await cards.add({ title: "Ship login", column: "todo" }) // { id, data, seq, ... }
  await cards.update(card.id, { column: "doing" }) // move it: merge fields in
  await cards.delete(card.id)
  await db.collection("votes").set("ada", { place: "tacos" }) // your own id: one per person
  cards.watch((docs, change) => render(docs)) // every card now, then again after each change
</script>

Documents

Importing documents over MCP

For imports and seed data, call collection_add with docs: [{ data }, ...] in groups of 100, up to 500 per call. Use one call per group instead of a loop of single-document calls or Promise.all of individual writes. The browser SDK's add(data) still writes one document.

{
  "app": "board",
  "collection": "cards",
  "docs": [
    { "id": "import-1", "data": { "title": "Ship login" } },
    { "id": "import-2", "data": { "title": "Write release notes" } }
  ]
}

Each group is one transaction: all documents are written or none are. The result contains written and docs with each document's id and seq. If a later group fails, earlier groups remain. Stop on a refusal, fix it, and resume from the failed group. After a lost response, read back the supplied ids before retrying; an import with generated ids can duplicate documents. Do not wait to accumulate a batch for a person's interactive write.

Using another app's data

Apps in a workspace can read each other's data. Start with search for what you need: the apps that match, with their matching collections. app_info gives one app's collections in full: about (what a document holds, from its openbelt.json), docs, lastWrite, writable, rules and the newest document of each as a sample. An openbelt.json description is the contract; a sample is one document, not a promise about the rest. With no about, read the app with app_files before you rely on a field.

import { db } from "/sdk.js"

const votes = db.app("lunch").collection("votes") // the same API as db.collection()
votes.watch((docs) => render(docs)) // get, list, subscribe, watch

await db.apps() // [{ app, title, url, description, owner, env }]
await db.app("lunch").collections() // [{ name, about, docs, lastWrite, writable, rules }]

Files

Pictures, PDFs, videos and other files people upload go to files, not into documents (a document is at most 64 KB). Keep the file's record in a document, and use its url wherever the file is shown:

import { db, files } from "/sdk.js"

input.onchange = async () => {
  const file = await files.put(input.files[0]) // { id, url, name, type, size, sha256 }
  await db.collection("photos").add({ file, caption: "" })
}

db.collection("photos").watch((docs) => {
  grid.innerHTML = docs.map((d) => `<img src="${d.data.file.url}" alt="">`).join("")
})

await files.delete(file.id) // the bytes and the record; the workspace gets the room back

An agent adds files the same way without a page, in this order: deploy the app (files belong to an app, so it must exist), upload the files, then write the documents that name them (collection_add, each with the answer or its url, which is what an <img> or a link uses):

What the app shows or opens as content (photos, receipts, PDFs, screenshots to review, whether a person or you add them) goes in files: it comes back with its type, so a PDF opens in the browser. What makes the app itself (its logo, icons, fonts) is deployed with its files.

Maintained counts and integer totals: db.aggregate

Declare dashboard totals in openbelt.json. OpenBelt backfills existing records on the first read and maintains the totals in the same transaction as every source write, including server functions, MCP writes and imports. Pages do not update a separate totals document.

{
  "aggregates": {
    "expense-count": { "collection": "expenses", "op": "count" },
    "expense-total": { "collection": "expenses", "op": "sumInteger", "field": "cents" }
  }
}
const total = await db.aggregate("expense-total")
// { count: 42, value: 12345, approximate: false }
const stop = db.aggregate("expense-total").watch(render, { onError: console.error })
stop()

count returns the number of source documents in value. sumInteger sums a top-level field; every visible source record must contain a safe integer there. Missing, fractional, nonnumeric and unsafe integer values refuse the sum. Counts still work. Store money as integer cents. count in either result is the number of visible source documents.

The collection's read rule controls the result: anyone, signedIn, nobody, or doc.author == me (also me == doc.author). Owner totals include only the viewer's records. Other read expressions refuse the aggregate; read the source records for those queries. There are no aggregate writes or separate permissions to keep in sync.

An app declares at most 16 aggregates. Names follow collection names. Fields are identifiers of 1–64 letters, digits or underscores, beginning with a letter or underscore. Aggregates support counts and integer sums, without filters or grouping. This API is in the browser SDK, including db.app(other).aggregate(name) for another app; server functions keep using source collections.

Large intermediate totals fall back to a source scan with integer arithmetic. If the final total exceeds JavaScript's safe integer range, approximate is true and value may be rounded. Deleting or correcting records restores an exact result when its value fits. The first read scans the collection and uses storage; later reads use maintained per-author totals unless that fallback is needed. More distinct authors and declared aggregates add storage and write work.

Watches use the same reconnect and error handling as db.query().watch. Writes are coalesced for 25 ms before a watched total is refreshed. Preview environments have separate totals over their own records. Removing or changing a declaration discards its old derived state; it never changes the source records.

Functions: db.fn and db.query

const { counts } = await db.fn("vote", { option: "tacos" }) // this app's functions/vote.js
await db.app("poll").fn("vote", { option: "tacos" }) // another app's function, as this app
const stop = db.query("totals").watch((totals) => render(totals)) // a query, live

db.fn(name, input, { key }) runs one of the app's functions for whoever is viewing and resolves to what it returns; a failure rejects with code "function_failed" (or "bad_input"). It rejects with "invalid" (400) when it's called with a key and nobody is signed in (signed out, every visitor would share the key), and (413) when its input is over 100 KB. db.query(name, input) runs a "kind": "query" function: await it, or .watch(cb, { onError }) for each new result (it returns a stop function). Keys and writing them: Functions.

Connections: tools.call

A page calls the workspace's connections (MCP servers like Linear or DeepWiki, Connections) with tools, for whoever is viewing it. OpenBelt holds every token and decides each call; the page never sees a token. List each tool the app's pages call in its openbelt.json "tools", and whose credential it runs with:

{
  "description": "My open issues, and ask DeepWiki about a repo",
  "tools": {
    "linear.list_issues": "viewer",
    "deepwiki.ask_wiki_question": "workspace"
  }
}
import { tools } from "/sdk.js"

try {
  const issues = await tools.call("linear.list_issues", { assignee: "me" })
  render(issues.structuredContent ?? JSON.parse(issues.text)) // { text, content, structuredContent, runsAs, ms, trace }
} catch (e) {
  if (e.code === "needs_token" || e.code === "needs_consent")
    show("Connect Linear to see your issues")
  else show(e.message) // not_allowed, signed_out, ...: the message says why and what to do
}

await tools.list() // [{ tool, binding, usable, description, input, runsAs | code, message, fix, url }]

Errors

A failed call rejects with an Error that has status, code and trace; its message says what to change and ends with (trace <id>). Branch on e.code, one word ("invalid", "denied", "missing", "conflict", ...), not on the message, whose wording changes. Bad names, ids and parameters are a 400. A write openbelt.json rules refuse is a 403 with code "denied", rule ("rules.polls.update") and the rule in the message (for an && chain, the clause that failed); it isn't reported as a browser error. When this OpenBelt can't read the app's openbelt.json (it was rolled back to an older version), every read and write is that 403, with rule "openbelt.json": deploy the app again. A 409's seq is the document's current one.

Every code

Sign-in

db.me(): Who is viewing.

Examples

watch() with an error handler. It subscribes first, then reads, so a write that lands during the read isn't missed or counted twice. Added documents come first; updated ones keep their place.

const stop = db.collection("bugs").watch(
  (docs, change) => render(docs), // change is null the first time, then { op, doc }
  { onError: (error) => showError(error.message) }, // without it, the console hears
)

Each person signs up for a slot once; a second sign-up by the same person is refused:

try {
  await signups.set(slot + ":" + me.email, { slot }, { ifSeq: 0 })
} catch (e) {
  if (e.status !== 409) throw e // 409: already signed up; e.seq is that document's seq
}

Reading a collection a page at a time:

let cursor = null
do {
  const page = await posts.list({ limit: 1000, cursor })
  show(page.docs)
  cursor = page.cursor
} while (cursor !== null)

The cursor is opaque: pass it back as it came. A limit over 1000 is a 400, not a silent cap.

Realtime and preview environments

The SDK keeps one WebSocket to the app (/_ws on its host), and one to each other app a page subscribes to or watches. When it drops, it reconnects within a second and first replays what it missed, in order: each changed document's latest version once (an add if it's new, else an update), and each delete. When a new version of the page's own app goes live, the page updates in place if only its linked stylesheets or the text of its <title>, <style> or elements with an id changed, keeping what was typed, its scripts' state and the scroll. Anything else (a script, an element added or moved, another file) reloads it, and so does a page whose viewer was removed from the workspace (it then shows why: People and groups). Give text an agent may edit an id to keep it in place. It also reloads, once, when it reconnects after OpenBelt itself was updated with a new /sdk.js. When a viewer turns Auto-update off for this app in its sidebar (saved per account), deploys hold off instead of updating automatically and show an Update available toast with Later and Reload; forced reloads (access revoked, preview reset, data compacted) still happen right away. A tab hidden for 5 minutes closes its sockets, so an app nobody is looking at can sleep; shown again, it reconnects and replays what it missed the same way. Live updates pause while it's hidden: code that has to act on a change with nobody looking belongs in a trigger or a schedule, not a page.

Under /_preview/<env>/ every call uses that environment's data, and the socket hears only its changes. Nothing in the page has to change; it can tell where it is:

import { env, appUrl } from "/sdk.js"

env // "triage" in the triage environment, null on the live app
link.href = appUrl("home") // "https://home.acme.../_preview/triage/" if home is in triage, else "https://home.acme.../"

There the SDK first asks which apps are in the environment (one request as the module loads), so appUrl() answers at once. The page updates in place or reloads, as above, when its app gets a new version in the environment, and reloads when the environment's data is reset (preview_reset) or deleted. See Apps.

On the public host (<app>--<workspace>.<public host>) the same page works for anyone, with what its openbelt.json public lists: db.me() is null, appUrl("home") is "https://home--acme.<public host>/" (a 404 unless home is public too), and db.app(), files and tools.call are refused. See Apps.

Theme

The person's OpenBelt theme, "light" or "dark" (with System, the device's, as it changes):

import { theme } from "/sdk.js"

theme.current // "dark"
const stop = theme.watch((t) => chart.setTheme(t)) // now, then on each change

OpenBelt also puts it on the page's root before it paints, <html data-theme="dark">, unless the page has its own data-theme: CSS can use :root[data-theme="dark"] with no script. See Apps.

Device

The device's location, camera and microphone, share sheet, and keeping the screen on. Use device, not the browser's own calls: in the workspace's app frame the browser gives an app none of them (Who is viewing), and device works there and everywhere else.

import { device } from "/sdk.js"

const here = await device.location() // { latitude, longitude, accuracy, altitude, heading, speed, timestamp }
video.srcObject = await device.media({ video: { facingMode: "environment" } }) // a MediaStream
await device.share({ title: "Lunch", url: location.href }) // from a tap: the device's share sheet
const awake = await device.wakeLock() // the screen stays on while the app shows, again after you come back; awake.release()

Desktop

Progressive desktop capabilities when someone installs the app through OpenBelt Desktop (transparent floating windows, click-through overlays, menu bar HTML popovers that stay alive in the background, start at login, global shortcuts, native notifications, screen/region capture and system clipboard). In a regular browser or browser PWA, desktop.available is false and every call resolves with { ok: false, error: "BROWSER_MODE" } instead of throwing.

import { desktop } from "/sdk.js"

if (desktop.available) {
  const caps = await desktop.capabilities() // e.g. ["desktop.menubar", "desktop.startAtLogin", ...]
  await desktop.setAlwaysOnTop(true)
  await desktop.setClickThrough(false)
  await desktop.setBounds({ x: 100, y: 100, width: 280, height: 280 })
  await desktop.setTray({
    title: "18:42",
    tooltip: "Focus Timer",
    menu: [{ id: "wave", label: "Wave" }], // menu is for "tray": true apps (ignored by "menuBar")
  })
  await desktop.popover.show()
  await desktop.popover.resize({ width: 340, height: 380 })
  await desktop.openWindow("/")
  const stopTray = desktop.onTrayAction((actionId) => handleAction(actionId))
  const stopKey = desktop.onShortcut("Alt+Shift+J", () => toggleMood())
  await desktop.notify({ title: "Jolly Pet", body: "Build passed" })
  const shot = await desktop.capture.region()
  const clip = await desktop.clipboard.read()
  await desktop.clipboard.write({ text: "Copied from OpenBelt" })
}

Under the hood

The SDK is plain HTTP and WebSocket on the app's host (<app>--<workspace>.<domain>), so anything can use it. Another app's routes are the same under /a/<other>/ on your app's host:

Signed-in browser requests share a per-person/workspace request allowance with that person's agents. A 429 includes Retry-After; wait before retrying. Other people behind the same office address have separate allowances, with a higher shared emergency ceiling for floods.

Source: docs/sdk.md on GitHub