# OpenBelt Documentation > Complete documentation for OpenBelt (https://openbelt.com/docs). --- url: https://openbelt.com/docs group: Start here --- > OpenBelt documentation: connect AI agents over MCP, build and host apps with /sdk.js, configure server functions and OAuth connections, or self-host. # OpenBelt OpenBelt is a workspace where AI agents build and deploy small web apps for your team over MCP. People open the apps in a browser, and agents create, test, and update them from any MCP client or the CLI. Every app is a folder of static files (HTML, CSS, and JavaScript) paired with one shared module at `/sdk.js`. That module gives each app SQLite-backed collections, live realtime sync, server functions, built-in AI, and external connections with zero build step. A deploy goes live immediately at its own URL, or lands in a named preview environment over separate test data first so you can verify changes across one or more apps before promoting them. ## Pick your path - **[Build your first app in 1 minute](/docs/quickstart)**: Connect your agent to `openbelt.com` and deploy a live team app. - **[Browse real example apps](/docs/examples)**: Explore complete apps built with collections, access rules, functions, and AI. - **[Connect your AI agent](/docs/mcp)**: Configure Claude Code, Codex, Claude, ChatGPT, or custom MCP clients with OAuth or API tokens. - **[Self-host on Docker or Tailscale](/docs/running)**: Run OpenBelt on your own server or private tailnet. ## How requests route One gateway serves every workspace and app across two host patterns: | Host | Path | Purpose | | --------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------- | | `.openbelt.app` | `/` | Workspace home: your apps and starter templates (`/?tab=starters`). | | `.openbelt.app` | `/mcp` | MCP endpoint for agents (`search`, `call`, `deploy_app`, `check_app`). | | `.openbelt.app` | `/a//` | App rendered inside the workspace frame (the URL people open). | | `.openbelt.app` | `/connections`, `/agents`, `/settings` | Personal connections, signed-in agents, and workspace settings. | | `.openbelt.app` | `/admin/...` | Admin pages for people, groups, activity, and workspace connections. | | `--.openbelt.app` | `/...` | The app's isolated origin: static files, `/sdk.js`, data (`/_db`), and realtime (`/_ws`). | | `--.openbelt.app` | `/_preview//` | Named preview environment running over isolated test data. | | `--.openbelt.app` | `/a//_db`, `/_ws` | Cross-app data and realtime access as the current viewer. | Each app runs in its own Durable Object backed by SQLite, keeping its files, versions, live and preview data, realtime sockets, and logs together. Public apps (when opted in via `openbelt.json`) serve on a separate public host (`--.openbelt.page`). ## All documentation ### Start here - **[Quickstart](/docs/quickstart)**: Connect an AI agent to OpenBelt, deploy your first live app, and iterate safely with previews. - **[Examples](/docs/examples)**: Complete, production-ready OpenBelt apps synced directly from tested starter code: tasks with server functions, live message board, and cross-app dashboard. - **[Connect an agent (MCP)](/docs/mcp)**: Connect an AI agent to OpenBelt over MCP with OAuth or an API token, plus every tool and operation it gets. - **[CLI](/docs/cli)**: Install the openbelt CLI, sign in once, configure your agents, and run workspace operations from a terminal or script. ### Building apps - **[Apps](/docs/apps)**: Deploying static web apps, preview environments, openbelt.json configuration, public apps, remixes, and agent skills. - **[SDK](/docs/sdk)**: The /sdk.js browser module for documents, aggregates, files people upload (files.put, a url for ), functions, connections, theme, device, and desktop APIs. - **[Functions](/docs/functions)**: Server-side JavaScript functions for atomic transactions, live queries, secrets, external APIs, webhooks, schedules, triggers, long jobs, and Stripe payments. - **[AI](/docs/ai)**: Built-in AI inference (ai.stream, ai.run, ai.status, ctx.ai) for streaming text, structured JSON, vision and PDFs, web search, and app function tools. - **[Access rules](/docs/rules)**: Declarative openbelt.json rules enforced by the platform on every collection read, create, update, and delete. - **[Users & auth](/docs/viewers)**: How apps identify signed-in users with db.me(), auth modes (email code, OIDC, Tailscale), multi-user testing, and app installation. - **[Debugging](/docs/debugging)**: Verify apps in a headless browser with check_app, inspect browser errors in app_logs, and trace requests end to end. - **[Code (execute)](/docs/code)**: Run short JavaScript scripts on OpenBelt with the execute tool across workspace apps, data, and connections. ### Workspaces & connections - **[Connections](/docs/connections)**: Connect MCP servers, OpenAPI specs, and GraphQL endpoints to a workspace with shared or personal OAuth credentials, per-tool access control, and app consent. - **[People & groups](/docs/people)**: Manage workspace members, roles, groups, invite-only access, offboarding, workspace renames, and SCIM 2.0 directory sync. - **[Workspace automation](/docs/workspace)**: Manage people, groups, connections, access policies, API tokens, app consent, and signed-in agents through MCP or the openbelt CLI. ### Self-hosting - **[Self-hosting](/docs/running)**: Run OpenBelt on your own server with Docker or the compiled Linux binary: DNS and HTTPS, sign-in, SQLite storage, backups, file uploads, logs, limits, and graceful restarts. - **[Run on Tailscale](/docs/tailnet)**: Run OpenBelt on macOS or Linux for your Tailscale tailnet with automatic Tailscale sign-in, safe upgrades, rollbacks, and local backups. - **[Feature flags](/docs/feature-flags)**: Every OpenBelt feature toggle and capability gate, its defaults across dev, self-hosted, and hosted deploys, and how to add a new flag. - **[Architecture](/docs/architecture)**: How OpenBelt is built: the gateway, Durable Objects on per-object SQLite files, the turn-based runtime, QuickJS sandboxes, and configuration reference. --- url: https://openbelt.com/docs/quickstart group: Start here --- > Connect an AI agent to OpenBelt, deploy your first live app, and iterate safely with previews. # Quickstart Go from zero to a live, realtime web app on `openbelt.com` in about 1 minute. Signing in creates your workspace automatically or lets you pick an existing one. ## 1. Connect your agent Pick the setup that matches where you run your AI agent. ### CLI (fastest for local agents) The `openbelt` CLI signs you in once and adds OpenBelt as an MCP server to every supported agent installed on your machine (Claude Code, Codex, Cursor, OpenCode, VS Code, Claude Desktop, pi, and more): ```sh curl -fsSL https://openbelt.com/install | sh ``` ### Claude Code Add the hosted MCP server directly and sign in via OAuth: ```sh claude mcp add --transport http openbelt https://openbelt.com/mcp ``` Then run `/mcp`, choose `openbelt`, and select **Authenticate**. ### Codex Add the MCP server and sign in: ```sh codex mcp add openbelt --url https://openbelt.com/mcp codex mcp login openbelt ``` ### Claude (web, desktop, and mobile) 1. Open the [Add custom connector dialog on claude.ai](https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=OpenBelt&connectorUrl=https%3A%2F%2Fopenbelt.com%2Fmcp) (pre-filled with `OpenBelt` and `https://openbelt.com/mcp`). 2. Click **Continue**, then **Add**, then **Connect**. 3. Sign in on the OpenBelt page that opens, then return to your chat. ### ChatGPT 1. Open `https://chatgpt.com/plugins`, click **Add**, then **Add custom MCP server**. 2. Enter **Name**: `OpenBelt` and **Server URL**: `https://openbelt.com/mcp`. 3. Confirm the prompt, click **Create as a plugin**, then **Connect OpenBelt**, and sign in on the OpenBelt page. > [!TIP] > You can also paste `Read https://openbelt.com/start.md, then help me build a tool` into any agent to walk through setup and starter apps interactively. ## 2. Build your first app Once connected, ask your agent to build a real app for your team: > Build and deploy a team standup board named `standup` where teammates post what they finished, what is next, and whether they are blocked. Updates should show up live across open tabs, and each person should only be able to edit or delete their own posts. Seed two example posts and verify the UI as two teammates. Here is what the agent does over MCP: 1. Calls `docs` to read OpenBelt's `apps`, `sdk`, and `rules` guides. 2. Calls `deploy_app` with `index.html` and `openbelt.json` (which defines the `posts` collection and owner-only write rules), then `collection_add` to seed two example posts. 3. Calls `check_app` to open the app in a real headless browser as two test teammates, checking for JS errors, failed requests, and rule denials. 4. Returns your live URL: `https://.openbelt.app/a/standup`. Open that URL in two browser tabs. Posting in one tab updates the other without a reload, and every MCP call returns a `trace` id you can inspect with `app_logs` ([Debugging](/docs/debugging)). ## 3. Iterate safely with previews When you want to change a live app without touching production data, ask your agent to deploy to a named preview environment (for example `preview: "v2"` in `deploy_app`). Previews run over isolated test data at their own URL, so your agent can verify the changes with `check_app` and you can review them in the browser. When it looks right, `promote_app` switches the live app to that version immediately while live data stays intact. ## 4. Next steps - **[Browse real example apps](/docs/examples)**: See complete apps using collections, rules, server functions, and AI. - **[Apps](/docs/apps)**: Learn about `openbelt.json`, preview environments, remixes, skills, and public apps. - **[SDK](/docs/sdk)**: Reference for `/sdk.js` collections, realtime sync, files, functions, and external connections. - **[Connect an agent (MCP)](/docs/mcp)**: Pin a client to one workspace, use API tokens in CI, or explore every MCP tool. > [!NOTE] > Running OpenBelt on your own infrastructure? Follow [Running OpenBelt](/docs/running) for Docker and Linux servers, or [OpenBelt on your tailnet](/docs/tailnet) for a private Tailscale deployment. --- url: https://openbelt.com/docs/examples group: Start here --- > Complete, production-ready OpenBelt apps synced directly from tested starter code: tasks with server functions, live message board, and cross-app dashboard. # Examples Every file below is synced straight from OpenBelt's tested starter apps (`apps/platform/starters/`), so the code stays accurate as the platform evolves. You can add any of these to a workspace in one call with `starter_add`, or copy the patterns into your own app. ## Tasks: collections, rules, and server functions Shared task list for people and agents with collection rules, a serialized `claim` server function, a scheduled `tidy` cleanup job, and a realtime UI. Add it to a workspace with `starter_add({ starter: "tasks" })`. ### `tasks/openbelt.json` Source: `apps/platform/starters/tasks/openbelt.json` ```json { "title": "Tasks", "description": "Shared tasks for people and agents: add, take, check off", "color": "#2f6fed", "icon": "list-todo", "category": "productivity", "tags": ["kanban"], "collections": { "tasks": "one doc per task: { title, done (bool), claimedBy (email of whoever is on it, or null), note (one line on what was done, or null), doneAt (ms, or null) }" }, "writable": ["tasks"], "rules": { "tasks": { "read": "anyone", "create": "signedIn", "update": "signedIn", "delete": "doc.author == me" } }, "functions": { "claim": "Claims the oldest open task nobody has taken, for the caller. input: none; returns { task: { id, title } }, or { task: null } when none is left. Safe when several agents call at once.", "tidy": { "description": "Deletes tasks done more than 7 days ago. input: none; returns { deleted }", "internal": true } }, "schedules": { "tidy": { "cron": "0 3 * * *" } } } ``` ### `tasks/functions/claim.js` Source: `apps/platform/starters/tasks/functions/claim.js` ```js export default async (_input, { db, caller }) => { if (!caller) throw new Error("sign in to claim a task") const { docs } = await db.collection("tasks").list({ limit: 1000 }) const open = docs.filter((d) => !d.data.done && !d.data.claimedBy) const task = open[open.length - 1] if (!task) return { task: null } await db.collection("tasks").update(task.id, { claimedBy: caller.email }) return { task: { id: task.id, title: task.data.title } } } ``` ### `tasks/functions/tidy.js` Source: `apps/platform/starters/tasks/functions/tidy.js` ```js export default async (_input, { db }) => { const weekAgo = Date.now() - 7 * 86400000 const { docs } = await db.collection("tasks").list({ limit: 1000 }) const old = docs.filter((d) => d.data.done && (d.data.doneAt ?? 0) < weekAgo).slice(0, 150) for (const d of old) await db.collection("tasks").delete(d.id) return { deleted: old.length } } ``` ### `tasks/app.js` Source: `apps/platform/starters/tasks/app.js` ```js import { db } from "/sdk.js" import "./prompt.js" const tasks = db.collection("tasks") const me = await db.me() const $ = (s) => document.querySelector(s) const esc = (s) => String(s ?? "").replace( /[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c], ) let byId = new Map() let names = new Map() const fromEmail = (email) => String(email) .split("@")[0] .split(/[._-]+/) .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) .join(" ") const who = (email, start) => email === me?.email ? (start ? "You" : "you") : names.get(email) || fromEmail(email) if (!me) $("#add").hidden = true async function busy(btn, work) { btn.classList.add("busy") btn.disabled = true try { await work() } catch (e) { alert(e.message) } finally { btn.classList.remove("busy") btn.disabled = false } } function row(d) { const t = d.data const meta = t.done ? t.note ? esc(t.note) : `Done by ${esc(who(d.updatedBy))}` : t.claimedBy ? `${esc(who(t.claimedBy, true))} ${t.claimedBy === me?.email ? "are" : "is"} on it` : `Added by ${esc(who(d.author))}` return `
  • ${esc(t.title)}
    ${meta}
    ${me && !t.done && !t.claimedBy ? `` : ""} ${me && d.author === me.email ? `` : ""}
  • ` } function render(docs) { byId = new Map(docs.map((d) => [d.id, d])) names = new Map( docs .filter((d) => d.authorName && !d.authorName.includes("@")) .map((d) => [d.author, d.authorName]), ) const open = docs.filter((d) => !d.data.done).reverse() const done = docs .filter((d) => d.data.done) .sort((a, b) => (b.data.doneAt ?? 0) - (a.data.doneAt ?? 0)) $("#open").innerHTML = open.map(row).join("") || `
  • Nothing open
  • ` $("#done").innerHTML = done.map(row).join("") $("#done-count").textContent = done.length $("#done-wrap").hidden = done.length === 0 } $("#add").onsubmit = (e) => { e.preventDefault() const input = $("#title") const title = input.value.trim() if (!title) return busy($("#add button"), async () => { await tasks.add({ title, done: false, claimedBy: null, note: null, doneAt: null }) input.value = "" }) } document.addEventListener("click", (e) => { const btn = e.target.closest("li [data-act]") if (!btn) return const id = btn.closest("li").dataset.id const d = byId.get(id) const act = btn.dataset.act if (act === "toggle") { const done = !d.data.done busy(btn, () => tasks.update(id, { done, doneAt: done ? Date.now() : null })) } if (act === "take") busy(btn, () => tasks.update(id, { claimedBy: me.email })) if (act === "delete") busy(btn, () => tasks.delete(id)) }) tasks.watch(render) ``` ## Messages: live threads and rules Live message board with one-level threaded replies enforced by `get(...)` collection rules in `openbelt.json` and realtime updates via `posts.watch(...)`. Add it with `starter_add({ starter: "messages" })`. ### `messages/openbelt.json` Source: `apps/platform/starters/messages/openbelt.json` ```json { "title": "Messages", "description": "A live message board people and agents post and reply on", "color": "#7c5cd6", "icon": "messages-square", "category": "communication", "tags": ["multiplayer"], "collections": { "posts": "one doc per post or reply: { text (plain text, up to 2000 chars), parent (the id of the post it replies to, or null for a post) }. Replies are one level deep: a reply's parent is always a post." }, "writable": ["posts"], "rules": { "posts": { "read": "anyone", "create": "signedIn && (newDoc.data.parent == null || (get('posts', newDoc.data.parent) != null && get('posts', newDoc.data.parent).data.parent == null))", "update": "doc.author == me && newDoc.data.parent == doc.data.parent", "delete": "doc.author == me" } } } ``` ### `messages/app.js` Source: `apps/platform/starters/messages/app.js` ```js import { db } from "/sdk.js" import "./prompt.js" const posts = db.collection("posts") const me = await db.me() const $ = (s) => document.querySelector(s) const esc = (s) => String(s ?? "").replace( /[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c], ) const fromEmail = (email) => String(email) .split("@")[0] .split(/[._-]+/) .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) .join(" ") const nameOf = (d) => d.authorName && !d.authorName.includes("@") ? d.authorName : fromEmail(d.author) function hue(s) { let h = 0 for (const c of String(s)) h = (h * 31 + c.charCodeAt(0)) % 360 return h } function ago(t) { const s = (Date.now() - new Date(t).getTime()) / 1000 if (s < 60) return "now" if (s < 3600) return `${Math.floor(s / 60)}m` if (s < 86400) return `${Math.floor(s / 3600)}h` if (s < 7 * 86400) return `${Math.floor(s / 86400)}d` return new Date(t).toLocaleDateString(undefined, { month: "short", day: "numeric" }) } let docs = [] const open = new Set() if (!me) $("#compose").hidden = true async function busy(btn, work) { btn.classList.add("busy") btn.disabled = true try { await work() } catch (e) { alert(e.message) } finally { btn.classList.remove("busy") btn.disabled = false } } function item(d, reply) { const name = nameOf(d) return `
    ${esc(name[0]?.toUpperCase())}
    ${esc(d.author === me?.email ? "You" : name)}${ago(d.created)} ${me && d.author === me.email ? `` : ""}

    ${esc(d.data.text)}

    ` } const replyInput = (id) => document.querySelector(`article[data-post="${id}"] .reply-form input`) function render() { const drafts = {} for (const f of document.querySelectorAll(".reply-form")) drafts[f.closest("article").dataset.post] = f.querySelector("input").value const focused = document.activeElement?.closest?.(".reply-form")?.closest("article")?.dataset.post const replies = new Map() for (const d of [...docs].reverse()) { if (!d.data.parent) continue if (!replies.has(d.data.parent)) replies.set(d.data.parent, []) replies.get(d.data.parent).push(d) } $("#posts").innerHTML = docs .filter((d) => !d.data.parent) .map((p) => { const rs = replies.get(p.id) ?? [] const action = !me ? "" : open.has(p.id) ? `
    ` : `` return `
    ${item(p)}${rs.length ? `
    ${rs.map((r) => item(r, true)).join("")}
    ` : ""}${action}
    ` }) .join("") || `

    No posts yet

    ` for (const [id, value] of Object.entries(drafts)) if (replyInput(id)) replyInput(id).value = value if (focused) replyInput(focused)?.focus() } async function post() { const text = $("#text").value.trim() const btn = $("#compose button") if (!text || btn.disabled) return busy(btn, async () => { await posts.add({ text, parent: null }) $("#text").value = "" }) } $("#compose").onsubmit = (e) => { e.preventDefault() post() } $("#text").onkeydown = (e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) post() } document.addEventListener("click", (e) => { const reply = e.target.closest(".reply-btn") if (reply) { const id = reply.closest("article").dataset.post open.add(id) render() replyInput(id)?.focus() return } const del = e.target.closest(".del") if (del) busy(del, () => posts.delete(del.closest(".item").dataset.id)) }) document.addEventListener("submit", (e) => { const form = e.target.closest(".reply-form") if (!form) return e.preventDefault() const id = form.closest("article").dataset.post const text = form.querySelector("input").value.trim() if (!text) return busy(form.querySelector("button"), async () => { await posts.add({ text, parent: id }) open.delete(id) render() }) }) document.addEventListener("keydown", (e) => { const form = e.key === "Escape" && e.target.closest?.(".reply-form") if (!form) return open.delete(form.closest("article").dataset.post) render() }) posts.watch((all) => { docs = all render() }) setInterval(render, 60000) ``` ## Pulse: cross-app realtime dashboard Workspace overview that reads live collections from other apps (`tasks`, `journal`, `sketch`, `messages`) with `db.apps()`, `appUrl(...)`, and `db.app(name).collection(...).watch(...)`. Add it with `starter_add({ starter: "pulse" })`. ### `pulse/openbelt.json` Source: `apps/platform/starters/pulse/openbelt.json` ```json { "title": "Pulse", "description": "Live overview of the workspace: open tasks, today's journal, the sketch, the message board, and the latest activity across them", "color": "#1f9d6b", "icon": "activity", "category": "data", "tags": ["dashboard"] } ``` ### `pulse/app.js` Source: `apps/platform/starters/pulse/app.js` ```js import { db, appUrl } from "/sdk.js" import "./prompt.js" const me = await db.me() const $ = (s) => document.querySelector(s) const esc = (s) => String(s ?? "").replace( /[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c], ) const ms = (t) => new Date(t).getTime() const DAY = 86400000 const localDay = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}` const APPS = { tasks: { name: "Tasks", color: "#2f6fed", collection: "tasks" }, journal: { name: "Journal", color: "#c27a1e", collection: "entries" }, sketch: { name: "Sketch", color: "#e0457b", collection: "strokes" }, messages: { name: "Messages", color: "#7c5cd6", collection: "posts" }, } const data = {} const urls = {} for (const app of Object.keys(APPS)) urls[app] = await appUrl(app) const present = new Set((await db.apps()).map((a) => a.app)) const shown = Object.keys(APPS).filter((app) => present.has(app)) const and = (parts) => parts.length < 2 ? parts.join("") : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}` $("#about").innerHTML = shown.length === 0 ? "Pulse shows Tasks, Journal, Sketch and Messages live, once you add them." : `Pulse reads ${and(shown.map((app) => `${APPS[app].name}`))} live, as they change.` const names = new Map() const fromEmail = (email) => String(email) .split("@")[0] .split(/[._-]+/) .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) .join(" ") const who = (email, start = true) => email === me?.email ? (start ? "You" : "you") : names.get(email) || fromEmail(email) function ago(t) { const s = (Date.now() - t) / 1000 if (s < 60) return "now" if (s < 3600) return `${Math.floor(s / 60)}m` if (s < 86400) return `${Math.floor(s / 3600)}h` if (s < 7 * 86400) return `${Math.floor(s / 86400)}d` return new Date(t).toLocaleDateString(undefined, { month: "short", day: "numeric" }) } function stats() { const out = [] const week = Date.now() - 7 * DAY if (data.tasks) { const open = data.tasks.filter((d) => !d.data.done).length const done = data.tasks.filter((d) => d.data.done && (d.data.doneAt ?? 0) > week).length out.push(["tasks", open, `open · ${done} done this week`]) } if (data.journal) { const today = localDay(new Date()) const n = data.journal.filter( (d) => (d.data.day || localDay(new Date(d.created))) === today, ).length out.push(["journal", n, n === 1 ? "entry today" : "entries today"]) } if (data.sketch) { const people = new Set(data.sketch.map((d) => d.author)).size out.push([ "sketch", data.sketch.length, `${data.sketch.length === 1 ? "stroke" : "strokes"} · ${people} ${people === 1 ? "person" : "people"}`, ]) } if (data.messages) { const posts = data.messages.filter((d) => !d.data.parent).length const replies = data.messages.length - posts out.push([ "messages", posts, `${posts === 1 ? "post" : "posts"} · ${replies} ${replies === 1 ? "reply" : "replies"}`, ]) } return out } function feed() { const items = [] for (const d of data.tasks ?? []) { const t = d.data if (t.done) items.push([ "tasks", t.doneAt ?? ms(d.updated), `${who(d.updatedBy)} checked off "${t.title}"`, ]) else if (t.claimedBy) items.push(["tasks", ms(d.updated), `${who(t.claimedBy)} took "${t.title}"`]) else items.push(["tasks", ms(d.created), `${who(d.author)} added "${t.title}"`]) } for (const d of data.journal ?? []) items.push(["journal", ms(d.created), `${who(d.author)}: ${d.data.text}`]) for (const d of data.messages ?? []) items.push([ "messages", ms(d.created), `${who(d.author)} ${d.data.parent ? "replied" : "posted"}: ${d.data.text}`, ]) const lastStroke = new Map() for (const d of data.sketch ?? []) if (!lastStroke.has(d.author)) lastStroke.set(d.author, ms(d.created)) for (const [author, t] of lastStroke) items.push(["sketch", t, `${who(author)} drew on the sketch`]) return items.sort((a, b) => b[1] - a[1]).slice(0, 12) } function render() { for (const docs of Object.values(data)) for (const d of docs) if (d.authorName && !d.authorName.includes("@")) names.set(d.author, d.authorName) $("#stats").innerHTML = stats() .map( ([app, num, sub]) => `
    ${APPS[app].name}
    ${num}
    ${sub}
    `, ) .join("") const items = feed() $("#feed").innerHTML = items .map( ([app, t, text]) => `
  • ${esc(text)}${ago(t)}
  • `, ) .join("") || `
  • Nothing yet
  • ` } for (const app of shown) { db.app(app) .collection(APPS[app].collection) .watch( (docs) => { data[app] = docs render() }, { onError: () => { delete data[app] render() }, }, ) } setInterval(render, 60000) render() ``` --- url: https://openbelt.com/docs/mcp group: Start here --- > Connect an AI agent to OpenBelt over MCP with OAuth or an API token, plus every tool and operation it gets. # Connect an agent (MCP) Agents talk to OpenBelt over Streamable HTTP MCP at `https://openbelt.com/mcp` (which picks or creates your workspace at sign-in) or at a workspace's own address (`https://.openbelt.app/mcp`). Protocol revisions from `2025-03-26` through `2026-07-28` are supported. Every MCP request carries `Authorization: Bearer `, either an OAuth access token from signing in or an API token you created. Every token belongs to one person in one workspace ([People and groups](/docs/people)), writes are attributed to that person (`author` is their email), and `whoami` reports the active identity and permissions. ## OAuth vs API tokens Choose how your agent authenticates based on where it runs: | Method | Best for | Setup | Expiry and revocation | | ------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | **OAuth** | Interactive agents (Claude Code, Codex, Claude, ChatGPT, Cursor, pi) | Add `https://openbelt.com/mcp` (or run `curl -fsSL https://openbelt.com/install \| sh`) and approve in the browser. | Access tokens last 30 days unused and slide on activity. Sign out anytime in `/agents`. | | **API token** | CI jobs, scripts, headless servers, or clients without OAuth | Create a token at `/agents` or with `openbelt token create`, and send `Authorization: Bearer ` to `/mcp`. | No refresh needed; lasts until its optional expiry or until you revoke it. | ## Quick setup - **CLI (configures installed local agents automatically):** ```sh curl -fsSL https://openbelt.com/install | sh ``` - **Claude Code:** ```sh claude mcp add --transport http openbelt https://openbelt.com/mcp ``` Then run `/mcp`, choose `openbelt`, and select **Authenticate**. - **Codex:** ```sh codex mcp add openbelt --url https://openbelt.com/mcp codex mcp login openbelt ``` - **Claude (claude.ai, desktop, mobile):** Open the [Add custom connector dialog](https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=OpenBelt&connectorUrl=https%3A%2F%2Fopenbelt.com%2Fmcp), click **Continue**, **Add**, then **Connect**, and sign in. - **ChatGPT:** Open `https://chatgpt.com/plugins`, click **Add**, then **Add custom MCP server**, set **Name** to `OpenBelt` and **Server URL** to `https://openbelt.com/mcp`, confirm, click **Create as a plugin**, and **Connect OpenBelt**. An agent that is not connected yet can also read `https://openbelt.com/auth.md` (or `/auth.md`) for machine-readable setup steps, or `https://openbelt.com/start.md` for the interactive first-app walkthrough ([Getting started](/start.md)). ## Signing in (OAuth) Any MCP client that supports OAuth needs only the server URL: ```sh claude mcp add --transport http openbelt https://acme.openbelt.app/mcp ``` Its first unauthenticated request receives a `401` whose `WWW-Authenticate` header points to `/.well-known/oauth-protected-resource/mcp` (RFC 9728) and the authorization server metadata at `/.well-known/oauth-authorization-server` (RFC 8414). The client registers via `/_oauth/register` (RFC 7591) or uses an HTTPS Client ID Metadata Document URL as its `client_id` (as Claude Code, Codex, and OpenCode do), then opens `/_oauth/authorize` in your browser. Key OAuth details: - **PKCE required:** `S256` PKCE (`code_challenge` and `code_verifier`) is enforced on every grant, and responses include `iss` (RFC 9207). - **Consent and scope:** The consent screen shows the agent's name, its redirect host, what level of access it gets, and which apps it can touch (defaults to Everything and Every app unless you narrow it). You approve once per agent and redirect host; repeat logins keep the previous scope until you change it in Settings ([Manage a workspace](/docs/workspace)). - **Redirect URIs:** Allowed for any HTTPS origin, custom app schemes, or loopback HTTP (`localhost`, `127.0.0.1`, `[::1]` on any port). - **Login hint:** Clients that know the user's email can pass `login_hint=` to prefill the sign-in form. - **Registration bounds:** Unauthenticated dynamic registrations are capped at 5 redirect URIs (512 characters each), 10 KB for metadata documents, and 500 unused clients per workspace (pruned after 24 hours; signed-in clients are never pruned). - **Workspace isolation:** Grants are bound to one workspace. Tokens from one workspace are rejected on every other workspace host, and `resource` values naming another workspace are refused. - **Signing out:** Visit `/agents` to inspect recent calls, edit an agent's access level, or sign it out (`/agents/`). Clients can also revoke themselves at `/_oauth/revoke` (RFC 7009). Removing a person from a workspace signs out all of their agents immediately. ### Device code flow (no browser or OAuth client) Scripts, shells, and CLIs over SSH can sign in with OAuth device authorization (RFC 8628): ```sh # 1. Register once and save client_id curl -s -X POST https://openbelt.com/_oauth/register \ -H 'content-type: application/json' \ -d '{"client_name":"my-script","grant_types":["urn:ietf:params:oauth:grant-type:device_code"],"token_endpoint_auth_method":"none"}' # 2. Request a device code; open verification_uri_complete and confirm user_code curl -s -X POST https://openbelt.com/_oauth/device_authorization \ -d client_id= # 3. Poll every interval seconds until access_token is returned curl -s -X POST https://openbelt.com/_oauth/token \ -d grant_type=urn:ietf:params:oauth:grant-type:device_code \ -d device_code= \ -d client_id= ``` Open `verification_uri_complete` (or `/_oauth/device`) on any phone or computer, verify the short code, pick a workspace if prompted, and approve. Codes expire after 10 minutes and work once. Polling returns `authorization_pending` until approved (or `slow_down` if polled faster than `interval`). ### One address for every workspace Under email sign-in (`OPENBELT_SIGNIN=email`), the base host (`https://openbelt.com/mcp`, or `https:///mcp` when self-hosted) acts as one MCP address for every workspace. ```sh claude mcp add --transport http openbelt https://openbelt.com/mcp ``` When you sign in with an email code or Google ([Email sign-in](/docs/viewers#email-sign-in)), OpenBelt routes you to your workspace: - If you belong to one workspace with no pending invites, you go straight back to your agent. - If you belong to multiple workspaces or have an invite, a picker lets you choose (selecting an invite accepts it). - If you have no workspace yet, OpenBelt creates one for you as its first admin (invite-only), named from your work domain or personal name. Codes and tokens carry the workspace's permanent id (`acme~pra_...`), so workspace renames ([People and groups](/docs/people)) do not break existing connections. The base host proxies `/mcp`, `/_oauth/token`, and `/_oauth/revoke` to that workspace's Durable Object. To pin the base address to a specific workspace, pass `?workspace=`: ```sh claude mcp add --transport http openbelt-acme 'https://openbelt.com/mcp?workspace=acme' ``` The `401` challenge and protected-resource metadata include that workspace name, the picker skips workspace creation, and tokens belonging to any other workspace are refused with `401` (`error="invalid_token"`). To connect one client to two workspaces, add two entries with different `?workspace=` values or use each workspace's own host (`https://.openbelt.app/mcp`). ### Cloud clients and proxies Cloud clients (Claude, ChatGPT, Cursor cloud agents, Grok Bot) call your MCP endpoint from their own servers, so self-hosted workspaces must be reachable from the internet (not a private tailnet-only instance). If you run a sign-in proxy in front of OpenBelt, leave `/mcp`, `/.well-known/*`, `/_oauth/token`, `/_oauth/register`, `/_oauth/device_authorization`, and `/favicon.*` open while authenticating `/_oauth/authorize` and `/_oauth/device`. In Grok Bot, ask in chat: `Add a custom MCP server called openbelt at https://acme.openbelt.app/mcp`, then click **Authorize** on the card and **Allow** on OpenBelt within 15 minutes. Grok Bot uses Cursor's OAuth client, so the consent screen and `/agents` list it as Cursor (`www.cursor.com`). ### Token refresh behavior Different MCP clients handle token refresh differently, especially when multiple local processes share one login: | Client | When it refreshes | Two processes at once | | ---------------------- | ----------------- | --------------------------- | | Codex 0.164 | Before expiry | One refresh; both use it | | Claude Code 2.1 | At every start | Serialized; no clash | | pi 1.4 | Before expiry | One refresh; both use it | | OpenCode 2.2 | After a `401` | Both refresh the same token | | MCP SDK 1.32 (scripts) | After a `401` | Depends on caller | OpenBelt handles all five patterns cleanly: - **30-day sliding TTL:** Access tokens last 30 days unused (`OPENBELT_OAUTH_ACCESS_TTL_SECONDS`) and slide forward while used, so clients that never refresh keep working. Every call checks live grant state, so signing out revokes access immediately. - **Concurrent refresh grace:** Refreshing issues a rotated refresh token derived from the previous one. Until the new token is used, presenting the immediately preceding refresh token returns the same successor pair so racing processes or lost writes recover without forcing re-login. Anything older returns `invalid_grant` without revoking the newer copy. - **Leak protection:** A refresh token presented by a different client, or an authorization code used twice, revokes the grant on the spot. ## Tokens API tokens work for scripts, CI pipelines, and local agents that prefer a static header (`Authorization: Bearer `). Send API tokens to the workspace's own host (`https://.openbelt.app/mcp`), not the base host. Create an API token in any of three ways: 1. **In the browser:** Open `https://.openbelt.app/agents` and create a token. The token value is shown once alongside a ready-to-paste `claude mcp add` command. 2. **From the CLI or MCP:** Run `openbelt token create --label laptop` (or `POST /_me/tokens/create`). Workspace admins can list and revoke any member's tokens (`openbelt token list --workspace`, `openbelt token revoke --workspace`). 3. **Platform admin API (self-hosted):** Use `OPENBELT_ADMIN_TOKEN` to mint a token for any email, adding that person to the workspace if they are new: ```sh curl -X POST https://acme.openbelt.app/_ops/tokens \ -H "Authorization: Bearer $OPENBELT_ADMIN_TOKEN" \ -H "content-type: application/json" \ -d '{"email": "ada@acme.com", "days": 30}' ``` OpenBelt stores only a hash of each token, so its plaintext is returned once. Refused tokens receive a `401` naming the reason: wrong workspace, expired (with timestamp), or revoked (with timestamp and actor). ## Tools OpenBelt exposes two top-level MCP tools on `/mcp` so tool lists stay compact regardless of how many apps or connections a workspace has: - `search({ query })`: Finds matching first-party operations (up to 6, with input schemas), matching workspace apps (with top functions, collections, skills, and exact `call_function` calls), unadded starter apps, and matching external connections. Pass `query: ""` to list every operation your current role can run. - `call({ tool, args })`: Runs any operation by name, such as `call({ tool: "deploy_app", args: { app, files } })`. Every call checks your current workspace role live. After a promotion or demotion, call `search` again; cached admin operation names do not bypass permission checks. Personal credentials and app consents always belong to the signed-in person, even for admins. > [!NOTE] > In `search` results, a connection's `matchedToolCount` counts matching tools for your query. When `schemasExpanded` is `false`, call `connections` (using the returned `inspect` call) to load its full tool schemas; an empty `tools` array does not mean the connection has no tools. ### Directory endpoint (`/mcp/directory`) Connector directories that disallow generic `search` and `call` dispatchers can connect to `/mcp/directory`. It uses the same OAuth flow and workspace permissions, exposes a curated list of discrete first-party tools (`whoami`, `docs`, `starter_list`, `starter_add`, `app_list`, `app_info`, `app_files`, `app_logs`, `deploy_app`, `promote_app`, `check_app`, `collection_list`, `collection_add`, `collection_update`, `collection_delete`, `call_function`) with explicit `title`, `readOnlyHint`, `destructiveHint`, and `openWorldHint` annotations, and refuses calls outside that set. On a self-hosted base host, setting `OPENBELT_OPENAI_APPS_CHALLENGE` serves `/.well-known/openai-apps-challenge` as `text/plain`. ### Built-in documentation (`docs`) The `docs` operation serves sections of [Getting started](/start.md), [Apps](/docs/apps), [SDK](/docs/sdk), [AI](/docs/ai), [Functions](/docs/functions), [Code (execute)](/docs/code), [Access rules](/docs/rules), [Users & auth](/docs/viewers), [Debugging](/docs/debugging), [Connections](/docs/connections) and [Workspace automation](/docs/workspace), as those pages have them. Call `docs({})` with no arguments for the full index, `docs({ page })` for one page, or `docs({ page, section })` for one section. ### Starter apps Agents can inspect and install tested starter apps (each with example data and a built-in skill) using `starter_list` and `starter_add`: | Starter | What it provides | | ---------- | ---------------------------------------------------------- | | `messages` | Team message board with live posts and replies | | `journal` | Daily log written by people and agents | | `tasks` | Shared task list that people and agents claim and complete | | `sketch` | Collaborative drawing board | | `pulse` | Lightweight status check-ins and team pulse updates | | `cut` | Short link and clip utility | `starter_add` deploys the starter immediately under your ownership; `remix_app` copies any visible app as your own ([Apps](/docs/apps#remix-an-app-made-from-another-as-your-own)). ### Operation groups - **Discovery and identity:** `search`, `docs`, `whoami` (person, role, groups, agent scope, workspace `mcp_url`), `app_list` (paged, filterable by `owner` and `sort`), and `skills` (also exposed via the MCP skills extension `io.modelcontextprotocol/skills` with `skills/list`, `skills/get`, and `skill://` resources). - **Apps and previews:** `app_info`, `app_files`, `app_diff`, `deploy_app`, `promote_app`, `preview_reset`, `preview_side_effects`, `remix_app`, and `app_delete` (requires `confirm` matching the app name; owner or admin). `deploy_app` and `app_info` include `public` when public access is enabled ([Apps](/docs/apps#public-apps-anyone-opens-them-on-the-public-host)). - **Data:** `collection_list`, `collection_add`, `collection_update`, `collection_delete`, and `collection_changes`. On apps you own (or as a workspace admin), data tools bypass page rules; on other people's apps, collection rules apply ([Who can change what](/docs/rules#mcp-writes)) and private apps are refused. Pass `wait` (up to 50 seconds, or 600 seconds with MCP Tasks) to `collection_changes` to tail a collection from a cursor; filter your own writes by `updatedBy` or `agent` ([Who is viewing](/docs/viewers)), or use a trigger to catch every write ([Functions](/docs/functions#schedules-webhooks-triggers-and-later-runs-nobody-calls)). - **Functions and code:** `call_function`, `function_runs`, `set_secret`, `webhook_secret`, `webhook_test` ([Functions](/docs/functions)), and `execute` to run JavaScript against the workspace ([Code](/docs/code)). - **Verification and logs:** `check_app` (real headless browser), `app_picture` (app card preview image), `app_logs`, and `feedback_submit` (attaches your last 20 workspace tool calls and returns an id such as `FB-12`; up to 100 per workspace per day). - **External connections:** `connections` and `connection_call` ([Connections](/docs/connections)). ### Every first-party operation | Operation | `/mcp/directory` | Summary | | ---------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `app_delete` | no | Delete an app for good: every version, its data, files, functions' runs and logs, its preview environments and the connections allowed to it. | | `app_diff` | no | What changed between two of an app's versions, as a unified diff, 16 KB a page: e.g. | | `app_files` | yes | A version's source files with their contents (default: the live version), and that version to pass to deploy_app as base_version. | | `app_info` | yes | An app's URL (and public: its public URL or null), owner, live version and files (unreadable: null, or why openbelt.json couldn't be read; pages and... | | `app_list` | yes | Every app in the workspace, a page at a time: name, URL, description, owner and last update, with total (how many match) and nextOffset (null on the last page). | | `app_logs` | yes | An app's log, newest first: deploys, promotions, data writes (in an environment they say preview ), 404s, and errors from people's browsers (uncaught... | | `call_function` | yes | Run an app's function as you (search finds one by what it does, with its input schema). | | `check_app` | yes | Open an app's page in a real headless browser, run steps (a whole flow in one call), and report what a person would see: each step ok or FAILED with why, JS... | | `collection_add` | yes | Add JSON documents to an app's collection, like db.collection(name).add(data): one (data) or up to 500 (docs: [{ data }, ...]) in one go, all or none. | | `collection_changes` | no | What changed in an app's collection since a cursor, oldest first: to follow a collection (a task queue, a channel) without reading it all again. | | `collection_delete` | yes | Delete one document by id, or with all: true every document in the collection (to clear test data). | | `collection_list` | yes | Read an app's documents in one collection, newest first (or filtered/sorted/searched): the same data pages read with db.collection(name).list(). | | `collection_update` | yes | Change documents by id, as pages do with update(id, patch): data's fields are merged in (shallow). | | `connection_call` | no | Call a tool of one of the workspace's connections, e.g. | | `connections` | no | Search first: before building an app, connections({ search: "pokemon" }) (what it's about: its data or service) lists the few connections that match, with... | | `deploy_app` | yes | Publish an app's files as a new version; the first deploy creates the app (its name is then yours). | | `docs` | yes | How to build and deploy an app or manage workspace settings, a page at a time. | | `execute` | no | Run JavaScript on OpenBelt as you, with the workspace in reach as workspace: every app's functions (await workspace.apps..fn.(input)), data... | | `feedback_submit` | no | Tell OpenBelt's team about a problem you hit here: a bug, something OpenBelt can't do yet, or docs, a schema or a refusal that misled you. | | `file_delete` | no | Delete a file from an app's files: its bytes, its record and the room it took. | | `file_from_url` | no | Copy a file (a picture, PDF, audio, video) at a public https URL into an app's files (where pages' files.put puts them), up to the file limit (app_info... | | `file_upload_url` | no | Upload files (pictures, PDFs, audio, video) from your computer to an app's files: returns a 10-minute link storing up to count files (default 1, max 100)... | | `function_runs` | no | An app's function runs, newest first, whatever started them (page, app:, agent, schedule, webhook, data, later): who, version, input, attempts... | | `preview_reset` | no | Delete a preview environment's data on every app in it (or only app's), to start a test over. | | `preview_side_effects` | no | Whether a preview environment's functions send what changes things outside OpenBelt (a fetch other than GET or HEAD, a connection tool not marked read-only). | | `promote_app` | yes | Make versions live. | | `remix_app` | no | Remix an app: a new app in this workspace, the caller's own, made from another app and live at once. | | `set_secret` | no | Get the link where a person gives an app a secret its functions send (an API key). | | `skills` | no | The workspace's skills (Agent Skills: a SKILL.md of instructions and the files it refers to). | | `starter_add` | yes | Add a starter app (starter_list) to the workspace as yours: a tested app with its first data and a skill, live at once. | | `starter_list` | yes | The starter apps you can add to the workspace: tested apps, each live in a second with its first data and a skill of its own. | | `webhook_secret` | no | A webhook's URL and secret (openbelt.json "webhooks", once deployed), how a delivery is signed, and a curl that sends a signed test one (webhook_test does... | | `webhook_test` | no | Send a webhook a test delivery exactly as an outside sender would, through the same signature checks and run (no shell needed): sign: "good" signs body with... | | `whoami` | yes | Who this token is in the workspace: the person (id, email, name, role, status), their groups, the workspace, how people join it (open or invite), its... | ### Results, traces, and refusals - **Trace IDs:** Every result except `docs` includes a `trace` field, and every error ends with `(trace )`. Pass that `trace` to `app_logs` to inspect the call; workspace admins also see every call in workspace activity ([Running OpenBelt](/docs/running)). - **Dual payload:** Results are returned both as JSON text and as `structuredContent` per the MCP specification so clients that read either field (such as Claude Code, Codex, OpenCode, or pi) see the full answer. Payloads stay compact: `app_files` supports `paths`, `around`, and `lines`, and `deploy_app` trims inline diffs at 4 KB (`app_diff` pages larger diffs). - **Actionable refusals:** Failed checks return `isError: true` with an explanation of what to fix, such as a missing `index.html`, an unavailable app name (with a suggestion), or a deploy conflict (with a diff). `check_app` failures also attach the structured browser report in `structuredContent`. ## Sessions MCP `2026-07-28` clients run sessionless and send every call directly without establishing a session. Older `2025-*` clients open a session backed by a per-person Durable Object (`McpDO`). Each session's `initialize` request is persisted so an instance that sleeps after 10 minutes of idle time (`OPENBELT_ACTOR_SLEEP_SECONDS`) transparently resumes the session on the next call. Unknown sessions or sessions older than the newest 50 return HTTP `404` with JSON-RPC error code `-32001` prompting the client to send `initialize` again. Every request validates the bearer token independently, so a session ID alone grants no access and removing a person stops their sessions on the next call. Because OpenBelt's tool list is static, `subscriptions/listen` returns `-32601` (method not found). ## MCP Tasks On protocol version `2026-07-28`, OpenBelt advertises the MCP Tasks extension (`io.modelcontextprotocol/tasks`, SEP-2663). Clients that declare `io.modelcontextprotocol/tasks` in `clientCapabilities` receive a `CreateTaskResult` handle (`resultType: "task"`) for long-running operations and can poll `tasks/get` or cancel cooperatively with `tasks/cancel`: | Operation | Behavior with MCP Tasks | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `check_app`, `app_picture` | Fast checks return synchronously; runs past 1.5s queue for browser slots up to 60s with live progress updates instead of timing out at 20s. | | `connection_call` | Slow upstream calls upgrade to a Task, mirror upstream progress, and forward `tasks/cancel`. | | `collection_changes` | Extends `wait` from 50s to 600s as a non-blocking background watch while keeping `McpDO` free for other calls; returns synchronously if changes already exist. | | `execute`, `call_function` (with `inputs`) | Fast runs return synchronously; runs past 1.5s report progress and `tasks/cancel` stops the QuickJS sandbox mid-run. | Clients that do not advertise `io.modelcontextprotocol/tasks` always receive synchronous responses. ## Events OpenBelt advertises MCP Events (`io.modelcontextprotocol/events`, webhook delivery profile) on `2026-07-28` (`server/discover` and `initialize`). Clients discover events with `events/list`, register a Standard Webhooks endpoint with `events/subscribe`, and stop deliveries with `events/unsubscribe`: - **`collection.changed`:** fires when a live document is added, updated, or deleted in a readable collection (`arguments`: `{ app, collection, ops?, where?, includeOwn? }`). Collection read rules and app visibility apply on every event; making an app private, deleting it, or removing a person revokes affected subscriptions immediately. - **Verification and signing:** `events/subscribe` rejects private, loopback, metadata, and non-HTTPS destinations (localhost allowed only with `OPENBELT_ALLOW_LOCAL_CONNECTIONS=1`), requires a Standard Webhooks `whsec_` secret (24 to 64 raw bytes), and sends a signed `{ type: "verification", subscriptionId, challenge }` POST that the receiver must echo back as `{ "challenge": "" }`. Deliveries are signed with HMAC-SHA256 (`v1,`) in `webhook-signature` alongside `webhook-id`, `webhook-timestamp`, and `x-mcp-subscription-id`, and never follow redirects. - **Leases and retries:** subscriptions upsert deterministically per person, URL, event name, and arguments, returning `{ id, refreshBefore, expiresAt }`. Failed deliveries (`5xx`, `429`, timeouts) retry durably on `WorkspaceDO` with exponential backoff reusing `webhook-id`; `404` and `410` auto-deactivate the subscription. --- url: https://openbelt.com/docs/cli group: Start here --- > Install the openbelt CLI, sign in once, configure your agents, and run workspace operations from a terminal or script. # CLI `openbelt` is a single ~2 MB binary that does two things: it signs you in once and configures OpenBelt in your local AI agents, and it exposes every MCP tool in your workspace as a terminal command. ```sh curl -fsSL https://openbelt.com/install | sh openbelt search expense claims openbelt fn run expenses.file '{"amount": 42, "what": "lunch"}' --key lunch-1108 openbelt data list expenses/claims --limit 50 | jq '.docs[].data' openbelt app deploy ./standup ``` ## Install and update Install `openbelt` from `openbelt.com` (or directly from your workspace's host to pin to that workspace): ```sh # Install and pick or create a workspace at sign-in curl -fsSL https://openbelt.com/install | sh # Or pin directly to one workspace curl -fsSL https://acme.openbelt.app/install | sh ``` The installer downloads the binary matching your platform to `~/.local/bin` (override with `OPENBELT_INSTALL_DIR` or `XDG_BIN_HOME`), verifies its SHA-256 checksum, and runs `openbelt install`. - **Pass flags to `openbelt install`:** Append `sh -s --` followed by flags such as `-y`, `-a codex`, or `--token `. Use `curl -fsSL https://openbelt.com/install | sh -s -- --dry-run` to download and verify the binary without installing it. - **Windows:** Download the binary from `https://openbelt.com/_cli/openbelt-x86_64-pc-windows-gnu.exe`. - **Updates:** Run `openbelt update` to replace the binary with your signed-in workspace's current build (verified by SHA-256), `openbelt update --check` to check without replacing, or `openbelt --version` to print your 12-character build hash. Interactive terminals check for updates once a day unless `CI` or `OPENBELT_NO_UPDATE_CHECK=1` is set. ## Sign in and configure agents `openbelt install [workspace url]` signs you in via OAuth device authorization (RFC 8628) and adds OpenBelt to the local agents it detects: Claude Code, Codex, OpenCode, Cursor, VS Code, Claude Desktop, Windsurf, Gemini CLI, Zed, Amp, Antigravity, Cline, GitHub Copilot CLI, and pi. Each configured agent starts `openbelt mcp`, which bridges MCP traffic using your CLI login so no token is ever written into an agent's config file. Existing config comments, formatting, symlinks, and custom keys are preserved, and an unrelated server named `openbelt` is left untouched. - **Browser and headless sign-in:** `openbelt login [workspace url]` (and `install`) prints a link and a short code such as `BCDF-GHJK` and opens your browser. Over SSH or with `--no-open`, open the link on another device (or visit `/_oauth/device` and enter the code). The CLI waits up to 10 minutes for approval. - **Agent-driven non-interactive sign-in:** `openbelt install -y` (or running without a TTY) prints the verification code and exits immediately, saving the pending request in `pending.json`. Run `openbelt login --wait` to wait for approval and complete agent setup. - **API token sign-in:** Pass `--token ` (created at `/agents`) to `install` or `login` to skip browser OAuth. - **Selecting agents:** Run `openbelt install` again anytime to add more agents, or pass `-a codex cursor`, `-a '*'` / `--all-agents`, or `-a none` (prints the MCP entry without modifying files). ## Core commands Commands and `--help` output are loaded dynamically from your workspace's MCP tool schemas, so your available commands match your current role. Run `openbelt` alone to list all commands, or `openbelt --help` for any command's flags. ### Setup and account | Command | Purpose | | ---------------------------------- | -------------------------------------------------------------------------------------------------- | | `openbelt install [workspace url]` | Sign in and configure OpenBelt in your local agents. | | `openbelt login [workspace url]` | Sign in again, finish `install -y` (`--wait`), or sign in with `--token`. | | `openbelt logout` | Sign out, revoke OAuth tokens, and clear the cached command list. | | `openbelt open [app]` | Open your workspace (or one app) in your browser (`--no-open` prints the URL only). | | `openbelt status [--json]` | Show workspace, signed-in user, CLI version, configured agents, and `PATH` status (works offline). | | `openbelt update [--check]` | Update the binary to match your workspace's build. | | `openbelt uninstall` | Sign out, remove OpenBelt from every configured agent, and delete local files and binary. | | `openbelt call [json]` | Invoke any MCP tool directly by name (such as `execute`, see [Code](/docs/code)). | ### Workspace operations | Group | Common commands | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Discovery** | `openbelt search `, `openbelt docs [page] [section]`, `openbelt skills [uri]`, `openbelt whoami` | | **Starters** | `openbelt starter list`, `openbelt starter add [--app ]` | | **Apps** | `openbelt app list`, `openbelt app info `, `openbelt app deploy [dir]`, `openbelt app pull [dir]`, `openbelt app diff [to]`, `openbelt app promote `, `openbelt app reset `, `openbelt app side-effects `, `openbelt app check `, `openbelt app picture `, `openbelt app secret `, `openbelt app logs `, `openbelt app remix `, `openbelt app delete --confirm ` | | **Data** | `openbelt data list / [--all]`, `openbelt data add / `, `openbelt data update / [id] `, `openbelt data delete / [id]`, `openbelt data changes / [--wait \| --follow]` | | **Files** | `openbelt file upload-url [--count ]`, `openbelt file from-url `, `openbelt file delete ` | | **Functions** | `openbelt fn run . [input]`, `openbelt fn runs [function]`, `openbelt fn webhook-secret .`, `openbelt fn webhook-test . ` | | **Connections & tokens** | `openbelt connection list [search]`, `openbelt connection info `, `openbelt connection call . [args]`, `openbelt token list`, `openbelt token create`, `openbelt token revoke ` | | **Feedback** | `openbelt feedback ` (`bug`, `not_possible`, `confusing`, or `other`) | > [!NOTE] > Personal connection settings and tokens are the default. Workspace admins can pass `--workspace` on commands that support both scopes (such as `openbelt token list --workspace` or `openbelt connection access --workspace`). `--workspace` requires admin permissions and never falls back to personal settings. Admin-only commands such as `people invite` and `connection add` need no scope flag. ## Arguments and output - **Compound positional arguments:** `/` and `.` pass both names in one word. All other parameters are flags derived from the tool schema (`--kebab-case`, `--snake_case`, and `--camelCase` all match; `--no-` sets a boolean to `false`). - **JSON, files, and stdin:** Pass values as plain strings, numbers, inline JSON (`'{"a": 1}'`), `@file.json`, or `-` for stdin. - **Batch writes and paging:** Pass a JSON array to `data add` or an array of `{ "id", "data" }` objects to `data update` (up to 500 documents, atomic). Combine `data list --all` with `jq` to transform an entire collection in one pipeline: ```sh openbelt data list shop/orders --all \ | jq '[.docs[] | select(.data.status == "open") | {id, data: {status: "late"}}]' \ | openbelt data update shop/orders ``` - **Streaming collection changes:** `openbelt data changes board/tasks --follow` prints each change as one JSON line as it arrives (from now, or from `--since `), ready for a shell loop. Without `--follow`, `--wait ` holds one call until a change arrives. - **Output format:** Results render as readable YAML-like text in a terminal, and as JSON when piped or when `--json` is set. Returned images (such as `app check --screenshot` or app pictures) are saved to a temporary file or to `--output `, with the file path printed in the result. - **Agent attribution:** Pass `--agent ` on any command (or set `OPENBELT_AGENT`, which `openbelt mcp` also reads) to tag writes with `agent: ""` so multiple agents sharing one login stay distinct (1 to 40 lowercase letters, digits, `.`, `_`, or `-`). - **Deploying and pulling folders:** `openbelt app deploy ` uploads every file in the folder except dotfiles and `node_modules`, naming the app after the folder unless `--app` is given. `openbelt app pull [dir]` writes an app's files to disk. ### Exit codes | Code | Meaning | | ---- | ------------------------------------------------------------------------ | | `0` | Command succeeded. | | `1` | OpenBelt refused the request (stderr explains why and what to run next). | | `2` | Invalid CLI usage or unknown flag (stderr lists valid flags). | ## Where credentials are stored Your active login is stored in `~/.config/openbelt/credentials.json` (or `$XDG_CONFIG_HOME/openbelt/credentials.json`) with permissions restricted to your user account. It holds either your API token or OAuth tokens that refresh automatically. - Pending non-interactive logins (`openbelt install -y`) live in `pending.json` next to `credentials.json` until `openbelt login --wait` finishes. - Cached workspace command metadata lives in `~/.cache/openbelt/tools.json` (or `$XDG_CACHE_HOME/openbelt/tools.json`) so `--help` and `status` work offline. - Run `openbelt logout` to revoke OAuth tokens and clear cached commands, or `openbelt uninstall` to remove all OpenBelt agent configs, local files, and the binary. To build the CLI binary from source, run `cargo build --release --manifest-path apps/cli/Cargo.toml` in the [OpenBelt repository](https://github.com/janedogco/openbelt). --- url: https://openbelt.com/docs/apps group: Building apps --- > Deploying static web apps, preview environments, openbelt.json configuration, public apps, remixes, and agent skills. # Apps An OpenBelt app is a folder of static files (HTML, CSS, JavaScript modules, images) served on its own origin with built-in storage, auth, and server functions. What you deploy is what OpenBelt serves: no build step, no bundler, and no TypeScript compilation. | Surface | URL | Used by | | --------------- | ------------------------------------------------- | ----------------------------------------------------------------- | | Workspace frame | `https://.openbelt.app/a//` | People opening the app in a browser (the `url` tools return) | | App host | `https://--./` | App iframe, `curl`, agent `fetch`, and link preview bots (`host`) | | Public host | `https://--.openbelt.page/` | Anyone signed out, when `openbelt.json` declares `public` | A browser opening the app host is redirected into the workspace frame, where the address bar follows links, `history.pushState`, and hash changes so copied links open the same view ([In the frame](#in-the-frame)). ## Deploying ```js deploy_app({ app: "standup", description: "Daily updates and blockers", files: [ { path: "index.html", content: "..." }, { path: "logo.png", base64: "iVBORw0..." }, ], }) ``` - **Full deploy vs patch:** without `edits` or `keep_others`, `files` replaces the whole app (omitted files are removed). Send `{ path, content }` for text or `{ path, base64 }` for binary or byte-exact files. - **Deploy result:** returns the app's `url`, `version`, and `reach` (who can open the URL and who is signed in there). Open pages that load `/sdk.js` reload automatically when a new version goes live. - **Relative links and cross-app links:** reference local assets relatively (`app.js`, not `/app.js`) so previews serve their own copies. Link to other apps with `appUrl("home")` from `/sdk.js` (stays inside the active preview and opens full-window from the frame). ## Files and names - **Paths and size limits:** `index.html` is required. Use relative paths (`css/style.css`) with no `..`, no segment starting with `_` (`_db`, `_ws`, `_log`, `_shot`, `_preview` are reserved), and no top-level `a/` folder (`/a//` serves another app's data). Max 5 MB per file and 64 MB per MCP request (for larger apps, split across calls with `keep_others`). Send large deploys sequentially; concurrent saturation returns 503 `busy` with `Retry-After`. - Pictures, PDFs, audio and video the app shows as content (photos, receipts, episodes; anything over 5 MB) aren't deployed: they go in its files, and documents keep their urls. Copy one at a public URL with `file_from_url`, send one from your computer with `file_upload_url` (docs page sdk, "Files"); never base64 a file into a tool call. A public app's public host doesn't serve uploads (below): what its public page shows is deployed with it, and `deploy_app` takes an upload's id for a file's bytes (`{ path: "poster.jpg", file: "" }`), so upload it first; or `"files": true` in `public` serves its uploads there. - **Favicons and mobile:** pages without `` use OpenBelt's icon. Use at least 16px font size on `input`, `textarea`, and `select` on phones so iOS Safari does not auto-zoom (avoid `maximum-scale`, which blocks manual zoom). OpenBelt sets `touch-action: manipulation` on `html` to prevent double-tap zoom while keeping pinch zoom; override with `touch-action: none` on custom canvases/maps or `html { touch-action: auto }`. - **App names:** 1-40 lowercase letters, digits, and single dashes. Because `--.` must fit one 63-character DNS label, long workspace names shorten the allowed app name length. A name becomes yours on the first successful deploy (collisions return a free suggestion like `standup-2`; a refused first deploy leaves the name free). Each app keeps a permanent id so its data stays with it. ## In the frame The workspace frame and the app page work as one page with zero setup (the app's own host gets the same theme and routes outside the frame): - **Keys:** the app receives keyboard focus immediately on open, so shortcuts work without clicking. - **Address and routing:** the address bar syncs with the app, and Back/Forward navigate within it. Use `location.pathname` and `history.pushState` (or hash routes like `#/issue/ENG-12`). Browser requests to extensionless paths (`/issue/ENG-12`) serve the nearest parent `index.html` with an automatic `` tag (unless one is already present) so relative assets and `#` links keep working; `curl` and missing files still return 404. A folder with its own `index.html` asked for without its slash (`/deals/black-friday`) answers `308` to the slash for every client, crawlers included, so a page meant for search is a real file (`deals/black-friday/index.html`). - **Title:** the tab reflects `document.title`. Put unread counts first: `(3) Inbox`. - **Theme:** OpenBelt sets `` or `"light"` before paint (unless the page already sets `data-theme`) and exposes `theme` in `/sdk.js` ([SDK](/docs/sdk#theme)). Style dark mode with `:root[data-theme="dark"] { color-scheme: dark; ... }` rather than relying solely on `prefers-color-scheme` (Chrome keeps `prefers-color-scheme` tied to the OS setting). ## Preview environments Test changes in a preview environment before touching a live app with real data: name it after the change, seed from live if needed, include every app the change touches, verify with `check_app`, then promote them together. > [!NOTE] > Preview environments are isolated from live data. `promote_app` promotes code only and never copies preview data to live. ```js deploy_app({ app: "bugbash", preview: "triage", seed: "live", note: "Duplicate status", files: [...] }) // -> { live: false, env: "triage", previewUrl: "https://bugbash--acme.openbelt.app/_preview/triage/", seeded: { docs: 10, capped: false } } deploy_app({ app: "home", preview: "triage", keep_others: true }) // home as it is, or changed check_app({ app: "bugbash", preview: "triage", steps: [...] }) promote_app({ apps: ["bugbash", "home"], env: "triage" }) ``` - **Isolated data:** each app runs at `/_preview//` over that environment's own data (starts empty; `seed: "live"` copies the newest 5000 live documents once). - **Multi-app previews:** apps in the same preview share preview data through `db.app(...)` under their preview `openbelt.json`. Apps not in the preview are read live and refuse writes (403); deploy them in with `keep_others: true` and no files (only an app's owner can deploy it; ask the owner named in `app_info` if needed). Inside a page, `import { env } from "/sdk.js"` returns `"triage"` (or `null` on live). - **Iterative fixes:** patches without `base_version` build on the app's current version in that preview. `collection_list`, `collection_changes`, `collection_add`, `collection_update`, `collection_delete`, and `check_app` all take `preview: "triage"` (`preview: true` is refused). - **Check isolation:** `check_app` only reaches the checked app and other apps in the same preview. On live, `db.app()` calls to other apps are refused during checks. - **Promoting and rolling back:** `promote_app({ apps, env })` promotes every listed app atomically and reloads open pages. If live changed since you branched, promote refuses naming who changed it and when; deploy into the preview again with `keep_others: true` to merge, re-check, and promote. Roll back with `promote_app({ app, version })` (`app_info` lists the last 20 versions, and every result includes `previous`). - **Lifecycle:** `app_info` lists active previews (`note`, other apps, `lastWrite`, `by`). Deploying into a preview containing someone else's app warns you. `preview_reset({ env })` clears preview data (`app` for one app). Previews expire after 7 days with no deploys or writes. ## More on environments - Preview names are 1-40 lowercase letters, digits, and dashes (not `live`), created on first deploy. Preview data supports the full SDK and its own realtime socket. `seeded` reports how many documents were copied and whether `capped` was reached. - A deploy's `previous` field is the prior version in that environment (`null` when newly added). - If any app fails to switch during `promote_app`, already-switched apps roll back. Merging newer live changes into a preview refuses with a diff if both edited the same file. - `preview_reset` keeps deployed versions and reloads open preview pages. Expired previews delete their data too. Unknown preview URLs return 404, never live data. - Apps have no separate gate of their own: whoever reaches the app's host can open it (reported in `reach` on deploy and promote). ## Changing an existing app 1. Read the live version first with `app_files({ app: "standup" })` (returns files and `version`, e.g. `"3f2a9c1e0b7d"`). For large files, fetch excerpts with `paths`, `around` + `context`, or `lines: "40-80"`. 2. Send targeted `edits` against that `base_version`. Each `find` string must match the file verbatim and occur once. Send whole `files` only for new files or full rewrites: ```js deploy_app({ app: "standup", base_version: "3f2a9c1e0b7d", preview: "standup-fix", edits: [ { path: "app.js", find: "const title = 'Standup'", replace: "const title = 'Daily standup'" }, ], files: [{ path: "search.js", content: "..." }], delete: ["old.css"], }) ``` - **Sequential edits:** edits apply in order on text files only. If any `find` matches zero or multiple times, nothing deploys and the error lists closest lines or every match's line numbers. - **Patch mode:** `edits` and `keep_others: true` preserve untouched files; `delete` removes paths. - **Diff review:** the result's `diff` summarizes changes (truncated past 4 KB with an `app_diff` call for the rest; lines past 400 chars show a window marked `⟪… N chars⟫`, do not copy that marker into `find`). `changed` lists paths differing from `base_version`. - **Conflict protection (`base_version`):** defaults to the preview's current version when deploying to a preview. If someone else updated live concurrently, their changes to other files are kept; deploy refuses only on overlapping files (or any file for a full deploy), returning who deployed when and a diff. Re-read `app_files`, re-apply, and deploy with the new version. ## More on reading and patching - Without `base_version`, nothing is checked: a patch applies on live and a full deploy replaces live. Patches also refuse if live modified a file your base preview already changed. - `app_files` accepts `version` and `paths`. Binary files return as `base64`. Past about 400 KB in one call, remaining files are marked `omitted` (request them by `paths`). Excerpts include `lineCount` (`context` defaults to 10) and omit non-matching files. - Failed edits also report whitespace-only matches, split lines, and when a new file belongs in `files`. - `app_diff({ app, from, to, paths?, offset? })` pages through diffs between any two kept versions in 16 KB chunks (`next` is the next `offset`, or `null`). ## Versions A version is the immutable set of files produced by a deploy. Files are content-addressed, so redeploys upload only changed bytes (`uploaded`), and identical file sets produce identical version ids. Switching live is atomic: a refused deploy leaves the previous version serving. `promote_app` returns `{ promoted: [{ app, url, version, previous }] }` with `reach`. `app_info` lists the last 20 versions newest first (`version`, `kind`, `by`, `deployedAt`, `promotedAt`, `files`). Older versions are pruned while the live version and any version running in a preview are always kept. ## openbelt.json Add an optional `openbelt.json` at the app root to declare collections, access rules, server functions, connections, AI, desktop capabilities, or public access. A lunch voting app where other apps can add votes, limited to one vote per person per day: ```json { "title": "Lunch Votes", "description": "Lunch votes, one per person per day", "collections": { "votes": "one doc per person per day, id :: { day, place }" }, "writable": ["votes"], "rules": { "votes": { "read": "anyone", "create": "signedIn && id == newDoc.data.day + ':' + me", "update": "doc.author == me && newDoc.data.day == doc.data.day", "delete": "doc.author == me" } } } ``` ### Reference | Field | Purpose | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `title` | Human-readable display name (up to 60 chars, one line) shown in Apps, header, installed apps, and link previews. Defaults to the URL slug. | | `description` | One-line summary shown in `search`, Apps, and `db.apps()` (wins over `deploy_app`'s `description`). | | `collections` | Documents what each collection stores (`about`), or `{ description, schema }` to validate every write against a JSON Schema. Supports prefix wildcards (`"v_*"`). | | `writable` | Collections other apps' pages may write via `db.app()`. Without it, only this app's pages can write. | | `rules` | Per-collection `read`, `create`, `update`, and `delete` rules enforced on every `/_db` call ([Access rules](/docs/rules)). Supports prefix wildcards (`"v_*"`). | | `aggregates` | Up to 16 maintained `count` or `sumInteger` totals read via [`db.aggregate(name)`](/docs/sdk#aggregates-dbaggregate). | | `tools` | Workspace connection tools pages may call with `tools.call`, bound to `"viewer"` or `"workspace"` (up to 100; [SDK](/docs/sdk#connections-toolscall)). Unservable bindings warn on deploy. | | `functions` | Server functions (`functions/.js`): one-line description or `{ description, kind?, internal?, http?, input?, output? }` ([Functions](/docs/functions)). Functions with `"http": true` serve custom HTTP endpoints at `/_http/`. | | `schedules`, `webhooks`, `triggers` | Automated function invocations ([Functions](/docs/functions#schedules-webhooks-triggers-and-later-runs-nobody-calls)). | | `network`, `secrets`, `uses` | Outbound hosts, secret placeholders, and workspace connections granted to functions ([Functions](/docs/functions#secrets-network-and-connections)). | | `public` | Publishes the app signed-out on `--.` with an explicit allowlist of collections and functions ([Public apps](#public-apps-anyone-opens-them-on-the-public-host)). | | `ai` | Enables built-in AI inference (`true` or `{ "webSearch": true }`) for browser `ai` and server `ctx.ai` ([AI](/docs/ai)). | | `card` | Unfurl card privacy: `"private"` (default: workspace card only) or `"public"` (shows `title`, `description`, and screenshot; [Link previews](#link-previews)). | | `color` | Hex color (`"#2563eb"`) for the app tile, link preview card, and Today tint. Falls back to ``, screenshot dominant color, or deterministic palette. | | `icon` | Any [Lucide icon](https://lucide.dev/icons) name (`"scissors"`, `"calendar-days"`). Without it, tiles show the first letter and `deploy_app` warns. | | `category` | Category on the Apps page: one of `"productivity"`, `"business"`, `"finance"`, `"communication"`, `"data"`, `"creative"`, `"websites"`, `"developer"`, `"personal"`, `"games"`. Manual pins on the App page override it; when omitted, an optional server classifier fills it in. | | `tags` | Up to 8 short lowercase search tags (such as `["video", "3d"]`) that power search invisibly without cluttering app cards. | | `desktop` | Optional OpenBelt Desktop capabilities (`floating`, `tray`, `menuBar`, `startAtLogin`, `shortcuts`, `notify`, `capture`, `clipboard`, `width`, `height`, `titleBar`). Ignored in regular browsers ([SDK](/docs/sdk#desktop)). | - **Collection schemas, indexes, and search:** pass `{ "description": "...", "schema": { ... }, "indexes": [...], "search": [...] }` to validate writes from pages, agents, and functions (refuses invalid writes with 400 `invalid` naming failing fields; existing documents are not re-checked). Supports the same JSON Schema subset as functions ([Input and output schemas](/docs/functions#input-and-output-schemas)): `type`, `properties`, `required`, `additionalProperties`, `items`, `enum`, `const`, `anyOf`, `minimum`, `maximum`, `minLength`, `maxLength`, `minItems`, `maxItems`, `description` (not `pattern` or `format`). `app_info` renders it as a TypeScript type (`holds`). `indexes` declares up to 8 field-path tuples (such as `[["status", "-createdAt"]]`, prefix `-` for descending, up to 4 fields each) for filtered and sorted `list({ where, orderBy })` queries; `search` declares up to 8 text field paths (such as `["title", "body"]`) for BM25-ranked `list({ search })` full-text search. OpenBelt builds indexes and search tables lazily on first query and prunes removed ones on deploy; wildcard keys (`"v_*"`) cannot declare `indexes` or `search`. - **Desktop options:** use `"menuBar": { "path": "/menubar.html", "width": 340, "height": 380 }` (width 200-800, height 140-900) for a background-alive HTML popover, or `"tray": true` for an OS dropdown menu (setting both is refused). `shortcuts` takes 1-4 modifier+key accelerators (`"Alt+Shift+J"`, `"CommandOrControl+Shift+K"`). `width` and `height` are 120-3840 (height up to 2160). On macOS, `"titleBar"` defaults to a seamless 34px draggable bar (`"default"`); set `"titleBar": "hidden"` for full-bleed floating traffic lights. OpenBelt Desktop prompts with a native permission sheet pinned to `x-openbelt-version`. - **Validation and rollback safety:** invalid `openbelt.json` refuses the deploy with the expected shape. If OpenBelt itself rolls back to an older server version that encounters unknown keys, it skips them and stops serving `functions/`. If a known key has an unreadable shape, page data reads/writes return 403 (`rule: "openbelt.json"`, details in `app_logs` and `app_info.unreadable`), functions stop running (calls 404, webhooks 503, schedules skip, triggers/later pause), and deploys that keep the unreadable file (`keep_others`) are refused until you deploy a fixed `openbelt.json`. Limits from `packages/model/src/config.ts` (`CONFIG_LIMITS`): `title`: 60, `description`: 300, `collection`: 500, `indexesPerCollection`: 8, `indexFields`: 4, `searchFields`: 8, `tools`: 100, `functions`: 50, `function`: 500, `schedules`: 10, `webhooks`: 20, `triggers`: 20, `secrets`: 20, `network`: 20, `uses`: 10. ### Link previews Links pasted into Slack, iMessage, X, LinkedIn, Discord, or WhatsApp unfurl into a 1200x630 card generated a few seconds after deploy (served signed-out at `/_og.png` on the app host): - By default (`"card": "private"`), previews show only the workspace card ("An app in ``") with no app details. - With `"card": "public"` (or on a public app's public host), previews show the app's title, description, and screenshot in the app's color. Over-saturated colors are toned down on the card (OKLCH chroma capped at 0.12), and a version keeps its initial card color unless you set `color`. ### An app without rules A trip app where other apps can add expenses: ```json { "description": "Split the offsite's costs", "collections": { "expenses": "one doc per expense: { payer, cents, for: [names], title }", "members": "one doc per person on the trip, id = their email: { name }" }, "writable": ["expenses"] } ``` Collection descriptions are the contract other apps build on; keep them accurate when schemas change. See [Using another app's data](/docs/sdk#using-another-apps-data). ## Public apps: anyone opens them on the public host Add `"public"` to `openbelt.json` to make an app reachable by anyone without signing in at `--.` (for example `https://game--acme.openbelt.page/`, configured via `OPENBELT_PUBLIC_HOST`). Owners can also toggle public access and per-collection/per-function permissions from the app header menu (Share -> Public), which deploys a new version updating only `public`. ```json { "public": { "collections": { "scores": ["read", "create"], "posts": ["read"] }, "functions": { "play": { "secrets": [], "uses": [] } } }, "collections": { "scores": "one doc per game played: { name, score }", "posts": "the team's notes about the game: { text }" }, "functions": { "play": "scores a move. input: { moves }; returns { score }" }, "rules": { "scores": { "read": "anyone", "create": "anyone", "update": "nobody", "delete": "nobody" }, "posts": { "read": "anyone", "create": "signedIn", "update": "doc.author == me", "delete": "doc.author == me" } } } ``` - **Static files are public:** every page, script, and image is served except `openbelt.json`, `skills/`, and `functions/`. `"public": {}` publishes static files with no data or functions. - **Collection allowlist + rules:** `public.collections` lists allowed ops (`"read"`, `"create"`, `"update"`, `"delete"`). Unlisted collections or ops return 403 (`rule: openbelt.json "public"`). Listed ops must also pass collection `rules` for a signed-out visitor (`me` is `null`, `signedIn` is `false`). Write-only collections (without `"read"`) return only `id` and `seq`, never document data. Aggregates require `"read"` on the source collection. - **Function allowlist:** `public.functions` lists callable functions (including `"http": true` endpoints at `/_http/`) with the exact `secrets` and `uses` allowed on the public host (`[]` for none). Calls run with `ctx.caller === null`, propagate the same secret/connection cap to `ctx.call`, `ctx.later`, and triggers (evaluated against the live `public` block when deferred runs start; public-write triggers get no secrets or connections), and reject connections requiring user tokens. Rules do not guard functions, so validate inputs; documents read in public functions mask member emails as opaque ids. - **Public realtime:** `"realtime": true` in `public` lets anonymous visitors on the public host use `realtime.presence` and `realtime.broadcast` / `realtime.send` ([SDK](/docs/sdk#presence-and-broadcast-realtime)). Off by default; public rooms are isolated from workspace rooms, stamp `email` and `name` as `null` (opaque connection ids only), and cap messages at 1 KB. - **OpenBelt bar:** browsers load the page inside a frame with OpenBelt's top bar (app name, Remix, Copy link). The bar appends `_framed=1`, which the page strips before scripts run so `location` matches the opened URL. Set `"bar": false` in `public` to remove the bar. `fetch`, `curl`, and link previews always get the bare page. - **Anonymous visitors and privacy:** no sign-in or session cookies exist on the public host (`db.me()` is `null`, writes have author `"anonymous"`). Member authors appear as stable per-app opaque ids (`"author": "member-3f9a…"`, `"authorName": "a member"`). Keep emails out of document data and document ids in public collections. - **Blocked surfaces:** `/mcp`, sign-in, settings, `db.app()`, previews, `/_log`, and uploads (unless `"files": true`, read-only) all return 404 on the public host. Previews are never public; removing `public` or leaving a trial unclaimed unpublishes the app. - **Verification:** run `check_app({ app, public: true })` to verify as a signed-out visitor and catch missing assets or blocked calls. - **CDN and limits:** behind a CDN, static files, `/sdk.js`, and barred pages cache up to 1 minute and purge immediately on deploy (`"bar": false` pages, data, and functions always hit the platform). Public rate limits: `OPENBELT_PUBLIC_APP_WRITES_PER_MINUTE` (default 6000) writes/functions/queries per app per minute, capped per client address at `OPENBELT_PUBLIC_ADDRESS_SHARE`% (default 2% = 120; refused requests do not count; watched queries recover automatically on `rate_limited`), and public writes stop at `OPENBELT_PUBLIC_DATA_SHARE`% (default 50%, HTTP 507) of the app data cap. - **DNS label length:** `--` must fit 63 characters (deploy or workspace rename refuses otherwise; renames redirect the old public host with 308). `deploy_app` and `app_info` return a `public` summary with URL and exposed operations. ## Installable apps and notifications - **Manifest:** put `manifest.webmanifest` at the app's root and link it from your pages (``). It's served as `application/manifest+json`. - **Members install from the workspace:** the app's side panel -> **Devices** -> **This browser** (**This phone**) installs it from its own origin (`--`), private apps included. OpenBelt's manifest there takes your names, description, icons (paths read from the app's root), display, orientation, colours, language and direction. Its id and scope stay `/`, and your start page opens through `/_app` (`today.html` becomes `/_app?to=%2Ftoday.html`), so the installed app opens on its own host, outside the frame. Icons must be paths in the app or `https:` URLs; when none is, OpenBelt's icons are used. A manifest over 64 KB, or with a field of another type (a number for `name`), is ignored: the app gets the one OpenBelt makes from `openbelt.json` (`title`, `icon`, `color`). - **Anyone installs from the public host:** the OpenBelt bar takes your page's manifest link, so Chrome offers the install, and your page in the bar's frame gets the `beforeinstallprompt` event for its own Install button. The installed app opens under the bar; `"bar": false` in `public` removes it. - **Service worker:** register `sw.js` from the root (scope `/`) and answer from the network first, from the cache only offline. A cache-first worker keeps serving the old version after a deploy: two reloads still showed it. Leave OpenBelt's paths (`/_…`) and other origins to the network, except `/_app`: the installed app opens there, so offline the worker answers it with the page its `to` names, or the app launches to the browser's offline page. ```js // sw.js self.addEventListener("install", () => self.skipWaiting()) self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())) self.addEventListener("fetch", (event) => { const url = new URL(event.request.url) if (event.request.method !== "GET" || url.origin !== location.origin) return if (url.pathname === "/_app") { const page = url.searchParams.get("to") ?? "/" event.respondWith(fetch(event.request).catch(() => caches.match(page, { ignoreSearch: true }))) return } if (url.pathname.startsWith("/_")) return event.respondWith( fetch(event.request) .then((response) => { const copy = response.clone() if (response.ok) caches.open("app").then((cache) => cache.put(event.request, copy)) return response }) .catch(() => caches.match(event.request)), ) }) ``` - **Notifications to members:** a function calls `notify(to, { title, body, path })` ([Functions](/docs/functions)). Each member allows the app once; OpenBelt's own worker on the workspace host shows the notification, and a tap opens `/a//`. Your `sw.js` needs no push code. On iPhone and iPad (iOS 16.4+), members install the workspace to the Home Screen first ([Users & auth](/docs/viewers)). - **Not supported:** notifications to people outside the workspace, such as public visitors. `notify` refuses an outside email, and a function can't sign Web Push itself. ## Remix: an app made from another, as your own Anyone who can open an app (workspace members for workspace apps, or any signed-in user for public apps) can remix it into a new live app in their own workspace. **Public means remixable, code included**; there is no opt-out. - **How:** open the app name menu -> Remix (or the public OpenBelt bar), or call `remix_app({ app })` (pass `workspace` for a public app in another workspace, e.g. `remix_app({ app: "game", workspace: "acme" })`). - **Name and privacy:** defaults to `-remix` (or `as`, with free suggestions like `potluck-remix-2` on collision). New remixes start **Private** (owner and admins only) so copied data is never exposed accidentally; share from the app panel when ready. - **What copies:** live files (pages, `functions/`, `skills/`, and `openbelt.json` minus `public`) and every readable document in order (member remixes keep document authors; public remixes include only publicly readable docs with author `"anonymous"`). Subject to standard app size caps (`OPENBELT_VERSIONS_APP_MB`, 256 MB; `OPENBELT_DATA_APP_MB`, 1 GB). - **What never copies:** secret values, connections, stored files, version history, logs, and stats. `remix_app`'s `needs` lists secrets the owner must configure with `set_secret` ([Functions](/docs/functions)). - **Attribution and key scan:** both apps link to each other in their panels (visible remixes only). Make public scans files for hardcoded API keys or tokens before publishing (not run on deploys that already include `public`; keep keys in secrets). ## Skills A skill packages agent instructions (`SKILL.md` plus referenced files) in the [Agent Skills](https://agentskills.io/specification) format under `skills//`: ``` skills/file-expense/SKILL.md skills/file-expense/references/policy.md ``` ```markdown --- name: file-expense description: "File an expense in the expenses app: who paid, how much, for whom. Use for a reimbursement, a receipt or splitting a bill." --- # File an expense Read [the policy](references/policy.md) first, then add one document to expenses. ``` - **Validation:** every folder under `skills/` needs a `SKILL.md` with YAML frontmatter whose `name` matches the folder (1-64 lowercase letters, digits, single dashes; cannot match the app's own name) and a `description` (up to 1024 chars; quote if it contains `: `). Optional fields: `license`, `compatibility`, `metadata`, `allowed-tools`. Max 512 files and 16 MiB per skill; `skills/` may contain only skill folders. - **Auto-generated app skill:** OpenBelt generates `skill:///SKILL.md` per live version describing the app, collections/rules, functions/signatures, and custom skills. Ship your own skills only for workflows, valid values, and policies OpenBelt cannot infer. Preview skills are not served until promoted. - **Discovery:** MCP clients supporting `io.modelcontextprotocol/skills` use `skills/list` (20 newest apps + all custom skills), `skills/get`, and `resources/read` (with SHA-256 and size per file). Other clients call the `skills` tool (`skills()` to list, `skills({ uri })` to read). `app_info` lists skills, `search` indexes them, and the app host serves the files statically. ## The workspace's home page `./` is **Apps**, the workspace home page. ### Tabs, search, and sorting - **Tabs:** All, Yours (`/?mine=1`, shown when you own some but not all visible apps), and Starters (`/?tab=starters`). Clicking a starter opens its detail page (`/?tab=starters&starter=`) with preview, data, skills/functions, and Add (`starter_add` for agents; [MCP](/docs/mcp)). - **All view:** highlights New (horizontal strip when the workspace has more than five apps) and Jump back in (five-card mosaic of your recently opened apps, tracked per user for 90 days without waking apps) above the All apps grid and Starter apps rail. - **Search and sort:** searches name, description, functions, collections, and owner with prefix/typo tolerance (e.g. `expen`, `paino`, `timeoff`), answered directly by the workspace without waking apps (60 per page, Show more for next 60). Sorting by Name or Newest adds a Recently updated strip (last 7 days). - **App cards and info page:** click a card's preview to open the app directly (`/a/`); click its title row underneath to open its info page (`/_apps/`) for details, copyable link, category/tag editing, Change, and Delete (owner/admins only; permanently deletes versions, data, files, runs, logs, previews, and connection grants; `app_delete` / `openbelt app delete --confirm `). - **Empty workspace:** displays a copyable agent prompt and a one-line Claude Code connect command (on plain HTTP under email sign-in, uses the base host `http://localhost:/mcp`). - **Navigation and chrome:** sidebar footer opens `/settings` (agents, tokens, and admin People/Groups/Events; [Connections](/docs/connections#your-settings)) and theme (System/Light/Dark). Cmd+B / Ctrl+B collapses the sidebar; on phones it becomes a drawer. ### App frame and side panel - Opening an app loads `/a/` in a rounded frame following your Light/Dark/System theme (within iPhone safe areas). Click Back to return to Apps; click the app name for Fullscreen (app host without frame) or Copy link. - The right side panel (`/a//_panel`) shows **Devices** (browser and OpenBelt Desktop installs), **Notifications**, **Auto-update** (per-account toggle: off shows an **Update available** toast with **Later** and **Reload** instead of auto-reloading on deploy), and **About**. - Owners and admins also see **Access** (Private, Workspace, or Public; Private hides the app and refuses all access for non-owners), **Stats**, **History** (click any of the last 20 versions to preview in an isolated `history-…` preview with Make live and Undo), **Data**, and **Logs**. ### Usage stats Stats track 7, 30, and 90 UTC days of live browser opens (unique people, page opens, function runs/failures, daily chart, top openers, and public visitors/referrers). Agent calls, `check_app`, previews, static assets, and link bots are excluded. Public visitors are counted once per UTC day with a cookieless daily hash. `app_info.usage` exposes 7-day, 30-day, and last-opened counts to agents. ### App screenshots OpenBelt captures the top 1280x800 of each live page at 1.5x (1920x1200) in both light and dark modes (served at `/a//_shot` and `/a//_shot?theme=dark`, or via MCP `app_picture({ app, theme })`). Captures run read-only and signed-out 10-15 seconds after deploy and at most every 5 minutes on live data changes (so pages requiring sign-in to render anything appear empty). Style dark mode with `:root[data-theme="dark"]`, `@media (prefers-color-scheme)`, `theme.watch`, or a `matchMedia` listener so dark screenshots render distinctly. ## Workspaces Each workspace has its own host (`.`), tokens, and apps (`--.`). Workspaces are fully isolated: two workspaces can both have a `standup` app without seeing each other. Inside a workspace, apps share visibility and can read each other's data via `db.app()`, while separate app origins prevent one app from spoofing writes as another. Legacy `/a//...` links open the app in the workspace frame. --- url: https://openbelt.com/docs/sdk group: Building apps --- > The /sdk.js browser module for documents, aggregates, files people upload (files.put, a url for ), functions, connections, theme, device, and desktop APIs. # SDK Import `/sdk.js` from any page in your app to store live JSON documents, call server functions, invoke workspace connections, and access theme, device, and desktop APIs. It binds to the current app automatically with no keys or setup: ```html ``` ## Documents Keep one mutable document per entity (a card, a vote) and update it in place rather than appending an event log. Collections are created on first write. | Method | Behavior | | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `add(data)` | Creates a document with a generated id and returns it. | | `get(id)` | Resolves to the document or `null` (200 with `null`, not a failed request). | | `set(id, data, { ifSeq? })` | Creates or replaces `id` (1-100 chars: letters, digits, `_ . : @ + -`). | | `update(id, patch, { ifSeq? })` | Shallow-merges fields into `id` (nested objects replace whole). 404 if missing. | | `delete(id, { ifSeq? })` | Deletes `id`. 404 if missing. | | `list({ limit?, cursor?, where?, orderBy?, search? })` | Returns `{ docs, cursor }` (`limit` 1-1000, default 100; `cursor` is `null` at end). `where` filters exact values (`{ status: "open" }`) or ranges (`eq`, `gt`, `gte`, `lt`, `lte`) and `orderBy` sorts (`"field"` or `"-field"`, up to 4) using declared `openbelt.json` `indexes`; `search` runs BM25 full-text search across declared `search` fields (read rules still apply). | | `watch(listener, { onError? })` | Reads all documents (paging automatically), then fires on every change with no gap. Returns a stop function. | | `subscribe(({ op, doc }) => ...)` | Raw realtime feed (`"add"`, `"update"`, `"delete"` where `data` is `null`), replaying missed events on reconnect. Returns a stop function. | - **Document shape:** `{ id, collection, data, author, authorName, updatedBy, agent, created, updated, seq }`. `author` and `authorName` identify the creator, `updatedBy` the last writer ([Users & auth](/docs/viewers)), and `agent` the MCP agent if an agent wrote it. `seq` increases on every app write. Edited documents keep their creation order in lists. - **Rendering from `watch()`:** always render from `docs`. If a write lands while connecting, `watch()` reloads and invokes the listener again with `change === null`. - **Optimistic concurrency (`ifSeq`):** passing `{ ifSeq: doc.seq }` to `set`, `update`, or `delete` fails with 409 (`e.seq` holds the current seq) if the document changed since you read it. `{ ifSeq: 0 }` requires the id not to exist yet (create-only). Rules run before `ifSeq` (403 on rule denial, else 409). Without `ifSeq`, last write wins. - **Limits:** max 64 KB per document. Collection names are 1-40 lowercase letters, digits, `_`, and `-`, starting with a letter or digit. ## 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. ```json { "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 the same workspace can read each other's collections. Discover apps with `search` and inspect schemas with `app_info` (`about`, `docs`, `lastWrite`, `writable`, `rules`, and a newest-doc sample). Treat `openbelt.json`'s `about` as the contract; if absent, read the app with `app_files` before relying on field names. ```js import { db } from "/sdk.js" const votes = db.app("lunch").collection("votes") // 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 }] await db.schedules() // [{ function, cron, timezone, next, last: { at, ok, ms, error, trace } | null }] ``` - **Permissions:** reads are open inside the workspace. Writes to another app fail with 403 (`not_writable`) unless its `openbelt.json` lists the collection in `writable`, and its `rules` still apply. `db.collections()` lists the current app's collections. - **Previews and checks:** in a preview, `db.app(other)` targets `other`'s preview data if `other` is deployed there, else its live data read-only. Link with `appUrl(other, path)`. In `check_app`, `db.app(other)` works only when `other` is in the same preview (else 403 `not_allowed`; [Debugging](/docs/debugging#check-your-work)). - **Realtime and origin isolation:** `subscribe` and `watch` on another app replay missed events after reconnect; deploys to another app do not reload your page. `db.app("lunch")` routes through `/a/lunch/_db/...` on your app's host so OpenBelt knows which app originated the call. Direct cross-origin requests to another app's host fail with 403 (`cross_origin`). - **MCP writes:** `collection_add`, `collection_update`, and `collection_delete` work on any app; coordinate with the owner before modifying someone else's app. ## Files Store user-uploaded images, PDFs, audio, and video in `files` instead of documents (documents cap at 64 KB). Save the returned file record in a document and render from `file.url`: ```js 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) => ``).join("") }) await files.delete(file.id) // removes bytes and record, reclaiming workspace quota ``` Agents upload files in the same order: deploy the app first, upload the files, then write documents referencing them (`collection_add`): - **`file_upload_url({ app, count })`:** returns a 10-minute upload URL for up to `count` files (default 1, max 100). POST raw bytes with `x-openbelt-file-name`: `for f in *.jpg; do curl -sS --data-binary @"$f" -H "x-openbelt-file-name: $f" ''; done`. Never base64 a file into a tool call. - **`file_from_url({ app, url })`:** copies a file from a public HTTPS URL. - **`file_delete({ app, id })`:** deletes a file your user uploaded; remove its references from documents too. - **No shell available:** render an `` with `files.put` so the user uploads directly. - **Previews:** preview files stay in the preview; `promote_app` promotes code only, so re-upload files on live. Put content assets (photos, receipts, PDFs) in `files`, and static app chrome (logos, icons, fonts) in deployed app files. - **`files.put(blob, { name?, onProgress?, signal? })`:** streams a `File` or `Blob`, reports `{ loaded, total }` to `onProgress`, and cancels via `AbortSignal` (`aborted`). Dropped connections fail with `unreachable` (status 0); `busy` retries automatically. Partial/failed uploads keep nothing. - **URLs and access:** `url` is `/a//_files/`, readable by anyone in the workspace from any app host. Only the uploader can delete a file (others get 403 `denied` with `rule: "files.delete"`, not reported as a browser error). Only the app's own pages can upload or delete (403 `not_writable` from other apps). - **24-hour garbage collection:** reference the file (`file`, `file.id`, or `file.url`, or use `file.id` as the doc id) in one of the app's documents within 24 hours, or OpenBelt deletes it (logged in `app_logs`). References in other apps do not retain it. - **Serving and limits:** supports HTTP Range requests and immutable caching. Images, audio, video, PDF, and plain text display inline; other types (HTML, SVG, scripts, zip) download as attachments (`` still displays SVGs). Default limits: 100 MB per file, 10 GB per workspace (see `uploads.fileLimit` and `uploads.workspaceLimit` in `app_info`). Refusals: `file_too_large` (413), `workspace_storage_full` (507), `busy` (503, auto-retried), and `invalid` (400 on interrupted uploads). - **Functions and logs:** server functions read uploads via `ctx.files.read` and mint temporary public URLs via `ctx.files.url` ([Function context (ctx)](/docs/functions#function-context-ctx)). `app_info` summarizes uploads; `app_logs` logs uploads, refusals, and deletes. Preview files clear on `preview_reset` or preview expiry. ## Aggregates: db.aggregate Declare dashboard totals in `openbelt.json`. OpenBelt backfills existing records on the first read and maintains totals in the same transaction as every write (pages, server functions, MCP writes, and imports). ```json { "aggregates": { "expense-count": { "collection": "expenses", "op": "count" }, "expense-total": { "collection": "expenses", "op": "sumInteger", "field": "cents" } } } ``` ```js 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() ``` - **Operations:** `count` returns visible document count in `value`; `sumInteger` sums a top-level safe integer field (store money as integer cents; missing, fractional, nonnumeric, or unsafe integers fail the sum while `count` still works). Both include `count`. - **Read rules:** supports `anyone`, `signedIn`, `nobody`, and `doc.author == me` (or `me == doc.author`, scoping totals to the viewer's records). Other read rules refuse the aggregate. - **Limits and scope:** up to 16 aggregates per app (collection-style names; field identifiers 1-64 chars `[A-Za-z_][A-Za-z0-9_]*`), without filters or grouping. Available in the browser SDK including `db.app(other).aggregate(name)`; server functions read collections directly. - **Overflow and updates:** intermediate overflows fall back to integer source scans; totals beyond JS safe integers set `approximate: true`. Watches coalesce writes for 25 ms and follow `db.query().watch` reconnect behavior. Previews maintain separate totals; editing or removing a declaration discards derived state without touching source records. ## Functions: db.fn and db.query ```js 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)) // live query ``` `db.fn(name, input, { key? })` invokes a server function as the current viewer (`function_failed` or `bad_input` on error; 400 `invalid` if `key` is passed while signed out; 413 past 100 KB input). `db.query(name, input)` runs a `"kind": "query"` function once or live via `.watch(cb, { onError })`. See [Functions](/docs/functions). ## Presence and broadcast: realtime For ephemeral live state that does not belong in documents (who is online, live cursors, typing indicators, reactions, transient room events), use `realtime`. It shares the app's `/_ws` WebSocket, stays in memory (never writes to SQLite), and evicts disconnected tabs immediately. ```js import { realtime } from "/sdk.js" const room = realtime.presence("board:1", { x: 0, y: 0, editing: null }, (peers) => { // peers: [{ id, email, name, state, self }] renderCursors(peers.filter((p) => !p.self)) }) room.update({ x: 120, y: 80, editing: "card-4" }) room.leave() const stop = realtime.broadcast("board:1", ({ room, event, payload, from }) => { // from: { id, email, name } if (event === "ping") showToast(`${from.name ?? "Someone"}: ${payload.text}`) }) realtime.send("board:1", "ping", { text: "Ready!" }) stop() ``` - **Server-stamped identity:** OpenBelt stamps `id`, `email`, and `name` from the viewer's session on the workspace host (`self` is `true` for the current tab). On the public host, `email` and `name` are `null` and `id` is an opaque per-connection id. - **Isolation and reconnects:** rooms are isolated per app, per dataset (live vs each preview), and between workspace and public hosts. When `/_ws` reconnects or a hidden tab wakes, the SDK automatically rejoins active presence and broadcast rooms with the latest state. - **Adaptive coalescing:** rooms with up to 12 viewers fan out presence updates immediately; larger rooms coalesce diffs every 33 ms. Leaves and disconnects evict immediately. - **Public host:** off by default. Set `"realtime": true` in `openbelt.json` `"public"` to allow signed-out visitors on the public host (1 KB payload cap). - **Limits and errors:** max 4 KB per message on workspace host (1 KB on public host), 20 messages/sec per connection (burst 40), 200 broadcasts/sec per room (burst 400), 64 active rooms/app, 8 rooms/connection, 200 viewers/room, room names 1-128 chars, event names 1-64 chars. Pass `{ onError }` to `realtime.presence` or `realtime.broadcast` to handle realtime error codes (`payload_too_large`, `rate_limited`, `room_rate_limited`, `room_cap`, `socket_room_cap`, `room_full`, `public_disabled`, `invalid`); errors never break `db` watches on the same socket. ## Connections: tools.call Call workspace MCP connections (such as Linear or DeepWiki; [Connections](/docs/connections)) from pages with `tools`. OpenBelt holds all tokens and enforces policy; pages never see credentials. Declare every tool and its credential binding in `openbelt.json`: ```json { "description": "My open issues, and ask DeepWiki about a repo", "tools": { "linear.list_issues": "viewer", "deepwiki.ask_wiki_question": "workspace" } } ``` - **`"viewer"`:** runs with the signed-in viewer's own token at their access level after they connect and approve the app on `https://.openbelt.app/connections` (binding new `"viewer"` tools prompts again). - **`"workspace"`:** runs with the workspace's token (or no token for public servers like DeepWiki) at the viewer's level (`none` refuses). ```js 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, ... } await tools.list() // [{ tool, binding, usable, description, input, runsAs | code, message, fix, url }] ``` - **Results and filtering:** `tools.call` returns `{ text, content, structuredContent, runsAs, ms, trace }` (tool errors reject with `code: "tool_error"`). Pass `{ fields: ["name", "types.type.name"] }` to project only needed JSON paths through arrays. - **Consent sheet:** on `needs_token` or `needs_consent`, OpenBelt displays a review sheet linking to the consent page (once per load). Pass `{ prompt: false }` to handle `e.url` yourself. Use `tools.list()` beforehand to render connect prompts cleanly. - **Refusals and checks:** refusals reject with `{ code, message, fix, url, setting, trace }` (not logged as browser errors) and appear in app logs and workspace activity. External servers can take 10-60 seconds, so show loading states (`check_app` waits up to 30 seconds in `wait`/`eval`). In `check_app`, test people have no personal tokens, so `"viewer"` tools refuse with `test_person` (logged in `refusedTools`, not `failedRequests`; verify with `assert: "result.code == 'test_person'"` or call directly with `connection_call`). Signed-out pages run only tokenless tools; `readonly: true` blocks every call (423). ## Theme Read and watch the viewer's OpenBelt theme (`"light"` or `"dark"`): ```js import { theme } from "/sdk.js" theme.current // "dark" const stop = theme.watch((t) => chart.setTheme(t)) // now, then on each change ``` OpenBelt also writes `` or `"light"` before paint (unless your page sets `data-theme`), so CSS can style `:root[data-theme="dark"]` with no script ([Apps](/docs/apps#in-the-frame)). ## Device Use `device` instead of raw browser APIs for geolocation, camera/mic, share sheet, and wake lock: inside the workspace frame, browsers block raw permission APIs ([Users & auth](/docs/viewers)), while `device` works everywhere. ```js 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" } }) // MediaStream await device.share({ title: "Lunch", url: location.href }) // requires a user tap const awake = await device.wakeLock() // stays on while visible; call awake.release() to stop ``` - **Per-app prompts:** location, camera, and microphone ask once per app per device (`NotAllowedError` if declined until reload; `device.share` and `device.wakeLock` need no prompt). - **Cleanup and errors:** stop camera/mic tracks when done (`stream.getTracks().forEach((t) => t.stop())`). Rejections use standard DOM error names: `NotAllowedError`, `NotFoundError`, `TimeoutError`, `NotSupportedError`. - **Photos without prompts:** a plain `` offers the camera and photo library on phones with no permission prompt. Upload it with `files.put`. ## Desktop Progressive desktop APIs when installed through OpenBelt Desktop (floating windows, click-through overlays, background-alive menu-bar popovers, start at login, global shortcuts, native notifications, capture, and clipboard). In regular browsers or browser PWAs, `desktop.available` is `false` and calls resolve `{ ok: false, error: "BROWSER_MODE" }` without throwing. ```js 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", dot: "amber", // "green" | "amber" | "red" | "blue" | "purple" | "#rrggbb" | null menu: [{ id: "wave", label: "Wave" }], // menu is for "tray": true apps (ignored by "menuBar") }) await desktop.setBadge(3) // 0 or "" clears 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()) const stopNotify = desktop.onNotifyAction((ev) => handleNotify(ev)) // click, action, reply, close await desktop.notify({ id: "build-42", title: "Jolly Pet", body: "Build passed", path: "/?focus=build-42", actions: [{ id: "open", label: "Open" }], // macOS action buttons replyPlaceholder: "Reply…", // macOS inline reply }) const sys = await desktop.system.state() // { idleSeconds, idleState, onBattery, locked, platform } const stopSys = desktop.system.onEvent((ev) => handlePower(ev)) // suspend, resume, lock, unlock, on-battery, on-ac const shot = await desktop.capture.region() const clip = await desktop.clipboard.read() await desktop.clipboard.write({ text: "Copied from OpenBelt" }) } ``` - **Permissions and version pinning:** declare capabilities in `openbelt.json` under `"desktop"` (`floating`, `tray`, `menuBar`, `startAtLogin`, `shortcuts`, `notify`, `capture`, `clipboard`, `width`, `height`, `titleBar`). OpenBelt Desktop pins grants to `x-openbelt-version`; after a new deploy, calls return `{ ok: false, error: "VERSION_CHANGED_REPROMPT_REQUIRED", grantedVersion, liveVersion }` until approved via `desktop.requestPermissions()` or **Approve update…**. `desktop.capabilities()` returns granted strings (`"desktop.floating"`, `"desktop.tray"`, `"desktop.menubar"`, `"desktop.startAtLogin"`, `"desktop.shortcut"`, `"desktop.notify"`, `"desktop.capture"`, `"desktop.clipboard"`). Missing/revoked grants return `"CAPABILITY_NOT_GRANTED"`; wrong origins return `"PERMISSION_DENIED"`. - **Title bar (macOS):** non-floating windows default to `"titleBar": "default"` (seamless 34px draggable bar matching top page background). Set `"titleBar": "hidden"` for full-bleed traffic lights (`env(titlebar-area-*)` and `-webkit-app-region: drag`). - **Menu-bar popover & background page:** `"menuBar": { "path": "/menubar.html", "width": 340, "height": 380, "tooltip": "Focus Timer" }` (mutually exclusive with `"tray": true`) pre-warms `/menubar.html` in a hidden frameless popover that stays alive and unthrottled even when windows close. Put background timers, `db` watches, `desktop.setTray({ title, tooltip, dot })`, and `desktop.onShortcut` in `/menubar.html`, sharing state with `index.html` via `db` or `BroadcastChannel`. Control with `desktop.popover.show()`, `hide()`, `resize({ width, height })` (200-800 x 140-900), and `desktop.openWindow(path?)`. - **Floating transparent windows and overlays (`"floating": true`):** OpenBelt Desktop opens a frameless, transparent, shadowless, always-on-top window (visible across macOS spaces and full-screen apps). Set `html, body { background: transparent; }` when `desktop.available` is `true` so the page does not paint an opaque rectangle inside the frameless window, and keep a normal fallback background when `desktop.available` is `false` for browsers. Compact windows (default `260x260`, or explicit `width`/`height` under `800x500`, resizable down to `40x32` with `desktop.setBounds`) drag via CSS `-webkit-app-region: drag` (`no-drag` on buttons/inputs) or move via `desktop.setBounds({ x, y, width, height })` + `desktop.getDisplay()`. Setting `width >= 800` and `height >= 500` creates a full-screen `workArea` overlay: call `await desktop.setClickThrough(true)` on load and toggle `false` on `pointerenter` / `true` on `pointerleave` of interactive elements (mouse move events still forward while click-through is on). `desktop.setAlwaysOnTop(enabled)`, `desktop.setClickThrough(enabled)`, and `desktop.setBounds(...)` require `"floating": true`. - **Start at login, tray, badge, shortcuts:** `"startAtLogin": true` restores hidden in the menu bar at login. `"tray": true` enables OS dropdown `menu` (up to 12 `{ id, label }` items) and `onTrayAction`. `setBadge(countOrText)` requires `notify`, `tray`, `menuBar`, or `floating` (pair with `setTray({ dot })` on Linux compositors without a dock). `onShortcut(accelerator, fn)` requires the exact accelerator in `openbelt.json` `"shortcuts"` (else `"SHORTCUT_NOT_DECLARED"`). - **Notifications, capture, clipboard, system:** `notify({ id, title, body, silent, urgency, path, actions, replyPlaceholder })` requires `"notify": true` and emits clicks/actions/replies to `onNotifyAction`. `desktop.capture` (`"capture": true`) provides `sources(...)`, `screen(...)`, `region(...)`, `pickRegion(...)` (live transparent region selector returning `{ displayId, sourceId, bounds, scaleFactor }` without screenshotting), `showRecordingFrame({ displayId, bounds, elapsedText })` / `hideRecordingFrame()` / `onRecordingFrameAction(fn)` (capture-excluded dashed border and floating stop bar), and `prepareStream(...)` (15-second pre-selection for `getDisplayMedia`). `desktop.clipboard` (`"clipboard": true`) provides `read({ includeImage })` (works from global shortcuts without focus), `write({ text, html, imageDataUrl })`, and `writeFile({ filename, data })` (writes a binary file up to 128 MB to the OS pasteboard so video/audio/document files paste into native apps). `desktop.startDrag({ filename, data, iconDataUrl })` (`"clipboard"` or `"capture"`) initiates a native OS file drag out of the window. `desktop.getDisplay()` (`"floating"` or `"capture"`) returns `display`, `displays`, `cursor`, and `windowBounds`. `desktop.show({ focus })`, `desktop.hide({ restoreFocus })`, `desktop.system.state({ idleThresholdSeconds })`, and `desktop.system.onEvent(fn)` work with any granted capability (Wayland compositors without idle protocol may report `idleSeconds: 0`). Window bounds persist and clamp to active displays. ## Errors Failed calls reject with an `Error` having `status`, `code`, and `trace` (message ends with `(trace )`). Always branch on `e.code`, never on message text. Rule denials (403 `denied`) include `rule` (and the failing clause for `&&` chains) and are not logged as browser errors. Unreadable `openbelt.json` after a server rollback returns 403 `denied` with `rule: "openbelt.json"`. Conflicts (409) include the current `seq`. ### Every code | Code | Status | Meaning | | -------------------------------------------------------------------------------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `invalid` | 400 | Bad name, id, parameter, or body. | | `bad_input` | 400 | Function input failed its `openbelt.json` input schema (function did not run). | | `unauthorized` | 401 | Missing or expired sign-in. | | `denied` | 403 | `openbelt.json` rules refused the read or write. | | `not_writable` | 403 | Target app's `openbelt.json` does not list this collection in `writable`. | | `cross_origin` | 403 | Page called another app's host directly; use `db.app(name)`. | | `live_from_preview` | 403 | Preview page or test person attempted to write live data. | | `not_callable` | 403 | Function is internal, webhook-only, or trigger-only. | | `not_admin`, `not_member`, `private`, `uploads_off` | 403 | Workspace admin required, non-member, private app, or file uploads disabled. | | `not_bound`, `needs_token`, `needs_consent`, `not_allowed`, `signed_out`, `test_person` | 403 | `tools.call` / AI refusal (unbound tool, missing credential or consent with `url`, policy block, signed out, or test person). | | `missing`, `method` | 404 / 405 | no such document, app, environment or file. Or unsupported HTTP method (`method`). | | `conflict` | 409 | `ifSeq` did not match the document's current `seq`. | | `file_too_large`, `workspace_storage_full`, `disk_low`, `busy`, `storage` | 413 / 507 / 503 / 502 | File upload limits or storage errors (`disk_low`: server disk nearly full; `busy`: retried by SDK; `storage`: file store failed). | | `check_readonly` | 423 | `check_app` with `readonly: true` blocked a write, `later`, non-GET/HEAD fetch, or mutating tool. | | `rate_limited` | 429 | Rate limit exceeded; wait `retryAfter` seconds (`Retry-After` header). | | `function_failed`, `internal` | 500 | Function threw or hit limits (`function_failed`; [Functions](/docs/functions)), or unexpected server error (`internal`). | | `upstream_failed`, `tool_error` | 502 / tool | External connection server did not answer (`upstream_failed`) or the tool returned an error (`tool_error`). | | `busy`, `unavailable` | 503 | Concurrency queue full or server restarting (`busy` on `db.fn`, retry after `Retry-After`), or upstream temporarily unavailable. | | `storage_full` | 507 | App, workspace, or server storage cap reached; deletes still work to free room. | | `unsupported_feature`, `quota_exceeded`, `context_too_long`, `refused`, `invalid_output`, `stream_interrupted`, `provider_error` | 400 / 402 / 422 / 502 | AI errors: unsupported capability (400), quota reached (402), prompt too long (400), model refusal (422), schema mismatch (422), dropped stream (502), or upstream provider error (502). | | `payload_too_large`, `room_rate_limited`, `room_cap`, `socket_room_cap`, `room_full`, `public_disabled` | ws | Realtime errors: message over 4 KB (1 KB public), >200 broadcasts/sec in a room, >64 rooms/app, >8 rooms/socket, >200 viewers/room, or public host without `"realtime": true`. | | `blocked_content_type`, `response_too_large`, `too_many_headers`, `unsafe_redirect` | 502 | HTTP route (`/_http/*`) errors: active HTML/script Content-Type blocked, response body >2 MB, >32 response headers, or non-relative `Location` redirect. | | `unreachable`, `aborted` | 0 | Network failure (`unreachable`), or caller's `AbortSignal` cancelled the request (`aborted`, not logged as browser error). | ## Sign-in See `db.me()` in [Users & auth](/docs/viewers). ## Examples Watch a collection with error handling (subscribes before reading so concurrent writes are never missed or duplicated): ```js const stop = db.collection("bugs").watch( (docs, change) => render(docs), // change is null on initial load, then { op, doc } { onError: (error) => showError(error.message) }, ) ``` Create-once signup per slot with `ifSeq: 0`: ```js try { await signups.set(slot + ":" + me.email, { slot }, { ifSeq: 0 }) } catch (e) { if (e.status !== 409) throw e // already signed up; e.seq is the existing document's seq } ``` Page through a whole collection: ```js let cursor = null do { const page = await posts.list({ limit: 1000, cursor }) show(page.docs) cursor = page.cursor } while (cursor !== null) ``` Cursors are opaque; pass them back verbatim. `limit` over 1000 returns 400. ## Realtime and preview environments The SDK maintains one WebSocket (`/_ws`) to the app and one to each watched cross-app target. On disconnect, it reconnects within a second and replays missed document changes in order. - **Hot updates vs reload:** when a new version deploys, OpenBelt patches changed stylesheets, ``, `<style>`, and elements with an `id` in place (preserving input, script state, and scroll). Script or structural changes reload the page (give agent-edited text elements an `id` to keep updates seamless). Turning **Auto-update** off in the app side panel holds deploys behind an **Update available** toast with **Later** and **Reload** (forced reloads for revoked access, preview reset, or compaction still apply immediately). - **Hidden tabs:** tabs hidden for 5 minutes close their sockets so idle apps sleep, then reconnect and replay when visible again. Background reactions belong in triggers or schedules, not pages. - **Previews:** under `/_preview/<env>/`, SDK calls and sockets target preview data automatically: ```js import { env, appUrl } from "/sdk.js" env // "triage" in the triage preview, null on live link.href = appUrl("home") // "https://home--acme.openbelt.app/_preview/triage/" if home is in triage, else "https://home--acme.openbelt.app/" ``` - **Public host:** on `<app>--<workspace>.<public host>`, `db.me()` is `null`, `appUrl("home")` points to the public host, and `db.app()`, `files`, and `tools.call` are refused ([Public apps](/docs/apps#public-apps-anyone-opens-them-on-the-public-host)). ## Under the hood `/sdk.js` wraps standard HTTP and WebSocket endpoints on the app host (`<app>--<workspace>.<domain>`, and `/a/<other>/...` for cross-app calls, or `/_preview/<env>/...` in previews): | Endpoint | Methods & behavior | | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `/_db` | `GET` lists collections (`[{ name, about, docs, lastWrite, writable, rules }]`). | | `/_db/<collection>` | `GET` lists (`?limit=&cursor=&where=&orderBy=&search=`, with `where` as JSON); `POST` adds a document. | | `/_db/<collection>/<id>` | `GET`, `PUT`, `PATCH`, `DELETE` (`?ifSeq=`). Sending `x-openbelt-missing: null` on `GET` turns 404 into 200 `null`. | | `/_changes?collection=&since=&wait=` | Long-polling feed (up to 50s) returning `{ changes: [{ op, doc }], cursor, reset? }` filtered by read rules (for scripts/agents; pages use `watch`/`subscribe`). | | `/_files`, `/_files/<id>` | `POST` uploads (`Content-Type`, `Content-Length`, URL-encoded `x-openbelt-file-name`); `GET`/`HEAD` (Range-capable) reads; `DELETE` removes. `/a/<other>/_files/<id>` is read-only. | | `/_apps`, `/_me` | `GET /_apps` (`?env=`) lists workspace apps; `GET /_me` (`?env=`) returns `{ email, name }` or `null`. | | `/_ws?since=<seq>` | Replays missed changes (or `reload` after reset), emits `hello`, then streams `change` and `reload` messages (carrying changed HTML/CSS payloads up to 64 KB for in-place patching). Ephemeral `presence_*` and `broadcast*` frames share the same socket without touching storage. | Error bodies are JSON `{ error, code, trace }` (plus `seq` on 409, and `rule`/`hint` on 403 rule denials). Origin checks use `Origin`, `Sec-Fetch-Site`, and `Referer` (`cross_origin`, `live_from_preview`, `not_writable`). Signed-in browser requests share a per-person/workspace rate-limit allowance with that person's agents (`429` with `Retry-After`); other users behind the same office IP have separate allowances under a higher shared flood ceiling. --- url: https://openbelt.com/docs/functions group: Building apps --- > Server-side JavaScript functions for atomic transactions, live queries, secrets, external APIs, webhooks, schedules, triggers, long jobs, and Stripe payments. # Functions A server function is JavaScript that runs on OpenBelt (`functions/<name>.js`), declared under `"functions"` in `openbelt.json`. Use functions for atomic writes, caller/group authorization, shared logic across apps and agents, secrets, outbound HTTP, and background runs. ```json { "functions": { "rsvp": "RSVPs the caller to a meetup. input { event }; returns { spots }" } } ``` ```js // functions/rsvp.js export default async ({ event }, { db, caller }) => { if (caller === null) throw new Error("sign in to RSVP") const meetup = await db.collection("events").get(event) const spots = meetup?.data.spots ?? 0 if (spots < 1) throw new Error("this meetup is full") await db.collection("events").update(event, { spots: spots - 1 }) await db.collection("rsvps").set(`${event}:${caller.email}`, { event }) return { spots: spots - 1 } } ``` Twenty users RSVPing for the last 8 spots concurrently get exactly 8: every run commits atomically and retries on read conflicts, so plain read-check-write logic needs no locks. ## Writing a function - **Module format:** standard JS module (no TypeScript, no imports) with default export `async (input, ctx) => result`. Names: 1-40 lowercase letters, digits, `_`, and `-`. - **Declaration:** add a one-line description (up to 500 chars) or `{ description, kind?: "query", internal?: true, http?: true, input?, output? }` in `openbelt.json` `"functions"`. `"internal": true` restricts calls to this app's own functions; `"http": true` (or `{ "methods": ["GET", "POST"] }`) exposes a custom HTTP endpoint at `/_http/<name>` (below). - **I/O and errors:** `input` is the caller's JSON (`null` when omitted), the return value is serialized as JSON (return created ids), and throwing returns the error message to the caller. - **Deploy check:** deploy loads every listed function and aborts if any fails to load. Listed files are never served to browsers. ## Function context (ctx) - `db`: this app's collections (`collection(name)` with `list` including `{ where, orderBy, search, limit, cursor }` for declared indexes and search, `get`, `add`, `set`, `update`, `delete`; `collections()`), targeting preview data in a preview. Errors throw with SDK `status` and `code`. Rules do not guard functions: check `caller` explicitly. - `caller`: `{ email, name, groups }` (plus `agent` when invoked by an agent, propagated to writes), set by OpenBelt. `null` when signed out or for background runs. In `check_app`, test people get only groups the checker is allowed to grant ([Users & auth](/docs/viewers)). - `via`: `"page"`, `"app:<name>"`, `"agent"`, `"http"`, `"schedule"`, `"webhook"`, `"data"`, or `"later"`. Also `env` (preview name or `null`), `app`, `kind`, `run` (`{ id, attempt, key }`), on scheduled runs `schedule` (`{ scheduledFor, lastOkAt, manual }`), and on HTTP routes `path` (the subpath after `/_http/<name>`, `""` when none) and `audience` (`"workspace"` or `"public"`). - `call(name, input)`, `later(name, input, options)`, `cache`, `NonRetryableError`, `secrets`, `connections`: see below. Global `fetch` is available for hosts in `openbelt.json` `"network"`. - `cache`: app-scoped stale-while-revalidate cache in SQLite (live and each preview keep their own; `preview_reset` clears a preview's). `await cache.get(key, { freshFor, staleFor, scope }, loader)` returns cached JSON while fresh (warm reads do no SQLite writes), serves stale immediately within `staleFor` while refreshing in the background (read-only guarded; failed refreshes keep the stale value), and coalesces concurrent cold misses so one `loader()` runs. `freshFor` and `staleFor` accept ms or `"500ms"`, `"30s"`, `"5m"`, `"1h"`, `"7d"` (up to 30 days). `scope` is `"app"` (default) or `"viewer"` (isolated per signed-in workspace viewer; refused for signed-out/public callers). `await cache.invalidate(keyOrPrefix, { prefix, scope })` removes one key or a prefix (`prefix: true` or trailing `"*"`), returning `{ invalidated }`; `scope` is `"app"`, `"viewer"`, or `"all"`. Queries cannot use `cache`. Max 256 KB per entry, 2 MB total per app (LRU evicted). - `files`: the app's own uploaded files ([Files](/docs/sdk#files)), by id or by the object `files.put` gave. `await files.read(file)` is `{ id, name, type, size, bytes }` (`bytes` a `Uint8Array`, up to 10 MB: a fetch sends it whole). `await files.url(file, { expiresIn })` is `{ url, expires }`: a link anyone who has it opens without signing in, for a service that fetches the file itself (a social network posting a picture, say). `expiresIn` is ms or `"10m"`, `"2h"`, `"7d"`: an hour by default, a week at most. `await files.fromUrl(url, { name, type })` streams a file at a public https URL directly into the app's files (up to the file limit, bypassing the 1 MB fetch response cap) and returns `{ id, url, name, type, size, sha256 }` (in a preview without `preview_side_effects`, it returns `{ previewed: true, ... }`). Reference the file in a document or it is deleted after 24 hours. Each is a `db` call (`fromUrl` counts as an external request); another app's file is `missing`, and a query can't make a link or call `fromUrl`. - `webhooks`: `await webhooks.url(fn, { key, expiresIn })` mints a signed, time-limited callback URL (`{ url, expires, key }`) for a function in `"webhooks"` without manual `webhook_secret` setup. Deliveries verify signature and expiry, pass `key` in input, and run once per body: a redelivery of the same body is answered from its first run, and another body at the same link (progress, then done) runs as its own delivery, so make the function safe to run for each event. `expiresIn` defaults to `"1h"` (max `"7d"`). Preview URLs invoke only that preview; queries cannot mint them. - `notify(to, { title, body, path })`: sends push notifications to workspace members (`to`: email or up to 50 emails) who opted in ([Users & auth](/docs/viewers)). Tap opens `path` (default `"/"`); `title` 1-120 chars, `body` up to 500. Returns `{ devices, reached, notOptedIn }` (non-opted-in users are prompted once on next open). Outside emails fail. Counts as an external effect (no silent retries); queries cannot notify; previews require `preview_side_effects`. ```js // functions/ready.js: notify the customer when an order is ready export default async ({ order }, { db, notify }) => { const { customer } = await db.collection("orders").get(order) return notify(customer, { title: `Order ${order} is ready`, body: "Pick it up at the front desk", path: `/?order=${order}`, }) } ``` - `email.send({ to, subject, text, html, replyTo, inReplyTo, references, idempotencyKey })`: sends an email to active people in this workspace (`to`: one email or up to 20; outsiders are refused). Provide `text` (up to 128 KB), `html` (up to 256 KB, sanitized of scripts, inline event handlers, and `javascript:` links; plain text is derived if `text` is omitted), or both. Optional `replyTo` and RFC 5322 `inReplyTo` / `references` thread replies; OpenBelt adds `Message-ID`, `Auto-Submitted: auto-generated`, and `X-OpenBelt-App`. Pass `idempotencyKey` (1-200 chars) so retries within 24 hours replay `{ ...result, replayed: true }`. Returns `{ sent, messageId, delivered, queued, bounced }` (`logged: true` without `OPENBELT_MAIL_TOKEN`, or `error` on failure). Counts as an external request, enforces hourly limits (30 recipients/hour per app, 100/hour per workspace), fails on commit conflict without silent retry, is refused in queries and read-only `check_app`, and returns `{ sent: false, preview, previewed: true }` in previews unless `preview_side_effects` is enabled. ```js // functions/digest.js: email an active member a daily summary export default async ({ to, summary }, { email }) => email.send({ to, subject: "Daily standup summary", text: summary, idempotencyKey: `digest:${to}:${new Date().toISOString().slice(0, 10)}`, }) ``` Do not store state or private caller data in module-level variables: sandboxes are shared across an app's functions per environment and evicted at any time. ## Transactions and retries All `db` writes in a run commit atomically on return; throws and limit errors write nothing. If what the run read changes before commit, the run retries automatically up to 6 attempts (`ctx.run.attempt`), even if it threw, so errors reflect current data. Competing runs wait up to 2 seconds while a retry commits. Reads (`get`, plain `list`, and `list` with `where` or `orderBy`) see uncommitted writes made earlier in the same run; full-text `search` and paginated `cursor` reads must run before writing to that collection. - **Reduce contention:** read by `get(id)`, list with `where`, or keep counters in one document. A `list` with `where` ties the run to the documents it returned and the ones that match it; a plain `list`, a `search`, or a `cursor` page ties it to the whole collection; `db.collections()` ties it to the whole app. - **Isolate independent work:** for multi-source syncs that finish within 30s, fan out with `Promise.allSettled` over `"internal": true` helpers via `ctx.call` so each source commits independently; for larger or slower syncs, have the scheduled function only enqueue `ctx.later` jobs (no inline work before queueing) so one failing source never blocks the rest. - **Nested `ctx.call`:** read-only sub-calls share read dependencies with the caller; committing sub-calls commit immediately (re-read modified data if needed). Sub-calls cannot see the caller's uncommitted writes and throw if they touch them: pass needed values as input or write after `call` returns. Unawaited fetches and writes are still awaited before commit. - **External effects and conflicts:** a run that sent a non-GET/HEAD `fetch`, a non-read-only connection tool, `ctx.ai.run`, or `ctx.notify` cannot retry silently and fails with kind `conflict` on DB contention. Split the atomic DB step into an `"internal": true` helper and `await call(...)` before calling the external API: ```js // functions/join.js: atomic RSVP (may retry), then email (once) export default async (input, { call, caller, secrets }) => { const { spots } = await call("rsvp", input) await fetch("https://mail.example.com/send", { method: "POST", headers: { authorization: `Bearer ${secrets.MAIL_KEY}` }, body: JSON.stringify({ to: caller.email, event: input.event }), }) return { spots } } ``` ## Live queries Set `"kind": "query"` for read-only functions (no writes, fetches, `call`, `later`, `notify`, or `ai`) that pages can watch live: ```js const stop = db.query("attendees", { event }).watch((list) => render(list)) const once = await db.query("attendees", { event }) db.app("meetups").query("attendees", { event }).watch(render) // another app's query ``` - Only watched queries whose reads a write could change re-run (for a `list` with `where`: a document it returned, or one that matches it), and identical results are not resent. - Queries calling `Date.now()` re-run every minute (keeping the app awake while watched); pass cutoffs as input when possible. - `db.fn` runs both functions and queries; `db.query` runs queries only. ## Input and output schemas Declare JSON Schemas (`type`, `properties`, `required`, `items`, `enum`, `const`, `anyOf`, `minimum`, `maximum`, `minLength`, `maxLength`, `minItems`, `maxItems`, `additionalProperties`, `description`) for strict validation: ```json { "functions": { "rsvp": { "description": "RSVPs the caller to a meetup", "input": { "type": "object", "properties": { "event": { "type": "string" } }, "required": ["event"] }, "output": { "type": "object", "properties": { "spots": { "type": "integer" } } } } } } ``` - **Validation:** bad input fails before execution (`bad_input`, naming only failing fields; unknown keys are rejected unless `additionalProperties` allows them). Omitted input (`null`) coerces to `{}` when the schema expects an object with no required fields (unless `null` is allowed). Webhooks and triggers skip input validation. Bad output fails the run (`output`) and rolls back all writes. - **Discovery:** agents see typed signatures in `app_info` and input schemas in `search`. Without schemas, OpenBelt reports observed shapes (`/* observed */`, tracking keys the function reads) and adds a `note` when an agent passes unread keys (such as a typo). ## Calling functions | Caller | How to invoke | Notes | | ---------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | App page | `await db.fn("rsvp", { event }, { key? })` | Rejects with `function_failed` or `bad_input`. Preview pages run preview functions only (`live_from_preview`). | | Another app's page | `await db.app("meetups").fn("rsvp", input)` | Sets `via: "app:<yours>"`, same viewer. | | Agent | `call_function({ app, function, input, key?, preview? })` or `execute` | Discover with `search` or `app_info` (`call` is `null` for webhook/trigger/internal functions; [Code](/docs/code)). | | Browser agent (WebMCP) | Automatic via `/sdk.js` (`GET /_webmcp`) | Exposes callable functions as tools (queries marked read-only) running as the viewer. Skips internal/HTTP/webhook/trigger functions; on public host, only `public.functions`. | - **Idempotency keys (`key`):** retries with the same `key` from the same signed-in caller within 24 hours replay the successful result (`replayed: true`). Reusing a key with different input or calling with a key while signed out returns 400. ### HTTP endpoints: `/_http/<name>` Add `"http": true` (or `"http": { "methods": ["GET", "POST"] }`) to a function's `openbelt.json` entry to serve it at `/_http/<name>` (and `/_http/<name>/*`, or `/_preview/<env>/_http/<name>` in a preview) with standard Web `Request` and `Response`: ```js // functions/calendar.js export default async (req, { db, path, audience }) => { const events = (await db.collection("events").list({ limit: 100 })).docs const lines = [ "BEGIN:VCALENDAR", "VERSION:2.0", ...events.map((e) => `SUMMARY:${e.data.title}`), "END:VCALENDAR", ] return new Response(lines.join("\r\n") + "\r\n", { headers: { "content-type": "text/calendar; charset=utf-8" }, }) } ``` - Use HTTP endpoints for non-JSON responses (iCal `.ics`, RSS/Atom XML, CSV, SVG badges, binary PNGs, raw `text/plain` webhook challenges) or REST subpaths (`ctx.path`). Cannot combine with `"kind": "query"`, `"internal": true`, schedules, webhooks, or triggers, and cannot be invoked via `db.fn` or `call_function`. List under `openbelt.json` `"public".functions` to expose on the public host. - **Response security boundary:** active HTML/script Content-Types (`text/html`, `application/xhtml+xml`, `text/javascript`, `application/javascript`, XSLT) are blocked (`502 blocked_content_type`; serve HTML/JS as static files). Safe data/media types (`text/calendar`, RSS/Atom/XML, CSV, plain text, JSON, SVG, PNG, JPEG, WebP, PDF) serve inline; unknown/binary types get `Content-Disposition: attachment`. Every response sets `X-Content-Type-Options: nosniff` and `Content-Security-Policy: sandbox; default-src 'none'; style-src 'unsafe-inline'`. `Set-Cookie`, `Refresh`, `X-OpenBelt-*`, `Access-Control-Allow-Credentials`, and workspace-host `Access-Control-*` headers are stripped (only `Access-Control-Allow-Origin: *` is allowed on public hosts); `Location` must be a same-origin `/` path (`unsafe_redirect`); ingress `Cookie`/`Authorization`/`X-OpenBelt-*` are stripped; mutating workspace requests enforce same-origin (`403 cross_origin`); secrets are scrubbed from body and headers. Request bodies cap at 256 KB, raw response bodies at 2 MB (`502 response_too_large`), and 32 headers (`too_many_headers`). `function_runs` records `{ status, contentType, bytes }` (`trigger: "http"`). ## Secrets, network, and connections Functions only reach external hosts, secrets, and connections declared in `openbelt.json`: ```json { "functions": { "join": "RSVPs the caller and emails a confirmation. input { event }" }, "network": ["mail.example.com"], "secrets": { "MAIL_KEY": "the mail service's API key" }, "uses": { "deepwiki": "answers questions about a repo's code" } } ``` ### Network - `"network"` allowlists public HTTPS hosts (`"api.example.com"`). OpenBelt hosts, private/local IPs, and DNS names resolving to them are blocked (`"localhost:<port>"` works only in `bun run dev` and verify). - Identity/proxy headers (`Tailscale-*`, `Cf-*`, `X-Forwarded-*`, `X-OpenBelt-*`, `Host`) are stripped. - `fetch` does not follow redirects so secrets never leak across hosts: 3xx responses return as-is with `Location` (logged in `app_logs`); fetch the target yourself if its host is in `"network"`. ### Secrets - Declare `"NAME": "purpose"` or `{ "for": "purpose", "hosts": [...] }` and deploy first. - **Never handle secret values in chat or code:** call `set_secret({ app, name })` (app owner or workspace admin only; sending a value is refused). On MCP `2026-07-28` clients supporting URL elicitation, `set_secret` opens the secure entry form and re-checks automatically; otherwise give the user the returned `url` (8-4000 chars, no leading/trailing whitespace, no U+FFFD) and wait until saved. `set_secret` with `value: null` removes it. - **Host pinning:** a secret only transmits to hosts allowed when it was set (or `set_secret`'s `hosts`); expanding allowed hosts in a later deploy pauses the secret until re-saved. - **Per-run placeholders:** `secrets.NAME` returns a single-run placeholder (`{{secret:NAME:<nonce>}}`) substituted only on outbound `fetch` from that run. Always read `secrets.NAME` inside the handler, never at module top-level (reused sandboxes reject stale placeholders). Any placeholder written to `db`, `call`, `later`, connections, results, or logs degrades to inert `{{secret:NAME}}`, and untrusted input containing placeholder text is never substituted. - **Context-aware encoding & redaction:** OpenBelt encodes substituted values to match context (percent-encoded in URLs/params, form-encoded in `application/x-www-form-urlencoded`, JSON-escaped in `application/json` strings; always set `content-type` for JSON/form bodies). Responses (bodies, status text, headers, connection outputs) echoing a secret raw, URL-encoded, form-encoded, or JSON-escaped (up to two layers) are redacted back to placeholders (note: scanning dense 1 MB escaped responses can add up to ~175 ms CPU outside the run limit; pin secrets only to their own API). OpenBelt controls `Accept-Encoding` (`gzip`, `br`) and rejects other encodings. Failed fetches return fixed messages with scrubbed runtime details in `app_logs`. - **HMAC signing:** `await secrets.hmac("NAME", text)` returns hex HMAC-SHA256 when the secret is active for every host in `"network"`. ### Connections (uses) - Call declared connections via `await connections.deepwiki.ask_wiki_question({ ... })` (bracket notation for dashes: `connections["cmp-deepwiki"]`). Returns structured content or parsed JSON/text directly. - Runs as the caller at their policy level. On `"both"`-credential connections, defaults to the workspace credential; pass `{ as: "me" }` as the second argument to use the caller's own token (requires the user to invoke the app directly and grant consent on Connections). - `later` and trigger runs evaluate under the initiating user (using workspace tokens only); `schedule` and `webhook` runs use workspace tokens at the stricter of everyone's level and the app owner's. Signed-out runs can use only tokenless connections (`signed_out`). ### Preview environments In previews, non-GET/HEAD fetches and non-read-only connection calls do not execute externally; they return `{ previewed: true, ... }`. Check `previewed` before treating a call as real. Only an owner of every app in the preview or a workspace admin can enable real side effects via `preview_side_effects` (resets if another app joins). ## Schedules, webhooks, triggers and later: runs nobody calls ```json { "schedules": { "reminders": { "cron": "0 9 * * *", "timezone": "Europe/London" } }, "webhooks": { "tickets": { "verify": "hmac-sha256" } }, "triggers": { "welcome": { "on": "add:rsvps" } } } ``` Background runs execute with `caller: null` and their `via` set. Webhook, trigger, and internal functions cannot be called directly (403 `not_callable`); scheduled functions can (for "refresh now" buttons). Your own functions can reach any of them via `call` or `later`. - **`schedules`:** 5-field cron (1-minute minimum step), IANA `timezone` (default `"UTC"`), optional `input`. Only live schedules run (`app_info` and page `await db.schedules()` show `next` and `last: { at, ok, ms, error, trace }`). Runs fire at a deterministic per-app offset within the minute; downtime-missed runs fire once. DST spring-forward shifts skipped times forward (collapsing multiple skipped times to one run at the transition); fall-back repeats `*` schedules and runs fixed-time schedules once. - **`webhooks`:** `POST https://<app>--<workspace>.openbelt.app/_hook/<function>`. Signatures verify before execution (bad signature -> 401; truncated body -> 400). `verify`: `"hmac-sha256"` (`X-Signature: sha256=<hex>`, customizable via `header`, `prefix`, `encoding`), `"github"`, `"stripe"`, `"token"`, `"callback"` (only links your function made with `webhooks.url`; see [Long jobs](#long-jobs-work-that-takes-minutes)), or `"none"` (anyone may POST). Optional `key` header (max 200 chars) dedupes identical raw bodies with 200 (different body refused); a `"stripe"` webhook with no `key` dedupes by the event's `id`. Use `webhook_secret` to create the secret and URL. A sender that makes its own signing secret (Stripe) gets `"secret": "<NAME>"`: the delivery is checked with that app secret, declared in `"secrets"` and pasted by a person through `set_secret` (see [Payments with Stripe](#payments-with-stripe)). Handler receives `{ body, headers, raw }`; return value is the 200 reply, throw is 500, queue saturation is 503 with `Retry-After`. A refused delivery (401) runs nothing and isn't a run: `app_info`'s `webhooks` counts them with the last reason and `trace`. **Reply fast:** external senders time out quickly (GitHub after 10s). Store the payload and enqueue slow work with `ctx.later`: ```js // functions/tickets.js: ack immediately; functions/triage.js handles slow work export default async ({ body }, { db, later }) => { await db.collection("tickets").set(String(body.id), { ...body, state: "new" }) await later("triage", { id: String(body.id) }, { in: "1s", key: String(body.id) }) return { ok: true } } ``` - **`triggers`:** `on` is `"<op>:<collection>"` or an array, where `op` is `add`, `update`, `delete`, `set` (add or update), or `write` (any). Receives `{ op, collection, id, doc, before }` right after commit. A trigger's own writes never re-trigger itself; chains stop at depth 4; failures do not retry; call-tree cap is 100 runs. - **`ctx.later(name, input, { in?, at?, key?, retries?, backoff? })`:** schedules a one-off run 1 second to 30 days ahead (`in`: ms or `"30s"`, `"10m"`, `"2h"`, `"1d"`; `at`: Date or ISO string), booked only if the run commits. `retries` (0-10, default 0) retries thrown errors with jittered `backoff` (`"exponential"`, `"linear"`, or `"constant"`, default `"exponential"`); throw `new NonRetryableError("...")` (global or `ctx.NonRetryableError`) to fail immediately without further retries. A `key` stays reserved while pending and across retries (`{ booked: false }` on duplicate), frees when done (a running `later` function can still re-book its own key), and can be cancelled with `await ctx.later.cancel(key)` (`{ cancelled, key }`). Inspect pending/retrying runs with `await ctx.later.list({ prefix?, fn?, limit? })`. Mark `later`-only functions `"internal": true`. ```js // functions/followup.js, booked with later("followup", { event }, { in: "1d", key: event }) export default async ({ event }, { db }) => { const meetup = await db.collection("events").get(event) if (meetup?.data.cancelled) return { skipped: true } await db.collection("followups").set(event, { event, sent: false }) } ``` ## Long jobs: work that takes minutes A run stops after 30 s and each `fetch` after 10 s, so a job that takes minutes (image or video generation, transcription, an export) runs at an outside service's queue API, and your app keeps a document per job: 1. **Start** (a function a page calls): add a `jobs` document, make a callback link for it with `webhooks.url("done", { key: jobId, expiresIn: "2h" })`, send the job with that link to the service, mark the document `status: "running"` with a `deadline`, and book a poll with `later("poll", { jobId }, { in: "10s", key: jobId })`. If the service refuses, throw: the run commits nothing. 2. **Finish** (`done`, a webhook with `"verify": "callback"`): look the job up by `key`, and write the result only if it isn't finished yet (a function run is one transaction, so a second delivery, or a poll that won, changes nothing). Cancel the poll with `later.cancel(key)`. 3. **Poll** (`poll`, `"internal": true`): the fallback when a webhook is lost. Ask the service for the status; if it's done, finish the job as `done` does; past `deadline`, cancel at the service and write `status: "failed"`; otherwise book itself again (a running `later` function may re-book its own key). 4. **Page**: watch `jobs` live (`db.collection("jobs").watch`) and give `jobs` rules a page can't write. ```json { "functions": { "start": "starts a generation. input { prompt }; returns { jobId }", "done": "the service's callback: finishes the job", "poll": { "description": "checks a job the callback hasn't finished", "internal": true } }, "webhooks": { "done": { "verify": "callback" } }, "secrets": { "FAL_KEY": { "for": "fal's API key", "hosts": ["queue.fal.run"] } }, "network": ["queue.fal.run"], "rules": { "jobs": { "read": "signedIn", "create": "nobody", "update": "nobody", "delete": "nobody" } } } ``` ```js // functions/start.js export default async ({ prompt }, { db, later, webhooks, secrets }) => { const { id: jobId } = await db.collection("jobs").add({ prompt, status: "starting" }) const { url } = await webhooks.url("done", { key: jobId, expiresIn: "2h" }) const r = await fetch( `https://queue.fal.run/fal-ai/flux/dev?fal_webhook=${encodeURIComponent(url)}`, { method: "POST", headers: { authorization: `Key ${secrets.FAL_KEY}`, "content-type": "application/json" }, body: JSON.stringify({ prompt }), }, ) if (!r.ok) throw new Error(`fal refused the job: ${r.status}`) const fal = await r.json() // { request_id, status_url, response_url, cancel_url } await db.collection("jobs").update(jobId, { status_url: fal.status_url, response_url: fal.response_url, cancel_url: fal.cancel_url, status: "running", deadline: Date.now() + 15 * 60_000, }) await later("poll", { jobId }, { in: "10s", key: jobId }) return { jobId } } ``` ```js // functions/done.js: fal POSTs { request_id, status: "OK" | "ERROR", payload, error } export default async ({ key, body }, { db, later }) => { const job = await db.collection("jobs").get(key) if (job === null || job.data.status === "done" || job.data.status === "failed") return { ok: true } await db .collection("jobs") .update( key, body.status === "OK" ? { status: "done", result: body.payload } : { status: "failed", error: String(body.error ?? "the service failed") }, ) await later.cancel(key) return { ok: true } } ``` ```js // functions/poll.js export default async ({ jobId }, { db, later, secrets }) => { const job = await db.collection("jobs").get(jobId) if (job === null || job.data.status !== "running") return const auth = { authorization: `Key ${secrets.FAL_KEY}` } if (Date.now() > job.data.deadline) { await fetch(job.data.cancel_url, { method: "PUT", headers: auth }) await db.collection("jobs").update(jobId, { status: "failed", error: "timed out" }) return } const { status } = await (await fetch(job.data.status_url, { headers: auth })).json() if (status === "COMPLETED") { const result = await (await fetch(job.data.response_url, { headers: auth })).json() await db.collection("jobs").update(jobId, { status: "done", result }) return } await later("poll", { jobId }, { in: "10s", key: jobId }) } ``` - **`"verify": "callback"`:** only a link the app made runs `done` (it carries `key`, `expires` and `sig`); any other POST, a changed `key` or an expired link is a 401 and runs nothing, so nobody can finish a job they didn't start. A link survives a redeploy and a restart; a delivery while OpenBelt is down is retried by the sender, and the poll finishes the job if none arrives. - **App secret or connection:** call the service with an app secret (`secrets.FAL_KEY` in `fetch`) when the poll must work alone: `later`, `schedules` and webhooks run with no signed-in person, and a connection then runs only with a workspace credential. A connection that each person signs in to (`connections.fal...`, per-person) works in `start`, which a person calls, but not in `poll`. - **Costs:** each poll is a run, so poll every 10-30 s, not every second; the app keeps 1000 run records and 1000 pending `later` runs. Copy a result you keep with `files.fromUrl` before the service's link expires. ## Payments with Stripe Bring your own Stripe account: a function starts a Checkout, Stripe's webhook stores the plan, and pages read it but can't write it. ```json { "functions": { "checkout": "starts a Stripe Checkout for the caller. returns { url }", "cancel": "cancels the caller's subscription at Stripe", "stripe": "Stripe's webhook: stores the payer's plan" }, "webhooks": { "stripe": { "verify": "stripe", "secret": "STRIPE_WHSEC" } }, "secrets": { "STRIPE_KEY": { "for": "Stripe's secret API key", "hosts": ["api.stripe.com"] }, "STRIPE_WHSEC": { "for": "the signing secret of Stripe's webhook endpoint", "hosts": [] } }, "network": ["api.stripe.com"], "rules": { "plans": { "read": "id == me", "create": "nobody", "update": "nobody", "delete": "nobody" }, "customers": { "read": "nobody", "create": "nobody", "update": "nobody", "delete": "nobody" } } } ``` ```js // functions/checkout.js export default async (input, { caller, secrets }) => { if (caller === null) throw new Error("sign in to upgrade") const r = await fetch("https://api.stripe.com/v1/checkout/sessions", { method: "POST", headers: { authorization: `Bearer ${secrets.STRIPE_KEY}`, "content-type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ mode: "subscription", "line_items[0][price]": "price_…", "line_items[0][quantity]": "1", client_reference_id: caller.email, success_url: "https://<app>--<workspace>.openbelt.app/?paid=1", cancel_url: "https://<app>--<workspace>.openbelt.app/", }), }) const session = await r.json() if (!r.ok) throw new Error(session.error?.message ?? "Stripe refused the checkout") return { url: session.url } } ``` ```js // functions/stripe.js export default async ({ body }, { db }) => { const s = body.data.object if (body.type === "checkout.session.completed") { await db.collection("plans").set(s.client_reference_id, { plan: "pro", customer: s.customer, subscription: s.subscription, }) await db.collection("customers").set(s.customer, { email: s.client_reference_id }) } if (body.type === "customer.subscription.deleted") { const payer = await db.collection("customers").get(s.customer) if (payer) await db.collection("plans").set(payer.data.email, { plan: "free", customer: s.customer }) } return { ok: true } } ``` ```js // functions/cancel.js: asks Stripe only; the webhook moves the plan to free export default async (input, { caller, db, secrets }) => { if (caller === null) throw new Error("sign in to cancel") const plan = await db.collection("plans").get(caller.email) if (plan === null || plan.data.plan !== "pro") return { plan: "free" } const r = await fetch(`https://api.stripe.com/v1/subscriptions/${plan.data.subscription}`, { method: "DELETE", headers: { authorization: `Bearer ${secrets.STRIPE_KEY}` }, }) if (!r.ok) throw new Error((await r.json()).error?.message ?? "Stripe refused the cancel") return { plan: "cancelling" } } ``` 1. Deploy, then `set_secret` for `STRIPE_KEY` and give the person its link. 2. In Stripe's dashboard, add a webhook endpoint at `webhook_secret`'s `url` (`/_hook/stripe` on the app's workspace host) for the events you handle. Stripe makes the endpoint's signing secret (`whsec_…`). 3. `set_secret({ app, name: "STRIPE_WHSEC" })`: the person pastes that signing secret. Until then every delivery is a 401. - OpenBelt checks `Stripe-Signature` with `STRIPE_WHSEC` before the function runs: no, a bad, or a signature more than 300 s old is a 401. `"hosts": []` keeps the signing secret out of every `fetch`. - Each event `id` runs once: a replay or Stripe's redelivery is answered from the first run. Ids are kept 24 hours and Stripe retries for 3 days, so write plans with `set` (the same result twice), not by counting. - Only the webhook writes `plans`. Stripe can deliver `customer.subscription.deleted` before its answer to `cancel`'s DELETE arrives: a `cancel` that also wrote the plan would find it changed, and a run that already called Stripe isn't run again, so it fails although the cancel worked. The page watches `plans` and shows Free when the webhook lands. `deploy_app` warns when a function that isn't a webhook reads and writes a collection a webhook writes, around a `fetch` that changes something outside. - Pages open the Checkout with `location = url` (`window.top.location` inside the OpenBelt frame). A function checks the plan with `await db.collection("plans").get(caller.email)`. ## Testing functions - **Simulate triggers:** `call_function` with `as: "schedule" | "webhook" | "data" | "later"` (`as: "data"` takes `{ collection, id }`) runs webhook, trigger, and internal functions immediately in live or preview with realistic connection permissions. - **Test webhook signatures:** `webhook_test({ app, function, body, sign: "good" | "bad" | "none" })` tests real signature verification; for a `"verify": "callback"` webhook, add `key` and it delivers at a signed link as `webhooks.url` makes one (`call_function` with `as: "webhook"` passes no `key`). Both `as` and `webhook_test` (and `webhook_secret`) require app owner or workspace admin (preview functions have real secrets). - **Test contention:** `call_function` with `inputs: [...]` (2-20 raw JSON objects, do not stringify) fires runs concurrently. - **Inspect history:** `function_runs({ app, function?, failed?, trace? })` lists runs with trigger, caller, version, attempts, writes, outcome, error `kind`, logs, and `trace` (pass `trace` to see a full `ctx.call` tree). ## Limits | Category | Limit | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Concurrency | 6 runs/workspace, 16/server (`OPENBELT_SANDBOX_TENANT_RUNS`, `OPENBELT_SANDBOX_RUNS`); queues up to 60s (`OPENBELT_SANDBOX_LINE_MS`) before 503 `busy` with `Retry-After`. Up to 8/workspace (16/server) parked waiting on `ctx.call` (`OPENBELT_SANDBOX_TENANT_PARKED`, `OPENBELT_SANDBOX_PARKED`). | | Per attempt | 30s wall time (starts after queueing), 10s CPU time, 200 `db` calls (`list` max 1000), 50 fetches/connection calls/`ctx.call`s (10s per fetch, 10 MB request body, 1 MB response body), 50 console lines. | | Per call tree | 100 total runs (including retries, `call`, and triggers), 2000 `db` calls, 200 fetches/connection calls, max `call` nesting depth 4. Batch items or fan out via `later` for large jobs. | | Payloads & runtime | 100 KB JSON input, 256 KB JSON result (HTTP endpoints: 256 KB request body, 2 MB raw response body, 32 headers). QuickJS interpreter with 128 MB heap (~10x slower than V8 for heavy compute). Web globals (`fetch`, `URL`, `URLSearchParams`, `Request`, `Response`, `Headers`, `crypto` digests/HMAC, `TextEncoder`, `atob`, `Intl`, timers, `structuredClone`); no Node APIs, filesystem, or child processes. | | Per app | 50 functions, 10 schedules, 20 webhooks, 20 triggers, 20 secrets (8-4000 chars), 20 network hosts, 10 `uses` connections, 1000 pending `later` runs (separate per preview; cleared on `preview_reset`), 1000 retained run records. | --- url: https://openbelt.com/docs/ai group: Building apps --- > Built-in AI inference (ai.stream, ai.run, ai.status, ctx.ai) for streaming text, structured JSON, vision and PDFs, web search, and app function tools. # AI OpenBelt provides built-in AI inference for both browser pages and server functions. Stream text, extract structured JSON from images or PDFs, search the web with citations, and let models call your app's functions without managing API keys or provider SDKs. ## Enable AI in openbelt.json Add `"ai": true` to `openbelt.json`, or `{ "webSearch": true }` if the app also uses live web search: ```json { "description": "Receipt scanner and research helper", "ai": { "webSearch": true }, "functions": { "listTasks": { "description": "Lists open tasks", "kind": "query" }, "createTask": { "description": "Creates a task", "input": { "type": "object", "properties": { "title": { "type": "string" } }, "required": ["title"] } } } } ``` ## Browser SDK: ai.stream, ai.run, ai.status Import `ai` from `/sdk.js`. | Method | Behavior | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ai.status()` | Non-throwing probe before the user acts. Returns readiness, active provider, capabilities, model tiers, and context window. | | `ai.stream(req)` | Async iterable of stream events. Never throws; pre-flight failures, disconnects, and aborts yield a terminal `error` event. | | `ai.run(req)` | Awaits `ai.stream(req)` to completion and returns `{ text, data?, sources, calls, messages, usage }`. Throws an `Error` with `code`, `fix`, `url`, `retryable`, `partialText`, `sources`, and `messages` on failure. | `ai.status()` resolves to: ```js { ready: boolean, provider: "openrouter" | "opencode" | "openai" | "anthropic" | "gemini" | "custom" | "chatgpt" | "api_key" | "stub" | null, scope?: "personal" | "workspace", email?: string | null, label?: string | null, creditRemaining?: number | null, creditLimit?: number | null, code?: string, message?: string, fix?: string, url?: string, manageUrl?: string, capabilities: { vision, pdf, webSearch, webSearchWithTools, jsonSchema, tools }, tiers: { fast, balanced, deep }, contextWindow: number, } ``` ### Request options and message shapes Both `ai.stream(req)` and `ai.run(req)` accept: | Option | Description | | --------------------- | --------------------------------------------------------------------------------------------------------- | | `prompt` / `messages` | A single prompt string, or an array of conversation messages (`user`, `assistant`, `tool`). | | `system` | Optional system prompt string. | | `files` | Array of `files.put()` refs (`file` or `file.id`) or browser `File`/`Blob` objects (when using `prompt`). | | `schema` | OpenBelt JSON Schema for strict structured JSON output (returned as `data`). | | `functions` | Explicit allowlist of this app's callable function names. | | `toolChoice` | `"auto" \| "required" \| "<functionName>"` (applies to step 0, then resets to `"auto"`). | | `maxSteps` | Maximum reasoning and tool steps (default `5`, max `20`). | | `webSearch` | Boolean (requires `"ai": { "webSearch": true }` in `openbelt.json`). | | `tier` / `model` | `"fast" \| "balanced" \| "deep"`, or an explicit `model` string. | | `signal` | `AbortSignal` to cancel streaming or an in-flight `onToolCall` prompt. | | `onToolCall` | Async approval hook `(call, { signal }) => "run" \| { run: editedInput } \| "deny" \| { deny: string }`. | | `connectPrompt` | Set `false` to suppress OpenBelt's automatic connect sheet on `needs_token`. | Message shapes for `messages`: - User: `{ role: "user", content: string, files?: [...] }` - Assistant: `{ role: "assistant", content: string, calls?: [{ id, name, input }] }` - Tool result: `{ role: "tool", callId: string, name: string, result: json, isError?: boolean }` `ev.messages` on `done` and `error` contains **only the newly committed messages produced during this call** (excluding your input `prompt` or `messages`), so multi-turn chats append them directly: `history.push(userMsg, ...ev.messages)`. If aborted while paused in `onToolCall`, the uncommitted tool call is omitted so `history` never holds an unpaired tool call. ### Streaming text and web search ```js import { ai } from "/sdk.js" const controller = new AbortController() const userMsg = { role: "user", content: "What are the latest Bun release highlights?" } let text = "" const sources = [] for await (const ev of ai.stream({ messages: [...history, userMsg], system: "Answer concisely with citations.", webSearch: true, tier: "fast", signal: controller.signal, })) { if (ev.type === "status") setStatus(ev.detail ?? ev.stage) if (ev.type === "delta") { text += ev.text render(text) } if (ev.type === "source") { sources.push(ev) renderSources(sources) } if (ev.type === "done") history.push(userMsg, ...ev.messages) if (ev.type === "error") showError(ev.code, ev.message, ev.url) } ``` Events emitted by `ai.stream(req)`: | Event `type` | Fields | Meaning | | ------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `step` | `index` | Start of a reasoning or tool step. | | `status` | `stage`, `detail?` | `"thinking" \| "searching" \| "calling_tool"`. | | `delta` | `text` | Streamed text chunk. | | `source` | `title`, `url` | Deduplicated web citation. | | `tool_call` | `id`, `name`, `input`, `readOnly` | Model requested an app function. | | `tool_result` | `id`, `name`, `result`, `isError` | Function result, or `{ denied: true, reason }` with `isError: true` when denied. | | `done` | `text`, `data?`, `sources`, `calls`, `messages`, `usage` | Terminal success. | | `error` | `code`, `message`, `fix?`, `url?`, `retryable`, `partialText`, `sources`, `messages`, `usage?` | Terminal failure or abort. | ### Structured JSON and files (vision and PDF) Pass `schema` (OpenBelt JSON Schema) to validate structured output, and `files` with uploaded `files.put()` refs (`file` or `file.id`) or ephemeral browser `File`/`Blob` objects: ```js import { ai, files } from "/sdk.js" const uploaded = await files.put(input.files[0]) const { data } = await ai.run({ prompt: "Extract merchant, date, and total in integer cents.", files: [uploaded], schema: { type: "object", properties: { merchant: { type: "string" }, date: { type: "string" }, totalCents: { type: "integer" }, }, required: ["merchant", "totalCents"], }, }) ``` ### App functions as tools and human approval Pass an explicit allowlist of your app's callable function names in `functions: [...]`. OpenBelt builds strict tool schemas from `openbelt.json`, runs each approved call via `db.fn`, and continues the multi-step loop automatically. Use `onToolCall(call, { signal })` to gate writes or let the user edit arguments before execution (`call` is `{ id, name, input, readOnly }`): ```js for await (const ev of ai.stream({ messages, functions: ["listTasks", "createTask"], onToolCall: async (call, { signal }) => { if (call.readOnly) return "run" return await askUserToApprove(call, signal) // "run" | { run: editedInput } | "deny" | { deny: "reason" } }, })) { // handle delta, tool_call, tool_result, done, error } ``` - `toolChoice` (`"auto" | "required" | "<functionName>"`) applies to step 0 and resets to `"auto"` on later steps so forced tool calls cannot infinite-loop. - Combine `schema` with `functions` or `webSearch` freely: OpenBelt routes the final structured answer and validates it against your `schema`. ## Server functions: ctx.ai Inside `functions/<name>.js`, use `ctx.ai.run(req)` and `ctx.ai.status()`: ```js // functions/extractReceipt.js export default async ({ fileId }, { db, ai }) => { const { data } = await ai.run({ prompt: "Extract merchant and totalCents from this receipt.", files: [fileId], schema: { type: "object", properties: { merchant: { type: "string" }, totalCents: { type: "integer" }, }, required: ["merchant", "totalCents"], }, }) return await db.collection("receipts").add({ fileId, ...data }) } ``` - `ctx.ai.run` resolves the app's uploaded file IDs directly on the server and records an external effect so a DB conflict never silently re-runs a spent AI call. - Queries (`"kind": "query"`) cannot call `ctx.ai.run`. Read-only checks (`check_app` with `readonly: true` on a live app) block both browser `ai.stream`/`ai.run` (`POST /_ai/step`) and `ctx.ai.run` unless `OPENBELT_AI_STUB=on`; test AI flows in a preview environment. - If the viewer has not connected an AI provider yet, `ctx.ai.run` fails with `code: "needs_token"` and a connect `url`, and `db.fn(...)` automatically opens the connect sheet on the page. ## Credentials and errors OpenBelt resolves credentials per viewer in this order: 1. `OPENBELT_AI_STUB=on`: deterministic offline stub for `check_app` and tests. 2. The viewer's own connected AI provider (`/_ai/connect`, linked from `/connections` and `/settings`): **OpenRouter** (1-click OAuth PKCE), **OpenCode Go**, **OpenAI**, **Anthropic**, **Gemini**, **Other** (custom OpenAI-compatible base URL), or **Sign in with ChatGPT** when `OPENBELT_AI_CHATGPT=on`. Kept sealed and private per person. 3. The workspace's shared AI provider (configured by a workspace admin at `/connections?tab=workspace`, sealed in the workspace's SQLite database). 4. Operator-configured `OPENBELT_AI_API_KEY` (with optional `OPENBELT_AI_BASE_URL` and `OPENBELT_AI_MODEL_FAST` / `OPENBELT_AI_MODEL_BALANCED` / `OPENBELT_AI_MODEL_DEEP`). > [!NOTE] > Signed-out visitors never fall back to workspace AI or `OPENBELT_AI_API_KEY`. `ai.status()` returns `{ ready: false, code: "signed_out" }`, and `ai.stream` / `ai.run` return `needs_token`. When a signed-in viewer has no credentials yet, `ai.stream` and `ai.run` open OpenBelt's connect sheet automatically. Pass `connectPrompt: false` to render your own link using `ev.url` or `status.url`. ### Hosted prod vs tailnet and local Credentials never cross instances: connecting a provider on a local or tailnet OpenBelt instance stays sealed in that instance's SQLite data and does not apply to hosted `openbelt.com` (or vice versa). | Deployment | How AI credentials work | | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Hosted prod (`openbelt.com`)** | Members connect OpenRouter (1-click OAuth) or bring their own API key at `/_ai/connect`. Admins can configure shared Workspace AI on `/connections?tab=workspace`, and operator `OPENBELT_AI_API_KEY` serves as a signed-in fallback. Sign in with ChatGPT is off by default (`OPENBELT_AI_CHATGPT=off`). Public anonymous visitors never consume workspace or operator keys. | | **Tailnet / self-hosted** | Members connect their own provider at `/_ai/connect` (via `/connections` or `/settings`), or admins connect one shared workspace provider. Optional `OPENBELT_AI_API_KEY` works as a member fallback. | | **Local (`bun run dev`)** | Connect OpenRouter, an API key (OpenCode Go, OpenAI, Anthropic, Gemini, or custom URL), or Sign in with ChatGPT at `/_ai/connect`, or set `OPENBELT_AI_API_KEY`. | Error codes: `needs_token`, `needs_consent`, `not_allowed`, `unsupported_feature`, `quota_exceeded`, `rate_limited`, `context_too_long`, `refused`, `invalid_output`, `aborted`, `stream_interrupted`, `provider_error`, `check_readonly`. --- url: https://openbelt.com/docs/rules group: Building apps --- > Declarative openbelt.json rules enforced by the platform on every collection read, create, update, and delete. # Access rules Declare access rules in `openbelt.json` to control who can read, create, update, and delete documents in each collection. OpenBelt enforces these rules on every request to `/_db` from your pages, other apps, and HTTP clients. > [!WARNING] > Hiding a button in the UI is not security: anyone in the workspace can call `/_db` directly. Enforce ownership and state checks in `openbelt.json` rules. In this poll app, only a poll's author can edit or delete it, and each signed-in user gets one vote per open poll: <!-- example: polls --> ```json { "collections": { "polls": "one doc per poll: { title, options, closed }", "votes": "one doc per person per poll, id <poll>:<email>: { poll, choice }" }, "rules": { "polls": { "read": "anyone", "create": "signedIn", "update": "doc.author == me", "delete": "doc.author == me" }, "votes": { "read": "anyone", "create": "signedIn && id == newDoc.data.poll + ':' + me && get('polls', newDoc.data.poll) != null && get('polls', newDoc.data.poll).data.closed != true", "update": "doc.author == me && newDoc.data.poll == doc.data.poll && get('polls', doc.data.poll) != null && get('polls', doc.data.poll).data.closed != true", "delete": "doc.author == me && get('polls', doc.data.poll) != null && get('polls', doc.data.poll).data.closed != true" } } } ``` ```js await db.collection("votes").set(poll.id + ":" + me.email, { poll: poll.id, choice }) // set: the rule checks the id await db.collection("polls").update(poll.id, { closed: true }) // closing is an update: its author only ``` - **All four ops required:** a collection listed under `rules` (by exact name or prefix like `"v_*"`) must state `read`, `create`, `update`, and `delete` (`"anyone"` for an open op). Deploy refuses partial rule blocks. A collection omitted from `rules` is open to anyone in the workspace. - **Create vs update:** `set(id)` runs the `create` rule when the id is new, and `update` with `ifSeq: 0` runs `create`. - **Every clause matters:** without `votes.delete`, anyone can delete someone else's vote; without the poll check on `votes.update`, a voter can move their vote to another poll or change it after closing. - Close a poll rather than delete it. Once a poll is deleted, anyone signed in can create a poll with its id (and its old votes), and no rule can refuse that. ## Rule syntax | Identifier | Meaning | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `anyone`, `nobody` | Always allow (`true`) or always refuse (`false`). | | `signedIn` | `true` when a user is signed in; `false` when signed out. | | `me` | The signed-in viewer's email, or `null` when signed out. | | `groups` | The viewer's workspace groups, a list: `'editors' in groups`. Empty when signed out and on the public host. | | `id` | The target document's id. | | `doc` | Existing stored document (`doc.author`, `doc.updatedBy`, `doc.id`, `doc.data.<field>`). Not available in `create`. | | `newDoc` | Document after the write (`create` and `update`). | | `get('coll', id)` | Reads another document in this app, or `null`. At most 2 distinct `(collection, id)` pairs per rule (repeating the same lookup counts once). | - **Operators and literals:** `== != < <= > >= in && || ! + ( )`, single-quoted strings (`'text'`), numbers, `true`, `false`, and `null`. A missing field evaluates to `null`. - **Comparisons:** `< <= > >=` hold only between two numbers or two strings; anything else is false (`'5' > 0` is false, as is a missing field). `"create": "signedIn && newDoc.data.qty > 0 && newDoc.data.qty <= 100"` refuses a quantity outside 1 to 100. - **Lists:** `x in list` is true when the list holds `x`, and false when the right side isn't a list. `"update": "me in doc.data.editors"` lets the people named in a document's `editors` edit it; add `&& newDoc.data.editors == doc.data.editors` so they can't change who edits. Rules can't write a list themselves, so the list comes from a document. - **Trusted identity fields:** `author` is the creator and never changes; `updatedBy` is the last writer. Both come from the session. Anything under `data` comes from the client, so compare it against `me`. - **Group checks:** `"create": "'editors' in groups"` lets only the `editors` group create; a person's agent is judged with that person's groups. A read rule about the viewer alone (`'staff' in groups`, no `doc`) applies to the whole collection at once, so lists stay indexed and [aggregates](/docs/sdk) count it. A change to someone's groups applies to their next request; their open pages reconnect. For a list of people that isn't a group, keep it in a document whose rules let only its owner change it, and check `me in get('teams', 'editors').data.people`. For a check rules can't express, set the write rule to `"nobody"` and write in a [server function](/docs/functions) that checks `caller.groups`. On live, an agent's direct write to a `"nobody"` collection is also refused when an app function writes that collection (call the function instead); with no such function (like seed-only data), owner and admin writes go through. ## More on rule syntax - An exact collection name beats a prefix key (`"v_*"`); between two prefixes, the longer wins. - `id` for `add()` is the generated random id. `doc.data` traverses nested objects (`doc.data.owner.email`). In `update`, `newDoc.data` is the stored document merged with the patch. `get()` reads the same environment (live or preview). - `+` adds numbers and concatenates strings (`null` if either side is `null`). A rule passes when its result is truthy in JavaScript (`null`, `false`, `0`, and `""` fail). Property access on `null` evaluates to `null`: `get('polls', x).data.closed != true` is true when the poll does not exist, so pair it with `!= null`. No loops, regexes, or extra functions exist. - Signed-out writes have author `"anonymous"`, which never equals `me`. Start rules with `signedIn &&` when signed-out visitors must be blocked. - An id convention like `<poll>:<email>` enforces nothing without a rule checking `id`. Setting `"delete": "nobody"` on `polls` makes closing the only way to end a poll. - Rules govern who can write which document, not field shapes. Use `collections.<name>.schema` in `openbelt.json` to validate document shapes. ## Denials - A refused write returns HTTP 403 and changes nothing: `{ error: "denied by rules.polls.update: doc.author == me", code: "denied", hint }`. The SDK error exposes `e.status`, `e.code`, and `e.rule`. For an `&&` chain, the error names the failing clause: `denied by rules.votes.update (failed: get('polls', ...).data.closed != true)`. Denials are logged as `"rule denied ..."` and are not reported as browser errors. - A `read` rule filters denied documents out of `list`, `get` (`null`), and `watch`. - Rules run before `ifSeq`: `set(id, data, { ifSeq: 0 })` on an existing id returns 403 if `update` refuses, and 409 otherwise. - Deploy refuses invalid rules (`doc.title` instead of `doc.data.title`, `=` instead of `==`). When sign-in is off, deploy warns if rules reference `me`, `signedIn`, `author`, or `updatedBy`. `app_info` lists each collection's active rules. - Test denials in a preview environment with `check_app` and `people` ([Test as several people](/docs/viewers#test-as-several-people)): run the SDK write in `eval`, then `{ action: "expect", status: 403 }`. ## Testing a denial Here `alice` creates a poll and `carol` (not the author) attempts to close it: <!-- example: polls-denial --> ```json { "app": "polls", "preview": "rules", "people": ["alice", "carol"], "steps": [ { "as": "alice", "action": "eval", "save": "pollId", "script": "const { db } = await import('/sdk.js'); return (await db.collection('polls').add({ title: 'Lunch?', closed: false })).id" }, { "as": "carol", "action": "eval", "script": "const { db } = await import('/sdk.js'); await db.collection('polls').update('{{pollId}}', { closed: true }).catch(() => {})" }, { "as": "carol", "action": "expect", "status": 403 } ] } ``` The `expect` step passes when the write is refused (`answered 403 (rules.polls.update)`) and fails with `expected 403 from PATCH /_db/polls/<id>, got 200` if it succeeds. Target a document that exists: updating or deleting a missing id returns 404 before rules run. Deploy also refuses `doc` in a `create` rule (use `newDoc`) and a third distinct `get()`. Rules take effect with their version; test rule changes in a preview before promoting. A `read` rule can return fewer than `limit` documents on a page while `cursor` is still non-null. When an update hides a document from a viewer, their `watch` receives a `delete` event with `data: null`. ## MCP writes An agent gets the same access as its user's browser, unless that user owns the app or is a workspace admin: - **App owner or workspace admin:** without `as`, `collection_add`, `collection_update`, and `collection_delete` write as the token's user and bypass rules (for seeding and data fixes). `collection_list` reads every document. - **Any other member:** rules evaluate with them as `me`, and `read` rules filter `collection_list`, `collection_changes`, and `execute`. A denial matches the browser's (`denied by rules.polls.update: doc.author == me (403)`). Ask the app's owner (`app_info` names them) to make changes outside the rules. - **Test people in previews:** passing `as: "carol"` with `preview` runs the write as that test person and evaluates rules as her page would. For migrations (merging duplicates or re-keying documents), owner and admin writes without `as` may specify `author` and `updatedBy` per document so the original owner keeps control. Passing `author` or `updatedBy` with `as` is refused. A batch (`docs: [...]`, up to 500) is atomic: if any document is refused, nothing writes and the error lists each refusal. <!-- example: polls-move --> ```js // bob's vote moves from duplicate poll p1 to p2, still his collection_update({ app: "polls", collection: "votes", docs: [ { id: "p2:bob@acme.com", data: { poll: "p2", choice: "Tacos" }, replace: true, ifSeq: 0, author: "bob@acme.com", updatedBy: "bob@acme.com", }, ], }) ``` --- url: https://openbelt.com/docs/viewers group: Building apps --- > How apps identify signed-in users with db.me(), auth modes (email code, OIDC, Tailscale), multi-user testing, and app installation. # Users & auth OpenBelt handles authentication for every app. Pages read the signed-in user from `/sdk.js` instead of building their own login forms or asking users to type their name: ```js const me = await db.me() // { email, name } when signed in, null when signed out // writes from a signed-in page set doc.author (email) and doc.authorName automatically ``` > [!NOTE] > Never build a sign-in form or ask users for their name. OpenBelt redirects signed-out visitors to sign in when email or SSO auth is enabled; show signed-out visitors a read-only view and enforce write access with [Access rules](/docs/rules). - **Verified vs client data:** OpenBelt sets `db.me()`, `doc.author`, `doc.authorName`, `doc.updatedBy`, and `doc.agent` from the session (client headers are stripped). `author` stays the creator forever; `updatedBy` tracks the last writer. Signed-out writes use `"anonymous"`. Over MCP, writes use the token's user and record `agent` (`_meta` `"openbelt/agent"`, `OpenBelt-Agent` header / `openbelt --agent`, or known client like `"claude-code"` / `"codex"`). Anything inside `doc.data` is untrusted client input. - **Caching:** `db.me()` fetches once per page load; pass `{ refresh: true }` to re-check. - **Who can reach an app (`deploy_app`'s `reach`):** - **Email sign-in / OIDC (hosted prod and public servers):** users sign in with an email code, Google, or company SSO (Okta, Entra ID, Keycloak) and return to the app ([Email sign-in](#email-sign-in), [Sign-in on a public host](#sign-in-on-a-public-host)). - **Tailnet:** everyone on the tailnet is signed in as their Tailscale login ([Tailnet](/docs/tailnet)); tagged devices (servers, exit nodes) are signed out. - **Invite-only workspaces:** only workspace members enter ([People and groups](/docs/people)); everyone else sees a refusal page. - **Local dev (`bun run dev`):** the owner port signs in as you automatically; the signed-out port (`<port> + 1000`) uses email sign-in. - **Sign-in off (`OPENBELT_SIGNIN=off`):** nobody is signed in; private apps open only for owner agents (MCP, `check_app`). - **Testing multiple users:** use preview test people below, never a real person's email. ## Test as several people In a preview environment, `check_app`'s `people` creates synthetic teammates, each in their own browser already signed in as `<name>@<app>.test` (e.g. `alice` is `"Alice"`). A step's `as` selects whose browser runs it (default: first person). All browsers stay open across steps so one user immediately sees another's live changes. `save` captures an `eval` return value (or matched text for `expect`/`wait`) for later `{{name}}` interpolation. To test group gates, pass objects with `groups`: `people: [{ "name": "ed", "groups": ["editors"] }, "viv"]` (visible in `caller.groups` inside functions; limited to groups you belong to unless you own every app in the preview or are a workspace admin; cross-app live queries outside the preview see no groups). <!-- example: polls-people --> ```js check_app({ app: "polls", preview: "close-rule", people: ["alice", "bob", "carol"], steps: [ { as: "alice", action: "fill", selector: "#question", value: "Lunch?" }, { as: "alice", action: "click", selector: "text=Create poll" }, { as: "alice", action: "eval", save: "pollId", script: "return document.querySelector('.poll').dataset.id", }, { as: "bob", action: "click", selector: ".poll[data-id='{{pollId}}'] .option" }, { as: "alice", action: "expect", selector: ".poll .votes", text: "1 vote" }, { as: "carol", action: "expect", selector: "text=Close poll", count: 0 }, { as: "carol", action: "eval", script: "const { db } = await import('/sdk.js'); await db.collection('polls').update('{{pollId}}', { closed: true }).catch(() => {})", }, { as: "carol", action: "expect", status: 403 }, ], }) ``` - **Per-person output:** step lines and console logs are tagged by person (e.g. `[carol] ok: expect status=403 (PATCH /_db/polls/<id> answered 403 (rules.polls.update))`), and `people` in the report includes each person's final text and controls. - **Asserting denials:** `expect` with `status` (and no selector) checks that person's latest data request since their previous step (`path` narrows it). Alternatively, `assert: "result.status == 403"` on `eval` treats a thrown SDK error as `result`. Expected denials go to `expectedDenials`; unexpected ones go to `denied` (never `failedRequests`). Always test the 403 write directly, not just a hidden button. - **Seeding as test people:** pass `as: "alice"` with `preview` to `collection_add`, `collection_update`, and `collection_delete` to write as `alice@<app>.test` under the app's rules. - **Preview-only:** test people are refused on live apps (403). ## More on test people - Names are 1-30 lowercase letters, digits, and dashes (up to 5 per check). Using `as: "alice"` without `people` implies `people: ["alice"]`. - `{{name}}` substitutes verbatim (quote it in scripts: `'{{pollId}}'`); referencing an unsaved variable fails before the check starts. - Test sessions work only under `/_preview/<env>/` and `/_me?env=<env>`. Without `people`, `check_app`'s browser is always signed out. - Check sessions are scoped strictly to the checked app and other apps in the same preview you may open; any other host returns 403. ## Who says so `OPENBELT_SIGNIN` controls how OpenBelt identifies viewers: | Value | Who is viewing | Typical environments | | ----------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------- | | `email` | Signed-in via `/signin` email code or OIDC, plus any front-door identity | Hosted prod (`openbelt.com`), public self-hosted, `bun run dev` | | `tailscale` | `Tailscale-User-Login` and `Tailscale-User-Name` set by the trusted front door | `bun run tailnet`, `bun run dev`, verify, `deploy/signin` | | `off` | Nobody | Local or headless server with no front door | Under `tailscale`, only a trusted front door (loopback proxy like `tailscale serve` / `scripts/lib/frontdoor.ts`, or a remote proxy sending `X-OpenBelt-Front-Door: <OPENBELT_FRONT_DOOR_SECRET>`) can assert identity; direct requests get 403 (except self-authenticated routes: `/mcp`, `/scim/v2`, `/_ops`, webhooks, OAuth token endpoints, `/_health`, `/_tls/ask`). Compose binds to `127.0.0.1` by default unless `OPENBELT_BIND` is set. On `bun run dev`, the owner door on `127.0.0.1:<port>` signs you in automatically for `*.localhost` hosts only (bare `localhost`, `127.0.0.1`, and unknown hostnames return 421). The platform port (`<port> + 1000`) has no owner door and accepts only OpenBelt's configured hostnames (`localhost`, `OPENBELT_HOST`, `OPENBELT_BASE_HOST`, loopback, `ts.net`). `/_me` (`/_me?env=<env>` in previews) returns `{ email, name }` or `null`. Sessions use a single host-scoped `__Host-openbelt_session` cookie signed with `OPENBELT_SESSION_SECRET` (defaults to the admin token). ## Email sign-in Under `OPENBELT_SIGNIN=email`, users sign in once on the base host with a 6-digit email code (or configured OIDC provider). Each workspace verifies membership and issues its own host-only session. ### Sign-in flow and workspace switching - Opening a workspace or app link returns directly to that destination after sign-in without a picker. - Your theme choice syncs across workspaces and devices (first signed-in visit imports any existing local browser theme). - In the workspace picker, each workspace is one tap (current marked with a check, invites marked **Join**, colleague workspaces **Ask**; **Create a workspace** reveals name + Create). Opening an existing workspace uses its active session or carries your base-host sign-in via a short-lived nonce-bound ticket (`/_signin/return`) with no second code. - The marketing page's Sign in opens your last-used accessible workspace (or only workspace), falling back to the picker when ambiguous; signed-in visitors see **Dashboard** (`/start`) in the header. - Clicking the workspace name in the sidebar (**Switch workspace**) opens the picker directly on the base host without redirecting through the current workspace. - Unknown workspaces return 404 without creating files (operator routes `/_ops/*`, `/_health`, `/_tls/ask` still answer). Signed-out data calls return 401. ### Codes, delivery, and allowlists - Codes expire after 10 minutes or 5 wrong guesses (single-use; 30s resend cooldown, 10/hour per email, 30/hour per client IP across hosts -> 429). Gmail/Outlook and Google Workspace/Microsoft 365 domains (300 ms MX lookup) show an **Open Gmail** or **Open Outlook** button. - Production email uses Cloudflare Email Sending via `OPENBELT_MAIL_TOKEN` (Email Sending: Edit), `OPENBELT_MAIL_ACCOUNT`, and `OPENBELT_MAIL_FROM` (default `hello@<base host>`). Codes are never logged in prod; without a mail token (local dev or Docker without mail configured), codes print to the server logs (`docker compose logs openbelt`). - `OPENBELT_SIGNIN_ALLOW` restricts who receives codes (comma/space-separated emails and `@domains`; disallowed addresses see the normal screen with no email sent). - Operator bootstrap links: `POST /_ops/signin-links` (`{"email": "..."}`) or `bun run workspace signin-link <email>` mints a 15-minute single-use sign-in link; `POST /_ops/claims` mints a 1-hour (`OPENBELT_CLAIM_TTL_SECONDS`) first-admin claim link (`<workspace host>/claim/<code>`, 409 once an admin exists). - For Tailscale previews of email sign-in, `bun run dev --email` uses email auth on HTTPS and accepts `000000` on `/signin/code` as the latest logged code for that email. ### Google and company OIDC - **Google:** set `OPENBELT_GOOGLE_CLIENT_ID` and `OPENBELT_GOOGLE_CLIENT_SECRET` (redirect URI `https://<base host>/_signin/google/callback`) to enable **Continue with Google** (`OPENBELT_GOOGLE_ISSUER` overrides for testing). - **Company SSO:** set `OPENBELT_SSO_ISSUER`, `OPENBELT_SSO_CLIENT_ID`, `OPENBELT_SSO_CLIENT_SECRET`, and optional `OPENBELT_SSO_NAME` (redirect URI `https://<base host>/_signin/sso/callback`). - Requires a verified email claim (`email_verified`, or Entra ID's `xms_edov` added under Token configuration) and honors `OPENBELT_SIGNIN_ALLOW`. Uses OIDC + PKCE + nonce (10-minute single-use in the initiating browser). Mismatched form/provider emails prompt before signing in. Test real OIDC end to end with `bun run e2e:oidc` ([Running](/docs/running)). ### Sessions and diagnostics - Sessions last 30 days (`Secure` cookie: requires HTTPS or `*.localhost`). Signing out ends the base browser sign-in and all derived workspace/app sessions (closing open sockets) without affecting other browsers or MCP tokens. Removing a workspace member ends their sessions there immediately. - The base host remembers the last email (`__Host-openbelt_email`, 1 year, `HttpOnly`) to prefill **Welcome back** (`/signin?another=1` clears it). - Signed-out visits to `/signin` log `sign-in: signed-out visitor at /signin: <reason>; remembered email: yes|no` (`no session cookie`, `bad signature`, `cookie expired`, `cookie for another host`, `malformed cookie`, `session ended`). Filter server logs for `"signed-out visitor"` when diagnosing sign-in issues. ## Sign-in on a public host To put a company identity provider in front of self-hosted OpenBelt via oauth2-proxy + Caddy (`deploy/signin/`): ```sh docker compose -f compose.yaml -f deploy/signin/compose.yaml --profile tls up -d ``` Configure `OPENBELT_FRONT_DOOR_SECRET` (`openssl rand -hex 32`), `OPENBELT_SSO_ISSUER`, `OPENBELT_SSO_CLIENT_ID`, `OPENBELT_SSO_CLIENT_SECRET` (redirect URI `https://<OPENBELT_HOST>/oauth2/callback`), `OPENBELT_SSO_COOKIE_SECRET` (`openssl rand -hex 16`), and optional `OPENBELT_SSO_EMAIL_DOMAIN`. - One cookie covers `.<OPENBELT_HOST>`; sign out at `/oauth2/sign_out`. OpenBelt's port stays unpublished behind Caddy, which strips incoming identity headers. - `/mcp` and webhooks keep their own auth. `check_app` routes through Caddy's unpublished `OPENBELT_CHECK_DOOR=caddy:8443` listener using its own session cookies. - Workspace joining still governs membership (`"open"`, `"invite"`, or SCIM; [People and groups](/docs/people)). For multiple customer IdPs, place a broker (Keycloak or Dex) in front. Removing a user in OpenBelt revokes access immediately (provider cookie refresh takes up to 7 days by default). ## Every app on its own host Each app runs on its own origin (`<app>--<workspace>.<domain>`) so browsers isolate apps just like separate domains: - **Origin enforcement:** OpenBelt identifies the calling app by host and rejects cross-origin data calls (`403 cross_origin` via `Origin`/`Sec-Fetch-Site`). - **Framing protection:** app responses send `Content-Security-Policy: frame-ancestors 'self' https://<workspace>.<domain>` (plus any admin-configured embedder via `workspace_embed_set`), preventing clickjacking. Apps cannot override response headers (`frame-ancestors` in `<meta>` is ignored by browsers). - **Device permission isolation:** the workspace frame withholds direct camera, mic, and geolocation grants so one app cannot inherit another's grants. Apps use `device` from `/sdk.js` ([SDK](/docs/sdk#device)), which prompts per app inside the frame and falls back to browser APIs in standalone windows/tabs. - **Session scoping:** under Tailscale, the front door authenticates every host directly. In `check_app`, each app host gets its own `__Host-` cookie. Under email sign-in, each app host exchanges a short-lived nonce-bound ticket for its own `__Host-` cookie. ## Installed workspace ### Installing the workspace - Open the person menu -> **Add to Home Screen** (mobile) or **Install OpenBelt** (desktop). Chromium triggers a native prompt; iPhone shows an interactive 4-step Safari guide. - Installs are per workspace (origin-isolated, named **OpenBelt**). Standalone windows hide install prompts, keep the workspace switcher, and show **Refresh app** in the person menu and `/settings` to apply OpenBelt platform updates on demand (checking on launch, foreground, reconnect, and every 5 minutes; restores URL and scroll; requires connectivity, no offline cache). ### Installing individual apps (browser & OpenBelt Desktop) - Open any app's side panel -> **Devices** to install to **This browser** / **This phone** or any connected **OpenBelt Desktop** computer (or manage all devices at `/settings/devices`). - Each app has its own origin, manifest (`/_pwa/manifest.webmanifest`), desktop metadata (`/_pwa/desktop.json`), generated PNG icons (`/_pwa/icon-{180,192,512}.png`), standalone entry (`/_app`), and install page (`/_install`). An app that ships its own `manifest.webmanifest` installs with its name, icons and start page ([Apps](/docs/apps#installable-apps-and-notifications)). Private apps refuse these routes to unauthorized users. - **OpenBelt Desktop:** clicking **Connect this Mac** in **Settings › Devices** (or **Install** when running locally) exchanges a one-time ticket (`POST /_desktop/connect` -> `http://127.0.0.1:47821/connect` -> `POST /_desktop/redeem`). Download the macOS app from `/_desktop/download` (`OPENBELT_DESKTOP_DOWNLOAD_BASE`, default `https://downloads.openbelt.com`). - OpenBelt Desktop runs installed apps in one shared host process with lightweight native launchers (`~/Applications/OpenBelt Apps/*.app` on macOS, `.desktop` on Linux), prompts with a native permission sheet pinned to `x-openbelt-version`, and lets you revoke capabilities from the tray menu. First launch plays a brief intro (**Get started** registers login item and opens the workspace; **Esc** dismisses; replay with `--intro`). On macOS it updates itself: it checks `desktop/releases-mac-<arch>.json` under the download base at launch and every 4 hours, downloads a newer signed build in the background, and installs it on the next quit, or right away from the tray's **Restart to update**. ## Notifications Notifications sent by server functions (`ctx.notify`, [Functions](/docs/functions)) are opted into per app: 1. After an app first notifies you, your next visit prompts **Get notifications from this app?** (**Allow** or **Not now**). 2. **Allow** subscribes the device and enables that app; **Not now** stays off without re-prompting. 3. Toggle anytime via **Notifications** in the app's side panel. - Tapping a notification opens `/a/<app>/<path>` in the workspace frame. - Choices sync across all your subscribed devices (up to 10 devices per person per workspace; oldest drops past 10; removing a member clears devices). Works in desktop Chrome, Edge, Firefox, Safari, and Android tabs; on iOS/iPadOS 16.4+, install the workspace to the Home Screen first. - `/_pwa/sw.js` registers only when you allow notifications and handles push/click events without intercepting page requests. --- url: https://openbelt.com/docs/debugging group: Building apps --- > Verify apps in a headless browser with check_app, inspect browser errors in app_logs, and trace requests end to end. # Debugging Verify every app change in a real headless browser with `check_app` before promoting it to live. When something breaks for a user in production, inspect `app_logs` and follow the request's `trace` id. ## Check your work Standard loop: deploy (`preview`) -> `check_app` with steps -> `app_logs` for browser errors -> patch -> `promote_app`. <!-- example: standup-check --> ``` check_app({ app: "standup", preview: "standup-fix", width: 390, steps: [ { action: "fill", selector: "#name", value: "Ada" }, { action: "select", selector: "#mood", value: "Happy" }, { action: "click", selector: "text=Post" }, { action: "expect", selector: ".post", count: 1 }, { action: "expect", selector: ".post .mood", text: "Happy" } ]}) ``` `check_app` opens the page in a fresh headless Chromium browser (through Playwright) and returns each step's outcome, `errors` (uncaught errors and rejections with stacks), `console` errors and warnings, `failedRequests` (a `get(id)` miss is not one), `dialogs`, `title`, visible `text`, and `controls` (buttons, links, and fields with values and options). Stack locations map to deployed files (`app.js:12:5`, `index.html:1:345`). ### Step actions (up to 40 per call) | Action | Parameters & behavior | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `click`, `hover` | Click or hover the first visible match. Hover-revealed controls (`li:hover .del`) are hovered into view first. | | `fill` | Sets any input value (including date `"2026-10-26"`, time `"09:30"`, color `"#ff8800"`), fires `input` and `change` without keystrokes, reads back, and fails if the value does not match. | | `type` | Clicks the field and types `value` key by key after existing text. Use when key handlers or autocomplete matter. | | `select` | Selects a `<select>` option by value, else label, and fires `change`. | | `check`, `uncheck` | Toggles a checkbox or radio (or its label). | | `drag` | Drags `selector` onto `to`, grabbing outside inner controls. Follow with `expect` (warns if nothing moved in the DOM). | | `scroll` | Scrolls `selector` into view, or `value`: `"top"` / `"bottom"`. | | `press` | Presses `value` (`"Enter"`, `"Tab"`, `"Escape"`, arrow key, character, or chord like `"Shift+Enter"`, `"Control+a"`). | | `wait` | Waits for `selector` (`state`: `visible` default, `hidden`, `attached`, `detached`), `ms`, or `assert`. | | `goto` | Navigates to `value` (a path in this app, or another app in the same preview). | | `upload` | Picks synthetic files for `<input type=file>` at `selector` (even hidden inputs). `value` is comma-separated names (real images for `.png`/`.jpg`/`.webp`/`.gif`, one-page `.pdf`, text for `.txt`/`.csv`/`.md`, else random bytes; `"deck.pdf:20MB"` up to 200MB tests size limits). | | `expect` | Asserts `text` (exact), `textIncludes`, `value`, `count` (`0` for none), `visible`, `checked`, or `attr: { name, value }`, retrying up to `ms` (default 3000). With `status` and no selector, asserts the last data request status (`403` for a rule denial; expected 4xx replies stay out of `failedRequests`). | | `eval` | Runs async JS `script` in the page and logs its JSON result. Single expressions (`document.title`) return directly. Throws fail the step (including SDK `status` and `rule`). | - **Selectors:** standard CSS (`:has()`, `:nth-child()`), `text=Label` (`text="Save"` for exact), and Playwright forms (`li:has-text("Milk") .del`, `:text-is()`, `>>` chaining like `#list >> text=Milk >> nth=0`, `role=button[name="Save"]`, `label=Email`, `placeholder=Search`). Invalid CSS fails before the check starts. - **Hidden targets:** a hidden control fails explaining why (closed menu or `<dialog>`, `display: none`) and what to open first. - **Inline assertions and `notes`:** any step accepts `assert` (a JS expression checked until `ms`). `check_app` normalizes common aliases (`timeout` -> `ms`, `waitFor` -> `wait`, `contains` -> `textIncludes`) and reports ignored fields in `notes`. Text assertions search the full element (only diagnostic excerpts truncate). - **Failure handling:** stops at the first failure, except in a preview or `readonly: true` check where failed `expect` steps continue up to 3 failures so one call shows every mismatch. - **Preview vs live (`readonly: true`):** preview data is isolated test data that persists across checks until `preview_reset`. On live data, pass `readonly: true`: writes (including from popups) and mutating functions (writes, `later`, non-GET/HEAD fetches, non-read-only connection tools) return 423 (`blocked`) with nothing saved. Rules do not run under `readonly: true`; test rules in a preview. - **Cross-app isolation:** a check reaches only the target app and other apps deployed in the same preview that you may open. Any other `db.app(other)` call returns 403 `not_allowed`. Deploy both apps into one preview (`deploy_app({ app: "<other>", preview: "<env>", keep_others: true, seed: "live" })` by its owner) to test cross-app flows; use `goto` to `/a/<other>/_preview/<env>/`. - **Fresh browser and `people`:** every check starts signed out with empty cookies and storage (service workers are disabled; `alert`/`confirm`/`prompt` auto-accept and log in `dialogs`). Pass `people` in a preview to test signed-in multi-user flows ([Test as several people](/docs/viewers#test-as-several-people)). Use `screenshot: true` for a JPEG image and `width: 390` for phone layout. Checks time out 30 seconds after launch (plus 10 seconds per extra person). - **Logs and traces (`app_logs`):** records deploys, promotions, writes, 404s, and automatic browser errors (`browser error on <page>: <message> (<file:line>) (<browser>, version <v>, live|preview <env>)`; `check_app` errors are marked `check`). Every tool result except `docs` includes a `trace`; pass it to `app_logs` to see only that call. Browsers receive the injected error reporter automatically; `curl` and `app_files` receive deployed files unchanged. - **Inspecting state and data:** - `app_info`: live version, files, last 20 versions (`version`, `deployedAt`, `promotedAt`, `by`, `kind`), collections (`about`, `docs`, `lastWrite`, `writable`, `sample`), and active preview environments. - `collection_changes`: changes since a `cursor` (`wait` holds up to 50 seconds). - `collection_list`, `collection_add`, `collection_update`, `collection_delete`: read and mutate live or `preview` data. Owners and admins bypass rules unless `as` is set (`as: "alice"` in a preview writes as that test person); other members are judged by rules ([Access rules](/docs/rules#mcp-writes)). `collection_list` pages with `cursor` (default 50, max 200 or about 100 KB). `collection_delete` with `all: true` clears a collection. `collection_add` and `collection_update` accept atomic `docs: [...]` batches (up to 500), `id`, `ifSeq` (`0` for create-only), and `author`/`updatedBy` (without `as`) for migrations. ## More on check_app - Actions and `expect` wait up to `ms` (default 3000) for the first visible match. Skipped steps read `not run: ...`. An `expect` with no check field is refused. - `fill` also handles `datetime-local`, `month`, `week`, and `range`; it fails if a handler rewrites the field or the value is out of range. `type` appends to existing text (run `fill` with `""` first to clear); `\n` presses Enter. - `drag` uses pointer events and HTML5 drag and drop. If every point on the element is a control or occluded, the step fails naming the obstacle. - `expect`'s `text` collapses whitespace; `text=Label` targets the innermost matching element. `path` on a status `expect` matches that path or any path beneath it. - `eval` truncates results past about 1500 characters. When an `eval` step has `assert`, a thrown error becomes `result` (`{ message, status, rule, code }`) instead of failing the step. A `readonly` 423 fails a status-403 `expect`; reads, sign-in, and error reporting still work under `readonly`. - Reports also include `denied`, `expectedDenials`, `blocked`, `refusedTools` (`tools.call` refusals, separate from `failedRequests`), `status`, `url`, and `incomplete` (when stopped early). - A check that fails to start (bad step or selector, missing app, busy pool) returns `isError: true` with fix instructions and a `structuredContent` report showing `errors`, `incomplete`, and `not run` steps. Servers run up to `OPENBELT_CHECKS_AT_ONCE` (default 4) browsers concurrently (one workspace gets all but 2) and wait up to 20 seconds for a slot. - Each browser page has a 512 MB JS heap cap; exceeding it logs `Page crashed` in `errors` (page through large datasets). - `check_app` has no daily limit. On self-hosted servers, set `OPENBELT_CHROME_PATH` if Chrome is in a custom location. ## Errors from the browser When a browser requests an app document (`Sec-Fetch-Dest: document`), OpenBelt prepends `<link rel="modulepreload" href="/sdk.js">` and a small error reporter in `<head>`. It posts uncaught errors, unhandled rejections, `console.error` calls, failed script or stylesheet loads, and failed SDK calls to `POST /_log` on the app host, producing log lines like: ``` browser error on /standup/: Uncaught TypeError: list is null (app.js:12:5) (Chrome 141, version 3f2a9c1e0b7d, live) ``` - Failed SDK calls log under that call's `trace`; `check_app` errors log under the check's `trace`. - Rate limits: at most 20 distinct reports per page load, 30 per app per minute, and 1 per minute for the same error from the same page and browser. ## Trace ids and logs - Every request receives a trace id: returned in `x-openbelt-trace`, error bodies, MCP results, SDK error messages (`(trace <id>)`), and every resulting log line. - Each app keeps its last 500 log lines: deploys, promotions, refused deploys, data writes (`added preview triage cards/...`), preview seeding/resets/expiry, 404s with serving version, and browser errors. Without `trace`, `app_logs` returns the newest lines. - Local and server logs: `bun run dev` prints every log line and writes `.dev/logs/dev.log`; `bun run verify` writes `.verify/<run>/<check>/platform.log`; Docker deployments log to stdout (`docker compose logs openbelt`). | Question | Where to look | | ------------------------- | ---------------------------------------------------------------------- | | Did my deploy go live? | `deploy_app` result's `version`, and `x-openbelt-version` on the page | | Why is the page blank? | `check_app`, then `app_logs` for browser errors and 404s | | Is it broken for users? | `app_logs`: browser errors with page, `file:line`, and version | | Did the write happen? | `collection_list`, or `app_logs` with the write's `trace` | | What did this request do? | `x-openbelt-trace` from the response, then `app_logs` or platform logs | --- url: https://openbelt.com/docs/code group: Building apps --- > Run short JavaScript scripts on OpenBelt with the execute tool across workspace apps, data, and connections. # Code (execute) `execute({ code })` runs a short JavaScript script on OpenBelt as you, with the entire workspace available on the `workspace` global. Use it to coordinate across multiple apps in one call, test concurrency with `Promise.all`, or test a webhook end to end with `fetch`. Send a function body that awaits and returns JSON: ```js const [found] = await workspace.search("rsvp to a meetup") const done = await workspace.apps.meetups.fn.rsvp({ event: "intro" }) const { docs } = await workspace.apps.meetups.collection("rsvps").list({ limit: 100 }) return { found: found.path, done, rsvps: docs.length } ``` ## The workspace API | Helper | Behavior | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `workspace.search("words")` | Finds functions (with signatures), collections, and connection tools. Names cannot be enumerated, only searched. | | `workspace.describe("<path>")` | Returns call instructions and schema for a discovered path. | | `workspace.apps.<app>.fn.<name>(input)` | Runs an app function, matching `call_function`. | | `workspace.apps.<app>.collection(name)` | Exposes `list`, `get`, `add`, `set`, `update`, and `delete`, matching the collection tools. | | `workspace.connections.<connection>.<tool>(input)` | Calls a workspace connection tool, matching `connection_call`. | | `workspace.me()` | Returns the signed-in user. | - **Non-identifier names:** use bracket notation for names with dashes or leading digits, such as `workspace.apps["hourly-joke"].fn.create_joke(input)` or `workspace.connections["cmp-deepwiki"].ask_question(input)`. `search` and `describe` print paths that way, and `describe` accepts either form. - **Webhook testing (`fetch`):** `fetch` reaches only this workspace's app hosts, as an external sender would. Sign a payload with `crypto.subtle` and POST it to test a webhook end to end. - **Concurrency and previews:** use `Promise.all` to test race conditions and retries. Pass `preview: "<env>"` to `execute` to target apps and data deployed in that preview environment. - **Read-only runs:** pass `readonly: true` to look into a live app's data without any chance of changing it. Each write is refused before it is sent, with status 423 and code `check_readonly`: `add`, `set`, `update` and `delete`, a write inside a function (the function still runs and reads), a connection tool not marked read-only, and a `fetch` other than GET or HEAD. - **No app state of its own:** `execute` has no secrets or external network access. Logic an app needs repeatedly belongs in a [server function](/docs/functions). - **Bulk imports:** use `collection_add` batches instead of looping over `add` in `execute`. See [Importing documents over MCP](/docs/sdk#importing-documents-over-mcp). ## Limits | Constraint | Limit | | ----------------- | -------------------- | | Wall timeout | 60 seconds | | `workspace` calls | 300 per run | | Code size | 100 KB | | Returned JSON | Truncated past 24 KB | Errors return `{ kind, message, line }`, where `kind` is `syntax`, `runtime`, `timeout`, `limit`, or `sandbox`. --- url: https://openbelt.com/docs/connections group: Workspaces & connections --- > Connect MCP servers, OpenAPI specs, and GraphQL endpoints to a workspace with shared or personal OAuth credentials, per-tool access control, and app consent. # Connections For setup, access changes, and personal connection settings through MCP or the `openbelt` CLI, see [Workspace automation](/docs/workspace). Admin operations appear only for workspace admins. A connection is an external MCP server (like DeepWiki or Linear), an HTTP API from an OpenAPI spec (each operation becomes a tool), or a GraphQL endpoint (each Query and Mutation field becomes a tool). Agents and app pages call connection tools through OpenBelt, which holds the credentials, enforces access policies, and logs every call: - `connections({ search: "pokemon" })` finds matching connections and tools across a large workspace. Search before building an app. - `connections()` lists connections you can see with credential state, your effective level (`none`, `read`, or `all`), the rule that set it, and each tool's status. Workspaces with more than 25 connections return a count and prompt you to search. - `connections({ connection: "deepwiki" })` adds each tool's input schema. Connections with more than 60 tools require a search query: `connections({ connection: "github", search: "latest release" })` returns the top 10 matching tools with input schemas. - `connection_call({ tool: "<connection>.<tool>", input: { ... } })` runs a tool with its schema input. Results return the upstream content (`isError` on tool failure) plus a summary line with outcome, duration, and trace id (`structuredContent` carries the same `outcome`). Upstream calls can take 10 to 60 seconds. OpenBelt's own MCP tool list never grows as connections are added; every connection tool runs through `connection_call` by `<connection>.<tool>`. ### Finding one Search by topic or service before building an app: ```js connections({ search: "pokemon" }) // pokeapi: pokemon_retrieve, pokemon_list, ... connections({ search: "weather forecast" }) // weather-gov connections({ search: "a team lunch poll" }) // none: build without a connection ``` - Search spans all MCP servers and APIs and returns at most 5 connections with up to 3 matching tools each (without schemas). Follow up with `connections({ connection, search })` to inspect input schemas. - Matching splits identifiers into whole words (`pet` matches `addPet` and `pet_list`, not `competitor`) and weights rare words higher than common verbs like `list` or `get`. - When nothing in the workspace matches, `notAdded` lists relevant providers from OpenBelt's catalog that a workspace admin can add in **Settings > Connections**. Ask the user rather than inventing mock data. ### Skills from connections When an MCP server advertises the MCP skills extension (`io.modelcontextprotocol/skills`), OpenBelt snapshots up to 50 skills (2 MB total per connection) on add and `refresh`. Each skill is namespaced as `<connection>-<name>` at `skill://_connection/<connection>/<connection>-<name>/SKILL.md` with content-hashed digests. Connection skills obey the connection's access level: members with effective level `none` cannot see or read them. Everyone else sees them in `skills/list`, the `skills` tool, `connections`, and `search`. Servers that do not advertise the extension receive no `skills/*` calls. ## Whose token Each connection declares who supplies credentials: | Credential | Who supplies the token | How a call runs | | ----------- | ---------------------------------------------------------- | -------------------------------------------------------------------------- | | `none` | Nobody (unauthenticated server such as DeepWiki) | No token | | `workspace` | A workspace admin, once for everyone | Workspace token | | `person` | Each member, individually | Caller's own token | | `both` | Workspace has a shared token and members may add their own | Whichever exists; requires `as: "workspace"` or `as: "me"` when both exist | When both tokens exist, `connection_call` refuses calls that omit `as` and names both options. For token-based services (not OAuth), members paste their token on `<workspace host>/connections/<name>` or pipe it via CLI/HTTP (`setYourToken` shows the exact command): ```sh openbelt connection token linear < token.txt curl -X POST https://acme.example.com/_me/connections/linear/token \ -H "Authorization: Bearer $OPENBELT_TOKEN" --data-binary @- ``` Never paste a token into agent chat, and agents must never ask for one. OpenBelt strips tokens from results, errors, lists, and logs, replacing any echoed token with `***`. ### Signing in with OAuth Most catalog services (Linear, Notion, GitHub, Gmail, Jira, Confluence) use OAuth (`signIn: "oauth"` in `connections`): - **Connecting.** When a connection is not yet linked, send the user the `connect` URL from `connections` or the refusal. On MCP `2026-07-28` clients supporting URL elicitation, `connection_call` prompts the client to open the link and retries automatically after sign-in. Each link is single-user and valid for 10 minutes. - **Tasks extension.** Upstream MCP `2026-07-28` servers that advertise `io.modelcontextprotocol/tasks` are polled automatically via `tasks/get` until completion. - **Automatic refresh and reconnect.** OpenBelt refreshes tokens automatically. Transient upstream outages only delay calls. If a provider revokes the grant or the user changes their password, `connections` reports `reconnect` and calls return a fresh link to reconnect. - **Granular scopes.** If a user unchecks optional permissions (such as individual Google services), `scopes` lists what is missing and tools needing that scope return a link requesting it. ## Who may use what Each connection has a default level for `everyone`, plus optional overrides per group or per person: | Level | Permitted tools | | ------ | ---------------------------------------------------------------------------------------------------------------------------- | | `none` | No tools. | | `read` | Tools marked read-only (`readOnlyHint`), read-only HTTP/GraphQL ops, or tools marked read by OpenBelt's catalog or an admin. | | `all` | All enabled tools. | **Effective level rule:** an explicit person override wins first; otherwise the lowest level across any of the person's groups that set one; otherwise the `everyone` default. Admins can also disable individual tools workspace-wide. Workspace policy sets your ceiling. You can further restrict yourself on the connection's page (set your own level to `read` or `none`, or toggle individual tools off). OpenBelt enforces the stricter of workspace policy and your personal setting. Only you can undo a personal restriction. Every refusal names the blocking setting (including `own` for personal settings) and who can change it: admins receive the exact command; members and app viewers receive admin email addresses. `connections` exposes `level` (workspace), `ownLevel` and `ownOff` (personal), `gets` (effective), and `asked` (pending access request). ## In apps App pages call connection tools with `tools.call` from `/sdk.js` ([SDK](/docs/sdk#connections-toolscall)) after declaring each binding in `openbelt.json` under `"tools"`: - **`"viewer"`:** runs with the viewer's own token at their effective level. Before the first call runs, the viewer connects their account (if needed) and grants consent on `/connections` for that exact app, connection, and tool list. Adding new `"viewer"` tools in a later deploy prompts for consent again. - **`"workspace"`:** runs with the workspace's shared token (or no token for unauthenticated servers) at the viewer's effective level. No per-user consent prompt is needed. Signed-out visitors can call only unauthenticated (`none`) tools. Removed members get nothing, and level `none` blocks app calls just like agent calls. OpenBelt identifies the caller app strictly from its origin (`<app>--<workspace>.<domain>`) and rejects cross-origin `/_tools/call` requests. ### What's refused, and why Refused calls reject with `{ code, message, fix, url, setting, trace }` (where `url` points to `/connections` for `needs_token` and `needs_consent`), and log to both `app_logs` and workspace activity. Deploying warns about broken bindings (unknown tool, wrong credential mode, disabled tool, unreachable level, or missing workspace token). In `check_app`, test people hold no personal tokens: `"viewer"` tools return `test_person`, while `"workspace"` tools run at the checking user's effective level (never higher). Apps that bind tools receive 30 extra seconds per check. App functions declaring `"uses"` in `openbelt.json` follow the same access rules ([Functions](/docs/functions)): - Interactive calls (from the app's own page, `call_function`, or manual runs by owner/admin) run as the caller and can use their personal token once they have granted consent for `<connection>.*`. - Cross-app calls, `ctx.later` jobs, and triggers run with the workspace token only (refused on `person`-only connections). - Schedules and webhooks (no user) run at the stricter of `everyone` and the app owner's level. ## Marks Each connection tile displays either the provider's Simple Icons brand mark (`apps/platform/src/web/ui/marks.ts`, adapting near-black marks like GitHub and Vercel for dark mode) or its first letter on a deterministic color tint. Admins can upload a custom icon (PNG, JPEG, GIF, WebP, SVG, or ICO up to 64 KB) from the connection's page, via `connection_icon_set`, or via `POST /_workspace/connections/<name>/icon`. Clear it to revert to the default mark. For custom connections without a built-in mark, OpenBelt attempts once at add time (up to 6 s, unauthenticated, following public-host egress rules) to fetch an icon from `/.well-known/mcp/server-card.json`, `/.well-known/mcp.json`, or the server's homepage/favicon (`apps/platform/src/connections/icon.ts`). ## Your settings `<workspace host>/connections` lives under **Settings > Connections**, with inline tabs across the top: - **Yours:** connections available to you as a 2-column card grid, with explicit account labels (`Workspace account` / `No sign-in`) and direct **Connect** / **Reconnect** actions. - **Workspace** (`?tab=workspace`, admins): all workspace connections, setup status, shared sign-in health, and **Add a connection** (catalog or custom URL). - **Browse** (`?tab=browse`, members): workspace connections currently set to `none` for you, with an **Add** button to request access. - **Allowed apps** (`?tab=apps`, shown when you have consented to apps): apps you have allowed to use your personal connections, with **Revoke**. - **Needs you** (`?tab=needs`, shown only when action is pending): expired personal sign-ins and pending app consent requests. - **AI** (`?tab=ai`): dual-scope view of **Your AI** (personal override) and **Workspace AI** (shared default). Each connection's detail page (`/connections/<name>`) shows its status, personal level and per-tool toggles, an access request form when your workspace grants less than `all`, credential management, consented apps, and (for admins) **Who has access**. When an app page requests viewer credentials or consent, OpenBelt's review sheet links to `/connections?connect=<connection>&app=<app>`, where you connect any unlinked accounts and approve all of the app's `"viewer"` tools in one step. Additional settings live under `<workspace host>/settings`: **Agents** (`/agents`, OAuth sign-ins and API tokens) and, for admins, **People**, **Requests**, **Activity**, and **General** ([People & groups](/docs/people#in-settings)). All settings pages block framing and cross-origin POSTs. ## For admins Admins manage connections in **Settings**, via MCP / `openbelt` CLI ([Workspace automation](/docs/workspace)), or via the self-hosted `bun run workspace` CLI ([People & groups](/docs/people#self-hosted-cli)) and HTTP routes. ### From the catalog OpenBelt ships a catalog (`apps/platform/providers/`) of OAuth MCP servers (Linear, Notion, Jira, Confluence, Sentry, Asana, Stripe, Supabase, Cloudflare, Vercel, Neon, PostHog, Datadog, Grafana, PagerDuty, GitLab, Airtable, PayPal, Paddle, Ramp, Webflow, Canva, Miro, ClickUp, Attio, Granola, GitHub, Google Workspace, DeepWiki, Microsoft Learn, AWS Knowledge, fal, Higgsfield, Apify, and more) and unauthenticated public APIs (OSV, Open-Meteo, World Bank, Crossref, ClinicalTrials.gov, Spaceflight News, PokeAPI, Countries, National Weather Service, Frankfurter, Wikipedia, xkcd, Swagger Petstore). Each catalog entry preconfigures URL, sign-in method, default credential mode, read-only scopes, read-only tool annotations, and (for APIs) spec fixes and a startup test call: ```sh bun run workspace connections add linear bun run workspace connections add stripe --credential person --everyone all bun run workspace connections add linear-eng --provider linear bun run workspace connections add pokeapi bun run providers list ``` ### Signing in: what admins set up Most OAuth servers register OpenBelt automatically via client metadata documents or Dynamic Client Registration. A few need extra setup: - **Services without self-registration (GitHub, Asana, Google).** When the deployment configures [OpenBelt's own apps](#openbelts-own-apps), users sign in immediately. Otherwise an admin registers one OAuth app at the provider using the callback URL shown on the connection page and enters the client ID and secret (shared across every connection at that authorization server, such as all Google Workspace servers): ```sh bun run workspace connections client gh --client-id Ov23li... < secret.txt ``` - **Google Workspace MCP.** Catalog entries target `/mcp/v1self` to omit interactive form-elicitation tools. Single-account setups can use Google's Personal Mode link; multi-user workspaces create a Web OAuth client in Google Cloud Console with "Use this client for an AI-powered agent" enabled ([Google's setup guide](https://developers.google.com/workspace/guides/configure-mcp-servers)). - **HTTPS requirement.** Providers such as Linear and Zendesk require a public HTTPS callback URL (Zendesk also fetches OpenBelt's client metadata document over HTTPS). - **Shared workspace sign-in.** After adding a `workspace` or `both` connection, connect it on its page or run `bun run workspace connections connect <name> --workspace`. - **Custom scopes and token mode.** Override scopes with `--scopes`, extra authorize parameters with `--authorize-params`, force pasted tokens with `--sign-in token`, or test refresh immediately with `bun run workspace connections renew <name> --mine|--workspace`. ### By address, access, and activity ```sh bun run workspace connections add deepwiki https://mcp.deepwiki.com/mcp --credential none bun run workspace connections add linear https://mcp.linear.app/mcp --credential both --everyone read bun run workspace connections add sentry https://sentry.example.com/mcp --credential workspace --sign-in token bun run workspace connections token sentry --workspace < sentry-token.txt # or --from-env SENTRY_TOKEN bun run workspace connections limits fal --per-person 20/1d --per-workspace 100/1d bun run workspace connections refresh linear bun run workspace access linear everyone all bun run workspace access linear group:contractors none bun run workspace access linear person:dave@acme.com all bun run workspace access linear disable delete_issue bun run workspace access linear read list_issues bun run workspace explain bob@acme.com linear.create_issue --app my-issues bun run workspace activity --connection linear --person bob@acme.com ``` Key operational rules: - **Names and egress.** Connection names are 1 to 30 lowercase letters, digits, and dashes starting with a letter. Upstream URLs must use HTTPS on a public host (loopback, RFC1918, link-local, `*.internal`, `*.ts.net`, and OpenBelt's own hosts are refused unless `OPENBELT_ALLOW_LOCAL_CONNECTIONS=1` is set in local dev). - **Safe tool refreshes.** The first tool list on add is enabled immediately for review. Any tool newly added on a later `refresh` (or whose HTTP method changed, or that newly claims `readOnlyHint`) starts **disabled** until an admin explicitly enables it (`bun run workspace access <conn> enable <tool>`). - **Tokens and offboarding.** Tokens are read from stdin or `--from-env`, never CLI arguments (`--clear` removes them). Removing a workspace member deletes all of their connection credentials ([People & groups](/docs/people#removing-someone)). - **Events and access requests.** **Settings > Activity** (`/admin/events`) combines the latest 5,000 MCP tool calls and 500 connection calls with search and filter chips ([Self-hosting](/docs/running#agents-tool-calls)). **Settings > Requests** (`/admin/requests`) groups pending access requests by connection and desired level so admins can approve or dismiss individually or in bulk (requests auto-close once satisfied or after 30 days). ### APIs (OpenAPI and GraphQL) Add any HTTP API from an OpenAPI 3, Swagger 2 (JSON/YAML), or Google Discovery spec (up to 32 MB), or any GraphQL endpoint: ```sh bun run workspace connections add petstore --kind openapi --spec https://petstore3.swagger.io/api/v3/openapi.json --credential none bun run workspace connections add github --kind openapi --spec https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json --credential workspace --tags repos,users bun run workspace connections add internal --kind openapi --spec https://internal.example.com/openapi.yaml --credential workspace --auth header:x-api-key bun run workspace connections add countries https://countries.trevorblades.com --kind graphql --credential none ``` - **Operations and tags.** OpenAPI tools use `operationId` (or method + path) with path/query/header parameters plus `body`. Specs with more than 300 operations require `--tags` (or `--tags '*'`). GraphQL tools accept field arguments plus an optional `select` selection set (tags are `query` and `mutation`). - **Read-only classification.** `GET`, `HEAD`, `OPTIONS`, and GraphQL `query` operations require `read`; all other methods and mutations require `all`. - **Auth and responses.** Credentials follow the spec's security scheme or `--auth bearer|basic|header:<name>|query:<name>` (or `--sign-in oauth`). Responses past 10 MB are refused; apps and `execute` receive up to 1 MB; every upstream request sends the trace id in `X-Correlation-Id`. - **Filtering big answers with `fields`.** Agent `connection_call` outputs truncate at 24,000 characters. Pass `fields` beside `input` (or `{ fields }` in `tools.call`) to project only the needed dot-paths through arrays: ```js connection_call({ tool: "pokeapi.pokemon_retrieve", input: { id: "pikachu" }, fields: ["name", "types.type.name", "sprites.front_default"], }) ``` ## HTTP All routes require `Authorization: Bearer <token>` on the workspace host and reject browser cookies or `Origin` headers with `401`. | Route | Who | Body | | ---------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------ | | `GET /_me/connections` | Anyone | | | `POST /_me/connections/<name>/token`, `/token/clear` | Anyone | Raw token or `{"token":"..."}` | | `POST /_me/connections/<name>/connect` | Anyone | Optional `{"scope":"..."}`; returns `{"url"}` | | `POST /_me/connections/<name>/signin/refresh` | Anyone | Empty; refreshes personal OAuth token | | `POST /_me/connections/<name>/own` | Anyone | `{"level":"read"}` (`all` clears restriction) | | `POST /_me/connections/<name>/own/tool` | Anyone | `{"tool":"create_issue","on":false}` | | `POST /_me/connections/<name>/ask`, `/ask/cancel` | Anyone | `{"want":"all","note":"..."}` (max 200 chars) | | `GET /_workspace/connections`, `/<name>` | Admin | | | `POST /_workspace/connections/add` | Admin | `{"provider":"linear"}` or `{"name","url","credential","everyone","signIn"}` | | `POST /_workspace/connections/remove`, `/refresh` | Admin | `{"name":"deepwiki"}` | | `POST /_workspace/connections/<name>/token`, `/token/clear` | Admin | Raw token or `{"token":"..."}` | | `POST /_workspace/connections/<name>/connect`, `/signin/refresh` | Admin | Workspace OAuth start (`{"scope"}`) or refresh | | `POST /_workspace/connections/<name>/client` | Admin | `{"clientId":"...","secret":"..."}` | | `POST /_workspace/access` | Admin | `{"connection":"linear","who":"group:contractors","level":"none"}` | | `POST /_workspace/access/tool` | Admin | `{"connection":"linear","tool":"delete_issue","change":"disable"}` | | `GET /_workspace/access/asks` | Admin | Open access requests and non-widening group suggestions | | `POST /_workspace/access/asks/grant`, `/asks/close` | Admin | `{"connection":"linear","want":"all","people":"bob@acme.com"}` | | `POST /_workspace/explain` | Admin | `{"person":"bob@acme.com","tool":"linear.get_me","as":"me","app":"my-issues"}` | | `POST /_workspace/activity` | Admin | `{"connection","person","app","tool","outcome","limit"}` | `who` accepts `everyone`, `group:<name>`, or `person:<email>`. `level` accepts `none`, `read`, `all`, or `unset`. `change` accepts `disable`, `enable`, `read`, or `unread`. ## How it works - **Execution and sealing.** `WorkspaceDO` owns all connection definitions, tool schemas, access rules, activity logs, and upstream MCP sessions. Credentials are encrypted with AES-GCM under `OPENBELT_SECRETS_KEY`, bound to connection and owner. - **Transport and isolation.** The upstream MCP client speaks Streamable HTTP (JSON or SSE, tracking `Mcp-Session-Id` without following redirects). Sessions are isolated per connection and per credential so two users never share an upstream session. Tool calls time out at 60 s, tool listings at 20 s, replies cap at 16 MB, and text output truncates at 100,000 chars. ### Sign-ins (OAuth) - **Discovery.** On add (or on a per-tool `401` challenge), OpenBelt discovers Protected Resource Metadata (RFC 9728) and Authorization Server Metadata (RFC 8414) requiring PKCE and HTTPS on public hosts. - **Registration precedence.** One registration per authorization server per workspace host, resolved in order: (1) workspace admin OAuth client (`connections client`), (2) deployment-wide [OpenBelt's own apps](#openbelts-own-apps), (3) Client ID Metadata Document (`/_oauth/clients/<registration>.json`) when reachable over public HTTPS, (4) Dynamic Client Registration (RFC 7591). Callbacks return to `/_oauth/callback/<registration>`. - **Refresh and safety.** Active sign-ins (used within 7 days) refresh 1 minute before expiry in the background, serialized per credential inside `WorkspaceDO`. Transient errors (`503`, `429`) back off exponentially (30 s to 15 min) without killing the grant; revocations (`invalid_grant`, `invalid_rapt`) halt retries and surface `reconnect`. New tokens are persisted before use, PKCE verifiers (when enabled; providers that reject `code_verifier` declare `pkce: false`) and `iss` (RFC 9207) prevent mix-up attacks, and disconnects/removals call RFC 7009 revocation only once the last connection sharing that OAuth app is removed. Provider quirks (Google `access_type=offline`, Entra `.default`, `pkce: false`, static OAuth endpoints) live in catalog data (`apps/platform/src/connections/providers.ts` or an external feed via `OPENBELT_CATALOG_URL`). OpenAPI specs can declare static request headers in top-level `x-openbelt-headers`, and empty `2xx` responses carrying `x-restli-id` or `location` return those values as JSON. ### OpenBelt's own apps A deployment can provide shared OAuth apps for providers that block self-registration by setting `OPENBELT_CONNECT_<FAMILY>_CLIENT_ID` and `OPENBELT_CONNECT_<FAMILY>_CLIENT_SECRET` (`GITHUB`, `GOOGLE`, `ASANA`, `LINKEDIN`, or any family in `OPENBELT_CATALOG_URL`), with callback `https://<base host>/_oauth/callback/<family>`. - State prefixes route callbacks from the base host to the workspace host, where the workspace exchanges the code using its own PKCE verifier. - Client secrets remain strictly in server environment variables and are never stored in workspace SQLite files. - Any workspace admin client configured via `connections client` overrides the shared app for that workspace. --- url: https://openbelt.com/docs/people group: Workspaces & connections --- > Manage workspace members, roles, groups, invite-only access, offboarding, workspace renames, and SCIM 2.0 directory sync. # People & groups Agents and scripts can manage everything on this page through MCP or the `openbelt` CLI; see [Workspace automation](/docs/workspace). Admin operations appear only for workspace admins. A workspace tracks every person who belongs to it with a permanent id (`p_3f9c0a1b2c3d4e5f`), lowercased email, display name, role (`admin` or `member`), and status (`invited`, `active`, or `removed`). The sign-in layer (email codes, OIDC, or Tailscale) proves identity; the workspace decides access. Document `author` fields store the person's email. ## Who can do what | Role | Permissions | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Member** | Open workspace apps (except private apps), run `whoami`, manage their own API tokens, OAuth agent sign-ins, and personal connection settings/credentials. | | **App owner** | Everything a member can do, plus on apps they own: deploy, read logs and function runs, write data past [rules](/docs/rules#mcp-writes), change visibility, and delete the app. | | **Workspace admin** | Everything an app owner can do on every app, plus invite/remove people, change roles, toggle joining mode, manage groups and [connections](/docs/connections), revoke anyone's tokens, set SCIM sync, rename the workspace, and set its icon. | | **Operator (`OPENBELT_ADMIN_TOKEN`)** | Mint API tokens for any email (`/_ops/tokens`) and bootstrap workspace admins (`/_ops/workspace-admins`). | Agents act with the exact permissions of their owner (never more). A workspace's last admin cannot be demoted or removed until another admin is appointed. ## Joining: open or invite-only | Mode | Behavior | | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `open` (default on self-hosted) | Anyone admitted by your sign-in mode becomes an active member on first visit. | | `invite` (default for workspaces created on the base host) | Only invited people can enter. Uninvited visitors get a `403` page naming workspace admins (with an option to request access), and SDK calls receive `{"code":"not_member"}`. Signed-out visitors are refused. | Both modes apply across the workspace host and all app hosts, for pages and data alike. Removed members are refused under both modes. `check_app`'s browser authenticates with a short-lived signed session cookie (`__Host-openbelt_session`, 15 min) so preview checks still run under invite-only workspaces. Under email sign-in, people with the same company email domain (excluding consumer mail like `gmail.com`) see invite-only workspaces under **Other workspaces** with an **Ask** button. Requests appear for admins on **Settings > People** until approved with **Invite**. ## Removing someone Removing a member (`people_remove` or **Settings > People**) takes effect immediately across the workspace: - Revokes all of their API tokens and signs out their OAuth agents (the next MCP call returns `401`). - Refuses all page and data requests with a notice showing who removed them and when. - Closes their open app WebSockets (`4403`), triggering the SDK to reload onto the removal notice. - Removes them from all groups and deletes their personal [connection](/docs/connections) credentials. Inviting the same email again restores membership, while previously revoked tokens remain revoked. ## Renaming the workspace Admins can rename a workspace in **Settings > General**, via `workspace_rename`, or with `openbelt workspace rename <new-name>`. The workspace host updates to `<new-name>.<domain>` and apps to `<app>--<new-name>.<domain>`. Internally, the workspace keeps its original immutable id, so no data moves. - **Old hosts keep working permanently.** Browser page loads on an old host return `308` to the new host. API calls, `/mcp`, OAuth callbacks, app data, WebSockets, functions, and webhooks continue serving transparently without reconfiguring agents or CLIs. - **Name reservation and limits.** Every name a workspace has ever held (up to 10 names total) stays reserved so another workspace cannot claim it. You can rename back to one of your own prior names. - **Constraints.** Unclaimed trial workspaces cannot be renamed (`403`). Colliding names or an 11th name return `409`. Under `OPENBELT_SIGNIN=email`, members sign in once on the new host because session cookies are host-scoped. In multi-process deployments (`OPENBELT_PROCESSES > 1`), other workers pick up renames within 2 seconds. ## The workspace's icon Admins can upload a workspace icon on **Settings > General** (browsers resize raster images to 256x256; SVGs up to 64 KB upload as-is) or via `workspace_icon_set` / `workspace_icon_clear` (PNG, JPEG, GIF, WebP, SVG, or ICO up to 64 KB). The workspace switcher displays the icon (served at `/_icon` to signed-in members) or falls back to the workspace's initial letter. ## Groups Groups are named lists of workspace members (1 to 40 lowercase letters, digits, and dashes, such as `support`) used to assign [connection](/docs/connections) access levels. - `source: "openbelt"` groups are managed inside OpenBelt. - `source: "scim"` groups are managed by your identity directory; their membership is read-only in OpenBelt, while connection access levels remain editable here. - Each group automatically picks a Lucide icon from its name (`packages/model/src/group-icons.ts`, defaulting to `users`), which admins can override even on directory-synced groups. ## In Settings Workspace admins manage members and groups at `<workspace host>/settings`: - **People (`/admin/people`):** member list, invite form (email + role), pending join requests, joining policy, and workspace name. - **Person detail (`/admin/people/<email>`):** role, group memberships, per-connection effective access and exceptions, active API tokens, recent calls, and removal. - **Groups (`/admin/groups` and `/admin/groups/<name>`):** group list, icon picker, paginated searchable member list (bulk-add by search or pasted emails), per-connection access levels (highlighting individual member exceptions), and deletion (which also removes that group's access levels). - **View as...** (under **You** in the settings sidebar): preview the workspace, apps, and Connections page exactly as another member, **Everyone**, or a hypothetical member of any group sees it. All mutations are blocked while previewing. ## Sync with a directory (SCIM) Connect Okta, Microsoft Entra ID, authentik, or any SCIM 2.0 provider to `https://<workspace host>/scim/v2` for automated provisioning and **instant offboarding**. Deactivating a user in your directory immediately revokes their API tokens, signs out their OAuth agents, closes active app tabs, and removes them from groups, instead of waiting for session expiry. SCIM handles lifecycle and groups, while sign-in (`OPENBELT_SIGNIN=email` with `OPENBELT_SSO_*` or a Tailscale front door) handles authentication; both match on the user's email (`userName`). ### Setup 1. Open **Settings > People > Sync** (or run `openbelt scim token create` / `bun run workspace scim token --label okta`) to mint a SCIM bearer token (shown once). 2. In your directory, configure a SCIM 2.0 app with base URL `https://<workspace host>/scim/v2`, Bearer token authentication, and `userName` mapped to the person's email. 3. Enable push for user creation, updates, deactivation, and the groups you want synced. Ensure `/scim/v2` is reachable from your directory provider. ### Sync behavior - **Users.** Provisioned users start as `invited` members (admitting them automatically into invite-only workspaces). `active: false` or `DELETE` removes them identically to `people_remove`. `active: true` reactivates a directory-deactivated user (old tokens stay revoked), but returns `409` if an OpenBelt admin manually removed them. `userName` cannot change; provision new emails as new users. - **Roles.** SCIM never promotes admins, and returns `409` if asked to deactivate the workspace's last admin. - **Groups.** Pushed display names slugify into OpenBelt group names (`Support Team` becomes `support-team`). Colliding with an OpenBelt-created group returns `409`; renaming a synced group returns `400` because access policies reference group names. Group PATCH updates are atomic. - **Troubleshooting.** OpenBelt retains the last 200 SCIM requests (with trace ids in `x-openbelt-trace`) on **Settings > People > Sync** and in `scim_status`. | SCIM / admin route | Notes | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | `GET`/`POST /scim/v2/Users` | Supports `?filter=userName eq "..."` (`id`, `externalId`), `startIndex`, `count` (max 200) | | `GET`/`PUT`/`PATCH`/`DELETE /scim/v2/Users/<id>` | `<id>` is the person id (`p_...`) | | `GET`/`POST /scim/v2/Groups` | Directory-managed groups (`source: scim`) | | `GET`/`PUT`/`PATCH`/`DELETE /scim/v2/Groups/<id>` | `<id>` is the group slug | | `GET /scim/v2/ServiceProviderConfig`, `/ResourceTypes` | Declares PATCH and filter support | | `GET /_workspace/scim`, `POST /_workspace/scim/token`, `/revoke` | Admin inspection and SCIM token management | ## Tokens API tokens belong to one person in one workspace ([MCP](/docs/mcp#tokens)). Each token has an id (`t_1a2b3c4d5e6f`) for listing and revocation; its secret value is shown once on creation. Members manage their tokens and OAuth agent sign-ins on **Settings > Agents** (`<workspace host>/agents`) and their connection credentials on **Connections** (`<workspace host>/connections`, [Connections](/docs/connections#your-settings)). ## Self-hosted CLI From a self-hosted checkout (or inside the Docker container), `bun run workspace` drives all workspace admin routes non-interactively against `--url <workspace-url> --token <token>`: ```sh bun run workspace whoami --url https://acme.example.com --token "$OPENBELT_TOKEN" bun run workspace people list bun run workspace people invite dave@acme.com --role member bun run workspace people remove dave@acme.com bun run workspace people role dave@acme.com admin bun run workspace joining invite bun run workspace rename acme-labs bun run workspace groups create support bun run workspace groups add support dave@acme.com erin@acme.com bun run workspace tokens create --label laptop --days 30 bun run workspace tokens list --workspace bun run workspace tokens revoke t_1a2b3c4d5e6f --workspace bun run workspace admins add ada@acme.com --admin-token "$OPENBELT_ADMIN_TOKEN" bun run workspace scim token --label okta bun run workspace scim ``` ## HTTP All routes below run on the workspace host (`<workspace>.<domain>`) with `Authorization: Bearer <token>` and JSON bodies for `POST`. Browser cookies, `Origin`, and `Sec-Fetch-Mode` headers are rejected with `401`. | Route | Who | Body | | ------------------------------------------- | -------- | -------------------------------------------------------------------- | | `GET /_me/whoami` | Anyone | | | `GET /_me/tokens` | Anyone | | | `POST /_me/tokens/create` | Anyone | `{"label":"laptop","days":30}` | | `POST /_me/tokens/revoke` | Anyone | `{"id":"t_..."}` | | `GET /_workspace/people` | Admin | | | `POST /_workspace/people/invite` | Admin | `{"email":"dave@acme.com","name":"Dave","role":"member"}` | | `POST /_workspace/people/remove` | Admin | `{"person":"dave@acme.com"}` (or id) | | `POST /_workspace/people/role` | Admin | `{"person":"dave@acme.com","role":"admin"}` | | `GET`/`POST /_workspace/joining` | Admin | `{"joining":"invite"}` | | `POST /_workspace/rename` | Admin | `{"to":"acme-labs"}` | | `POST /_workspace/icon`, `/icon/clear` | Admin | `{"type":"image/png","base64":"..."}` | | `GET /_workspace/groups` | Admin | | | `POST /_workspace/groups/create`, `/delete` | Admin | `{"name":"support"}` (optional `"icon"`) | | `POST /_workspace/groups/icon` | Admin | `{"name":"support","icon":"headset"}` (`null` resets) | | `POST /_workspace/groups/add`, `/remove` | Admin | `{"group":"support","person":"dave@acme.com"}` (or `"people":[...]`) | | `GET /_workspace/tokens` | Admin | | | `POST /_workspace/tokens/revoke` | Admin | `{"id":"t_..."}` | | `POST /_ops/workspace-admins` | Operator | `{"email":"ada@acme.com"}` | Errors return `{ error, code, trace }` where `code` is `unauthorized`, `not_admin`, `invalid`, `missing`, or `conflict`. --- url: https://openbelt.com/docs/workspace group: Workspaces & connections --- > Manage people, groups, connections, access policies, API tokens, app consent, and signed-in agents through MCP or the openbelt CLI. # Manage a workspace Use the same MCP connection or `openbelt` CLI sign-in you use for apps. `whoami` returns your workspace, role, groups, and what this agent is permitted to do (access level, allowed apps, and workspace MCP URL). Search and CLI help list only operations your role can run; admins can manage workspace settings, while every member can manage their own connection preferences, API tokens, and app consent. Every call checks your live permissions. ## Find operations Use `search({ query: "effective access" })` to find matching management operations with input schemas, or `search({ query: "" })` to list all operations available to you. Run any operation with `call({ tool: "<operation>", args: { ... } })`. ```sh openbelt help openbelt search effective access ``` ## People and groups Admins manage membership with `people_list`, `people_invite`, `people_remove`, and `people_role_set`. Check pending join requests with `workspace_join_requests` and invite a requester to admit them. Manage groups with `group_create`, `group_member_add`, `group_member_remove`, `group_list`, and `group_delete` (SCIM-synced groups change in the directory). ```sh openbelt people invite ada@example.com openbelt group create support openbelt group add support ada@example.com openbelt workspace joining invite openbelt workspace rename acme-labs ``` The last admin cannot be removed or demoted. See [People & groups](/docs/people) for joining modes, offboarding, renaming, and SCIM sync. ## Apps that embed other apps By default, no app can embed another app in an `<iframe>` (`frame-ancestors`, [Who is viewing](/docs/viewers)) to prevent clickjacking. For app-builder apps that need to render a live or preview app beside a chat UI, admins can allowlist up to 10 embedder apps with `workspace_embed_set` (`[]` resets to none; all processes pick up changes within 5 seconds): ```sh openbelt workspace embed builder ``` During `check_app`, an embedded app loads only when both apps share the same preview environment. ## Make another workspace Under email sign-in, any signed-in member can create a separate workspace (for example, for a client or side project) with `workspace_create`: ```sh openbelt workspace create studio-lab ``` - You become the new workspace's first admin, and it starts invite-only. - Your current MCP session stays attached to the original workspace. The response returns `workspace_url`, `mcp_url`, and a one-time non-expiring `token` acting as you in the new workspace. Send `Authorization: Bearer <token>` to `mcp_url` (adding it as an MCP server, or POSTing JSON-RPC `initialize` followed by `tools/call` with the returned `mcp-session-id`, as shown in `next`). - Names use lowercase letters, digits, and single dashes (`"Studio Lab"` becomes `studio-lab`). Names held now or previously by another workspace are refused. Unclaimed trials must be claimed first. - Limit: 5 new workspaces per person per hour. When Stripe billing is enabled, the Personal plan includes 1 free workspace; additional workspaces can start on Pro ($29/month) at `/start/new` or upgrade at `/admin/billing`. ## Connections and access Search with `connections` before adding a service. Admins add connections using `connection_add` (catalog), `connection_mcp_add` (custom MCP URL), or `connection_api_add` (OpenAPI or GraphQL), and inspect them without secrets via `connection_admin_info`: ```sh openbelt connection add github openbelt connection info github --workspace openbelt connection access github --workspace --who group:support --level read openbelt connection access github --level read ``` - **Personal vs. workspace scope.** Personal settings are the default (`connection_preferences_set`, `connection_tool_preferences_set`). Workspace policy sets the ceiling and requires an admin (`connection_access_set`, `connection_tool_policy_set`) with an explicit `who` target (`person:<email>`, `group:<name>`, or `everyone`). The CLI selects workspace-scoped tools via `--workspace`; an unavailable workspace operation is refused rather than silently falling back to personal settings. - **Access requests and audits.** Members ask for higher access with `connection_access_request`. Admins inspect requests with `connection_access_requests`, resolve them with `connection_access_request_grant` or `connection_access_request_close`, diagnose effective access with `connection_access_explain`, and inspect recent tool calls with `workspace_activity`. Pending requests include scoped `nextActions`; prefer granting the named person rather than widening `everyone` access. - **Credentials.** `connection_connect` (or `connection_workspace_connect` for admins) returns an OAuth link for the user to open in a browser; re-read the connection to confirm completion. For token-based services, pipe tokens into `openbelt connection token <connection>` (add `--workspace` for a shared token) rather than pasting secrets in chat. See [Connections](/docs/connections) for credential ownership and how policy levels combine. ## Tokens, consent and agent sign-outs - **API tokens.** `token_create` mints an API token acting as you, returned once alongside this workspace's `/mcp` URL (never the base host's shared `/mcp` URL). `token_list` lists ids and expiries; `token_revoke` revokes your own token. Admins inspect and revoke any workspace token with `workspace_token_list` and `workspace_token_revoke` (`--workspace` in the CLI). - **App consent.** `connection_consent_list` shows allowed apps and pending requests; `connection_consent_grant`, `connection_consent_revoke`, and `connection_consent_dismiss` manage your own consent (admins never grant consent on another person's behalf). - **OAuth agents.** `agent_signins` lists agents signed in as you via OAuth, and `agent_signout` revokes an OAuth grant (access and refresh tokens). ### What an agent can do, and which apps Every OAuth agent sign-in and API token carries two scopes chosen at consent time or later in **Settings > Agents**: an **access level** and an **app scope**. Both default to full access. | Level | Label | Permissions | | ------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `look` | Read only | Inspect apps, code, and data. No mutations. | | `draft` | Write (drafts only) | Create and edit preview environments only. Live apps stay untouched. | | `live` | Write | Deploy and promote live, mutate live data, run functions and `execute`, call connections. | | `all` | Everything | Manage secrets, webhooks, people, connections, and agents, and deploy versions that expand `network`, `uses`, page `tools`, `webhooks`, or `public`. | Only `all` grants workspace admin capabilities or agent management. App scope is `"every"` (all accessible apps including future ones), `"yours"` (apps you own including future ones), or an explicit list of app names. Outside its scope, an agent cannot see, check, deploy, or edit other apps, and apps it deploys have cross-app `db.app("<other>")` reads refused (`403`) until redeployed by an unrestricted agent. Scoped-app agents are never workspace admins and cannot create workspaces. Manage scopes via `token_create` (`apps`, `level`, bounded by the caller's own scope), `token_apps_set`, `token_level_set`, `agent_apps_set`, and `agent_level_set`. ### Which connections a sign-in may use An OAuth sign-in follows its access level for connections (`live` and `all` can call all your accessible connections; `look` and `draft` call none) until customized on its **Settings > Agents** page. Per connection, choose **Off**, **Read only**, **Read and edit**, or **Custom** (per-tool toggles). Changes apply immediately and stay bounded by your personal and workspace access levels. API tokens follow their access level; function calls triggered by an agent are not restricted by the sign-in's per-connection filter. ```sh openbelt token create --label laptop --days 30 openbelt token list openbelt token revoke <id> openbelt connection consent list openbelt agent list openbelt agent signout <id> ``` Admins manage directory sync with `scim_status`, `scim_token_create`, and `scim_token_revoke`. Operator tokens (`OPENBELT_ADMIN_TOKEN`) are never needed for workspace management. ## Reference: every operation Generated from `apps/platform/src/objects/mcp/management.ts` (`bun run docs:sync`): <!-- generated:management-ops:start --> | Operation | Summary | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `agent_apps_set` | Set which apps one of your signed-in agents (by grant id from agent_signins) may use: "every", "yours" (the apps you own, and each one you make later) or a... | | `agent_level_set` | Set what one of your signed-in agents (by grant id from agent_signins) can do: "look" (Read only), "draft" (Write (drafts only)), "live" (Write) or "all"... | | `agent_signins` | List agents signed in as you with OAuth, including their grant ids and last use. | | `agent_signout` | Sign out one of your OAuth agents by grant id from agent_signins. | | `connection_access_explain` | Check a person's effective access and explain why they can or cannot use a connection tool, optionally through an app. | | `connection_access_request` | Ask workspace admins for read or all access to a connection. | | `connection_access_request_cancel` | Withdraw your pending request for more access to a connection. | | `connection_access_request_close` | Close pending requests for a connection and level without granting access. | | `connection_access_request_grant` | Grant pending requests for a connection and level to one person, comma-separated people, or all pending requesters when neither is given. | | `connection_access_requests` | List people's pending requests for more connection access, grouped by connection and desired level. | | `connection_access_set` | Set workspace access to a connection for everyone, a group, or a person. | | `connection_add` | Add a connection from OpenBelt's provider catalog. | | `connection_admin_info` | Inspect a connection's workspace configuration and access policy. | | `connection_admin_list` | List all configured workspace connections and their setup, access policies, and credential status. | | `connection_api_add` | Add an OpenAPI or GraphQL connection. | | `connection_client_set` | Set a connection's registered OAuth client id and optional client secret. | | `connection_connect` | Start signing in to a connection with your own account. | | `connection_consent_dismiss` | Dismiss an app's pending request to use your personal connection. | | `connection_consent_grant` | Allow an app to use your personal connection, as you, for its exact viewer-bound tools. | | `connection_consent_list` | List the apps you allowed to use your personal connections, the exact tools allowed, and pending requests from apps. | | `connection_consent_revoke` | Revoke an app's use of your personal connection. | | `connection_disconnect` | Disconnect your account from a connection, clearing its credential. | | `connection_icon_clear` | Reset a connection's icon. | | `connection_icon_set` | Set a connection's icon from a base64 image, at most 64 KB. | | `connection_mcp_add` | Add a custom MCP server to the workspace. | | `connection_preferences_set` | Restrict a connection for yourself to none, read, or all the tools your workspace grants you. | | `connection_refresh` | Refresh a connection's tool list from its server or specification. | | `connection_remove` | Remove a workspace connection, its credentials, app consents, and access settings. | | `connection_signin_refresh` | Refresh your connection's OAuth credential now, without changing its account. | | `connection_token_set` | Set your personal token for a connection. | | `connection_tool_policy_set` | Disable, enable, or classify a connection tool as read-only for the workspace. | | `connection_tool_preferences_set` | Turn one connection tool on or off for yourself, within your workspace access. | | `connection_workspace_connect` | Start signing in to a connection with the workspace's shared account. | | `connection_workspace_disconnect` | Disconnect a connection's shared workspace credential. | | `connection_workspace_signin_refresh` | Refresh a shared workspace connection's OAuth credential now. | | `connection_workspace_token_set` | Set a connection's shared workspace token through secure credential input. | | `group_create` | Create a workspace group. | | `group_delete` | Delete a workspace-managed group and its access levels. | | `group_list` | List workspace groups and their members. | | `group_member_add` | Add a workspace person to a workspace-managed group. | | `group_member_remove` | Remove a person from a workspace-managed group. | | `people_invite` | Invite someone into this workspace, or restore a removed person. | | `people_list` | List workspace people, roles, status, groups, and the joining policy. | | `people_remove` | Remove someone from the workspace, revoking their credentials and closing their app pages. | | `people_role_set` | Set a person's workspace role to admin or member. | | `scim_status` | List directory-sync tokens and recent provisioning requests. | | `scim_token_create` | Create a SCIM directory-sync token, returned once. | | `scim_token_revoke` | Revoke a directory-sync token by id from scim_status. | | `token_apps_set` | Set which apps one of your API tokens (by id from token_list) may use: "every", "yours" (the apps you own, and each one you make later) or a list of names. | | `token_create` | Create an API token acting as you in this workspace. | | `token_level_set` | Set what one of your API tokens (by id from token_list) can do: "look" (Read only), "draft" (Write (drafts only)), "live" (Write) or "all" (Everything). | | `token_list` | List your API tokens by id and expiry; token values are never returned. | | `token_revoke` | Revoke one of your API tokens by id from token_list. | | `workspace_activity` | Inspect recent platform-tool and connection-tool activity, filtered by person, app, tool, connection, or outcome. | | `workspace_create` | Create a new workspace with you as its first admin, invite-only. | | `workspace_embed_set` | Set which of the workspace's apps may embed its other apps in a frame (an app builder showing the app it builds, live or in a preview environment). | | `workspace_icon_clear` | Remove the workspace's icon: its first letter shows instead. | | `workspace_icon_set` | Set the workspace's icon, shown beside its name in the top bar, from a base64 image, at most 64 KB. | | `workspace_join_requests` | List people waiting to join this workspace. | | `workspace_joining_set` | Set whether the workspace accepts anyone who can sign in or only invited people. | | `workspace_rename` | Rename the workspace and its hosts. | | `workspace_token_list` | List API tokens across the workspace, without token values. | | `workspace_token_revoke` | Revoke any API token in the workspace by id. | <!-- generated:management-ops:end --> --- url: https://openbelt.com/docs/running group: Self-hosting --- > Run OpenBelt on your own server with Docker or the compiled Linux binary: DNS and HTTPS, sign-in, SQLite storage, backups, file uploads, logs, limits, and graceful restarts. # Self-hosting OpenBelt runs on a single Linux server from one Docker image or a compiled binary. Every workspace, app, and MCP session stores its state in its own SQLite file on a local volume, so there is no external database to manage. ## Quick start with Docker `compose.yaml` starts the platform (`Dockerfile`: Bun, Chromium for `check_app`, and the server) with its state on the `openbelt-data` volume: ```sh OPENBELT_HOST=openbelt.example.com docker compose up -d ``` - **Network binding and sign-in.** Compose binds port `1337` to `127.0.0.1` and defaults to `OPENBELT_SIGNIN=tailscale`, which expects a trusted identity proxy in front of the server. Set `OPENBELT_SIGNIN=email` for email code or OIDC sign-in on a public domain. For an anonymous local sandbox, set `OPENBELT_SIGNIN=off`. Only change `OPENBELT_BIND` if you keep authentication enabled. - **Generated keys.** On a fresh volume, if `OPENBELT_SECRETS_KEY` or `OPENBELT_ADMIN_TOKEN` is unset, the supervisor generates them into `/data/<namespace>/secrets.key` and `/data/<namespace>/admin-token.key` (`0600`) and logs their paths. Read the generated admin token with: ```sh docker compose exec openbelt cat /data/openbelt/admin-token.key ``` > [!WARNING] > Back up `OPENBELT_SECRETS_KEY` (or `/data/<namespace>/secrets.key`). It seals every connection token, app secret, and webhook secret. If existing SQLite files are present without the matching key, OpenBelt refuses to start rather than generating a replacement key that cannot decrypt stored secrets. ## Running on a server ### Domains and DNS Workspaces live at `<workspace>.<OPENBELT_HOST>` and apps at `<app>--<workspace>.<OPENBELT_HOST>`. Because each workspace and app occupies a single DNS label under `OPENBELT_HOST` (up to 63 characters total, with `--` reserved as the separator), one wildcard DNS record and one wildcard TLS certificate cover every workspace and app. Point these DNS records (A and AAAA) at your server: | Variable | DNS records | Role | | ---------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `OPENBELT_HOST` | `<host>` and `*.<host>` | Workspaces (`<ws>.<host>`) and apps (`<app>--<ws>.<host>`). | | `OPENBELT_BASE_HOST` | `<base-host>` | Optional separate domain under `OPENBELT_SIGNIN=email` for landing pages, sign-in, and the shared `/mcp` endpoint (for example, `openbelt.com` beside `openbelt.app`). Keeps app cookies and SameSite context isolated from sign-in. | | `OPENBELT_PUBLIC_HOST` | `*.<public-host>` | Optional separate domain under `OPENBELT_SIGNIN=email` for apps with `"public"` in `openbelt.json` (`<app>--<ws>.<public-host>`). Visitors are never signed in and no cookies are set. | One configured domain may never be a subdomain of another; OpenBelt refuses that layout at startup. ### HTTPS and reverse proxy Run the bundled Caddy proxy (`deploy/Caddyfile`) on ports 80 and 443 while keeping OpenBelt bound to `127.0.0.1`: ```sh OPENBELT_HOST=openbelt.example.com OPENBELT_BIND=127.0.0.1 docker compose --profile tls up -d ``` - **On-demand certificates.** Caddy queries `/_tls/ask` before issuing a Let's Encrypt certificate. OpenBelt approves only `OPENBELT_HOST`, `OPENBELT_BASE_HOST`, the default workspace, active workspaces, and existing apps, so random hostnames cost nothing. - **Wildcard certificates.** Let's Encrypt caps new certificates at 50 per registered domain per week. Once you host more than a few dozen apps, or when serving `OPENBELT_PUBLIC_HOST`, use a DNS-challenge build of Caddy (`deploy/caddy.Dockerfile`) with `CLOUDFLARE_DNS_API_TOKEN` for a single `*.<domain>` certificate, or place the domain behind Cloudflare's proxy. - **Private networks.** Set `OPENBELT_TLS=internal` to test with Caddy's internal CA (note that `check_app`'s Chromium trusts only public certificate authorities). - **Custom proxies.** Forward the original `Host` header and set `X-Forwarded-Proto: https`. Ensure the external URL is reachable from inside the container so `check_app` can load apps. OpenBelt compresses text responses of 1 KB or larger itself and handles `If-None-Match` (`304`), so disable proxy-level gzip compression (which breaks `206` range responses). ### Sign-in and access Choose how OpenBelt identifies people with `OPENBELT_SIGNIN` (see [Who is viewing](/docs/viewers#who-says-so)): | Mode | How people sign in | Key settings | | ----------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `tailscale` | Trusted front door sets `Tailscale-User-Login` and `Tailscale-User-Name` (for example, `tailscale serve` or a private proxy). | Keep OpenBelt unreachable outside the proxy, or set `OPENBELT_FRONT_DOOR_SECRET`. | | `email` | 6-digit email codes, optional Google OAuth, and optional company OIDC SSO. | `OPENBELT_MAIL_TOKEN`, `OPENBELT_MAIL_ACCOUNT`, `OPENBELT_GOOGLE_CLIENT_ID` / `_SECRET`, `OPENBELT_SSO_ISSUER` / `_CLIENT_ID` / `_SECRET`. | | `off` | Anonymous access only. Every page load and app write is anonymous. | Development or isolated sandboxes only. | - **Closing sign-ups.** Under `OPENBELT_SIGNIN=email`, set `OPENBELT_SIGNIN_ALLOW` to a comma-separated list of allowed emails and `@domains` (for example, `ada@acme.com,@acme.com`) to restrict new sign-ins without logging out existing sessions. - **Operator routes.** `/_ops/*` routes require `Authorization: Bearer <OPENBELT_ADMIN_TOKEN>`. Restrict `/_ops/*` to loopback or your private tailnet at the reverse proxy. - **Sessions.** Set `OPENBELT_SESSION_SECRET` separately from `OPENBELT_ADMIN_TOKEN` so an admin token leak cannot forge browser sessions. - **Trial workspaces.** `OPENBELT_TRIALS=on` (under `OPENBELT_SIGNIN=email`, off by default) lets unauthenticated agents create temporary unclaimed workspaces via `POST /trial`. Leave this off on public hosts unless you have dedicated domains and proxy-enforced rate limits. ### Processes, sandboxes, and browsers - **Multi-process scaling.** Set `OPENBELT_PROCESSES` (`compose.yaml` defaults to `auto`: 1 process per 2 CPUs, up to 4). A supervisor (`packages/runtime/src/supervisor.ts`) binds one shared port via `SO_REUSEPORT`, hashes each Durable Object to one process, routes cross-process calls over loopback, shares one sandbox pool, and restarts a crashed worker in about 1.4 seconds. - **Function sandboxes.** App functions and agent `execute` calls run in QuickJS compiled to WASM inside isolated sandbox processes (never shared across workspaces, running as `nobody` in the container). On Linux, sandboxes confine themselves with Landlock (kernel 5.13+, TCP rules on 6.7+) and seccomp (no sockets, no `ptrace`, self-signals only). - **Headless browser (`check_app`).** By default (`OPENBELT_BROWSER=local`), the image runs its pinned Chromium as uid `990` with a clean environment and egress blocking (`169.254.169.254` and private networks are refused). `compose.yaml` mounts `deploy/seccomp.json` so Chromium's user-namespace sandbox works inside Docker. To offload headless Chrome, set `OPENBELT_BROWSER=cloudflare` (with `OPENBELT_BROWSER_CF_ACCOUNT` and `OPENBELT_BROWSER_CF_TOKEN`), `OPENBELT_BROWSER=cdp` (with `OPENBELT_BROWSER_CDP_URL` and optional `OPENBELT_BROWSER_CDP_TOKEN`), or `OPENBELT_BROWSER=off`. Set `OPENBELT_CHROME_PATH` to use a custom local Chrome binary. - **App category classifier (`OPENBELT_CLASSIFIER`).** Apps can declare `"category"` and silent search `"tags"` in `openbelt.json`, or owners/admins can pin them on the App page. When omitted, `OPENBELT_CLASSIFIER` (`auto` default, `cloudflare`, `ai`, `clef`, or `off`) classifies apps asynchronously in the background: `cloudflare` calls Cloudflare Workers AI (`@cf/cloudflare/clef` via `OPENBELT_CLASSIFIER_CF_ACCOUNT` and `OPENBELT_CLASSIFIER_CF_TOKEN`), `clef` calls a self-hosted Clef-compatible endpoint (`OPENBELT_CLASSIFIER_URL` and optional `OPENBELT_CLASSIFIER_TOKEN`), and `ai` reuses `OPENBELT_AI_API_KEY` (`OPENBELT_AI_MODEL_FAST`). In `auto` mode, OpenBelt uses whichever of those is configured, or makes no outbound calls when none is set. - **Memory limit.** `compose.yaml` sets `mem_limit: ${OPENBELT_MEMORY_LIMIT:-4g}` (6 GB on an 8 GB server). Under memory pressure, the platform sets `oom_score_adj` so the kernel terminates sandbox processes and browsers before platform workers. ### Zero-downtime upgrades and restarts Pull the new image and recreate the container while keeping the `openbelt-data` volume intact: ```sh docker compose pull && docker compose up -d ``` On `SIGTERM`, the server performs an ordered shutdown (`packages/runtime/src/shutdown.ts`): `/_health` returns `503` for 600 ms while requests finish (up to 5 s), Durable Objects flush and sleep (up to 6 s), sandbox processes stop, and OTLP batches flush (typically 1 to 4 seconds, 22 s maximum). Keep `stop_grace_period` at `30s` or higher so Docker never cuts a clean shutdown short. To upgrade without client errors, configure your reverse proxy to hold incoming requests while the container restarts and retry once `/_health` returns `200`: ```caddyfile https:// { reverse_proxy openbelt:1337 { lb_try_duration 30s lb_try_interval 100ms health_uri /_health health_interval 250ms health_timeout 1s health_passes 1 health_fails 1 fail_duration 1s } } ``` Open pages automatically reconnect their WebSockets with `?since=` and replay missed changes; MCP sessions continue across the restart. > [!NOTE] > Never roll back past a version that introduced a new alarm job kind that the older version neither runs nor drains, or the older server will retry those pending jobs every 30 seconds indefinitely. ## Compiled server Install and start the latest compiled server archive in one command: ```sh curl -fsSL https://openbelt.com/server | sh ``` The installer verifies `SHA256SUMS`, unpacks the release under `~/.local/share/openbelt/server`, links `~/.local/bin/openbelt-server`, and starts it locally at `http://acme.localhost:1337` with `OPENBELT_SIGNIN=off`. Pass `--dry-run` to check the download without installing, or `--install-only` to install without starting it (`apps/platform/src/web/public/server-install.sh`). To run the binary manually on a server with your own domain and data directory: ```sh ./openbelt-server --version OPENBELT_HOST=openbelt.example.com OPENBELT_DATA=/var/lib/openbelt ./openbelt-server ``` Each archive contains `openbelt-server` (a self-contained Bun executable), `VERSION`, and the runtime assets (`apps/www/`, `brand/`, `docs/`, starters, QuickJS WASM, icons, and CLI builds). It accepts the exact same `OPENBELT_*` environment variables as Docker and includes built-in backup commands: ```sh ./openbelt-server data backup /var/backups/openbelt --data /var/lib/openbelt ./openbelt-server data restore /var/backups/openbelt --data /var/lib/openbelt ./openbelt-server data restore-backup s3://bucket/prefix /var/lib/openbelt ``` Chromium is not bundled in the tarball. Install Chromium on the host (or set `OPENBELT_CHROME_PATH`), configure a remote browser (`OPENBELT_BROWSER=cloudflare` or `cdp`), or disable browser checks (`OPENBELT_BROWSER=off`). ## The data Each Durable Object (workspace, app, MCP session, and the platform's `ApexDO`) keeps its state in a dedicated SQLite file under `OPENBELT_DATA` (Docker default `/data`): ```text <OPENBELT_DATA>/<OPENBELT_NAMESPACE>/<object>-<key hash>.sqlite ``` - **Durability.** Commits write to the file's WAL and sync to disk roughly once per second (`OPENBELT_LOCAL_DB_SYNC=SECOND`, default). Process crashes (`SIGKILL`) lose zero acknowledged writes; power loss or kernel panic can lose at most about 1 second of acknowledged writes. Set `OPENBELT_LOCAL_DB_SYNC=FULL` to fsync every commit if you prefer strict per-commit durability over throughput. - **Worker threads.** App SQLite I/O runs on dedicated worker threads (`OPENBELT_DB_THREADS`, default `4` per process), plus one dedicated control thread for `ApexDO`, `WorkspaceDO`, and `McpDO`, so disk syncs do not block HTTP requests. - **Lifecycle and locking.** Objects wake on first request and sleep after 10 minutes idle with no open WebSockets (`OPENBELT_ACTOR_SLEEP_SECONDS`, default `600`). A process locks every SQLite file it opens; a competing process waits up to `OPENBELT_LOCAL_DB_WAIT_MS` (15 s) before refusing. Scheduled jobs and retries are stored in the process's wake file so restarts re-arm them automatically. ### Backups #### Live local backups Take a consistent snapshot while OpenBelt is running: ```sh # Inside Docker docker compose exec openbelt bun run data backup /data/backups/snap-1 --data /data # Compiled binary or checkout openbelt-server data backup /var/backups/snap-1 --data /var/lib/openbelt ``` The command holds `<data>/.snapshot.lock` so no SQLite file checkpoints or closes during the copy; on copy-on-write filesystems (APFS, btrfs, XFS), cloning takes milliseconds. Restore with the platform stopped: ```sh openbelt-server data restore /var/backups/snap-1 --data /var/lib/openbelt ``` #### Continuous S3 / R2 replication Set `OPENBELT_BACKUP_URL`, `OPENBELT_BACKUP_KEY_ID`, and `OPENBELT_BACKUP_SECRET` to replicate WAL changes continuously to any S3-compatible bucket (Cloudflare R2, Backblaze B2, AWS S3, or MinIO): ```sh OPENBELT_BACKUP_URL=s3://my-bucket/openbelt-prod?endpoint=https://<account>.r2.cloudflarestorage.com OPENBELT_BACKUP_KEY_ID=... OPENBELT_BACKUP_SECRET=... ``` - Each process uploads compressed WAL deltas every `OPENBELT_BACKUP_SECONDS` (default `1`) and full file snapshots every `OPENBELT_BACKUP_SNAPSHOT_SECONDS` (default `300`), plus a clean base snapshot on startup that prunes obsolete batches. - Give every server instance its own prefix in `OPENBELT_BACKUP_URL`. Startup pruning removes older batches under that prefix. - Losing a machine loses at most 1 to 2 seconds of writes. To rebuild on a new machine, stop OpenBelt, restore into a clean directory, and start OpenBelt with the same `OPENBELT_SECRETS_KEY`: ```sh openbelt-server data restore-backup "$OPENBELT_BACKUP_URL" /var/lib/openbelt ``` Continuous replication retains the latest state only. For point-in-time history, schedule `deploy/nightly.sh` to archive daily snapshots into a separate bucket with a lifecycle retention rule. ## Files App file uploads (`files.put` in [the SDK](/docs/sdk#files)) stream directly through the gateway to a file store rather than entering SQLite. Downloads read straight from the store without waking an app. - **Disabled by default.** Set `OPENBELT_UPLOADS=on` to enable uploads. When `off`, new uploads and deletes return `403 uploads_off`, existing files remain readable, and agent docs omit upload APIs. - **Storage backend (`OPENBELT_FILES`).** Unset, files live on disk under `<OPENBELT_DATA>/<namespace>/files/<workspace>/<app>/<id>` and are included in local backups. To store files in an S3-compatible bucket, set: ```sh OPENBELT_FILES=s3://<key>:<secret>@<host>/<bucket>?region=auto ``` Append `&tls=off` for plain HTTP (such as local MinIO). Each process verifies write, read, and delete access at startup and exits with a clear diagnostic if credentials or bucket settings fail. Bucket files are separate from SQLite backups. - **Limits and cleanup.** Defaults cap each file at `100 MB` (`OPENBELT_FILES_MAX_MB`), each workspace at `10240 MB` (`OPENBELT_FILES_WORKSPACE_MB`), local disk headroom at `2048 MB` (`OPENBELT_FILES_DISK_FLOOR_MB`), and concurrent streams at `16` per process (`OPENBELT_FILES_IN_FLIGHT`, up to ~32 MB per stream). Apps automatically sweep unreferenced uploads after `24` hours (`OPENBELT_FILES_ORPHAN_HOURS`), and each process cleans abandoned partial uploads at start and every `3600` seconds (`OPENBELT_FILES_SWEEP_SECONDS`): on disk, a partial file idle for 10 minutes; in a bucket, a multipart upload begun a day ago. An upload holds its size of the workspace's room while it runs: a dropped connection gives it back at once, and a process killed mid-upload holds it for 30 seconds at most. Store outages return `502 storage` (never `404`). ## Logs, metrics and traces Every log line written to `stderr` is a single JSON object containing `at`, `level`, `msg`, `trace`, `span`, context fields (`workspace`, `app`, `actor`, `ms`), and `cause` on failure. Set `OPENBELT_LOG_LEVEL=debug` to log every request instead of only slow (>1 s) and `4xx`/`5xx` responses. ### Built-in operator endpoints The server keeps recent logs (`OPENBELT_KEEP_LOGS`, default `20000`) and spans (`OPENBELT_KEEP_SPANS`, default `50000`) in memory, exposed on the workspace host with `Authorization: Bearer $OPENBELT_ADMIN_TOKEN`: | Endpoint | What it returns | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /_ops/logs` | Recent JSON log lines (filter by `trace`, `workspace`, `app`, `level`, `since`, `text`, `limit`). | | `GET /_ops/trace?id=<trace>` | Full span tree (including in-flight spans) and matching log lines for one trace id. | | `GET /_ops/actors` | Every Durable Object on disk and whether it is `awake` or `asleep`. `POST /_ops/actors/sleep?id=<id>` puts one to sleep. | | `GET /_ops/turns` | Active and queued Durable Object turns (useful for diagnosing a stuck object; `POST /_ops/turns/release?id=<id>` breaks glass). | | `GET /_ops/metrics` | Prometheus metrics (`openbelt_http_*`, `openbelt_function_*`, `openbelt_mcp_tool_calls_*`, `openbelt_object_commits_total`, `openbelt_sandbox_*`, `openbelt_file_*`, `openbelt_turn_violations_total`). | | `POST /_ops/catalog/refresh` | Re-fetches `OPENBELT_CATALOG_URL` immediately using `If-None-Match` and updates the in-memory provider catalog snapshot. | Set `OPENBELT_DB_TRACE` (`sampled` default: 1 in 16 traces, `all`, or `off`) to include SQLite worker queue and execution timings in traces. ### OpenTelemetry export Export traces, logs, and metrics to any OTLP collector (Grafana, Honeycomb, Datadog) with standard OpenTelemetry variables: | Variable | Purpose | | ----------------------------- | ------------------------------------------------------------------------------------- | | `OTEL_EXPORTER_OTLP_ENDPOINT` | Collector base URL (`/v1/traces` and `/v1/logs` are appended). Empty disables export. | | `OTEL_EXPORTER_OTLP_HEADERS` | Comma-separated `key=value` auth headers (for example, `Authorization=Basic ...`). | | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` (default) or `http/json`. | | `OTEL_SERVICE_NAME` | Service name (`openbelt` by default). | | `OTEL_RESOURCE_ATTRIBUTES` | Extra `key=value` attributes (for example, `deployment.environment.name=prod`). | Compose includes a local Grafana + Tempo + Loki + Prometheus stack (`grafana/otel-lgtm`) with OpenBelt's dashboards at `http://localhost:3000`: ```sh OTEL_EXPORTER_OTLP_ENDPOINT=http://telemetry:4318 docker compose --profile telemetry up -d ``` ### Agents' tool calls Workspace admins can browse MCP calls and connection calls together in **Settings > Activity** (`/admin/events`), showing person, agent client, app, outcome (`ok`, `failed`, `refused`, `invalid`, `defect`), duration, shortened arguments (with secret fields stripped), and trace id. - Each workspace retains the latest 5,000 MCP calls and 500 connection calls across restarts, plus 8 days of hourly aggregates (`activity_hours`) powering the 24h / 7d activity chart. - Every tool call emits a structured `tool call:` log line, increments `openbelt_mcp_tool_calls_total` / `openbelt_mcp_tool_call_seconds`, and creates an `McpDO.tool <name>` span carrying `openbelt.tool`, `openbelt.person`, `openbelt.client`, `openbelt.agent`, and `openbelt.outcome`. - Every tool refusal and JSON-RPC error ends with `(trace <id>)` so users can pass it directly to `app_logs` or `/_ops/trace`. ## Production checklist and limits ### Storage and public-app caps | Setting | Default | What it caps | | --------------------------------------- | ------- | ------------------------------------------------------------------------------------ | | `OPENBELT_DATA_APP_MB` | `1024` | One app's SQLite data (`0` disables). Refusals return `507 storage_full`. | | `OPENBELT_DATA_WORKSPACE_MB` | `10240` | All apps in one workspace combined (`0` disables). | | `OPENBELT_DATA_DISK_FLOOR_MB` | `1024` | Minimum free disk preserved across all workspaces before writes stop. | | `OPENBELT_VERSIONS_APP_MB` | `256` | Retained deploy history per app (protects live, previous live, and active previews). | | `OPENBELT_PUBLIC_APP_WRITES_PER_MINUTE` | `6000` | Public-host writes, function calls, and live queries per app per minute (`429`). | | `OPENBELT_PUBLIC_ADDRESS_SHARE` | `2` | Max percent of an app's public write budget one client IP may use. | | `OPENBELT_PUBLIC_DATA_SHARE` | `50` | Max percent of `OPENBELT_DATA_APP_MB` writable from the public host (`507`). | ### Request, sandbox, and browser limits | Setting | Default | What it caps | | -------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------- | | `OPENBELT_RATE_PER_MINUTE` | `6000` | Requests per minute per signed-in person/workspace (persisted in `McpDO`) or anonymous IP. | | `OPENBELT_RATE_WRITES_PER_MINUTE` | `3000` | Mutating requests per minute per person/workspace or anonymous IP. | | `OPENBELT_RATE_IP_EMERGENCY_PER_MINUTE` | `30000` | Emergency per-IP ceiling across all traffic on each process. | | `OPENBELT_DEPLOYS_PER_HOUR` | `1000` | Deploy attempts per hour per person/workspace. | | `OPENBELT_FEEDBACK_PER_DAY` | `100` | `feedback_submit` reports per workspace in 24 hours. | | `OPENBELT_SANDBOX_RUNS` / `_TENANT_RUNS` | `16` / `6` | Concurrent sandbox runs machine-wide / per workspace. | | `OPENBELT_SANDBOX_PARKED` / `_TENANT_PARKED` | `16` / `8` | Runs parked waiting on `ctx.call` machine-wide / per workspace. | | `OPENBELT_SANDBOX_MACHINE_PROCESSES` | `16` | Maximum idle sandbox processes kept warm (~60 MB each at rest). | | `OPENBELT_SANDBOX_RUN_MB` / `_IDLE_MB` | `128` / `128` | Per-run WASM heap cap / per-process cached idle WASM budget. | | `OPENBELT_SANDBOX_RECYCLE_MB` | `160` | RSS threshold above which an idle sandbox process exits to free memory. | | `OPENBELT_CHECKS_AT_ONCE` | `4` | Concurrent `check_app` Chromium instances (~150 MB each; one workspace gets all but 2; prod runs 6). | MCP requests are capped at 64 MB (`413` past that), upstream connection replies at 16 MB, and in-flight MCP request memory per process at 192 MB total (80 MB per person, `503 busy`). ### Failure and crash recovery | Event | Behavior | | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | Graceful stop (`SIGTERM`, `docker stop`) | Drains requests and sleeps all objects in 1 to 4 s (22 s max). Zero data loss. | | Hard kill (`SIGKILL`, OOM) | Restarts on the same data in under 1 s with zero acknowledged writes lost; scheduled jobs re-arm automatically. | | Single worker exit (`OPENBELT_PROCESSES > 1`) | Supervisor restarts the worker in ~1.4 s while other workers keep serving. | | Kernel panic or power cut (disk intact) | Same as `SIGKILL`, minus at most ~1 s of unsynced WAL writes (0 under `OPENBELT_LOCAL_DB_SYNC=FULL`). | | Machine loss (disk lost) | Attach the persistent volume to a new VM, or restore from `OPENBELT_BACKUP_URL` with `restore-backup` and the original `OPENBELT_SECRETS_KEY`. | For a private single-machine install over Tailscale, see [Run on Tailscale](/docs/tailnet). For every environment toggle and capability gate, see [Feature flags](/docs/feature-flags) and [Architecture](/docs/architecture#configuration). --- url: https://openbelt.com/docs/tailnet group: Self-hosting --- > Run OpenBelt on macOS or Linux for your Tailscale tailnet with automatic Tailscale sign-in, safe upgrades, rollbacks, and local backups. # Run on Tailscale `bun run tailnet up` runs OpenBelt as a background service (`launchd` on macOS, `systemd --user` on Linux) for everyone on your Tailscale tailnet. Agents on any device connect over MCP, teammates open apps in the browser signed in as their Tailscale identity, and nothing is exposed to the public internet. You need Tailscale running and signed in, plus a wildcard domain configured once (see [A domain for the tailnet](#a-domain-for-the-tailnet) below). Then start the service from your OpenBelt checkout: ```sh bun run tailnet up ``` When it finishes starting, `tailnet up` prints: - Your workspace URL (`https://acme.<your-domain>:8444`), where everyone on your tailnet signs in automatically with their Tailscale account, and each app runs on `https://<app>--acme.<your-domain>:8444`. - Ready-to-paste MCP commands (with a minted `pr_...` API token) for connecting Claude Code, Codex, or other agents from any device on your tailnet. ## A domain for the tailnet Every app runs on its own origin (`<app>--acme.<domain>`, see [Who is viewing](/docs/viewers#every-app-on-its-own-host)), whereas `tailscale serve` answers only the host's single `.ts.net` name. `bun run tailnet` and `bun run dev` run a lightweight front door (`scripts/lib/frontdoor.ts`) that terminates HTTPS for your wildcard domain, identifies peers through Tailscale, and holds requests while the platform restarts. Configure the domain once: 1. Pick a domain whose DNS you control, such as `openbelt.example.com`. 2. Add two DNS-only (unproxied) `A` records pointing `openbelt.example.com` and `*.openbelt.example.com` at this host's tailnet IP (`tailscale ip -4`). The address is private to your tailnet, and MagicDNS resolves the public DNS records for every device on the tailnet. 3. Save the domain and a Cloudflare DNS API token (zone DNS edit permission) in `~/.config/openbelt/dev.env` and restrict permissions (`chmod 600 ~/.config/openbelt/dev.env`): ```sh CLOUDFLARE_DNS_API_TOKEN=... OPENBELT_DEV_DOMAIN=openbelt.example.com OPENBELT_DEV_CERT=~/.config/openbelt/dev-cert/certificates/openbelt.example.com.crt OPENBELT_DEV_KEY=~/.config/openbelt/dev-cert/certificates/openbelt.example.com.key ``` `bun run tailnet` and `bun run dev` load these `OPENBELT_DEV_*` variables automatically (shell environment variables take precedence). 4. Obtain a wildcard certificate via DNS challenge with [lego](https://go-acme.github.io/lego/) v5 (`brew install lego` on macOS, or your Linux package manager / `go install`): ```sh lego run --env-file ~/.config/openbelt/dev.env --path ~/.config/openbelt/dev-cert \ --dns cloudflare --dns.propagation.wait 60s --accept-tos --email you@example.com \ -d openbelt.example.com -d '*.openbelt.example.com' ``` `--dns.propagation.wait 60s` avoids local DNS lookup failures on networks that intercept port 53. Certificates expire after 90 days; `bun run tailnet up` and `bun run dev` print the expiry date and warn starting 14 days ahead with the renewal command. Once set up, `bun run tailnet up` serves `https://acme.openbelt.example.com:8444` (and `bun run dev` uses port `8445`). The front door also answers the host's `.ts.net` name using Tailscale's certificate so older links and MCP URLs keep working. To connect another person's agent on the tailnet, mint a token for them: ```sh bun run tailnet token teammate@example.com ``` ## Commands | Command | What it does | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `bun run tailnet up [ref] [--drop]` | Start or upgrade the service to `ref` (branch, tag, or commit; default `main`; use `origin/main` to track remote without moving your local branch). | | `bun run tailnet status` | Show running state, active commit, commits behind `main`, and the available rollback target. | | `bun run tailnet rollback [--data]` | Revert to the previous release. Pass `--data` to also restore the pre-upgrade data snapshot. | | `bun run tailnet token [email]` | Mint an API token (defaults to your Tailscale login) and print ready-to-paste MCP commands. | | `bun run tailnet logs [--follow]` | Print the last 50 log lines (or stream with `--follow`). | | `bun run tailnet down` | Stop both the platform and front-door services. Data stays intact. | Set `OPENBELT_TAILNET=<name>` before any command to run a separate isolated tailnet instance with its own paths, services, and ports. ## How it runs and who is signed in - **Two background services.** `bun run tailnet` installs two user services that start at login and auto-restart on failure: the platform server listening only on `127.0.0.1`, and the HTTPS front door listening on your host's tailnet IP (port `8444` or the next free port). - **Isolated releases.** Each `up` deploys from its own cloned release directory, so editing your git checkout never reloads or affects the running tailnet server. - **Automatic Tailscale identity.** The front door runs `tailscale whois` on each peer IP, strips any client-supplied identity headers, and injects `Tailscale-User-Login` and `Tailscale-User-Name`. Everyone on the tailnet signs in automatically (`db.me()` returns their Tailscale `{ email, name }`). Tagged devices (such as servers or exit nodes) have no user login and appear signed out. > [!WARNING] > Because the platform trusts identity headers arriving on `127.0.0.1`, any local process on the host could forge headers directly against the loopback port. Run `bun run tailnet` only on a machine you control. ## Upgrading and rollbacks Pull updates into `main` (or pass `origin/main`) and run `bun run tailnet up`: 1. **Dry-run on a live copy.** `up` starts the new version on spare ports against a copy of your live data while the current version keeps serving. If startup fails or any apps, live versions, documents, previews, or tokens go missing, `up` aborts with zero impact. 2. **Snapshot and swap.** `up` stops the old server, snapshots the data directory, and starts the new release. The front door holds requests for a few seconds during the swap so browsers and agents see a brief pause instead of an error (past 30 seconds, pages show an auto-reloading "Updating" screen and API callers get `503`). 3. **Automatic rollback.** If the new release fails to answer within 2 minutes or drops an app that the dry-run had, `up` restores the previous version and snapshot automatically. If a release intentionally drops stored data listed under `dropped` in `apps/platform/storage.json`, `up` prints what will be removed and stops until you re-run with `--drop`. `bun run tailnet rollback` reverts one release (add `--data` to restore the pre-upgrade data snapshot, discarding writes made since). Both `up` and `rollback` refuse to switch to an older version that neither runs nor drains an alarm job kind booked by the current version (see [Running on a server](/docs/running#running-on-a-server)). ## Data, backups, and settings State lives under `~/.local/share/openbelt/`: - `tailnet-data/data/`: Durable Object SQLite files (`tailnet` namespace). Take a live backup anytime with: ```sh bun run data backup ~/openbelt-backup --data ~/.local/share/openbelt/tailnet-data/data ``` See [Backups](/docs/running#backups) for restore instructions. Delete this folder (after `bun run tailnet down`) to start fresh. - `tailnet-snapshots/`: Automatic pre-upgrade snapshots (last 5 retained). - `tailnet-releases/`: Current and previous releases with their dependencies. - `tailnet/`: Internal git clone used to build releases. - `tailnet-front.js` and `tailnet-front.json`: Front-door script and routing state. Secrets and settings live in `~/.config/openbelt/tailnet.env` (`0600`), generated on the first `up`. Optional feature flags (`OPENBELT_STUDIO`, `OPENBELT_STUDIO_MODEL`, `OPENBELT_UPLOADS`, `OPENBELT_AI_CHATGPT`, `OPENBELT_AI_API_KEY`, `OPENBELT_AI_BASE_URL`, `OPENBELT_AI_API`, `OPENBELT_AI_MODEL_*`, `OPENBELT_AI_STUB`, `OPENBELT_BROWSER`, `OPENBELT_APP_PAGES`, `OPENBELT_PROCESSES`, `OPENBELT_ALLOW_LOCAL_CONNECTIONS`) set in `tailnet.env` are forwarded into the service environment (`launchd` plist on macOS, `systemd --user` env file on Linux). Run `bun run tailnet up` after editing `tailnet.env` to validate and reload. ## AI on your tailnet Apps with `"ai": true` (see [AI](/docs/ai)) can use each member's personal ChatGPT subscription without configuring a server-wide API key: 1. Open **Settings** (`/settings`) and choose **AI** (`/_ai/connect`). 2. Complete the ChatGPT sign-in flow. 3. Because the server runs on your tailnet rather than `localhost`, copy the final `127.0.0.1` redirect URL from your browser's address bar and paste it into the OpenBelt form. Credentials are sealed in this instance's SQLite storage and remain isolated from hosted `openbelt.com` and from other workspace members. ## Limits - **Headless Linux hosts.** `bun run tailnet` uses `systemd --user` on Linux. Enable `loginctl enable-linger "$USER"` so services keep running after you log out. - **Single host availability.** When the host sleeps or powers off, apps and MCP connections are unavailable. - **Non-443 port.** Port `443` is often occupied on workstations, so the front door binds port `8444` (or the next available port). - **Platform hangs.** Requests have no global process CPU cap; if a platform bug hangs the server process, run `bun run tailnet up` to restart it. --- url: https://openbelt.com/docs/feature-flags group: Self-hosting --- > Every OpenBelt feature toggle and capability gate, its defaults across dev, self-hosted, and hosted deploys, and how to add a new flag. # Feature flags OpenBelt controls optional features and deployment modes through `OPENBELT_*` environment variables. Every flag is validated at startup; an invalid value stops the server and names the offending variable. ## Feature toggles | Flag | Values | Code default | `bun run dev` | Self-hosted (`compose.yaml`) | Hosted (`deploy/compose.server.yaml`) | What it controls | | ---------------------------------- | ----------------------------------------- | ------------ | ------------------------- | ---------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `OPENBELT_AI_API` | `responses` \| `completions` | `responses` | `responses` | `responses` | not forwarded (`responses`) | Wire format for custom OpenAI-compatible AI endpoints (`apps/platform/src/ai/index.ts`). | | `OPENBELT_AI_CHATGPT` | `on` \| `off` | `on` | `on` | `on` | `off` | Optional Sign in with ChatGPT on `/_ai/connect` and stored `provider='chatgpt'` token usage. `off` returns 404 on `/_ai/connect/{start,callback,finish}` while leaving OpenRouter OAuth and BYOK keys active ([AI](/docs/ai)). | | `OPENBELT_AI_STUB` | `off` \| `on` | `off` | `off` | `off` | `off` | Deterministic offline AI stub for `check_app` and verification runs ([AI](/docs/ai)). | | `OPENBELT_STUDIO` | `off` \| `on` \| `<ws1,ws2>` | `off` | `off` | `off` | `off` | Built-in Studio app builder (`/build`, `/_studio/*`, workspace dock, Archived filter). Accepts `on`, `off`, or a comma-separated workspace allowlist (`apps/platform/src/objects/studio/config.ts`). | | `OPENBELT_UPLOADS` | `on` \| `off` | `off` | `on` | `off` | `off` | App file uploads (`files.put()` and upload MCP tools). `off` refuses new uploads and omits upload docs for agents while still serving stored files ([Self-hosting](/docs/running#files)). | | `OPENBELT_TRIALS` | `on` \| `off` | `off` | `off` | `off` | `off` (not forwarded) | Agent-started trial workspaces (`/trial`, `/claim/*`) under `OPENBELT_SIGNIN=email` only ([Self-hosting](/docs/running)). | | `OPENBELT_ALLOW_LOCAL_CONNECTIONS` | `1` \| unset | off | `1` | off | off | Lets workspace MCP connections target `http://localhost`. For local development and verification only ([Architecture](/docs/architecture#configuration)). | | `OPENBELT_BROWSER` | `local` \| `cloudflare` \| `cdp` \| `off` | `local` | `local` | `local` | `local` | Headless browser backend for `check_app` and link preview cards (`packages/runtime/src/browser.ts`). | | `OPENBELT_SIGNIN` | `off` \| `tailscale` \| `email` | `off` | `email` (with owner door) | `tailscale` | `off` (set `email` in stage env) | Viewer authentication mode: anonymous (`off`), identity proxy headers (`tailscale`), or email codes and OIDC (`email`) ([Who is viewing](/docs/viewers)). | | `OPENBELT_APP_PAGES` | `frame` \| `host` | `frame` | `frame` | `frame` | not forwarded (`frame`) | Whether page loads on `<app>--<workspace>.<host>` redirect into the workspace frame (`/a/<app>/...`) or render directly on the app host ([Architecture](/docs/architecture#configuration)). | ## Verified toggle forwarding Generated directly from `Config.Literals` in `apps/platform/src/` and the compose, deploy, and tailnet configs (`bun run docs:sync`): <!-- generated:feature-flag-literals:start --> | Flag | Values | Code default | `bun run dev` | `compose.yaml` | `deploy/compose.server.yaml` | `scripts/dev/tailnet/index.ts` | Source | | --------------------- | ------------------------------------------------- | ------------ | ---------------------- | -------------- | ---------------------------- | ------------------------------ | -------------------------------------- | | `OPENBELT_AI_API` | `responses` \| `completions` | `responses` | `responses` | not forwarded | not forwarded | forwarded | `apps/platform/src/ai/index.ts` | | `OPENBELT_AI_CHATGPT` | `on` \| `off` | `on` | `on` | forwarded | forwarded | forwarded | `apps/platform/src/ai/index.ts` | | `OPENBELT_AI_STUB` | `off` \| `on` | `off` | `off` | not forwarded | not forwarded | forwarded | `apps/platform/src/ai/index.ts` | | `OPENBELT_APP_PAGES` | `frame` \| `host` | `frame` | `frame` | not forwarded | not forwarded | forwarded | `apps/platform/src/gateway/context.ts` | | `OPENBELT_CLASSIFIER` | `auto` \| `cloudflare` \| `ai` \| `clef` \| `off` | `auto` | `auto` | not forwarded | forwarded | not forwarded | `apps/platform/src/ai/classifier.ts` | | `OPENBELT_TRIALS` | `on` \| `off` | `off` | `off` | not forwarded | not forwarded | not forwarded | `apps/platform/src/billing/trials.ts` | | `OPENBELT_UPLOADS` | `on` \| `off` | `off` | configured in `dev.ts` | not forwarded | forwarded | forwarded | `apps/platform/src/lib/files.ts` | <!-- generated:feature-flag-literals:end --> ## Capability gates (enabled when configured) These features have no separate `on`/`off` toggle. Setting the primary variable enables them; leaving it empty keeps them off. | Variable(s) | When unset | What setting it enables | | ----------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `OPENBELT_STRIPE_SECRET_KEY` (+ `_WEBHOOK_SECRET`, `_PRICE_PRO`) | Plan limits off | Stripe billing, checkout, and workspace plan quotas (`apps/platform/src/billing/index.ts`). | | `OPENBELT_PUBLIC_HOST` | No public apps | Serves apps marked `"public"` in `openbelt.json` to signed-out visitors on `<app>--<workspace>.<public host>` (requires `OPENBELT_SIGNIN=email`; [Apps](/docs/apps)). | | `OPENBELT_AI_API_KEY` | No server fallback key | Operator OpenAI-compatible API key used for signed-in workspace members when no personal AI connection is active ([AI](/docs/ai)). | | `OPENBELT_GOOGLE_CLIENT_ID` / `_SECRET` | Email codes only | Continue with Google button on the email sign-in page ([Who is viewing](/docs/viewers)). | | `OPENBELT_SSO_ISSUER` / `_CLIENT_ID` / `_SECRET` | No custom SSO | Custom OpenID Connect SSO button on the email sign-in page ([Who is viewing](/docs/viewers)). | | `OPENBELT_CATALOG_URL` | Built-in catalog only | External provider catalog feed JSON URL (`off` disables; cached on disk and refreshed via ETag or `POST /_ops/catalog/refresh`; [Connections](/docs/connections)). | | `OPENBELT_CONNECT_<FAMILY>_CLIENT_ID` / `_SECRET` | Workspaces register own apps | Shared platform OAuth apps for MCP and API connections (`GITHUB`, `GOOGLE`, `ASANA`, `LINKEDIN`, or feed families; [Connections](/docs/connections)). | | `OPENBELT_JOURNAL` (+ `_KEY`, `_UPLOAD_URL`) | No incident journal | Rolling per-process incident journal and sealed bundle uploads (`packages/runtime/src/journal.ts`). | | `OPENBELT_BACKUP_URL` (+ `_KEY_ID`, `_SECRET`) | Local disk only | Continuous SQLite WAL replication to S3 or R2 ([Self-hosting](/docs/running#backups)). | | `OPENBELT_MAIL_TOKEN` (+ `_ACCOUNT`, `_FROM`, `OPENBELT_APP_MAIL_FROM`) | Logged only (no email sent) | Cloudflare Email Sending for sign-in codes (`OPENBELT_MAIL_FROM`, default `hello@<base host>`) and app emails via `ctx.email.send` (`OPENBELT_APP_MAIL_FROM`, separate sender domain defaulting to `notifications@mail.<host>`; [Functions](/docs/functions)). | | `OPENBELT_WEB_ANALYTICS` | No beacon | Cloudflare Web Analytics beacon on the public landing pages only ([Architecture](/docs/architecture#configuration)). | ## Adding or changing a flag 1. **Read it with Effect `Config`** in `apps/platform/src/` with an explicit, safe default. 2. **Forward it to hosted deploys** if operators need it in prod: add it to both `scripts/ops/deploy/index.ts` (`envFile`) and `deploy/compose.server.yaml` (`environment`). `scripts/ops/deploy/index.ts` refuses to deploy if a stage `.env` sets a key that `deploy/compose.server.yaml` would drop. 3. **Forward it to self-hosted and tailnet installs** in `compose.yaml` and `FORWARDED_ENV` in `scripts/dev/tailnet/index.ts` (`~/.config/openbelt/tailnet.env`) when self-hosters should control it. 4. **Update `docs/feature-flags.md`**, run `bun run docs:sync`, and test both off and on states in `scripts/verify/checks/`. --- url: https://openbelt.com/docs/architecture group: Self-hosting --- > How OpenBelt is built: the gateway, Durable Objects on per-object SQLite files, the turn-based runtime, QuickJS sandboxes, and configuration reference. # Architecture OpenBelt is a single Bun + Effect v4 server (`apps/platform/src/entry/server.ts`) combining a stateless HTTP gateway with four Durable Object classes (`WorkspaceDO`, `AppDO`, `McpDO`, and the singleton `ApexDO`) hosted on OpenBelt's own runtime (`packages/runtime/src/`). Every object owns a dedicated SQLite file inside `OPENBELT_DATA`. With `OPENBELT_PROCESSES > 1`, a supervisor spreads workers across one port via `SO_REUSEPORT`, hashes each object to one worker, and routes cross-worker calls over loopback. ```text browser / agent │ <domain>, <workspace>.<domain> or <app>--<workspace>.<domain> ▼ Gateway (apps/platform/src/gateway/index.ts) host -> workspace (+ app), trace id per request base host (email sign-in; gateway/base.ts): ├─ /, /auth.md, /start.md, /llms.txt marketing pages (apps/www/) and agent onboarding ├─ /signin, /_oauth/*, /start ───► ApexDO base sign-ins, OAuth clients, workspace directory ├─ /mcp, /_oauth/token ──────────► WorkspaceDO / McpDO workspace-prefixed token routing └─ /trial, /claim/* ─────────────► WorkspaceDO trial workspaces (OPENBELT_TRIALS=on) workspace host: ├─ /mcp ─────────────────────────► McpDO (workspace/person) MCP server calling WorkspaceDO & AppDO ├─ /.well-known/oauth-*, /_oauth/* ─► WorkspaceDO MCP client OAuth ├─ /scim/v2/* ───────────────────► WorkspaceDO SCIM 2.0 directory sync └─ /, /settings, /_workspace, /_me, /_ops ─► WorkspaceDO (workspace) └─► upstream MCP servers and APIs app host: ├─ /... ─────────────────────────► AppDO (app id) files, versions, documents, WebSockets, logs ├─ /_fn/<name> ──────────────────► AppDO sandboxed function execution ├─ /a/<other>/_db, /_ws, /_fn ───► AppDO cross-app reads and calls ├─ /_hook/<fn> ──────────────────► AppDO signed external webhooks ├─ /_tools, /_tools/call ────────► WorkspaceDO viewer/workspace connection tools └─ /sdk.js SDK served directly by the gateway ``` | Component | Keyed by | Responsibilities | | --------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Gateway** | Stateless | Resolves host to workspace and app, mints trace ids, serves `/sdk.js`, authenticates viewers (front door or session cookie), checks membership with `WorkspaceDO`, and proxies requests and WebSockets. | | **WorkspaceDO** | Workspace id | People, roles, groups, joining policy, API token hashes ([People & groups](/docs/people)), MCP OAuth grants ([MCP](/docs/mcp#signing-in-oauth)), connections, sealed tokens, access rules, consents, upstream MCP sessions, OAuth refresh sweeps ([Connections](/docs/connections)), app registry and directory cards (so home and search wake no app), and preview TTLs. | | **AppDO** | Permanent app id | Content-addressed files, manifests, live and preview pointers, documents, change log, WebSockets, logs, usage metrics, sealed secrets, and durable jobs (live queries, schedules, triggers, `ctx.later`, preview screenshots). Runs functions in QuickJS WASM sandboxes and commits their writes atomically. | | **ApexDO** | Platform singleton | Base-host email sign-ins, base OAuth clients, email-to-workspace membership index, workspace creation and domain discovery, trial quotas, and the workspace rename directory. | | **McpDO** | Workspace id + person id | Per-person MCP server exposing platform operations, `execute` sandboxes, and rate-limit buckets. | ## Packages and layers The codebase separates Layer-0 shared packages (`packages/`) from deployable apps (`apps/`) with strict downward boundaries enforced by `bun run arch` (`fallow architecture` via `.fallowrc.json`) and `scripts/check/guard/index.ts`: ```text packages/model/src/ Layer 0: pure schemas, IDs, errors, hosts, openbelt.json config, rules packages/runtime/src/ Layer 0: Durable Objects on SQLite, turns, jobs, sockets, QuickJS sandbox, Chromium packages/client/src/ Layer 0: browser scripts (*.browser.js, sdk.browser.js) and Solid Studio bundle apps/platform/src/ Server application in six strict layers: lib/ Layer 1: stateless helpers (HTTP, files, mail, outbound fetch, rate limits, redaction, skills) activity/ Layer 2: domain modules (acyclic: check -> auth -> connections -> activity, ai -> connections; billing & people standalone) ai/ AI providers, streaming, classifier, SIWC auth/ email sign-in, OIDC, OAuth server, device sign-in, session, front door billing/ plans, usage billing, trial workspaces check/ check_app browser harness, steps, cards, reporter connections/ upstream MCP servers, APIs, OAuth signins/, access policy, provider catalog people/ people, groups, admission, tokens, avatars, SCIM objects/ Layer 3: Durable Objects (apex/, app/, workspace/, mcp/, studio/) web/ Layer 4: SafeHtml views and static assets (ui/, public/, home/, studio/, frame/, pages/) gateway/ Layer 5: stateless HTTP & WebSocket router entry/ Layer 6: server and compiled-binary entrypoints apps/desktop/ Electron desktop host, app shims and macOS packaging apps/cli/ Rust `openbelt` CLI apps/www/ Marketing site ``` - **Leaf packages stay pure.** `packages/model`, `packages/runtime`, and `packages/client` import no other workspace package. - **Dependencies flow strictly downward.** Layer 2 domains never import `objects/`, `web/`, `gateway/`, or `entry/`; `objects/` never imports `web/`, `gateway/`, or `entry/`; `web/` never imports `gateway/` or `entry/`; `gateway/` never imports `entry/`. - **Zero cycles and complete coverage.** Package cycles, circular imports, loose files at `apps/platform/src/`, and sibling `<name>.ts` + `<name>/` pairs fail `bun run check`. Run `bunx fallow guard <file>` before editing to inspect a file's allowed import zones. ## Why one Durable Object per app An app's files, documents, realtime feed, and logs are always accessed together. Co-locating them in one SQLite-backed object serves pages in one hop, promotes versions in one transaction, prevents noisy neighbors from sharing a database lock, and reduces idle apps to zero CPU cost. ## The runtime Platform code targets `packages/runtime/src/` (`Runtime.DurableObject`, `state.storage.sql.exec`, `Runtime.makeCallback`): - **Single-threaded turns (`events.ts`, `turn.ts`).** Every request, RPC, timer, or WebSocket message queues in the object's mailbox and runs exclusively until it finishes or yields an _away_ wait (another object, sandbox, network, or `Runtime.idle`). Before yielding, writes flush durably so another event can take a turn; when the wait finishes, the event re-enters the queue. Read-modify-write sequences inside a turn never interleave. - **One away at a time.** Parallel external calls must share one `Runtime.away(...)` block that does not touch object storage. - **Background work.** Use `Runtime.tell(effect)` for fire-and-forget calls to other objects, or `ObjectState.ownEvent(what, effect)` for queued work on the same object (`Effect.forkDetach` is banned by `scripts/check/guard/index.ts`). - **Storage and timeouts.** Storage calls (`sql.exec`, `kv`, `transaction`, jobs) are enforced at runtime to run only while holding an active turn. Timeouts use `Runtime.holdingTimeout(duration)` rather than `Effect.timeout*`. - **Violation detection.** Any rule violation throws immediately, logs a `turns:` error, and increments `openbelt_turn_violations_total{kind}`. `scripts/proofs/turns.ts`, `scripts/proofs/turns-model/index.ts`, `scripts/proofs/turns-fuzz.ts`, and `scripts/proofs/sim/` verify the turn kernel continuously. - **SQLite storage (`storage.ts`, `localdb.ts`).** `sql.exec` runs on dedicated worker threads (synced ~1/sec; see [Self-hosting](/docs/running#the-data)), `kv` lives in the same SQLite database, and `transaction` wraps both in a savepoint. - **Durable jobs (`jobs.ts`).** `makeCallback` persists jobs inside the same transaction that schedules them, providing at-least-once delivery across restarts via per-process wake files. - **Sockets (`socket.ts`, `serve.ts`).** The gateway bridges browser WebSockets to the owning object (over loopback if hosted by another worker). - **QuickJS sandboxes (`sandbox.ts`, `sandbox-process.ts`, `sandbox-confine.ts`).** Functions and agent `execute` calls run in QuickJS WASM inside per-workspace sandbox processes (never shared across workspaces, running as `nobody` in Docker) confined via Linux Landlock + seccomp or macOS `sandbox_init` (no filesystem, no exec, no sockets, no cross-process signals). Each concurrent call gets a memory-capped WASM instance. - **Browser (`browser.ts`) and lifecycle (`actor.ts`, `supervisor.ts`).** `check_app` launches isolated headless Chromium sessions. Objects wake on demand and sleep after 10 minutes idle with no open sockets. Each deployment instance isolates its data in a namespace folder under `OPENBELT_DATA`. ## Why not workerd OpenBelt preserves the Durable Object programming model so platform code remains portable to Cloudflare's `workerd`, but runs its own Bun runtime for throughput and isolation. Benchmarked on a Hetzner CCX33 (3 runs each, `workerd 1.20261115.1` with functions and `check_app` stubbed): | Metric | Bun runtime | workerd | | ---------------------------------- | ----------- | -------- | | App pages/sec (32 clients) | 1,748 | 704 | | App pages p99 | 29 ms | 91 ms | | Document writes/sec (32 clients) | 551 | 282 | | p99 at 1,000 pages/sec | 2 ms | 42 ms | | Broadcast to 10,000 sockets p99 | 137 ms | 1,264 ms | | Restart with 2,000 objects on disk | 409 ms | 27 ms | | Memory while serving pages | 638 MB | 392 MB | While `workerd` restarts faster and uses less memory, standalone `workerd` cannot enforce per-script CPU or memory caps on user code (`while (true) {}` blocks the process and memory bombs abort it). Running QuickJS sandboxes, Chromium checks, and SQLite backups alongside the objects in Bun avoids operating two separate runtimes. ## Workspaces and hosts The first DNS label identifies the workspace (`acme.<OPENBELT_HOST>`), and each app gets its own origin (`<app>--<workspace>.<OPENBELT_HOST>`, parsed in `packages/model/src/hosts.ts`). The gateway passes the caller app in `x-openbelt-caller` and serves `/_db` and `/_tools` only to that app's own origin. Reserved labels (`www`, `staging`, `api`, `admin`, `docs`, `status`, `mail`, `dev`, `pr`) cannot be workspace names. Workspaces share no objects, data, or tokens. ### Workspace names and ids A workspace's **id** (`WorkspaceId`) is its original creation name and never changes; all Durable Object keys and base-host tokens reference the id. Its **name** (`WorkspaceName`) is the live hostname label, which admins can change ([Renaming the workspace](/docs/people#renaming-the-workspace)). `ApexDO` stores renamed workspaces in `workspace_names` (every current and historical name, max 10 per workspace), `workspace_current`, and `workspace_ids`. Unrenamed workspaces need no rows. Every worker caches the small rename table in memory (`apps/platform/src/objects/apex/workspace-names.ts`) and refreshes it every 2 seconds (or within 250 ms on a cache miss under email sign-in), redirecting page requests on historical hosts via `308` while routing API and MCP calls transparently. ## Configuration For every feature toggle and capability gate across dev, self-hosted, and hosted deploys, see [Feature flags](/docs/feature-flags). | Setting | Default | Purpose | | -------------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------- | | `OPENBELT_HOST` | `localhost` | Wildcard domain for workspaces (`<ws>.`) and apps (`<app>--<ws>.`). | | `OPENBELT_BASE_HOST` | `OPENBELT_HOST` | Dedicated domain under email sign-in for landing pages, sign-in, and shared `/mcp`. | | `OPENBELT_PUBLIC_HOST` | none | Dedicated domain under email sign-in for `"public"` apps (`<app>--<ws>.<public-host>`). | | `OPENBELT_APP_PAGES` | `frame` | `frame` redirects app-host browser loads into `/a/<app>/...`; `host` serves directly. | | `OPENBELT_DEFAULT_WORKSPACE` | `acme` | Workspace used for hosts without a workspace label. | | `OPENBELT_PORT` | `1337` | HTTP listen port. | | `OPENBELT_PROCESSES` | `1` | Worker count (`auto`: 1 per 2 CPUs, max 4; default in `compose.yaml`). | | `OPENBELT_DATA` | `~/.openbelt/data` | Root directory for per-object SQLite files ([Self-hosting](/docs/running#the-data)). | | `OPENBELT_NAMESPACE` | `openbelt` | Subdirectory inside `OPENBELT_DATA` for this instance. | | `OPENBELT_ADMIN_TOKEN` | required | Operator bearer token for `/_ops/*` routes. | | `OPENBELT_SECRETS_KEY` | required | AES-GCM key sealing connection tokens, app secrets, and webhook secrets. | | `OPENBELT_SESSION_SECRET` | `OPENBELT_ADMIN_TOKEN` | Signs browser session cookies. Set separately in production. | | `OPENBELT_SIGNIN` | `off` | Viewer auth mode: `tailscale`, `email`, or `off`. | | `OPENBELT_SIGNIN_ALLOW` | anyone | Comma-separated emails and `@domains` permitted under `OPENBELT_SIGNIN=email`. | | `OPENBELT_MAIL_TOKEN` | none | Cloudflare Email Sending token (`OPENBELT_MAIL_ACCOUNT`, `OPENBELT_MAIL_FROM`). | | `OPENBELT_UPLOADS` | `off` | Enable (`on`) or disable (`off`) app file uploads ([Self-hosting](/docs/running#files)). | | `OPENBELT_FILES` | local disk | File store backend: local disk or `s3://<key>:<secret>@<host>/<bucket>` ([Self-hosting](/docs/running#files)). | | `OPENBELT_FILES_MAX_MB` / `_WORKSPACE_MB` / `_DISK_FLOOR_MB` | `100` / `10240` / `2048` | Upload size cap, workspace file quota, and local disk headroom floor (MB). | | `OPENBELT_FILES_IN_FLIGHT` / `_ORPHAN_HOURS` / `_SWEEP_SECONDS` | `16` / `24` / `3600` | Concurrent upload streams, orphan file TTL, and partial-upload sweep interval. | | `OPENBELT_PUBLIC_APP_WRITES_PER_MINUTE` / `_ADDRESS_SHARE` / `_DATA_SHARE` | `6000` / `2` / `50` | Public-host rate cap, single-IP percent share, and max percent of app storage writable publicly. | | `OPENBELT_CLI_DIR` | `apps/cli/dist` | Directory of prebuilt `openbelt` CLI binaries served at `/install` and `/_cli/*`. | | `OPENBELT_CHROME_PATH` | auto-detected | Path to local Chrome/Chromium executable for `check_app`. | | `OPENBELT_ALLOW_LOCAL_CONNECTIONS` | off | `1` permits `http://localhost` MCP connections (local dev and verify only). | | `OPENBELT_DOOR_PORT` / `OPENBELT_HTTPS_PORT` | none | Local `bun run dev` owner door and tailnet HTTPS ports. | | `OPENBELT_PREVIEW_TTL_SECONDS` | 7 days | Idle lifetime before unused preview environments expire. | | `OPENBELT_HIDDEN_SOCKET_SECONDS` | 5 minutes | Delay before hidden browser tabs close WebSockets so apps can sleep. | | `OPENBELT_CHECK_TIME_LIMIT_SECONDS` / `OPENBELT_FUNCTION_SECONDS` | `30` / `30` | Max wall time for `check_app` and function runs. | | `OPENBELT_SANDBOX_WARM_SECONDS` / `OPENBELT_LIVE_CLOCK_SECONDS` | `30` / `60` | Extra warm sandbox retention and live-query clock refresh interval. | | `OPENBELT_REFRESH_HOLD_SECONDS` / `OPENBELT_REFRESH_BACKOFF_SECONDS` | `60` / `30` | OAuth refresh cooldown after a 401 and initial transient-error backoff. | | `OPENBELT_OAUTH_ACCESS_TTL_SECONDS` | 30 days | Sliding idle TTL for MCP OAuth access tokens. | | `OPENBELT_WEB_ANALYTICS` | none | Cloudflare Web Analytics token for public marketing pages only. | | `OPENBELT_INTERNAL_EMAILS` | nobody | Addresses and `@domains` tagged `kind=internal` in sign-up funnel logs. | | `OPENBELT_JOURNAL` / `OPENBELT_TURNS_REPORT` | none | Diagnostic turn replay journal (`scripts/ops/replay/index.ts`) and turn-violation report output directories. | ## Current architectural limits - **Single-machine storage.** Each deployment keeps its SQLite files on one server's disk; scale horizontally by running separate deployments rather than clustering one workspace across nodes. - **Custom domains.** Workspaces and apps use subdomains under `OPENBELT_HOST` (and `OPENBELT_PUBLIC_HOST`) rather than arbitrary per-app custom domains.