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
{
"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
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
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
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 `<li data-id="${d.id}" class="${t.done ? "done" : ""}">
<button class="check" data-act="toggle" aria-label="${t.done ? "Mark open" : "Mark done"}" ${me ? "" : "disabled"}></button>
<div class="body"><div class="title">${esc(t.title)}</div><div class="meta">${meta}</div></div>
${me && !t.done && !t.claimedBy ? `<button class="btn sm" data-act="take">Take</button>` : ""}
${me && d.author === me.email ? `<button class="del" data-act="delete" aria-label="Delete">×</button>` : ""}
</li>`
}
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("") || `<li class="empty">Nothing open</li>`
$("#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
{
"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
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 `<div class="item${reply ? " reply" : ""}" data-id="${d.id}">
<div class="avatar" style="background:hsl(${hue(d.author)} 45% 48%)">${esc(name[0]?.toUpperCase())}</div>
<div class="body">
<div class="head"><b>${esc(d.author === me?.email ? "You" : name)}</b><span class="time">${ago(d.created)}</span>
${me && d.author === me.email ? `<button class="del" aria-label="Delete">×</button>` : ""}</div>
<p>${esc(d.data.text)}</p>
</div>
</div>`
}
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)
? `<form class="reply-form"><input placeholder="Reply" maxlength="2000" autocomplete="off"><button class="btn sm primary">Reply</button></form>`
: `<button class="reply-btn">Reply</button>`
return `<article data-post="${p.id}">${item(p)}${rs.length ? `<div class="replies">${rs.map((r) => item(r, true)).join("")}</div>` : ""}${action}</article>`
})
.join("") || `<p class="empty">No posts yet</p>`
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
{
"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
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) => `<a href="${urls[app]}">${APPS[app].name}</a>`))} 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]) =>
`<a class="stat" href="${urls[app]}"><div class="name"><span class="dot" style="background:${APPS[app].color}"></span>${APPS[app].name}</div><div class="num">${num}</div><div class="sub">${sub}</div></a>`,
)
.join("")
const items = feed()
$("#feed").innerHTML =
items
.map(
([app, t, text]) =>
`<li><a href="${urls[app]}"><span class="dot" style="background:${APPS[app].color}"></span><span class="text">${esc(text)}</span><span class="when">${ago(t)}</span></a></li>`,
)
.join("") || `<li class="empty">Nothing yet</li>`
}
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()