# Forkbase documentation > All of https://forkbase.tech/docs in one file. Each page is also at its address plus `.md`. # Introduction > A backend for apps where AI agents write data: what Supabase gives you, plus a fork of your data per agent run, merge policies, review by a person, and undo. Source: https://forkbase.tech/docs Forkbase is a backend for apps where AI agents write data. It gives you what Supabase gives you (Postgres tables over REST, sign-in, storage, realtime, functions) and adds the part agents need: **every agent run works on its own fork of your data, a merge policy decides what reaches the real data, a person reviews the rest, and any merged change can be undone.** One binary. It runs over a Postgres you already have, or on the bundled Chronos engine. Free to self-host under [FSL-1.1-ALv2](https://github.com/2090-labs/forkbase/blob/main/LICENSE). ## Start here | Page | What it covers | |---|---| | [Getting started](https://forkbase.tech/docs/getting-started) | Install, start a server, make a table, run your first agent | | [Concepts](https://forkbase.tech/docs/concepts) | Runs, worlds, merge policies, held runs, undo, keys and tokens, the two database modes | | [Set up with an AI agent](https://forkbase.tech/docs/agent-setup) | One prompt for Claude Code, Codex or Cursor that installs Forkbase or connects your app | ## Build with it | Page | What it covers | |---|---| | [Auth](https://forkbase.tech/docs/auth) | Sign-up, passwords, emailed links and codes, Google and GitHub, sessions, admin | | [Database and REST](https://forkbase.tech/docs/rest) | `/rest/v1`: PostgREST-style reads and writes under row-level security | | [Realtime](https://forkbase.tech/docs/realtime) | Table changes and broadcast over WebSocket | | [Storage](https://forkbase.tech/docs/storage) | Buckets and files, on disk or S3, signed URLs, policies | | [Agents](https://forkbase.tech/docs/agents) | Runs, policies as code, approvals, webhooks, undo | | [Jobs](https://forkbase.tech/docs/jobs) | TypeScript and Python functions: retries, steps, sleeps, schedules, triggers | | [MCP](https://forkbase.tech/docs/mcp) | Connect Claude, Cursor or any MCP client, with OAuth 2.1 | | [Observability](https://forkbase.tech/docs/observability) | Each agent run's ledger, OpenTelemetry traces and metrics | | [SDKs](https://forkbase.tech/docs/sdks) | `forkbase` for TypeScript and Python, and supabase-js | | [Dashboard](https://forkbase.tech/docs/dashboard) | The built-in studio at `/dashboard` | ## Run it | Page | What it covers | |---|---| | [Configuration](https://forkbase.tech/docs/configuration) | Every `forkbase.toml` setting and `FORKBASE_*` variable, with defaults | | [CLI](https://forkbase.tech/docs/cli) | `init`, `start`, `migrate`, `keys`, `status`, `deploy`, `invoke` | | [Self-hosting](https://forkbase.tech/docs/self-hosting) | Docker, a TLS proxy, production checklist, backups, upgrades | | [HTTP reference](https://forkbase.tech/docs/http-reference) | Every route, who may call it, and the error shapes | | [Troubleshooting](https://forkbase.tech/docs/troubleshooting) | Common errors and what to do | | [Skills](https://forkbase.tech/docs/skills) | The whole manual as skills for coding agents, and how to install them | ## For AI agents and LLMs - [`/llms.txt`](https://forkbase.tech/llms.txt): a short map of these docs, in the [llms.txt](https://llmstxt.org) format. - [`llms-full.txt`](https://forkbase.tech/llms-full.txt): every page above in one file, for a model's context. - [Skills for coding agents](https://forkbase.tech/docs/skills): the whole of these docs as installable skills, so any coding agent knows Forkbase: `curl -fsSL /skills/install.sh | sh`. --- # Getting started > Install, start a server, make a table, and run your first agent, in about ten minutes. Source: https://forkbase.tech/docs/getting-started Ten minutes from nothing to an agent's change waiting for your review. Prefer to let a coding agent do this? Paste the prompt from [Set up with an AI agent](https://forkbase.tech/docs/agent-setup) into Claude Code or Codex and answer its questions. ## 1. Install Forkbase is one binary, `forkbase`. Agents' worlds need the Chronos engine, `chronos`, beside it. **From a release** (macOS and Linux, x86-64 and ARM): ```bash curl -fsSL https://github.com/2090-labs/forkbase/releases/latest/download/install.sh | FORKBASE_ENGINE=1 sh ``` `FORKBASE_ENGINE=1` also installs the engine. Without it you get Forkbase alone: everything works except agents. **With Docker**: see [Self-hosting](https://forkbase.tech/docs/self-hosting). **From source** (Rust 1.90+, Node 20+ for the dashboard): ```bash git clone https://github.com/2090-labs/forkbase && cd forkbase (cd dashboard && npm ci && npm run build) # the dashboard is built into the binary cargo build --profile dist -p forkbase # target/dist/forkbase ``` Get the engine from the [Chronos releases](https://github.com/2090-labs/Chronos-DB/releases) and put `chronos` on your `PATH` (or set `FORKBASE_CHRONOS_BIN`). ## 2. Pick a database mode | | `postgres` | `chronos` | |---|---|---| | Your data lives in | a Postgres 16+ you run (local, RDS, Neon, Supabase...) | the bundled Chronos engine | | Use it when | you have a Postgres, or want to keep your usual tools | you're starting fresh and want the fewest moving parts | | Agents' worlds | the engine attaches to your Postgres | native | Not sure? Start in `chronos` mode on your laptop. See [Concepts](https://forkbase.tech/docs/concepts#database-modes) for the details. ## 3. Start it ```bash mkdir myapp && cd myapp # over your Postgres forkbase init --db postgres --database-url postgres://user:pass@127.0.0.1:5432/app # or on the engine forkbase init --db chronos forkbase start ``` `init` writes `forkbase.toml` and makes a data folder, `.forkbase/`, with the server's secrets. `start` runs the migrations, starts the engine (chronos mode, or postgres mode once an agent runs) and serves on `http://127.0.0.1:8000`. In another terminal: ```bash forkbase status # {"status": "ok", ...} forkbase keys # {"anon": "...", "service_role": "..."} ``` - **anon** is safe in a browser or a phone app. It can do only what row-level security lets anonymous and signed-in people do. - **service_role** bypasses row-level security. Keep it on your servers. Never ship it to a browser. Open **http://127.0.0.1:8000/dashboard/** and sign in with the service_role key. ## 4. Make a table In the dashboard's SQL editor, or with `psql`: ```sql create table tickets ( id bigint generated always as identity primary key, title text not null, status text not null default 'open', updated_at timestamptz not null default now() ); insert into tickets (title, status) values ('Login broken', 'open'), ('Old bug', 'closed'), ('Typo', 'closed'); grant select on tickets to anon, authenticated; alter table tickets enable row level security; create policy read_all on tickets for select using (true); ``` Where to connect `psql`: your Postgres URL in postgres mode. In chronos mode `postgres://app:@127.0.0.1:54329/main?sslmode=require`, where `` is `engine_token` in the data folder's `secrets.json` (`jq -r .engine_token data/secrets.json`; keep it secret). Read it over REST: ```bash export URL=http://127.0.0.1:8000 ANON= SERVICE= curl "$URL/rest/v1/tickets?select=id,title&status=eq.open" -H "apikey: $ANON" ``` supabase-js works too: `createClient(URL, ANON).from('tickets').select()`. ## 5. Run an agent An agent is a name, a merge policy and a token. Make one with the service key: ```bash curl -X POST $URL/agents/v1/agents -H "apikey: $SERVICE" -H "authorization: Bearer $SERVICE" \ -H "content-type: application/json" -d '{"name": "cleanup", "policy": "careful"}' # {"id": "...", "name": "cleanup", "policy": "careful", "token": "fba_..."} ``` Give it a policy: make `policies/careful.toml` beside `forkbase.toml`, then restart Forkbase. ```toml max_rows = 50 # more rows than this: a person reviews it max_deletes = 0 # any delete: a person reviews it ``` Now the agent starts a run, works in its world, and proposes: ```bash AGENT=fba_... curl -X POST $URL/agents/v1/runs -H "authorization: Bearer $AGENT" \ -H "content-type: application/json" -d '{"intent": "delete closed tickets"}' # {"id": "run_...", "token": "fbr_...", "database_url": "postgres://...", ...} RUN=run_... RUNTOKEN=fbr_... curl -X POST $URL/agents/v1/runs/$RUN/sql -H "authorization: Bearer $RUNTOKEN" \ -H "content-type: application/json" -d '{"sql": "delete from tickets where status = $1", "params": ["closed"]}' curl $URL/agents/v1/runs/$RUN/changes -H "authorization: Bearer $RUNTOKEN" # 2 rows deleted, in the world only curl -X POST $URL/agents/v1/runs/$RUN/propose -H "authorization: Bearer $RUNTOKEN" # 202 {"status": "held", "reasons": [...]} the policy allows 0 deletes ``` Your `tickets` table still has all three rows. Open **Dashboard, Agents, Approvals**: the run is there with the two rows it would delete. Approve it and they go; reject it and nothing happened. If you approve and change your mind, **Undo** puts the rows back. The same in TypeScript: ```ts import { createClient } from "@chronosdb/forkbase"; const fb = createClient("http://127.0.0.1:8000", process.env.FORKBASE_AGENT_TOKEN!); const { outcome } = await fb.agents.withRun("delete closed tickets", (run) => run.sql("delete from tickets where status = $1", ["closed"]), ); console.log(outcome.status); // "held" ``` ## Next - [Concepts](https://forkbase.tech/docs/concepts): the model behind runs, policies and undo. - [Agents](https://forkbase.tech/docs/agents): every policy rule, approvals by Slack and email, webhooks. - [MCP](https://forkbase.tech/docs/mcp): connect Claude or Cursor to the same database, as one agent. - [Self-hosting](https://forkbase.tech/docs/self-hosting): put it on a server. --- # Concepts > Runs, worlds, merge policies, held runs, undo, keys and tokens, and the two database modes. Source: https://forkbase.tech/docs/concepts ## The idea in one paragraph Agents are fast and sometimes wrong. A normal backend lets an agent's bad write land in production at once. Forkbase puts a **fork** between each agent and your data: the agent works in a private copy, Forkbase checks what it changed against a **merge policy**, and only then does the change reach the real data. A change the policy doesn't allow waits for a **person**. A change that merged can still be **undone**, row by row. Your app's own code (your servers, your users' browsers) keeps writing straight to the data, as with any Postgres. Only agents go through forks. ## Runs and worlds A **run** is one task an agent does: "close stale tickets", "backfill country codes". Starting a run makes a **world**: a copy-on-write branch of the data kept by the Chronos engine. It costs nothing to make, because it shares every row with the data until the run changes one. Inside its world a run reads the data as it was when the run started, plus its own changes, and writes freely. Nobody else sees those writes. A run has: - an `id` (`run_...`) and an `intent` (a sentence a reviewer reads), - a token (`fbr_...`) that acts on this run only, - a `database_url`: a plain Postgres connection to its world, for `psql`, any driver or an ORM, - a time to live (`agents.run_ttl_s`, one hour by default). An open run that outlives it is discarded. A run ends one of these ways: | Status | Meaning | |---|---| | `open` | working | | `merging` | a merge is being applied | | `merged` | its changes are in the data | | `held` | the policy wants a person; waits up to `agents.hold_ttl_s` (seven days) | | `rejected` | a person said no; nothing changed | | `discarded` | the agent (or its code) threw it away | | `expired` | its time ran out before it merged | | `undone` | it merged, then a person undid it | ## Propose: merged, held or conflict When the agent is done it **proposes**. Forkbase hands the world's changes to the engine with the agent's merge policy, and gets one of three answers: - **merged** (HTTP 200): within policy. The changes are in the data now. - **held** (HTTP 202): the policy wants a person. The response has `reasons` ("deletes 3 rows, policy allows 0"). Nothing reached the data. A held run is a normal outcome, not an error. - **conflict** (HTTP 409): someone changed the same rows after the run started. Start a new run on fresh data. ## Merge policies A policy is a named set of rules, written as a file: `policies/.toml` beside `forkbase.toml`. ```toml # policies/careful.toml max_rows = 50 # changes to more rows than this are held max_deletes = 0 # any delete is held review_tables = ["payments", "refunds"] max_age = "1h" # a run older than this is held ``` Each key is one of the engine's merge-policy rules. Forkbase applies the files every time it starts, and a file is the whole policy: a rule you remove from the file is removed from the policy. Every agent names a policy; an agent that names none uses `agents.default_policy` (`forkbase_default`, which holds every delete unless you write a file for it). See [Agents](https://forkbase.tech/docs/agents#policy-rules) for every rule. ## Review A held run shows up in the dashboard's **Approvals** inbox with the rows it changes, its SQL and its counts. Forkbase can also announce it to Slack and by email, each with a signed link to an approve-or-reject page. Approving merges exactly what was held, nothing that came after. Only a person decides: no agent token, run token or MCP client can approve, reject or undo. ## Undo Any merged run can be undone: Forkbase writes back the rows as they were before the merge. If someone has changed one of those rows since, the undo stops and tells you, unless you ask it to skip rows changed since (`skip_changed`). In chronos mode undo reaches back `agents.undo_window` (seven days by default). ## Keys and tokens Every credential has a prefix so you can tell them apart in a log. | Credential | Prefix | Who holds it | What it can do | |---|---|---|---| | anon key | (a JWT) | browsers, phone apps | what RLS allows the `anon` and `authenticated` roles | | service_role key | (a JWT) | your servers only | everything; bypasses RLS; manages agents, approves runs | | user access token | (a JWT) | a signed-in person's app | acts as that person under RLS; lives `auth.access_ttl_s` | | user refresh token | | the same app | gets a new access token; rotates on every use | | agent token | `fba_` | an agent's process | starts runs and reads its own runs | | run token | `fbr_` | one run | SQL, changes, propose and discard on that run only | | job token | `fbj_` | one running job | its own steps and sleeps (`/jobs/v1/self`) | | MCP access token | `fbm_` | an MCP client | the tools of the agent it was granted; one hour | | MCP refresh token | `fbmr_` | an MCP client | a new `fbm_`; 30 days, rotated on use | | webhook secret | `whsec_` | your webhook receiver | checks Forkbase's signature on deliveries | ## Database modes Forkbase stores your data in one of two places, set by `database.mode`. **postgres**: your Postgres 16+ is the system of record. Your app connects to it as always. When the first agent run starts, the engine **attaches** to your `public` tables that have a primary key: it keeps a copy-on-write copy, refreshed from Postgres every `agents.refresh_every_s`. Merges are written back to Postgres in one checked transaction. Tables made later are picked up by attaching again, once no run is open. **chronos**: the bundled Chronos engine is the database. Apps connect to `postgres://app:@127.0.0.1:54329/main?sslmode=require` with any Postgres driver (`engine_token` is in `secrets.json`). Worlds are native. Forkbase switches off the engine's `protect_main`, so apps write `main` as they would any Postgres; agents still go through worlds. Agents see Forkbase's own tables (`auth`, `storage`, `agents`, `jobs`, `mcp`) masked, and every policy holds changes to them for a person. Differences to know: | | postgres | chronos | |---|---|---| | Table triggers and realtime see rows an agent merged | yes | no (the engine applies merges without running triggers; use a `run.merged` event trigger) | | Undo window | until a re-attach | `agents.undo_window` | | Tables agents can touch | `public` tables with a primary key | all | | Agents without the engine installed | off; the rest works | the engine is required | ## What Forkbase is made of One `forkbase` process serves every API on one port: | Prefix | Part | |---|---| | `/auth/v1` | sign-in for your app's people | | `/rest/v1` | your tables over HTTP | | `/realtime/v1` | changes and broadcast over WebSocket | | `/storage/v1` | files in buckets | | `/agents/v1` | agents, runs, approvals, webhooks | | `/jobs/v1` | functions, jobs, schedules, triggers | | `/mcp`, `/oauth` | the MCP server and its OAuth 2.1 | | `/dashboard` | the studio | | `/platform/v1` | what the dashboard calls | The Chronos engine runs as a separate program that Forkbase starts and watches; Forkbase talks to it over HTTP and the Postgres protocol. Forkbase's own state lives in your database, in schemas of its own (`forkbase`, `auth`, `storage`, `agents`, `jobs`, `mcp`). Several Forkbase servers can share one database: schedules fire once, jobs are leased, and realtime travels by `LISTEN`/`NOTIFY`. --- # Set up with an AI agent > One prompt for Claude Code, Codex or Cursor that installs Forkbase or connects your app, one question at a time. Source: https://forkbase.tech/docs/agent-setup Let your coding agent (Claude Code, Codex, Cursor, Windsurf, any agent that can read a URL and run commands) set Forkbase up with you. Paste one line; it asks you a question at a time and does the work. ## New to Forkbase Paste into your agent, in the folder of your app (or an empty folder for a new one): ```text Read https://chronos.2090.tech/forkbase/setup.md and set up Forkbase for me. ``` It asks, one at a time: 1. **Where should Forkbase run?** This machine, a server you have (over SSH), or one already running. 2. **Which database?** The bundled Chronos engine, or your own Postgres. 3. **New app or this app?** It reads your folder first. If the app already uses Supabase, Forkbase drops in. 4. **What are you building, and with what?** (new apps) One sentence, and a stack. 5. **Which parts?** Sign-in, storage, live updates, AI agents, background jobs. 6. **What will the agent change, and what needs a person?** (if you picked agents) It writes the merge policy from your answer. Then it installs, starts Forkbase, writes the keys to your env file (never into the chat), wires the clients in, makes your tables with row-level security, sets up the agent and its policy, and proves each part works. ## Already running Forkbase The dashboard's overview has **Connect with an AI agent**: a prompt with your server's address in it. ```text Read https://api.myapp.com/skill/setup.md and connect this project to my Forkbase at https://api.myapp.com. ``` The agent skips the install and goes straight to your app. It asks you to put the keys in your env file yourself (from Settings in the dashboard), so they never pass through the chat. ## What the agent follows The prompt points at the setup skill, [`skills/forkbase-setup/SKILL.md`](https://github.com/2090-labs/forkbase/blob/main/skills/forkbase-setup/SKILL.md). Every Forkbase server serves it at `/skill/setup.md`. It tells the agent to: - ask one question per message, with a recommended answer first, - look at your folder before asking what it can see for itself, - say what it will install or run before it does, and wait for a yes, - keep keys and passwords out of the chat, and the service key out of browser code, - never approve held runs or loosen a policy for you. ## After setup To let the same agent work *in* your data (not just in your code), connect it over [MCP](https://forkbase.tech/docs/mcp). The setup asks whether you want that at the end. --- # Example: a claims desk > An insurance claims app with two agents and two policies: small claims merge on their own, large ones wait for a person. Source: https://forkbase.tech/docs/example-claims An insurance claims app on Forkbase, where AI agents decide claims and a merge policy decides what reaches the data. - A customer files a claim. The app hands it to an agent job. - Claims under $1,000 go to `settle-small`, run by the agent `claims_bot` under policy [`small_claims`](https://github.com/2090-labs/forkbase/blob/main/examples/claims/policies/small_claims.toml): one claim per run, only the claims table. Its decisions land on their own. - Larger claims go to `review-large`, run by `claims_senior` under [`large_claims`](https://github.com/2090-labs/forkbase/blob/main/examples/claims/policies/large_claims.toml): every decision is **held** until an adjuster approves or rejects it on the desk. - Both run the same [function](https://github.com/2090-labs/forkbase/blob/main/examples/claims/functions/triage.mjs) in their own fork of the data: plain rules decide (covered causes, exclusions, a $250 deductible). With `ANTHROPIC_API_KEY` set, Claude writes the note the customer reads. - Every run's **ledger** is a click away: the SQL the agent ran, its proposal, the hold, who approved it. ## Run it ```bash docker compose up ``` Then open and file a claim. Forkbase's dashboard is at (its service key: `docker compose exec forkbase forkbase keys`). ```bash ANTHROPIC_API_KEY=sk-ant-... docker compose up # Claude writes each decision's note FORKBASE_IMAGE=forkbase:dev docker compose up # an image you built yourself ``` Without a published image to pull, Compose builds one from this checkout (`deploy/Dockerfile`). ## Check it With the desk running: ```bash node test.mjs ``` It files a $400 burst-pipe claim (approved and merged on its own), an $8,200 kitchen fire (held, approved by the test, then merged), and a mold claim (denied), and reads a run's ledger. ## Without Docker With a Forkbase server running (`forkbase start`, Node 22 on the machine for jobs): ```bash export FORKBASE_SERVICE_KEY=$(forkbase keys | node -pe 'JSON.parse(require("fs").readFileSync(0)).service_role') FORKBASE_URL=http://127.0.0.1:8000 node app/server.mjs ``` On a server in postgres mode, agents' worlds start from the engine's copy of your tables, refreshed every `agents.refresh_every_s` (60 s). Set `CLAIMS_DELAY_S` to at least that, so a job starts once its claim is in the copy. ## What's where | File | | |---|---| | [app/server.mjs](https://github.com/2090-labs/forkbase/blob/main/examples/claims/app/server.mjs) | the desk: sets Forkbase up, files claims, routes them to a job, approves and rejects | | [functions/triage.mjs](https://github.com/2090-labs/forkbase/blob/main/examples/claims/functions/triage.mjs) | the agents' function, deployed twice | | [policies/](https://github.com/2090-labs/forkbase/tree/main/examples/claims/policies) | the two merge policies | | [compose.yml](https://github.com/2090-labs/forkbase/blob/main/examples/claims/compose.yml) | Forkbase (Chronos engine inside) and the desk | | [test.mjs](https://github.com/2090-labs/forkbase/blob/main/examples/claims/test.mjs) | the end-to-end check | --- # Auth > Sign-up, passwords, emailed links and codes, Google and GitHub, sessions, row-level security and the admin API. Source: https://forkbase.tech/docs/auth `/auth/v1` signs in your app's people: email and password, emailed sign-in links and six-digit codes, Google and GitHub. It speaks the API supabase-js uses, so `supabase.auth.signUp`, `signInWithPassword`, `signInWithOtp`, `signInWithOAuth`, `getUser` and `signOut` work against Forkbase. ## Keys and tokens Every request carries an API key in the `apikey` header: - `anon` from browsers and phone apps, - `service_role` from your servers only. A signed-in person's app also sends `Authorization: Bearer `. Access tokens are JWTs signed with EdDSA. Check them offline against `GET /auth/v1/.well-known/jwks.json`. They live `auth.access_ttl_s` (an hour). Refresh tokens rotate on every use. A spent refresh token presented again ends its whole session: someone copied it. The claims your SQL sees: `sub` (the user's id), `role` (`authenticated`), `email`, `aal`, `session_id`, `app_metadata`, `user_metadata`. In SQL, `auth.uid()` (text), `auth.role()` and `auth.jwt()` read them. ## Routes | Route | Body | | |---|---|---| | `GET /settings` | | which sign-ins are on: `passwords`, `magic_links`, `signups`, `providers` | | `POST /signup` | `{email, password, name?, data?, redirect_to?}` | makes the user, signs them in, emails a verification link | | `POST /token?grant_type=password` | `{email, password}` | sign in | | `POST /token?grant_type=refresh_token` | `{refresh_token}` | a new access token | | `POST /otp` | `{email, code_challenge, redirect_to?}` | emails a sign-in link and a six-digit code | | `POST /token?grant_type=email_code` | `{email, code}` | sign in with the code | | `POST /token?grant_type=pkce` | `{auth_code, code_verifier}` | redeem the `?code=` a link or social sign-in returned | | `GET /authorize?provider=google\|github&code_challenge=&redirect_to=` | | start social sign-in | | `POST /recover` | `{email, redirect_to?}` | emails a reset link (`?type=recovery&token=`) | | `POST /reset` | `{token, password}` | set the new password | | `POST /resend` | `{email}` | another verification email | | `GET /user` | | the signed-in person | | `PUT /user` | `{password?, name?, data?}` | change own password, name, `data` | | `POST /logout?scope=local\|global\|others` | | this session, all sessions, or the others | Sign-in answers `{access_token, token_type, expires_in, expires_at, refresh_token, user}`. ### Links never carry tokens Emailed links and social sign-ins send the person back to your page (`auth.site_url`, or an allowed `redirect_to`) with a one-time `?code=`. Only the PKCE `code_verifier` your page kept can redeem it (`grant_type=pkce`). supabase-js does this for you with `flowType: 'pkce'`. `redirect_to` must be `auth.site_url` or start with one of `auth.redirect_urls`. ### Limits - Failed sign-ins: 10 per 15 minutes per address, and per IP when a proxy sets `X-Forwarded-For`. - Emails: 5 of a kind per address per hour. ## Admin (service key) | Route | | |---|---| | `GET /admin/users`, `POST /admin/users` | list (`?page=&per_page=&q=`, newest first), make a user (`email`, `password`, `name`, `email_confirm`, `app_metadata`, `user_metadata`) | | `GET`, `PUT`, `DELETE /admin/users/{id}` | one user: read, change (`email`, `password`, `name`, `email_confirm`, `disabled`, metadata), delete | | `GET /admin/users/{id}/sessions`, `POST /admin/users/{id}/logout` | their sessions; sign them out everywhere | | `POST /admin/invite` | `{email, redirect_to?}`: emails an invitation | | `GET /admin/events` | the sign-in audit log | | `GET /admin/keys`, `POST /admin/keys/rotate`, `POST /admin/keys/{kid}/retire` | the signing keys: list, add a new one, retire an old one | Rotate signing keys without signing anyone out: `rotate` adds a key that signs from now on while the old one still verifies; `retire` the old one once its tokens have expired. ## Settings All in `[auth]` in `forkbase.toml` (see [Configuration](https://forkbase.tech/docs/configuration#auth)): ```toml [auth] external_url = "https://api.myapp.com" # where this server is reached; tokens name it, links point at it site_url = "https://myapp.com" # your app: where people come back to redirect_urls = ["https://myapp.com/auth", "http://localhost:3000/auth"] # http:// or https:// only origins = ["https://admin.myapp.com"] # extra browser origins (site_url's is always allowed) signups = true passwords = true magic_links = true require_verified = false # true: a password sign-in waits for a verified address access_ttl_s = 3600 ``` ### Email `auth.email.mode`: | Mode | | |---|---| | `log` (default) | emails, links included, are written to the server's log. Development only. | | `smtp` | sent through `smtp_host`, `smtp_port` (587), `smtp_user`, `smtp_password`, `smtp_tls` (`starttls`, `tls` or `none`) | | `file` | appended as JSON lines to `auth.email.file` (tests, or piping to another sender) | | `off` | anything that needs an email is refused | Set `from` to `"My App "`. Put the password in `FORKBASE_SMTP_PASSWORD`, not the file. ### Google and GitHub ```toml [auth.google] client_id = "....apps.googleusercontent.com" # secret: FORKBASE_GOOGLE_CLIENT_SECRET [auth.github] client_id = "Iv1...." # secret: FORKBASE_GITHUB_CLIENT_SECRET ``` Register the callback `https:///auth/v1/callback/google` (or `/github`) with the provider. A provider is on when it has both a client id and a secret. ## Row-level security Requests to `/rest/v1`, `/storage/v1` and `/realtime/v1` run as a database role: | Caller | Role | |---|---| | the anon key alone | `anon` | | a signed-in person | `authenticated` | | the service key | `service_role` (bypasses RLS) | Forkbase makes these roles when it starts. Write policies as in Supabase: ```sql create table notes (id text primary key, owner text not null default auth.uid(), body text); grant select, insert, update, delete on notes to authenticated; alter table notes enable row level security; create policy own on notes for all to authenticated using (owner = auth.uid()) with check (owner = auth.uid()); ``` People live in `auth.users`. Don't write that table by hand; use the routes above. --- # Database and REST > /rest/v1: PostgREST-style reads and writes under row-level security, with filters, embedding and upserts. Source: https://forkbase.tech/docs/rest Your data is Postgres. Connect with any Postgres driver, ORM or `psql`: - postgres mode: your own database URL; - chronos mode: `postgres://app:@127.0.0.1:54329/main?sslmode=require` (`chronos.pg_listen`). The password is `engine_token` from the data folder's `secrets.json`; any login name works except `forkbase`, the engine's own. On top of it, `/rest/v1/` serves the tables and views of `rest.schemas` over HTTP, the way PostgREST does. So supabase-js works as is: ```ts import { createClient } from "@supabase/supabase-js"; const supabase = createClient("http://127.0.0.1:8000", ANON_KEY); const { data } = await supabase.from("notes").select("id, body, tags(name)").gt("n", 1).order("n", { ascending: false }); ``` ## Reads ```http GET /rest/v1/notes?select=id,body,tags(name)&n=gt.1&order=n.desc&limit=20&offset=40 apikey: Authorization: Bearer (when someone is signed in) ``` - `select`: columns, `*`, renames (`title:body`), and one level of embedding along single-column foreign keys either way: `tags(name)`, `note:notes(body)`, `rel!column(...)` when two keys join the same tables. - `order=col.asc|desc[.nullsfirst|.nullslast]`, several separated by commas. - `limit`, `offset`. A read returns at most `rest.max_rows` (1000). - `Prefer: count=exact` adds the total to `Content-Range`. - `Accept: application/vnd.pgrst.object+json` asks for exactly one row (406 otherwise). ## Filters `column=operator.value`: | Operator | SQL | |---|---| | `eq`, `neq` | `=`, `<>` | | `gt`, `gte`, `lt`, `lte` | `>`, `>=`, `<`, `<=` | | `like`, `ilike` | `LIKE`, `ILIKE` (`*` is `%`) | | `is` | `IS NULL`, `IS TRUE`, `IS FALSE` | | `in` | `IN (...)`: `id=in.(1,2,3)` | | `cs`, `cd` | contains, contained by (arrays, JSON) | `not.` before any operator negates it (`status=not.eq.closed`). Combine with `or=(a.eq.1,and(b.gt.2,c.is.null))`. ## Writes | | | |---|---| | `POST /rest/v1/notes` | insert one object or an array | | `POST` with `Prefer: resolution=merge-duplicates` | upsert; `on_conflict=cols` (default: the primary key) | | `PATCH /rest/v1/notes?id=eq.5` | update the rows the filters match | | `DELETE /rest/v1/notes?id=eq.5` | delete them | `PATCH` and `DELETE` need at least one filter, and refuse `limit` and `offset`: a mistake never touches every row. `Prefer: return=representation` returns the written rows. Other schemas in `rest.schemas`: `Accept-Profile: ` for reads, `Content-Profile: ` for writes. ## Schema `GET /rest/v1/` lists the served tables, their columns and keys. A table you make or change is served at once. ## Who sees what Every request runs as a role (`anon`, `authenticated` or `service_role`) with the caller's token claims in `request.jwt.claims`. A new table is closed to `anon` and `authenticated` until you `grant` it, and row-level security decides which rows. See [Auth, row-level security](https://forkbase.tech/docs/auth#row-level-security). Forkbase's own schemas (`auth`, `storage`, `forkbase`, `agents`, `jobs`, `mcp`) are never served. ## Errors ```json {"code": "42501", "message": "permission denied for table notes", "details": null, "hint": null} ``` Postgres errors keep their SQLSTATE `code`. Request mistakes use PostgREST's `PGRST...` codes. --- # Realtime > Table changes and broadcast over WebSocket, in the shape supabase-js expects. Source: https://forkbase.tech/docs/realtime `/realtime/v1/websocket?apikey=&vsn=1.0.0` speaks the protocol supabase-js uses. Two things travel over it: **table changes** and **broadcast** messages. ```ts const channel = supabase .channel("notes") .on("postgres_changes", { event: "*", schema: "public", table: "notes", filter: "owner=eq.42" }, (p) => console.log(p)) .subscribe(); ``` ## Which tables send changes None, until you say. Either list them in `forkbase.toml`: ```toml [realtime] tables = ["public.notes", "messages"] # schema.table, or a table in the first REST schema ``` or add them while running, with the service key: ```bash curl -X POST $URL/realtime/v1/tables -H "authorization: Bearer $SERVICE" -d '{"table": "public.notes"}' curl $URL/realtime/v1/tables -H "authorization: Bearer $SERVICE" curl -X DELETE $URL/realtime/v1/tables/public.notes -H "authorization: Bearer $SERVICE" ``` Filters on a subscription: `col=eq.value`, with `eq neq lt lte gt gte in`. ## Who sees what - The service key gets every change as written. - Everyone else gets an insert or update only if they may `select` that row, checked by primary key under their own role and policies at that moment, with only the columns they may select. A delete arrives as the row's primary key alone. - A table without a primary key sends changes to the service key only. - When a person's token expires, their channel stops getting changes. Send a fresh token (`access_token`) and join again. supabase-js does this on refresh. ## Broadcast Messages between the sockets joined to one topic, with `self` (receive your own) and `ack` (confirm delivery) as in supabase-js: ```ts const room = supabase.channel("room-1", { config: { broadcast: { self: true } } }); room.on("broadcast", { event: "cursor" }, ({ payload }) => draw(payload)).subscribe(); room.send({ type: "broadcast", event: "cursor", payload: { x: 10, y: 20 } }); ``` ## Limits - Changes travel by Postgres `LISTEN`/`NOTIFY`, so every Forkbase server on the same database sends them. - A row over about 8 KB arrives without its values (`too_big`); read it over REST. - Changes made while Forkbase reconnects to the database are not sent. Read the table again when a channel reconnects. - In chronos mode, rows an agent's merge wrote are not sent (the engine merges without running triggers). - Not yet: presence, private channels. --- # Storage > Buckets and files, on disk or S3, signed URLs, and policies on storage.objects. Source: https://forkbase.tech/docs/storage `/storage/v1` keeps files in buckets, the way Supabase Storage does: ```ts await supabase.storage.from("avatars").upload(`${user.id}/me.png`, file, { upsert: true }); const { data } = supabase.storage.from("avatars").getPublicUrl(`${user.id}/me.png`); ``` Each file is a row in `storage.objects`. Its bytes live in a backend: ```toml [storage] backend = "local" # a folder: storage.path, default /storage file_size_limit = 52428800 # bytes; a bucket may set less # or S3, and anything that speaks it (MinIO, Cloudflare R2, ...) backend = "s3" s3_bucket = "myapp-files" s3_region = "eu-west-1" # default: AWS_REGION, then us-east-1 s3_endpoint = "https://.r2.cloudflarestorage.com" # S3-compatible services only # keys: FORKBASE_S3_ACCESS_KEY_ID / FORKBASE_S3_SECRET_ACCESS_KEY, else AWS_* or the machine's role ``` ## Who may do what Row-level security on `storage.objects` (and `storage.buckets`) decides. Every request reads and writes those rows as the caller. With no policy, only the service key reaches them. Policies can use `auth.uid()`, the row's `owner` (who uploaded it), and the helpers `storage.foldername(name)`, `storage.filename(name)` and `storage.extension(name)`: ```sql -- each person reads and writes only their own folder in "docs" create policy own_folder on storage.objects for all to authenticated using (bucket_id = 'docs' and (storage.foldername(name))[1] = auth.uid()) with check (bucket_id = 'docs' and (storage.foldername(name))[1] = auth.uid()); ``` ## Buckets | Route | | |---|---| | `GET /bucket`, `POST /bucket` | list; make one: `{id, name?, public?, file_size_limit?, allowed_mime_types?}` | | `GET`, `PUT`, `DELETE /bucket/{id}` | read, change, delete (an empty bucket) | | `POST /bucket/{id}/empty` | delete every file in it | - `public: true`: anyone reads its files at `/object/public/{bucket}/{path}`, no key. - `file_size_limit`: bytes, or `"5MB"`. - `allowed_mime_types`: `["image/*", "application/pdf"]`. ## Files | Route | | |---|---| | `POST /object/{bucket}/{path}` | upload: a raw body with its `content-type`, or a form as supabase-js sends a Blob. `x-upsert: true` replaces a file already there | | `PUT /object/{bucket}/{path}` | replace only | | `GET /object/{bucket}/{path}` | download (`?download` to save it); `etag` and `If-None-Match` | | `GET /object/public/{bucket}/{path}` | download from a public bucket, no key | | `GET /object/info/{bucket}/{path}` | its size, type, owner, times | | `POST /object/list/{bucket}` | `{prefix, search, limit, offset, sortBy}`; folders come back with `id: null` | | `POST /object/move`, `POST /object/copy` | `{bucketId, sourceKey, destinationKey, destinationBucket?}` | | `DELETE /object/{bucket}/{path}` | delete one | | `DELETE /object/{bucket}` | `{"prefixes": ["a.png", "b/c.png"]}`: delete several | ## Signed URLs - `POST /object/sign/{bucket}/{path}` `{"expiresIn": 60}` (or `POST /object/sign/{bucket}` with `paths`), by someone who may read the file: a URL anyone can read it at until then. - `POST /object/upload/sign/{bucket}/{path}`, by someone who may upload there: a URL anyone can `PUT` that one file to for two hours. The file belongs to whoever made the URL. ## Guarantees and limits - Every upload is a new version of the bytes, so a reader never gets half of one. Replaced or deleted bytes are removed once no row points at them. - Not yet: image transforms, resumable (TUS) uploads, byte ranges. --- # Agents > Runs, merge policies as code, approvals, webhooks and events, and undo of any merge. Source: https://forkbase.tech/docs/agents `/agents/v1` lets AI agents change real data safely. Read [Concepts](https://forkbase.tech/docs/concepts) first for runs, worlds and policies. Agents need the Chronos engine. In postgres mode without it, Forkbase starts with agents off (the log says `agents are off`), `/agents/v1` is not served, and the rest works. ## Who may call what | Caller | Header | Can | |---|---|---| | service key | `Authorization: Bearer ` | everything: make agents, see every run, approve, reject, undo, webhooks | | agent token `fba_` | `Authorization: Bearer fba_...` | start runs as that agent, list and read its own runs | | run token `fbr_` | `Authorization: Bearer fbr_...` | `sql`, `changes`, `propose`, `discard` on that one run | | approval link | the signed link in a Slack message or email | approve or reject that one held run | Only the service key and approval links approve, reject and undo. An agent can never approve its own work. ## Agents ```bash # make one; the token is shown once curl -X POST $URL/agents/v1/agents -H "authorization: Bearer $SERVICE" -H "content-type: application/json" \ -d '{"name": "support_bot", "policy": "careful"}' # 201 {"id": "...", "name": "support_bot", "policy": "careful", "token": "fba_..."} curl $URL/agents/v1/agents -H "authorization: Bearer $SERVICE" # {"agents": [...]} curl -X DELETE $URL/agents/v1/agents/support_bot -H "authorization: Bearer $SERVICE" # disables it ``` `name`: letters, digits and `_`, up to 63. `policy`: a policy's name; none means `agents.default_policy`. A disabled agent's token stops working. ## Runs ### Start: `POST /runs` | Field | | |---|---| | `intent` | what the run will do, in a sentence. Reviewers read it. | | `ttl_seconds` | how long the world lives (at most `agents.run_ttl_s`) | | `meta` | any JSON you want kept with the run | | `agent` | with the service key: whose run it is | | `policy` | with the service key: a policy for this run instead of the agent's | | `act_as` | `{"user_token": ""}`: row-level security judges the run's reads and writes as that person's | Answers 201 with the run: `id`, `status`, `agent`, `intent`, `world`, `token` (`fbr_`, shown once) and `database_url`. `database_url` is a plain Postgres URL to the run's world. Anything that speaks Postgres works there: ```bash psql "$DATABASE_URL" -c "update tickets set status = 'closed' where updated_at < now() - interval '90 days'" ``` ### Work: `POST /runs/{id}/sql` ```json {"sql": "update carts set closed = true where id = $1", "params": [42]} ``` One statement per call, `$1`-style parameters. Answers `{"columns": [...], "rows": [[...]], ...}`. Reads see the data as of the fork plus the run's own writes. ### Check: `GET /runs/{id}/changes` | `view` | Answer | |---|---| | `rows` (default) | `changes`: the inserted, updated and deleted rows, per table (`limit` rows per table, default 200, at most 1000) | | `summary` | `total`, `tables`, `summary`: counts only | | `sql` | `sql`: the statements that would replay the change | Always read the changes before proposing: it's what a person will review. ### Propose: `POST /runs/{id}/propose` | HTTP | Body | Meaning | |---|---|---| | 200 | `{"status": "merged", ...}` | in the data now | | 202 | `{"status": "held", "reasons": [...]}` | a person decides; nothing changed yet | | 409 | `{"code": "conflict", "message": ..., "conflicts": [...]}` | rows changed under the run; start a new run. `code` is `stale_reads` when the policy has `check_reads` and rows the run read changed | ### The rest | Route | Who | | |---|---|---| | `GET /runs?status=&limit=` | service, agent | runs, newest first; an agent sees its own | | `GET /runs/{id}` | service, agent, run | one run, with its `outcome` | | `POST /runs/{id}/discard` | service, agent, run | throw the world away | | `POST /runs/{id}/approve` | service | merge a held run, exactly what was held | | `POST /runs/{id}/reject` | service | `{"reason": "..."}`; nothing merges | | `POST /runs/{id}/undo` | service | put back what a merged run changed; `{"skip_changed": true}` leaves rows changed since | Undo refuses (409) a run that isn't `merged`, and in postgres mode a run that merged before the engine was attached again (`reattached`). ## Policies as code Write one file per policy in `agents.policies` (default `policies/` beside `forkbase.toml`). The file name is the policy name. Forkbase applies every file when it starts: new files make policies, changed files change them, and a rule removed from a file is removed from the policy. Policies the engine has that no file names are left alone. The dashboard's **Agents, Policies** page edits the same files: saving writes `.toml` and applies it at once (a file the engine refuses is put back as it was), and **Try** checks an open or held run's world against the text in the editor without merging anything. From a server: `PUT /agents/v1/policies/ {"toml": "..."}`, `POST /agents/v1/policies/check {"run": "", "toml": "..."}` (or `"name"` for a policy as it is), and `DELETE /agents/v1/policies/` (not the default policy, nor one an agent keeps to). ```toml # policies/support.toml: a support bot fixing tickets tables = ["tickets", "ticket_notes"] # it may change nothing else max_rows = 20 max_deletes = 0 review_columns = ["tickets.assignee"] ``` ```toml # policies/money.toml: an agent near payments max_deletes = 0 review_tables = ["payments", "refunds", "payouts"] check_reads = true max_age = "30m" ``` ### Policy rules A merge that breaks any rule is **held** for a person. A rule left out doesn't limit. | Rule | Value | Holds a merge when | |---|---|---| | `max_rows` | number | it changes more rows than this | | `max_deletes` | number | it deletes more rows than this | | `rows_per_hour` | number | the agent's merges changed more rows than this in the last hour, this one included | | `deletes_per_hour` | number | the same, for deletes | | `confirm_deletes_over` | number | it deletes more than this; the approver must confirm the count | | `max_age` | `"1h"`, `"30 minutes"` | the run was forked longer ago than this | | `tables` | list of tables | it changes a table not in the list | | `review_tables` | list of tables | it changes any table in the list | | `review_columns` | list of `table.column` | it changes any of these columns, even in one row | | `schema` | `true`/`false` (default false) | `false` and it changes a table's shape, a view, function, sequence, schema or type | | `overwrite` | `true`/`false` (default false) | `false` and it overwrites rows changed in the data since the fork | | `critical` | `true`/`false` (default false) | `false` and it changes a column marked critical in the engine | | `check_reads` | `true`/`false` (default false) | `true` and rows it read changed since the fork (it decided on state that's gone) | | `max_effects` | number | it queues more side effects than this | | `effects_per_hour` | number | the agent's merges queued more effects than this in the last hour | | `review_channels` | list of channels | it queues an effect on one of these channels | The default policy, `agents.default_policy` (`forkbase_default`), is made with `max_deletes = 0` unless a file of that name says otherwise. `GET /agents/v1/policies` (service key) lists every policy with its rules. In chronos mode every policy also lists Forkbase's own tables in `review_tables`, and Forkbase never approves those holds: agents cannot change sign-ins, files or other agents behind your back. ## Approvals A held run reaches people three ways: 1. **The dashboard**: Agents, Approvals. Each held run with its intent, reasons, rows, SQL and counts. 2. **Slack**: set `agents.slack_webhook_url` (or `FORKBASE_SLACK_WEBHOOK_URL`) to an incoming-webhook URL. 3. **Email**: list addresses in `agents.approver_emails`. Uses the [auth email settings](https://forkbase.tech/docs/auth#email). Slack messages and emails carry a signed link to a page (`/agents/v1/approvals/{token}`) that shows the rows and has Approve and Reject buttons. A link works only for its run, only while the run is held. A held run that nobody decides within `agents.hold_ttl_s` (seven days) is discarded. ## Webhooks and events Everything that happens to a run is an **event**. `GET /agents/v1/events` (service key) lists them. | Event | When | |---|---| | `run.created` | a run started | | `run.merged` | a run's changes reached the data | | `run.held` | a policy held a run | | `run.conflict` | a proposal hit a conflict | | `run.rejected` | a person rejected a held run | | `run.discarded`, `run.expired` | a world was thrown away | | `run.undone` | a merged run was undone | | `effect.` | a side effect a merge queued, delivered after the merge landed | | `job.succeeded`, `job.failed` | a job ended (see [Jobs](https://forkbase.tech/docs/jobs)) | Subscribe a URL: ```bash curl -X POST $URL/agents/v1/webhooks -H "authorization: Bearer $SERVICE" -H "content-type: application/json" \ -d '{"url": "https://example.com/hooks/forkbase", "events": ["run.held", "run.merged"]}' # 201 {"id": "...", "url": "...", "events": [...], "secret": "whsec_..."} ``` `events` takes names, `run.*`, `effect.*` or `*`. `GET /webhooks` lists, `DELETE /webhooks/{id}` removes. Every delivery is a JSON `POST` signed in a `forkbase-signature` header: ``` forkbase-signature: t=1733140000,v1=." with the whsec_ secret> ``` Check it before trusting a delivery: ```ts import { createHmac, timingSafeEqual } from "node:crypto"; function verify(body: string, header: string, secret: string) { const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("="))); if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false; // older than 5 minutes const want = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex"); return timingSafeEqual(Buffer.from(want), Buffer.from(v1)); } ``` A failed delivery (not 2xx) is retried with backoff. ### Side effects that wait for the merge An agent's world can queue a side effect (an email, a payment call) with the engine's `NOTIFY ON MERGE`. It is sent as an `effect.` event only once the merge lands, never for a run that was held and rejected or discarded. `max_effects`, `effects_per_hour` and `review_channels` put effects under policy too. ## Postgres mode details - The engine attaches to your `public` tables that have a primary key, at the first run. - It refreshes its copy from Postgres every `agents.refresh_every_s` (60 s). - A merge is written back to Postgres in one transaction, checked against the rows as they are now. - A table made later is picked up by attaching again, once no run is open. Runs merged before a re-attach can't be undone. - Tables without a primary key are invisible to agents. ## Chronos mode details - Agents read Forkbase's own tables (`auth`, `storage`, `agents`, `jobs`, `mcp`) masked, and every change to them is held for a person, who Forkbase never stands in for. - Merges can be undone for `agents.undo_window` (`"7 days"`). - Table triggers and realtime don't see merged rows: react to `run.merged` events instead. --- # Jobs > TypeScript and Python functions with retries, durable steps, sleeps, schedules and table triggers. Source: https://forkbase.tech/docs/jobs `/jobs/v1` runs your code on the server. Deploy a TypeScript, JavaScript or Python **function**, then start **jobs** of it: by a call, after a delay, on a schedule, when a table changes, or when an event happens. Failed jobs retry. Long jobs keep their progress in **steps** and can **sleep** for days without holding a worker. Every `/jobs/v1` route except `/self` takes the service key. ## A first function ```ts // welcome/index.ts import { step, sleep } from "@chronosdb/forkbase"; export default async function (payload: { email: string }, ctx) { await step("welcome", () => sendEmail(payload.email, "Welcome!")); // runs once, even if a later step fails await sleep("a-day", 86_400); // the job leaves its worker until tomorrow await step("tips", () => sendEmail(payload.email, "Three tips")); return { sent: 2 }; } ``` ```bash forkbase deploy ./welcome --env RESEND_KEY=re_xxx --max-attempts 5 forkbase invoke welcome --payload '{"email": "ada@example.com"}' --wait 30 ``` Python works the same way: ```python # nightly.py from forkbase import step, sql def main(payload, ctx): n = step("count", lambda: 42) return {"rows": n} ``` ```bash forkbase deploy ./nightly.py --cron "0 3 * * *" ``` ## How a job runs - **TypeScript and JavaScript** (`.ts .mts .js .mjs .cjs`) run on Node: `node` on `PATH` or `jobs.node_bin`. `.ts` needs Node 22.6 or later (types are stripped, not checked). The entry's default export is called, or its `handler`, with `(payload, ctx)`. - **Python** (`.py`) runs on `python3` on `PATH` or `jobs.python_bin`. The entry's `main` is called, or its `handler`, with `(payload, ctx)` (or fewer arguments if it takes fewer). An `async def` works. - What the function returns (JSON) is the job's `result`. A throw, a non-zero exit or a timeout fails the attempt. - Each attempt is a fresh process in a fresh folder, in its own process group, with a time limit and a memory limit (Node's heap; Python's address space on Linux). Only these variables reach it: the function's own `env`, and: | Variable | | |---|---| | `FORKBASE_URL` | this server | | `FORKBASE_JOB_ID`, `FORKBASE_ATTEMPT`, `FORKBASE_FUNCTION` | which job, which attempt | | `FORKBASE_JOB_TOKEN` | the job's `fbj_` token, for its steps and sleeps | | `DATABASE_URL`, `FORKBASE_RUN_ID`, `FORKBASE_RUN_TOKEN` | agent functions only: the job's world | - The SDK (`step`, `sleep`, `sql`, `context`, `createClient`) is shipped with every job: import it from `@chronosdb/forkbase` (or `forkbase`) in TypeScript, `forkbase` in Python, without installing it. - **Dependencies are not installed.** Deploy sends your text files; `node_modules`, virtualenvs and binaries are left out. Use the standard library and `fetch`, or bundle your function into one file first (`esbuild index.ts --bundle --platform=node --format=esm --outfile=dist/index.mjs`). - **Not a sandbox.** A function runs as Forkbase's own user, like any code you deploy yourself. Don't run code you don't trust. ## Functions `POST /jobs/v1/functions` deploys. Deploying a name again makes a new version; jobs keep the version they started on. | Field | Default | | |---|---|---| | `name` | | letters, digits, `_`, `-` | | `files` | | `{"index.ts": "...", "lib/util.ts": "..."}` | | `source` | | one file's text instead of `files` (with `runtime`: `node` or `python`) | | `entry` | `index.ts` / `main.py` | the file that's run | | `env` | | `{"NAME": "value"}`; sealed at rest; `null` removes one | | `timeout_s` | `jobs.timeout_s` (300) | up to `jobs.max_timeout_s` (3600) | | `memory_mb` | `jobs.memory_mb` (512) | 64 to `jobs.max_memory_mb` (4096) | | `max_attempts` | `jobs.max_attempts` (3) | 1 to 100 | | `concurrency` | 0 (no limit) | most jobs of it at once | | `agent` | | run each job as a run of this agent (below) | | `propose` | true | agent functions: propose the run when the job ends well | | `disabled` | false | stop starting jobs of it | `GET /functions` lists; `GET /functions/{name}` shows one (variable names, never values); `PATCH` changes settings without new files; `DELETE` removes it. `GET /jobs/v1/runtimes` says which runtimes this server found. ## Jobs ```bash curl -X POST "$URL/jobs/v1/functions/welcome/invoke?wait=30" -H "authorization: Bearer $SERVICE" \ -H "content-type: application/json" -d '{"payload": {"email": "ada@example.com"}}' ``` | Field | | |---|---| | `payload` | any JSON | | `delay_s` or `run_at` | start later (`run_at` in Unix ms) | | `idempotency_key` | a second invoke with the same key returns the first job | | `?wait=` | wait up to 60 s for it to end | | Route | | |---|---| | `GET /jobs?function=&status=&before=&limit=` | jobs, newest first | | `GET /jobs/{id}` | one job: status, result, every attempt with the end of its output, its steps | | `POST /jobs/{id}/cancel` | stop it (a running attempt is killed) | | `POST /jobs/{id}/retry` | run a failed or canceled job again | Statuses: `queued` (waiting to start, including a sleeping job), `running`, `succeeded`, `failed`, `canceled`. **Retries:** a failed attempt is tried again after 10 s, 20 s, 40 s and so on (at most an hour apart) until `max_attempts`. **Leases:** a job whose server died goes back in line when its lease runs out, so another server picks it up. Up to `jobs.log_bytes` (64 KiB) of each attempt's output is kept, the end of it. Finished jobs are deleted after `jobs.keep_days` (30). ## Steps and sleep - `step(name, fn)` runs `fn` once and records what it returned. When the job retries, the step returns the recorded value without running `fn` again. A step is found by its name, so give each step in a function its own name. - `sleep(name, seconds)` ends the attempt and starts the job again after the time, steps kept. A sleep does not use up an attempt and holds no worker. Both call `/jobs/v1/self` with the job's own token, so the function never needs the database password. ## Schedules ```bash curl -X POST $URL/jobs/v1/schedules -H "authorization: Bearer $SERVICE" -H "content-type: application/json" \ -d '{"function": "nightly", "cron": "0 3 * * *", "payload": {"full": true}}' ``` `cron` is in UTC: five fields (`*/5 * * * *`), `@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`, or `@every 30m`. Each time starts once, however many servers share the database. `PATCH /schedules/{id}` with `{"enabled": false}` pauses, `POST /schedules/{id}/run` runs it now, `DELETE` removes it. ## Triggers **On a table's changes:** ```json {"function": "on_signup", "table": "public.profiles", "ops": ["insert"]} ``` The job's payload is shaped like Supabase's database webhooks: ```json {"type": "INSERT", "schema": "public", "table": "profiles", "at": 1733140000000, "record": {...}, "old_record": null, "too_big": false} ``` **On an event:** ```json {"function": "page_oncall", "event": "run.held"} ``` `event`: `run.held`, `run.merged`, any [agent event](https://forkbase.tech/docs/agents#webhooks-and-events), `run.*`, `job.failed`, `job.succeeded`, `effect.`, `effect.*` or `*`. The payload is `{"id", "type", "run", "data", "created_at"}`. `PATCH /triggers/{id}` with `{"enabled": false}` pauses one; `DELETE` removes it. Jobs started by events stop three triggers deep, so a trigger can't start jobs forever. In chronos mode a table trigger doesn't see rows an agent's merge wrote (the engine merges without running triggers); use a `run.merged` event trigger for those. ## Agent functions Deploy with `agent` set and every job runs as a run of that agent: - `DATABASE_URL` is the job's own world, and `sql(query, params)` from the SDK runs there. - When the job ends well, the run is proposed, so the agent's merge policy decides. A held run still counts as a succeeded job; a conflict fails the job. - A failed or canceled job discards its world. - A world lives `agents.run_ttl_s`. A job whose world expires while it sleeps, after steps ran in it, fails rather than go on in a new world. ```ts import { sql } from "@chronosdb/forkbase"; export default async function () { await sql("update carts set closed = true where updated_at < now() - interval '30 days'"); } ``` ```bash forkbase deploy ./close-carts.ts --agent cleanup --cron "@daily" ``` ## Servers and workers `[jobs]` in `forkbase.toml`: `enabled` (does this server run jobs), `workers` (how many at once, default 4), `node_bin`, `python_bin`, the limits above, `log_bytes`, `keep_days`. A server without a runtime leaves those jobs to one that has it; a server with `enabled = false` takes functions and jobs over the API but runs none. --- # MCP > Connect Claude, Cursor, Codex or any MCP client to /mcp, signed in with OAuth 2.1. Source: https://forkbase.tech/docs/mcp `POST /mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server. It lets an AI client (Claude Code, Claude Desktop, Cursor, Codex, your own agent) work in your data **as one agent**: every change goes through a run, and that agent's merge policy decides what reaches the data. Transport: Streamable HTTP, stateless, protocol `2025-06-18` and earlier. No server-sent stream (`GET /mcp` answers 405). ## Connect a client ```bash claude mcp add --transport http forkbase https://api.myapp.com/mcp ``` Cursor, `.cursor/mcp.json`: ```json { "mcpServers": { "forkbase": { "url": "https://api.myapp.com/mcp" } } } ``` Codex, `~/.codex/config.toml`: ```toml [mcp_servers.forkbase] url = "https://api.myapp.com/mcp" ``` The first call answers 401. The client finds Forkbase's OAuth server from it, registers itself, and opens a browser at `/oauth/authorize`. You land on the dashboard's consent page (sign in with the service key if you aren't), pick **which agent** the client works as and whether it may run **jobs**, and approve. Clients without OAuth: send an agent's `fba_` token as `Authorization: Bearer fba_...`. The service key is never accepted as an MCP token. ## Tools | Tool | Arguments | | |---|---|---| | `describe_schema` | | tables, columns, types, primary and foreign keys | | `start_run` | `intent`, `ttl_seconds?` | a new run (a private world) | | `run_sql` | `run`, `sql`, `params?` | one statement in the run's world | | `run_changes` | `run`, `limit?` | the rows the run changed (default 200 per table) | | `propose_run` | `run` | `merged`, `held` (with `reasons`) or `conflict` | | `discard_run` | `run` | throw an open run away | | `list_runs` | `status?`, `limit?` | this agent's runs | | `get_run` | `run` | one run: status, intent, policy, outcome | With the `jobs` scope, also: | Tool | Arguments | | |---|---|---| | `list_functions` | | the functions deployed with this agent | | `invoke_function` | `name`, `payload?`, `idempotency_key?`, `wait_s?` | start a job (wait up to 60 s) | | `get_job` | `id` | status, result, attempts, steps | | `list_jobs` | `function`, `status?`, `limit?` | a function's jobs | Nothing over MCP approves, rejects or undoes. A held proposal comes back as `{"status": "held", "reasons": [...]}` for a person to review in the dashboard. ## OAuth 2.1 | Route | | |---|---| | `GET /.well-known/oauth-protected-resource[/mcp]` | where the authorization server is | | `GET /.well-known/oauth-authorization-server` | its metadata | | `POST /oauth/register` | dynamic client registration (open; public clients) | | `GET /oauth/authorize` | starts sign-in; sends you to the consent page | | `POST /oauth/token` | `authorization_code` (PKCE S256 only) and `refresh_token` grants | | `POST /oauth/revoke` | revoke a token | | `GET /oauth/grants`, `DELETE /oauth/grants/{id}` | service key: connected apps, and disconnect one | - Scopes: `agent` (the run tools), `jobs` (the job tools), `offline_access` (a refresh token). - Access tokens (`fbm_`) last an hour. Refresh tokens (`fbmr_`, with `offline_access`) last 30 days and rotate on use. - A reused authorization code, or a refresh token replayed after it was spent, ends the whole grant. - Redirect URIs: `https://`, `http://` on localhost, or an app's own scheme. - The dashboard's **Agents, Connected apps** lists grants and disconnects them. ## The agent skill The **forkbase-agent** skill teaches an agent the run, check, propose, stop-when-held loop. Install the whole pack with `curl -fsSL /skills/install.sh | sh` (see [Skills](https://forkbase.tech/docs/skills)), so the client works well with the tools above. --- # Observability > Every agent run’s ledger, OpenTelemetry traces and metrics, and the Prometheus endpoint. Source: https://forkbase.tech/docs/observability Every agent run keeps a **ledger**: each step it took, in order, with a line a person reads. The same steps go to OpenTelemetry as one trace per run, and counters go to `/metrics` and OTLP. ## The run ledger `GET /agents/v1/runs/{id}/ledger` (service key, the run's agent, or the run itself): ```json { "run": "run_7f3c...", "entries": [ {"id": "led_...", "run_id": "run_7f3c...", "seq": 1, "at": 1764633600000, "kind": "run.created", "status": "ok", "duration_ms": null, "actor": "agent:claims_bot", "summary": "Run started by claims_bot: close claim 2", "detail": {...}}, {"kind": "sql", "status": "ok", "duration_ms": 3, "actor": "run:run_7f3c...", "summary": "UPDATE in its world, 1 rows", "detail": {"sql": "update claims set ...", "params": 4, "rows": 1, "tool": "run_sql"}}, {"kind": "run.proposed", "actor": "run:run_7f3c...", "summary": "Proposed its changes to main, under policy large_claims", "detail": {"policy": "large_claims"}}, {"kind": "run.held", "actor": "policy", "summary": "Held for a person: it changes claims, a table under review"}, {"kind": "run.merged", "actor": "link:ops@example.com", "summary": "Merged 1 rows, approved by link:ops@example.com"} ], "next": null } ``` | Kind | Recorded when | |---|---| | `run.created`, `run.held`, `run.merged`, `run.rejected`, `run.conflict`, `run.discarded`, `run.expired`, `run.undone` | the [event](https://forkbase.tech/docs/agents#webhooks-and-events) of the same name happens | | `run.proposed` | the run asks to merge (before the policy decides) | | `run.propose_failed`, `run.approve_refused` | a proposal or an approval fails | | `sql` | a statement runs through `POST /runs/{id}/sql`, the SDK's `sql()` or MCP's `run_sql` (failures too) | | `tool` | an MCP tool reads the run (`run_changes`, `get_run`) | | `job.attempt` | an attempt of an [agent function](https://forkbase.tech/docs/jobs#agent-functions)'s job ends | | `job.succeeded`, `effect.` | the event of the same name happens for the run | - `status` is `ok` or `error`. A failed statement keeps its error in `detail.error`. - `actor` says who caused the step: `service`, `agent:`, `run:`, `policy`, `link:`, `job:`. - `detail.via` is `mcp` for steps taken through the MCP server. - SQL text is kept up to `observe.sql_text_bytes` (4000) bytes; longer text is cut, with `detail.truncated` set and the full length in `detail.sql_bytes`. `0` keeps only the length. Parameter values are never kept, only their count. - `?limit=` (1 to 5000, default 1000) and `?after=` page through it; `next` is the last id of a full page. - `?format=jsonl` answers JSON lines (`application/x-ndjson`), one entry per line, for `jq` or a log pipeline. - The dashboard's run sheet shows the same ledger as a timeline, with each statement's SQL a click away. What the ledger can't see: statements an agent runs straight through its run's `database_url` with a Postgres driver. Those reach the engine without passing Forkbase. Their effect is still in the run's changes (`GET /runs/{id}/changes`), its proposal and its merge, which are in the ledger. Entries are written in batches a quarter of a second apart, so a burst of steps costs one transaction. Reading the ledger writes what's waiting first. If the database can't keep up, entries beyond 10,000 waiting are dropped and counted (`forkbase_ledger_dropped_total`); the run itself is never slowed or failed by its ledger. Entries older than `observe.retention_days` (30) are deleted once a day; `0` keeps them. ## OpenTelemetry Set an OTLP/HTTP endpoint and Forkbase sends traces and metrics there, JSON over HTTP, to any OpenTelemetry collector, Grafana, Honeycomb, Datadog, Langfuse, Arize Phoenix or similar: ```bash FORKBASE_OTLP_ENDPOINT=http://127.0.0.1:4318 forkbase start # or the standard variables OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io OTEL_EXPORTER_OTLP_HEADERS=x-honeycomb-team=... forkbase start ``` - **One trace per run.** Its id is made from the run's id, so every step of the run, recorded by any server or job, lands in the same trace. - **The run's own span**, `invoke_agent `, spans the run from start to end. It is sent when the run ends (merged, rejected, discarded or expired), with `gen_ai.operation.name = invoke_agent`, `gen_ai.agent.name`, `gen_ai.agent.id`, `gen_ai.conversation.id` (the run id), `forkbase.run.intent` and `forkbase.run.outcome`. - **Each statement and tool call** is a child span, `execute_tool run_sql` (or the tool's name), with `gen_ai.tool.name`, `db.system.name`, `db.query.text`, `forkbase.rows` and its duration; a failure has an error status. Every other ledger entry is a child span named by its kind. - Names and attributes follow the OpenTelemetry GenAI semantic conventions, so tools that understand agent traces show runs as agents, and their SQL as tool calls. - Export never blocks a request: spans go out with each ledger batch, metrics every `observe.metrics_every_s` (60). An endpoint that refuses or is down is logged, and nothing is retried. ## Metrics `GET /metrics` (Prometheus text) has, beside the server's own gauges: | Metric | Type | Labels | |---|---|---| | `forkbase_ledger_entries_total` | counter | `kind`, `status` | | `forkbase_ledger_dropped_total` | counter | | | `forkbase_runs_total` | counter | `outcome`: `created`, `held`, `merged`, `rejected`, `conflict`, `discarded`, `expired`, `undone` | | `forkbase_agent_tool_duration_seconds` | histogram | `tool` | With an endpoint set, the same go out over OTLP as `forkbase.ledger.entries`, `forkbase.ledger.dropped`, `forkbase.runs` and `forkbase.agent.tool.duration`. Counters start at zero when the server starts. ## Configuration `[observe]` in `forkbase.toml`; see [Configuration](https://forkbase.tech/docs/configuration#observe). ```toml [observe] retention_days = 30 sql_text_bytes = 4000 otlp_endpoint = "http://otel-collector:4318" service_name = "forkbase" metrics_every_s = 60 ``` --- # SDKs > forkbase for TypeScript and Python, and supabase-js and supabase-py as they are. Source: https://forkbase.tech/docs/sdks Two kinds of client work with Forkbase: - **supabase-js / supabase-py** for tables, auth, storage and realtime. Forkbase speaks their APIs; point them at your Forkbase URL and anon key. - **`@chronosdb/forkbase`** (TypeScript) and **`forkbase`** (Python) for what Supabase's clients don't cover: agents' runs and jobs. No dependencies. ```bash npm i @chronosdb/forkbase # Node 18+, browsers, Deno, Bun pip install forkbase # Python 3.9+, standard library only ``` > The TypeScript SDK is on npm as `@chronosdb/forkbase` (npm refuses the bare name `forkbase`); the Python SDK is on > PyPI as `forkbase`. ## TypeScript ```ts import { createClient } from "@chronosdb/forkbase"; const fb = createClient("https://api.myapp.com", process.env.FORKBASE_AGENT_TOKEN!); // the usual shape: a block that runs in a world, then proposes const { outcome, result } = await fb.agents.withRun("close stale carts", async (run) => { const r = await run.sql("update carts set closed = true where updated_at < now() - interval '30 days' returning id"); return r.rows.length; }); if (outcome.status === "held") console.log("waiting for a person:", outcome.reasons); ``` `withRun` proposes when the block returns and discards the run when it throws. `propose()` never throws for `merged`, `held` or `conflict`: read `outcome.status`. ### `createClient(url, key, { fetch?, headers? })` `key` is an agent token (`fba_`), a run token (`fbr_`) or the service key. What you can call depends on it; see [Agents, who may call what](https://forkbase.tech/docs/agents#who-may-call-what). ### `fb.agents` | Method | Key | | |---|---|---| | `run(intent, opts?)` | agent, service | a `Run` | | `withRun(intent, fn, opts?)` | agent, service | `{ run, result, outcome }` | | `get(id)` | any | a `Run` | | `listRuns({ status?, limit? })` | agent, service | | | `create(name, { policy? })` | service | a new agent, with its `token` | | `list()` | service | | | `approve(id)`, `reject(id, reason?)`, `undo(id, { skipChanged? })` | service | | `opts`: `agent` (service key: whose run), `ttlSeconds`, `meta`, `policy`, `actAs` (a signed-in person's access token: RLS judges the run as theirs). ### `Run` `id`, `status`, `token`, `databaseUrl`, `data`, and: | Method | | |---|---| | `sql(query, params?)` | `{ columns, rows }` | | `changes({ limit? })` | the rows it changed | | `propose()` | `{ status: "merged" \| "held" \| "conflict", reasons? }` | | `discard()` | | | `refresh()` | reload its status | `databaseUrl` works with any Postgres driver or ORM (`pg`, Drizzle, Prisma). ### `fb.jobs` (service key) | Method | | |---|---| | `deploy({ name, files \| source, entry?, env?, timeout_s?, memory_mb?, max_attempts?, concurrency?, agent? })` | | | `functions()` | | | `invoke(name, payload?, { wait?, delayS?, runAt?, idempotencyKey? })` | | | `get(id)`, `list({ fn?, status?, before?, limit? })` | | | `cancel(id)`, `retry(id)` | | | `schedule(fn, cron, payload?)` | | ### Everything else `fb.request(method, path, body?)` calls any route. `await fb.supabase()` returns a supabase-js client for the same server (install `@supabase/supabase-js`). Errors throw `ForkbaseError` with `status`, `code` and `body`. ### Inside a job ```ts import { step, sleep, sql, context } from "@chronosdb/forkbase"; ``` | | | |---|---| | `step(name, fn)` | run once, remembered across retries | | `sleep(name, seconds)` | pause the job without holding a worker | | `sql(query, params?)` | agent functions: SQL in the job's world | | `context()` | `{ payload, job: { id, attempt, function }, run, url, step, sleep, sql }` | The job runtime ships this module; functions import it without installing it. See [Jobs](https://forkbase.tech/docs/jobs). ## Python ```python from forkbase import create_client fb = create_client("https://api.myapp.com", agent_token) scope = fb.agents.with_run("close stale carts") with scope as run: run.sql("update carts set closed = true where updated_at < now() - interval '30 days'") print(scope.outcome) # {"status": "merged" | "held" | "conflict", ...}; an exception in the block discards the run ``` The same methods in snake_case: `fb.agents.run(intent, agent=, ttl_seconds=, meta=, act_as=, policy=)`, `with_run`, `get`, `list_runs`, `create`, `list`, `approve`, `reject`, `undo(run_id, skip_changed=False)`; `fb.jobs.deploy(**fn)`, `functions`, `invoke(name, payload, delay_s=, run_at=, idempotency_key=, wait=)`, `get`, `list`, `cancel`, `retry`, `schedule`; `fb.request`, `fb.supabase()` (install `forkbase[supabase]`). Errors raise `ForkbaseError` (`status`, `code`, `body`). Inside a job: `from forkbase import step, sleep, sql, context`. ## supabase-js ```ts import { createClient } from "@supabase/supabase-js"; const supabase = createClient("https://api.myapp.com", ANON_KEY, { auth: { flowType: "pkce" } }); await supabase.auth.signInWithPassword({ email, password }); await supabase.from("notes").insert({ body: "hi" }); await supabase.storage.from("avatars").upload("me.png", file); supabase.channel("notes").on("postgres_changes", { event: "*", schema: "public", table: "notes" }, console.log).subscribe(); ``` What works: tables (`from`), auth (passwords, OTP, OAuth with PKCE, sessions), storage, realtime changes and broadcast. Not yet: `rpc` (Postgres functions over REST), presence, edge functions (use [Jobs](https://forkbase.tech/docs/jobs)). --- # Dashboard > The built-in studio at /dashboard: tables, SQL, auth, storage, agents, approvals, jobs and logs. Source: https://forkbase.tech/docs/dashboard `/dashboard/` is built into the binary. Open `http://127.0.0.1:8000/dashboard/` and sign in with the `service_role` key (`forkbase keys`), or with a team member's own key (below). The key stays in that browser tab unless you tick **Remember**. | Page | What you do there | |---|---| | **Overview** | tables, users, buckets, runs waiting for review; requests, errors, latency and agent runs over the last hour, day or week; database and storage size; recent runs; connect a coding agent | | **Table editor** | browse rows with several filters; edit a cell in place (double-click) or a whole row; JSON values in a viewer; follow a foreign key to its row; drag a column's edge to size it; import and export CSV. **Structure**: make, change and delete tables and columns without SQL, open or close a table to the API | | **API docs** | each table's REST calls in JavaScript, Python and curl with the project's URL and keys; auth and storage; turn realtime on per table | | **SQL editor** | run SQL as the database owner; a result per statement; snippets kept in the browser; ⌘↵ runs | | **Database** | a schema diagram (tables, their keys and the foreign keys between them); indexes, views, functions, triggers, enums and roles per schema, each with its definition | | **Database, Backups** | chronos mode: checkpoints, restore main to a checkpoint or a time, back up the engine's folder while it serves. postgres mode: download a `pg_dump` | | **Database, Connection** | the database URL (with where its password is, never the password), host, port, pooler; the HTTP URLs and keys | | **Auth, Users** | people: make, invite, confirm, disable, sign out, delete | | **Auth, Policies** | row level security per table: turn it on, write policies from templates, see the SQL | | **Auth, Sign-in methods / URLs / Google and GitHub / Email / Email templates** | the auth settings, saved in the database over `forkbase.toml`'s and applied without a restart | | **Storage** | buckets and files: upload, download, signed links | | **Realtime** | connected clients and what each listens to, open channels, the last 200 messages (where they went, never what they said), which tables send changes | | **Agents, Approvals** | the inbox of held runs, the oldest open beside the list: the rows it changes (before and after, the changed columns only), the reasons, SQL and counts; approve or reject | | **Agents, Runs** | every run and its outcome | | **Agents, Worlds** | open worlds; undo a merged run | | **Agents, Agents / Webhooks** | agents and their tokens, webhook endpoints | | **Agents, Policies** | the merge policies: edit their files, try one against an open or held run before saving, delete | | **Agents, Connected apps** | MCP clients that were granted access; disconnect them | | **Jobs** | jobs with each attempt's output (live while it runs) and a timeline of its steps; functions (deploy, run); schedules; triggers | | **Logs** | API requests (time range, status and method facets, a histogram, each request's detail, live tail), sign-in events, agent events | | **Settings** | API keys, signing keys; **Team** (members and roles); **Audit log** | ⌘K searches pages and tables. The OAuth consent page for [MCP](https://forkbase.tech/docs/mcp) clients is a dashboard page too (`/dashboard/oauth/`). ## Team Give each person who uses the dashboard a key of their own, with a role, so approvals and changes name who made them. **Settings, Team** adds a member (an email, a role) and shows their key once; send it to them privately. The service key stays for your servers and acts as the owner. | Role | May | |---|---| | viewer | read every page, and try a merge policy against a run; change nothing | | operator | a viewer who also approves, rejects, undoes and discards agents' runs, and cancels, retries and runs jobs | | admin | everything the service key does, the team included | Members below admin never see the service key. SQL, the team, `pg_dump`, signing keys and MCP are admin-only, reads included. A member key (`fbtm_...`) works on every API the dashboard calls, as `apikey` or `Authorization: Bearer`. A new key, turning a member off or removing them takes effect within 5 seconds on every server (at once on the one that made the change). An admin can't lower, turn off or remove themself. **Audit log** (Settings) lists every write a member made, with what their role refused, and the service key's changes to the team, backups, policies, approval links, auth settings and runs: who, when, the route, the result. ## `/platform/v1` What the dashboard calls besides the public APIs. Service key or a member key. | Route | | |---|---| | `GET /platform/v1/project` | mode, versions, instance, uptime, counts | | `GET /platform/v1/tables` | served tables, columns, primary and foreign keys | | `POST /platform/v1/sql` | `{"query": "..."}`: runs as the database owner, up to 1,000 rows a statement, 60 s, on its own connection; errors keep Postgres's code and position | | `GET /platform/v1/logs?after=&limit=` | the last 5,000 requests, from memory: method, path, status, time, size, user agent (no query strings, no bodies) | | `GET /platform/v1/stats?range=1h\|24h\|7d` | requests, 4xx, 5xx and latency (median, p95) by time, counted a minute at a time for a week in memory; agent runs by outcome; database and storage size | | `GET /platform/v1/database?schema=` | a schema's indexes, views, functions, triggers and enums, and the database's roles (each with its definition) | | `GET /platform/v1/connection` | mode, the HTTP URLs, the database URL with its password left out, host, port, pooler | | `GET /platform/v1/backups` | chronos: checkpoints and the backups in `/backups`; postgres: whether `pg_dump` is here | | `POST /platform/v1/backups` | chronos: back up the engine's folder into `/backups/