# PocketOne > PocketOne is a community fork of PocketBase (one Go binary: database, auth, files, realtime, admin UI) with extensions for point-in-time recovery, backups, mail, many instances on one server, deploys, tokens and OAuth, MCP, and server-rendered pages. PocketOne takes the same commands and flags as PocketBase, plus its own; core PocketBase topics live at https://pocketbase.io/docs. Agent Skills for PocketOne: https://github.com/pocketonehq/pocketone/tree/main/agent (Claude Code: `/plugin marketplace add pocketonehq/pocketone`). --- Source: https://pocketone.dev/docs/overview # What is PocketOne? PocketOne is a community fork of [PocketBase](https://pocketbase.io). It tracks upstream PocketBase and keeps its own changes to the core small: only the hooks that let extensions extend and override PocketBase. Every feature lives in an extension. It's maintained by [Ben Allfree](https://github.com/benallfree) and contributors. Ben also created [PocketHost](https://pockethost.io), which runs PocketOne in production, but PocketOne is its own project, open to anyone who wants to help. PocketOne is not affiliated with or endorsed by the PocketBase project. ## Why a fork PocketBase is a remarkable piece of software, and a lot of that comes from how it's made: one author, a deliberately narrow scope, and a careful, steady pace. That focus is a big part of why it's so good, and how PocketBase is run is Gani's call to make. It also means PocketBase isn't set up to take larger contributions from the community, so ideas people want to build have nowhere to land upstream: hooks that can do more, apps that run many instances, features anyone can write and share. PocketOne is a different path for that work. It stays close to upstream and passes PocketBase's own tests, keeps its changes to PocketBase small, and puts everything else in extensions that anyone can build on, improve and send back. ## What it adds Run `pocketone` the way you run `pocketbase`. These are the differences you'll notice; [New in PocketOne](https://pocketone.dev/docs/features) compares each one with PocketBase. ### Hooks with async, import and TypeScript Your `pb_hooks` run on QuickJS with PocketBase's JS API, so they work unchanged, and they also get: `async` handlers with `await` (the app keeps serving while one waits), ES module `import` and `node_modules` packages, `.pb.ts` TypeScript files, globals shared by every handler, and memory and time limits. [QuickJS hooks](https://pocketone.dev/docs/quickjs) walks through each one. ### Pages in TSX, TypeScript or EJS Put `.tsx`, `.jsx`, `.ejs` or Markdown files in a `pb_pages` folder and they're server-rendered pages, with your records a function call away. Components `import` each other, route files can be TypeScript, and every part of a page can `await`. esbuild is built into the binary, so there's no Node, no `npm install` and no build step. This site is one. `pocketone pages create myapp` starts a new site from a starter kit. [Pages](https://pocketone.dev/docs/features/sites) shows a page in TSX. ### Hundreds of apps in one process Add a `multisite` section to `pocketone.yaml` and one `pocketone` process runs hundreds of PocketBase apps as isolates, routed by hostname. Each is a complete app with its own data, hooks and dashboard. It starts on its first request in tens of milliseconds, costs about 3 MB while it runs, and is sandboxed from the others. No container per app. [PocketBase isolates](https://pocketone.dev/docs/features/isolates) shows it running in a minute. ### Point-in-time restore, on by default Your database is replicated with Litestream, so you can restore it to any moment from **Settings → Backups** or with `pocketone pitr restore`. Turn it off with `--pitr=false`. ### Mail you can see in dev mode In dev mode (`serve --dev`), an app with no SMTP settings doesn't send through the system's `sendmail`. The mail is caught and shown at `http://127.0.0.1:8025`. ### A config file Settings can live in `pocketone.yaml`, with secrets in a `.env` file beside it that your JS hooks never see. Without the file, PocketOne behaves like stock PocketBase. `pocketone config` lists every section, and `pocketone config check` checks a file. The [config reference](https://pocketone.dev/docs/config-reference) lists every section. ### Commands for working with remote apps - `pocketone login`, `remote` and `link`: save logins to your apps. - `pocketone deploy`, `dev`, `pull` and `logs`: ship `pb_hooks`, `pb_migrations` and `pb_public` to an app and watch it. - `pocketone upgrade`: move to the latest release, keeping the old executable. - `pocketone remote …`: every operation of every contract an app offers is a command, such as `pocketone remote restore to --at -2h`. The same operations are REST endpoints and MCP tools. [Remote CLI](https://pocketone.dev/docs/features/remote) explains it, and the [CLI reference](https://pocketone.dev/docs/reference/cli) lists every command. ### Agents and API tokens - An MCP endpoint at `/mcp` lets agents such as Claude manage your app and call its tools. - Long-lived API tokens (`pbt_…`) with scopes, for scripts and integrations. - Your app can act as an OAuth provider; `pocketone login` and MCP sign-in use it. ### Extensions that fit together PocketOne's extensions meet through contracts: named, versioned promises like `restore/v1` that any extension can keep. The dashboard, the `pocketone` command, agents and your `pb_hooks` call the contract, so you can swap the extension behind it without changing anything else. [How PocketOne fits together](https://pocketone.dev/docs/how-pocketone-fits-together) explains it. ### Everything else Automatic TLS certificates, bulk mail to your own users, scheduled VACUUM, signed S3 download redirects, and more. See [all extensions](https://pocketone.dev/docs/extensions/all). ## What stays the same The admin dashboard, collections, rules, the REST and realtime APIs, JS hooks and migrations all work as in PocketBase. For those, the [PocketBase docs](https://pocketone.dev/docs/pocketbase) are the reference. ## How it's built - **A small core.** PocketBase's own code changes only to add hooks. Each change is marked in the source, reviewed by someone who didn't write it, and kept minimal so upstream releases merge cleanly. You can review the complete core changes [here](https://github.com/pocketonehq/pocketone#changes-we-made-to-pocketbase). - **Everything else is an extension.** Extensions live in `ext/` in the repo. Each is its own Go module, with a README and a small example. - **Off until you use it.** The extensions in the `pocketone` binary add no work to an app that doesn't use them. - **One app or hundreds.** An extension written against the extension contract works the same on a single app and on every instance under a multi-instance host. ## Open to contributions PocketOne is open to everyone. Ask questions and share ideas in [GitHub Discussions](https://github.com/pocketonehq/pocketone/discussions), report bugs in [Issues](https://github.com/pocketonehq/pocketone/issues), and send extensions as pull requests. Start with [Writing an extension](https://pocketone.dev/docs/writing-an-extension). ## Where to next - [Install PocketOne](https://pocketone.dev/docs/installation) - [Browse the extensions](https://pocketone.dev/docs/extensions/all) --- Source: https://pocketone.dev/docs/installation # Installation PocketOne is one executable, `pocketone`. It is built on PocketBase and takes the same commands and flags, plus its own. - **Install:** [macOS](#macos) · [Windows](#windows) · [Linux](#linux) - **Use:** [Run it](#run-it) · [Upgrade](#upgrade) · [Moving from PocketBase](#moving-from-pocketbase) Another way to install (a release zip, Windows without Scoop, building from source, the install script's settings)? See [Advanced installation](https://pocketone.dev/docs/guides/advanced-installation). ## macOS With [Homebrew](https://brew.sh): ```bash brew install pocketonehq/tap/pocketone ``` The formula lives in [pocketonehq/homebrew-tap](https://github.com/pocketonehq/homebrew-tap). Without Homebrew, use the install script: ```bash curl -fsSL https://pocketone.dev/install.sh | sh ``` It picks the newest release for your Mac, checks its checksum and puts `pocketone` in `/usr/local/bin` (asking for your password through `sudo` when that folder isn't yours). Read it first if you like: [pocketone.dev/install.sh](/install.sh). ## Windows With [Scoop](https://scoop.sh), in PowerShell: ```powershell scoop bucket add pocketonehq https://github.com/pocketonehq/scoop-bucket scoop install pocketone ``` The manifest lives in [pocketonehq/scoop-bucket](https://github.com/pocketonehq/scoop-bucket). Without Scoop, see [Windows without Scoop](https://pocketone.dev/docs/guides/advanced-installation#windows-without-scoop). ## Linux With [Homebrew](https://brew.sh), as on macOS: ```bash brew install pocketonehq/tap/pocketone ``` Or with the install script, which suits a server: ```bash curl -fsSL https://pocketone.dev/install.sh | sh ``` It finds your package manager (apt, dnf, yum, zypper or apk), downloads the newest release's `.deb`, `.rpm` or `.apk` package for your system, checks its checksum and installs it with `sudo`. The package also sets PocketOne up as a systemd service, stopped until you start it. With none of those package managers it puts the plain binary in `/usr/local/bin` instead. To set the service up, see [Run PocketOne on a Linux server](https://pocketone.dev/docs/guides/linux-server). ## Run it Create your first superuser before the first serve: ```bash pocketone superuser upsert pocketone serve ``` Opening `http://127.0.0.1:8090/_/` to create it also works, as in PocketBase. To start a site with server-rendered pages: ```bash pocketone pages create myapp cd myapp pocketone serve --dev --dir ./pb_data ``` In dev mode (`serve --dev`), an app with no SMTP settings doesn't send mail through the system's `sendmail`. PocketOne catches the mail and shows it at `http://127.0.0.1:8025`. ## Upgrade Upgrade the way you installed: | Installed with | Upgrade with | |---|---| | Homebrew | `brew update && brew upgrade pocketone` | | Scoop | `scoop update pocketone` | | The install script | Run it again. | | Anything else | `pocketone upgrade` | `pocketone upgrade` replaces the executable with the latest release. The old one is kept beside it as `pocketone-` (`pocketone-.exe` on Windows), never deleted, so you can go back. For a Homebrew, Scoop or Linux package install it tells you the command above instead. ## Moving from PocketBase PocketOne reads the same `pb_data`, `pb_hooks`, `pb_migrations` and `pb_public` folders. Point it at your existing data directory with `--dir`, as you would with `pocketbase`. Back up `pb_data` first. --- Source: https://pocketone.dev/docs/running # Running PocketOne PocketOne is your whole backend in one file. The `pocketone` executable is a database, a REST and realtime API, user accounts and sign-in, file storage, an admin dashboard, a server for your pages and static files, and a JavaScript runtime for your own code, plus PocketOne's extensions (deploys, restore, API tokens, AI models, MCP). There's nothing else to install and nothing else to run. An app is a folder. You start `pocketone` in it, and everything it keeps sits next to it. ## Start it ```bash mkdir myapp && cd myapp pocketone superuser upsert admin@example.com 'a long password' --dir ./pb_data pocketone serve --dir ./pb_data ``` ``` Server started at http://127.0.0.1:8090 > Dashboard: http://127.0.0.1:8090/_/ > REST API: http://127.0.0.1:8090/api/ ``` - **`--dir`** is the app's data folder. Without it, `pocketone` uses `pb_data` next to the executable, so pass it (or set `dir:` in the [configuration](https://pocketone.dev/docs/pocketone-yaml)'s `app:` section) to keep each app's data in its own folder. - **`--http`** is where it listens (default `127.0.0.1:8090`); `--http 0.0.0.0:8090` listens on every address. `pocketone serve example.com` serves HTTPS for that domain, with a certificate it gets and renews itself. - **`--dev`** prints every request and SQL statement, catches outgoing mail when no mail server is set (and shows it at http://127.0.0.1:8025), and skips a hook file with an error instead of stopping. - Stop it with Ctrl-C. Nothing else is running: no database server, no queue, no worker. `pocketone --help` lists every command; `pocketone serve --help` every flag. To keep it running on a server, see [Run on a Linux server](https://pocketone.dev/docs/guides/linux-server). ## What's in the folder | Folder | What it holds | Backed up | Deployed and synced | Safe to delete | |---|---|---|---|---| | `pb_data` | the database, uploaded files, logs | yes | never | no: it's your data | | `pb_hooks` | your server code: [hooks](https://pocketone.dev/docs/hooks) and [routes](https://pocketone.dev/docs/routes) (`*.pb.ts`), and `*.pb.wasm` modules | as code, in git | yes | no | | `pb_pages` | your site's [pages](https://pocketone.dev/docs/extensions/pages) | as code, in git | yes | no | | `pb_migrations` | your [migrations](https://pocketone.dev/docs/migrations): collection changes and seed data | as code, in git | yes | no | | `pb_public` | static files served as they are (a built single-page app, images) | as code, in git | yes | no | | `pb_templates` | page templates you ejected (`pocketone template eject`) | as code, in git | yes | no | | `pb_cache` | files extensions can rebuild, one folder each | never | never | yes, at any time | Only `pb_data` is created for you; make the others when you need them. The app also writes `types.d.ts` and a `tsconfig.json` next to them, so your editor knows the JavaScript API, and reads `pocketone.yaml` and `.env` from the same folder if you add them ([Configuration](https://pocketone.dev/docs/pocketone-yaml)). Add `pb_data/` and `pb_cache/` to your `.gitignore`. ### `pb_data` | In it | Is | |---|---| | `data.db` | the database: every collection and record, the settings | | `auxiliary.db` | the logs | | `storage/` | uploaded files, by collection and record (unless files are stored in S3) | | `backups/` | backups you made (unless they're sent to S3) | | `litestream/` | the change history for [point-in-time restore](https://pocketone.dev/docs/features/restore) | Never edit these by hand while the app runs, and never open the live database with another tool. Use the dashboard, the API or your code. ### `pb_cache` Each extension that keeps disposable files has its own folder, `pb_cache//`. Everything in it can be rebuilt, so deleting it is always safe: the app carries on, perhaps a little slower until the cache fills again. ```bash pocketone cache # each extension's folder, its file count and size pocketone cache clear # empty every folder pocketone cache clear # empty one extension's folder ``` On a multisite host, each instance's `pb_cache` is kept by the host outside the instance's folder, so copies and moves of an instance never carry it. ## The dashboard and superusers The dashboard at `/_/` is where you manage the app: collections and records, settings, logs, backups, and the screens extensions add (AI models, search, tokens, bulk mail). ![Settings in the dashboard: application, mail, files storage, backups, crons, LLM, SQL console and API tokens](https://pocketone.dev/docs/screenshots/dashboard-settings.jpg) **Superusers** are the people who can open it. They're records of a built-in collection, `_superusers`, and they can do everything: see and change every record, past every [API rule](https://pocketone.dev/docs/api-rules), and call the admin endpoints. Keep them few. ```bash pocketone superuser upsert admin@example.com 'a long password' --dir ./pb_data # create, or reset the password pocketone superuser delete admin@example.com --dir ./pb_data pocketone superuser otp admin@example.com --dir ./pb_data # a one-time password to sign in with ``` Create the first one before the first `serve`. Without any superuser, the app prints a link (and opens it in a browser, on your own machine) to a page that creates one. ![The dashboard's superuser sign-in](https://pocketone.dev/docs/screenshots/dashboard-superuser-login.jpg) ![The _superusers collection, under System with the tables extensions keep](https://pocketone.dev/docs/screenshots/dashboard-superusers.jpg) ## Your app's users Your app's own accounts are a different thing: records of an **auth collection** you control. Every app starts with one, `users`, and you can add more (`customers`, `staff`). Users sign in through the [API](https://pocketone.dev/docs/rest/authentication) or your [pages](https://pocketone.dev/docs/extensions/pages/authentication), never the dashboard, and what each may do is decided by your collections' [API rules](https://pocketone.dev/docs/api-rules). ![The users collection: your app's accounts, with email, verified and name](https://pocketone.dev/docs/screenshots/dashboard-users.jpg) | | Superusers | Users | |---|---|---| | Collection | `_superusers` (built in) | `users`, or any auth collection you add | | Sign in at | the dashboard (`/_/`), the CLI, the admin API | your app: the [REST API](https://pocketone.dev/docs/rest/authentication), the SDK, your pages | | May do | everything | what your API rules allow | | Made by | `pocketone superuser upsert`, or another superuser | signing up, or you, in the dashboard or code | See [Authentication](https://pocketone.dev/docs/authentication) for sign-in methods, and [API tokens](https://pocketone.dev/docs/features/tokens) for scripts and other apps that call yours. ## Where a request goes | Path | Served by | |---|---| | `/_/` | the dashboard | | `/api/...` | the [REST API](https://pocketone.dev/docs/rest): records, auth, files, realtime, and your [custom routes](https://pocketone.dev/docs/routes) | | `/api/_c/...` | the [extension APIs](https://pocketone.dev/docs/extensions/apis) | | `/mcp` | [MCP](https://pocketone.dev/docs/features/mcp), for AI agents | | anything else | your [pages](https://pocketone.dev/docs/extensions/pages) in `pb_pages` and the files in `pb_public` | [Hooks](https://pocketone.dev/docs/hooks) run on all of it: before and after records are saved, on requests, when mail goes out. ## Extension tables Extensions that store records keep them in collections named `__` (`_bulkmail_campaigns`, `_llm_calls`), so you can tell them from your own at a glance and see which extension owns each. They live in `pb_data` with the rest of your data, so they're backed up with it. Extensions create and update them with their own migrations, recorded apart from yours, so `pocketone migrate` never touches them: ```bash pocketone extensions migrations # every extension's migrations and when each was applied pocketone extensions migrate down bulkmail # revert bulkmail's last migration (its data goes with it) ``` ## Next - [Collections and fields](https://pocketone.dev/docs/collections): define your data. - [Hooks](https://pocketone.dev/docs/hooks): your first server code. - [Starter kits](https://pocketone.dev/docs/starters): an app to begin from. - [Deploy and live sync](https://pocketone.dev/docs/features/deploy): put the folder on a server. --- Source: https://pocketone.dev/docs/pocketbase # Coming from PocketBase PocketOne is PocketBase with more built in. Run `pocketone` the way you run `pocketbase`: the same commands and flags, the same API, the same dashboard and the same `pb_data`, `pb_hooks` and `pb_migrations` folders. ## What stays the same - **Your API and SDKs.** Collections, records, auth, files and realtime work as in PocketBase. The JS and Dart SDKs work unchanged. - **Your hooks.** The JS API (`$app`, `routerAdd`, `onRecordCreate`, `cronAdd`, …) is PocketBase's, so existing `pb_hooks` run as they are. They run on [QuickJS](https://pocketone.dev/docs/quickjs), which adds imports, TypeScript and async handlers on top. - **PocketBase's own tests.** PocketBase's test suite runs unmodified against PocketOne's core on every change and every day. See the live results on [PocketBase compatibility](https://pocketone.dev/docs/compatibility). PocketOne is built on PocketBase v0.42. When pocketbase.io describes a newer release, some of it may not be in PocketOne yet. ## What's added Everything below is on by default. For each one, here's how you'd handle it in PocketBase and what PocketOne brings. ### Hooks PocketBase runs `pb_hooks` on goja: CommonJS `require`, synchronous handlers, and a pool of runtimes that each load your hook files. PocketOne runs the same JS API on QuickJS, so your hooks keep working, and adds `async`/`await`, ES module `import` with `node_modules` packages, `.pb.ts` TypeScript, globals shared by every handler, and memory and time limits. [QuickJS hooks](https://pocketone.dev/docs/quickjs) ### Sites PocketBase serves static files and single-page apps from `pb_public`, and hooks can render HTML with `$template`. PocketOne adds server-rendered pages: a `.tsx`, `.jsx`, `.ejs` or `.md` file in `pb_pages` becomes a route, with `await` everywhere and no build step. [Pages](https://pocketone.dev/docs/features/sites) ### Many apps on one server A PocketBase app is one process, and you host several by running a process, container or VM for each. PocketOne can run hundreds of apps as isolates inside one process; each starts on its first request in tens of milliseconds, uses about 3 MB and is sandboxed from the others. [PocketBase isolates](https://pocketone.dev/docs/features/isolates) ### Backups and restore PocketBase makes backups on a schedule, to local disk or S3, and restores a whole backup. PocketOne also records every change, so you can restore to any second in the last 72 hours, and undo the restore. [Point-in-time restore](https://pocketone.dev/docs/features/restore) ### Deploying A PocketBase app is a folder you copy to the server; hooks reload when they change, and migrations run on the next start. PocketOne adds `pocketone deploy`, which uploads only what changed, and `pocketone dev`, which keeps a local folder and the running app in step both ways and streams the logs. [Deploy and live sync](https://pocketone.dev/docs/features/deploy) ### Admin from anywhere PocketBase's CLI runs on the machine that holds `pb_data`, and the dashboard and REST API work from anywhere. PocketOne adds a remote CLI: sign in once, then run admin commands against any app from your terminal, a script or an agent. [Remote CLI](https://pocketone.dev/docs/features/remote) ### Tokens A PocketBase auth token acts as its account, and changing the account's token key signs out all of its tokens at once. PocketOne adds named, scoped API tokens that you revoke one by one, and makes your app an OAuth server that apps and agents sign in through. [API tokens and OAuth](https://pocketone.dev/docs/features/tokens) ### AI agents PocketBase offers a REST API and realtime subscriptions, with official JavaScript and Dart SDKs. PocketOne also serves MCP at `/mcp` on every app, with OAuth sign-in, so Claude and other agents work with your app as you, using your own tools from `pb_hooks` too. [MCP for AI agents](https://pocketone.dev/docs/features/mcp) ### Mail PocketBase sends account mail (verification, password reset, email change, one-time codes), and your hooks can send any message through its mailer. PocketOne adds campaigns from the dashboard, with unsubscribes, suppression and pacing handled. [Bulk mail](https://pocketone.dev/docs/features/bulk-mail) ### Desktop apps A PocketBase app is a server: you host it, and people reach it from a browser. PocketOne can also build the same app folder into a native desktop app for macOS, Windows and Linux, with your hooks, migrations and public files inside one executable and each user's data on their own machine. It's a preview. [Desktop apps](https://pocketone.dev/docs/extensions/desktop) ### Configuration In PocketBase, app settings live in the dashboard and `serve` takes its options as command-line flags. PocketOne adds `pocketone.yaml`, one file next to your app for those options and every extension's, with a `.env` for secrets. [pocketone.yaml](https://pocketone.dev/docs/pocketone-yaml) Smaller additions are listed under [Also built in](https://pocketone.dev/docs/features#also-built-in). --- Source: https://pocketone.dev/docs/agents # LLM skills for coding agents PocketOne is new, so coding agents haven't seen much of it. Two things close that gap. Both are built from these docs, so they change when the docs change. ## Agent Skills The `pocketone` plugin has two skills: - **pocketone:** using PocketOne in an app: the `pocketone` binary and its commands, `pocketone.yaml`, deploying, every extension, and the app's pages in `pb_pages/` (routing, `ctx`, templates, layouts, auth). - **pocketone-extensions:** writing your own extension and contributing it as a pull request: contracts, `extkit`, tests, and the README and changelog CI checks. Each skill carries a copy of the docs in its `reference/` folder, so it works offline. **Claude Code** ``` /plugin marketplace add pocketonehq/pocketone /plugin install pocketone@pocketone ``` `/plugin marketplace update pocketone` picks up new versions. **Other agents that read Agent Skills** (Cursor, Codex, Gemini CLI and others) ```bash npx skills add pocketonehq/pocketone ``` Or copy a skill folder into your project yourself. The skills live in [`agent/skills/`](https://github.com/pocketonehq/pocketone/tree/main/agent/skills). ## llms.txt For agents and tools that read the web: - [pocketone.dev/llms.txt](https://pocketone.dev/llms.txt) indexes every docs page with a one-line summary. - [pocketone.dev/llms-full.txt](https://pocketone.dev/llms-full.txt) holds every docs page in one Markdown file. --- Source: https://pocketone.dev/docs/collections # Collections and fields A collection is a table of records with fields you define, plus its own [API rules](https://pocketone.dev/docs/api-rules) and a [REST API](https://pocketone.dev/docs/rest). Every app starts with two: `_superusers` (who can open the dashboard) and `users` (your app's accounts). You add the rest. ## Three kinds | Kind | What it is | For | |---|---|---| | **Base** | a plain table | posts, orders, settings: anything | | **Auth** | a table whose records can sign in, with email, password, verification and the sign-in methods you turn on | users, customers, staff; see [Authentication](https://pocketone.dev/docs/authentication) | | **View** | a read-only table defined by a SQL `SELECT` over other collections | reports, joins, counts | Every record has an `id` (15 characters, made for you unless you set one). Base and auth collections usually also get `created` and `updated` (autodate fields, added by default in the dashboard). ## Create one in the dashboard Open the dashboard (`/_/`), choose **New collection**, name it, add fields, and save. With automigrate on (the default for `pocketone serve`), saving writes a migration file to `pb_migrations`, so the change goes with your code when you [deploy](https://pocketone.dev/docs/features/deploy) it. See [Migrations](https://pocketone.dev/docs/migrations). ![The dashboard: collections in the sidebar, and the posts collection's records](https://pocketone.dev/docs/screenshots/dashboard-collection-records.jpg) The gear next to a collection's name opens its settings: its fields, its API rules and, for an auth collection, its sign-in options. ![Editing the posts collection: its fields, each with its type and options](https://pocketone.dev/docs/screenshots/dashboard-collection-fields.jpg) ## Create one from code The same collection as a migration, so it's created on every copy of your app: ```ts // pb_migrations/1732300000_create_posts.ts migrate((app) => { const posts = new Collection({ type: "base", name: "posts", listRule: "", // anyone can list viewRule: "", // anyone can view createRule: "@request.auth.id != ''", // signed-in users can create updateRule: "author = @request.auth.id", deleteRule: "author = @request.auth.id", fields: [ { type: "text", name: "title", required: true, max: 200 }, { type: "text", name: "slug" }, { type: "editor", name: "body" }, { type: "relation", name: "author", collectionId: app.findCollectionByNameOrId("users").id, maxSelect: 1 }, { type: "bool", name: "published" }, { type: "autodate", name: "created", onCreate: true }, { type: "autodate", name: "updated", onCreate: true, onUpdate: true }, ], indexes: ["CREATE UNIQUE INDEX idx_posts_slug ON posts (slug)"], }) app.save(posts) }, (app) => { app.delete(app.findCollectionByNameOrId("posts")) }) ``` ```go // migrations/1732300000_create_posts.go func init() { m.Register(func(app core.App) error { users, err := app.FindCollectionByNameOrId("users") if err != nil { return err } posts := core.NewBaseCollection("posts") posts.ListRule = types.Pointer("") posts.ViewRule = types.Pointer("") posts.CreateRule = types.Pointer("@request.auth.id != ''") posts.UpdateRule = types.Pointer("author = @request.auth.id") posts.DeleteRule = types.Pointer("author = @request.auth.id") posts.Fields.Add( &core.TextField{Name: "title", Required: true, Max: 200}, &core.TextField{Name: "slug"}, &core.EditorField{Name: "body"}, &core.RelationField{Name: "author", CollectionId: users.Id, MaxSelect: 1}, &core.BoolField{Name: "published"}, &core.AutodateField{Name: "created", OnCreate: true}, &core.AutodateField{Name: "updated", OnCreate: true, OnUpdate: true}, ) posts.AddIndex("idx_posts_slug", true, "slug", "") return app.Save(posts) }, func(app core.App) error { posts, err := app.FindCollectionByNameOrId("posts") if err != nil { return err } return app.Delete(posts) }) } ``` A rule left unset (`null`, in Go `nil`) means only superusers may do that action; an empty string means anyone may. [API rules](https://pocketone.dev/docs/api-rules) explains the rest. ## Field types | Type | Stores | Options | Reference | |---|---|---|---| | `text` | Any string value. | `help`, `min`, `max`, `pattern`, `autogeneratePattern`, `required`, `primaryKey` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coretextfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#textfield) | | `editor` | HTML formatted text. | `help`, `maxSize`, `convertURLs`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coreeditorfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#editorfield) | | `number` | Numeric (float64) value. | `help`, `min`, `max`, `onlyInt`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#corenumberfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#numberfield) | | `bool` | A single true/false value. | `help`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coreboolfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#boolfield) | | `email` | A single email string address. | `help`, `exceptDomains`, `onlyDomains`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coreemailfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#emailfield) | | `url` | A single URL string value. | `help`, `exceptDomains`, `onlyDomains`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coreurlfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#urlfield) | | `date` | A single types.DateTime value. | `help`, `min`, `max`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coredatefield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#datefield) | | `autodate` | Datetime value could be auto set on record create/update. | `onCreate`, `onUpdate` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coreautodatefield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#autodatefield) | | `select` | Single or multiple string values from a predefined list. | `help`, `values`, `maxSelect`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coreselectfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#selectfield) | | `file` | Record file(s). | `help`, `maxSize`, `maxSelect`, `mimeTypes`, `thumbs`, `protected`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#corefilefield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#filefield) | | `relation` | Single or multiple collection record references. | `help`, `collectionId`, `cascadeDelete`, `minSelect`, `maxSelect`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#corerelationfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#relationfield) | | `json` | Any serialized JSON value. | `help`, `maxSize`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#corejsonfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#jsonfield) | | `geoPoint` | Latitude and longitude GPS coordinates. | `help`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#coregeopointfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#geopointfield) | | `password` | Bcrypt hashed strings (usually used only internally for the "password" auth collection system field). | `help`, `pattern`, `min`, `max`, `cost`, `required` | [JS](https://pocketone.dev/docs/reference/javascript/pocketbase/core/fields#corepasswordfield) · [Go](https://pocketone.dev/docs/reference/go/pocketbase/core/fields#passwordfield) | Every field also has `name`, `hidden` (left out of API answers; superusers still see it) and `presentable` (shown in the dashboard when another record points to this one). A field's value comes back from the API in its natural JSON form: a number for `number`, an array of ids for a multi-relation, file names for `file`. ## Change a collection Load it, change it, save it. Renaming a field keeps its data; removing one drops its column: ```ts // pb_migrations/1732400000_posts_add_summary.ts migrate((app) => { const posts = app.findCollectionByNameOrId("posts") posts.fields.add(new TextField({ name: "summary", max: 300 })) posts.fields.getByName("body").required = true app.save(posts) }, (app) => { const posts = app.findCollectionByNameOrId("posts") posts.fields.removeByName("summary") posts.fields.getByName("body").required = false app.save(posts) }) ``` ```go m.Register(func(app core.App) error { posts, err := app.FindCollectionByNameOrId("posts") if err != nil { return err } posts.Fields.Add(&core.TextField{Name: "summary", Max: 300}) posts.Fields.GetByName("body").(*core.EditorField).Required = true return app.Save(posts) }, func(app core.App) error { posts, err := app.FindCollectionByNameOrId("posts") if err != nil { return err } posts.Fields.RemoveByName("summary") posts.Fields.GetByName("body").(*core.EditorField).Required = false return app.Save(posts) }) ``` Saving a collection checks it first (a relation must point at a real collection, an index must be valid SQL), and fails with the reason if not. ## View collections A view collection is a `SELECT` that the API serves like any other collection, read-only. Its fields come from the query's columns, and it needs an `id` column: ```ts migrate((app) => { app.save(new Collection({ type: "view", name: "posts_per_author", listRule: "", viewQuery: "SELECT author AS id, COUNT(*) AS posts FROM posts GROUP BY author", })) }, (app) => { app.delete(app.findCollectionByNameOrId("posts_per_author")) }) ``` ```go m.Register(func(app core.App) error { view := core.NewViewCollection("posts_per_author") view.ListRule = types.Pointer("") view.ViewQuery = "SELECT author AS id, COUNT(*) AS posts FROM posts GROUP BY author" return app.Save(view) }, func(app core.App) error { view, err := app.FindCollectionByNameOrId("posts_per_author") if err != nil { return err } return app.Delete(view) }) ``` ## Next - [Records](https://pocketone.dev/docs/records): create, find and change the records in a collection. - [API rules and filters](https://pocketone.dev/docs/api-rules): who may list, view, create, update and delete. - [Migrations](https://pocketone.dev/docs/migrations): how collection changes travel with your code. - [`core.Collection`](https://pocketone.dev/docs/reference/javascript/pocketbase/core/records#corecollection): every method, in the JavaScript API ([Go](https://pocketone.dev/docs/reference/go/pocketbase/core/records#collection)). --- Source: https://pocketone.dev/docs/records # Records A record is one row of a [collection](https://pocketone.dev/docs/collections). Clients reach records through the [REST API](https://pocketone.dev/docs/rest); this page is about your own code: a [hook](https://pocketone.dev/docs/hooks), a [route](https://pocketone.dev/docs/routes), a cron job or a migration. In JavaScript the app is `$app` (or `e.app` inside a handler, which is the right one inside a transaction); in Go it's your `app`. In the dashboard, a collection's records are a table you can search and filter; open one to edit it. Saving there runs the same validation and hooks as your code. ![Editing a posts record in the dashboard, with the slug a hook filled in](https://pocketone.dev/docs/screenshots/dashboard-record-edit.jpg) ## Find records ```ts // one by id (throws a not-found error when it doesn't exist) const post = $app.findRecordById("posts", "abc123def456ghi") // many, by filter: collection, filter, sort, limit, offset, params const recent = $app.findRecordsByFilter( "posts", "published = true && created > {:since}", "-created", 20, 0, { since: "2026-01-01 00:00:00" }, ) // the first match, or an error when there's none const bySlug = $app.findFirstRecordByFilter("posts", "slug = {:slug}", { slug: "hello-world" }) // by one field's exact value const sameSlug = $app.findFirstRecordByData("posts", "slug", "hello-world") // how many const drafts = $app.countRecords("posts", $dbx.hashExp({ published: false })) ``` ```go post, err := app.FindRecordById("posts", "abc123def456ghi") recent, err := app.FindRecordsByFilter( "posts", "published = true && created > {:since}", "-created", 20, 0, dbx.Params{"since": "2026-01-01 00:00:00"}, ) bySlug, err := app.FindFirstRecordByFilter("posts", "slug = {:slug}", dbx.Params{"slug": "hello-world"}) sameSlug, err := app.FindFirstRecordByData("posts", "slug", "hello-world") drafts, err := app.CountRecords("posts", dbx.HashExp{"published": false}) ``` The filter is the same language as [API rules](https://pocketone.dev/docs/api-rules) and the API's `?filter=`. **Always pass values as `{:name}` parameters**, never by building the string, so a value can't change the filter's meaning. The sort is a comma list of fields, `-` for descending (`"-created,title"`). A limit of `0` means no limit. Not finding a record is an error (`findRecordById`, `findFirstRecordBy...`), which a route turns into a 404. To check without failing, catch it, or use `findRecordsByFilter` and look at the length. ## Read values `get` returns a field's value as it is; the typed getters convert: ```ts const title = post.getString("title") const views = post.getInt("views") const published = post.getBool("published") const created = post.getDateTime("created") // a DateTime: .time(), .string(), .isZero() const tags = post.getStringSlice("tags") // multi-select, multi-relation, multi-file const meta = post.get("meta") // json: the parsed value const id = post.id ``` ```go title := post.GetString("title") views := post.GetInt("views") published := post.GetBool("published") created := post.GetDateTime("created") tags := post.GetStringSlice("tags") meta := post.Get("meta") id := post.Id ``` An auth record also has `email()`, `verified()` and `validatePassword(password)` (in Go `Email()`, `Verified()`, `ValidatePassword`). ## Create, change and delete ```ts const posts = $app.findCollectionByNameOrId("posts") const post = new Record(posts) post.set("title", "Hello") post.set("author", userId) $app.save(post) // validates, runs hooks, then inserts; post.id is set post.set("title", "Hello again") $app.save(post) // updates $app.delete(post) ``` ```go posts, err := app.FindCollectionByNameOrId("posts") if err != nil { return err } post := core.NewRecord(posts) post.Set("title", "Hello") post.Set("author", userID) if err := app.Save(post); err != nil { return err } post.Set("title", "Hello again") if err := app.Save(post); err != nil { return err } if err := app.Delete(post); err != nil { return err } ``` - **`save` validates first** (required fields, lengths, patterns, unique indexes) and fails with each field's problem. `saveNoValidate` skips that; use it only for data you've already checked. - **Hooks run on every save,** whether the save came from the API, the dashboard or your code. Use `$app.unsafeWithoutHooks().save(record)` (Go `app.UnsafeWithoutHooks().Save`) to skip them, for example inside a hook that would otherwise trigger itself. - **Set a field by its modifier**, as the API does: `post.set("views+", 1)` adds one, `post.set("tags+", "new")` appends, `post.set("tags-", "old")` removes. - **Files:** set a file field to a file made with `$filesystem.fileFromPath`, `fileFromBytes` or `fileFromURL` (Go `filesystem.NewFileFrom...`); saving uploads it to the app's storage ([`$filesystem`](https://pocketone.dev/docs/reference/javascript/pocketbase#filesystem)). ## Relations A relation field holds ids. To get the related records, expand it: ```ts const post = $app.findRecordById("posts", id) $app.expandRecord(post, ["author"], null) const author = post.expandedOne("author") // the users record, or null const authorName = author?.getString("name") // or follow the relation by hand const sameAuthor = $app.findRecordById("users", post.getString("author")) ``` ```go post, err := app.FindRecordById("posts", id) if err != nil { return err } if errs := app.ExpandRecord(post, []string{"author"}, nil); len(errs) > 0 { return fmt.Errorf("expand: %v", errs) } author := post.ExpandedOne("author") ``` `expandedAll(field)` returns the list for a multi-relation. To find the records that point *to* a record (a user's posts), filter on the relation: `findRecordsByFilter("posts", "author = {:id}", ...)`. In the REST API, the same is `?expand=author` and, backwards, `?expand=posts_via_author`. ## Transactions Several saves that must all happen or none: ```ts $app.runInTransaction((txApp) => { const order = new Record(txApp.findCollectionByNameOrId("orders")) order.set("total", 42) txApp.save(order) const stock = txApp.findRecordById("products", productId) stock.set("stock-", 1) txApp.save(stock) // throw (or fail) here and the order isn't saved either }) ``` ```go err := app.RunInTransaction(func(txApp core.App) error { orders, err := txApp.FindCollectionByNameOrId("orders") if err != nil { return err } order := core.NewRecord(orders) order.Set("total", 42) if err := txApp.Save(order); err != nil { return err } stock, err := txApp.FindRecordById("products", productID) if err != nil { return err } stock.Set("stock-", 1) return txApp.Save(stock) }) ``` Inside the function, use `txApp` for everything; `$app` would wait for the transaction's own lock. Keep it short: SQLite allows one writer at a time, so a long transaction holds up every other save. ## Queries and raw SQL For what a filter can't say (joins, aggregates, `GROUP BY`), write the query. The query builder: ```ts const rows = arrayOf(new DynamicModel({ author: "", posts: 0 })) $app.db() .select("author", "COUNT(*) AS posts") .from("posts") .where($dbx.exp("published = {:p}", { p: true })) .groupBy("author") .orderBy("posts DESC") .limit(10) .all(rows) ``` ```go rows := []struct { Author string `db:"author" json:"author"` Posts int `db:"posts" json:"posts"` }{} err := app.DB(). Select("author", "COUNT(*) AS posts"). From("posts"). Where(dbx.NewExp("published = {:p}", dbx.Params{"p": true})). GroupBy("author"). OrderBy("posts DESC"). Limit(10). All(&rows) ``` Or plain SQL, with bound parameters: ```ts const result = new DynamicModel({ total: 0 }) $app.db() .newQuery("SELECT COUNT(*) AS total FROM posts WHERE author = {:author}") .bind({ author: userId }) .one(result) ``` ```go var result struct { Total int `db:"total"` } err := app.DB(). NewQuery("SELECT COUNT(*) AS total FROM posts WHERE author = {:author}"). Bind(dbx.Params{"author": userID}). One(&result) ``` To get records (not plain rows) from a query, start from `$app.recordQuery("posts")` and finish with `.all(records)` on `arrayOf(new Record())`. `$dbx` has the expression helpers: `hashExp`, `exp`, `and`, `or`, `not`, `in`, `like`, `between` and the rest. ## Next - [API rules and filters](https://pocketone.dev/docs/api-rules): the filter language in full. - [Hooks](https://pocketone.dev/docs/hooks): run code when records change. - [`core.Record`](https://pocketone.dev/docs/reference/javascript/pocketbase/core/records#corerecord) and [`core.App`](https://pocketone.dev/docs/reference/javascript/pocketbase/core#coreapp) in the JavaScript API; in Go, [`core.Record`](https://pocketone.dev/docs/reference/go/pocketbase/core/records#record) and [`core.App`](https://pocketone.dev/docs/reference/go/pocketbase/core#app). --- Source: https://pocketone.dev/docs/api-rules # API rules and filters Every [collection](https://pocketone.dev/docs/collections) has five API rules, one per action: **list**, **view**, **create**, **update** and **delete**. A rule decides who may do that action through the [REST API](https://pocketone.dev/docs/rest), and it's written in the same filter language clients use to search. Superusers skip the rules; your own code (`$app.save`, `findRecords...`) isn't checked against them either. ## The three kinds of rule | Rule | Means | |---|---| | unset (`null`, the default; a lock in the dashboard) | only superusers | | empty string `""` | anyone, signed in or not | | a filter, like `author = @request.auth.id` | whoever the filter matches | ![The posts collection's API rules in the dashboard: list, view, create and update rules, and delete for superusers only](https://pocketone.dev/docs/screenshots/dashboard-api-rules.jpg) Set them in the dashboard (the collection's **API rules** tab) or in a migration: ```ts migrate((app) => { const posts = app.findCollectionByNameOrId("posts") posts.listRule = "published = true || author = @request.auth.id" posts.viewRule = "published = true || author = @request.auth.id" posts.createRule = "@request.auth.id != '' && @request.body.author = @request.auth.id" posts.updateRule = "author = @request.auth.id" posts.deleteRule = null // superusers only app.save(posts) }) ``` ```go m.Register(func(app core.App) error { posts, err := app.FindCollectionByNameOrId("posts") if err != nil { return err } posts.ListRule = types.Pointer("published = true || author = @request.auth.id") posts.ViewRule = types.Pointer("published = true || author = @request.auth.id") posts.CreateRule = types.Pointer("@request.auth.id != '' && @request.body.author = @request.auth.id") posts.UpdateRule = types.Pointer("author = @request.auth.id") posts.DeleteRule = nil return app.Save(posts) }, nil) ``` ## How a rule is applied - **List** works as a filter: a client gets only the records the rule matches, never an error. A guest listing `posts` with the rule above sees only published posts. - **View, update and delete** check the one record: if the rule doesn't match, the API answers 404, as if the record weren't there (so it doesn't leak which ids exist). - **Create** checks the record that would be created, built from the request's body. - Auth collections have a sixth rule, **manage**, for records allowed to change another record's email and password (a team admin, say). ## The filter language ``` title ~ 'hello' && (published = true || created > '2026-01-01 00:00:00') ``` | Operator | Means | |---|---| | `=` `!=` | equal, not equal | | `>` `>=` `<` `<=` | greater, less | | `~` `!~` | contains, doesn't contain (a `like`; `%` wildcards allowed) | | `?=` `?!=` `?>` `?~` ... | the same, for any item of a multi-value field ("any tag is ...") | | `&&` `\|\|` `( )` | and, or, grouping | Values are quoted strings (`'text'`), numbers, `true`, `false` or `null`. Dates compare as `'YYYY-MM-DD HH:MM:SS'` strings, in UTC. Fields of related records are reached with dots: `author.verified = true`. ## What a rule can see | Identifier | Is | |---|---| | `@request.auth.*` | the signed-in record: `@request.auth.id` (empty for a guest), `@request.auth.collectionName`, any of its fields (`@request.auth.role = 'admin'`) | | `@request.body.*` | the submitted values (create and update): `@request.body.status`, `@request.body.title:isset = true` | | `@request.query.*` | the URL's query parameters | | `@request.headers.*` | the request's headers, lowercase with `_` for `-` (`@request.headers.x_token`) | | `@request.method`, `@request.context` | the HTTP method; where the request came from (`default`, `oauth2`, `otp`, `password`, `realtime`, `protectedFile`) | | `@collection..*` | another collection's records, matched like a join: `@collection.members.user = @request.auth.id && @collection.members.team = team` | | `@now`, `@today...`, `@yesterday`, `@tomorrow` ... | the current time and date parts (`@todayStart`, `@monthEnd`, `@year`) | Modifiers on a field: | Modifier | Gives | |---|---| | `:isset` | whether the client sent the field (`@request.body.role:isset = false`: may not set `role`) | | `:changed` | whether an update changes it (`@request.body.owner:changed = false`) | | `:length` | the number of items in a multi-value field (`tags:length <= 5`) | | `:each` | applies to every item (`tags:each ~ 'blog-'`) | | `:lower` | compares lowercase (`email:lower = 'ada@example.com'`) | ## Recipes | Who | Rule | |---|---| | anyone | `""` | | any signed-in user | `@request.auth.id != ''` | | signed-in users of one collection | `@request.auth.collectionName = 'customers'` | | only verified users | `@request.auth.verified = true` | | the record's owner | `author = @request.auth.id` | | published, or mine | `published = true \|\| author = @request.auth.id` | | create only as yourself | `@request.auth.id != '' && @request.body.author = @request.auth.id` | | update, but not the owner field | `author = @request.auth.id && @request.body.author:isset = false` | | members of the record's team | `@collection.members.team = team && @collection.members.user = @request.auth.id` | | users with a role | `@request.auth.role = 'editor'` | ## Filters in the API and in code The same language filters lists through the REST API: ```bash curl "http://127.0.0.1:8090/api/collections/posts/records?filter=(title~'hello')&sort=-created" ``` and in your code, where values go in as `{:params}` so they can't change the filter's meaning: ```ts const mine = $app.findRecordsByFilter("posts", "author = {:me} && title ~ {:q}", "-created", 20, 0, { me: userId, q: search, }) ``` ```go mine, err := app.FindRecordsByFilter("posts", "author = {:me} && title ~ {:q}", "-created", 20, 0, dbx.Params{"me": userID, "q": search}) ``` A rule is combined with the client's own `filter` (both must match), so clients can narrow what they may see, never widen it. ## When a rule isn't enough A rule answers "may this request do this to this record?" from data. When the answer needs code (a call to another service, a limit per day, a check that spans many records), write a [hook](https://pocketone.dev/docs/hooks) on the request (`onRecordCreateRequest` and the rest) and throw a `ForbiddenError` there. Request hooks run after the rule: they see only the requests it allows, so the two add up (the rule first, then your code). ## Next - [Authentication](https://pocketone.dev/docs/authentication): how a request gets `@request.auth`. - [Records](https://pocketone.dev/docs/records): filters in your own code. - [Collections and fields](https://pocketone.dev/docs/collections): where rules live. --- Source: https://pocketone.dev/docs/migrations # Migrations Your app's schema (its collections, fields, rules and indexes) lives in its database, but it belongs with your code: the copy on your laptop and the one on your server need the same collections. Migrations are how: small files in `pb_migrations/`, each with an **up** (make the change) and a **down** (undo it), that every copy of the app runs once, in order. ## Automigrate: change the dashboard, get a file With automigrate on (the default for `pocketone serve`), every collection change you save in the dashboard writes a migration file: ``` pb_migrations/ 1732300000_created_posts.js 1732300512_updated_posts.js ``` Commit those files with your code. When the app starts somewhere else, or when you run [`pocketone deploy`](https://pocketone.dev/docs/features/deploy), it applies the ones it hasn't run yet. So the usual flow is: change collections in your local dashboard, then deploy. Turn it off with `--automigrate=false` or `automigrate: false` in [pocketone.yaml](https://pocketone.dev/docs/pocketone-yaml)'s `server` section, for example on a production server where nobody should change collections by hand. ## Write one yourself For seed data, data fixes, or changes you'd rather write than click: ```bash pocketone migrate create seed_categories # pb_migrations/1732400000_seed_categories.js ``` Rename it `.ts` if you like; PocketOne runs TypeScript migrations directly. ```ts // pb_migrations/1732400000_seed_categories.ts migrate((app) => { const categories = app.findCollectionByNameOrId("categories") for (const name of ["News", "Guides", "Releases"]) { const record = new Record(categories) record.set("name", name) app.save(record) } }, (app) => { for (const name of ["News", "Guides", "Releases"]) { const record = app.findFirstRecordByData("categories", "name", name) app.delete(record) } }) ``` ```go // migrations/1732400000_seed_categories.go package migrations import ( "ganigeorgiev.com/pocketbase/pocketbase/core" m "ganigeorgiev.com/pocketbase/pocketbase/migrations" ) func init() { m.Register(func(app core.App) error { categories, err := app.FindCollectionByNameOrId("categories") if err != nil { return err } for _, name := range []string{"News", "Guides", "Releases"} { record := core.NewRecord(categories) record.Set("name", name) if err := app.Save(record); err != nil { return err } } return nil }, func(app core.App) error { for _, name := range []string{"News", "Guides", "Releases"} { record, err := app.FindFirstRecordByData("categories", "name", name) if err != nil { return err } if err := app.Delete(record); err != nil { return err } } return nil }) } ``` - The `app` a migration gets runs inside a transaction: if the up throws, nothing it did is kept. - Files run in the order of their names, which start with a Unix time, so new files run after old ones. - A Go build imports its migrations package (`_ "yourapp/migrations"`) so its files register; they run with the JS ones, in one order. - [Collections and fields](https://pocketone.dev/docs/collections) shows creating and changing collections in a migration. ## Run, undo and inspect ```bash pocketone migrate up # apply every migration not yet applied (serve does this at start) pocketone migrate down 1 # undo the last one pocketone migrate collections # write one file with every collection as it is now (a snapshot) pocketone migrate history-sync # forget applied migrations whose files are gone ``` The app records applied migrations in its `_migrations` table, so each runs once per database. A snapshot (`migrate collections`) is a good way to start over: one file that creates every collection as it is, in place of a long history. Delete the old files, keep the snapshot, and run `history-sync` on each existing copy. ## Extensions bring their own PocketOne's extensions keep their own tables (the LLM ledger, API tokens, bulk mail) with their own migrations, tracked apart from yours. They never appear in `pb_migrations`, and you don't need to copy their schema. ## Next - [Collections and fields](https://pocketone.dev/docs/collections): what migrations change. - [Deploy and live sync](https://pocketone.dev/docs/features/deploy): how migrations reach your server. - [CLI reference](https://pocketone.dev/docs/reference/cli): every `migrate` option. --- Source: https://pocketone.dev/docs/extensions/kv # Key-Value Store **Keep a setting without making a collection.** Your app's title, a feature switch, the prompts your page sends a model, the last time a job ran: each is one value, not a table of records. `$kv` stores it under a name and gives it back: ```ts const settings = $kv.get("storytime/settings") ?? { title: "Story Time", minutes: 10 } ``` ```go var settings Settings found, err := kvv1.Get(app, "storytime/settings", &settings) ``` There's no collection to create and no migration to write. Values live in PocketBase's own `_params` table, beside its settings, so they ride along in every backup. It's built into `pocketone` and on by default. The examples show each thing in TypeScript, as [Pages](https://pocketone.dev/docs/extensions/pages/overview) page code or `pb_hooks`, and in Go. The Go examples use the contract's helpers (`kvv1` is `pocketone.dev/ext/contracts/kv/v1`). ## Read and write values A value is anything JSON can hold: an object, a list, a string, a number, `true` or `false`. ```ts $kv.set("storytime/settings", { title: "Story Time", minutes: 10, voices: ["alloy"] }) const s = $kv.get("storytime/settings") // { title: "Story Time", minutes: 10, voices: ["alloy"] } const none = $kv.get("storytime/nothing") // null: no value under that name $kv.delete("storytime/settings") // no error when there was nothing to delete ``` ```go err := kvv1.Set(app, "storytime/settings", Settings{Title: "Story Time", Minutes: 10}) var s Settings found, err := kvv1.Get(app, "storytime/settings", &s) // found is false, and s untouched, when there's no value err = kvv1.Delete(app, "storytime/settings") ``` Every call is quick and local (one read or write of your app's database), so `$kv` has no `Async` forms. `set` replaces the whole value: to change one field, read the value, change it and set it again. ## Defaults until someone changes them A common shape: ship defaults with your app, and store a value only once someone changes something. ```ts const defaults = { title: "Story Time", minutes: 10 } // read: the stored settings over the defaults const settings = { ...defaults, ...($kv.get("storytime/settings") ?? {}) } // save: only what the form sent $kv.set("storytime/settings", { ...settings, minutes: Number(body.minutes) }) ``` Merging over the defaults means a field you add in a later version gets its default on apps that saved settings before it existed. ## List values Names can share a prefix, and `list` returns every value whose name starts with it, sorted by name: ```ts $kv.list("storytime/") // [{ name: "storytime/settings", value: {...}, created: "2026-11-22T10:00:00Z", updated: "..." }, ...] ``` ```go entries, err := kvv1.List(app, "storytime/") // each has Name, Value (JSON), Created, Updated ``` `$kv.list()` with no prefix returns every value in the store. ## Names A name is 1 to 128 characters: letters, digits and `_ - . : /`, starting with a letter or digit. Start yours with a prefix of your own, such as your app's or extension's name (`storytime/settings`), so they never meet another extension's. A name that breaks these rules throws (in Go, returns `kvv1.ErrInvalidName`). Names starting with `_` are private to Go code on the app. Extensions keep their secrets there (LLM's provider keys are `_llm/settings`): `$kv`, the API and agents can't read, change or list them. A value is at most 1 MiB of JSON. For more than that, or for many similar things you want to filter, sort or let users own, use a collection. ## From outside the app Superusers can read and change values from the API, the `pocketone` command and agents, for example to fix a setting on a live app: ```bash curl -H "Authorization: $TOKEN" "https://app.example.com/api/_c/kv/v1?prefix=storytime/" # list curl -H "Authorization: $TOKEN" "https://app.example.com/api/_c/kv/v1/get?name=storytime/settings" # one value curl -H "Authorization: $TOKEN" -d '{"name":"storytime/settings","value":{"minutes":15}}' \ https://app.example.com/api/_c/kv/v1/set curl -H "Authorization: $TOKEN" -d '{"name":"storytime/settings"}' https://app.example.com/api/_c/kv/v1/delete ``` `$TOKEN` is a superuser's token, or an [API token](https://pocketone.dev/docs/extensions/api-tokens) with the `kv:read` scope (list, get) or `kv` (all four). From your project folder, `pocketone remote kv` does the same on the project's remote: ```bash pocketone remote kv list --prefix storytime/ pocketone remote kv get --name storytime/settings pocketone remote kv set --name storytime/settings --value '{"minutes":15}' # --value @settings.json reads a file pocketone remote kv delete --name storytime/settings ``` Agents get them as MCP tools (`kv_list`, `kv_get`, `kv_set`, `kv_delete`). Users and guests can't reach the store: your page code decides what, if anything, they see. ## Good to know - **Where values live:** the value named `storytime/settings` is the `_params` row with id `kv:storytime/settings`. The `kv:` prefix keeps your names apart from PocketBase's own rows (its `settings`) and from rows other extensions keep there. Read and write through `$kv` or the helpers, never the table. - **Transactions:** the Go helpers take any `core.App`, so inside `app.RunInTransaction` pass the transaction's app and the write is part of it. `$kv`, like `$app`, writes through the main app. - **Turning it off:** `kv: {enabled: false}` in `pocketone.yaml` removes `$kv` and the API. The Go helpers keep working, since they need nothing but the database. ## Next - [Key-Value Store reference](https://pocketone.dev/docs/extensions/kv/extension): the extension's page. - [kv/v1](https://pocketone.dev/docs/contracts/kv/v1): the contract, for extension authors. --- Source: https://pocketone.dev/docs/authentication # Authentication Users sign in to an **auth collection**: a [collection](https://pocketone.dev/docs/collections) whose records have an email, a password and the sign-in methods you turn on. Every app has one, `users`, and `_superusers` for the dashboard; add more for different kinds of account (`customers`, `staff`). Signing in returns a **token**; the client sends it with each request, and the request then knows who it's from: `@request.auth` in [API rules](https://pocketone.dev/docs/api-rules), `e.auth` in [hooks](https://pocketone.dev/docs/hooks) and [routes](https://pocketone.dev/docs/routes). ## Sign-in methods Turn them on per collection, in the dashboard (the collection's **Options**) or in code: ![The users collection's Options: password, OAuth2 and one-time password on, multi-factor off, and its mail templates](https://pocketone.dev/docs/screenshots/dashboard-auth-options.jpg) | Method | The user | Turn on | |---|---|---| | **Password** | enters an email (or another identity field) and a password | `passwordAuth` (on for `users`) | | **One-time code** | asks for a code by email and enters it | `otp` | | **OAuth2** | signs in with Google, GitHub, Apple, Microsoft and many more providers | `oauth2`, with each provider's client id and secret | | **Multi-factor** | signs in with two methods (a password, then a code) | `mfa`, together with two of the above | ```ts // pb_migrations/1732500000_users_signin.ts migrate((app) => { const users = app.findCollectionByNameOrId("users") users.passwordAuth.enabled = true users.passwordAuth.identityFields = ["email"] users.otp.enabled = true users.otp.duration = 300 // a code lasts 5 minutes users.oauth2.enabled = true users.oauth2.providers = [{ name: "google", clientId: $os.getenv("GOOGLE_CLIENT_ID"), clientSecret: $os.getenv("GOOGLE_CLIENT_SECRET"), }] app.save(users) }) ``` ```go m.Register(func(app core.App) error { users, err := app.FindCollectionByNameOrId("users") if err != nil { return err } users.PasswordAuth.Enabled = true users.PasswordAuth.IdentityFields = []string{"email"} users.OTP.Enabled = true users.OTP.Duration = 300 users.OAuth2.Enabled = true users.OAuth2.Providers = []core.OAuth2ProviderConfig{{ Name: "google", ClientId: os.Getenv("GOOGLE_CLIENT_ID"), ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"), }} return app.Save(users) }, nil) ``` ## Sign in from a client With the JavaScript SDK (`npm install pocketbase`, it works with PocketOne unchanged): ```js import PocketBase from "pocketbase" const pb = new PocketBase("https://myapp.example.com") // password await pb.collection("users").authWithPassword("ada@example.com", "a long password") // one-time code: ask, then enter the code from the email const { otpId } = await pb.collection("users").requestOTP("ada@example.com") await pb.collection("users").authWithOTP(otpId, "123456") // OAuth2: opens the provider's sign-in in a popup await pb.collection("users").authWithOAuth2({ provider: "google" }) pb.authStore.isValid // true pb.authStore.record // the signed-in user pb.authStore.token // sent with every request from now on ``` The same over HTTP: ```bash curl -X POST http://127.0.0.1:8090/api/collections/users/auth-with-password \ -H "Content-Type: application/json" \ -d '{"identity": "ada@example.com", "password": "a long password"}' # {"token": "eyJhbGciOi...", "record": {"id": "...", "email": "ada@example.com", ...}} curl http://127.0.0.1:8090/api/collections/posts/records \ -H "Authorization: eyJhbGciOi..." ``` When `authWithOAuth2` finishes, the popup shows a short "Authentication completed" or "Authentication failed" page from the app and closes itself. If the sign-in came back from a different IP than the one that started it (a phone switching from Wi-Fi to cellular, say), the popup first shows both IPs and asks the user to confirm or cancel. These pages are built into PocketBase: their wording and look can't be changed, and `pocketone template eject` doesn't reach them. To show your own pages, skip the popup: send the user to the provider's `authURL` with a redirect URL your app serves, and exchange the `code` there with `authWithOAuth2Code` (see [OAuth2](https://pocketone.dev/docs/rest/authentication#oauth2) in the REST API). Tokens expire (after 7 days for `users`, set per collection); `authRefresh` swaps a valid token for a fresh one. In [Pages](https://pocketone.dev/docs/extensions/pages), sign-in works through a cookie instead: see [Sign users in on your pages](https://pocketone.dev/docs/extensions/pages/authentication). ## Sign up, verify, reset - **Sign up** is a create on the auth collection (`pb.collection("users").create({ email, password, passwordConfirm })`), allowed by its create rule (empty for `users`: anyone may sign up). - **Verify an email:** `requestVerification(email)` sends a link; the user's `verified` field turns true when they open it. Require it in rules with `@request.auth.verified = true`. - **Reset a password:** `requestPasswordReset(email)` sends a link to a page where the user picks a new one. - **Change an email:** `requestEmailChange(newEmail)` sends a confirmation to the new address. The emails' wording and links are set per collection (**Options** → mail templates), and they're sent through the app's SMTP settings. ## Multi-factor auth With `mfa` on, signing in with one method answers `401` with an `mfaId`; the client then signs in with a second method, passing it: ```js try { await pb.collection("users").authWithPassword(email, password) } catch (err) { const mfaId = err.response?.mfaId if (!mfaId) throw err const { otpId } = await pb.collection("users").requestOTP(email) await pb.collection("users").authWithOTP(otpId, codeFromUser, { mfaId }) } ``` ## The signed-in user in your code In a hook or route, `e.auth` is the record that signed in, or `null`: ```ts // pb_hooks/me.pb.ts routerAdd("GET", "/api/me", (e) => { if (!e.auth) throw new UnauthorizedError("Sign in first.") return e.json(200, { id: e.auth.id, email: e.auth.email(), collection: e.auth.collection().name, superuser: e.hasSuperuserAuth(), }) }) ``` ```go se.Router.GET("/api/me", func(e *core.RequestEvent) error { if e.Auth == nil { return e.UnauthorizedError("Sign in first.", nil) } return e.JSON(200, map[string]any{ "id": e.Auth.Id, "email": e.Auth.Email(), "collection": e.Auth.Collection().Name, "superuser": e.HasSuperuserAuth(), }) }) ``` `$apis.requireAuth()` on a route does the check for you ([Custom routes](https://pocketone.dev/docs/routes#require-sign-in)). To sign a user in from your own route (a magic link, a code from another system), find the record and answer with a token: ```ts // pb_hooks/magic.pb.ts routerAdd("POST", "/api/magic/{code}", (e) => { const link = e.app.findFirstRecordByData("magic_links", "code", e.request.pathValue("code")) const user = e.app.findRecordById("users", link.getString("user")) e.app.delete(link) // one use return $apis.recordAuthResponse(e, user, "magic") }) ``` ```go se.Router.POST("/api/magic/{code}", func(e *core.RequestEvent) error { link, err := e.App.FindFirstRecordByData("magic_links", "code", e.Request.PathValue("code")) if err != nil { return e.NotFoundError("", err) } user, err := e.App.FindRecordById("users", link.GetString("user")) if err != nil { return err } if err := e.App.Delete(link); err != nil { return err } return apis.RecordAuthResponse(e, user, "magic", nil) }) ``` The answer is the same `{token, record}` as a password sign-in, so the SDK's auth store takes it as is. ## Impersonation A superuser can get a token for any user, to see the app as they do (support cases). In the dashboard, open the record and choose **Impersonate**; over the API, `POST /api/collections/users/impersonate/{id}` with a superuser's token. The token can't be refreshed and lasts as long as you ask (`duration`, in seconds). ## Tokens for scripts and other apps A user's sign-in token is for that user's session. For a script, a server or another app that calls yours, give it an [API token](https://pocketone.dev/docs/features/tokens): named, scoped to what it may do, and revoked one by one. ## Next - [API rules and filters](https://pocketone.dev/docs/api-rules): `@request.auth` in rules. - [API tokens and OAuth](https://pocketone.dev/docs/features/tokens): access for scripts, apps and agents. - [Sign users in on your pages](https://pocketone.dev/docs/extensions/pages/authentication): sessions in a Pages site. - [Let users sign in with Google](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2): the provider setup, step by step. --- Source: https://pocketone.dev/docs/features/tokens # API tokens and OAuth A script, a CI job or another service can't type a password. Give it an API token instead: a long secret that starts with `pbt_`, acts as the account that owns it, and can be limited to a few scopes and given an expiry. Revoke it, and it stops working at once. This is on for every PocketOne app. You don't need to set anything up. Ordinary PocketBase sign-ins keep working as before. ## Create a token in the dashboard 1. Sign in to the dashboard as a superuser and open **Settings → API tokens** (under **Access**). 2. Fill in a **Name**, so you can recognize the token later. 3. Optionally set **Expires in (days)**. Leave it empty and the token never expires. 4. Tick the **Scopes** the token needs. Tick none and it gets its owner's full rights. 5. The token is yours by default. To make one for another account, fill in **Owner collection** and **Owner (id or email)**. 6. Click **Create token**, then copy it. It's shown only once and never stored. Send it with each request: ```bash curl -H "Authorization: Bearer pbt_…" https://myapp.example.com/api/collections/notes/records ``` ## See and revoke tokens The same screen lists every token: its name, its first characters, owner, scopes, expiry and when it was last used (time and IP). Click **Revoke** and confirm to delete one. Anything using it stops working at once. ## Let apps and tools sign in Some clients sign in for you instead of asking for a pasted token: `pocketone login`, Claude and other [AI agents](https://pocketone.dev/docs/features/mcp), or an app of your own. They send you to your app's own sign-in pages: 1. Sign in with whatever the collection allows: a password, an emailed code, or (for app users) Google and other providers, plus a second step if the account has MFA. Click **Sign in as a superuser** to sign in as one. 2. The consent page names the client and the account it will act as. Choose **Full access**, or **Only these** and tick the scopes it may use. 3. Click **Allow**. On a machine with no browser (over SSH, say), the client shows a code instead. Open `https:///api/_c/oauth/v1/device/verify`, enter it under **Connect a device**, sign in and allow. Codes last 10 minutes. Each sign-in becomes an API token named ` (OAuth)`, bound to exactly what you approved. It shows up under **Settings → API tokens** with an `oauth: ` label. Click **Revoke** to disconnect the client. `pocketone logout` revokes a browser login from your terminal. ## From your terminal On the machine that runs the app, the `token` command works on the app's data folder, even before the first serve: ```bash pocketone token create --superuser admin@example.com --name ci --scope deploy --ttl 720h # prints the secret pocketone token create --collection users --record user@example.com --name script pocketone token list pocketone token revoke pocketone token revoke --all --superuser admin@example.com ``` `--scope` can be repeated. Without `--ttl` the token never expires. For CI that runs `pocketone` against your app, put the token in `P1_TOKEN` instead of signing in ([Remote CLI](https://pocketone.dev/docs/features/remote)). To let an app of your own sign people in, register it once: ```bash pocketone oauth clients add --name "My app" --redirect https://myapp.example.com/callback ``` It prints the client id, and a secret once. Add `--public` for a desktop or mobile app with no secret. Claude, the `pocketone` CLI and other MCP clients don't need this. ## From pb_hooks Add your own scopes, and they show up in the dashboard and on the consent page: ```js // pb_hooks/scopes.pb.js $apiTokens.registerScope({ name: 'notes:read', description: 'Read notes', paths: ['/api/collections/notes/records'], methods: ['GET'] }) routerAdd('GET', '/api/notes/summary', (e) => { /* ... */ }, $apis.requireAuth(), $apiTokens.requireScope('notes:read')) ``` A collection rule can check a scope too: `@request.headers.x_token_scope_notes_read = "1"`. A scope can also limit a token to some records. Register it with `values: { description: 'a note id' }`, and a token can hold `notes=abc123` instead of all of `notes`. Your route checks the record with `$apiTokens.hasScope(e, 'notes', id)`. In the dashboard, a ticked scope that takes values has a box for them; leave it empty for every value. ## What a token can do - **No scopes:** everything its owner can do. - **With scopes:** only the requests its scopes cover. Anything else gets `403`. - **Which scopes:** the ones features add (`deploy`, and one for each admin feature, often with a `:read` version, such as `restore` and `restore:read`), plus your own. Some, like `deploy`, only superusers can hold. The [CLI reference](https://pocketone.dev/docs/reference/cli) and [MCP reference](https://pocketone.dev/docs/reference/mcp) name the scope each operation needs. - **Expiry:** never, unless you set one. Tokens from a sign-in last 30 days, and the client renews them; AI agents' tokens never expire. Expired tokens are deleted once a day. - **Gone with the account:** deleting an account deletes its tokens. - **No way around a revoke:** a token can't be traded for a PocketBase auth token, so revoking it really ends its access. Only superusers see **Settings → API tokens**. Other signed-in users manage their own tokens through the [token API](https://pocketone.dev/docs/contracts/api-tokens/v1). A token with scopes can only create tokens within those scopes. ## Change it or turn it off There's no `pocketone.yaml` key for API tokens: they're always on, and a token does nothing until someone creates one. To limit what a token can do, give it scopes and an expiry, or revoke it. Every key is in the [pocketone.yaml reference](https://pocketone.dev/docs/config-reference). To restyle the sign-in pages, copy them into your app with `pocketone template eject oauth`. ## How it works - [API Tokens](https://pocketone.dev/docs/extensions/api-tokens) stores the tokens (only a hash of each secret), checks them on every request and adds the dashboard screen. - [OAuth server](https://pocketone.dev/docs/extensions/api-tokens/oauth) runs the sign-in and consent pages and issues tokens for what you approved. - They answer the [api-tokens/v1](https://pocketone.dev/docs/contracts/api-tokens/v1) and [oauth/v1](https://pocketone.dev/docs/contracts/oauth/v1) contracts. - [Templates](https://pocketone.dev/docs/extensions/templates) lets you restyle the sign-in pages. --- Source: https://pocketone.dev/docs/hooks # Hooks A hook is a function your app calls when something happens: a record is about to be created, a request asks for a list, an email is about to go out, the app starts. Your function sees the event, can change it or stop it, and then lets it go on. Hooks are how you add rules, side effects and integrations without changing PocketOne itself. In JavaScript, hooks live in `pb_hooks/*.pb.ts` files, which PocketOne loads at start and reloads when they change. In Go, you bind them on your `app` in your own build. The examples on this page show both. ## Your first hook Make `pb_hooks/posts.pb.ts` in your app folder: ```ts // pb_hooks/posts.pb.ts onRecordCreate((e) => { e.record.set("slug", slugify(e.record.getString("title"))) e.next() }, "posts") function slugify(s: string): string { return s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") } ``` ```go app.OnRecordCreate("posts").BindFunc(func(e *core.RecordEvent) error { e.Record.Set("slug", slugify(e.Record.GetString("title"))) return e.Next() }) ``` Create a post (in the dashboard, or with `POST /api/collections/posts/records`) and it's saved with a slug. Three things in that example hold for every hook: - **The handler gets the event** (`e`): here the record being created, the app (`e.app`), and for request hooks the request and who made it. - **`e.next()` lets the event go on**: to the next handler, then to the action itself. Code before `e.next()` runs before the action (the record isn't saved yet); code after it runs once the action is done. - **Tags narrow a hook**: `"posts"` makes it run only for that collection. Pass several (`"posts", "pages"`), or none for every collection. PocketOne runs `.pb.ts` files directly, with no build step, and writes the whole JS API's types to `types.d.ts` next to `pb_hooks`, so your editor completes `e.record.` and flags mistakes. See [QuickJS hooks](https://pocketone.dev/docs/quickjs) for imports, async handlers, shared state and limits. ## Stop or change an action Throw an error before `e.next()` and the action doesn't happen. In a hook triggered by an API request, the client gets the error: ```ts // pb_hooks/posts.pb.ts onRecordCreateRequest((e) => { if (e.record.getString("title").length < 3) { throw new BadRequestError("A title needs at least 3 characters.") } e.next() }, "posts") ``` ```go app.OnRecordCreateRequest("posts").BindFunc(func(e *core.RecordRequestEvent) error { if len(e.Record.GetString("title")) < 3 { return e.BadRequestError("A title needs at least 3 characters.", nil) } return e.Next() }) ``` The client gets `400` with `{"message": "A title needs at least 3 characters."}`. Change the event instead, and the action goes on with your change: set a field on `e.record`, or filter what a list request returns. ## Before and after: which hook to use Record hooks come in layers. Pick the one that matches when your code should run: | You want to | Hook | Runs for | |---|---|---| | Fill in or check fields on every save, from anywhere (API, dashboard, your own code) | `onRecordCreate`, `onRecordUpdate`, `onRecordDelete`, `onRecordValidate` | every save | | Do something once a save has really happened (send a mail, call a webhook) | `onRecordAfterCreateSuccess`, `onRecordAfterUpdateSuccess`, `onRecordAfterDeleteSuccess` | every save, after the transaction commits | | Clean up when a save failed | `onRecordAfterCreateError` (and Update, Delete) | every failed save | | Act on what a client asked for (check who's asking, change the input, change the answer) | `onRecordCreateRequest`, `onRecordUpdateRequest`, `onRecordDeleteRequest`, `onRecordViewRequest`, `onRecordsListRequest` | API requests only | | Change how a record looks in every API answer (hide or add a field per user) | `onRecordEnrich` | every record the API returns, realtime included | The model hooks (`onModelCreate` and the rest) are the same layers for anything saved, collections and logs included. Collections have their own (`onCollectionCreate`...). A side effect like sending mail belongs in an `AfterSuccess` hook: a plain `onRecordCreate` runs inside the save's transaction, so if something later fails, the record is rolled back but your mail already went out. ```ts // pb_hooks/welcome.pb.ts onRecordAfterCreateSuccess((e) => { const message = new MailerMessage({ from: { address: e.app.settings().meta.senderAddress, name: e.app.settings().meta.senderName }, to: [{ address: e.record.email() }], subject: "Welcome!", html: "

Thanks for signing up.

", }) e.app.newMailClient().send(message) e.next() }, "users") ``` ```go app.OnRecordAfterCreateSuccess("users").BindFunc(func(e *core.RecordEvent) error { message := &mailer.Message{ From: mail.Address{Address: e.App.Settings().Meta.SenderAddress, Name: e.App.Settings().Meta.SenderName}, To: []mail.Address{{Address: e.Record.Email()}}, Subject: "Welcome!", HTML: "

Thanks for signing up.

", } if err := e.App.NewMailClient().Send(message); err != nil { e.App.Logger().Error("welcome mail", "error", err) } return e.Next() }) ``` ## Who's asking Request hooks know who made the request. `e.auth` is the signed-in record, or `null` for a guest; superusers are records of the `_superusers` collection. Request hooks run after the collection's [API rule](https://pocketone.dev/docs/api-rules) has let the request through, so this hook decides only with a rule that lets guests in (an empty create rule); with a rule like `@request.auth.id != ''`, the rule turns guests away first: ```ts // pb_hooks/posts.pb.ts onRecordCreateRequest((e) => { if (!e.auth) { throw new UnauthorizedError("Sign in to post.") } if (!e.hasSuperuserAuth()) { e.record.set("author", e.auth.id) // members can't post as someone else } e.next() }, "posts") ``` ```go app.OnRecordCreateRequest("posts").BindFunc(func(e *core.RecordRequestEvent) error { if e.Auth == nil { return e.UnauthorizedError("Sign in to post.", nil) } if !e.HasSuperuserAuth() { e.Record.Set("author", e.Auth.Id) } return e.Next() }) ``` Most "who may do what" rules don't need a hook at all: [API rules](https://pocketone.dev/docs/api-rules) express them as filters on the collection. Use a hook when the rule needs code. ## The app's own events Hooks with no record cover the app's life and its other parts: | Hook | When | |---|---| | `onBootstrap` | the app starts and opens its database (after `e.next()` it's open) | | `onServe` | the HTTP server starts (Go builds add routes here) | | `onTerminate` | the app stops | | `onMailerSend` | any email is about to go out (change it, or stop it) | | `onRealtimeConnectRequest`, `onRealtimeSubscribeRequest`, `onRealtimeMessageSend` | realtime clients connect, subscribe and get messages | | `onBackupCreate`, `onBackupRestore` | a backup is made or restored | | `onSettingsReload` | the app's settings change | Every hook, with its event's type, is in the [hooks table](https://pocketone.dev/docs/reference/javascript/pocketbase#hooks) of the JavaScript API, and on [`core.App`](https://pocketone.dev/docs/reference/go/pocketbase/core#app) in Go. ## Order and errors - Handlers run in the order they were bound: within a file from top to bottom, files in alphabetical order. In Go, `Bind(&hook.Handler{Id: "...", Priority: -10, Func: ...})` runs a handler earlier (lower first) and gives it an id you can `Unbind`. - A handler that doesn't call `e.next()` stops the chain: later handlers and the action don't run. That's how you skip an action without an error. Most hooks should call it. - An error thrown in a request hook becomes the response (`BadRequestError` is 400, `ForbiddenError` 403, `NotFoundError` 404, `UnauthorizedError` 401, `TooManyRequestsError` 429). Any other error is a 400 with a generic message, and its own text goes to the logs, so clients never see internals. An error in a model hook fails the save, and the request that caused it. ## When hooks reload PocketOne watches `pb_hooks`. Change a file and the app's JavaScript restarts with the new code, in a moment, without dropping the database or other requests. In development (`pocketone serve --dev`), a file with an error is skipped and logged, so the rest keep working; in production the app stops on it, so a broken deploy shows up at once. A Go build picks up hook changes when you rebuild and restart it. ## Next - [Custom routes](https://pocketone.dev/docs/routes): add your own API endpoints. - [QuickJS hooks](https://pocketone.dev/docs/quickjs): imports, `async` handlers, shared state, memory and time limits. - [Records](https://pocketone.dev/docs/records): read and write records from a hook. - [JavaScript API](https://pocketone.dev/docs/reference/javascript/pocketbase): every global, hook and type. --- Source: https://pocketone.dev/docs/routes # Custom routes Your app already serves the [REST API](https://pocketone.dev/docs/rest) for its collections. A custom route adds an endpoint of your own: a webhook receiver, a report, a search that joins three collections, anything that isn't plain record CRUD. In JavaScript, add routes with `routerAdd` in a `pb_hooks/*.pb.ts` file. In Go, add them in an `onServe` hook. ## A first route ```ts // pb_hooks/hello.pb.ts routerAdd("GET", "/api/hello/{name}", (e) => { const name = e.request.pathValue("name") return e.json(200, { message: `Hello, ${name}!` }) }) ``` ```go app.OnServe().BindFunc(func(se *core.ServeEvent) error { se.Router.GET("/api/hello/{name}", func(e *core.RequestEvent) error { name := e.Request.PathValue("name") return e.JSON(200, map[string]string{"message": "Hello, " + name + "!"}) }) return se.Next() }) ``` ```bash curl http://127.0.0.1:8090/api/hello/Ada # {"message":"Hello, Ada!"} ``` - **Methods:** `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, or `*` for any. - **Paths:** `{name}` matches one segment, `{path...}` the rest of the path. API routes usually go under `/api/` (but not `/api/collections/`, which is the built-in API's), with a prefix of your own so they never meet a future one. - A route's answer is whatever the handler returns: `e.json`, `e.string`, `e.html`, `e.redirect`, `e.noContent`, `e.blob`, or `e.stream`. To serve HTML pages for people, rather than an API, [Pages](https://pocketone.dev/docs/extensions/pages) is usually the better fit: a file per route, with templates. ## Read the request ```ts // pb_hooks/feedback.pb.ts routerAdd("POST", "/api/feedback", (e) => { const data = new DynamicModel({ message: "", rating: 0 }) e.bindBody(data) // JSON, form or multipart const info = e.requestInfo() const page = info.query["page"] // ?page=... if (data.message.trim() === "") { throw new BadRequestError("Write a message first.") } const record = new Record(e.app.findCollectionByNameOrId("feedback")) record.set("message", data.message) record.set("rating", data.rating) record.set("page", page) e.app.save(record) return e.json(201, { id: record.id }) }) ``` ```go se.Router.POST("/api/feedback", func(e *core.RequestEvent) error { data := struct { Message string `json:"message" form:"message"` Rating int `json:"rating" form:"rating"` }{} if err := e.BindBody(&data); err != nil { return e.BadRequestError("Couldn't read the body.", err) } page := e.Request.URL.Query().Get("page") if strings.TrimSpace(data.Message) == "" { return e.BadRequestError("Write a message first.", nil) } collection, err := e.App.FindCollectionByNameOrId("feedback") if err != nil { return err } record := core.NewRecord(collection) record.Set("message", data.Message) record.Set("rating", data.Rating) record.Set("page", page) if err := e.App.Save(record); err != nil { return err } return e.JSON(201, map[string]string{"id": record.Id}) }) ``` - `e.requestInfo()` has the request's `query`, `headers`, `body` (already parsed) and `auth` in one object. - `e.request` is the underlying HTTP request: `e.request.pathValue(...)`, `e.request.header.get(...)`, `e.request.method`. - Saving through `e.app.save` runs your [hooks](https://pocketone.dev/docs/hooks) and validation, as any other save does. ## Require sign-in Routes are open to anyone unless you say otherwise. Add a middleware after the handler: ```ts // pb_hooks/me.pb.ts routerAdd("GET", "/api/me/summary", (e) => { const posts = e.app.countRecords("posts", $dbx.hashExp({ author: e.auth.id })) return e.json(200, { email: e.auth.email(), posts }) }, $apis.requireAuth()) ``` ```go se.Router.GET("/api/me/summary", func(e *core.RequestEvent) error { posts, err := e.App.CountRecords("posts", dbx.HashExp{"author": e.Auth.Id}) if err != nil { return err } return e.JSON(200, map[string]any{"email": e.Auth.Email(), "posts": posts}) }).Bind(apis.RequireAuth()) ``` | Middleware | Lets through | |---|---| | `$apis.requireAuth()` | any signed-in record; `requireAuth("users")` only records of those collections | | `$apis.requireSuperuserAuth()` | superusers | | `$apis.requireSuperuserOrOwnerAuth("id")` | superusers, or the record whose id is the `{id}` path parameter | | `$apis.requireGuestOnly()` | requests with no auth (a sign-up form) | | `$apis.bodyLimit(bytes)` | bodies up to that size | | `$apis.gzip()` | (compresses the answer) | A client signs in through the [Authentication](https://pocketone.dev/docs/authentication) API and sends its token in the `Authorization` header; `e.auth` is then that record. ## Middleware of your own A middleware is a function that takes the event and calls `e.next()` to go on. Pass it to one route, or to all of them with `routerUse`: ```ts // pb_hooks/timing.pb.ts routerUse((e) => { const start = Date.now() e.next() e.app.logger().info("request", "path", e.request.url.path, "ms", Date.now() - start) }) ``` ```go se.Router.BindFunc(func(e *core.RequestEvent) error { start := time.Now() err := e.Next() e.App.Logger().Info("request", "path", e.Request.URL.Path, "ms", time.Since(start).Milliseconds()) return err }) ``` In Go, `se.Router.Group("/api/shop")` makes a group whose routes share middleware. ## Errors Throw one of the API errors and the client gets its status and message as JSON: | Throw (JS) | Return (Go) | Status | |---|---|---| | `new BadRequestError(message, data?)` | `e.BadRequestError(message, err)` | 400 | | `new UnauthorizedError(message)` | `e.UnauthorizedError(message, err)` | 401 | | `new ForbiddenError(message)` | `e.ForbiddenError(message, err)` | 403 | | `new NotFoundError(message)` | `e.NotFoundError(message, err)` | 404 | | `new TooManyRequestsError(message)` | `e.TooManyRequestsError(message, err)` | 429 | | `new ApiError(status, message, data?)` | `router.NewApiError(status, message, data)` | any | ```json { "status": 400, "message": "Write a message first.", "data": {} } ``` Any other error becomes a 400 with a generic message; its real text goes to the app's logs, so internals never reach clients. A record that isn't found (`findRecordById` on a missing id) becomes a 404. ## Next - [Hooks](https://pocketone.dev/docs/hooks): run code on the built-in API's events instead. - [Records](https://pocketone.dev/docs/records): find and save records from a route. - [Calling other services](https://pocketone.dev/docs/reference/javascript/pocketbase#http): `$http.send` for webhooks out. - [JavaScript API](https://pocketone.dev/docs/reference/javascript/pocketbase): `routerAdd`, `$apis` and the request event's every method. --- Source: https://pocketone.dev/docs/quickjs # QuickJS hooks: async, import and TypeScript PocketOne runs your `pb_hooks` and `pb_migrations` on [QuickJS](https://pocketone.dev/docs/extensions/jsvm) instead of goja, the engine stock PocketBase uses. It's the same JS API (`$app`, `routerAdd`, `onRecordCreate`, `cronAdd`, `$http`, …), so your existing hooks run unchanged. On top of that you get: - **Shared globals.** Top-level helpers and state are visible to every handler. - **Imports.** ES modules with `import`/`export`, and `node_modules` packages. - **TypeScript.** `.ts` hooks run directly. - **Async.** Handlers can `await`, and the app keeps serving other requests while they wait. - **Limits.** A runaway script stops with an error instead of taking the app down. Each app gets one QuickJS VM. The engine is pure Go, so builds need no cgo, as with stock PocketBase. This tutorial builds a small app that tries each of these. Every example below was run on `pocketone`, and the outputs are real. ## Set up Make a folder for the app, create a superuser, and start it: ```bash mkdir -p qjs/pb_hooks/lib && cd qjs pocketone superuser upsert admin@example.com password --dir=pb_data pocketone serve --dir=pb_data ``` Leave it running. PocketOne watches `pb_hooks`, so each file you add below is picked up without a restart. ## 1. Your PocketBase hooks run unchanged Here's a hook written for stock PocketBase, with `require()` inside the handler and the global `$app`: ```js // pb_hooks/legacy.pb.js routerAdd("GET", "/legacy", (e) => { const util = require(`${__hooks}/lib/util.cjs`) return e.json(200, { shout: util.shout("hello"), users: $app.countRecords("users") }) }) ``` ```js // pb_hooks/lib/util.cjs module.exports = { shout: (s) => s.toUpperCase() + "!" } ``` ```bash curl http://127.0.0.1:8090/legacy # {"shout":"HELLO!","users":0} ``` A plain `.pb.js` file is still a CommonJS script, as in PocketBase. Nothing in it needs to change. ## 2. Top-level code is shared by every handler On goja, each handler runs in a separate runtime from a pool, so it can't see the variables at the top of its own file. That's why PocketBase hooks call `require()` inside every handler. On QuickJS, every hook file runs in the app's one global scope: ```js // pb_hooks/counter.pb.js let hits = 0 function greet(name) { return `hi ${name}` } routerAdd("GET", "/hits", (e) => { hits++ return e.json(200, { hits, msg: greet("there") }) }) ``` ```bash curl http://127.0.0.1:8090/hits # {"hits":1,"msg":"hi there"} curl http://127.0.0.1:8090/hits # {"hits":2,"msg":"hi there"} ``` The same file on goja (`pocketone serve --jsvm goja`) answers every request with a 400, because the handler can't see `hits` or `greet`. Globals live as long as the app's VM. A restart or a change to `pb_hooks` starts a fresh one (`hits` goes back to 0), so keep anything that must last in the database. Use globals for caches, helpers and constants. Hook files run before the app opens its database, as in PocketBase. A `$app` query at a file's top level fails, so to fill a global from the database, do it in `onBootstrap`: ```js let users = null onBootstrap((e) => { e.next() // the database is open after this users = e.app.findCollectionByNameOrId("users") }) ``` ## 3. Split your code into modules Name a hook file `.pb.mjs` and it's an ES module, with `import` and `export`: ```js // pb_hooks/lib/slug.mjs export const slugify = (s) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") ``` ```js // pb_hooks/modules.pb.mjs import { slugify } from "./lib/slug.mjs" routerAdd("GET", "/slug/{text}", (e) => { return e.json(200, { slug: slugify(e.request.pathValue("text")) }) }) ``` ```bash curl "http://127.0.0.1:8090/slug/Hello%20World%21" # {"slug":"hello-world"} ``` - `.mjs` files are ES modules; `.js` and `.cjs` files are CommonJS. Both kinds can load each other. - `import` and `require()` find files the same way: relative paths first, then packages in `node_modules`. - A module loads once per app, so every file that imports it shares the same instance and its state. ## 4. Write hooks in TypeScript Name the file `.pb.ts` and write TypeScript: ```ts // pb_hooks/typed.pb.ts interface Total { count: number label: string } function total(count: number): Total { return { count, label: `${count} users` } } routerAdd("GET", "/typed", (e) => { return e.json(200, total(e.app.countRecords("users"))) }) ``` ```bash curl http://127.0.0.1:8090/typed # {"count":0,"label":"0 users"} ``` PocketOne removes the types when it loads the file, with no build step. An error names the line in your `.ts` file. Types aren't checked at run time: run `tsc --noEmit` or rely on your editor. The app writes the whole JS API's types to `types.d.ts` in your project folder, next to `pb_hooks`, and a `tsconfig.json` that uses it if you don't have one ([JSVM page](https://pocketone.dev/docs/extensions/jsvm#types)). ## 5. Async handlers A handler can be `async`. Every Go function has an `.async` twin that does its work outside the VM and returns a promise: ```js // pb_hooks/async.pb.js routerAdd("GET", "/slow", async (e) => { await sleep.async(2000) // waits outside the VM const n = await e.app.countRecords.async("users") return e.json(200, { waited: "2s", users: n }) }) ``` Call `/slow`, and call `/hits` while it waits: ```bash curl http://127.0.0.1:8090/slow & curl http://127.0.0.1:8090/hits ``` `/hits` answered after 0.35 s, and `/slow` after 2.06 s. The app went on serving requests while `/slow` waited. Without `.async`, a call that waits (`$http.send`, `sleep`) still lets other requests run, but those requests nest on one stack and wait on each other: under load, a plain `sleep(100)` served 19 requests a second where `await sleep.async(100)` served 481 ([How it performs](#how-it-performs)). Use `.async` for anything slow. Two things to watch: - After an `await`, other requests may have run in between. Use `e.app`, not the global `$app`. - A transaction holds SQLite's write lock, so keep it short across `await`s. ### Timers `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval` and `queueMicrotask` work as in browsers and Node.js, so code and npm packages that use them run unchanged: ```js // pb_hooks/timers.pb.js routerAdd("GET", "/later", async (e) => { const word = await new Promise((resolve) => setTimeout(resolve, 500, "later")) return e.string(200, word) }) ``` Each run of a timer's callback is a separate task with its own time limits. A thrown error is logged and the app carries on. A timer set while a request is being served belongs to that request: it's cleared once the request has its answer, or when the client goes away. So a callback never writes to a response that's already finished. A handler that streams from a timer stays open by waiting (`await new Promise(() => {})`) until the client leaves. Timers set at the top of a hook file or in a cron job run until cleared. An app can have 1024 timers pending at once. ### Why there's no VM pool goja runs JS synchronously: while a handler waits on the database or an HTTP call, its runtime can't do anything else. To serve requests at the same time, PocketBase keeps a pool of runtimes (15 by default, `--hooksPool`) and makes more when they're all busy. Each runtime loads every hook file separately. That's why a handler can't see the top of its own file, why state can't be shared between requests, and why memory grows with load. QuickJS here works like a Node.js process. Each app has one VM with an event loop. While a handler waits, the loop runs other requests, and the handler picks up again when its result arrives. There's one copy of your code and your globals, so nothing needs a pool (`--hooksPool` is accepted and ignored). As in Node.js, the JS itself runs one piece at a time. A handler that computes for a long time holds the loop until it finishes or hits its time budget. Keep heavy work out of the request path, or move it into Go. ## 6. Memory and time limits Each app has a memory cap, and each task has a time budget: ```js // pb_hooks/limits.pb.js routerAdd("GET", "/hog", (e) => { const junk = [] while (true) junk.push("x".repeat(1024 * 1024)) }) routerAdd("GET", "/spin", (e) => { while (true) {} }) ``` Both requests fail and the app keeps running: | Request | Stopped after | Error in the request log | |---|---|---| | `/hog` | 0.08 s | `InternalError: out of memory at pb_hooks/limits.pb.js:3:36` | | `/spin` | 5.0 s | `InternalError: interrupted at pb_hooks/limits.pb.js:5:27` | Calls to `/hits` right after each one answered normally. These are the limits in the `pocketone` binary: | Limit | What it counts | Default | `js_limits` key | |---|---|---|---| | Memory | The JS heap plus the Go objects JS holds, for the whole app | 64 MiB | `memory` | | JS time | Time spent running JS in one stretch of a task | 5 s | `task_time` | | Wall time | Clock time of one stretch, sync Go calls (`sleep`, `$http.send`, queries) included | 30 s | `task_wall` | | Await time | Clock time of a whole async handler, from its start until it returns, awaits included | 15 min | `await_time` | A stretch is the JS between two `await`s: the start of a handler up to its first `await`, then each part that runs when an awaited result comes back. A handler without `await` is one stretch. JS time and wall time start over with each stretch. While a handler is awaiting an `.async` call (`sleep.async`, `e.app.save.async`, an `$llm` provider call, `$http.send.async`), no JS runs and the VM serves other requests, so the wait counts toward none of the first three limits, only toward await time. So a handler can await a slow provider call for a minute or two, and a loop of awaits can run for several minutes, while a loop that computes without awaiting is still stopped after 5 s: ```js // pb_hooks/long.pb.js routerAdd("GET", "/long", async (e) => { for (let i = 0; i < 6; i++) { await sleep.async(10000) // 60 s in all, none of it JS time } return e.json(200, { waited: "60s" }) }) ``` When a handler passes its await time, or the client goes away (the browser closed the tab, a proxy gave up), the request fails and the handler stops at its next `await`: the result of the call it's waiting for is dropped, the code after the `await` never runs, and a new `.async` call from it throws. Work it handed off with no `await` (a detached promise) keeps running after the handler returns. Change the limits in `pocketone.yaml` ([pocketone.yaml](https://pocketone.dev/docs/pocketone-yaml)): ```yaml app: js_limits: memory: 128MiB # the JS heap plus the Go objects JS holds task_time: 10s # JS time per stretch task_wall: 60s # wall time per stretch, sync Go calls included await_time: 30m # a whole async handler, awaits included ``` With `task_time: 1s`, `/spin` stopped after 1.0 s instead of 5. A custom Go build sets the same limits in `jsvm.Config.VM` ([JSVM](https://pocketone.dev/docs/extensions/jsvm#configure)). On a multisite host each app has its own VM and its own limits, so one app's runaway script doesn't stop the others. ### Jobs that take minutes Await time allows a long request, but the network in front of your app usually doesn't. Cloudflare closes a proxied request after about 100 seconds with no answer, and other proxies and browsers have their own limits. A request that waits through minutes of work gets cut off on the way, and its handler stops with it. For work that takes longer than a few seconds (generating images or audio, a chain of provider calls, a big import), answer at once and do the work in the background: 1. The request saves a record for the job, starts the work without awaiting it, and answers with the record's id. 2. The work saves its progress and results on that record as it goes. 3. The page polls the record (or subscribes to it with realtime) and shows the progress. ```js // pb_hooks/jobs.pb.js routerAdd("POST", "/jobs", (e) => { const job = new Record(e.app.findCollectionByNameOrId("jobs")) job.set("status", "running") e.app.save(job) runJob(e.app, job.id) // no await: it keeps running after this answer return e.json(202, { id: job.id }) }) async function runJob(app, id) { const save = async (fields) => { const job = await app.findRecordById.async("jobs", id) for (const [k, v] of Object.entries(fields)) job.set(k, v) await app.save.async(job) } try { for (let step = 1; step <= 5; step++) { await sleep.async(10000) // stands in for a slow provider call await save({ progress: step * 20 }) } await save({ status: "done" }) } catch (err) { await save({ status: "failed", error: String(err) }) } } ``` The page then reads `/api/collections/jobs/records/` every few seconds until `status` is `done`. A detached job isn't tied to any request, so await time and abandoned requests don't stop it, but it isn't saved anywhere either: a restart (a deploy, a hooks change) ends it. Keep its state on the record, so a job left `running` after a restart can be found and started again (by a `cronAdd` job, say). ## How it performs The same hook file, on the `pocketone` binary with each engine (QuickJS, and `--jsvm goja` with its default pool of 15): ```js // pb_hooks/bench.pb.js routerAdd("GET", "/b/ping", (e) => e.json(200, { ok: true })) routerAdd("GET", "/b/db", (e) => e.json(200, { n: e.app.findRecordsByFilter("_superusers", "id != ''", "", 10, 0).length })) routerAdd("GET", "/b/cpu", (e) => { const items = [] for (let i = 0; i < 2000; i++) items.push({ id: i, name: "item" + i, tags: ["a", "b", "c"] }) return e.json(200, { n: JSON.parse(JSON.stringify(items)).length }) }) routerAdd("GET", "/b/wait", (e) => { sleep(100); return e.json(200, { ok: true }) }) routerAdd("GET", "/b/waitasync", async (e) => { await sleep.async(100); return e.json(200, { ok: true }) }) ``` Each route got 50 concurrent clients for 10 seconds (`hey -c 50 -z 10s`, after a 3-second warm-up), with `--dev=false`, on an Apple M1 Max (10 cores): | Route | QuickJS req/s | p50 | p99 | goja req/s | p50 | p99 | |---|---|---|---|---|---|---| | A JSON reply | 19,471 | 2.2 ms | 9.4 ms | 55,901 | 0.8 ms | 3.3 ms | | A database query (10 rows) | 18,116 | 1.9 ms | 12.8 ms | 40,447 | 0.8 ms | 7.9 ms | | CPU-heavy JS (2,000-object JSON round trip) | 84 | 591 ms | 648 ms | 409 | 91 ms | 525 ms | | Waits 100 ms with `sleep(100)` | 19 | 1.93 s | 12.0 s | 491 | 102 ms | 113 ms | | Waits 100 ms with `await sleep.async(100)` | 481 | 103 ms | 110 ms | – | – | – | | Memory (resident) | QuickJS | goja | |---|---|---| | Idle, after start | 46 MB | 49 MB | | After all the routes above | 313 MB | 3.1 GB | What it shows: - **goja does more requests a second.** Its pool runs handlers on every core at once. QuickJS runs an app's JS on one thread, like Node.js: about 18,000 short requests a second for one app, on one core. - **QuickJS uses a tenth of the memory.** goja's runtimes each hold a copy of every hook file, and it makes more of them as load grows. On a host running many apps, that's the difference that counts. - **Waiting costs nothing with `.async`.** `await sleep.async(100)` kept pace with goja's pool. A plain `sleep(100)` didn't, so use `.async` for anything slow. - **CPU-heavy JS is slower.** Move heavy work into Go, a cron job, or a background task. ## Going back to goja To run an app on PocketBase's own engine, set it in `pocketone.yaml`: ```yaml app: jsvm: goja ``` You can also pass `--jsvm goja`. The startup lines list what that turns off: pages, `$mcp`, `$tokens`, `$bulkmail`, JS contracts, shared globals and async handlers. ## Next - [JSVM](https://pocketone.dev/docs/extensions/jsvm): every file type, module resolution rule and setting. - [Hooks](https://pocketone.dev/docs/hooks) and [Custom routes](https://pocketone.dev/docs/routes): what to write in a hook file. - [JavaScript API](https://pocketone.dev/docs/reference/javascript/pocketbase): every global, hook and type. - [LLM skills for coding agents](https://pocketone.dev/docs/agents): give your agent the PocketOne skill so it writes hooks the QuickJS way. --- Source: https://pocketone.dev/docs/extensions/wasm # WASM **Bring your own WASM.** Your page code is TypeScript, and most of the time that's all you need. Sometimes it isn't: the library you need only exists in Rust or Go, or the work (parsing, image processing, crypto, number crunching) is too slow in JS. WASM lets your page code call code written in another language, compiled to WebAssembly, as if it were a JavaScript function: ```ts const out = await $wasm.run.async<{ greeting: string }>("hello", { name: "pocket" }) // out is { greeting: "Hello, POCKET!" } ``` It's built into `pocketone`. There's nothing to install and nothing to configure: put a module in `pb_hooks/` and call it from your page code. ## How it works A module is a small program compiled to WebAssembly: a `.pb.wasm` file in `pb_hooks/`. A call works like running a command-line tool: 1. Your code calls `$wasm.run.async(name, input)`. 2. The module starts fresh, reads the input, and writes its answer. 3. Your code gets the answer back, parsed from JSON, and carries on. The module runs in a sealed box. It can't touch your database, your files, the network or other programs; it sees only the input your code gives it, and its answer goes only back to your code. Your code stays in charge: it decides what goes in and what to do with what comes out. A module that crashes, loops or runs out of memory fails its own call, and the app goes on. ## Try it in two minutes You don't need a compiler to try it. The Markdown module from the [recipes](https://pocketone.dev/docs/extensions/wasm/recipes/markdown) is kept built in the repository. In your app's folder: ```bash curl -L -o pb_hooks/markdown.pb.wasm \ https://github.com/pocketonehq/pocketone/raw/main/ext/wasm/example/markdown/markdown.pb.wasm ``` Add an API route that saves a note with its Markdown rendered to HTML: ```ts // pb_pages/notes.ts export async function post(ctx: any) { const { body } = ctx.req.body() const note = new Record(ctx.app.findCollectionByNameOrId("notes")) note.load({ body, html: await $wasm.run.async("markdown", body) }) ctx.app.save(note) return ctx.res.json(201, { id: note.id, html: note.getString("html") }) } ``` Make a `notes` collection with two text fields, `body` and `html`, then post a note with `# Hello` and some `**bold**` text in its body: ```bash curl -X POST localhost:8090/notes -H "Content-Type: application/json" -d '{"body":"# Hello\n\nSome **bold** text"}' ``` The saved note's `html` field is the rendered HTML. This module passes raw HTML through, so for text your users write, add [Sanitize HTML](https://pocketone.dev/docs/extensions/wasm/recipes/sanitize-html) after it. ## Write your first module A module is an ordinary program: it reads its input from stdin and prints its answer to stdout. Here's one in Go: ```go // main.go package main import ( "encoding/json" "os" "strings" ) func main() { var in struct { Name string `json:"name"` } json.NewDecoder(os.Stdin).Decode(&in) if in.Name == "" { os.Stderr.WriteString(`{"code":"no_name","message":"say who to greet"}`) os.Exit(1) } json.NewEncoder(os.Stdout).Encode(map[string]string{ "greeting": "Hello, " + strings.ToUpper(in.Name) + "!", }) } ``` Build it into your `pb_hooks/`. Go can build WebAssembly with nothing extra; [TinyGo](https://pocketone.dev/docs/extensions/wasm/languages/tinygo) makes the same program 15 times smaller and much faster to call: ```bash GOOS=wasip1 GOARCH=wasm go build -o pb_hooks/hello.pb.wasm . # Go: 4.3 MB tinygo build -target=wasip1 -opt=z -no-debug -scheduler=none -o pb_hooks/hello.pb.wasm . # TinyGo: 284 KB ``` Call it from an API route: ```ts // pb_pages/hello/[name].ts export async function get(ctx: any) { const out = await $wasm.run.async<{ greeting: string }>("hello", { name: ctx.params.name }) return ctx.res.json(out) } ``` ```bash curl localhost:8090/hello/pocket # {"greeting":"Hello, POCKET!"} ``` That's the whole contract: - **Input:** your code's value arrives on stdin, as JSON (a string or bytes arrive as they are). - **Output:** what the module prints comes back to your code, parsed if it's JSON. - **Errors:** to fail, the module exits non-zero. If it prints `{"code", "message"}` to stderr, your code's `catch` gets those as `err.code` and `err.message`. ## Good to know - **Calls are async.** Use `await $wasm.run.async(...)` in an `async` handler. The module runs off the JS engine, so the rest of your app keeps serving requests while it works. - **Every call starts fresh.** Nothing carries over from one call to the next, so a module can't remember anything. When it needs to, your code keeps the state and passes it in: see [Keeping state in JS](https://pocketone.dev/docs/extensions/wasm/guides/state). - **The first call compiles, later calls don't.** A module's first call compiles it and keeps the result on disk; every later call, after a restart too, loads it from there. A C, Rust or Zig module takes 17 to 33 ms the first time and 1 to 2 ms after; a Go module about a second, then 38 ms. [Choosing a language](https://pocketone.dev/docs/extensions/wasm/languages) compares them. - **Modules deploy with your app.** They live in `pb_hooks/`, so git, `pocketone deploy` and anything else that ships `pb_hooks/` ships them too. Replacing a module's file takes effect on the next call. ## Next - **[Choosing a language](https://pocketone.dev/docs/extensions/wasm/languages):** C and C++, Go, TinyGo, Rust, Zig, AssemblyScript, and what else runs. - **[Recipes](https://pocketone.dev/docs/extensions/wasm/recipes):** modules built on real libraries, each with page code that calls it: Markdown, HTML sanitizing, thumbnails, QR codes, diffs, CSV. - **[Keeping state in JS](https://pocketone.dev/docs/extensions/wasm/guides/state):** modules that work on a series, with the state held by your app. - **[Extension reference](https://pocketone.dev/docs/extensions/wasm/extension):** every call, error code, limit and setting, and how it works inside. --- Source: https://pocketone.dev/docs/extensions/pages # Pages
Pages logo

Pages

brew install pocketonehq/tap/pocketone
pocketone pages create myapp
On Windows? Install with Scoop

No-Build Multi-Page Apps for PocketOne

<!-- pb_pages/index.ets -->
<%= `Hello, PocketOne!` %>
<%- include('browser', { content: 'Hello, PocketOne!' }) %>

Why Pages is Better

Zero compilation, zero bundling, zero build steps. Just write code and deploy, frontend and backend.

Zero Build Steps

No compilation anywhere. Write HTMX, Alpine.js, or VanJS and see changes instantly.

Server-Side Rendered

Pages render on the server using PocketBase JSVM. Fast, SEO-friendly, and reliable.

PocketOne Native

Built into PocketOne: routing and templates in Go, your page code in PocketBase's JS VM. Your data, auth, and APIs are right there.

Why Multi-Page Apps Matter

While SPAs dominate the conversation, MPAs offer proven benefits for most web applications. Pages brings this architecture to PocketBase's powerful backend.

✓ MPA Advantages

  • Instant Page Loads: Server renders HTML, browser shows content immediately
  • SEO by Default: Search engines get fully rendered HTML
  • Progressive Enhancement: Works without JavaScript, enhanced with it
  • Simpler Mental Model: Each URL = one page, like the web was designed
  • Zero Compilation: No build steps anywhere, frontend or backend
pb_pages/users/[id].ets
<% // Server-side data loading in PocketBase JSVM
const user = $app.findRecordById('users', params.id)
%>
<!-- Template renders with live data -->
<%= user.get('name') %> joined <%= user.get('created') %>

PocketBase JSVM Integration

Direct access to your database, authentication, and APIs server-side.

Perfect for No-Build Frontend

Drop in your favorite no-build frontend library and start building. No webpack configs, no bundlers, no compile steps.

htmx

High power tools for HTML

Alpine.js

Minimal framework for HTML

Datastar

Reactive UI with data binding

VanJS

Ultra-lightweight reactive UI

Vanilla JS

Pure JavaScript, no dependencies

HTMX + Pages
<%- include('header.ets') %>
<div hx-get="/fragments/todos"
     hx-trigger="load"
     hx-target="#todo-list">
  Loading todos...
</div>
<div id="todo-list"></div>
Alpine.js + Pages
<div x-data="{ todos: <%= JSON.stringify(todos) %> }">
  <template x-for="todo in todos">
    <div x-text="todo.title"
         :class="{ 'completed': todo.done }">
    </div>
  </template>
</div>
Datastar + Pages
<input type="text" name="message" data-bind:message />
<button data-on:click="@get('/fragments/chat')">
  Send
</button>
<div id="chat-box">
  <% for (const msg of ctx.store('messages')||[]) { %>
    <div><%= msg.message %></div>
  <% } %>
</div>
--- Source: https://pocketone.dev/docs/features/bulk-mail # Bulk mail Got a newsletter, a launch or a change to announce? Write it once, pick which users get it, and your app sends it at a steady pace through its own mail settings. Every message gets an unsubscribe link, and people who unsubscribe, bounce or complain are never mailed again. This is on for every PocketOne app. Nothing is sent until a superuser starts a campaign. ## Before your first campaign 1. Sign in to the dashboard as a superuser and open **Settings → Mail**. Set up your mail server and sender there, as you would for any PocketBase app. Campaigns send through them. 2. Below that form, in the **Bulk mail** section, fill in **Postal address**. It's shown in every campaign footer, and anti-spam laws require one. Click **Save bulk mail settings**. 3. Open **Settings → Application** and check that **Application URL** is the address people reach your app on. Unsubscribe links are built from it. ## Send a campaign from the dashboard 1. Open **Mail** in the dashboard menu and click **New campaign**. It starts as a draft for the verified users of `users`. 2. Fill in **Name**, **Subject** and **Body**. Use `{{record.name}}` (any field of the user's record), `{{email}}` and `{{campaign.name}}` to fill in each message. 3. Under **Audience**, pick who gets it. With **Filter**, choose the **Collection**, an optional **Filter** in the same syntax as API rules (such as `verified = true`), and the **Email field**. Click **Count recipients** to see how many match, how many are suppressed, and a few sample addresses. 4. Click **Save changes**. Click **Preview** to see the message for one recipient, or fill in **Test address** and click **Send test**. 5. Click **Send** and confirm. The campaign page shows its progress and a **Recipients** table. While it runs, you can **Pause**, **Resume** or **Cancel** it. To send later, set **Schedule (UTC)** before you save. The button then says **Schedule**. To send slower than your app's limit, set **Max per second**. For audiences a filter can't express, choose **SQL** and write a read-only `SELECT` that returns an `email` column. Every other column it returns can be used in the message as `{{record.column}}`. A view works too: pick it as the **Collection**. ## Send it again to new users Each address gets a campaign at most once. Click **Send** on a finished campaign and only users who match now but weren't mailed before get it. ## Repeat it To mail the same campaign every week (a reminder, a digest), set **Repeat** to **Every week**, and optionally **Repeat until (UTC)**. When a run starts, the next one is scheduled as a new campaign with the same content, audience and settings, a week after this run's scheduled time. Each run looks up its audience again when it starts, so whoever matches then gets it, including people the last run already mailed, and people who stopped matching (say, they did what the reminder asked) don't. **Next run** on the campaign page opens it. To stop the series, cancel the scheduled run. ## From your terminal Write the campaign in the dashboard first. Then sign in to your app once ([Remote CLI](https://pocketone.dev/docs/features/remote)) and run it from your terminal: ```bash pocketone remote bulkmail preview --campaign # see the message pocketone remote bulkmail test --campaign --to you@example.com pocketone remote bulkmail start --campaign pocketone remote bulkmail pause --campaign # also resume, cancel ``` `--limit 100` on `start` queues at most 100 new recipients, to send a campaign in batches. To see who an audience reaches before you send: ```bash pocketone remote bulkmail count --audience '{"collection": "users", "filter": "verified = true", "email_field": "email"}' ``` ## From pb_hooks `$bulkmail` does the same from your JS hooks: ```js const { count, suppressed } = $bulkmail.count({ collection: "users", filter: "verified = true", email_field: "email" }) $bulkmail.start("CAMPAIGN_ID") $bulkmail.suppress("someone@example.com") ``` ## From an agent An agent connected to your app over [MCP](https://pocketone.dev/docs/reference/mcp) has a tool for each step: `bulkmail_count`, `bulkmail_preview`, `bulkmail_test`, `bulkmail_start`, `bulkmail_pause`, `bulkmail_resume` and `bulkmail_cancel`. Count and preview need a token with the `bulkmail:read` scope, the rest the `bulkmail` scope. Only superusers can run campaigns. ## Unsubscribes, bounces and complaints - **Unsubscribe:** every message ends with a footer holding your postal address and an unsubscribe link. It also carries the one-click unsubscribe headers that Gmail and Yahoo require from bulk senders. Opening the link shows a confirm button, so link scanners can't unsubscribe anyone. - **Suppressions:** **Mail → Suppressions** lists the addresses that never get campaign mail, whatever the audience says. Unsubscribes are added automatically. Click **Add address** to add one by hand, or **Export CSV** to download the list. - **Bounces and complaints:** to add those to the list too, open **Bounces and complaints** in the **Bulk mail** section. For Amazon SES, subscribe your SNS topic to the **Amazon SES (SNS) endpoint** shown there. For other providers, set a **Webhook secret** and point the provider at the **Generic webhook** URL. ## Limits - Your app sends at most **5 messages a second** and **5,000 a day** (UTC), across all campaigns. The **Bulk mail** section shows your app's limits and how many it sent today. A host may set other limits for your app. - A message counts as sent only once the mail server accepts it, so a restart doesn't send twice or skip anyone. - A permanent error from the mail server fails that recipient. Other errors are retried, up to three attempts. - A campaign pauses itself when more than 5% of its sends fail after the first 100, or when spam complaints pass 0.3% of its sends (at least 3). The reason shows next to its status. ## Try it locally In dev mode with SMTP off, `pocketone` catches every mail, campaigns included, in an inbox at http://127.0.0.1:8025: ```bash pocketone serve --dev ``` ## Change it There's no `pocketone.yaml` section for bulk mail; the [pocketone.yaml reference](https://pocketone.dev/docs/config-reference) lists none. Sending uses your **Settings → Mail** server and sender, and you lower the pace per campaign with **Max per second**. ## How it works - [Bulk Mail](https://pocketone.dev/docs/extensions/bulkmail) runs the campaigns, the pages in the dashboard and `$bulkmail`. - [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) is the contract behind the command, the REST API and the MCP tools. - [mail.suppression/v1](https://pocketone.dev/docs/contracts/mail.suppression/v1) keeps the suppression list and the unsubscribe link. - [mail.feedback/v1](https://pocketone.dev/docs/contracts/mail.feedback/v1) takes bounce and complaint reports from your mail provider. --- Source: https://pocketone.dev/docs/extensions/billing # Billing **Billing lets your app sell.** You list products, each with a price at your payment processor and what it grants (`instances: 1`, `seats: 5`). A user checks out, pays on the processor's page, and comes back. Billing keeps every subscription and order in step with the processor, and your code asks one question: what does this user have? ```ts // pb_pages/upgrade.ts: start a checkout and send the browser there module.exports = { async post(ctx) { if (!ctx.auth) return ctx.res.redirect('/login') const { url } = await $billing.checkout.async(ctx.auth, { product: 'pro' }) return ctx.res.redirect(url) }, } ``` ```go // what the user has, from Go ent, err := billing.For(app).Entitlements("users", userId) // ent.Totals["seats"] == 5 ``` ## What you get - **Products** in your app's database, each mapped to a price at one or more processors. - **Checkout** for signed-in users, or for visitors before they have an account (pay first). - **Webhooks** that are checked against the processor: Billing reads each subscription or order back from the processor and writes what it finds, so a webhook that arrives twice or out of order changes nothing. - **Entitlements**: the sum of what each user's active purchases grant, for gating features. - **A Billing page in the dashboard**: products, customers, every item with its actions (cancel, resume, change quantity, refund, sync), manual grants, and webhook errors. - **Customer self-service** through the processor's portal (cards, invoices) and Billing's own cancel, resume, quantity and plan calls. ## Payment processors Billing doesn't take payments itself. A processor extension does, and you install the ones you use: | Processor | Merchant of record | Checkout | |---|---|---| | [Stripe](https://pocketone.dev/docs/extensions/stripe) | You, or Stripe with Managed Payments | Stripe Checkout | | [Paddle](https://pocketone.dev/docs/extensions/paddle) | Paddle | Paddle.js overlay on a page Billing serves | | [Creem](https://pocketone.dev/docs/extensions/creem) | Creem | Creem's hosted checkout | A merchant of record sells to the buyer in its own name: it collects and files sales tax and VAT and handles disputes. Several processors can be installed at once; one takes new checkouts and the others keep renewing what was sold through them. See [Payment processors](https://pocketone.dev/docs/extensions/billing/processors). ## Not in the stock binary Billing and its processors are community extensions. The `pocketone` binary you install doesn't include them, so an app that sells is a small custom build: a Go `main.go` that adds them to the standard set. [Add Billing to your app](install.md) walks through it. ## Next 1. [Add Billing to your app](https://pocketone.dev/docs/extensions/billing/install) 2. [Products and prices](https://pocketone.dev/docs/extensions/billing/products) 3. [Selling: checkout](https://pocketone.dev/docs/extensions/billing/checkout) 4. [Gating features with entitlements](https://pocketone.dev/docs/extensions/billing/entitlements) --- Source: https://pocketone.dev/docs/extensions/stripe # Stripe The Stripe extension connects [Billing](https://pocketone.dev/docs/extensions/billing) to Stripe. Buyers pay on Stripe Checkout, Stripe's webhooks keep Billing's items current, and users manage cards and invoices in Stripe's Customer Portal. With **Managed Payments** on (the default), Stripe sells as merchant of record: it collects and files sales tax and VAT and handles disputes. Turn it off to sell under your own Stripe account. ## Install Add it to your build next to Billing ([Add Billing to your app](https://pocketone.dev/docs/extensions/billing/install)): ```go set.Add(billing.New(billing.Config{}), stripe.New(stripe.Config{})) ``` The module is `pocketone.dev/ext/stripe`. ## Keys In the dashboard, open **Billing → Settings**. Stripe's section is below Billing's own. | Setting | Where to find it | |---|---| | Secret key | Stripe's **Developers → API keys**. A test key (`sk_test_`) uses Stripe's sandbox. A restricted key (`rk_`) works when it can write Checkout Sessions, subscriptions and refunds and read prices, customers, invoices and payments. | | Webhook signing secret | The `whsec_` secret of the webhook endpoint below. | | Managed Payments | Stripe is merchant of record for new checkouts. Subscriptions that started without it renew as they are. | Press **Test** to check the key, then **Save changes**. ## Webhooks In Stripe, add a webhook endpoint (**Developers → Webhooks**) at the URL shown in Stripe's settings section: `/api/_c/billing/v1/webhook?provider=stripe`. Send these events: - `checkout.session.completed`, `checkout.session.async_payment_succeeded` - `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `customer.subscription.paused`, `customer.subscription.resumed` - `invoice.paid`, `invoice.payment_failed` - `charge.refunded`, `charge.dispute.created`, `charge.dispute.closed` Paste the endpoint's signing secret into the settings. ## Try it on your machine The [Stripe CLI](https://docs.stripe.com/stripe-cli) forwards a sandbox's webhooks to your local app: ```sh stripe login stripe listen --forward-to 'localhost:8090/api/_c/billing/v1/webhook?provider=stripe' \ --events checkout.session.completed,checkout.session.async_payment_succeeded,customer.subscription.created,customer.subscription.updated,customer.subscription.deleted,customer.subscription.paused,customer.subscription.resumed,invoice.paid,invoice.payment_failed,charge.refunded,charge.dispute.created,charge.dispute.closed ``` It prints a `whsec_` signing secret to paste into the settings (`stripe listen --print-secret` shows it again). Use a test key, start a checkout, and pay with card `4242 4242 4242 4242`, any future date and any CVC. ## Products In Stripe, make a product with a price: recurring for a subscription product, one-time for an order. On **Billing → Products**, set the product's `prices` to the price id: `{"stripe": "price_..."}`. **Check prices** confirms it. ## What Billing's calls do at Stripe | Billing | Stripe | |---|---| | `checkout` | A Checkout Session for the product's price and quantity. A returning buyer's Stripe customer is reused. | | `portal` | A Customer Portal session. Set up the portal once under **Settings → Billing → Customer portal** in Stripe. | | `cancel`, `resume` | Cancels at the period end or now; clears a scheduled cancel. | | `quantity`, `plan` | Updates the subscription's item, prorated as asked. | | `refund` | Refunds a one-time purchase, or a subscription's latest paid invoice, in full or in part. | A one-time purchase is its PaymentIntent (`pi_...`). A subscription in Stripe's `incomplete` or `unpaid` state grants nothing until it's paid. The extension's reference is on [its extension page](https://pocketone.dev/docs/extensions/stripe/extension). --- Source: https://pocketone.dev/docs/extensions/paddle # Paddle The Paddle extension connects [Billing](https://pocketone.dev/docs/extensions/billing) to Paddle Billing. Paddle sells as merchant of record: buyers pay Paddle, and Paddle collects and files sales tax and VAT, approves refunds and handles disputes. Paddle's webhooks keep Billing's items current, and users manage cards and invoices in Paddle's customer portal. ## Install Add it to your build next to Billing ([Add Billing to your app](https://pocketone.dev/docs/extensions/billing/install)): ```go set.Add(billing.New(billing.Config{}), paddle.New(paddle.Config{})) ``` The module is `pocketone.dev/ext/paddle`. ## Keys In the dashboard, open **Billing → Settings**. Paddle's section is below Billing's own. All three come from Paddle's **Developer tools**. | Setting | Where to find it | |---|---| | API key | **Developer tools → Authentication**. A sandbox key (`pdl_sdbx_apikey_`) uses Paddle's sandbox. | | Client-side token | Same page (`test_` in the sandbox, `live_` in production). The checkout page loads Paddle.js with it; it isn't secret. | | Webhook secret key | The `pdl_ntfset_` secret of the notification destination below. | The API key and token must come from the same account: both sandbox or both live. Press **Test** to check the key, then **Save changes**. Paddle's sandbox is a separate account at [sandbox-vendors.paddle.com](https://sandbox-vendors.paddle.com), with its own products and keys. ## Webhooks Add a notification destination (**Developer tools → Notifications**) at the URL shown in Paddle's settings section: `/api/_c/billing/v1/webhook?provider=paddle`. Send these events: - `transaction.completed`, `transaction.payment_failed` - `subscription.created`, `subscription.updated`, `subscription.activated`, `subscription.canceled`, `subscription.paused`, `subscription.resumed`, `subscription.past_due`, `subscription.trialing` - `adjustment.created`, `adjustment.updated` Paste the destination's secret key into the settings. ## Try it on your machine Paddle sends webhooks only to a public HTTPS address. Put your local app behind a tunnel and use the tunnel's address for the notification destination: ```sh cloudflared tunnel --url http://localhost:8090 # or: ngrok http 8090 ``` Set the app's **Application URL** (Settings → Application) to the tunnel's address too, so the checkout page and return URLs use it. Use sandbox keys, start a checkout, and pay with card `4242 4242 4242 4242`, any future date and CVC `100`. ## Checkout and your domain Paddle's checkout runs on a page Billing serves at `/api/_c/billing/v1/pay`: it opens Paddle's checkout over the page, and closing it sends the buyer to the cancel URL. Live checkouts need your app's domain approved under **Checkout → Website approval** in Paddle. Set a default payment link there too (any page on your domain). ## Products In Paddle, make a product with a price: with a billing cycle for a subscription product, without one for an order. On **Billing → Products**, set `prices` to the price id: `{"paddle": "pri_..."}`. **Check prices** confirms it. ## What Billing's calls do at Paddle | Billing | Paddle | |---|---| | `checkout` | A transaction for the product's price and quantity, opened with Paddle.js. | | `portal` | A customer portal session. | | `cancel`, `resume` | Cancels at the next billing period or now; removes a scheduled cancel. | | `quantity`, `plan` | Updates the subscription's items, prorated as asked. | | `refund` | A refund adjustment, in full or in part. Paddle approves it, so it stays pending until Paddle does. | A one-time purchase is its transaction (`txn_...`). The extension's reference is on [its extension page](https://pocketone.dev/docs/extensions/paddle/extension). --- Source: https://pocketone.dev/docs/extensions/creem # Creem The Creem extension connects [Billing](https://pocketone.dev/docs/extensions/billing) to [Creem](https://creem.io). Creem is always the merchant of record: it collects and files sales tax and VAT and handles disputes. Buyers pay on Creem's hosted checkout page, Creem's webhooks keep Billing's items current, and users manage cards and receipts in Creem's customer portal. ## Install Add it to your build next to Billing ([Add Billing to your app](https://pocketone.dev/docs/extensions/billing/install)): ```go set.Add(billing.New(billing.Config{}), creem.New(creem.Config{})) ``` The module is `pocketone.dev/ext/creem`. ## Keys In the dashboard, open **Billing → Settings**. Creem's section is below Billing's own. | Setting | Where to find it | |---|---| | API key | **Developers** in Creem's dashboard. With **Test Mode** on, the key starts `creem_test_` and uses Creem's test API. | | Webhook secret | The secret of the webhook below, from **Developers → Webhooks**. Test mode has its own webhooks and secret. | Press **Test** to check the key, then **Save changes**. ## Webhooks Add a webhook (**Developers → Webhooks**) at the URL shown in Creem's settings section: `/api/_c/billing/v1/webhook?provider=creem`. Send these events: - `checkout.completed` - `subscription.active`, `subscription.trialing`, `subscription.paid`, `subscription.update` - `subscription.scheduled_cancel`, `subscription.canceled`, `subscription.expired` - `subscription.past_due`, `subscription.unpaid`, `subscription.paused` - `refund.created`, `dispute.created` Paste the webhook's secret into the settings. ## Try it on your machine Creem sends webhooks only to a public HTTPS address. Put your local app behind a tunnel and use the tunnel's address for the webhook: ```sh cloudflared tunnel --url http://localhost:8090 # or: ngrok http 8090 ``` Turn on Test Mode in Creem, use the test key and the test webhook's secret, start a checkout, and pay with one of Creem's test cards. ## Products A Creem product carries its own price. Make one in Creem, recurring for a subscription product or one-time for an order. On **Billing → Products**, set `prices` to the Creem product id: `{"creem": "prod_..."}`. **Check prices** confirms it. ## What Billing's calls do at Creem | Billing | Creem | |---|---| | `checkout` | A checkout for the product and its units. Discount codes pass through. | | `portal` | A customer portal link. | | `cancel`, `resume` | Cancels now or at the period end; undoes a scheduled cancel. | | `quantity`, `plan` | Changes the units, or upgrades to another product, prorated as asked. | | `refund` | Refunds a one-time purchase, or a subscription's last payment, in full. Partial refunds aren't supported. | A one-time purchase is the checkout that made it (`ch_...`). The extension's reference is on [its extension page](https://pocketone.dev/docs/extensions/creem/extension). --- Source: https://pocketone.dev/docs/extensions/llm # AI in your app **Your app can call cloud models.** `$llm` writes text, draws pictures, reads text aloud, writes down what's said in audio, makes music and video, and turns text into vectors for search. You bring the provider accounts and keys; PocketOne connects them to your pages' code and your Go code. ```ts const r: LlmTextAnswer = await $llm.text.completeAsync({ model: "vultr/glm-5.3", prompt: "Summarize in one sentence: " + record.getString("body"), reasoning: "off", }) // r.text is the summary ``` ```go r, err := textv1.Contract.Must(app).Complete(ctx, extkit.Internal, textv1.CompleteInput{ Model: "vultr/glm-5.3", Prompt: "Summarize in one sentence: " + record.GetString("body"), Reasoning: "off"}) // r.Text is the summary ``` The examples show each thing in TypeScript, as [Pages](https://pocketone.dev/docs/extensions/pages/overview) page code (endpoints and a page's `.ts`), and in Go. The Go examples call the contract packages (`textv1` is `pocketone.dev/ext/contracts/llm/text/v1`) with a `context.Context` named `ctx`. ## Add a provider Open your dashboard, go to **Settings → LLM** and add a provider: - **Vultr** (Serverless Inference): every kind, music and video included. Paste your API key. - **Cloudflare Workers AI**: text, pictures, speech, transcription and embeddings, with a free daily allowance. Enter your account ID and a token with Workers AI permission. - **OpenRouter**: one key for hundreds of models. Pictures need credits on your OpenRouter account; small text models run on its free allowance. - **OpenAI-compatible API**: OpenAI, Groq, Together, or a model on your own machine with Ollama or llama-server. Give the endpoint with its version path (`http://localhost:11434/v1` for Ollama). Press **New provider** and pick its type. Give it a short name (it's how your code picks it) and its key, press its **Test**, then **Save changes**. ## Name a model Every call names its model as `provider/model`: the name you gave the provider, a slash, and the provider's own id for the model. With providers named `vultr`, `cf` and `or`: | Model | Means | |---|---| | `vultr/glm-5.3` | Vultr's `glm-5.3` | | `cf/@cf/meta/llama-3.3-70b-instruct-fp8-fast` | Workers AI's Llama 3.3 | | `or/black-forest-labs/flux.2-klein-4b` | OpenRouter's FLUX.2 Klein | To see what you can use, ask: `$llm.text.modelsAsync()`, `$llm.image.modelsAsync()` and so on list each provider's models of that kind, with their prices where the provider lists them. Keep model names in one place in your app (a `_private/models.ts` module, say), so changing provider is one edit. ## What you can do - [Structured answers](https://pocketone.dev/docs/extensions/llm/guides/structured): get JSON back that matches a schema. - [Streaming answers](https://pocketone.dev/docs/extensions/llm/guides/streaming): show an answer as it's written. - [Pictures, speech and music](https://pocketone.dev/docs/extensions/llm/guides/media): generate files and save them on records. - [Conversations](https://pocketone.dev/docs/extensions/llm/guides/conversations): chats that remember, with LLM Chat. - [Search and RAG](https://pocketone.dev/docs/extensions/llm/guides/search): retrieval-augmented generation over your own files, web pages, Git repositories and records: knowledge bases (buckets), hybrid search with `$llm.search`, and `enrich` to ground any call in them. - [Limits](https://pocketone.dev/docs/extensions/llm/guides/limits): cap what the app spends, per day or month, for the whole app, each user and each guest. - [Custom limits](https://pocketone.dev/docs/extensions/llm/guides/custom-limits): your own rules in code with `$llm.onCall` and `$llm.onCallDone`: plan tiers, credits, team buckets. - [Users and guests](https://pocketone.dev/docs/extensions/llm/guides/users-and-guests): `$llm.for(ctx)`, so per-user and per-guest limits apply. - [Spend and the ledger](https://pocketone.dev/docs/extensions/llm/guides/spend): `$llm.ledger`: what's left of each limit, what someone spent, where the money goes. Every member of `$llm`, with its options and types, is in the [LLM JavaScript API](https://pocketone.dev/docs/reference/javascript/llm) reference, generated from the declarations your editor sees in `types.d.ts`. ## Thinking models Many models think before they answer, and their thinking counts toward `maxTokens`. For short jobs (a label, a title, some JSON) say `reasoning: "off"`; otherwise a short `maxTokens` can be spent entirely on thinking and the answer comes back empty. For hard questions, `"high"` lets the model think longer. A model that doesn't think ignores it. ## When something goes wrong A failed call throws an `Error` whose `code` says what went wrong, with a message you can show: ```ts try { const r = await $llm.for(ctx).text.completeAsync({ model: "vultr/glm-5.3", prompt }) } catch (err: any) { if (err.code === "limit") return ctx.res.json(429, { error: err.message }) // "limit reached: ..., it resets at 00:00 UTC" throw err } ``` | Code | Means | |---|---| | `not_configured` | No provider in Settings → LLM yet. | | `unknown_model` | No model named, or no provider by that name. | | `not_supported` | That kind of provider doesn't do this (music on Cloudflare, say). | | `provider` | The provider said no: a wrong key, no credits, a model it doesn't have. Its message is kept, with your provider's name in front. | | `timeout` | The provider didn't answer in time, and the request was cancelled. The message names the model and what ran out. Worth a retry. | | `limit` | A limit refused the call before it reached the provider: one in Settings → LLM or your own ([Limits](https://pocketone.dev/docs/extensions/llm/guides/limits)). | ### Time limits A provider sometimes drops a request and never answers. Calls don't wait on one for long: - **Text** is always streamed from the provider, even from `completeAsync`, so a stalled answer is spotted as soon as the provider goes quiet: after 10 seconds with nothing from Vultr or OpenRouter (both send something every second while a model works, thinking included), 30 from Cloudflare, 2 minutes from other OpenAI-compatible APIs (OpenAI sends nothing while its reasoning models think, and a local server may take a while to read a long prompt). - **Every call** also has an overall limit: 10 minutes for text, 3 for a picture, 2 for speech or alignment, 5 for a transcription, 1 for embeddings or starting a music or video job (following one with `wait` has its own limit). Either one cancels the request and throws with code `timeout`: `vultr/glm-5.3: the provider sent nothing for 10s, so the call was cancelled`, or `...: no answer in 3m0s, so the call was cancelled`. To give up sooner, give `$llm` a Go context ([cancelling Go calls](https://pocketone.dev/docs/quickjs#cancelling-go-calls)): `$llm.withContext(ctx)` returns a copy of `$llm` whose calls stop when `ctx` ends. The promise rejects with the context's cause and the provider's request is cancelled: ```js // at most 30 seconds, even in background work after the response was sent const deadline = new TimeoutContext(30) try { const a = await $llm.withContext(deadline).text.completeAsync({ model: "vultr/glm-5.3", prompt }) } finally { deadline.cancel() } // or stop it yourself: a "Stop" button, a newer question const stop = new CancelContext() const s = $llm.withContext(stop).text.streamAsync({ model, prompt }, (t) => { /* ... */ }) stop.cancel("a newer question") // s rejects: "context canceled: a newer question" ``` A `TimeoutContext` rejects with `context deadline exceeded`, `cancel()` with `context canceled` (plus the reason you gave). `$llm.withContext(c).context()` returns `c`; on plain `$llm` it returns a background context that never ends. `withContext` and `$llm.for(ctx)` combine in either order, and a chat opened from the copy uses its context too: `$llm.for(ctx).withContext(stop).chat.open(id).sendAsync(text)`. Go code passes a context with an earlier deadline, or cancels it. ## Costs Every call is billed by your provider, on your account. Every answer's `usage` says what it used, and `usage.costMicroUSD` what it cost, in millionths of a US dollar (`1000000` is $1, so `usage.costMicroUSD / 1e6` is dollars). It's a whole number, so costs add up exactly, and it's on every answer of every kind: what the provider charged when it says (OpenRouter always does; Vultr does for media), else worked out from the model's listed prices, with `usage.costEstimated` true, else `0` (free, or no prices PocketOne can count). --- Source: https://pocketone.dev/docs/features/mcp # MCP for AI agents Point Claude, or any other MCP client, at your app and sign in. The agent can then read and change your data, check on the app and run admin tasks, as you and with your rights, nothing more. Every PocketOne app serves MCP at `/mcp`. It's on by default. You don't need to set anything up. ## Connect Claude 1. In your MCP client, add `https:///mcp` as a remote MCP server. In Claude, that's a custom connector. 2. A browser opens on your app's sign-in page. Sign in as an app user, or click **Sign in as a superuser**. 3. The consent page names the client and the account it will act as. Choose **Full access**, or **Only these** and tick what the agent may do. 4. Click **Allow**. The agent stays connected until you disconnect it. In Claude Code: ```bash claude mcp add --transport http my-app https:///mcp claude mcp login my-app # or /mcp in a session ``` Claude and Claude Code connect without any setup on your side. Other MCP clients register themselves with your app first. ## What the agent can do Every tool call is one request to your app's own API, made as whoever signed in. Your API rules, hooks and rate limits apply as they would to any request. - **PocketBase's whole API**, as `pb_*` tools: records (`pb_list_records`, `pb_create_record`, …), files and auth for everyone; collections, settings, logs, crons, SQL and backups for superusers. SQL (`pb_run_sql`) goes straight to the database, past API rules and hooks. - **Admin tasks** each feature adds, such as `restore_points` and `restore_restore_to` to [undo a mistake](https://pocketone.dev/docs/features/restore), or `remote_status` and `remote_logs` to check on the app. The [MCP reference](https://pocketone.dev/docs/reference/mcp) lists them all. - **Your app's own tools**, from `pb_hooks` (below). A superuser gets what the API gives superusers. An app user gets what your collection rules give them, and doesn't see the superuser-only tools. ## Add your own tools Write the endpoint as you would anyway, then declare its tool at the top level of a `pb_hooks` file: ```js // pb_hooks/blog.pb.js routerAdd('POST', '/api/blog/posts/{id}/publish', (e) => { /* … */ }, $apis.requireSuperuserAuth()) $mcp.addEndpoint({ name: 'blog_publish_post', description: 'Publish a draft post and email subscribers.', method: 'POST', path: '/api/blog/posts/{id}/publish', // {id} comes from the tool's id argument inputSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } }, }) $mcp.instructions('blog_publish_post also emails subscribers.') ``` The tool runs the request as the caller, so the route's own auth check is what protects it. When your app has its own tools, agents are told to prefer them over `pb_*`. ## What's covered - **Limited to scopes:** with **Only these**, each call is checked like a request from an [API token](https://pocketone.dev/docs/features/tokens) with those scopes. Calls they don't cover get `403`, and tools they can't reach are hidden. - **Only for MCP:** the agent's token works on `/mcp` and nowhere else. - **Not tools:** sign-in endpoints that hand out a new token, and realtime subscriptions. A file download through `pb_download_file` is capped at 10 MB. - **Browsers:** a web page on another site can't call `/mcp`. Clients that send no `Origin` header, such as Claude's servers and Claude Code, can. Anyone who can sign in to your app can connect an agent, with their own rights. To give an agent less, choose **Only these**, or sign it in as an account with fewer rights. ## Disconnect an agent Each connection is an [API token](https://pocketone.dev/docs/features/tokens) named ` (OAuth)`. Open **Settings → API tokens**, find the one with the `oauth: ` label, and click **Revoke**. ## Paste a token instead A client that can't sign in can send a PocketBase auth token, or an API token, as `Authorization: Bearer …`. An API token with scopes works only if one of them covers `/mcp`, so to limit an agent, use the consent page instead. ## Change it or turn it off There's no `pocketone.yaml` key for MCP: it always serves `/mcp`, and an agent can do nothing until someone signs it in. The name agents see is your app's **Settings → Application → Application name**. Every key is in the [pocketone.yaml reference](https://pocketone.dev/docs/config-reference). `$mcp` isn't available in `pb_hooks` when the app runs PocketBase's own JS engine (`jsvm: goja`). ## How it works - [MCP](https://pocketone.dev/docs/extensions/mcp) serves `/mcp` and turns each tool call into a request to your app's API. - The [OAuth server](https://pocketone.dev/docs/extensions/api-tokens/oauth) in [Tokens](https://pocketone.dev/docs/extensions/api-tokens) runs the sign-in and consent pages, and issues the agent's token. - Admin tools come from the [contracts](https://pocketone.dev/docs/contracts) your app answers. Another MCP server can stand in through the [mcp/v1](https://pocketone.dev/docs/contracts/mcp/v1) contract and serve the same tools. Looking to teach a coding agent how to build with PocketOne? That's a different thing: see [LLM skills for coding agents](https://pocketone.dev/docs/agents). --- Source: https://pocketone.dev/docs/pocketone-yaml # Configuration Every `pocketone` flag has a default. `pocketone.yaml` lets you change those defaults in one file, next to your app, instead of typing them on every start. The same file holds each extension's options, and your secrets go in a `.env` beside it. Without the file, nothing changes: PocketOne behaves like stock PocketBase. Every step below was run on `pocketone`. ## 1. Write the file In your app's folder, create `pocketone.yaml`: ```yaml server: http: 127.0.0.1:8090 app: dir: ./pb_data dev: false ``` Check it, create a superuser, and start the app: ```bash pocketone config check # pocketone.yaml: ok (2 sections) pocketone superuser upsert admin@example.com password pocketone serve ``` `pocketone serve` listens on the address under `server`, and the data folder is `pb_data` next to the file. Relative paths are relative to the file's folder, so the app starts the same from any working directory. PocketOne looks for `pocketone.yaml` in the working directory, then next to the executable. `--config ` picks another file. ## 2. Flags still win A flag always beats the file. The file only changes the defaults: ```bash pocketone serve --http=127.0.0.1:8091 # listens on 8091, whatever the file says ``` ## 3. Keep secrets in a .env Put secrets in a `.env` beside the file, and refer to them as `$VAR` or `${VAR}` in any value: ```bash # .env LISTEN=127.0.0.1:8090 STRIPE_KEY=sk_test_123 OTHER_SECRET=hidden ``` ```yaml server: http: ${LISTEN} ``` Your JS hooks don't see the `.env` unless you allow each name: ```yaml app: env_allow: [STRIPE_KEY] ``` ```js // pb_hooks/env.pb.js routerAdd("GET", "/env", (e) => { return e.json(200, { stripe: process.env.STRIPE_KEY || null, other: process.env.OTHER_SECRET || null }) }) ``` ```bash curl http://127.0.0.1:8090/env # {"stripe":"sk_test_123","other":null} ``` `pocketone config check` says when it read secrets from a `.env`. Keep the `.env` out of git. ## 4. Set an extension's options Each top-level key is a section owned by one extension. For example, keep three days of point-in-time history, and give the app's JS more room: ```yaml pitr: retention: 72h app: js_limits: memory: 128MiB task_time: 10s ``` `js_limits` sets the limits of the JS engine your hooks run on (`memory`, `task_time`, `task_wall`, `await_time`); [QuickJS hooks](https://pocketone.dev/docs/quickjs#6-memory-and-time-limits) shows what each one counts and stops. To see every section your binary knows, with each key, run: ```bash pocketone config ``` The [pocketone.yaml reference](https://pocketone.dev/docs/config-reference) lists the same, with each key's type, default and meaning. ## 5. Choose which extension does a job Extensions offer their abilities through [contracts](https://pocketone.dev/docs/how-pocketone-fits-together). When more than one extension can do the same job, `providers` picks one. Both PITR and Backups can restore your data. PITR is used when it's on, but you can choose Backups: ```yaml providers: restore/v1: backups ``` The startup lines show the choice: ``` INFO standard: restore/v1 ← backups (providers:) ``` ## The whole file ```yaml server: http: ${LISTEN} app: dir: ./pb_data dev: false env_allow: [STRIPE_KEY] js_limits: memory: 128MiB task_time: 10s pitr: retention: 72h providers: restore/v1: backups ``` ## Next - [pocketone.yaml reference](https://pocketone.dev/docs/config-reference): every section and key. - [Config](https://pocketone.dev/docs/extensions/config): how the file is found, `.env` rules, and loading it in your own Go build. --- Source: https://pocketone.dev/docs/features/deploy # Deploy and live sync Write your hooks, migrations and pages on your own machine, then send them to your running app with one command. Only the files that changed are uploaded, and the app swaps them in while it keeps serving. This is on for every PocketOne app. Its superusers can deploy to it, and the `pocketone` command can deploy to any PocketOne app. You don't need to set anything up. ## Deploy from your terminal Run these from your project folder, the one that holds `pb_hooks`, `pb_pages` and the rest: ```bash pocketone link https://myapp.example.com # add the app as a remote and sign in, once pocketone deploy # upload what changed ``` `link` signs you in through your browser when the app offers it, or asks for an API token. When the deploy is done you see a line like `Deployed : 3 changed, 0 deleted, 41 unchanged.` With nothing to send, it says `Up to date: no changes.` A few more ways to run it: ```bash pocketone deploy prod # to the remote named prod pocketone deploy --dry-run # list what would be sent, send nothing pocketone deploy --restart # restart afterwards if migrations or packages changed pocketone deploy --force # overwrite files that changed on the server since your last deploy pocketone restart # restart later instead ``` Every command takes a remote's name or a URL. Without one, it uses the project's default remote. [Remote CLI](https://pocketone.dev/docs/features/remote) covers adding more remotes and signing in. ## When changes take effect - **Right away:** `pb_hooks`, `pb_pages` and `pb_public`. Hooks reload by themselves, and pages and public files are read fresh on the next request. - **After a restart:** migrations and npm packages. The deploy tells you `Migrations or packages changed` and leaves the restart to you: pass `--restart`, or run `pocketone restart`. Your first deploy that creates `pb_hooks` needs a restart too. A deploy never restarts the app on its own. ## When the server changed too If a file changed on the server since your last deploy, pull or `dev` (someone edited it there, or the dashboard wrote a migration) and your deploy would overwrite it, the deploy stops, lists those files and sends nothing. Bring them down with `pocketone pull` or `pocketone dev`, then deploy again, or pass `--force` to overwrite them. The record of what you last deployed lives in `.pocketone/` in your project, so a fresh checkout or a CI run deploys without the check. ## Work live with `dev` ```bash pocketone dev ``` `dev` keeps your folder and the app in step both ways, and streams the app's logs. Your edits go up half a second after you save. Changes made on the app, such as the migrations the dashboard writes when you edit a collection, come down within a few seconds. After you upload a migration or new packages, type `r` and Enter to restart the app. Stop with Ctrl+C. If a file changed on both sides, your copy wins and the app's copy is saved in `.pocketone/conflicts/`. `dev` keeps its state in `.pocketone/`, so add that folder to `.gitignore`. To leave files out, list gitignore-style patterns in `.pocketoneignore`. ## Start from a running app With nothing local, `clone` gets you a project folder in one step: ```bash pocketone clone https://myapp.example.com # makes ./myapp, signs you in, downloads the app's code cd myapp bun install # if there's a package.json: dev and deploy upload packages from here pocketone dev ``` It downloads the same files as `pull`, never `pb_data`, and remembers the app as the folder's remote. From there, `dev` keeps both sides in step: a save is live on the app's next request. ## Pull files and read logs ```bash pocketone pull # download pb_hooks, pb_migrations, pb_pages, pb_public, pb_templates, package.json, the lockfile, patches/ pocketone pull pb_hooks pb_public/index.html pocketone logs # the last 100 lines, then follow ``` ## Deploy from CI 1. Sign in to the dashboard as a superuser and open **Settings → API tokens**. 2. Fill in a **Name**, such as `ci`. 3. Under **Scopes**, tick `deploy`. Add `remote` if CI will pass `--restart`. 4. Click **Create token** and copy it. It's shown only once. In CI, set `P1_TOKEN` to that token, then run `pocketone deploy --restart`. ## From an agent An agent with a terminal runs the same `pocketone deploy`. Over [MCP](https://pocketone.dev/docs/reference/mcp), it can restart the app with `remote_restart` and read its log with `remote_logs`. There's no MCP tool that uploads files. ## What's sent - **Sent:** every `pb_*` folder except `pb_data` (so `pb_hooks`, `pb_migrations`, `pb_pages`, `pb_public`, `pb_templates`), plus `package.json`, `bun.lock` or `bun.lockb`, and `patches/`. Dotfiles are included, such as `pb_public/.well-known`. - **Packages:** with a `package.json`, the production `node_modules` tree goes too, so your hooks can `require` npm packages. Dev dependencies stay behind. `--no-node-modules` leaves the app's `node_modules` alone. - **Never sent:** `pb_data` (your live data), `.git*` files and symlinks. Add your own patterns with `-e`. Only superusers, or an API token with the `deploy` scope, can deploy. A token with `deploy:read` can only pull files and read logs. ## Change it There's nothing to set in `pocketone.yaml`. Your project's remotes are kept in `.pocketbase/remotes.json`, which you can commit. Your logins are saved in your home folder, never in the project. Every `pocketone.yaml` key is in the [pocketone.yaml reference](https://pocketone.dev/docs/config-reference). ## How it works - [Deploy](https://pocketone.dev/docs/extensions/deploy) gives the app its deploy API and adds the `deploy`, `dev`, `pull`, `logs` and `restart` commands. - [Remotes](https://pocketone.dev/docs/extensions/remotes) keeps your remotes and logins, and gives the app its restart and logs. - [Tokens](https://pocketone.dev/docs/extensions/api-tokens) makes the API tokens CI uses. - The commands talk to the [deploy/v1](https://pocketone.dev/docs/contracts/deploy/v1) and [remote/v1](https://pocketone.dev/docs/contracts/remote/v1) contracts, so they work against any app or host that offers them. --- Source: https://pocketone.dev/docs/features/remote # Remote CLI Everything an extension lets you do to an app, you can do from afar, three ways: - the `pocketone` command, against any app you've signed in to; - the REST API, from a script or another service; - MCP, from an agent such as Claude. Nobody writes these by hand. Each extension API is a [contract](https://pocketone.dev/docs/how-pocketone-fits-together): a Go interface with one method per operation. PocketOne generates the command, the endpoint and the tool from that interface. Install an extension, or use a host that provides a contract, and its commands show up in the `pocketone` you already have. There's no other tool to install. ## From your terminal Sign in to an app once, then run its commands: ```bash pocketone remote add prod https://myapp.example.com --default pocketone login prod pocketone remote whoami # who you are there, your token's scopes, and the contracts the app offers pocketone remote restore points pocketone remote restore to --at -2h ``` `remote restore to` calls [restore/v1](https://pocketone.dev/docs/contracts/restore/v1) on the app. On an app with [PITR](https://pocketone.dev/docs/extensions/pitr), you get the data as it was two hours ago, to the second. On an app with [Backups](https://pocketone.dev/docs/extensions/backups) only, you get the latest backup before that. The command is the same either way. How a command is named and read: - **Name:** `remote`, the contract's name, then the operation. restore/v1's `restore_to` is `remote restore to`, mail.suppression/v1's `check` is `remote mail suppression check`, remote/v1's `status` is `remote status`. - **Flags:** one per field of the operation's input: `--at`, `--email`, `--campaign`. - Times take RFC 3339 (`2026-11-10T15:00:00Z`), a local time (`2026-11-10 15:00`) or a duration from now (`-2h`). - Lists take `a,b` or a repeated flag. - Anything else takes JSON, or `@file` to read it from a file. - **Whole input:** `--json` takes the whole input as JSON (`@file` reads a file, `-` reads stdin). Flags you also give override its fields. - **Which app:** `--remote` (`-r`) takes a remote's name or a URL. Without it you get the project's default remote. - **Output:** JSON, so you can pipe it to `jq`. A stream (`remote logs`) prints one JSON line per entry until Ctrl-C. - **Errors:** if the app doesn't offer the contract, the command says so ("this remote doesn't offer restore/v1"). In CI, set `P1_TOKEN` to an [API token](https://pocketone.dev/docs/extensions/api-tokens) instead of signing in. [Remotes](https://pocketone.dev/docs/extensions/remotes) covers remotes and saved logins. ## From a script: REST Every operation is an endpoint under `/api/_c//`: ```bash curl -X POST https://myapp.example.com/api/_c/restore/v1/restore \ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"at": "2026-11-10T15:00:00Z"}' ``` `GET /api/_c/remote/v1` is the one fixed path. It answers who you are and lists every contract the app offers. ## From an agent: MCP An app serves MCP at `/mcp` ([MCP](https://pocketone.dev/docs/extensions/mcp)). Each operation is a tool named after its contract and operation (`restore_points`, `restore_restore_to`, `remote_status`). Add `https://myapp.example.com/mcp` to Claude and sign in. ## The same checks every way The command, the endpoint and the tool all call the contract, so each passes the same checks: - **Token scope:** each operation needs a token scope (`restore`, `restore:read`). An API token carries only the scopes it was given. A superuser's own sign-in passes all of them. - **Superuser:** only superusers may call an operation, unless it's public. - **Hooks:** the same hooks run, in Go and in `pb_hooks` (`onRestoreRestoreTo`). ## Every command, endpoint and tool - [CLI reference](https://pocketone.dev/docs/reference/cli): every command of `pocketone`, PocketBase's own included. - [Extension APIs](https://pocketone.dev/docs/extensions/apis): every contract endpoint. - [MCP reference](https://pocketone.dev/docs/reference/mcp): every contract tool. Each [contract page](https://pocketone.dev/docs/contracts) lists its operations all three ways. Each extension page lists the commands it adds and the contracts it answers. ## Your own commands An extension can replace a generated command with its own, or add new ones under `remote`, by providing [cli.commands/v1](https://pocketone.dev/docs/contracts/cli.commands/v1). [Writing an extension](https://pocketone.dev/docs/writing-an-extension) explains how. --- Source: https://pocketone.dev/docs/guides/linux-server # Run PocketOne on a Linux server This guide sets PocketOne up on a Linux server as a systemd service that starts at boot, runs as its own `pocketone` user and serves your app over HTTPS. It takes a few minutes on any distribution with apt, dnf, yum, zypper or apk. ## Install the package ```bash curl -fsSL https://pocketone.dev/install.sh | sh ``` The [install script](https://pocketone.dev/docs/installation#linux) installs the newest release's `.deb`, `.rpm` or `.apk` package for your system. The package makes the `pocketone` system user and a systemd service, and leaves the service stopped. ### Or install a package by hand Every [release](https://github.com/pocketonehq/pocketone/releases) has `.deb` (Debian, Ubuntu), `.rpm` (Fedora, RHEL, Rocky, Alma, openSUSE) and `.apk` (Alpine) packages, named `pocketone__linux_.`, and a `checksums.txt` with the SHA-256 of each. To install one: ```bash # Debian, Ubuntu sudo apt install ./pocketone__linux_amd64.deb # Fedora, RHEL, Rocky, Alma sudo dnf install ./pocketone__linux_amd64.rpm # openSUSE sudo zypper install --allow-unsigned-rpm ./pocketone__linux_amd64.rpm # Alpine sudo apk add --allow-untrusted ./pocketone__linux_amd64.apk ``` The packages aren't signed; check them against `checksums.txt` (`sha256sum -c checksums.txt --ignore-missing`). ### What the package installs | Path | What it is | |---|---| | `/usr/bin/pocketone` | The binary. | | `/usr/lib/systemd/system/pocketone.service` | The service (`.deb` and `.rpm`; Alpine uses OpenRC, so its package has the binary and config only). | | `/etc/pocketone/pocketone.yaml` | The service's [pocketone.yaml](https://pocketone.dev/docs/pocketone-yaml): data in `/var/lib/pocketone`. Kept when you upgrade. | | `/etc/pocketone/service.env` | What the service passes to `pocketone serve`: your domain. Kept when you upgrade. | | `/var/lib/pocketone` | The `pocketone` user's home, holding `pb_data` and your app's `pb_hooks`, `pb_migrations`, `pb_public` and `pb_pages`. | Installing makes the `pocketone` system user and leaves the service stopped. ## Run it as a service Create your first superuser, as the `pocketone` user so the files it makes are that user's: ```bash sudo -u pocketone pocketone superuser upsert --config /etc/pocketone/pocketone.yaml ``` Run any other `pocketone` command for the service's app the same way, with `sudo -u pocketone` and `--config /etc/pocketone/pocketone.yaml`. Then choose how it's reached, in `/etc/pocketone/service.env`: - **Its own HTTPS.** Put your domain in `SERVE_ARGS`, after pointing the domain's DNS at the server: ```bash SERVE_ARGS=example.com ``` `serve` then listens on ports 80 and 443 and gets a Let's Encrypt certificate for the domain by itself, as in PocketBase. List more domains with spaces between them. - **Behind a reverse proxy** (Caddy, nginx) that handles HTTPS: leave `SERVE_ARGS` empty. PocketOne listens on `127.0.0.1:8090`; point the proxy there. Start it now and at every boot, and follow its log: ```bash sudo systemctl enable --now pocketone journalctl -u pocketone -f ``` After changing `service.env` or `pocketone.yaml`, restart it: `sudo systemctl restart pocketone`. Secrets for `pocketone.yaml` go in `/etc/pocketone/.env`, written in the yaml as `$NAME`; make it readable by the `pocketone` user only (`sudo chown root:pocketone /etc/pocketone/.env && sudo chmod 640 /etc/pocketone/.env`). To deploy your app, put its folders in `/var/lib/pocketone`, owned by the `pocketone` user, and restart the service: ```bash sudo cp -r pb_hooks pb_migrations pb_public /var/lib/pocketone/ sudo chown -R pocketone:pocketone /var/lib/pocketone sudo systemctl restart pocketone ``` Or push it from your machine with `pocketone deploy` ([Deploy and live sync](https://pocketone.dev/docs/features/deploy)). ## A service without a package With the plain binary in `/usr/local/bin` (the install script with `POCKETONE_NO_PACKAGE=1`, or a release zip), set the service up yourself. Make the user and data folder, and the first superuser: ```bash sudo useradd --system --user-group --home-dir /var/lib/pocketone --create-home --shell /usr/sbin/nologin pocketone sudo -u pocketone pocketone superuser upsert --dir /var/lib/pocketone/pb_data ``` Save this as `/etc/systemd/system/pocketone.service`, with your domain in place of `example.com` (or, behind a reverse proxy, no domain and no `AmbientCapabilities` line): ```ini [Unit] Description=PocketOne After=network-online.target Wants=network-online.target [Service] User=pocketone Group=pocketone WorkingDirectory=/var/lib/pocketone ExecStart=/usr/local/bin/pocketone serve example.com --dir /var/lib/pocketone/pb_data --publicDir /var/lib/pocketone/pb_public Restart=on-failure RestartSec=5s LimitNOFILE=4096 # lets the pocketone user listen on ports 80 and 443 AmbientCapabilities=CAP_NET_BIND_SERVICE [Install] WantedBy=multi-user.target ``` Then: ```bash sudo systemctl daemon-reload sudo systemctl enable --now pocketone ``` ## Upgrade Run the install script again. It installs the newest release's package over the old one; the package manager restarts the service if it's running and keeps your `/etc/pocketone` files and your data. For the plain binary of [A service without a package](#a-service-without-a-package), run `sudo pocketone upgrade` (it keeps the old one as `pocketone-`), then `sudo systemctl restart pocketone`. ## Uninstall ```bash sudo apt remove pocketone # or: sudo dnf remove pocketone, sudo zypper remove pocketone, sudo apk del pocketone ``` This stops the service and removes the binary and the service. Your data in `/var/lib/pocketone` and the `pocketone` user stay; delete them yourself if you're sure (`sudo rm -rf /var/lib/pocketone && sudo userdel pocketone`). --- Source: https://pocketone.dev/docs/features/restore # Point-in-time restore Deleted the wrong records, ran a bad migration, or let a script loose on production? Pick a moment from before it happened, and your app's data goes back to how it was then. This is on for every PocketOne app. You don't need to set anything up. ## How far back you can go PocketOne records every change to your database as it happens and keeps **the last 72 hours**. You can restore to any second inside that window. If history recording is turned off, the app restores from your PocketBase backups instead: the latest backup made at or before the moment you pick. The steps below are the same either way. The app tells you which point it used. ## Restore from the dashboard 1. Sign in to the dashboard as a superuser and open **Settings → Backups**. 2. Find **Restore to a moment**. It shows how far back you can go. 3. Under **Restore to**, pick the date and time to go back to, then click **Restore**. The app keeps serving while it rebuilds the old data, then restarts with it. That takes a few seconds for most apps. ## Changed your mind? Undo the restore The data you replaced is kept, and changes keep being recorded after a restore. So after a restore, the section shows when you restored and to what time, with an **Undo this restore** button. Click it to put things back as they were just before you restored. ## What's covered - **Restored:** your database: records, collections, rules, settings and superusers. - **Not restored:** uploaded files, `pb_hooks`, `pb_public` and the logs. Keep those in your PocketBase backups, or in your own source control. Only superusers can see or run a restore. ## From your terminal Sign in to your app once ([Remote CLI](https://pocketone.dev/docs/features/remote)), then: ```bash pocketone remote restore points # how far back you can go pocketone remote restore to --at -2h # back to two hours ago ``` `--at` takes a duration from now (`-2h`, `-30m`), a local time (`2026-11-10 15:00`) or an RFC 3339 time (`2026-11-10T15:00:00Z`). On the machine that runs the app, you can also work from its files directly. Pull a copy of the old database to look through without touching the live one, or restore in place while the server is stopped (it's swapped in at the next start): ```bash pocketone pitr restore --at 2026-11-10T15:00:00Z --to /tmp/then.db # a copy, safe any time pocketone pitr restore --at 2026-11-10T15:00:00Z # in place, server stopped ``` ## From an agent An agent connected to your app over [MCP](https://pocketone.dev/docs/reference/mcp) has two tools: `restore_points` to see how far back it can go, and `restore_restore_to` to restore. It needs a token with the `restore` scope, and only a superuser can grant one. ## Keep history somewhere safer By default, history is kept on the same disk as your database. That protects you from mistakes, but not from losing the disk. To keep it in your own S3-compatible bucket, open **Settings → Backups → Point-in-time restore**, tick **Store the history in my own S3 bucket**, fill in the bucket details, click **Test connection**, then **Save**. ## Change how far back it goes, or turn it off In `pocketone.yaml`: ```yaml pitr: retention: 168h # keep a week instead of 72 hours # enabled: false # stop recording; restores then use your backups ``` A longer window uses more storage. Every key is in the [pocketone.yaml reference](https://pocketone.dev/docs/config-reference). ## How it works - [PITR](https://pocketone.dev/docs/extensions/pitr) records the history with Litestream and restores to any second. - [Backups](https://pocketone.dev/docs/extensions/backups) restores from PocketBase's own backups when PITR is off. - Both answer the same [restore/v1](https://pocketone.dev/docs/contracts/restore/v1) contract, which is why the dashboard, the command and the MCP tools don't care which one is on. --- Source: https://pocketone.dev/docs/features/isolates # PocketBase isolates: hundreds of apps in one process An isolate is a complete PocketOne app: its own folder, `pb_data`, `pb_hooks`, `pb_migrations`, dashboard and superusers, at its own hostname. What's different is where it runs. Instead of a process or container of its own, it runs inside one shared `pocketone` process, with its own JavaScript VM, and the host routes each request to it by hostname. Most apps sit idle most of the time, so a process or container per app is mostly paying for nothing. Isolates make a server full of PocketBase apps cheap: SaaS with one app per customer, a site per client, a preview app per branch. It's built into `pocketone`. You don't need Docker, Kubernetes or a separate host program. ## Try it in a minute Put this `pocketone.yaml` in an empty folder: ```yaml server: { http: "127.0.0.1:8090" } multisite: {} instances: { dev: true } pocker: { root: ./pb_root } ``` Start it, then ask for any hostname: ```bash pocketone serve curl -H 'Host: blog.localhost' http://127.0.0.1:8090/api/health curl -H 'Host: shop.localhost' http://127.0.0.1:8090/api/health ``` In dev mode, each new hostname becomes an app: its folder appears under `pb_root/` and it starts on that first request. Open `http://blog.localhost:8090/_/` for that app's own dashboard. On a laptop, each new app answered its first request in about 45 ms, and later requests in under a millisecond. A hundred running apps took the process from 53 MB to 365 MB: about 3 MB each. ## Run it for real List your apps and their hostnames in an instances file: ```yaml # instances.yaml instances: - id: blog # also its folder: pb_root/blog hosts: [blog.example.com] - id: shop hosts: [shop.example.com] secrets: { STRIPE_KEY: sk_live_... } # seen only by this app's hooks limits: { max_js_execution: 60s } ``` ```yaml # pocketone.yaml multisite: {} instances: { file: ./instances.yaml } pocker: { root: ./pb_root } ``` The host checks the file every 2 seconds, so adding, changing or removing an app needs no restart. In production, only the hostnames listed there are served. [Auto TLS](https://pocketone.dev/docs/extensions/autotls) gets certificates for them. ## What each app gets - **Everything a PocketOne app has.** [Point-in-time restore](https://pocketone.dev/docs/features/restore), [API tokens](https://pocketone.dev/docs/features/tokens), [MCP](https://pocketone.dev/docs/features/mcp), [Pages](https://pocketone.dev/docs/features/sites), [bulk mail](https://pocketone.dev/docs/features/bulk-mail) and the rest are on in every isolate. Each can be turned off per app. - **Its own deploys.** [`pocketone deploy`](https://pocketone.dev/docs/features/deploy) and the [Remote CLI](https://pocketone.dev/docs/features/remote) work against each app's hostname. - **Its own restarts.** A change to its `pb_hooks`, a restore or its settings restarts that app alone. Nothing else notices. ## Sandboxed from each other Isolates share a process, so PocketOne puts the walls inside it. Assume every app's owner is hostile: - **Memory:** each app's JS has a hard cap (64 MiB by default). Going past it is an out-of-memory error for that app only. - **CPU:** every JS call (hook, route, cron, migration) is stopped after `max_js_execution`. At most `max_concurrent_js` calls per app run at once. - **Files, SQL and network:** an app's hooks and SQL reach only its own data. Outbound requests can't reach private networks unless you allow them. - **Failures stay put:** a broken hooks file, a panic or a failed migration takes down that app alone. It answers 502 until it's fixed. - **Secrets:** each app's hooks see only its own `secrets`. Every limit has a default for the whole host and an override per app. [Sandbox](https://pocketone.dev/docs/extensions/sandbox) lists every check. ## When to use containers instead An isolate runs the PocketOne code in the `pocketone` binary. For an app that needs a specific PocketBase release, use the [Docker](https://pocketone.dev/docs/extensions/docker) runtime, which runs each app in its own container with the official binary of the version it asks for. One host can run both. ## How it works - [Multisite](https://pocketone.dev/docs/extensions/multisite) takes over `serve` when `pocketone.yaml` has a `multisite` section. It routes each request by hostname, applies the gates, and hands it to a runtime. - [Pocker](https://pocketone.dev/docs/extensions/pocker) is the runtime that runs apps as isolates in the host's process. - [Sandbox](https://pocketone.dev/docs/extensions/sandbox) confines each isolate's JS, SQL and outbound network. - [Docker](https://pocketone.dev/docs/extensions/docker) is the container runtime, for apps that need it. --- Source: https://pocketone.dev/docs/extensions/desktop # Desktop apps Your app is a folder: `pb_hooks`, `pb_migrations` and `pb_public`. `pocketone serve` runs it as a server, as always. `pocketone desktop build` turns the same folder into an app your users double-click: ```sh pocketone serve # the app as a server pocketone desktop build # a desktop app for this machine, in dist/ pocketone desktop build --all # macOS, Windows and Linux, arm64 and amd64 ``` All you need is `pocketone` and Docker. The build runs in a build image that holds Go and PocketOne's source, so there's no Go, C compiler or Xcode to install, and every platform builds from any machine. > **Preview.** Desktop builds work today, but how a desktop app handles trust and settings is still settling (see > [What's next](#whats-next)). The desktop runtime uses Wails' cgo-free backends, which Wails marks experimental on > macOS and Linux. ## How it works The desktop app is your PocketOne app plus a window: 1. Your `pb_hooks`, `pb_migrations` and `pb_public` are embedded in the executable. Nothing is read from disk, so nobody can change a shipped app's hooks. 2. When it starts, it runs your app's server on a private `127.0.0.1` port, applying your migrations to the user's data. 3. It opens a native window on that server, using the system's own webview: WebKit on macOS, WebView2 on Windows, WebKitGTK on Linux. Your pages call the API with `fetch`, exactly as they do in a browser. The PocketBase JS SDK, realtime and file uploads work the same, because it's the same server. ## Try it: hello world PocketOne's source has a hello-world app in `ext/desktop/example/hello`: a hook, a migration and one page that lists and adds greetings. ```js // pb_hooks/main.pb.js routerAdd("GET", "/api/hello", (e) => { const rows = $app.findRecordsByFilter("greetings", "", "-created", 50, 0) return e.json(200, { message: "Hello from PocketOne hooks", greetings: rows.map((r) => r.get("text")) }) }) ``` Its `pocketone.yaml` keeps the server's data in the folder and names the desktop app: ```yaml app: dir: pb_data server: public_dir: pb_public desktop: name: Hello id: dev.pocketone.hello width: 900 height: 640 ``` Run it both ways: ```sh cd ext/desktop/example/hello pocketone superuser upsert admin@example.com password pocketone serve # http://127.0.0.1:8090 pocketone desktop build # dist/darwin-arm64/Hello.app on an Apple Silicon Mac open dist/darwin-arm64/Hello.app ``` The server and the desktop app keep separate data: the server's in `pb_data/`, the desktop app's in your app-data folder. ## Next - [Building](https://pocketone.dev/docs/extensions/desktop/build): targets, the build image, building with your own Go, and what lands in `dist/`. - [How the app runs](https://pocketone.dev/docs/extensions/desktop/runtime): where each user's data lives, upgrades, the window and what each platform needs. - [Signing and sharing](https://pocketone.dev/docs/extensions/desktop/signing): signing and notarizing for macOS, signing for Windows, and checksums for Linux. - [Extension reference](https://pocketone.dev/docs/extensions/desktop/extension): the `desktop` section of `pocketone.yaml` and building on the runtime from Go. ## What's next A desktop app has one person at the keyboard and data on their machine, so PocketBase's users and superusers don't quite fit. Being worked out: - **Trust:** requests from the app's own window run as its owner, and nothing else on the machine can reach the server. - **Settings:** a native Preferences window for the settings your app and its extensions declare, since the superuser dashboard isn't part of a shipped app. --- Source: https://pocketone.dev/docs/starters # Starter kits A starter kit is a whole PocketOne app to begin from: a `pb_pages` folder (and sometimes migrations), written in TypeScript with [ETS templates](https://pocketone.dev/docs/extensions/pages/ets), run by the stock `pocketone` binary with no build step. Start an app from one, then run it: ```bash pocketone pages create myapp --starter cd myapp pocketone superuser upsert you@example.com --dir ./pb_data pocketone serve --dir ./pb_data ``` `pocketone pages create myapp` with no `--starter` uses **minimal**, and `pocketone pages starters` lists the kits. The folder must not exist yet. | Kit | What it is | |---|---| | [ask](https://pocketone.dev/docs/starters/ask) | Ask your docs a question and get a short answer with links to the pages it came from. | | [auth](https://pocketone.dev/docs/starters/auth) | Multi-page app (MPA) auth with the built-in `auth` plugin: register, password, anonymous, OTP and OAuth2 login, logout, email verification (with a resend page), password reset by email, email change with confirmation, and a protected `/account` section (`account/+middleware.ts`). | | [daisyui](https://pocketone.dev/docs/starters/daisyui) | A layout with a responsive navbar and drawer, built with [Tailwind CSS](https://tailwindcss.com/) and [DaisyUI](https://daisyui.com/) (cupcake theme). | | [daisyui-docs](https://pocketone.dev/docs/starters/daisyui-docs) | A docs site built from Markdown pages, styled with [Tailwind CSS](https://tailwindcss.com/) and [DaisyUI](https://daisyui.com/). | | [datastar](https://pocketone.dev/docs/starters/datastar) | A realtime chat with rooms and a live counter, built with [Datastar](https://data-star.dev/) and the Datastar add-on (`_private/datastar.js`, listed as `'datastar'`) and the built-in `realtime` plugin. | | [htmx](https://pocketone.dev/docs/starters/htmx) | A realtime demo with [htmx](https://htmx.org/) and the built-in `realtime` plugin. | | [minimal](https://pocketone.dev/docs/starters/minimal) | A single `index.ets` page: a Tailwind (CDN) splash screen with no layout, no config and no build step. | | [mvp](https://pocketone.dev/docs/starters/mvp) | One page styled with [MVP.css](https://andybrewer.github.io/mvp/): classless CSS that makes plain semantic HTML look good, for a minimal, responsive, mobile-friendly site with no build step. | | [tsx](https://pocketone.dev/docs/starters/tsx) | Server-rendered components: a `+layout.tsx`, an `index.tsx` page built from a `_private/Feature.tsx` component, and `index.ts` beside it, which loads the page's data. | Everything in the [Pages docs](https://pocketone.dev/docs/extensions/pages) applies to an app made from a kit; each kit's page lists its files and what each one does. --- Source: https://pocketone.dev/docs/examples # Example apps Small, complete apps that show what a PocketOne app looks like. Each is a PocketOne app with no Go: a `pb_pages` folder (and sometimes migrations and hooks) run by the stock `pocketone` binary. Their source is in the PocketOne repository, ready to copy. ## Starter kits To start an app of your own instead, begin from a [starter kit](https://pocketone.dev/docs/starters): `pocketone pages create myapp --starter `. --- Source: https://pocketone.dev/docs/extensions/pages/htmx # HTMX Integration with Pages [HTMX](https://htmx.org) lets HTML elements fetch HTML from the server and swap it into the page. Pages renders that HTML. ## Setting up HTMX Add HTMX to your layout: ```html ``` ## Route organization HTMX requests want HTML fragments, not whole pages wrapped in your layout. Put the layout in a group, and the fragment routes outside it: ``` pb_pages/ (site)/ # Pages with layouts +layout.ets # Main site layout index.ets # / products/ index.ets # /products xapi/ # HTMX endpoints (no layouts) products/ search.ets # /xapi/products/search create/ index.ets # /xapi/products/create index.ts # its code ``` 1. `(site)` holds full pages. Its `+layout.ets` wraps them, and the group adds nothing to the URL. 2. `xapi/` holds fragments. No layout applies to them, because there is no `+layout.ets` at the root. Don't name the folder `api/`: `/api/` belongs to PocketBase. A handler can also send a fragment directly with `ctx.res.html()`, which never applies layouts. ## Sharing partials Render the same fragment on the first page load and in HTMX responses by keeping it in a `_private/` partial: ``` pb_pages/ _private/ product-card.ets # shared partial (site)/ products/ index.ets # includes the partial xapi/ products/ more.ets # includes the same partial ``` ```ets

<%= product.getString('name') %>

<%= product.getString('description') %>

``` ```ets <% const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 20) %>
<% for (const product of products) { %> <%- include('product-card', { product }) %> <% } %>
``` ```ets <% const page = Number(ctx.req.query('page') ?? 1) const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 20, (page - 1) * 20) %> <% for (const product of products) { %> <%- include('product-card', { product }) %> <% } %> ``` ## Search as you type ```html
``` ```ets <% const products = ctx.app.findRecordsByFilter( 'products', 'name ~ {:q}', 'name', 20, 0, { q: ctx.req.query('q') ?? '' } ) %> <% for (const product of products) { %> <%- include('product-card', { product }) %> <% } %> ``` ## Forms ```html
``` ```ts // pb_pages/xapi/products/create/index.ts module.exports = { post(ctx) { const { name, description } = ctx.req.body() const product = new Record(ctx.app.findCollectionByNameOrId('products')) product.set('name', name) product.set('description', description) ctx.app.save(product) return { product } }, } ``` ```ets <%- include('product-card', { product: data.product }) %> ``` ## Out-of-band updates Update more than one element with a single response: ```ets <%- include('product-card', { product: data.product }) %>
<%= ctx.app.countRecords('products') %> Products
``` ## Polling ```html
``` ## Realtime updates With the [`realtime` plugin](plugins/realtime.md), a page can push rendered HTML to every subscriber. A template has `include()`, so render the partial there and send it: ```ts // pb_pages/+config.ts module.exports = { plugins: ['realtime'] } ``` ```ts // pb_pages/xapi/chat/index.ts module.exports = { post() {}, // accept POST; the page below does the work } ``` ```ets <% ctx.realtime.send('chat', include('chat-msg', { message: ctx.req.body().message })) %> ``` ```html
``` In the browser, subscribe to the topic with the PocketBase JS SDK and append what arrives: ```html ``` ## Best practices 1. **Route organization**: keep fragment routes outside the layout group, in a folder like `xapi/`. 2. **Response size**: return only the HTML the swap needs. 3. **Loading states**: use `hx-indicator` to show progress. 4. **Security**: check `ctx.auth` in middleware before changing data, validate input on the server, and debounce triggers like search inputs. --- Source: https://pocketone.dev/docs/extensions/pages/speedruns/custom-domain-fly-cloudflare # Speedrun: Connecting Your Fly.io App to a Custom Domain with Cloudflare Proxy Custom domains on your Fly.io app with Cloudflare in front can be a little complex because you must validate the domain on Fly.io BEFORE turning on Cloudflare proxying. Follow these steps. ## 1. Create the Fly.io App - Start by deploying your app on [Fly.io](https://fly.io/). Follow the standard process to get your app up and running. ## 2. Register Your Domain - If you haven't already, register your domain. It's often convenient to register it through [Cloudflare](https://cloudflare.com), which will also handle your DNS and proxying needs. ## 3. Configure DNS in Cloudflare - In Cloudflare's DNS settings, add **A** and **AAAA** records pointing to your Fly.io app's public IPv4 and IPv6 addresses. - **Important:** Turn off proxying (the orange cloud icon) for these records. This ensures that the Fly.io app can be accessed directly. ## 4. Add a Certificate in Fly.io - In your Fly.io dashboard, add an SSL certificate for your custom domain. - Since proxying is turned off, Fly.io should be able to validate the certificate immediately. Your app should now respond on your custom domain, but it's not yet proxied through Cloudflare. ## 5. Verify Domain Ownership and Proxying - From the Fly.io certificate area, add the **CNAME** record required for domain ownership verification. - **Important:** Turn off proxying for the CNAME record as well. Fly.io needs to verify ownership whenever the SSL certificate is renewed, which requires direct access. - Go back to Fly.io, check the certificate, and ensure domain ownership verification is successful. ## 6. Turn On Proxying in Cloudflare - Once everything is verified and working, return to Cloudflare and turn on proxying (enable the orange cloud) for your A and AAAA records. - In Cloudflare’s **SSL/TLS** settings, set the encryption mode to **Full** (not Full Strict) to ensure proper SSL handshakes between Cloudflare and Fly.io. ## 7. Test Your Setup - Finally, browse to your new domain to confirm everything is working as expected with Cloudflare proxying enabled. You now have a fully functioning Fly.io app served through a custom domain with Cloudflare as the proxy! --- Source: https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2 # Google OAuth2 Setup Guide This guide walks you through setting up Google OAuth2 sign-in for your PocketOne app. ## 1. Create/Select Google Cloud Project 1. Go to [Google Cloud Console](https://console.cloud.google.com) 2. Either select an existing project or create a new one 3. If creating new, provide a project name when prompted ![Creating a new Google Cloud project](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-54-56.png) ![Naming the new project](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-56-00.png) ![Selecting the project](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-56-28.png) ## 2. Configure OAuth Credentials 1. Navigate to "Credentials" in the left sidebar 2. Click "Create Credentials" and select "OAuth client ID" ![Navigating to credentials](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-56-56.png) ![Creating OAuth credentials](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-57-07.png) ### Configure Application Type 1. Select "Web application" as the application type 2. Configure your authorized origins and redirect URIs: - **Authorized JavaScript origins**: Your application domain (e.g., `http://localhost:8090`) - **Authorized redirect URIs**: Your auth callback URL (e.g., `http://localhost:8090/auth/oauth/confirm`) ![Selecting web application](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-57-57.png) ![Configuring URIs](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-07-00-42.png) ### Configure Consent Screen (if needed) If you haven't set up a consent screen before, you'll need to configure it: 1. Choose External/Internal user type 2. Fill in the required application information ![Consent screen setup](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-57-19.png) ![Consent screen details](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-57-27.png) ### Download Credentials 1. After creating the OAuth client, download the JSON credentials file 2. Store this file securely - it contains sensitive information ![Downloading credentials](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-58-27.png) ![Credentials JSON format](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-58-37.png) ## 3. Configure OAuth2 in the dashboard OAuth2 providers belong to an auth collection, usually `users`: 1. Open your app's dashboard (`/_/`) and go to **Collections**. 2. Open the `users` collection's settings (the gear icon) and its **Options** tab. 3. Under **OAuth2**, turn it on. 4. Click **Add provider** and pick **Google**. ![OAuth2 settings for the users collection](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-59-00.png) ![OAuth2 providers section](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-59-09.png) ![Adding new provider](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-59-17.png) ![Selecting Google provider](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-59-24.png) There's no site URL to set for this. The `auth` plugin builds the redirect URL from the address the request came in on: the scheme and host the browser used, plus `/auth/oauth/confirm`. So the redirect URI in Google must match that address exactly. `http://localhost:8090` and `http://127.0.0.1:8090` are different to Google, so add each one you use, plus your live domain (`https://example.com/auth/oauth/confirm`). Behind a proxy, the host is the one the browser asked for, and HTTPS is detected from `X-Forwarded-Proto`. ### Provider Configuration 1. Enter your Client ID and Client Secret from the downloaded credentials 2. Configure any additional auth options as needed 3. Save your changes ![Configuring Google provider](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-59-32.png) ![Saving changes](https://pocketone.dev/docs/extensions/pages/speedruns/google-oauth2/2025-02-08-06-59-59.png) ## Customizing the Return URL By default, the `auth` plugin uses `/auth/oauth/confirm` as the OAuth2 return path. Change it when you start the flow: ```ts ctx.session.requestOAuth2('google', { redirectPath: '/custom/oauth/callback' }) ``` Remember to add the new redirect URL to your Google OAuth2 configuration too. ## Implementation Guide ### 1. Turn on the auth plugin ```ts // pb_pages/+config.ts module.exports = { plugins: ['auth'], } ``` ### 2. Login form ```html
``` ### 3. Start the flow ```ts // pb_pages/auth/oauth.ts module.exports = { post(ctx) { ctx.session.requestOAuth2(ctx.req.body().provider) }, } ``` `requestOAuth2` stores its state in a cookie and redirects the user to Google's consent screen. ### 4. Callback ```ts // pb_pages/auth/oauth/confirm/index.ts module.exports = { load(ctx) { try { ctx.session.signInWithOAuth2(ctx.req.query('state'), ctx.req.query('code')) } catch (e) { return { error: e.message } } return ctx.res.redirect('/') }, } ``` ```ets <%= data.error %> ``` ### 5. Migration Set up Google OAuth2 in a PocketBase migration: ```js migrate( (app) => { const users = app.findCollectionByNameOrId('users') users.oauth2.enabled = true users.oauth2.providers = [ { name: 'google', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, ] app.save(users) }, (app) => { const users = app.findCollectionByNameOrId('users') users.oauth2.enabled = false users.oauth2.providers = [] app.save(users) } ) ``` ### 6. Protected routes ```ts // pb_pages/account/+middleware.ts module.exports = (ctx, next) => { if (!ctx.auth) return ctx.res.redirect('/login') return next() } ``` ### 7. Auth state in the UI ```ets <% if (ctx.auth) { %>
Welcome, <%= ctx.auth.email() %>
<% } else { %> Log in <% } %> ``` ### 8. Logout ```ts // pb_pages/logout.ts module.exports = { post(ctx) { ctx.session.signOut() return ctx.res.redirect('/') }, } ``` See [Authentication](https://pocketone.dev/docs/extensions/pages/authentication) and the [auth plugin](https://pocketone.dev/docs/extensions/pages/plugins/auth). ## Troubleshooting Common issues and solutions: - **Invalid redirect URI**: Ensure your redirect URI exactly matches what's configured in Google Cloud Console - **Consent screen not showing**: Make sure you've properly configured the OAuth consent screen - **Authentication failed**: Verify your client ID and secret are correctly copied to the dashboard ## Security Considerations - Always use HTTPS in production - Keep your client secret secure - Regularly rotate credentials - Review Google OAuth2 access regularly in your Google Cloud Console --- Source: https://pocketone.dev/docs/extensions/pages/speedruns/ses # Speedrun: Setting Up Email with Google Suite and AWS SES - [Prerequisite: Make sure you can receive emails first](#prerequisite-make-sure-you-can-receive-emails-first) - [Create an SES Identity](#create-an-ses-identity) - [Add DNS Records](#add-dns-records) - [Add a custom FROM domain](#add-a-custom-from-domain) - [Add DMARC settings](#add-dmarc-settings) - [Verifying the Setup](#verifying-the-setup) - [Submit for Approval](#submit-for-approval) - [Creating SMTP Credentials](#creating-smtp-credentials) - [Configure SMTP in the dashboard](#configure-smtp-in-the-dashboard) ## Prerequisite: Make sure you can receive emails first To receive emails, you'll need an email provider. I use Google Suite, but you can choose any provider you prefer. [Setting up a new email domain in Google Suite](https://pocketone.dev/docs/extensions/pages/speedruns/gs-gmail). (Someone should write about how to do it using Proton.me) ## Create an SES Identity Log in to your Amazon SES account and follow their getting started guide to create a FROM address and sending domain. Make sure you're in the region you prefer. This is important if you have existing domains because AWS frowns upon approving multiple sending regions. ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-20-29-10.png) Start by creating an Identity: ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-20-30-52.png) ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-20-33-41.png) ## Add DNS Records You'll need to add DNS records provided by SES to your DNS provider. Unlike Google Suite, you'll need to enter these values manually. They do not provide integrations with any DNS providers. ![AWS SES DNS Setup](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-03-06-20-55.png) **Note for Cloudflare users: If you’re using Cloudflare, make sure these records are not proxied.** ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-28-33.png) ## Add a custom FROM domain Deliverability is better if you add a custom FROM domain: ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-38-12.png) ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-38-51.png) It requires a few additional DNS entries. Note that the MX `priority` goes into a separate field, not the MX server field: ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-41-08.png) ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-42-35.png) ## Add DMARC settings ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-45-05.png) ## Verifying the Setup After adding the DNS records, go back to AWS SES and wait for the domain to show as verified. Then, send a verification email. You should receive it if everything is set up correctly. ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-32-26.png) ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-35-46.png) If verification takes too long, go to **Identities > DKIM**, click **Edit**, then **Save** to trigger an immediate re-verification. ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-33-32.png) ## Submit for Approval Before you can send emails to anyone, you must submit everything for approval in AWS SES. This step is crucial to avoid issues when sending emails outside your verified domain. If you have previously had a domain approved, you may be able to skip this step. To find out, simply try sending a test message to anything with a different domain. ## Creating SMTP Credentials Create SMTP credentials in the AWS SES console. These credentials will be used in your app's dashboard for sending emails. ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-48-53.png) ## Configure SMTP in the dashboard Once you have your SMTP credentials, head over to the dashboard (Settings → Mail). Enter the SMTP credentials in the dashboard, and ensure the **SENDER** address is correctly set. If SES hasn't verified your email yet, you can test it by sending an email to `test@`, which should go through if the domain is the same. ![](https://pocketone.dev/docs/extensions/pages/speedruns/ses/2024-09-08-22-53-02.png) --- Source: https://pocketone.dev/docs/reference/javascript # JavaScript API Everything `pb_hooks` and page code can call, generated from the TypeScript declarations PocketOne ships (the same ones your app's `types.d.ts` gets, so your editor knows them too). ## PocketBase What core gives every app: [the globals, hooks, functions and classes](https://pocketone.dev/docs/reference/javascript/pocketbase) (`$app`, `$apis`, `$security`, `routerAdd`, `cronAdd`, `onRecordCreate`, `new Record()`...), and the types they hand you, one page per Go namespace: - PocketBase's: [apis](https://pocketone.dev/docs/reference/javascript/pocketbase/apis), [auth](https://pocketone.dev/docs/reference/javascript/pocketbase/auth), [blob](https://pocketone.dev/docs/reference/javascript/pocketbase/blob), [core](https://pocketone.dev/docs/reference/javascript/pocketbase/core), [cron](https://pocketone.dev/docs/reference/javascript/pocketbase/cron), [dbx](https://pocketone.dev/docs/reference/javascript/pocketbase/dbx), [filesystem](https://pocketone.dev/docs/reference/javascript/pocketbase/filesystem), [forms](https://pocketone.dev/docs/reference/javascript/pocketbase/forms), [hook](https://pocketone.dev/docs/reference/javascript/pocketbase/hook), [logger](https://pocketone.dev/docs/reference/javascript/pocketbase/logger), [mailer](https://pocketone.dev/docs/reference/javascript/pocketbase/mailer), [pocketbase](https://pocketone.dev/docs/reference/javascript/pocketbase/pocketbase), [router](https://pocketone.dev/docs/reference/javascript/pocketbase/router), [search](https://pocketone.dev/docs/reference/javascript/pocketbase/search), [store](https://pocketone.dev/docs/reference/javascript/pocketbase/store), [subscriptions](https://pocketone.dev/docs/reference/javascript/pocketbase/subscriptions), [template](https://pocketone.dev/docs/reference/javascript/pocketbase/template), [types](https://pocketone.dev/docs/reference/javascript/pocketbase/types) - From the Go libraries it builds on: [bufio](https://pocketone.dev/docs/reference/javascript/pocketbase/bufio), [bytes](https://pocketone.dev/docs/reference/javascript/pocketbase/bytes), [cobra](https://pocketone.dev/docs/reference/javascript/pocketbase/cobra), [context](https://pocketone.dev/docs/reference/javascript/pocketbase/context), [exec](https://pocketone.dev/docs/reference/javascript/pocketbase/exec), [filepath](https://pocketone.dev/docs/reference/javascript/pocketbase/filepath), [fs](https://pocketone.dev/docs/reference/javascript/pocketbase/fs), [http](https://pocketone.dev/docs/reference/javascript/pocketbase/http), [io](https://pocketone.dev/docs/reference/javascript/pocketbase/io), [jwt](https://pocketone.dev/docs/reference/javascript/pocketbase/jwt), [multipart](https://pocketone.dev/docs/reference/javascript/pocketbase/multipart), [net](https://pocketone.dev/docs/reference/javascript/pocketbase/net), [oauth2](https://pocketone.dev/docs/reference/javascript/pocketbase/oauth2), [os](https://pocketone.dev/docs/reference/javascript/pocketbase/os), [ozzo_validation](https://pocketone.dev/docs/reference/javascript/pocketbase/ozzo_validation), [slog](https://pocketone.dev/docs/reference/javascript/pocketbase/slog), [sql](https://pocketone.dev/docs/reference/javascript/pocketbase/sql), [sync](https://pocketone.dev/docs/reference/javascript/pocketbase/sync), [syntax](https://pocketone.dev/docs/reference/javascript/pocketbase/syntax), [syscall](https://pocketone.dev/docs/reference/javascript/pocketbase/syscall), [textproto](https://pocketone.dev/docs/reference/javascript/pocketbase/textproto), [time](https://pocketone.dev/docs/reference/javascript/pocketbase/time), [url](https://pocketone.dev/docs/reference/javascript/pocketbase/url) ## Extensions Each PocketOne extension adds to that: a global such as `$llm`, functions to bind hooks, types. Each page below lists what one extension adds. An extension that's off on your app adds nothing. | Extension | Adds | |---|---| | [API Tokens](https://pocketone.dev/docs/reference/javascript/api-tokens) | `tokens`, `$apiTokens` | | [Bulk Mail](https://pocketone.dev/docs/reference/javascript/bulkmail) | `bulkmail`, `$bulkmail` | | [Key-Value Store](https://pocketone.dev/docs/reference/javascript/kv) | `$kv` | | [LLM](https://pocketone.dev/docs/reference/javascript/llm) | `$llm` | | [MCP](https://pocketone.dev/docs/reference/javascript/mcp) | `mcp`, `$mcp` | | [Pages](https://pocketone.dev/docs/reference/javascript/pages) | `pages`, `JSX` | | [WASM](https://pocketone.dev/docs/reference/javascript/wasm) | `$wasm` | | [Contract hooks](https://pocketone.dev/docs/reference/javascript/contracts) | `contracts`, `onContracts`, `ContractError`, `contracts.bulkmail.v1`, `onBulkmailCount`, `onBulkmailStart`, `onBulkmailPause`, `onBulkmailResume`, and 94 more | --- Source: https://pocketone.dev/docs/reference/go # Go API The Go packages under [`ext/contracts`](https://github.com/pocketonehq/pocketone/tree/main/ext/contracts): each [contract](https://pocketone.dev/docs/contracts)'s interface, the types its operations take and return, and the helpers it ships, for a custom build or an extension that calls one. Generated from the source with `go/doc`, examples included. An extension's JavaScript side is in the [JavaScript API](https://pocketone.dev/docs/reference/javascript). ## Contracts | Package | | |---|---| | [`api-tokens/v1`](https://pocketone.dev/docs/reference/go/api-tokens/v1) | Package apitokensv1 is the api-tokens/v1 contract: an app's API tokens. | | [`api-tokens/verify/v1`](https://pocketone.dev/docs/reference/go/api-tokens/verify/v1) | Package verifyv1 is the api-tokens.verify/v1 contract: another server checks an app's API token. | | [`billing/v1`](https://pocketone.dev/docs/reference/go/billing/v1) | Package billingv1 is the billing/v1 contract: selling subscriptions and one-time purchases from an app, whatever processor takes the money. | | [`bulkmail/v1`](https://pocketone.dev/docs/reference/go/bulkmail/v1) | Package bulkmailv1 is the bulkmail/v1 contract: campaigns to many recipients, sent at a safe pace. | | [`cache/clear/v1`](https://pocketone.dev/docs/reference/go/cache/clear/v1) | Package clearv1 is the cache.clear/v1 contract: empty an app's cache buckets from outside the app's code, so its admins (the dashboard, `pocketone remote cache clear`, an agent) can drop what cache/v1 keeps for it after a change that left stale entries behind. | | [`cache/v1`](https://pocketone.dev/docs/reference/go/cache/v1) | Package cachev1 is the cache/v1 contract: named buckets of bytes an app keeps for a while, so extensions and apps can remember what was expensive to compute. | | [`cli/commands/v1`](https://pocketone.dev/docs/reference/go/cli/commands/v1) | Package clicmdv1 is the cli.commands/v1 contract: the `pocketone` command tree. | | [`deploy/v1`](https://pocketone.dev/docs/reference/go/deploy/v1) | Package deployv1 is the deploy/v1 contract: a project's code files on an app (check, upload, commit, list, read, write, delete, tree). | | [`gate/v1`](https://pocketone.dev/docs/reference/go/gate/v1) | Package gatev1 is the gate/v1 contract: what admits requests on a multisite host, before an instance is served or forwarded (a firewall: peer allow lists, client IPs, rate limits). | | [`http/wrap/v1`](https://pocketone.dev/docs/reference/go/http/wrap/v1) | Package wrapv1 is the http.wrap/v1 contract: middleware around everything a multisite host serves (a Server-Timing header, request logging). | | [`instance/fs/v1`](https://pocketone.dev/docs/reference/go/instance/fs/v1) | Package fsv1 is the instance.fs/v1 contract: one instance's code files on local disk, for extensions that read and write them (ext/deploy today). | | [`instance/lookup/v1`](https://pocketone.dev/docs/reference/go/instance/lookup/v1) | Package lookupv1 is the instance.lookup/v1 contract: a multisite host asks for a hostname it doesn't know. | | [`instance/resolve/v1`](https://pocketone.dev/docs/reference/go/instance/resolve/v1) | Package resolvev1 is the instance.resolve/v1 contract: on a control plane (a mothership), what a hostname serves for a given edge, built from the control plane's own records, and which records each answer was built from. | | [`instance/source/v1`](https://pocketone.dev/docs/reference/go/instance/source/v1) | Package sourcev1 is the instance.source/v1 contract: the instance record a multisite host serves (its id, hostnames, version, folder, secrets, limits, ...) and where the records come from. | | [`instance/source/v1/sourcetest`](https://pocketone.dev/docs/reference/go/instance/source/v1/sourcetest) | Package sourcetest is an instance.source/v1 provider for tests: a fixed list of instances that a test can change while it runs, the way an edit to a host's instances file or a control plane's update would. | | [`instance/status/v1`](https://pocketone.dev/docs/reference/go/instance/status/v1) | Package statusv1 is the instance.status/v1 contract: what a multisite host knows about each instance it runs (starting, running, idle, failed), as it changes. | | [`instance/tokens/v1`](https://pocketone.dev/docs/reference/go/instance/tokens/v1) | Package tokensv1 is the instance.tokens/v1 contract: a multisite host checks an API token one of its instances issued, so it can accept the instance's own tokens on the routes it answers for that instance (deploy/v1, remote/v1). | | [`instance/watch/v1`](https://pocketone.dev/docs/reference/go/instance/watch/v1) | Package watchv1 is the instance.watch/v1 contract: an edge follows a control plane (a mothership) lazily. | | [`kv/v1`](https://pocketone.dev/docs/reference/go/kv/v1) | Package kvv1 is the kv/v1 contract: an app's key-value store. | | [`llm`](https://pocketone.dev/docs/reference/go/llm) | Package llm holds what the llm.* contracts share: a model reference, generated files, usage, model info, jobs and errors. | | [`llm/align/v1`](https://pocketone.dev/docs/reference/go/llm/align/v1) | Package alignv1 is the llm.align/v1 contract: forced alignment. | | [`llm/chat/v1`](https://pocketone.dev/docs/reference/go/llm/chat/v1) | Package chatv1 is the llm.chat/v1 contract: stored conversations with the app's language model. | | [`llm/embed/v1`](https://pocketone.dev/docs/reference/go/llm/embed/v1) | Package embedv1 is the llm.embed/v1 contract: a model turns texts into vectors, for search by meaning. | | [`llm/image/v1`](https://pocketone.dev/docs/reference/go/llm/image/v1) | Package imagev1 is the llm.image/v1 contract: a model makes pictures from a prompt, and from reference pictures. | | [`llm/ledger/v1`](https://pocketone.dev/docs/reference/go/llm/ledger/v1) | Package ledgerv1 is the llm.ledger/v1 contract: what an app's model calls have used and cost, read from the ledger every llm.* call leaves (the provider's own record of each call), and how much of each limit is left. | | [`llm/music/v1`](https://pocketone.dev/docs/reference/go/llm/music/v1) | Package musicv1 is the llm.music/v1 contract: a model makes music from a prompt (and lyrics). | | [`llm/search/v1`](https://pocketone.dev/docs/reference/go/llm/search/v1) | Package searchv1 is the llm.search/v1 contract: named buckets of content an app searches. | | [`llm/speech/v1`](https://pocketone.dev/docs/reference/go/llm/speech/v1) | Package speechv1 is the llm.speech/v1 contract: a model reads text aloud. | | [`llm/text/v1`](https://pocketone.dev/docs/reference/go/llm/text/v1) | Package textv1 is the llm.text/v1 contract: a language model answers a prompt or a conversation. | | [`llm/transcribe/v1`](https://pocketone.dev/docs/reference/go/llm/transcribe/v1) | Package transcribev1 is the llm.transcribe/v1 contract: a model writes down what's said in audio. | | [`llm/video/v1`](https://pocketone.dev/docs/reference/go/llm/video/v1) | Package videov1 is the llm.video/v1 contract: a model makes a video from a prompt (and a first frame). | | [`mail/fallback/v1`](https://pocketone.dev/docs/reference/go/mail/fallback/v1) | Package fallbackv1 is the mail.fallback/v1 contract: where an app's mail goes when its SMTP is off. | | [`mail/feedback/v1`](https://pocketone.dev/docs/reference/go/mail/feedback/v1) | Package feedbackv1 is the mail.feedback/v1 contract: what mail providers report back about mail an app sent (bounces, complaints, unsubscribes), received at one place and turned into [Event]s that any extension can act on. | | [`mail/suppression/v1`](https://pocketone.dev/docs/reference/go/mail/suppression/v1) | Package suppressionv1 is the mail.suppression/v1 contract: addresses an app must not send bulk mail to (unsubscribed, bounced, complained), and the unsubscribe link every bulk message carries. | | [`mcp/v1`](https://pocketone.dev/docs/reference/go/mcp/v1) | Package mcpv1 is the mcp/v1 contract: the app's Model Context Protocol endpoint, so agents (a Claude connector, Claude Code, any Streamable HTTP client) can work with it. | | [`oauth/v1`](https://pocketone.dev/docs/reference/go/oauth/v1) | Package oauthv1 is the oauth/v1 contract: an OAuth 2.1 authorization server for the app (authorization code with PKCE, device code, refresh, revocation, dynamic and metadata-document client registration), so the CLI and MCP clients like Claude can sign in. | | [`payments/v1`](https://pocketone.dev/docs/reference/go/payments/v1) | Package paymentsv1 is the payments/v1 contract: what a payment processor (Stripe, Paddle, Creem, ...) does for an app, behind one interface. | | [`remote/v1`](https://pocketone.dev/docs/reference/go/remote/v1) | Package remotev1 is the remote/v1 contract: remote control of an app. | | [`remote/v1/remoteclient`](https://pocketone.dev/docs/reference/go/remote/v1/remoteclient) | Package remoteclient is remote/v1's CLI client: the remotes a project links (.pocketone/remotes.yaml), saved logins, sign-in (an API token, a password, or OAuth in the browser or with a device code), and an authenticated HTTP client for a remote. | | [`restore/v1`](https://pocketone.dev/docs/reference/go/restore/v1) | Package restorev1 is the restore/v1 contract: put an app's data back as it was at a moment. | | [`runtime/v1`](https://pocketone.dev/docs/reference/go/runtime/v1) | Package runtimev1 is the runtime/v1 contract: what runs a multisite host's instances (ext/pocker as isolates, ext/docker in containers). | | [`settings/v1`](https://pocketone.dev/docs/reference/go/settings/v1) | Package settingsv1 is the settings/v1 contract: the settings an app's admins change for its extensions (pitr's S3 bucket, bulkmail's sending limits), one API for all of them. | | [`templates/v1`](https://pocketone.dev/docs/reference/go/templates/v1) | Package templatesv1 is the templates/v1 contract: an extension's own pages as a set of Go html/template files that a project can override. | | [`tls/v1`](https://pocketone.dev/docs/reference/go/tls/v1) | Package tlsv1 is the tls/v1 contract: the TLS of a multisite host's main listener (automatic certificates). | | [`vacuum/v1`](https://pocketone.dev/docs/reference/go/vacuum/v1) | Package vacuumv1 is the vacuum/v1 contract: an app's databases are compacted (SQLite VACUUM) so space freed by deleted records goes back to the disk, and its admins can see when that last happened. | ## PocketBase PocketOne's core: the app (`core`), its HTTP API (`apis`), the tools it's built from, and the test helpers (`tests`). A custom build or an extension imports these by the module path in each page's import line. | Package | | |---|---| | [`pocketbase`](https://pocketone.dev/docs/reference/go/pocketbase) | | | [`apis`](https://pocketone.dev/docs/reference/go/pocketbase/apis) | | | [`core`](https://pocketone.dev/docs/reference/go/pocketbase/core) | Package core is the backbone of PocketBase. | | [`core/validators`](https://pocketone.dev/docs/reference/go/pocketbase/core/validators) | Package validators implements some common custom PocketBase validators. | | [`forms`](https://pocketone.dev/docs/reference/go/pocketbase/forms) | | | [`mails`](https://pocketone.dev/docs/reference/go/pocketbase/mails) | Package mails implements various helper methods for sending common emails like forgotten password, verification, etc. | | [`plugins/ghupdate`](https://pocketone.dev/docs/reference/go/pocketbase/plugins/ghupdate) | Package ghupdate implements a new command to selfupdate the current PocketBase executable with the latest GitHub release. | | [`plugins/migratecmd`](https://pocketone.dev/docs/reference/go/pocketbase/plugins/migratecmd) | Package migratecmd adds a new "migrate" command support to a PocketBase instance. | | [`plugins/update`](https://pocketone.dev/docs/reference/go/pocketbase/plugins/update) | Package update implements a new command to replace the current PocketBase executable with the one from the latest BugStage releases. | | [`tests`](https://pocketone.dev/docs/reference/go/pocketbase/tests) | Package tests provides common helpers and mocks used in PocketBase application tests. | | [`tools/archive`](https://pocketone.dev/docs/reference/go/pocketbase/tools/archive) | | | [`tools/auth`](https://pocketone.dev/docs/reference/go/pocketbase/tools/auth) | | | [`tools/cron`](https://pocketone.dev/docs/reference/go/pocketbase/tools/cron) | Package cron implements a crontab-like service to execute and schedule repeative tasks/jobs. | | [`tools/dbutils`](https://pocketone.dev/docs/reference/go/pocketbase/tools/dbutils) | | | [`tools/filesystem`](https://pocketone.dev/docs/reference/go/pocketbase/tools/filesystem) | | | [`tools/filesystem/blob`](https://pocketone.dev/docs/reference/go/pocketbase/tools/filesystem/blob) | Package blob defines a lightweight abstration for interacting with various storage services (local filesystem, S3, etc.). | | [`tools/hook`](https://pocketone.dev/docs/reference/go/pocketbase/tools/hook) | | | [`tools/inflector`](https://pocketone.dev/docs/reference/go/pocketbase/tools/inflector) | | | [`tools/list`](https://pocketone.dev/docs/reference/go/pocketbase/tools/list) | | | [`tools/logger`](https://pocketone.dev/docs/reference/go/pocketbase/tools/logger) | | | [`tools/mailer`](https://pocketone.dev/docs/reference/go/pocketbase/tools/mailer) | | | [`tools/osutils`](https://pocketone.dev/docs/reference/go/pocketbase/tools/osutils) | | | [`tools/picker`](https://pocketone.dev/docs/reference/go/pocketbase/tools/picker) | | | [`tools/router`](https://pocketone.dev/docs/reference/go/pocketbase/tools/router) | | | [`tools/routine`](https://pocketone.dev/docs/reference/go/pocketbase/tools/routine) | | | [`tools/search`](https://pocketone.dev/docs/reference/go/pocketbase/tools/search) | | | [`tools/security`](https://pocketone.dev/docs/reference/go/pocketbase/tools/security) | | | [`tools/store`](https://pocketone.dev/docs/reference/go/pocketbase/tools/store) | | | [`tools/subscriptions`](https://pocketone.dev/docs/reference/go/pocketbase/tools/subscriptions) | | | [`tools/template`](https://pocketone.dev/docs/reference/go/pocketbase/tools/template) | Package template is a thin wrapper around the standard html/template and text/template packages that implements a convenient registry to load and cache templates on the fly concurrently. | | [`tools/tokenizer`](https://pocketone.dev/docs/reference/go/pocketbase/tools/tokenizer) | Package tokenizer implements a rudimentary tokens parser of buffered io.Reader while respecting quotes and parenthesis boundaries. | | [`tools/types`](https://pocketone.dev/docs/reference/go/pocketbase/tools/types) | Package types implements some commonly used db serializable types like datetime, json, etc. | --- Source: https://pocketone.dev/docs/rest # REST API Every PocketOne app serves a JSON API under `/api/`: its collections' records, signing in, files, realtime and, for superusers, the admin endpoints the dashboard uses. The [JavaScript SDK](https://pocketone.dev/docs/authentication#sign-in-from-a-client) wraps it, but anything that speaks HTTP can use it. | Area | What it covers | |---|---| | [Records](https://pocketone.dev/docs/rest/records) | list, view, create, update and delete a collection's records | | [Authentication](https://pocketone.dev/docs/rest/authentication) | sign in, refresh, sign up flows, verify, reset, change email, impersonate | | [Realtime](https://pocketone.dev/docs/rest/realtime) | subscribe to record changes over server-sent events | | [Files](https://pocketone.dev/docs/rest/files) | download files and thumbnails, protected-file tokens | | [Batch](https://pocketone.dev/docs/rest/batch) | several record writes in one transaction | | [Collections](https://pocketone.dev/docs/rest/collections) | create and change collections (superusers) | | [Settings](https://pocketone.dev/docs/rest/settings) | the app's settings, test mail and S3 (superusers) | | [Logs](https://pocketone.dev/docs/rest/logs) | request and app logs (superusers) | | [Crons](https://pocketone.dev/docs/rest/crons) | list and run scheduled jobs (superusers) | | [Backups](https://pocketone.dev/docs/rest/backups) | make, download, upload and restore backups (superusers) | | [SQL](https://pocketone.dev/docs/rest/sql) | run a SQL query (superusers) | | [Health](https://pocketone.dev/docs/rest/health) | is the app up | | [Extension APIs](https://pocketone.dev/docs/extensions/apis) | the endpoints PocketOne's extensions add, under `/api/_c/` | ## Requests The base URL is your app's address: `https://myapp.example.com/api/...`, or `http://127.0.0.1:8090/api/...` locally. Send JSON bodies with `Content-Type: application/json`, or `multipart/form-data` when you upload files. ## Auth Sign in through an [Authentication](https://pocketone.dev/docs/rest/authentication) endpoint and you get a token. Send it as the `Authorization` header, with or without `Bearer `: ```bash curl http://127.0.0.1:8090/api/collections/posts/records \ -H "Authorization: eyJhbGciOiJIUzI1NiJ9..." ``` A request with no token is a guest. What each request may do is decided by the collection's [API rules](https://pocketone.dev/docs/api-rules); endpoints marked **superusers** need a token from the `_superusers` collection. An [API token](https://pocketone.dev/docs/features/tokens) works the same way for scripts and other apps. ## Lists Every list endpoint takes the same query parameters: | Parameter | Does | Example | |---|---|---| | `page` | the page, from 1 | `page=2` | | `perPage` | items per page, up to 1000 (default 30) | `perPage=100` | | `sort` | fields, `-` for descending, `@random` for random order | `sort=-created,title` | | `filter` | a [filter](https://pocketone.dev/docs/api-rules#the-filter-language) | `filter=(published=true && title~'hello')` | | `expand` | relations to include, nested with dots, up to 6 levels | `expand=author,comments_via_post.author` | | `fields` | only these fields in the answer; `*` for all at a level, `:excerpt(200,true)` to shorten | `fields=id,title,expand.author.name` | | `skipTotal` | skip counting `totalItems` and `totalPages` (faster for big tables) | `skipTotal=1` | A list answers: ```json { "page": 1, "perPage": 30, "totalItems": 2, "totalPages": 1, "items": [{ "id": "...", "collectionName": "posts", "title": "Hello" }] } ``` URL-encode `filter` and `sort` values in real requests (`curl --get --data-urlencode` does it for you). ## Errors Errors answer with a status and a JSON body: ```json { "status": 400, "message": "Failed to create record.", "data": { "title": { "code": "validation_required", "message": "Cannot be blank." } } } ``` | Status | Means | |---|---| | 400 | the request is invalid; `data` names each field's problem | | 401 | the endpoint needs auth and the request has none (or its token is invalid) | | 403 | the request's auth may not do this | | 404 | not found, or a rule hides it (so ids don't leak) | | 429 | too many requests (rate limits, set in Settings) | ## Next - [Records](https://pocketone.dev/docs/rest/records): the endpoints most clients use. - [API rules and filters](https://pocketone.dev/docs/api-rules): who may call what. - [Custom routes](https://pocketone.dev/docs/routes): add endpoints of your own. --- Source: https://pocketone.dev/docs/reference/cli # CLI reference Every command of the `pocketone` binary with its [standard extensions](https://pocketone.dev/docs/extensions/standard): PocketBase's own, the ones extensions add, and a `pocketone remote …` command for every operation of every contract, generated from it ([how](https://pocketone.dev/docs/features/remote)). `pocketone --help` says the same. ## Global flags Every command takes these. | Flag | Type | Default | | |---|---|---|---| | `--config` | string | – | the config file (default ./pocketone.yaml, else next to the executable) | | `--env-file` | string | – | secrets for $VAR references in the config file (default .env beside it); never passed to the app | `pocketone --version` (or `-v`) prints the PocketOne version and the PocketBase version under it. It reads no config, so it works even when `pocketone.yaml` or its `.env` wouldn't load. ## pocketone cache Shows each extension's folder in pb\_cache and its size ``` pocketone cache ``` pb\_cache, next to pb\_data, holds files extensions can rebuild (one folder each). It's never backed up or deployed, and emptying it is always safe. From [Standard Set](https://pocketone.dev/docs/extensions/standard). ### pocketone cache clear Empties pb\_cache (every extension's folder, or the ones named) ``` pocketone cache clear [extension...] ``` From [Standard Set](https://pocketone.dev/docs/extensions/standard). ## pocketone clone Starts a local project from a running app: makes the folder, links and signs in, and pulls its code ``` pocketone clone [dir] ``` Makes dir (default: named after the app's host, e.g. pocketcon for https://pocketcon.dev), adds the app as the project's default remote, signs in (in the browser when the app offers it, else with an API token), and pulls pb\_hooks, pb\_migrations, pb\_pages, pb\_public, pb\_templates, package.json, the lockfile and patches/. pb\_data never comes. Then run `dev` in the folder to keep both sides in step. | Flag | Type | Default | | |---|---|---|---| | `--device` | bool | – | sign in on another device with a code (SSH, headless) | | `--name` | string | `default` | remote name | | `--no-browser` | bool | – | print the sign-in URL instead of opening a browser | | `--token` | string | – | use this API token (pbt\_..., a PocketHost token, or a JWT) | | `--token-stdin` | bool | – | read the token from stdin | From [Deploy](https://pocketone.dev/docs/extensions/deploy). ## pocketone config Lists the pocketone.yaml sections this binary understands, with their defaults ``` pocketone config ``` | Flag | Type | Default | | |---|---|---|---| | `--json` | bool | – | print the sections as JSON (name, doc, owning extension, keys with types and defaults) | From [Config](https://pocketone.dev/docs/extensions/config). ### pocketone config check Checks the config file: every section known and valid, every $VAR set ``` pocketone config check ``` From [Config](https://pocketone.dev/docs/extensions/config). ## pocketone deploy Deploys pb\_hooks, pb\_migrations, pb\_pages, pb\_public and packages to a remote ``` pocketone deploy [remote] ``` Deploys the project's code set (pb\_\* folders except pb\_data and pb\_cache, package.json, bun.lock(b), patches/, and the production node\_modules tree) to a remote. Only changed files are uploaded and the remote swaps them in. Hooks, pages and public files take effect by themselves; migrations and packages apply when the app restarts: pass --restart, or run 'pocketone restart' later. A deploy stops when files changed on the remote since your last deploy, pull or dev (an edit through the file drive, a migration the dashboard wrote) and lists them; --force overwrites them. A project with no record of the remote yet (a fresh checkout, CI) deploys without that check. | Flag | Type | Default | | |---|---|---|---| | `--dry-run` | bool | – | list what would be deployed, deploy nothing | | `-e`, `--exclude` | stringSlice | – | exclude patterns (pb\_data and pb\_cache are always excluded) | | `--force` | bool | – | deploy even when files changed on the remote since your last deploy, pull or dev, overwriting them | | `-i`, `--include` | stringSlice | – | add include patterns (default set: pb\_\*,pb\_\*/\*\*/\*,package.json,bun.lockb,bun.lock,patches,patches/\*\*/\*) | | `--no-node-modules` | bool | – | don't ship node\_modules; leave the remote's alone | | `--node-modules` | bool | – | ship the production node\_modules tree (default with a package.json) | | `--out` | string | – | write the deploy set to a local folder instead of deploying | | `--restart` | bool | – | restart the app after deploying when migrations or packages changed | | `-v`, `--verbose` | bool | – | list every file | From [Deploy](https://pocketone.dev/docs/extensions/deploy). ## pocketone desktop Commands under desktop From [Desktop](https://pocketone.dev/docs/extensions/desktop/extension). ### pocketone desktop build Build this folder's app as a native desktop app (this platform; --all for every platform) ``` pocketone desktop build ``` Compiles the PocketOne app in the current folder into a desktop app: pb\_hooks, pb\_migrations and pb\_public are embedded in the executable, which runs the app's server on a private 127.0.0.1 port and shows it in a native window. Each user's data lives in their own app-data folder, named by the app id. Without flags it builds for this machine. --all builds macOS (arm64, amd64), Windows (amd64, arm64) and Linux (amd64, arm64); --target picks some. The apps land in dist/, macOS's as an .app and a .dmg. With a sign section in pocketone.yaml it signs what it built afterwards, here on this machine: macOS with your Developer ID (and notarizes), Windows with your command, Linux with GPG. --no-sign skips it. It runs in Docker, in the build image matching this pocketone (Go and PocketOne's source, vendored, so it needs nothing else and works offline once the image is here). --local builds with your own Go and a PocketOne checkout. | Flag | Type | Default | | |---|---|---|---| | `--all` | bool | – | build for every platform | | `--image` | string | – | the build image (default pocketone-build:dev) | | `--local` | bool | – | build with your own Go instead of the build image | | `--no-sign` | bool | – | skip pocketone.yaml's desktop.sign section (builds stay signed ad hoc) | | `--out` | string | `dist` | the folder the apps are written to | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | a PocketOne checkout: `--local` builds against it; a development pocketone builds its image from it (default $P1\_SOURCE, else the checkout this folder is in) | | `--target` | stringSlice | – | platforms to build, as os/arch (darwin/arm64,windows/amd64,...) | From [Desktop](https://pocketone.dev/docs/extensions/desktop/extension). ### pocketone desktop image Build the desktop build image from a PocketOne checkout ``` pocketone desktop image ``` Builds the image desktop build runs in (Go plus this checkout's source, vendored) and tags it. A release publishes it as ghcr.io/pocketonehq/pocketone-build:v<version>; a development pocketone builds pocketone-build:dev on first use. | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | the PocketOne checkout (default $P1\_SOURCE, else the one this folder is in) | | `--tag` | string | `pocketone-build:dev` | the image's tag | From [Desktop](https://pocketone.dev/docs/extensions/desktop/extension). ### pocketone desktop prepare Write the build image's vendored module into <dir> (the build image's Dockerfile runs this) ``` pocketone desktop prepare ``` | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | the PocketOne source tree | From [Desktop](https://pocketone.dev/docs/extensions/desktop/extension). ## pocketone dev Keeps the project's code and a remote in step both ways (and streams the remote's logs) ``` pocketone dev [remote] ``` Syncs pb\_hooks, pb\_migrations, pb\_pages, pb\_public and the other pb\_\* folders, package.json, bun.lock(b) and patches/ both ways: edits here are uploaded half a second after you save, and changes on the remote (such as migrations the dashboard writes) are downloaded within seconds. node\_modules is only uploaded, when package.json or the lockfile changes. pb\_data is never synced. Hooks, pages and public files take effect by themselves; migrations and packages you upload apply when the app restarts: type r and Enter. State is kept in .pocketone/; files to leave out go in .pocketoneignore. | Flag | Type | Default | | |---|---|---|---| | `-e`, `--exclude` | stringSlice | – | exclude patterns (pb\_data and pb\_cache are always excluded) | | `-i`, `--include` | stringSlice | – | add include patterns (default set: pb\_\*,pb\_\*/\*\*/\*,package.json,bun.lockb,bun.lock,patches,patches/\*\*/\*) | | `--no-logs` | bool | – | don't stream the remote's logs | | `--no-node-modules` | bool | – | don't ship node\_modules; leave the remote's alone | | `--node-modules` | bool | – | ship the production node\_modules tree (default with a package.json) | | `--poll` | duration | `5s` | how often to check the remote for changes | | `--prefer` | string | – | on the first sync, files that differ: local (upload yours) or remote (download theirs); default asks | | `--push-only` | bool | – | only upload changes (the old one-way dev); never download | | `-v`, `--verbose` | bool | – | list every file | From [Deploy](https://pocketone.dev/docs/extensions/deploy). ## pocketone docker Release binaries for the docker runtime provider (docker.versions in pocketone.yaml) From [Docker](https://pocketone.dev/docs/extensions/docker). ### pocketone docker seed Downloads the releases docker.versions lists that the cache doesn't have yet ``` pocketone docker seed ``` From [Docker](https://pocketone.dev/docs/extensions/docker). ### pocketone docker update Finds the latest patch of each docker.versions minor, records and downloads it ``` pocketone docker update ``` From [Docker](https://pocketone.dev/docs/extensions/docker). ## pocketone extensions Manages the extensions' own schema (their migrations) From [Standard Set](https://pocketone.dev/docs/extensions/standard). ### pocketone extensions migrate Applies or reverts an extension's migrations From [Standard Set](https://pocketone.dev/docs/extensions/standard). ### pocketone extensions migrate down Reverts an extension's last n migrations (default 1; 0: all of them) ``` pocketone extensions migrate down [n] ``` Reverting drops what the migrations created, data included. The next start applies them again, unless the extension is turned off (`<extension>: {enabled: false}` in pocketone.yaml). From [Standard Set](https://pocketone.dev/docs/extensions/standard). ### pocketone extensions migrate up Applies pending extension migrations (startup does this too) ``` pocketone extensions migrate up [extension] ``` From [Standard Set](https://pocketone.dev/docs/extensions/standard). ### pocketone extensions migrations Lists each extension's migrations and whether they're applied ``` pocketone extensions migrations ``` Extensions apply their migrations at startup, after PocketBase's own and before the app's pb\_migrations, and record them in \_extension\_migrations (apart from the app's \_migrations). From [Standard Set](https://pocketone.dev/docs/extensions/standard). ## pocketone link Adds a remote (default name "default") and signs in to it ``` pocketone link [token] ``` | Flag | Type | Default | | |---|---|---|---| | `--device` | bool | – | sign in on another device with a code (SSH, headless) | | `--name` | string | `default` | remote name | | `--no-browser` | bool | – | print the sign-in URL instead of opening a browser | | `--token` | string | – | use this API token (pbt\_..., a PocketHost token, or a JWT) | | `--token-stdin` | bool | – | read the token from stdin | From [Remotes](https://pocketone.dev/docs/extensions/remotes). ## pocketone login Signs in to a remote and saves the login ``` pocketone login [remote] ``` Signs in to a remote: in the browser when the remote offers OAuth (--device for a code on another device), else with a superuser's email and password (or a pasted API token). | Flag | Type | Default | | |---|---|---|---| | `--device` | bool | – | sign in on another device with a code (SSH, headless) | | `--no-browser` | bool | – | print the sign-in URL instead of opening a browser | | `--token` | string | – | use this API token (pbt\_..., a PocketHost token, or a JWT) | | `--token-stdin` | bool | – | read the token from stdin | From [Remotes](https://pocketone.dev/docs/extensions/remotes). ## pocketone logout Forgets the saved login (and revokes it, for a browser login) ``` pocketone logout [remote] ``` From [Remotes](https://pocketone.dev/docs/extensions/remotes). ## pocketone logs Streams a remote's app logs ``` pocketone logs [remote] ``` | Flag | Type | Default | | |---|---|---|---| | `-n`, `--lines` | int | `100` | replay this many earlier lines (0..1000) | From [Deploy](https://pocketone.dev/docs/extensions/deploy). ## pocketone migrate Executes app DB migration scripts ``` pocketone migrate ``` Supported arguments are: - up - runs all available migrations - down [number] - reverts the last [number] applied migrations - create name - creates new blank migration template file - collections - creates new migration file with snapshot of the local collections configuration - history-sync - ensures that the \_migrations history table doesn't have references to deleted migration files | Flag | Type | Default | | |---|---|---|---| | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | From PocketBase. ## pocketone oauth Manage the OAuth server From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). Every `pocketone oauth` command takes these. | Flag | Type | Default | | |---|---|---|---| | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | ### pocketone oauth clients Manage registered OAuth clients From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ### pocketone oauth clients add Registers a client (prints its id, and its secret once for a confidential client) ``` pocketone oauth clients add ``` | Flag | Type | Default | | |---|---|---|---| | `--name` | string | – | name shown on the consent page | | `--public` | bool | – | public client (no secret; PKCE only), e.g. a desktop or mobile app | | `--redirect` | stringSlice | – | allowed redirect URI (repeatable; loopback URIs match any port) | From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ### pocketone oauth clients list Lists registered clients ``` pocketone oauth clients list ``` From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ### pocketone oauth clients rm Removes a client ``` pocketone oauth clients rm ``` From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ## pocketone pages Pages: create an app from a starter kit From [Pages](https://pocketone.dev/docs/extensions/pages/extension). ### pocketone pages create Create a folder with a starter kit (pb\_pages and anything it needs) ``` pocketone pages create ``` | Flag | Type | Default | | |---|---|---|---| | `--starter` | string | – | starter kit (default minimal; list them with: pages starters) | From [Pages](https://pocketone.dev/docs/extensions/pages/extension). ### pocketone pages starters List the starter kits ``` pocketone pages starters ``` From [Pages](https://pocketone.dev/docs/extensions/pages/extension). ## pocketone pitr Point-in-time restore of the database From [PITR](https://pocketone.dev/docs/extensions/pitr). Every `pocketone pitr` command takes these. | Flag | Type | Default | | |---|---|---|---| | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | ### pocketone pitr restore Restore the database as it was at --at, into --to, or in place on the next start ``` pocketone pitr restore ``` With --to, writes the database as it was at --at into that file (any time, also on a fresh machine with the same bucket config). Without --to, stages the restore in place; run it while the server is stopped: the swap happens on the next start. | Flag | Type | Default | | |---|---|---|---| | `--at` | string | – | time to restore to (RFC 3339) | | `--to` | string | – | write into this file instead of restoring in place | From [PITR](https://pocketone.dev/docs/extensions/pitr). ### pocketone pitr status Show the restorable window and history size ``` pocketone pitr status ``` From [PITR](https://pocketone.dev/docs/extensions/pitr). ## pocketone pull Downloads files from a remote into the project (default: pb\_hooks, pb\_migrations, pb\_pages, pb\_public, pb\_templates, package.json, the lockfile, patches/) ``` pocketone pull [remote] [paths...] ``` | Flag | Type | Default | | |---|---|---|---| | `--dry-run` | bool | – | list what would be pulled | From [Deploy](https://pocketone.dev/docs/extensions/deploy). ## pocketone remote The project's remotes, and the commands that run on them (every contract an app offers) ### pocketone remote add Adds or replaces a remote ``` pocketone remote add ``` | Flag | Type | Default | | |---|---|---|---| | `--default` | bool | – | make it the default remote | From [Remotes](https://pocketone.dev/docs/extensions/remotes). ### pocketone remote api-tokens Commands under remote api-tokens ### pocketone remote api-tokens verify Checks an API token and says who it acts as and what it may do (its scopes, with their values) (api-tokens.verify/v1) ``` pocketone remote api-tokens verify ``` Checks an API token and says who it acts as and what it may do (its scopes, with their values). A token that isn't valid is an answer (Valid false), not an error, so callers can tell a refused token from an outage. Calls POST /api/\_c/api-tokens.verify/v1/ on the remote (token scope: api\_tokens\_verify). | Flag | Type | Default | | |---|---|---|---| | `--ip` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--token` | string | – | | From [api-tokens.verify/v1](https://pocketone.dev/docs/contracts/api-tokens.verify/v1) (generated). ### pocketone remote bulkmail Calls bulkmail/v1 on a remote ### pocketone remote bulkmail cancel Stops a campaign for good; recipients not yet sent to are dropped (bulkmail/v1) ``` pocketone remote bulkmail cancel ``` Stops a campaign for good; recipients not yet sent to are dropped. Calls POST /api/\_c/bulkmail/v1/cancel on the remote (token scope: bulkmail). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote bulkmail count Says how many recipients an audience reaches, how many of them are suppressed, and a few sample addresses (bulkmail/v1) ``` pocketone remote bulkmail count ``` Says how many recipients an audience reaches, how many of them are suppressed, and a few sample addresses. Calls POST /api/\_c/bulkmail/v1/count on the remote (token scope: bulkmail:read). | Flag | Type | Default | | |---|---|---|---| | `--audience` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote bulkmail pause Stops sending a campaign; Resume carries on (bulkmail/v1) ``` pocketone remote bulkmail pause ``` Stops sending a campaign; Resume carries on. Calls POST /api/\_c/bulkmail/v1/pause on the remote (token scope: bulkmail). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote bulkmail preview Renders a campaign's message for one recipient (the first in its audience when Email is empty) (bulkmail/v1) ``` pocketone remote bulkmail preview ``` Renders a campaign's message for one recipient (the first in its audience when Email is empty). Calls POST /api/\_c/bulkmail/v1/preview on the remote (token scope: bulkmail:read). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--email` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote bulkmail resume Carries on sending a paused campaign (bulkmail/v1) ``` pocketone remote bulkmail resume ``` Carries on sending a paused campaign. Calls POST /api/\_c/bulkmail/v1/resume on the remote (token scope: bulkmail). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote bulkmail start Queues a campaign's recipients and starts sending (Limit > 0: at most that many new recipients) (bulkmail/v1) ``` pocketone remote bulkmail start ``` Queues a campaign's recipients and starts sending (Limit > 0: at most that many new recipients). Calls POST /api/\_c/bulkmail/v1/start on the remote (token scope: bulkmail). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--limit` | int64 | `0` | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote bulkmail test Sends a campaign's message to one address, marked as a test (bulkmail/v1) ``` pocketone remote bulkmail test ``` Sends a campaign's message to one address, marked as a test. Calls POST /api/\_c/bulkmail/v1/test on the remote (token scope: bulkmail). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--to` | string | – | | From [bulkmail/v1](https://pocketone.dev/docs/contracts/bulkmail/v1) (generated). ### pocketone remote cache Commands under remote cache ### pocketone remote cache clear Empties one of the app's cache buckets, or every bucket it has (cache.clear/v1) ``` pocketone remote cache clear ``` Empties one of the app's cache buckets, or every bucket it has. Calls POST /api/\_c/cache.clear/v1/ on the remote (token scope: cache). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [cache.clear/v1](https://pocketone.dev/docs/contracts/cache.clear/v1) (generated). ### pocketone remote default Sets the default remote ``` pocketone remote default ``` From [Remotes](https://pocketone.dev/docs/extensions/remotes). ### pocketone remote instance Commands under remote instance ### pocketone remote instance watch Calls instance.watch/v1 on a remote ### pocketone remote instance watch stream Opens this edge's stream: a hello first, then answers and changes for the hostnames it watches, the edges list when it changes, and its standing set when that changes (instance.watch/v1) ``` pocketone remote instance watch stream ``` Opens this edge's stream: a hello first, then answers and changes for the hostnames it watches, the edges list when it changes, and its standing set when that changes. Calls GET /api/\_c/instance.watch/v1/stream on the remote (token scope: fleet). | Flag | Type | Default | | |---|---|---|---| | `--edge` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [instance.watch/v1](https://pocketone.dev/docs/contracts/instance.watch/v1) (generated). ### pocketone remote instance watch unwatch Stops changes for a hostname on a stream (instance.watch/v1) ``` pocketone remote instance watch unwatch ``` Stops changes for a hostname on a stream. Calls POST /api/\_c/instance.watch/v1/unwatch on the remote (token scope: fleet). | Flag | Type | Default | | |---|---|---|---| | `--conn` | string | – | | | `--host` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [instance.watch/v1](https://pocketone.dev/docs/contracts/instance.watch/v1) (generated). ### pocketone remote kv Calls kv/v1 on a remote ### pocketone remote kv delete Removes a value (kv/v1) ``` pocketone remote kv delete ``` Removes a value. Deleting a name with no value is not an error. Calls POST /api/\_c/kv/v1/delete on the remote (token scope: kv). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [kv/v1](https://pocketone.dev/docs/contracts/kv/v1) (generated). ### pocketone remote kv get Returns one value (kv/v1) ``` pocketone remote kv get ``` Returns one value. A name with no value is a not\_found error; a private name is a private error. Calls GET /api/\_c/kv/v1/get on the remote (token scope: kv:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [kv/v1](https://pocketone.dev/docs/contracts/kv/v1) (generated). ### pocketone remote kv list Returns the values whose names start with prefix (all of them when it's empty), sorted by name (kv/v1) ``` pocketone remote kv list ``` Returns the values whose names start with prefix (all of them when it's empty), sorted by name. Private names (starting with \_) are left out. Calls GET /api/\_c/kv/v1/ on the remote (token scope: kv:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--prefix` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [kv/v1](https://pocketone.dev/docs/contracts/kv/v1) (generated). ### pocketone remote kv set Stores a JSON value under a name, replacing any value it had (kv/v1) ``` pocketone remote kv set ``` Stores a JSON value under a name, replacing any value it had. Calls POST /api/\_c/kv/v1/set on the remote (token scope: kv). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--value` | string | – | a JSON value (@file reads a file) | From [kv/v1](https://pocketone.dev/docs/contracts/kv/v1) (generated). ### pocketone remote list Lists remotes and whether you're logged in ``` pocketone remote list ``` Aliases: `ls` From [Remotes](https://pocketone.dev/docs/extensions/remotes). ### pocketone remote llm Commands under remote llm ### pocketone remote llm align Says when each line and word of the text is said in the audio (llm.align/v1) ``` pocketone remote llm align ``` Says when each line and word of the text is said in the audio. Calls POST /api/\_c/llm.align/v1/align on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--audio` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--language` | string | – | | | `--mode` | string | – | | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--text` | string | – | | From [llm.align/v1](https://pocketone.dev/docs/contracts/llm.align/v1) (generated). ### pocketone remote llm align models Lists the alignment models of every provider in Settings → LLM (llm.align/v1) ``` pocketone remote llm align models ``` Lists the alignment models of every provider in Settings → LLM. Calls GET /api/\_c/llm.align/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.align/v1](https://pocketone.dev/docs/contracts/llm.align/v1) (generated). ### pocketone remote llm chat Calls llm.chat/v1 on a remote ### pocketone remote llm chat forget Deletes a chat, its messages and the model's state for it (llm.chat/v1) ``` pocketone remote llm chat forget ``` Deletes a chat, its messages and the model's state for it. Calls POST /api/\_c/llm.chat/v1/forget on the remote (token scope: chat). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat forget-where Deletes every chat whose meta matches (as in List), e.g (llm.chat/v1) ``` pocketone remote llm chat forget-where ``` Deletes every chat whose meta matches (as in List), e.g. all of a user the app deleted. Calls POST /api/\_c/llm.chat/v1/forget-where on the remote (token scope: chat). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--limit` | int64 | `0` | | | `--meta` | string | – | a JSON value (@file reads a file) | | `--offset` | int64 | `0` | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat get Returns a chat (llm.chat/v1) ``` pocketone remote llm chat get ``` Returns a chat. Calls POST /api/\_c/llm.chat/v1/get on the remote (token scope: chat:read). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat history Returns a chat's messages, oldest first: the last Limit before the message Before (all when 0 and "") (llm.chat/v1) ``` pocketone remote llm chat history ``` Returns a chat's messages, oldest first: the last Limit before the message Before (all when 0 and ""). Calls POST /api/\_c/llm.chat/v1/history on the remote (token scope: chat:read). | Flag | Type | Default | | |---|---|---|---| | `--before` | string | – | | | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--limit` | int64 | `0` | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat list Returns chats, most recently updated first; Meta keeps those whose meta has each of its top-level keys with that value (llm.chat/v1) ``` pocketone remote llm chat list ``` Returns chats, most recently updated first; Meta keeps those whose meta has each of its top-level keys with that value. Calls POST /api/\_c/llm.chat/v1/list on the remote (token scope: chat:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--limit` | int64 | `0` | | | `--meta` | string | – | a JSON value (@file reads a file) | | `--offset` | int64 | `0` | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat new Starts a chat and returns it; its id is how the app finds it again (llm.chat/v1) ``` pocketone remote llm chat new ``` Starts a chat and returns it; its id is how the app finds it again. Calls POST /api/\_c/llm.chat/v1/new on the remote (token scope: chat). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--meta` | string | – | a JSON value (@file reads a file) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--title` | string | – | | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat send Asks the chat a question: the provider sends the system text, the chat's summary, its recent messages and the question (with Context after it) to llm.text/v1, saves both turns, and folds older messages into the summary when it's due (llm.chat/v1) ``` pocketone remote llm chat send ``` Asks the chat a question: the provider sends the system text, the chat's summary, its recent messages and the question (with Context after it) to llm.text/v1, saves both turns, and folds older messages into the summary when it's due. Calls POST /api/\_c/llm.chat/v1/send on the remote (token scope: chat). | Flag | Type | Default | | |---|---|---|---| | `--context` | string | – | | | `--enrich` | string | – | a JSON value (@file reads a file) | | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--maxtokens` | int64 | `0` | | | `--model` | string | – | | | `--reasoning` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--schema` | string | – | a JSON value (@file reads a file) | | `--summarizeevery` | int64 | `0` | | | `--system` | string | – | | | `--temperature` | string | – | a JSON value (@file reads a file) | | `--text` | string | – | | | `--window` | int64 | `0` | | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat send-stream Is Send with the answer as it's written: llm.text/v1 chunks, the last one with done and the result (llm.chat/v1) ``` pocketone remote llm chat send-stream ``` Is Send with the answer as it's written: llm.text/v1 chunks, the last one with done and the result. Calls POST /api/\_c/llm.chat/v1/send-stream on the remote (token scope: chat). | Flag | Type | Default | | |---|---|---|---| | `--context` | string | – | | | `--enrich` | string | – | a JSON value (@file reads a file) | | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--maxtokens` | int64 | `0` | | | `--model` | string | – | | | `--reasoning` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--schema` | string | – | a JSON value (@file reads a file) | | `--summarizeevery` | int64 | `0` | | | `--system` | string | – | | | `--temperature` | string | – | a JSON value (@file reads a file) | | `--text` | string | – | | | `--window` | int64 | `0` | | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm chat update Sets a chat's title or meta (fields left out stay) (llm.chat/v1) ``` pocketone remote llm chat update ``` Sets a chat's title or meta (fields left out stay). Calls POST /api/\_c/llm.chat/v1/update on the remote (token scope: chat). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--meta` | string | – | a JSON value (@file reads a file) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--title` | string | – | a JSON value (@file reads a file) | From [llm.chat/v1](https://pocketone.dev/docs/contracts/llm.chat/v1) (generated). ### pocketone remote llm embed Returns one vector per input text, in order (llm.embed/v1) ``` pocketone remote llm embed ``` Returns one vector per input text, in order. Calls POST /api/\_c/llm.embed/v1/embed on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--dimensions` | int64 | `0` | | | `--input` | stringSlice | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.embed/v1](https://pocketone.dev/docs/contracts/llm.embed/v1) (generated). ### pocketone remote llm embed models Lists the embedding models of every provider in Settings → LLM (llm.embed/v1) ``` pocketone remote llm embed models ``` Lists the embedding models of every provider in Settings → LLM. Calls GET /api/\_c/llm.embed/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.embed/v1](https://pocketone.dev/docs/contracts/llm.embed/v1) (generated). ### pocketone remote llm image Calls llm.image/v1 on a remote ### pocketone remote llm image generate Makes pictures from a prompt, and from the reference pictures it's given (llm.image/v1) ``` pocketone remote llm image generate ``` Makes pictures from a prompt, and from the reference pictures it's given. Calls POST /api/\_c/llm.image/v1/generate on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--aspectratio` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--model` | string | – | | | `--n` | int64 | `0` | | | `--options` | string | – | a JSON value (@file reads a file) | | `--prompt` | string | – | | | `--references` | string | – | a JSON value (@file reads a file) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--size` | string | – | | From [llm.image/v1](https://pocketone.dev/docs/contracts/llm.image/v1) (generated). ### pocketone remote llm image models Lists the image models of every provider in Settings → LLM (llm.image/v1) ``` pocketone remote llm image models ``` Lists the image models of every provider in Settings → LLM. Calls GET /api/\_c/llm.image/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.image/v1](https://pocketone.dev/docs/contracts/llm.image/v1) (generated). ### pocketone remote llm ledger Calls llm.ledger/v1 on a remote ### pocketone remote llm ledger calls Lists the ledger's rows, newest first (llm.ledger/v1) ``` pocketone remote llm ledger calls ``` Lists the ledger's rows, newest first. Calls GET /api/\_c/llm.ledger/v1/calls on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--kind` | string | – | | | `--limit` | int64 | `0` | | | `--model` | string | – | | | `--offset` | int64 | `0` | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--since` | string | – | | | `--status` | string | – | | | `--subject` | string | – | | | `--until` | string | – | | | `--window` | string | – | | From [llm.ledger/v1](https://pocketone.dev/docs/contracts/llm.ledger/v1) (generated). ### pocketone remote llm ledger remaining Is, for each limit in Settings → LLM that counts the subject's calls, how much is used and left in its current window, the tightest first (llm.ledger/v1) ``` pocketone remote llm ledger remaining ``` Is, for each limit in Settings → LLM that counts the subject's calls, how much is used and left in its current window, the tightest first. Calls GET /api/\_c/llm.ledger/v1/remaining on the remote (token scope: public). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--subject` | string | – | | From [llm.ledger/v1](https://pocketone.dev/docs/contracts/llm.ledger/v1) (generated). ### pocketone remote llm ledger spent Is what the subject's calls used in a window (llm.ledger/v1) ``` pocketone remote llm ledger spent ``` Is what the subject's calls used in a window. Calls GET /api/\_c/llm.ledger/v1/spent on the remote (token scope: public). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--kind` | string | – | | | `--model` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--since` | string | – | | | `--subject` | string | – | | | `--until` | string | – | | | `--window` | string | – | | From [llm.ledger/v1](https://pocketone.dev/docs/contracts/llm.ledger/v1) (generated). ### pocketone remote llm ledger summary Is what calls used, grouped by model, kind, subject or day (llm.ledger/v1) ``` pocketone remote llm ledger summary ``` Is what calls used, grouped by model, kind, subject or day. Calls GET /api/\_c/llm.ledger/v1/summary on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--by` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--kind` | string | – | | | `--limit` | int64 | `0` | | | `--model` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--since` | string | – | | | `--subject` | string | – | | | `--until` | string | – | | | `--window` | string | – | | From [llm.ledger/v1](https://pocketone.dev/docs/contracts/llm.ledger/v1) (generated). ### pocketone remote llm music Calls llm.music/v1 on a remote ### pocketone remote llm music content Fetches one of a done job's files (llm.music/v1) ``` pocketone remote llm music content ``` Fetches one of a done job's files. Calls POST /api/\_c/llm.music/v1/content on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--index` | int64 | `0` | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.music/v1](https://pocketone.dev/docs/contracts/llm.music/v1) (generated). ### pocketone remote llm music create Starts making music (llm.music/v1) ``` pocketone remote llm music create ``` Starts making music. With Wait it returns once the job is done (or failed), its files included; otherwise at once, to follow with Get. Calls POST /api/\_c/llm.music/v1/create on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--lyrics` | string | – | | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `--prompt` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--seconds` | float64 | `0` | | | `--wait` | string | – | | From [llm.music/v1](https://pocketone.dev/docs/contracts/llm.music/v1) (generated). ### pocketone remote llm music get Says how a job is going (llm.music/v1) ``` pocketone remote llm music get ``` Says how a job is going. Calls POST /api/\_c/llm.music/v1/get on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.music/v1](https://pocketone.dev/docs/contracts/llm.music/v1) (generated). ### pocketone remote llm music models Lists the music models of every provider in Settings → LLM (llm.music/v1) ``` pocketone remote llm music models ``` Lists the music models of every provider in Settings → LLM. Calls GET /api/\_c/llm.music/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.music/v1](https://pocketone.dev/docs/contracts/llm.music/v1) (generated). ### pocketone remote llm search Calls llm.search/v1 on a remote ### pocketone remote llm search add Puts a file or pasted text in a bucket as its own source (one document), replacing the source of that name (llm.search/v1) ``` pocketone remote llm search add ``` Puts a file or pasted text in a bucket as its own source (one document), replacing the source of that name. The same text again costs nothing; changed text embeds only its new chunks. It returns at once; the document is embedded in the background (its status says how far it got). Calls POST /api/\_c/llm.search/v1/add on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--kind` | string | – | | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--replace` | string | – | | | `--text` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search add-folder Adds a folder of the app's own files on the server (named by its path, replacing one of that name): every text file in it, read in the background and read again every few minutes, so changed files are embedded again and removed ones leave (llm.search/v1) ``` pocketone remote llm search add-folder ``` Adds a folder of the app's own files on the server (named by its path, replacing one of that name): every text file in it, read in the background and read again every few minutes, so changed files are embedded again and removed ones leave. With URL, each result from it links to the page that file is published at. Calls POST /api/\_c/llm.search/v1/add-folder on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--exclude` | stringSlice | – | | | `--include` | stringSlice | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--path` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--url` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search add-u-r-l Adds a web page or a Git repository as a source (named by its URL, replacing one of that name) and reads it in the background; Every keeps it current (llm.search/v1) ``` pocketone remote llm search add-u-r-l ``` Adds a web page or a Git repository as a source (named by its URL, replacing one of that name) and reads it in the background; Every keeps it current. Calls POST /api/\_c/llm.search/v1/add-url on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--commits` | int64 | `0` | | | `--every` | string | – | | | `--exclude` | stringSlice | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--kind` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--url` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search bucket Returns one bucket with its counts (llm.search/v1) ``` pocketone remote llm search bucket ``` Returns one bucket with its counts. Calls GET /api/\_c/llm.search/v1/bucket on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search buckets Lists the app's buckets with their counts (llm.search/v1) ``` pocketone remote llm search buckets ``` Lists the app's buckets with their counts. Calls GET /api/\_c/llm.search/v1/buckets on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search delete Removes a bucket and everything in it (llm.search/v1) ``` pocketone remote llm search delete ``` Removes a bucket and everything in it. Calls POST /api/\_c/llm.search/v1/delete on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search detect-u-r-l Says how AddURL would read a URL: as a Git repository when its server answers the Git protocol (any host, with or without .git), otherwise as a web page (llm.search/v1) ``` pocketone remote llm search detect-u-r-l ``` Says how AddURL would read a URL: as a Git repository when its server answers the Git protocol (any host, with or without .git), otherwise as a web page. Calls POST /api/\_c/llm.search/v1/detect-url on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--url` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search documents Lists a bucket's documents (or one source's), by source and name (llm.search/v1) ``` pocketone remote llm search documents ``` Lists a bucket's documents (or one source's), by source and name. Calls GET /api/\_c/llm.search/v1/documents on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--prefix` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search ensure Makes a bucket if it's missing and returns it (llm.search/v1) ``` pocketone remote llm search ensure ``` Makes a bucket if it's missing and returns it. An existing bucket keeps its settings, except that an empty title, description or owner is filled in. Apps call it at startup for the bucket they need. Calls POST /api/\_c/llm.search/v1/ensure on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--description` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--name` | string | – | | | `--owner` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--title` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search follow Adds one of the app's collections as a source (named by the collection): each record the filter keeps is a document, kept in sync as records are saved and deleted (llm.search/v1) ``` pocketone remote llm search follow ``` Adds one of the app's collections as a source (named by the collection): each record the filter keeps is a document, kept in sync as records are saved and deleted. Calls POST /api/\_c/llm.search/v1/follow on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--collection` | string | – | | | `--fields` | stringSlice | – | | | `--filter` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search prune Removes the documents of a folder source that aren't in Keep: the files the folder no longer has (llm.search/v1) ``` pocketone remote llm search prune ``` Removes the documents of a folder source that aren't in Keep: the files the folder no longer has. Calls POST /api/\_c/llm.search/v1/prune on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--keep` | stringSlice | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search put Adds one file to a folder source (made on the first one), the way the dashboard sends a dropped folder; Prune ends it (llm.search/v1) ``` pocketone remote llm search put ``` Adds one file to a folder source (made on the first one), the way the dashboard sends a dropped folder; Prune ends it. Calls POST /api/\_c/llm.search/v1/put on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--path` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--replace` | string | – | | | `--source` | string | – | | | `--text` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search refresh Reads a source again now: fetches a URL or repository, rereads a collection, resplits a file or zip (llm.search/v1) ``` pocketone remote llm search refresh ``` Reads a source again now: fetches a URL or repository, rereads a collection, resplits a file or zip. Calls POST /api/\_c/llm.search/v1/refresh on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search remove Takes sources out of a bucket, with their documents (llm.search/v1) ``` pocketone remote llm search remove ``` Takes sources out of a bucket, with their documents. Calls POST /api/\_c/llm.search/v1/remove on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--sources` | stringSlice | – | | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search sample Returns chunks picked at random from the buckets named: material to draw from ("surprise me", a topic nobody asked about), not matches (llm.search/v1) ``` pocketone remote llm search sample ``` Returns chunks picked at random from the buckets named: material to draw from ("surprise me", a topic nobody asked about), not matches. No query, no embedding, so it costs nothing. Like Search without a viewer, it may return any chunk, a followed record's included. Calls POST /api/\_c/llm.search/v1/sample on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--buckets` | stringSlice | – | | | `--count` | int64 | `0` | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--prefix` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search set-model Changes the app's embedding model ("provider/model" from llm.embed/v1's models; "" picks one again) (llm.search/v1) ``` pocketone remote llm search set-model ``` Changes the app's embedding model ("provider/model" from llm.embed/v1's models; "" picks one again). Every bucket is embedded again in the background; until a chunk is, keywords still find it. Calls POST /api/\_c/llm.search/v1/set-model on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--model` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search sources Lists a bucket's sources, by name (llm.search/v1) ``` pocketone remote llm search sources ``` Lists a bucket's sources, by name. Calls GET /api/\_c/llm.search/v1/sources on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `--bucket` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search status Is the app's embedding model and how far embedding has got across every bucket (llm.search/v1) ``` pocketone remote llm search status ``` Is the app's embedding model and how far embedding has got across every bucket. Calls GET /api/\_c/llm.search/v1/status on the remote (token scope: search:read). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search update Changes a bucket's title, description or limits (fields left out stay) (llm.search/v1) ``` pocketone remote llm search update ``` Changes a bucket's title, description or limits (fields left out stay). Calls POST /api/\_c/llm.search/v1/update on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--description` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--maxbytes` | string | – | a JSON value (@file reads a file) | | `--maxdocuments` | string | – | a JSON value (@file reads a file) | | `--name` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--title` | string | – | a JSON value (@file reads a file) | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm search upload Adds a file sent as the request body: ?bucket=<name>&name=<file name>[&replace=<source>] (llm.search/v1) ``` pocketone remote llm search upload ``` Adds a file sent as the request body: ?bucket=<name>&name=<file name>[&replace=<source>]. A .zip is one source with a document per text file inside it; anything else is a file source. Calls POST /api/\_c/llm.search/v1/upload on the remote (token scope: search). | Flag | Type | Default | | |---|---|---|---| | `--content-type` | string | `application/octet-stream` | the body's content type | | `--file` | string | `-` | the body to send (- for stdin) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.search/v1](https://pocketone.dev/docs/contracts/llm.search/v1) (generated). ### pocketone remote llm speech Calls llm.speech/v1 on a remote ### pocketone remote llm speech models Lists the speech models of every provider in Settings → LLM (llm.speech/v1) ``` pocketone remote llm speech models ``` Lists the speech models of every provider in Settings → LLM. Calls GET /api/\_c/llm.speech/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.speech/v1](https://pocketone.dev/docs/contracts/llm.speech/v1) (generated). ### pocketone remote llm speech speak Reads the text aloud and returns the audio (llm.speech/v1) ``` pocketone remote llm speech speak ``` Reads the text aloud and returns the audio. Calls POST /api/\_c/llm.speech/v1/speak on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--format` | string | – | | | `--instructions` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `--reference` | string | – | a JSON value (@file reads a file) | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--speed` | float64 | `0` | | | `--text` | string | – | | | `--voice` | string | – | | From [llm.speech/v1](https://pocketone.dev/docs/contracts/llm.speech/v1) (generated). ### pocketone remote llm speech voices Lists a model's voices, when the provider says (llm.speech/v1) ``` pocketone remote llm speech voices ``` Lists a model's voices, when the provider says. Calls POST /api/\_c/llm.speech/v1/voices on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--model` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.speech/v1](https://pocketone.dev/docs/contracts/llm.speech/v1) (generated). ### pocketone remote llm text Calls llm.text/v1 on a remote ### pocketone remote llm text complete Answers a prompt or a conversation (llm.text/v1) ``` pocketone remote llm text complete ``` Answers a prompt or a conversation. Calls POST /api/\_c/llm.text/v1/complete on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--enrich` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--maxtokens` | int64 | `0` | | | `--messages` | string | – | a JSON value (@file reads a file) | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `--prompt` | string | – | | | `--reasoning` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--schema` | string | – | a JSON value (@file reads a file) | | `--stop` | stringSlice | – | | | `--system` | string | – | | | `--temperature` | string | – | a JSON value (@file reads a file) | From [llm.text/v1](https://pocketone.dev/docs/contracts/llm.text/v1) (generated). ### pocketone remote llm text count Says about how many tokens a text or a conversation is, for budgeting what to send (llm.text/v1) ``` pocketone remote llm text count ``` Says about how many tokens a text or a conversation is, for budgeting what to send. Calls POST /api/\_c/llm.text/v1/count on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--messages` | string | – | a JSON value (@file reads a file) | | `--model` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--system` | string | – | | | `--text` | string | – | | From [llm.text/v1](https://pocketone.dev/docs/contracts/llm.text/v1) (generated). ### pocketone remote llm text models Lists the text models of every provider in Settings → LLM (llm.text/v1) ``` pocketone remote llm text models ``` Lists the text models of every provider in Settings → LLM. Calls GET /api/\_c/llm.text/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.text/v1](https://pocketone.dev/docs/contracts/llm.text/v1) (generated). ### pocketone remote llm text stream Answers like Complete, sending the answer as it's written: a chunk with text (or reasoning) for each piece, then one with done and the whole result (llm.text/v1) ``` pocketone remote llm text stream ``` Answers like Complete, sending the answer as it's written: a chunk with text (or reasoning) for each piece, then one with done and the whole result. Calls POST /api/\_c/llm.text/v1/stream on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--enrich` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--maxtokens` | int64 | `0` | | | `--messages` | string | – | a JSON value (@file reads a file) | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `--prompt` | string | – | | | `--reasoning` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--schema` | string | – | a JSON value (@file reads a file) | | `--stop` | stringSlice | – | | | `--system` | string | – | | | `--temperature` | string | – | a JSON value (@file reads a file) | From [llm.text/v1](https://pocketone.dev/docs/contracts/llm.text/v1) (generated). ### pocketone remote llm transcribe Writes down what's said in the audio (llm.transcribe/v1) ``` pocketone remote llm transcribe ``` Writes down what's said in the audio. Calls POST /api/\_c/llm.transcribe/v1/transcribe on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--audio` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--language` | string | – | | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `--prompt` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.transcribe/v1](https://pocketone.dev/docs/contracts/llm.transcribe/v1) (generated). ### pocketone remote llm transcribe models Lists the transcription models of every provider in Settings → LLM (llm.transcribe/v1) ``` pocketone remote llm transcribe models ``` Lists the transcription models of every provider in Settings → LLM. Calls GET /api/\_c/llm.transcribe/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.transcribe/v1](https://pocketone.dev/docs/contracts/llm.transcribe/v1) (generated). ### pocketone remote llm video Calls llm.video/v1 on a remote ### pocketone remote llm video content Fetches one of a done job's files (llm.video/v1) ``` pocketone remote llm video content ``` Fetches one of a done job's files. Calls POST /api/\_c/llm.video/v1/content on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--index` | int64 | `0` | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.video/v1](https://pocketone.dev/docs/contracts/llm.video/v1) (generated). ### pocketone remote llm video create Starts making a video (llm.video/v1) ``` pocketone remote llm video create ``` Starts making a video. With Wait it returns once the job is done (or failed); otherwise at once, to follow with Get. A done job lists how many files it made (Outputs); Content fetches each. Calls POST /api/\_c/llm.video/v1/create on the remote (token scope: llm). | Flag | Type | Default | | |---|---|---|---| | `--aspectratio` | string | – | | | `--image` | string | – | a JSON value (@file reads a file) | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--model` | string | – | | | `--options` | string | – | a JSON value (@file reads a file) | | `--prompt` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--seconds` | float64 | `0` | | | `--size` | string | – | | | `--wait` | string | – | | From [llm.video/v1](https://pocketone.dev/docs/contracts/llm.video/v1) (generated). ### pocketone remote llm video get Says how a job is going (llm.video/v1) ``` pocketone remote llm video get ``` Says how a job is going. Calls POST /api/\_c/llm.video/v1/get on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--id` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.video/v1](https://pocketone.dev/docs/contracts/llm.video/v1) (generated). ### pocketone remote llm video models Lists the video models of every provider in Settings → LLM (llm.video/v1) ``` pocketone remote llm video models ``` Lists the video models of every provider in Settings → LLM. Calls GET /api/\_c/llm.video/v1/models on the remote (token scope: llm:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--provider` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [llm.video/v1](https://pocketone.dev/docs/contracts/llm.video/v1) (generated). ### pocketone remote logs Streams the app's log: the last entries, then new ones as they're written (remote/v1) ``` pocketone remote logs ``` Streams the app's log: the last entries, then new ones as they're written. Calls GET /api/\_c/remote/v1/logs on the remote (token scope: remote:read). | Flag | Type | Default | | |---|---|---|---| | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--n` | int64 | `0` | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [remote/v1](https://pocketone.dev/docs/contracts/remote/v1) (generated). ### pocketone remote mail Commands under remote mail ### pocketone remote mail suppression Calls mail.suppression/v1 on a remote ### pocketone remote mail suppression check Says whether an address is suppressed, and why (mail.suppression/v1) ``` pocketone remote mail suppression check ``` Says whether an address is suppressed, and why. Calls GET /api/\_c/mail.suppression/v1/check on the remote (token scope: suppression:read). | Flag | Type | Default | | |---|---|---|---| | `--email` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [mail.suppression/v1](https://pocketone.dev/docs/contracts/mail.suppression/v1) (generated). ### pocketone remote mail suppression suppress Adds an address (or changes its reason) (mail.suppression/v1) ``` pocketone remote mail suppression suppress ``` Adds an address (or changes its reason). Calls POST /api/\_c/mail.suppression/v1/suppress on the remote (token scope: suppression). | Flag | Type | Default | | |---|---|---|---| | `--campaign` | string | – | | | `--email` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `--reason` | string | – | | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--source` | string | – | | From [mail.suppression/v1](https://pocketone.dev/docs/contracts/mail.suppression/v1) (generated). ### pocketone remote mail suppression unsuppress Removes an address, so it receives bulk mail again (mail.suppression/v1) ``` pocketone remote mail suppression unsuppress ``` Removes an address, so it receives bulk mail again. Calls POST /api/\_c/mail.suppression/v1/unsuppress on the remote (token scope: suppression). | Flag | Type | Default | | |---|---|---|---| | `--email` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [mail.suppression/v1](https://pocketone.dev/docs/contracts/mail.suppression/v1) (generated). ### pocketone remote restart Restarts the app; requests in flight finish first (remote/v1) ``` pocketone remote restart ``` Restarts the app; requests in flight finish first. Calls POST /api/\_c/remote/v1/restart on the remote (token scope: remote). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [remote/v1](https://pocketone.dev/docs/contracts/remote/v1) (generated). ### pocketone remote restore Calls restore/v1 on a remote ### pocketone remote restore points Says what the app's data can be restored to: a window of time (continuous history) or a list of moments (backups), and whether a restore is running (restore/v1) ``` pocketone remote restore points ``` Says what the app's data can be restored to: a window of time (continuous history) or a list of moments (backups), and whether a restore is running. Calls GET /api/\_c/restore/v1/ on the remote (token scope: restore:read). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [restore/v1](https://pocketone.dev/docs/contracts/restore/v1) (generated). ### pocketone remote restore to Puts the app's data back as it was at the given moment, from the latest point at or before it (restore/v1) ``` pocketone remote restore to ``` Puts the app's data back as it was at the given moment, from the latest point at or before it. The app restarts to apply it; its current data is kept aside until the next restore. Calls POST /api/\_c/restore/v1/restore on the remote (token scope: restore). | Flag | Type | Default | | |---|---|---|---| | `--at` | string | – | a time: RFC 3339 ("2026-11-10T15:00:00Z"), local ("2026-11-10 15:00"), or relative to now ("-2h") | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [restore/v1](https://pocketone.dev/docs/contracts/restore/v1) (generated). ### pocketone remote rm Removes a remote (its saved login stays; see logout) ``` pocketone remote rm ``` Aliases: `remove` From [Remotes](https://pocketone.dev/docs/extensions/remotes). ### pocketone remote settings Calls settings/v1 on a remote ### pocketone remote settings get Returns one extension's settings (settings/v1) ``` pocketone remote settings get ``` Returns one extension's settings. Secrets come back empty, with a flag saying they're set. Calls GET /api/\_c/settings/v1/get on the remote (token scope: settings:read). | Flag | Type | Default | | |---|---|---|---| | `--extension` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [settings/v1](https://pocketone.dev/docs/contracts/settings/v1) (generated). ### pocketone remote settings list Names the extensions whose settings this app's admins can change (settings/v1) ``` pocketone remote settings list ``` Names the extensions whose settings this app's admins can change. Calls GET /api/\_c/settings/v1/ on the remote (token scope: settings:read). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [settings/v1](https://pocketone.dev/docs/contracts/settings/v1) (generated). ### pocketone remote settings save Replaces one extension's settings and applies them (settings/v1) ``` pocketone remote settings save ``` Replaces one extension's settings and applies them. A secret left empty keeps its saved value. Settings a host sets are read-only here. Calls POST /api/\_c/settings/v1/save on the remote (token scope: settings). | Flag | Type | Default | | |---|---|---|---| | `--extension` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--values` | string | – | a JSON value (@file reads a file) | From [settings/v1](https://pocketone.dev/docs/contracts/settings/v1) (generated). ### pocketone remote settings test Checks one extension's settings without saving them (a test write to a bucket, a test message) (settings/v1) ``` pocketone remote settings test ``` Checks one extension's settings without saving them (a test write to a bucket, a test message). Calls POST /api/\_c/settings/v1/test on the remote (token scope: settings). | Flag | Type | Default | | |---|---|---|---| | `--extension` | string | – | | | `--json` | string | – | the whole input as JSON (@file reads a file, - reads stdin); flags override its fields | | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | | `--values` | string | – | a JSON value (@file reads a file) | From [settings/v1](https://pocketone.dev/docs/contracts/settings/v1) (generated). ### pocketone remote status Reports whether the app is running, its versions, uptime and mode (remote/v1) ``` pocketone remote status ``` Reports whether the app is running, its versions, uptime and mode. Calls GET /api/\_c/remote/v1/status on the remote (token scope: remote:read). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [remote/v1](https://pocketone.dev/docs/contracts/remote/v1) (generated). ### pocketone remote vacuum Calls vacuum/v1 on a remote ### pocketone remote vacuum status Says who compacts the app's databases, whether and how often, and how the last run went (vacuum/v1) ``` pocketone remote vacuum status ``` Says who compacts the app's databases, whether and how often, and how the last run went. Calls GET /api/\_c/vacuum/v1/ on the remote (token scope: vacuum:read). | Flag | Type | Default | | |---|---|---|---| | `-r`, `--remote` | string | – | the remote (a name or URL); default: the project's default remote | From [vacuum/v1](https://pocketone.dev/docs/contracts/vacuum/v1) (generated). ### pocketone remote whoami Shows who you are on a remote and what it offers ``` pocketone remote whoami [remote] ``` From [Remotes](https://pocketone.dev/docs/extensions/remotes). ## pocketone restart Restarts a remote's app so it applies new migrations and packages ``` pocketone restart [remote] ``` From [Deploy](https://pocketone.dev/docs/extensions/deploy). ## pocketone serve Starts the web server (default to 127.0.0.1:8090 if no domain is specified) ``` pocketone serve [domain(s)] ``` | Flag | Type | Default | | |---|---|---|---| | `--automigrate` | bool | `true` | enable/disable auto migrations | | `--autotls` | bool | – | HTTPS certificates through CertMagic instead of the built-in autocert (with serve <domain> or `--https`): other CAs, extra domains, wildcards through DNS-01 | | `--autotlsCA` | string | – | certificate authority for `--autotls`: letsencrypt (default), letsencrypt-staging, zerossl, or an ACME directory URL | | `--autotlsDNS` | string | – | DNS provider for DNS-01 challenges with `--autotls` (supported: cloudflare) | | `--autotlsDNSTokenEnv` | string | `CF_API_TOKEN` | environment variable holding the DNS provider's API token for `--autotlsDNS` | | `--autotlsDomains` | stringSlice | – | extra domains for `--autotls`, obtained at start (comma separated; wildcards like \*.example.com need `--autotlsDNS`) | | `--autotlsEmail` | string | – | ACME account email for `--autotls` (expiry notices from the CA) | | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--hooksWatch` | bool | `true` | auto restart the app on pb\_hooks file change; it has no effect on Windows | | `--http` | string | – | TCP address to listen for the HTTP server (if domain args are specified - default to 0.0.0.0:80, otherwise - default to 127.0.0.1:8090) | | `--https` | string | – | TCP address to listen for the HTTPS server (if domain args are specified - default to 0.0.0.0:443, otherwise - default to empty string, aka. no TLS) The incoming HTTP traffic also will be auto redirected to the HTTPS version | | `--indexFallback` | bool | `true` | fallback the request to index.html on missing static path, e.g. when pretty urls are used with SPA | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--origins` | stringSlice | `[*]` | CORS allowed domain origins list | | `--pagesDir` | string | – | the directory with the app's pages (default pb\_pages next to pb\_data); served when it exists | | `--pitr` | bool | `true` | point-in-time restore: replicate data.db into pb\_data/litestream/ while serving | | `--pitrRetention` | duration | `72h0m0s` | how far back a point-in-time restore can go | | `--publicDir` | string | `/pb_public` | the directory to serve static files | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | | `--s3Redirect` | bool | `true` | answer file downloads with a short-lived signed redirect to the bucket when S3 file storage is on | | `--s3RedirectTTL` | duration | `5m0s` | how long each signed file download URL stays valid | From PocketBase. ## pocketone superuser Manage superusers From PocketBase. Every `pocketone superuser` command takes these. | Flag | Type | Default | | |---|---|---|---| | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | ### pocketone superuser create Creates a new superuser ``` pocketone superuser create ``` From PocketBase. ### pocketone superuser delete Deletes an existing superuser ``` pocketone superuser delete ``` From PocketBase. ### pocketone superuser ips Updates the superuser IPs whitelist setting (the IPs/subnets arguments must be space separated; leave empty to clear the whitelist restriction) ``` pocketone superuser ips ``` From PocketBase. ### pocketone superuser otp Creates a new OTP for the specified superuser ``` pocketone superuser otp ``` From PocketBase. ### pocketone superuser update Changes the password of a single superuser ``` pocketone superuser update ``` From PocketBase. ### pocketone superuser upsert Creates, or updates if email exists, a single superuser ``` pocketone superuser upsert ``` From PocketBase. ## pocketone template Lists and ejects extensions' page templates (pb\_templates) From [Templates](https://pocketone.dev/docs/extensions/templates). Every `pocketone template` command takes these. | Flag | Type | Default | | |---|---|---|---| | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | ### pocketone template eject Copies a template set (every set without a name) into pb\_templates/<set>/ for you to edit ``` pocketone template eject [set] ``` Copies the set's built-in Go templates into pb\_templates/<set>/; the app renders your copy of each file from then on (delete a file to go back to the built-in one). Files you already have and haven't changed are left alone; files you changed are only overwritten after you confirm, or with --force. | Flag | Type | Default | | |---|---|---|---| | `--force` | bool | – | overwrite files you changed without asking | From [Templates](https://pocketone.dev/docs/extensions/templates). ### pocketone template list Lists the template sets extensions offer, and what you've changed in pb\_templates ``` pocketone template list ``` From [Templates](https://pocketone.dev/docs/extensions/templates). ## pocketone token Manage API tokens (pbt\_...) From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). Every `pocketone token` command takes these. | Flag | Type | Default | | |---|---|---|---| | `--dev` | bool | – | enable dev mode, aka. printing logs and sql statements to the console | | `--dir` | string | `/pb_data` | the PocketBase data directory | | `--encryptionEnv` | string | – | the env variable whose value of 32 characters will be used as encryption key for the app settings (default none) | | `--hooksDir` | string | – | the directory with the JS app hooks | | `--hooksPool` | int | `15` | only with `--jsvm` goja: the JS runtimes kept ready for hooks | | `--jsvm` | string | `quickjs` | the JS engine: quickjs (PocketOne's) or goja (PocketBase's own, for pure PocketBase compatibility) | | `--migrationsDir` | string | – | the directory with the user defined migrations | | `--queryTimeout` | int | `30` | the default SELECT queries timeout in seconds | ### pocketone token create Creates an API token and prints its secret (shown once) ``` pocketone token create ``` | Flag | Type | Default | | |---|---|---|---| | `--collection` | string | – | owner: auth collection (with `--record`) | | `--name` | string | – | a name to recognize the token by | | `--record` | string | – | owner: record id or email in `--collection` | | `--scope` | stringSlice | – | limit the token to a scope, name or name=value (repeatable; none: the owner's full rights) | | `--superuser` | string | – | owner: a superuser's email | | `--ttl` | duration | `0s` | lifetime, e.g. 720h (default: never expires) | From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ### pocketone token list Lists API tokens (all, or one owner's) ``` pocketone token list ``` | Flag | Type | Default | | |---|---|---|---| | `--collection` | string | – | owner: auth collection (with `--record`) | | `--record` | string | – | owner: record id or email in `--collection` | | `--superuser` | string | – | owner: a superuser's email | From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ### pocketone token revoke Revokes API tokens by id, or all of one owner's (--all) ``` pocketone token revoke [id...] ``` | Flag | Type | Default | | |---|---|---|---| | `--all` | bool | – | revoke every token of the owner | | `--collection` | string | – | owner: auth collection (with `--record`) | | `--record` | string | – | owner: record id or email in `--collection` | | `--superuser` | string | – | owner: a superuser's email | From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ### pocketone token scopes Lists the scopes extensions registered ``` pocketone token scopes ``` From [API Tokens](https://pocketone.dev/docs/extensions/api-tokens). ## pocketone upgrade Upgrades this executable to the latest release, keeping the old one as <name>-<version> ``` pocketone upgrade ``` Upgrades this executable to the latest release, keeping the old one as <name>-<version>. The newest release is offered, prereleases included. Moving from a stable release to a prerelease asks first (no means the newest stable release instead, if there's a newer one); from one prerelease to the next it doesn't. | Flag | Type | Default | | |---|---|---|---| | `--backup` | bool | `true` | Back up pb\_data after upgrading, if this folder has one | | `-y`, `--yes` | bool | – | Move from a stable release to a prerelease without asking | From [Upgrade](https://pocketone.dev/docs/extensions/upgrade). --- Source: https://pocketone.dev/docs/reference/mcp # MCP reference A PocketOne app serves MCP at `/mcp` ([MCP](https://pocketone.dev/docs/extensions/mcp)): PocketBase's whole API as `pb_*` tools, the tools your `pb_hooks` add, and one tool per operation of every contract the app provides, listed here for the [standard set](https://pocketone.dev/docs/extensions/standard). Each contract tool calls the contract, so it passes the same token scope check and hooks as the REST API and the CLI ([how](https://pocketone.dev/docs/features/remote)). Uploads and downloads have no tool. ## api-tokens.verify/v1 [Contract page](https://pocketone.dev/docs/contracts/api-tokens.verify/v1). Answered by [API Tokens](https://pocketone.dev/docs/extensions/api-tokens) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `api-tokens_verify_verify` | Checks an API token and says who it acts as and what it may do (its scopes, with their values). | | `api_tokens_verify` | `token` (string), `ip` (string) | ## bulkmail/v1 [Contract page](https://pocketone.dev/docs/contracts/bulkmail/v1). Answered by [Bulk Mail](https://pocketone.dev/docs/extensions/bulkmail) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `bulkmail_count` | Says how many recipients an audience reaches, how many of them are suppressed, and a few sample addresses. | | `bulkmail:read` | `audience` (json) | | `bulkmail_start` | Queues a campaign's recipients and starts sending (Limit > 0: at most that many new recipients). | | `bulkmail` | `campaign` (string), `limit` (int) | | `bulkmail_pause` | Stops sending a campaign; Resume carries on. | | `bulkmail` | `campaign` (string) | | `bulkmail_resume` | Carries on sending a paused campaign. | | `bulkmail` | `campaign` (string) | | `bulkmail_cancel` | Stops a campaign for good; recipients not yet sent to are dropped. | | `bulkmail` | `campaign` (string) | | `bulkmail_preview` | Renders a campaign's message for one recipient (the first in its audience when Email is empty). | | `bulkmail:read` | `campaign` (string), `email` (string) | | `bulkmail_test` | Sends a campaign's message to one address, marked as a test. | | `bulkmail` | `campaign` (string), `to` (string) | ## cache.clear/v1 [Contract page](https://pocketone.dev/docs/contracts/cache.clear/v1). Answered by [Cache](https://pocketone.dev/docs/extensions/cache) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `cache_clear_clear` | Empties one of the app's cache buckets, or every bucket it has. | | `cache` | `bucket` (string) | ## instance.watch/v1 [Contract page](https://pocketone.dev/docs/contracts/instance.watch/v1). | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `instance_watch_stream` | Opens this edge's stream: a hello first, then answers and changes for the hostnames it watches, the edges list when it changes, and its standing set when that changes. | yes | `fleet` | `edge` (string) | | `instance_watch_watch` | Registers a hostname on a stream and sends its answer there (or, with no live stream, in the reply). | | `fleet` | `conn` (string), `edge` (string), `host` (string) | | `instance_watch_unwatch` | Stops changes for a hostname on a stream. | | `fleet` | `conn` (string), `host` (string) | ## kv/v1 [Contract page](https://pocketone.dev/docs/contracts/kv/v1). Answered by [Key-Value Store](https://pocketone.dev/docs/extensions/kv/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `kv_list` | Returns the values whose names start with prefix (all of them when it's empty), sorted by name. | yes | `kv:read` | `prefix` (string) | | `kv_get` | Returns one value. | yes | `kv:read` | `name` (string) | | `kv_set` | Stores a JSON value under a name, replacing any value it had. | | `kv` | `name` (string), `value` (json) | | `kv_delete` | Removes a value. | | `kv` | `name` (string) | ## llm.align/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.align/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_align_align` | Says when each line and word of the text is said in the audio. | | `llm` | `model` (string), `audio` (json), `text` (string), `mode` (string), `language` (string), `options` (json) | | `llm_align_models` | Lists the alignment models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.chat/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.chat/v1). Answered by [LLM Chat](https://pocketone.dev/docs/extensions/llm-chat) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_chat_new` | Starts a chat and returns it; its id is how the app finds it again. | | `chat` | `title` (string), `meta` (json) | | `llm_chat_send` | Asks the chat a question: the provider sends the system text, the chat's summary, its recent messages and the question (with Context after it) to llm.text/v1, saves both turns, and folds older messages into the summary when it's due. | | `chat` | `id` (string), `text` (string), `system` (string), `window` (int), `summarizeEvery` (int), `context` (string), `schema` (json), `maxTokens` (int), `temperature` (json), `model` (string), `reasoning` (string), `enrich` (json) | | `llm_chat_send_stream` | Is Send with the answer as it's written: llm.text/v1 chunks, the last one with done and the result. | | `chat` | `id` (string), `text` (string), `system` (string), `window` (int), `summarizeEvery` (int), `context` (string), `schema` (json), `maxTokens` (int), `temperature` (json), `model` (string), `reasoning` (string), `enrich` (json) | | `llm_chat_get` | Returns a chat. | | `chat:read` | `id` (string) | | `llm_chat_history` | Returns a chat's messages, oldest first: the last Limit before the message Before (all when 0 and ""). | | `chat:read` | `id` (string), `limit` (int), `before` (string) | | `llm_chat_update` | Sets a chat's title or meta (fields left out stay). | | `chat` | `id` (string), `title` (json), `meta` (json) | | `llm_chat_list` | Returns chats, most recently updated first; Meta keeps those whose meta has each of its top-level keys with that value. | | `chat:read` | `meta` (json), `limit` (int), `offset` (int) | | `llm_chat_forget` | Deletes a chat, its messages and the model's state for it. | | `chat` | `id` (string) | | `llm_chat_forget_where` | Deletes every chat whose meta matches (as in List), e.g. | | `chat` | `meta` (json), `limit` (int), `offset` (int) | ## llm.embed/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.embed/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_embed_embed` | Returns one vector per input text, in order. | | `llm` | `model` (string), `input` (strings), `dimensions` (int), `options` (json) | | `llm_embed_models` | Lists the embedding models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.image/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.image/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_image_generate` | Makes pictures from a prompt, and from the reference pictures it's given. | | `llm` | `model` (string), `prompt` (string), `n` (int), `size` (string), `aspectRatio` (string), `references` (json), `options` (json) | | `llm_image_models` | Lists the image models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.ledger/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.ledger/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_ledger_remaining` | Is, for each limit in Settings → LLM that counts the subject's calls, how much is used and left in its current window, the tightest first. | yes | public | `subject` (string) | | `llm_ledger_spent` | Is what the subject's calls used in a window. | yes | public | `subject` (string), `window` (string), `since` (string), `until` (string), `kind` (string), `model` (string) | | `llm_ledger_summary` | Is what calls used, grouped by model, kind, subject or day. | yes | `llm:read` | `by` (string), `window` (string), `since` (string), `until` (string), `subject` (string), `kind` (string), `model` (string), `limit` (int) | | `llm_ledger_calls` | Lists the ledger's rows, newest first. | yes | `llm:read` | `window` (string), `since` (string), `until` (string), `subject` (string), `kind` (string), `model` (string), `status` (string), `limit` (int), `offset` (int) | ## llm.music/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.music/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_music_create` | Starts making music. | | `llm` | `model` (string), `prompt` (string), `lyrics` (string), `seconds` (float), `wait` (string), `options` (json) | | `llm_music_get` | Says how a job is going. | | `llm:read` | `id` (string) | | `llm_music_content` | Fetches one of a done job's files. | | `llm:read` | `id` (string), `index` (int) | | `llm_music_models` | Lists the music models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.search/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.search/v1). Answered by [LLM Search](https://pocketone.dev/docs/extensions/llm-search) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_search_status` | Is the app's embedding model and how far embedding has got across every bucket. | yes | `search:read` | | | `llm_search_set_model` | Changes the app's embedding model ("provider/model" from llm.embed/v1's models; "" picks one again). | | `search` | `model` (string) | | `llm_search_buckets` | Lists the app's buckets with their counts. | yes | `search:read` | | | `llm_search_bucket` | Returns one bucket with its counts. | yes | `search:read` | `name` (string) | | `llm_search_ensure` | Makes a bucket if it's missing and returns it. | | `search` | `name` (string), `title` (string), `description` (string), `owner` (string) | | `llm_search_update` | Changes a bucket's title, description or limits (fields left out stay). | | `search` | `name` (string), `title` (json), `description` (json), `maxDocuments` (json), `maxBytes` (json) | | `llm_search_delete` | Removes a bucket and everything in it. | | `search` | `name` (string) | | `llm_search_sources` | Lists a bucket's sources, by name. | yes | `search:read` | `bucket` (string) | | `llm_search_add` | Puts a file or pasted text in a bucket as its own source (one document), replacing the source of that name. | | `search` | `bucket` (string), `name` (string), `text` (string), `kind` (string), `replace` (string) | | `llm_search_put` | Adds one file to a folder source (made on the first one), the way the dashboard sends a dropped folder; Prune ends it. | | `search` | `bucket` (string), `source` (string), `path` (string), `text` (string), `replace` (string) | | `llm_search_prune` | Removes the documents of a folder source that aren't in Keep: the files the folder no longer has. | | `search` | `bucket` (string), `source` (string), `keep` (strings) | | `llm_search_add_u_r_l` | Adds a web page or a Git repository as a source (named by its URL, replacing one of that name) and reads it in the background; Every keeps it current. | | `search` | `bucket` (string), `url` (string), `kind` (string), `every` (string), `commits` (int), `exclude` (strings) | | `llm_search_add_folder` | Adds a folder of the app's own files on the server (named by its path, replacing one of that name): every text file in it, read in the background and read again every few minutes, so changed files are embedded again and removed ones leave. | | `search` | `bucket` (string), `path` (string), `include` (strings), `exclude` (strings), `url` (string) | | `llm_search_detect_u_r_l` | Says how AddURL would read a URL: as a Git repository when its server answers the Git protocol (any host, with or without .git), otherwise as a web page. | | `search:read` | `url` (string) | | `llm_search_follow` | Adds one of the app's collections as a source (named by the collection): each record the filter keeps is a document, kept in sync as records are saved and deleted. | | `search` | `bucket` (string), `collection` (string), `fields` (strings), `filter` (string) | | `llm_search_refresh` | Reads a source again now: fetches a URL or repository, rereads a collection, resplits a file or zip. | | `search` | `bucket` (string), `source` (string) | | `llm_search_remove` | Takes sources out of a bucket, with their documents. | | `search` | `bucket` (string), `sources` (strings) | | `llm_search_documents` | Lists a bucket's documents (or one source's), by source and name. | yes | `search:read` | `bucket` (string), `source` (string), `prefix` (string) | | `llm_search_search` | Returns the chunks that best match a query across the buckets named, best first. | | `search:read` | `buckets` (strings), `bucket` (string), `query` (string), `limit` (int), `prefix` (string), `viewer` (json) | | `llm_search_sample` | Returns chunks picked at random from the buckets named: material to draw from ("surprise me", a topic nobody asked about), not matches. | | `search:read` | `buckets` (strings), `bucket` (string), `count` (int), `prefix` (string) | ## llm.speech/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.speech/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_speech_speak` | Reads the text aloud and returns the audio. | | `llm` | `model` (string), `text` (string), `voice` (string), `format` (string), `speed` (float), `instructions` (string), `reference` (json), `options` (json) | | `llm_speech_voices` | Lists a model's voices, when the provider says. | | `llm:read` | `model` (string) | | `llm_speech_models` | Lists the speech models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.text/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.text/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_text_complete` | Answers a prompt or a conversation. | | `llm` | `model` (string), `system` (string), `prompt` (string), `messages` (json), `schema` (json), `maxTokens` (int), `temperature` (json), `stop` (strings), `reasoning` (string), `options` (json), `enrich` (json) | | `llm_text_stream` | Answers like Complete, sending the answer as it's written: a chunk with text (or reasoning) for each piece, then one with done and the whole result. | | `llm` | `model` (string), `system` (string), `prompt` (string), `messages` (json), `schema` (json), `maxTokens` (int), `temperature` (json), `stop` (strings), `reasoning` (string), `options` (json), `enrich` (json) | | `llm_text_count` | Says about how many tokens a text or a conversation is, for budgeting what to send. | | `llm:read` | `model` (string), `text` (string), `system` (string), `messages` (json) | | `llm_text_models` | Lists the text models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.transcribe/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.transcribe/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_transcribe_transcribe` | Writes down what's said in the audio. | | `llm` | `model` (string), `audio` (json), `language` (string), `prompt` (string), `options` (json) | | `llm_transcribe_models` | Lists the transcription models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## llm.video/v1 [Contract page](https://pocketone.dev/docs/contracts/llm.video/v1). Answered by [LLM](https://pocketone.dev/docs/extensions/llm/extension) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `llm_video_create` | Starts making a video. | | `llm` | `model` (string), `prompt` (string), `image` (json), `seconds` (float), `size` (string), `aspectRatio` (string), `wait` (string), `options` (json) | | `llm_video_get` | Says how a job is going. | | `llm:read` | `id` (string) | | `llm_video_content` | Fetches one of a done job's files. | | `llm:read` | `id` (string), `index` (int) | | `llm_video_models` | Lists the video models of every provider in Settings → LLM. | yes | `llm:read` | `provider` (string) | ## mail.suppression/v1 [Contract page](https://pocketone.dev/docs/contracts/mail.suppression/v1). Answered by [Bulk Mail](https://pocketone.dev/docs/extensions/bulkmail) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `mail_suppression_check` | Says whether an address is suppressed, and why. | yes | `suppression:read` | `email` (string) | | `mail_suppression_suppress` | Adds an address (or changes its reason). | | `suppression` | `email` (string), `reason` (string), `source` (string), `campaign` (string) | | `mail_suppression_unsuppress` | Removes an address, so it receives bulk mail again. | | `suppression` | `email` (string) | ## remote/v1 [Contract page](https://pocketone.dev/docs/contracts/remote/v1). Answered by [Remotes](https://pocketone.dev/docs/extensions/remotes) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `remote_whoami` | Says who the credential is, the app's name and URL, and the contracts it offers. | yes | public | | | `remote_status` | Reports whether the app is running, its versions, uptime and mode. | yes | `remote:read` | | | `remote_restart` | Restarts the app; requests in flight finish first. | | `remote` | | | `remote_logs` | Streams the app's log: the last entries, then new ones as they're written. | yes | `remote:read` | `n` (int) | ## restore/v1 [Contract page](https://pocketone.dev/docs/contracts/restore/v1). Answered by [PITR](https://pocketone.dev/docs/extensions/pitr) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `restore_points` | Says what the app's data can be restored to: a window of time (continuous history) or a list of moments (backups), and whether a restore is running. | yes | `restore:read` | | | `restore_restore_to` | Puts the app's data back as it was at the given moment, from the latest point at or before it. | | `restore` | `at` (time) | ## settings/v1 [Contract page](https://pocketone.dev/docs/contracts/settings/v1). Answered by [Settings](https://pocketone.dev/docs/extensions/settings) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `settings_list` | Names the extensions whose settings this app's admins can change. | yes | `settings:read` | | | `settings_get` | Returns one extension's settings. | yes | `settings:read` | `extension` (string) | | `settings_save` | Replaces one extension's settings and applies them. | | `settings` | `extension` (string), `values` (json) | | `settings_test` | Checks one extension's settings without saving them (a test write to a bucket, a test message). | | `settings` | `extension` (string), `values` (json) | ## vacuum/v1 [Contract page](https://pocketone.dev/docs/contracts/vacuum/v1). Answered by [Vacuum](https://pocketone.dev/docs/extensions/vacuum) in the standard set. | Tool | What it does | Reads only | Token scope | Arguments | |---|---|---|---|---| | `vacuum_status` | Says who compacts the app's databases, whether and how often, and how the last run went. | yes | `vacuum:read` | | --- Source: https://pocketone.dev/docs/config-reference # pocketone.yaml reference Every section the `pocketone` binary understands, from `pocketone config --json`. Each extension owns its own section. `pocketone config check` checks a file. How the file works (where it's found, `.env` secrets) is on the [Config](https://pocketone.dev/docs/extensions/config) page. #### `api-tokens:` Turns the api-tokens extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.api-tokens`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `app:` The single app, for every command that opens it: data dir, dev mode, encryption, JS engine, hooks, migrations, and the .env names it may read (env_allow). Not used on a multisite host. | Key | Type | Default | Description | |---|---|---|---| | `dir` | string | | The data folder (pb_data). Default: pb_data next to the executable. The --dir flag wins. | | `dev` | bool | | Dev mode: logs and SQL statements printed to the console. The --dev flag wins. | | `encryption_env` | string | | Name of the environment variable holding a 32-character key that encrypts the app settings. The --encryptionEnv flag wins. | | `query_timeout` | duration | | Default timeout for SELECT queries, such as 30s. The --queryTimeout flag wins. | | `hooks_dir` | string | | The JS hooks folder. Default: pb_hooks next to pb_data. The --hooksDir flag wins. | | `jsvm` | string | | The JS engine for pb_hooks and pb_migrations: quickjs (PocketOne's, the default) or goja (PocketBase's own, for pure PocketBase compatibility: pages, $mcp, $apiTokens and JS contracts are off). The --jsvm flag wins. | | `hooks_pool` | int | | Only with jsvm: goja: how many JS runtimes are kept ready for hooks. Default 15. The --hooksPool flag wins. | | `migrations_dir` | string | | The migrations folder. Default: pb_migrations next to pb_data. The --migrationsDir flag wins. | | `env_allow` | list of string | | Names from the .env the app and its JS hooks may read. Default none. | | `js_limits.memory` | int | | The app's JS memory: the JS heap plus the Go objects JS holds, such as 128MiB. Default 64MiB. | | `js_limits.task_time` | duration | | JS time one stretch of a task (a request, a hook, a cron job, each part between awaits) may use, Go calls and waits not counted, such as 10s. Default 5s. | | `js_limits.task_wall` | duration | | Wall time one stretch of JS may take, sync Go calls included, such as 60s; an async handler's awaits end a stretch and don't count. Default 30s. | | `js_limits.await_time` | duration | | How long an async handler (a request, a hook, a cron job) may take in all, awaits included, such as 30m; past it, or when the client goes away, the handler stops at its next await. Default 15m. | #### `autotls:` Automatic HTTPS certificates (ACME): auto, email, CA, domains, DNS-01, certificate storage. The --autotls* flags win. | Key | Type | Default | Description | |---|---|---|---| | `auto` | bool | | Get certificates through ACME (CertMagic). Flag: --autotls. | | `email` | string | | ACME account email, for expiry notices from the CA. Flag: --autotlsEmail. | | `ca` | string | | letsencrypt (default), letsencrypt-staging, zerossl, or an ACME directory URL. Flag: --autotlsCA. | | `storage` | string | | Where certificates are kept. Default pb_data/.autotls. | | `domains` | list of string | | Extra domains to get at start; wildcards (*.example.com) need dns. Flag: --autotlsDomains. | | `dns.provider` | string | | DNS provider for DNS-01 challenges (needed for wildcards): cloudflare. Flag: --autotlsDNS. | | `dns.api_token` | string | | The provider's API token. Write $VAR to read it from the .env beside the file. | | `dns.api_token_env` | string | | Or: the environment variable holding the token. Default CF_API_TOKEN. Flag: --autotlsDNSTokenEnv. | Owned by [Auto TLS](https://pocketone.dev/docs/extensions/autotls). #### `backups:` Turns the backups extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.backups`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `bulkmail:` Turns the bulkmail extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.bulkmail`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `cache:` The cache (cache/v1): one store for every app in the process (memory, disk tier), and caps per bucket. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | Turns the cache off when false; extensions then run uncached. | | `eviction` | string | | Which values leave memory (or disk) first when the store reaches its ceiling: lru, mru, fifo or lifo. | | `max_memory` | int | | Memory for every bucket together, such as 512MiB. Default 128MiB. | | `disk` | bool | | Turns on a disk tier in pb_cache/cache, next to pb_data (on a multisite host, the host's own pb_cache). | | `disk_path` | string | | Puts the disk tier in a cache folder there instead of pb_cache, and turns it on. Relative: to the app's folder (the one holding pb_data) when the app has the process to itself, the working directory when several apps share it (Pocker). | | `max_disk` | int | | Size of the disk tier for every bucket together, such as 10GiB. Default 1GiB. | | `defaults.eviction` | string | | Which of the bucket's entries go first when it's full: lru, mru, fifo or lifo. | | `defaults.max_items` | int | | Most entries the bucket holds. | | `defaults.max_memory` | int | | Most bytes of keys and values the bucket holds in memory, such as 32MiB (the default). | | `defaults.max_disk` | int | | Most bytes of disk files the bucket's keys point at, each counted in full, such as 256MiB (the default). | | `defaults.ttl` | int | | How long an entry lives unless the code says otherwise, such as 10m. | | `buckets` | map of object | | Caps per bucket name, over what its code asks for. | Owned by [Cache](https://pocketone.dev/docs/extensions/cache). #### `deploy:` Turns the deploy extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.deploy`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `desktop:` How `pocketone desktop build` names and sizes the desktop app built from this folder. | Key | Type | Default | Description | |---|---|---|---| | `name` | string | | The app's name: the window title and the executable's name. Default: the folder's name. | | `id` | string | | Reverse-DNS app id (dev.example.notes): names the app's data folder on each user's machine and its single-instance lock. Default: app.pocketone.. | | `width` | int | | The window's starting width. Default: 1024. | | `height` | int | | The window's starting height. Default: 768. | | `sign.macos.identity` | string | | The signing identity in your keychain, as security find-identity -v -p codesigning shows it: Developer ID Application: Your Name (TEAMID). | | `sign.macos.notary_profile` | string | | The notarytool keychain profile (xcrun notarytool store-credentials ). Set: each DMG is notarized and stapled. Empty: signed, not notarized. | | `sign.windows.command` | string | | The command that signs one executable in place; {file} is its path. signtool on Windows, osslsigncode anywhere, or your signing service's tool. | | `sign.linux.gpg_key` | string | | The GPG key to sign with (its email or id). Each build gets .sha256 and a detached .asc signature. | Owned by [Desktop](https://pocketone.dev/docs/extensions/desktop). #### `docker:` Runtime provider docker: each instance in its own container with the PocketBase (pb:) or PocketOne (p1:) binary of its version (image, binary cache and manifest, instance root, default version, idle stop, limits). | Key | Type | Default | Description | |---|---|---|---| | `socket` | string | | The Docker socket. Default $DOCKER_HOST when it is unix://, else /var/run/docker.sock. | | `image` | string | | Base image the binaries run in, such as alpine:3.20. Required; pulled when missing. | | `binaries` | string | | Folder of the release binary cache and its releases.json. Required. | | `versions` | list of string | | The minors this host serves, such as pb:0.36 or p1:0.0 (latest patch of each, from docker update). | | `root` | string | | Folder with one folder per instance (/). Required. | | `home` | string | | The instance folder inside the container. Default /home/pockethost. | | `default_version` | string | | Version for instances that name none, such as p1:0.0.*. Empty: such instances fail. | | `min_upstream` | string | | Oldest upstream PocketBase release served. Default 0.23.0; lower it only for releases you cache yourself. | | `idle_ttl` | duration | | Stop a container after this long without requests. Default 10m. | | `max_concurrent_starts` | int | | Containers starting at once. Default 4. | | `start_timeout` | duration | | How long a container gets to answer its health check. Default 60s. | | `nano_cpus` | int | | CPU limit per container in billionths of a CPU (1000000000 = one CPU). 0: no limit. | | `pids_limit` | int | | Process limit per container. 0: Docker's default. | | `nofile` | list of int | | Open-file limit per container: [soft, hard]. Empty: Docker's default. | | `cap_drop` | list of string | | Linux capabilities to drop, such as [ALL]. | | `no_new_privileges` | bool | | Set no-new-privileges on every container. | | `network` | string | | Docker network for the containers. Default the bridge. | | `adopt_image` | string | | Also adopt running unlabeled containers of this image named after an instance id (taking over from another manager). | Owned by [Docker](https://pocketone.dev/docs/extensions/docker). #### `edges:` The fleet: this edge's id and a fixed list of the other edges (id, internal_url, region). | Key | Type | Default | Description | |---|---|---|---| | `self` | string | | This edge's id, such as lax-1. | | `list` | list of object | | The other edges: id, internal_url (where this edge reaches it) and optional region. | Owned by [Edge](https://pocketone.dev/docs/extensions/edge). #### `firewall:` Peers allowed to connect, trusted proxies and client-IP headers, trusted clients, the rate-limit header prefix. Turns the firewall on. | Key | Type | Default | Description | |---|---|---|---| | `allow_cidrs` | list of string | | Peers (IPs or CIDRs) allowed to connect; others get 403. Empty: everyone. | | `trusted_proxies` | list of string | | Peers whose client-IP headers are believed. | | `client_ip_headers` | list of string | | Headers read, in order, for the client IP from a trusted proxy. Default CF-Connecting-IP, True-Client-IP, X-Forwarded-For, X-Real-IP. | | `trusted_clients` | list of string | | Client IPs or CIDRs that get the trusted rate limits on every instance. | | `trusted_client_headers` | list of string | | Headers a trusted client uses to name its end user's IP, so each user gets their own limits. Default X-Client-IP. | | `rate_limit_header_prefix` | string | | Prefix of the rate-limit response headers. Default X-RateLimit. | Owned by [Firewall](https://pocketone.dev/docs/extensions/firewall). #### `instances:` Where a multi-instance host's instances come from (a YAML file), and dev mode (serve unknown hostnames). | Key | Type | Default | Description | |---|---|---|---| | `file` | string | `instances.yaml` | The instances file (id, hosts and settings for each instance), reloaded when it changes. | | `dev` | bool | | Also serve unknown hostnames: each becomes an instance named after it, in dev mode, with its folder made on first use. | Owned by [Multisite](https://pocketone.dev/docs/extensions/multisite). #### `kv:` Turns the kv extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.kv`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `lifecycle:` Instance data on this host: how often disk use is measured and last-request times are reported. | Key | Type | Default | Description | |---|---|---|---| | `measure_every` | duration | `24h0m0s` | How old an instance's disk measurement may get before it is measured again. Default 24h. | | `report_every` | duration | `1h0m0s` | How often changed last-request times are reported to the sink. Default 1h. | | `concurrency` | int | `2` | How many instances are measured at once. Default 2. | Owned by [Stats](https://pocketone.dev/docs/extensions/stats). #### `llm:` Cloud models for $llm (the llm.* contracts); providers and keys are set in Settings → LLM. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | false turns the extension off on this app ($llm and the llm.* contracts are gone). | Owned by [LLM](https://pocketone.dev/docs/extensions/llm). #### `llm-chat:` Turns the llm-chat extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.llm-chat`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `llm-search:` Turns the llm-search extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.llm-search`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `mcp:` Turns the mcp extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.mcp`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `mothership:` A community mothership: serve: true makes this app one; url, login and self make a host follow one. | Key | Type | Default | Description | |---|---|---|---| | `serve` | bool | | This app is the mothership: it serves instance.watch/v1 to its edges (and keeps the edges and instances collections). | | `apex` | string | | On the mothership: makes . a hostname of every instance. Empty: hosts only. | | `url` | string | | On an edge: the mothership's URL. Required there. | | `email` | string | | Superuser email this edge logs in with; use a $VAR from the .env. | | `password` | string | | Superuser password; use a $VAR from the .env. | | `self` | string | | This edge's edge_id, such as lax-1. Default: the edges section's self. Required on an edge. | | `internal_url` | string | | Where other edges reach this one. Set: the edge registers itself when the mothership has no record for it. | | `region` | string | | Region recorded when the edge registers itself. | | `heartbeat` | duration | | How often this edge marks itself online. Default 15s; negative: never. | | `max_hosts` | int | | Most hostnames an edge keeps answers for (its cache bucket mothership.hosts). Default 50000. | Owned by [Mothership](https://pocketone.dev/docs/extensions/mothership). #### `multisite:` Serve many instances (a multisite host) instead of a single app. The runtimes are the providers of runtime/v1. Owned by [Multisite](https://pocketone.dev/docs/extensions/multisite). #### `pages:` Turns the pages extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.pages`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `pitr:` Point-in-time restore: on by default, retention, snapshot interval. The --pitr and --pitrRetention flags win. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. The --pitr flag wins. | | `retention` | duration | | How far back a restore can go. Default 72h. The --pitrRetention flag wins. | | `snapshot_interval` | duration | | How often a full copy is taken. Default 24h. Shorter: faster restores, more storage. | Owned by [PITR](https://pocketone.dev/docs/extensions/pitr). #### `pocker:` Runtime provider pocker: instances run as isolates in this process (root folder, hooks pool, egress allow list, instance limit defaults). | Key | Type | Default | Description | |---|---|---|---| | `root` | string | `./pb_root` | The folder holding one folder per instance: /. | | `hooks_pool_size` | int | `2` | Ignored: each instance has one JS VM (ext/jsvm). Kept so existing configs load. | | `max_js_execution` | duration | `30s` | Longest any single JS call (hook, route, cron job, migration) may run. | | `max_js_allocation` | int | `67108864` | Largest result a JS built-in may allocate in one step, such as 64MiB. | | `max_call_stack_size` | int | `2000` | Deepest JS recursion allowed. | | `max_sleep` | duration | `10s` | Longest a JS sleep() call may wait. | | `max_query_duration` | duration | `30s` | Longest an SQL statement without its own deadline may run. | | `http_send_max_timeout` | duration | `1m0s` | Longest timeout a JS $http.send call may use. | | `http_send_max_body` | int | `10485760` | Largest response body a JS $http.send call may read, such as 10MiB. | | `max_concurrent_js` | int | `16` | JS calls an instance runs at once; more wait up to max_js_execution, then fail. | | `egress_allow` | list of string | | Private networks (CIDRs) instances may still connect to. Default none: public addresses only. | | `isolate_config` | map of map of interface | | Every instance's config, in pocketone.yaml's shape: one section per extension the instances run, such as api-tokens: {enabled: false}. Each takes what an instance's extensions. takes, and an instance's own extensions. overrides it. | Owned by [Pocker](https://pocketone.dev/docs/extensions/pocker). #### `providers:` Which extension provides a contract when several do. Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `rate_limits:` Default rate limits for every instance (per instance: extensions.firewall.rate_limits). Turns the firewall on. | Key | Type | Default | Description | |---|---|---|---| | `ip_hourly` | int | | Requests per hour from one client IP to one instance. Default 1000. | | `instance_hourly` | int | | Requests per hour to one instance from everyone. Default 10000. | | `ip_concurrent` | int | | Requests one client IP may have open on one instance at once. Default 15. | | `instance_concurrent` | int | | Requests one instance may have open at once. Default 250. | | `file_weight` | number | | What a /api/files request costs, as a share of a request. Default 0.1. | | `trusted.ip_hourly` | int | | Requests per hour from one trusted client IP to one instance. | | `trusted.instance_hourly` | int | | Requests per hour to one instance. | | `trusted.ip_concurrent` | int | | Requests one trusted client IP may have open on one instance at once. | | `trusted.instance_concurrent` | int | | Requests one instance may have open at once. | | `off` | bool | | No rate limiting. The default in dev mode unless rate_limits is set. | Owned by [Firewall](https://pocketone.dev/docs/extensions/firewall). #### `remotes:` Turns the remotes extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.remotes`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `s3redirect:` Signed S3 redirects for file downloads: enabled, URL lifetime. The --s3Redirect and --s3RedirectTTL flags win. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false (it only acts when S3 file storage is on). Flag: --s3Redirect. | | `ttl` | duration | | How long each signed URL stays valid. Default 5m, max 7 days. Flag: --s3RedirectTTL. | Owned by [S3 Redirect](https://pocketone.dev/docs/extensions/s3redirect). #### `server:` The serve command: http, https and CORS origins, and for a single app its static files, pages, hooks watching and automigrate. | Key | Type | Default | Description | |---|---|---|---| | `http` | string | | Plain HTTP address, such as 127.0.0.1:8090. Single app: the --http default (the flag wins). Many instances: redirects to https when https is set. | | `https` | string | | HTTPS address. Single app: the --https default (the flag wins). Many instances: the main address. | | `origins` | list of string | | Allowed CORS origins. Single app: the --origins default (the flag wins). | | `plain` | list of string | | Many instances only: extra plain HTTP addresses with no redirect. | | `tls.cert` | string | | Many instances only: the certificate file, reloaded when it changes. | | `tls.key` | string | | Many instances only: the private key file, reloaded when it changes. | | `shutdown_timeout` | duration | | Many instances only: how long in-flight requests get to finish at stop. | | `public_dir` | string | | Single app only: the static files folder. Default: pb_public next to the executable. The --publicDir flag wins. | | `index_fallback` | bool | | Single app only: serve index.html for a missing static path, for single-page apps. On unless false. The --indexFallback flag wins. | | `pages_dir` | string | | Single app only: the pages folder, served when it exists. Default: pb_pages next to pb_data. The --pagesDir flag wins. | | `hooks_watch` | bool | | Single app only: restart the app when a pb_hooks file changes. On unless false. The --hooksWatch flag wins. | | `automigrate` | bool | | Single app only: write a migration file when you change collections in the dashboard. On unless false. The --automigrate flag wins. | #### `settings:` Turns the settings extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.settings`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `storage:` A default S3 bucket for apps without their own (on a multisite host, one folder per instance): backends and mounts for uploads, backups, PITR history. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On for every instance unless false; an instance's extensions.storage.enabled overrides it. | | `backends` | map of object | | Named S3-compatible destinations: endpoint, bucket, region, access_key, secret, prefix, force_path_style. | | `mounts` | map of string | | Filesystem kind (storage, backups, litestream, ...) to backend name. | | `bucket.endpoint` | string | | S3 endpoint URL. | | `bucket.bucket` | string | | Bucket name. | | `bucket.region` | string | | Bucket region (auto for R2). | | `bucket.access_key` | string | | Access key id. | | `bucket.secret` | string | | Secret key; use a $VAR from the .env. | | `bucket.prefix` | string | | Prepended to every key, to share a bucket. | | `bucket.force_path_style` | bool | | Path-style addressing, for MinIO and similar servers. | | `uploads` | bool | | Deprecated: with bucket, false keeps uploads off it. | | `backups` | bool | | Deprecated: with bucket, false keeps backups off it. | Owned by [S3 Fallback](https://pocketone.dev/docs/extensions/s3-fallback). #### `templates:` Turns the templates extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.templates`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `uicache:` Turns the uicache extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.uicache`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). #### `vacuum:` Defaults for compacting the app's SQLite databases (VACUUM): on or off, and how often. The app's admins change them in Settings. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | Compact the databases on a schedule, until the app's admins change it in Settings. | | `every` | string | `168h` | How often, e.g. 24h or 168h (weekly). | Owned by [Vacuum](https://pocketone.dev/docs/extensions/vacuum). #### `wasm:` Turns the wasm extension off on a single app (`enabled: false`). On a multisite host it doesn't reach the instances: use pocker's isolate_config, or an instance's `extensions.wasm`. | Key | Type | Default | Description | |---|---|---|---| | `enabled` | bool | | On unless false. Extensions that require it turn off too, and the startup lines say why. | Owned by [Standard Set](https://pocketone.dev/docs/extensions/standard). --- Source: https://pocketone.dev/docs/extensions # Extensions PocketOne is PocketBase plus extensions. An extension is a Go module in [`ext/`](https://github.com/pocketonehq/pocketone/tree/main/ext) that adds one feature to an app: point-in-time restore, deploys, API tokens, MCP, bulk mail, AI models, server-rendered pages. Each is compiled into the binary, registers itself on every app, and is configured in `pocketone.yaml`. PocketBase's own code ("core") changes only where an extension needs a place to hook in. This page is the reference for how extensions work. To build one, see [Writing an extension](https://pocketone.dev/docs/writing-an-extension); for the idea behind contracts, [How PocketOne fits together](https://pocketone.dev/docs/how-pocketone-fits-together). ## Kinds | Kind | What it is | Where | |---|---|---| | **Standard** | ships in every `pocketone` binary and runs on every app unless turned off | the [standard set](https://pocketone.dev/docs/extensions/standard) | | **Community** | in `ext/`, added to a custom Go build | the [catalogue](https://pocketone.dev/docs/extensions/all) | | **Host** | runs many apps on one server (isolates, docker, edges) | in the standard set, on only in that mode | Every extension has its own README (its page in the catalogue), a version, a changelog and owners. ## Turning one on and off - **Standard extensions** are on. Turn one off on a single app with `enabled: false` in its `pocketone.yaml` section: ```yaml bulkmail: enabled: false ``` Extensions that require it turn off too, and the startup lines say why. - **Community extensions** are added to a custom build in Go: `set.Add(myextension.New(...))` on the standard set. - **On a multisite host**, each instance's `extensions.` settings sit over the defaults, and `enabled: false` keeps an extension from running for that instance. ## What an extension is made of | Part | What it does | Where it shows | |---|---|---| | `Name()` | its config key, table prefix and log name | `pocketone.yaml` section `:`, collections `__*` | | `Register(app, cfg)` | binds it to an app: its hooks, its contracts | every app it runs on | | `Contracts()` | the contracts it implements, requires, wraps and works with | the startup lines, the contract catalogue | | Settings | its `pocketone.yaml` section, read on start | `pocketone config`, the [pocketone.yaml reference](https://pocketone.dev/docs/config-reference) | | Migrations | its own tables, tracked apart from the app's `pb_migrations` | `__*` collections | | `BindJS`, `TypeScript()` | a global for hooks and page code (`$llm`, `$kv`) and its types | the [JavaScript API](https://pocketone.dev/docs/reference/javascript) | | A dashboard screen | the contract's `UI` | the dashboard's sidebar | | Disposable files | caches it can rebuild | `pb_cache//` | An extension has no HTTP routes of its own. Everything a client can call is a contract. ## Contracts A contract is a named, versioned Go interface in [`ext/contracts`](https://pocketone.dev/docs/contracts): `deploy/v1`, `kv/v1`, `llm.text/v1`. Extensions meet only through contracts, never by importing each other: - An extension **provides** a contract (`Contract.Provide`) or a default that steps aside for any other provider (`ProvideDefault`). - An extension, a hook or a custom build **looks one up** by contract (`Contract.Must(app)`), not by extension. - A **wrapper** decorates whatever provides a contract (`Contract.Wrap`). - **`providers:`** in `pocketone.yaml` picks one when two extensions provide the same contract: ```yaml providers: restore/v1: backups ``` At startup, PocketOne resolves every contract and prints who provides it: ``` standard: restore/v1 ← pitr standard: bulkmail off: needs mail.fallback/v1, which nothing provides ``` A contract's major version is part of its name. Its promise never changes within a version; a different promise is a new version beside the old one. Each contract has a README with its owners, how to use it and how to provide it, and a generated list of the extensions that provide, require and work with it: the [contract catalogue](https://pocketone.dev/docs/contracts). ## Extension APIs A contract with operations is a wire API. Every operation is, from one definition: | Surface | Where | |---|---| | An HTTP endpoint | `/api/_c//`: the [Extension APIs](https://pocketone.dev/docs/extensions/apis) reference | | A `pocketone` command | `pocketone remote `: the [CLI reference](https://pocketone.dev/docs/reference/cli) | | An MCP tool | at `/mcp`: the [MCP tools](https://pocketone.dev/docs/reference/mcp) reference | | A hook in Go and JS | `deployv1.OnUpload`, `onDeployUpload`: change the input or refuse the call | Every caller passes the same check: a superuser's auth token, or an [API token](https://pocketone.dev/docs/features/tokens) with the operation's scope. Only paths a standard fixes stay outside `/api/_c/`: `/.well-known/*` and `/mcp`. ## From JavaScript An app's own JS takes part in contracts too: - Extensions with a JS API add a global (`$llm`, `$kv`, `$bulkmail`) whose types land in the app's `types.d.ts`. - Each wire operation has a hook, `on`, that sees the call's input and may change or refuse it. - `onContracts` in `pb_hooks` provides contracts from JS, and declares the ones the app requires: ```ts // pb_hooks/contracts.pb.ts onContracts((e) => { e.provide("mail.fallback/v1", { send(m) { /* deliver it some other way */ } }) e.require("restore/v1") e.next() }) ``` The [Contracts JavaScript API](https://pocketone.dev/docs/reference/javascript/contracts) lists every hook and type. ## Find your way - [All extensions](https://pocketone.dev/docs/extensions/all): every extension, by group, each with its reference page. - [Contracts](https://pocketone.dev/docs/contracts): every contract, who provides it and who uses it. - [Extension APIs](https://pocketone.dev/docs/extensions/apis): every endpoint under `/api/_c/`. - [Writing an extension](https://pocketone.dev/docs/writing-an-extension): build one, step by step. - [How PocketOne fits together](https://pocketone.dev/docs/how-pocketone-fits-together): why everything is a contract. --- Source: https://pocketone.dev/docs/contracts # Contracts New to the idea? Read [How PocketOne fits together](https://pocketone.dev/docs/how-pocketone-fits-together) first. This page is the list of every contract and how to write one. Every API a PocketOne extension offers is a contract: a versioned Go interface, and the HTTP API, hooks and MCP tools that come with it, at `/api/_c//`. Extensions have no routes of their own. An extension says what it **implements**, **requires** and **works with** in terms of these contracts, never another extension's name, so any extension that implements a contract can stand in for another. PocketOne answers "who provides this contract on this app?" at startup and prints the answer. Every contract lives here, standard or community; extensions live in `ext/`. Each contract is a package named for its id and major version: `deploy/v1` is `pocketone.dev/ext/contracts/deploy/v1`, `mail.fallback/v1` is `.../mail/fallback/v1`. A change to what a contract promises is a new major version (`v2`) next to the old one. The table is generated from each contract's README and every extension's `Contracts()`: run `go run ./.github/extensions contracts` (CI fails when it's stale). | Contract | What it promises | Provided by | Required by | Works with | Owners | |---|---|---|---|---|---| | [`api-tokens.verify/v1`](https://pocketone.dev/docs/contracts/api-tokens.verify/v1) | Another server checks an app's API token: who it acts as and what it may do. | api-tokens | | | @benallfree | | [`api-tokens/v1`](https://pocketone.dev/docs/contracts/api-tokens/v1) | An app's API tokens: check one, register scopes, read a request's token, limit in-process requests; the token API. | api-tokens | | deploy, mcp, remotes | @benallfree | | [`billing/v1`](https://pocketone.dev/docs/contracts/billing/v1) | Sell subscriptions and one-time purchases from an app: checkout, who bought what, entitlements and item events, whatever processor takes the money. | billing (default) | | | @benallfree | | [`bulkmail/v1`](https://pocketone.dev/docs/contracts/bulkmail/v1) | Run bulk mail campaigns: count an audience; start, pause, resume, cancel, preview and test a campaign. | bulkmail | | | @benallfree | | [`cache.clear/v1`](https://pocketone.dev/docs/contracts/cache.clear/v1) | Emptying an app's cache buckets, one or all, from the dashboard, the CLI or an agent. | cache (default) | | | @benallfree | | [`cache/v1`](https://pocketone.dev/docs/contracts/cache/v1) | Named buckets of bytes an app keeps for a while, with limits and eviction; memory, disk or a shared cache behind it. | cache (default) | mothership | pages | @benallfree | | [`cli.commands/v1`](https://pocketone.dev/docs/contracts/cli.commands/v1) | The pocketone command tree: every contract operation as a remote command by default; extensions replace or add commands. | desktop | | | @benallfree | | [`deploy/v1`](https://pocketone.dev/docs/contracts/deploy/v1) | A project's code files on an app: check, upload, commit, list, read, write, delete, tree. | deploy (default) | | | @benallfree | | [`gate/v1`](https://pocketone.dev/docs/contracts/gate/v1) | What admits requests on a multisite host: peer checks, client IPs and rate limits, in order. | firewall | | | @benallfree | | [`http.wrap/v1`](https://pocketone.dev/docs/contracts/http.wrap/v1) | Middleware around everything a multisite host serves, nested in order. | servertiming | | | @benallfree | | [`instance.fs/v1`](https://pocketone.dev/docs/contracts/instance.fs/v1) | An instance's code files on disk: its folder, a cache folder, one writers' lock and a restart around a change. | deploy (default), docker, pocker | deploy | | @benallfree | | [`instance.lookup/v1`](https://pocketone.dev/docs/contracts/instance.lookup/v1) | A multisite host asks what a hostname it doesn't know serves. | mothership | | | @benallfree | | [`instance.resolve/v1`](https://pocketone.dev/docs/contracts/instance.resolve/v1) | On a control plane: what a hostname serves for an edge, and the records the answer was built from. | mothership (default) | mothership | | @benallfree | | [`instance.source/v1`](https://pocketone.dev/docs/contracts/instance.source/v1) | The instance record a multisite host serves, and where the records come from. | mothership | pocker | | @benallfree | | [`instance.status/v1`](https://pocketone.dev/docs/contracts/instance.status/v1) | A multisite host reports each instance's state (starting, running, idle, failed) as it changes. | | | | @benallfree | | [`instance.tokens/v1`](https://pocketone.dev/docs/contracts/instance.tokens/v1) | A multisite host checks an API token one of its instances issued, to accept it on the routes it answers. | pocker | | | @benallfree | | [`instance.watch/v1`](https://pocketone.dev/docs/contracts/instance.watch/v1) | An edge follows a control plane lazily: one stream, hostnames watched as requests name them. | mothership | | | @benallfree | | [`kv/v1`](https://pocketone.dev/docs/contracts/kv/v1) | An app's key-value store: named JSON values with no collection or migration, kept in PocketBase's _params. | kv (default) | | api-tokens, billing, bulkmail, creem, llm, llm-search, paddle, stripe | @benallfree | | [`llm.align/v1`](https://pocketone.dev/docs/contracts/llm.align/v1) | Forced alignment: audio and the exact words spoken in it in, the time of every line and word out. | llm | | | @benallfree | | [`llm.chat/v1`](https://pocketone.dev/docs/contracts/llm.chat/v1) | Stored conversations with a language model: start a chat, send to it, read its history, find and forget chats by the app's own meta. | llm-chat | | | @benallfree | | [`llm.embed/v1`](https://pocketone.dev/docs/contracts/llm.embed/v1) | Turn texts into vectors for search by meaning: texts in, one vector each out. | llm | | llm-search | @benallfree | | [`llm.image/v1`](https://pocketone.dev/docs/contracts/llm.image/v1) | Make pictures from a prompt, and from reference pictures you give it; they come back as files. | llm | | | @benallfree | | [`llm.ledger/v1`](https://pocketone.dev/docs/contracts/llm.ledger/v1) | What an app's model calls used and cost, from the ledger every llm.* call leaves, and how much of each limit is left. | llm | | | @benallfree | | [`llm.music/v1`](https://pocketone.dev/docs/contracts/llm.music/v1) | Make music from a prompt and lyrics, as a job: start it, follow it, fetch its files (or wait for them). | llm | | | @benallfree | | [`llm.search/v1`](https://pocketone.dev/docs/contracts/llm.search/v1) | RAG knowledge bases (buckets) with hybrid search: sources (files, folders, zips, pages, Git repositories, collections) kept current, one embedding model per app. | llm-search | | llm-chat | @benallfree | | [`llm.speech/v1`](https://pocketone.dev/docs/contracts/llm.speech/v1) | Read text aloud: text in, an audio file out, in a voice the model offers or one cloned from a clip. | llm | | | @benallfree | | [`llm.text/v1`](https://pocketone.dev/docs/contracts/llm.text/v1) | Ask a language model: a prompt or a conversation in, text (or JSON matching a schema) out, whole or streamed. | llm | llm-chat | | @benallfree | | [`llm.transcribe/v1`](https://pocketone.dev/docs/contracts/llm.transcribe/v1) | Write down what's said in audio: an audio file in, text out. | llm | | | @benallfree | | [`llm.video/v1`](https://pocketone.dev/docs/contracts/llm.video/v1) | Make video from a prompt (and a first frame), as a job: start it, follow it, fetch its files (or wait for them). | llm | | | @benallfree | | [`mail.fallback/v1`](https://pocketone.dev/docs/contracts/mail.fallback/v1) | Where an app's mail goes when SMTP is off: a chain of providers that send it or pass it on. | mailrelay, mailtrap | | | @benallfree | | [`mail.feedback/v1`](https://pocketone.dev/docs/contracts/mail.feedback/v1) | Mail providers' reports (bounces, complaints, unsubscribes) received at one place and raised as events any extension can act on. | bulkmail (default) | | | @benallfree | | [`mail.suppression/v1`](https://pocketone.dev/docs/contracts/mail.suppression/v1) | Addresses an app must not send bulk mail to, and the unsubscribe link every bulk message carries. | bulkmail (default) | | | @benallfree | | [`mcp/v1`](https://pocketone.dev/docs/contracts/mcp/v1) | The app's MCP endpoint at /mcp, with every provided contract's operations as tools. | mcp (default) | | wasm | @benallfree | | [`oauth/v1`](https://pocketone.dev/docs/contracts/oauth/v1) | The app's OAuth 2.1 authorization server, so the CLI and MCP clients can sign in. | api-tokens | | mcp | @benallfree | | [`payments/v1`](https://pocketone.dev/docs/contracts/payments/v1) | What a payment processor does for an app (checkout, portal, subscriptions, refunds, webhooks), one interface for Stripe, Paddle, Creem and the rest. | creem, paddle, stripe | | billing | @benallfree | | [`remote/v1`](https://pocketone.dev/docs/contracts/remote/v1) | Remote control of an app: whoami, status, restart, logs. The base every client starts from. | docker, remotes (default) | deploy | | @benallfree | | [`restore/v1`](https://pocketone.dev/docs/contracts/restore/v1) | Put an app's data back as it was at a moment: from continuous history, or the latest backup before it. | backups (default), pitr | | | @benallfree | | [`runtime/v1`](https://pocketone.dev/docs/contracts/runtime/v1) | What runs a multisite host's instances (as isolates, in containers): one per host. | docker, pocker | | | @benallfree | | [`settings/v1`](https://pocketone.dev/docs/contracts/settings/v1) | The settings an app's admins change for its extensions, one API for all of them. | settings (default) | | billing, bulkmail, creem, llm, mailrelay, paddle, pitr, stripe, vacuum | @benallfree | | [`templates/v1`](https://pocketone.dev/docs/contracts/templates/v1) | An extension's own pages as Go templates a project can eject and edit. | templates | | api-tokens | @benallfree | | [`tls/v1`](https://pocketone.dev/docs/contracts/tls/v1) | The TLS of a multisite host's listener: automatic certificates instead of certificate files. | autotls | | | @benallfree | | [`vacuum/v1`](https://pocketone.dev/docs/contracts/vacuum/v1) | Compacting an app's databases so freed space goes back to the disk, and when it last happened. | vacuum | | | @benallfree | [`internal/example/v1`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/internal/example/v1/example.go) is a test-only wire contract that exercises the generated code. ## Three kinds - **Service:** a Go interface, looked up in the same process (`fallbackv1.Contract.Of(app)`). - **Wire:** a service with an HTTP API under `/api/_c//`, generated from its interface: each method is an operation with its own HTTP method, path and token scope (`//op: POST restart scope=remote`); inputs and results are JSON, uploads (`extkit.RawIn`), downloads (`extkit.RawOut`) or streams (`extkit.Stream`, sent as server-sent events: a GET or a POST, pushed as they happen with `Run` or polled with `Poll`). It gets action hooks (`remotev1.OnRestart`, `onRemoteRestart` in `pb_hooks`), an MCP tool per JSON operation and a client. Every caller (HTTP, MCP, Go) passes the same scope check and hooks. - **Routed:** a contract whose provider is an `http.Handler` serving everything under `/api/_c//` as it is, for an API a protocol shapes (OAuth) or an existing API moved under a contract (deploy/v1). A multisite host can provide a wire or routed contract for its instances, so it works for instances that run stock PocketBase. A contract can bring its own dashboard screen (`Contract.UI(name, fsys)`): it shows on every app that provides the contract, whichever extension does, and calls only the contract's API. restore/v1's "Restore to a moment" works this way. An extension that calls a contract for its own work (bulk mail checking whoever keeps the suppression list) passes `extkit.Internal` as the auth, and can ask who provides it with `Contract.Provider(app)`. ## Add a contract A contract is a folder `ext/contracts//vN/` (`mail.fallback/v1` → `mail/fallback/v1/`) with: - the Go package: the interface, its `//contract:` directives and `zz_contract.go`; - a `README.md`, its page on pocketone.dev, with front matter and four sections in this order: ```markdown --- owners: ["@your-github-handle"] summary: "One line: what the contract promises." --- # mail.fallback/v1 ## Use how to call it: HTTP, Go, pb_hooks, MCP, CLI ## Provide how to implement it ## Extensions (generated: who provides, requires and works with it) ## License MIT ``` Whoever first creates a contract owns it; an extension author who adds one owns both the contract and the extension that provides it. Ids are unique across PocketOne. Pick a name for what the contract does (`restore/v1`), not for the extension that first provides it. ## Write the interface A contract is an interface with `//contract:` directives; [`contractgen`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/cmd/contractgen/main.go) writes the rest (`zz_contract.go`) with `go generate ./...`. A test fails when a generated file is stale. ```go //go:generate go run pocketone.dev/ext/contracts/cmd/contractgen // Deployer sends a project's code to an app. // //contract:id deploy/v1 //contract:kind wire //contract:scope deploy //contract:host //contract:js hooks type Deployer interface { // Upload writes changed files to the app. Upload(ctx context.Context, a extkit.Auth, in UploadInput) (UploadResult, error) } ``` Methods take `ctx`, then (wire) `extkit.Auth`, then at most one input; they return `error` or one value and `error`. A contract `pb_hooks` can touch (`//contract:js hooks` or `open`) also gets `zz_contract.d.ts`, its TypeScript for `types.d.ts`: each action hook typed with its operation's input (`onExampleUpload(handler: (e: contracts.CallEvent) => void)`), and for `open` the interface `e.provide` checks (`contracts.Providers["mail.fallback/v1"]`). Hooks see the Go value, so fields carry Go names with the first letter lowered (`maxTokens`); a JS provider gets JSON, so fields carry their json names, `omitempty` ones optional. The doc comment of a wire method is its MCP tool's description. Contracts are reviewed like PocketOne's core: a contract is a promise every implementation keeps. ## Use one ```go // provide (in Register) deployv1.Contract.ProvideDefault(app, myDeployer{}) // consume (after registration: in hooks, at serve time) d := deployv1.Contract.Must(app) // declare it, so PocketOne can order and switch extensions func (e *Extension) Contracts() extkit.Contracts { return extkit.Contracts{Implements: extkit.IDs("deploy/v1"), Defaults: extkit.IDs("deploy/v1")} } ``` Choose between providers in `pocketone.yaml`: ```yaml providers: mail.fallback/v1: mailrelay ``` ## License MIT --- Source: https://pocketone.dev/docs/how-pocketone-fits-together # Contracts: how PocketOne fits together PocketOne is PocketBase plus extensions. What keeps those extensions from turning into a pile of plugins that know too much about each other is how they meet: through **contracts**. ## The idea A contract is a promise with a name and a version. `restore/v1` promises one thing: *put this app's data back as it was at a moment*. It says what you can ask and what you get back. It says nothing about how. An extension that keeps the promise **provides** the contract. Everything else talks to the contract, never to the extension behind it: the dashboard, the `pocketone` command, an AI agent over MCP, your `pb_hooks`, and other extensions. That's the whole rule: **every API an extension offers is a contract.** Extensions have no private routes and never import each other. ## An example: restore/v1 Every PocketOne app can restore its data to a moment. Who does the work depends on the app: | Provider | How close it gets | |---|---| | [PITR](https://pocketone.dev/docs/extensions/pitr) | Any second in the last three days, from continuous history. | | [Backups](https://pocketone.dev/docs/extensions/backups), the default | The latest backup made at or before the moment. It steps aside when PITR is on. | | A multisite host | It could restore an instance from the host's own disk snapshots. | Asking looks the same whoever answers: ```bash pocketone remote restore to --at -2h # the command line curl -X POST https://app.example.com/api/_c/restore/v1/restore \ -H "Authorization: $TOKEN" -d '{"at": "2026-11-10T15:00:00Z"}' # HTTP ``` An agent asked to "restore my app to yesterday at 3pm" calls the same operation as an MCP tool. Settings → Backups shows the contract's own "Restore to a moment" screen. The answer always says which point the data came from: exactly 3pm with PITR, or the 2:00 backup without it. If something better than PITR comes along tomorrow, it provides `restore/v1`, and nothing that restores apps has to change. ## Why it matters - **Swap anything.** Any extension that provides a contract can stand in for another. One line in `pocketone.yaml` chooses when several could. - **Build on anything.** Extensions depend on contracts, not on each other: Deploy requires `remote/v1`, not "the Remotes extension". Replace Remotes and Deploy keeps working. - **One surface, promised.** If a client can call it, it's in a contract: named, versioned, documented and checked. Every extension route lives under `/api/_c//`; only paths a standard fixes stay at the root (`/.well-known/*`, `/mcp`). - **Written once, reachable everywhere.** A contract's interface is the source for everything around it. Each operation is at once an HTTP endpoint, a `pocketone remote` command, an MCP tool, a hook in Go and in `pb_hooks`, and a typed client call. Every one of those paths passes the same checks: superusers only unless the operation is public, the token's scopes, and the action hooks. - **Nothing hidden.** Each app prints who provides what when it starts; `pocketone remote whoami` lists the contracts an app offers; the [catalogue](https://pocketone.dev/docs/contracts) lists every contract with the extensions that provide it, require it and work with it. ## What one interface gives you Write the interface, run `go generate`, and a contract like `restore/v1` gets all of this: | Surface | `restore/v1` | |---|---| | HTTP API | `GET /api/_c/restore/v1`, `POST /api/_c/restore/v1/restore` | | Command line | `pocketone remote restore points`, `pocketone remote restore to --at -2h` | | MCP tools | `restore_points`, `restore_restore_to` | | Hooks | `restorev1.OnRestoreTo(app, ...)` in Go, `onRestoreRestoreTo(...)` in `pb_hooks` | | Client | `restorev1.NewClient(url, token, nil).RestoreTo(...)` | | Dashboard | "Restore to a moment" on Settings → Backups, shown for any provider | ## Who provides what When an app starts, PocketOne settles every contract and says what it decided: ``` standard: restore/v1 ← pitr (default backups stepped aside) standard: mail.fallback/v1 ← mailtrap standard: deploy/v1 ← deploy (default) ``` - **Defaults.** A standard extension often provides a contract as the default: it steps aside as soon as anything else provides it. - **Choices.** When two extensions provide a contract that takes one, the app won't start until `pocketone.yaml` picks one: ```yaml providers: restore/v1: pitr ``` - **Chains.** Some contracts take several providers in order. Mail with SMTP off goes through `mail.fallback/v1`'s chain: the dev inbox in dev mode, then a host's relay. - **Your own JS.** An app's `pb_hooks` can provide contracts too, in `onContracts((e) => e.provide(...))`. - **The host.** On a multisite host, some contracts are answered by the host for its instances. An instance running a stock PocketBase image in Docker has no PocketOne extensions inside it, but the host still answers `remote/v1` for it, so `pocketone remote logs` works there too. The host's own parts are contracts as well: what runs instances (`runtime/v1`, Pocker or Docker), what admits requests (`gate/v1`), its TLS (`tls/v1`). ## Versions A contract's id carries its major version only: `restore/v1`. Within `v1` the promise doesn't change. Changing it means a `restore/v2` beside `v1`, so whatever relies on `v1` keeps working. A new optional ability is usually a new, small contract rather than a change to an old one. ## Where contracts live, and who owns them Every contract, from the standard set or the community, lives in one place: `ext/contracts//vN/` (`mail.fallback/v1` is `ext/contracts/mail/fallback/v1/`). Extensions live in `ext//`. Keeping contracts together means one namespace, so two authors can't publish different `rehash/v1`s, and it means one place to look for what you can build on. Each contract has a README like an extension's, with its owners and a one-line promise at the top. Its list of the extensions that provide it, require it and work with it is generated from the code, so it's never out of date. Whoever first creates a contract owns it. An extension author who needs a contract that doesn't exist yet writes it first, and then owns both the contract and the extension that provides it. Changes to a contract are reviewed carefully, because every provider and every caller relies on the promise. Name a contract for what it does (`restore/v1`), not for the extension that happens to provide it first. ## Words | Word | Meaning | |---|---| | **Contract** | A named, versioned promise: a Go interface plus the API, commands, tools and hooks generated from it. | | **Provide** | An extension keeps the promise for an app. | | **Require** | An extension can't work without the contract; without a provider it's turned off, and the startup lines say why. | | **Works with** | An extension uses the contract when something provides it. | | **Default** | A provider that steps aside when any other extension provides the contract. | | **Host-provided** | A multisite host answers the contract for its instances. | ## Next - [Contracts](https://pocketone.dev/docs/contracts): what each one promises, and who provides, requires and works with it. - [Writing an extension](https://pocketone.dev/docs/writing-an-extension): declare, provide and use contracts in your extension. - [Add a contract](https://pocketone.dev/docs/contracts#add-a-contract): the folder, the README and the generated code. --- Source: https://pocketone.dev/docs/writing-an-extension # Create your own extension A PocketOne extension is Go code compiled into your build. There are two kinds, by where they run: - **App extensions** add to an app: Go routes, PocketBase hooks, collections, admin dashboard screens, a JS API for `pb_hooks`, contracts other extensions use. They run on every app: a standalone app, or each instance of a multisite host. Almost every extension is one. - **Host extensions** add to a multisite host, the process that serves many instances: request gates (firewall, rate limits), TLS, middleware around every instance, instance sources, background jobs. How a multisite host runs its instances (as isolates in its own process with [pocker](https://pocketone.dev/docs/extensions/pocker), in containers with [docker](https://pocketone.dev/docs/extensions/docker), or both) is the host's `runtime/v1` contract. App extensions don't depend on it. ## App extensions: `extkit` Write an extension once, against [`extkit`](https://github.com/pocketonehq/pocketone/blob/main/ext/extkit/extkit.go) (its own module, `pocketone.dev/ext/extkit`; core has no part in it), and the same value runs on every app: ```go type Extension struct{ cfg Config } func New(cfg Config) *Extension { return &Extension{cfg: cfg} } func (p *Extension) Name() string { return "hello" } // config key, `_hello_
` collections, pb_cache/hello, logs func (p *Extension) Register(app core.App, cfg extkit.Config) error { c := p.cfg if err := cfg.Decode(&c); err != nil { // this app's settings over the defaults (json tags) return err } app.OnServe().BindFunc(func(se *core.ServeEvent) error { /* routes, UI extensions */ return se.Next() }) return nil } // optional: a $hello global in the app's JS hooks func (p *Extension) BindJS(app core.App, rt js.Runtime) { /* rt.Set("$hello", ...) */ } // optional: its TypeScript declarations, added to each app's types.d.ts func (p *Extension) TypeScript() string { return `declare var $hello: { greet(name: string): string };` } ``` - **Every app has the [standard set](https://pocketone.dev/docs/extensions/standard)** (tokens, mcp, pitr, deploy and the rest). Add yours to it: `set.Add(myextension.New(...))`. On a standalone app, build the app with `set.NewApp(...)`, or build it yourself and call `set.Register(app, jsvm.Config{...})`. The stock binary does the second: `pocketbase.NewWithConfig`, then `set.Register` ([`examples/pocketone`](https://github.com/pocketonehq/pocketone/blob/main/examples/pocketone/binary/binary.go)). Without the set: `extkit.MustRegister(app, extensions...)`, and `extkit.BindJS(app, vm, extensions...)` in jsvm's `OnInit`. - **On a multisite host** every instance gets the set, with that instance's `extensions.` settings over your constructor's defaults. `enabled: false` there means `Register` and `BindJS` are never called for that instance. What runs inside an instance depends on its runtime: pocker registers the set in each isolate; a docker instance runs the `pocketone` binary in its container, so it has the stock set (your own extras need your own image); an instance on a stock PocketBase image runs none, and gets only the contracts the host provides for it ([Working together](#working-together-contracts)). - **Routes:** an extension has none of its own. Its API is contracts, mounted for you under `/api/_c//`; design the contract in `ext/contracts` first ([Working together](#working-together-contracts)). Admin settings go through `settings/v1` (`settingsv1.Add`). Only paths a standard fixes stay at the root (`/.well-known/*`, `/mcp`). The conformance test fails any other route unless `conformance.Options.AllowRoutes` lists it with a reason. - **Process-wide settings** come from a `pocketone.yaml` section your extension owns (`extkit.NewSection`). - **State per app:** keep it in `app.Store()`. Something shared across apps (a pool, a client) closes through `extkit.Closer`. Data that must survive a restart goes in your own collections ([Your schema](#your-schema-migrations-and-table-names)); files you can rebuild go in `pb_cache` ([Disposable files](#disposable-files-pb_cache)). Never write into `pb_data` yourself, and never into the app's `pb_migrations`. - **Name the command with `extkit.Command`:** when a message tells people what to run ("run 'pocketone login prod'"), build it from `extkit.Command` (default `pocketone`), never a literal. A build shipped under another name (PocketHost's, say) sets it once in `main`, or with `-ldflags "-X pocketone.dev/ext/extkit.Command=pockethost"`. - [bulkmail](https://github.com/pocketonehq/pocketone/blob/main/ext/bulkmail/extension.go) is the reference implementation, and [`ext/standard/example`](https://github.com/pocketonehq/pocketone/blob/main/ext/standard/example/main.go) a complete program. ## Your schema: migrations and table names An extension that stores records owns its collections and creates them with its own migrations, in Go, shipped in its module. Never copy its schema into an app's `pb_migrations`. ```go func (p *Extension) Migrations() []extkit.Migration { return []extkit.Migration{ {Name: "0001_chats", Up: createChats, Down: dropChats}, {Name: "0002_chats_title_index", Up: addTitleIndex, Down: dropTitleIndex}, } } func createChats(txApp core.App) error { c := core.NewBaseCollection("_hello_chats") c.Fields.Add(&core.TextField{Name: "title"}) return txApp.Save(c) } ``` - **An extension with a `Migrations()` method is an `extkit.Migrator`.** extkit applies its pending migrations on every app it runs on (each isolate has its own database): at bootstrap, right after PocketBase's own system migrations, so its collections exist for every command, before the app's `pb_migrations` run at serve, and an app migration may refer to them. - **Order:** within an extension, by `Name` (zero-pad the numbers: `0001_chats`); across extensions, in the order they register, which puts a contract's provider before the extensions that require it. - **Each migration runs in a transaction**, like PocketBase's: one that fails leaves nothing behind and stops the ones after it, and the app doesn't start. - **History** is in `_extension_migrations` (extension, name, applied), apart from the app's `_migrations`, so the app's `migrate down` and `migrate history-sync` never touch your tables, and turning your extension off keeps its history. `pocketone extensions migrations` lists every extension's migrations; `pocketone extensions migrate down [n]` reverts the last n (`0`: all). A migration with no `Down` can't be reverted. - **Never edit a migration that has shipped.** Change the schema with a new one. To rename a collection, use `extkit.RenameCollection(name, id, from, to)`: it renames by id (keep the id, so code that finds it by id keeps working), works on system collections, and reverts. - **They build into the binary**, so there are no files to copy into the app. A migration that needs a file (a SQL script, a JSON schema) embeds it with `//go:embed` and reads it in `Up`. **Table names:** every collection your extension creates is named **`__
`**: your extension's name with hyphens as underscores, then the table: `_bulkmail_campaigns`, `_api_tokens_oauth_clients`, `_llm_chat_messages` (for llm-chat). The leading underscore keeps them apart from the app's own collections, and the name says which extension owns a table. The conformance test fails any other name unless `conformance.Options.AllowCollections` lists it with a reason (a collection the app's users are meant to see and edit, say). When one extension's prefix starts with another's (`llm`'s `_llm_` and `llm-chat`'s `_llm_chat_`), the shorter one never names a table under the longer one's prefix; `go run ./.github/extensions check` refuses it. The conformance test checks a Migrator's migrations too: they apply at bootstrap, applying again does nothing, reverting all of them changes the schema, and applying them again brings back exactly what they made. ## Disposable files: `pb_cache` Files your extension can rebuild (a download, a computed index, a model's saved state) go in **`pb_cache//`**, next to `pb_data`. Get the folder from extkit, never build the path: ```go dir, err := extkit.CacheDir(app, p.Name()) // this app's pb_cache/hello, created shared, err := extkit.HostCacheDir(app, p.Name()) // one folder for every app of the process (a shared store) ``` - **Anything in it may be deleted at any time** (`pocketone cache clear`, an admin, a cleanup), and your extension carries on: it rebuilds, re-downloads or re-reads what it needs. If losing a file loses data, it doesn't belong here: put it in a collection. - **Never backed up, deployed or synced:** it's outside `pb_data`, so backups skip it, and `deploy` and `dev` leave it out like `pb_data`. Apps add `pb_cache/` to their `.gitignore`. - **Per app:** each app has its own, and one instance never sees another's. On a multisite host an instance's `pb_cache` is outside its folder, in the host's `pb_cache/instances//` (`CacheDir` returns it), so copies, archives and moves of the instance folder never carry it. `HostCacheDir` is for caches that serve every instance at once; it is the host's own `pb_cache//` (a single app is its own host). Never put one instance's data there. - **Keep it bounded.** Give your cache a size budget (a setting with a sensible default) and evict past it; on a host, every instance's cache shares the host's disk. - `pocketone cache` shows each folder and its size; say in your README what yours holds and whether it may grow large. ## Working together: contracts > Start with [How PocketOne fits together](https://pocketone.dev/docs/how-pocketone-fits-together) for the idea: every API an extension offers is a named, > versioned contract, any extension can provide one, and everything else (the dashboard, the CLI, agents, `pb_hooks`, > other extensions) calls the contract, never the extension. This section is how to do it in code. In short, when you design an extension: 1. **Find the contracts you need** in the [catalogue](https://pocketone.dev/docs/contracts). Use them; don't reach into another extension. 2. **Decide what you offer.** Anything a client calls is a contract. If one already promises it, provide that one (your extension then stands in for the current provider). If not, write the contract first, named for what it does, not for your extension. 3. **Declare it** in `Contracts()` and **provide it** in `Register`. The startup lines, whoami and the catalogue show it from then on. Extensions never depend on each other by name. They depend on **contracts**: versioned Go interfaces in [`ext/contracts`](https://pocketone.dev/docs/contracts), such as `deploy/v1` or `mail.fallback/v1`. Every API an extension offers is a contract too, served at `/api/_c//`: extensions have no routes of their own. Every contract, standard or community, lives in `ext/contracts//vN/` with a README like an extension's (owners and a one-line summary in its front matter; `## Use`, `## Provide`, `## Extensions`, `## License`). Its Extensions section is generated from every extension's `Contracts()`: who provides it, requires it and works with it (`go run ./.github/extensions contracts`; CI fails when it's stale or when an extension names a contract that doesn't exist). Whoever first creates a contract owns it, so an extension author who adds one owns both. Design the contract first, then the extension that provides it. An extension declares what it implements, requires and works with: ```go func (e *Extension) Contracts() extkit.Contracts { return extkit.Contracts{ Implements: extkit.IDs("deploy/v1"), Defaults: extkit.IDs("deploy/v1"), // steps aside if another extension provides it WorksWith: extkit.IDs("api-tokens/v1"), // used when present } } func (e *Extension) Register(app core.App, cfg extkit.Config) error { deployv1.Contract.ProvideDefault(app, myDeployer{}) return nil } ``` At startup PocketOne resolves every contract and prints who provides it: ``` standard: deploy/v1 ← fastdeploy (default deploy stepped aside) standard: bulkmail off: needs mail.fallback/v1, which nothing provides ``` - **Look contracts up after registration** (in hooks, at serve time): `deployv1.Contract.Must(app)`. A lookup inside `Register` panics. - **Defaults, conflicts, choices.** A default steps aside for any other provider. Two other providers of a contract that allows one fail the start until `pocketone.yaml` picks one (`providers: { mail.fallback/v1: mailrelay }`). - **Wrappers** decorate whatever provides a contract (`Contract.Wrap`), in registration order. - **Wire contracts** have an HTTP API at `/api/_c//`, action hooks in Go (`deployv1.OnUpload`) and JS (`onDeployUpload`), an MCP tool per operation and a client. Every caller passes the same scope check and hooks. - **From pb_hooks:** an app's JS declares and provides its contracts in `onContracts`, which runs once after `pb_hooks` load and before the seal (so before bootstrap): ```js onContracts((e) => { e.provide("mail.fallback/v1", { send(m) { /* ... */ } }) // a contract open to JS e.require("restore/v1") // the start fails (dev mode: warns) when nothing provides it e.worksWith("api-tokens/v1") // shown in the startup lines e.next() }) ``` The startup lines show it (`pb_hooks: provides mail.fallback/v1; requires restore/v1`). Methods run on pooled runtimes like any hook handler, so they can't use the file's local variables. A Go extension that *requires* a contract only JS provides is resolved before the JS runs: name `pb_hooks` under `providers:` for it in `pocketone.yaml`. `types.d.ts` types both sides from the contract's Go interface: `e.provide` checks the object against the contract (`contracts.Providers`), and each action hook's `e.input` has its operation's input type. - **CLI:** every operation of a wire contract is a `pocketone remote ...` command with no code (`remote restore to --at -2h`), flags from its input. Provide [cli.commands/v1](../ext/contracts/cli/commands/v1/README.md) to replace one with your own, or to add one (`remote rehash`). - **No imports between extensions.** An extension imports `extkit` and contract packages, never another extension's module (tests and examples may). What it needs from another goes in the contract package: api-tokens/v1 has `RegisterScope`, `FromRequest` and `WithScopes`; remote/v1 has its CLI client (`remoteclient`), which deploy's commands use. ## Compiled in, not loaded at run time Extensions are Go packages linked into the binary, the way Caddy modules work. Go's `plugin` package (`.so` files) isn't used: - it needs identical toolchain and dependency versions; - it can't unload; - it rules out static `CGO_ENABLED=0` builds. A build is a small `main.go`: the standard set with your extensions added, as a standalone app or a multisite host. ## Your module PocketOne keeps PocketBase's module path, so upstream merges stay clean. Point it at PocketOne in your `go.mod`: ``` require ganigeorgiev.com/pocketbase/pocketbase v0.41.1 replace ganigeorgiev.com/pocketbase/pocketbase => pocketone.dev ``` Go only honors `replace` in the main module, so the final binary's `go.mod` needs this line, not only your extension's. ## Admin screens: `UIExtensions` The dashboard loads extensions before it starts its router: - Each extension is a named file system served at `/_/extensions//`. - Every extension's `main.js` is bundled into `/_/extensions.js`. Add yours in the same `OnServe` hook: ```go //go:embed ui var uiFiles embed.FS ui, _ := fs.Sub(uiFiles, "ui") se.UIExtensions = append(se.UIExtensions, core.UIExtension{Name: "hello", FS: ui}) ``` `ui/main.js` runs in the dashboard with its UI kit (`t.*`) and globals (`app.routes`, `app.store`, `app.pb`): ```js // a new page, with a link in the header app.routes.superuserOnly("#/hello", async () => { const res = await app.pb.send("/api/hello"); return t.div({ className: "page" }, t.div({ className: "page-content" }, t.h1({}, "Hello"), t.p({}, `Instance ${res.instance}`)), ); }); app.store.headerLinks.push({ href: "#/hello", icon: "ri-emotion-happy-line", label: "Hello" }); // add to an existing screen: screens marked with pbEvent fire mount: with their element document.addEventListener("mount:pageBackupsSettings", (e) => { e.detail.prepend(t.p({ className: "txt-hint" }, "Hello from an extension.")); }); ``` - **More hooks:** `app.store.settingsNavGroups` adds entries to the Settings sidebar. Search `pbEvent:` in [`ui/src`](https://github.com/pocketonehq/pocketone/tree/main/ui/src) for every screen you can add to (Backups exposes `pageBackupsSettings`, `backupsList`, `backupsSettingsForm`, `backupCreateModal` and `backupRestoreModal`). - **No build step:** plain JS works. Bundle with Vite if you prefer. - **Experimental upstream:** this UI extension API is undocumented and can change between PocketBase releases (`ui/README.md`). Keep `main.js` small, and test it after each upstream update. ## Host extensions A multisite host is one process serving many instances. A host extension works on that process, for every instance. Like app extensions, host extensions work together through contracts, on the host's own scope: | Concern | Contract | Providers | |---|---|---| | What runs the instances (one or several, in preference order) | [runtime/v1](https://pocketone.dev/docs/contracts/runtime/v1) | [pocker](https://pocketone.dev/docs/extensions/pocker), [docker](https://pocketone.dev/docs/extensions/docker) | | Which instances exist (the instance record) | [instance.source/v1](https://pocketone.dev/docs/contracts/instance.source/v1) | `instances.yaml` (default), [mothership](https://pocketone.dev/docs/extensions/mothership) | | Admit requests (firewall, rate limits) | [gate/v1](https://pocketone.dev/docs/contracts/gate/v1) | [firewall](https://pocketone.dev/docs/extensions/firewall) | | TLS for the host's listener | [tls/v1](https://pocketone.dev/docs/contracts/tls/v1) | [autotls](https://pocketone.dev/docs/extensions/autotls) | | Middleware around everything | [http.wrap/v1](https://pocketone.dev/docs/contracts/http.wrap/v1) | [servertiming](https://pocketone.dev/docs/extensions/servertiming) | A host extension is a `multisite.Extension`: `Name()` and `RegisterHost(h)`, which provides its contracts on `h.Scope` and provides nothing when it isn't configured (no section). Pass it in `multisite.Options.Extensions` (in preference order), or `multisite.Link` it from an `init` so linking its package is enough. The host seals its scope once, with `providers:` choices for host contracts, and logs who provides what: ```go h, err := multisite.FromConfig(multisite.Options{Choices: providers, Extensions: []multisite.Extension{ servertiming.New(), // http.wrap/v1, outermost autotls.New(), // tls/v1 from the `autotls` section &pocker.Provider{}, // runtime/v1 &docker.Provider{}, // runtime/v1 too, when there's a `docker` section }}) ``` ``` multisite: runtime/v1 ← pocker, docker multisite: tls/v1 ← autotls ``` Background work goes on `h.Background`, and an extension with `Close(ctx) error` is closed once every app has stopped. Some contracts are provided by the host for its instances (host-provided contracts), because the instance can't answer them itself: docker runs stock PocketBase images, so the host answers remote/v1 for them. The host serves them in `h.InstanceRoutes`, which run after the peer check, the blocked answer and the gates (firewall, rate limits) and before the runtime, with the resolved instance in `multisite.InstanceOf(r)`: ```go remotev1.Contract.ProvideForInstances(h.Scope, myRemote) h.InstanceRoutes = append(h.InstanceRoutes, func(next http.Handler) http.Handler { return remotev1.W.HostHandler(h.Scope, multisite.InstanceID, myAuth, next) }) ``` Other servers in the fleet are [edge](../ext/edge) (`edge.EdgeSource`, the host's `Forward`), and runtime-only hooks are pocker's `Starter`, `SetupApp`, `OnStart`, `OnEvent` and `Manager` ([POCKER.md](https://pocketone.dev/docs/extensions/pocker/pocker#extensions)). App extensions that only need settings shared by every instance (mailrelay, s3-fallback, pitr) read their own `pocketone.yaml` section on first use and stay app extensions: they work on any host and on a single app. ## Rules on a multisite host On a multisite host, instances can belong to people who don't trust each other, and your Go code runs with the host's full power, outside the JS sandbox: - **Act only for the app you were called for.** Keep per-app state in `app.Store()`, and use `extkit.AppID(app)` for anything shared that must differ per instance (a bucket prefix, a rate-limit key); never build a path from request input. - **Instance data needs instance auth.** Protect routes that read or change it with PocketBase's auth middlewares (`apis.RequireSuperuserAuth()`, record auth). - **Exposing something to JS is a sandbox decision.** Expose a function to an instance's JS only if it's safe for a hostile tenant to call. See [How is this safe?](https://pocketone.dev/docs/extensions/sandbox#how-is-this-safe). - **Outbound calls follow the egress policy.** Go's default HTTP client already refuses private addresses. If your extension must reach a private service, give it its own `http.Client` and transport, and never let instance input pick the address. ## Contributing an extension Extensions are welcome, from us and from you. Open a pull request that adds `ext//`. ### Change PocketBase's core as little as possible PocketOne stays close to upstream so every PocketBase release merges cleanly. If your extension needs something the core doesn't offer yet: - **Add the smallest hook that makes it possible:** an extension point or an override, not your extension's logic. A nil-checked function field, a list callers can append to, or an event, with upstream behavior unchanged when nothing is registered. - **Make it generic.** Name it for what it allows ("storage backend for an app"), not for your extension. Assume someone else's extension will use it too, and that we'll offer it to upstream PocketBase. - **Mark every changed line** in PocketBase's own files with `// PocketOne:` and a few words on why, so the next upstream merge knows what to keep. - **Keep it separate:** the core change goes in its own commit, with a test, ahead of the extension. - **Prefer what exists:** jsvm `OnInit`, `OnServe`, the record and request hooks, `BaseAppConfig.DBConnect`, `UIExtensions`. Many extensions need no core change at all. ### What an extension folder contains ``` ext// go.mod module pocketone.dev/ext/ README.md the extension's docs, and its page on pocketone.dev (below) CHANGELOG.md its changes, newest first (see Changelogs) TODO.md optional: work that waits for something else to exist first (see Blocked work) .go the extension _test.go conformance_test.go the shared extension test (below) modes_test.go the feature on the real binary, in every mode it runs in (below) example/main.go a minimal program that builds cleanly and shows the feature ui/ optional: admin screens (embedded main.js) docs/ optional: end-user docs (tutorials, guides), as pages (below) blog/ optional: posts for the pocketone.dev blog ``` - **`example/main.go` is required.** Keep it as small as possible: just enough to build a binary that shows the feature working, with no extra harness. `go build ./example` and `go vet ./...` must pass with no warnings. [`ext/standard/example`](https://github.com/pocketonehq/pocketone/tree/main/ext/standard/example) and [`ext/sandbox/example`](https://github.com/pocketonehq/pocketone/tree/main/ext/sandbox/example) are the size to aim for. - **Examples come with two logins:** superuser `admin@example.com` and user `user@example.com` (verified, in `users`), both with password `password`. Every `example/main.go` calls `devusers.Register(app)` right after the app is created (on a multisite host, `devusers.Ensure(app)` in the host's per-instance setup), from [`ext/devusers`](https://github.com/pocketonehq/pocketone/blob/main/ext/devusers/devusers.go). A fresh data dir is then ready to log in to, with no installer page and no CLI step. Never register it in a production build. - **`conformance_test.go` is required.** It runs the shared extension test from [`ext/extkit/conformance`](https://github.com/pocketonehq/pocketone/blob/main/ext/extkit/conformance/conformance.go) once: ```go func TestConformance(t *testing.T) { conformance.Run(t, func() extkit.Extension { return myextension.New(myextension.Config{}) }) } ``` It checks that the extension registers, migrates, serves and shuts down on a fresh app with no goroutines left behind; that its only routes are contracts' (`/api/_c//`); that PocketBase's own collections are unchanged and every collection it adds is named `_` or `__…`; and that one extension value serves several apps at once (as on a multisite host) without registering on one app touching another's hooks. An extension that requires another (`Contracts().Requires`) lists it in `conformance.Options{Deps: ...}`. An extension that adds MCP tools ([`ext/mcp`](https://pocketone.dev/docs/extensions/mcp#tools-from-an-extension)) also passes `conformance.Options{Setup: ...}` that registers MCP on the test apps; the test then checks each tool is named `__`, is described, and has an object input schema (`pb_` is reserved). Run it with `go test -race`. It's the minimum every extension passes; your own tests cover the feature. - **`modes_test.go` tests the feature in every mode it runs in**, on the real `pocketone` binary, with [`ext/extkit/modetest`](https://github.com/pocketonehq/pocketone/blob/main/ext/extkit/modetest/modetest.go). Declare the instances the test needs, each configured in full (files, extension settings, secrets), and the harness lays them out once per mode: `Single` (each its own `pocketone serve`), `Host` (one multisite host serving them all) and `Fleet` (several hosts that forward to each other). An app extension runs `modetest.AllApp` (Single and Host); a host extension picks Host and/or Fleet. ```go func TestModes(t *testing.T) { top := modetest.Topology{Instances: []modetest.Inst{{ID: "app", Extensions: map[string]any{"myextension": map[string]any{"limit": 5}}}}} modetest.Run(t, top, modetest.AllApp, func(t *testing.T, w *modetest.World) { s := w.Instance("app") s.MustJSON(http.MethodGet, "/api/_c/myextension/v1", s.Token(), nil, 200, nil) }) } ``` The same test body runs in every mode: each instance has the URL `http://.localhost:` in all of them, and `World.Update`, `World.Add`, `World.Restart` and `Site.WaitRestarted` do what each mode does (a host reloads its instances file; a single app restarts its process). Where a mode really behaves differently, check `w.Mode` and say why in a comment. `-short` skips mode tests. - **The README starts with front matter**: who owns the extension and its version (see [Ownership](#ownership)), and its entry in the [catalogue on pocketone.dev](https://pocketone.dev/docs/extensions): its `title`, its `group` (one of the ids in [`site/extensions.json`](https://github.com/pocketonehq/pocketone/blob/main/site/extensions.json): `binary`, `many`, `services`, `saas`, `authors`) and a one-line `summary`. Nothing outside your folder lists your extension: the site finds it there. ```markdown --- owners: ["@your-github-handle"] version: 0.1.0 title: "My Extension" group: services summary: "One line: what it does for someone running an app." --- ``` - **The README has five required sections**, in this order. It is also your extension's page on pocketone.dev. - `## Install`: how to get it (built into `pocketone`, or the lines to add to a Go build). - `## Configure`: the `pocketone.yaml` section, flags and settings screens. The site adds a table of your section's keys, generated from your `extkit.NewSection` defaults; describe each key with a `doc:"…"` struct tag. - `## Use`: day to day: the admin screens and what to click, the commands. - `## Integrations`: the extensions yours works with and how (multisite hosting goes here, not in the sections above), and how other extensions can build on yours (hooks, filesystem kinds, per-instance settings, Go and REST APIs). Hosting is a [Multisite](https://pocketone.dev/docs/extensions/multisite) row: what an instance gets and its `extensions.` settings. Pocker and Docker are two `runtime/v1` providers, not the host: name one only for what differs by runtime (isolates, which share the host's process; sleeping instances; and today per-instance settings and the host's extras, which only Pocker applies), never as the stand-in for "a multisite host". - `## Example`: the code that uses it. A sentence on what your `example/main.go` runs, then the whole file in a ```` ```go ```` block, exactly as it is; `go run ./.github/extensions examples` copies it in, and CI fails when the two differ. Without an example (an extension built into `pocketone`), say where to see it used. Write the first three for someone running one PocketOne app, not for a Go developer. Anything else (how it works, limits) goes in sections after these, and extra guides can sit next to the README as other `.md` files. - **Your README is your extension's reference; end-user docs go in `docs/`.** The README is your extension's page in the Extensions reference. Tutorials, guides and recipes, written for someone learning to use it, go in an optional `docs/` folder of [Pages](https://pocketone.dev/docs/extensions/pages) pages beside it, which pocketone.dev serves under your extension's URL: `docs/ctx/req.md` is `/docs/extensions//ctx/req`. [`ext/pages/docs`](../ext/pages/docs) (Pages' docs) and [`ext/wasm/docs`](../ext/wasm/docs) are the examples. - `docs/index.md` is required: the docs' landing page, at `/docs/extensions/`. Its front matter names the main nav section that links it, one of the `# Section` headings of the main docs nav: the subject your extension is about (`Database`, `Users and sign-in`, `Hooks and routes`, `Websites`, `Email`, `AI`, `Go`, `Deploy and run`), and the link's text is its `title`: ```yaml --- title: WASM section: Hooks and routes description: Bring your own WASM ... --- ``` - Any other page can be listed in the main nav too, the same way. A guide that gets something done across features (start to finish, not just with your extension) goes under `How-to guides`, with `nav:` as the link's text when the page's title doesn't say the outcome; guides about your extension alone stay in your own nav: ```yaml --- title: 'Speedrun: Google OAuth2' section: How-to guides nav: "Let users sign in with Google" --- ``` Your README moves to `/docs/extensions//extension`, where the Extensions reference links it. - `docs/_private/toc.md` is its nav: `# Section` headings and `- [Title](page.md)` links. Your docs pages show it as their sidebar, in place of the main docs nav, under a link back and a link to `index.md`. The README and the guides beside it aren't in it: they're in the Extensions reference. - Pages are templates: EJS runs in `.md` files as in any PocketOne app, so a code sample writes `<%%` for a literal `<%`. Partials go in `docs/_private/`; the site's own (`browser`, for one) are found too. - Link the way GitHub does, relative to the file (`ctx/req.md`, `../routing.md`, `../README.md`, `shot.png` beside the page); the site turns them into site URLs, and a link to a file that doesn't exist fails the build. - Content only: no `+` files (layouts, `+config.js`, middleware, API routes). - `blog/*.md` files are posts on the pocketone.dev blog at `/blog/`, with the same front matter as the blog's own (title, description, date, author, tags) and links relative to the file. - **Examples are TypeScript page code and Go.** Show server code as [Pages](https://pocketone.dev/docs/extensions/pages) page code in TypeScript (endpoints and page code in `.ts` files, modules in `_private/`, and an `.ets` template when the example needs a page), and the same thing in Go when an app's Go code can do it. Not `pb_hooks`, and not JavaScript: pages give routes a file structure people can read, and TypeScript carries the types. - **In `docs/`**, put the versions of one example in consecutive fenced blocks (```` ```ts ````, ```` ```go ````, and ```` ```ets ```` when it needs a template), nothing between. pocketone.dev shows them as tabs (TS | Go | ETS), one at a time. TS and ETS are the same choice, TypeScript, against Go: a group has one or the other, never both (a page's `.ts` next to the `.ets` template it feeds shows both blocks), and picking any tab switches every group on every page to that side and remembers it. On GitHub they're just consecutive blocks. - **In the README**, keep samples inline: when you show the Go version too, put a line of text before it ("In Go:") so the two don't become tabs and the README reads as plain Markdown. - **Extensions here are MIT.** The README ends with `## License` and the single line `MIT`. An extension under another license lives in its author's own repository, not here. [`ext/pitr/README.md`](https://pocketone.dev/docs/extensions/pitr) is the example to follow. - **Your pull request touches only your folder** (and, for a new contract, its folder in `ext/contracts`). Don't commit generated files: the site pages, nav, search index, `llms.txt` and contract indexes are rebuilt on `main` after your change merges ([`.github/regenerate.sh`](https://github.com/pocketonehq/pocketone/blob/main/.github/regenerate.sh)). To preview your page, run `cd site/sync && go run .` and don't commit what it writes outside your folder. - **CI enforces all of this.** [`.github/workflows/extensions.yml`](https://github.com/pocketonehq/pocketone/blob/main/.github/workflows/extensions.yml) fails when an extension README is missing its owners, version, title, group or summary, one of the five sections or its MIT `## License`, or its Example doesn't match `example/main.go`, when it has no `CHANGELOG.md`, or when a module that implements `extkit.Extension` has no conformance test, then builds, vets and runs `go test -race` on every module the change affects: the modules it touches, every module that reaches one of them through a `replace`, or all of them for a core change. [`.github/workflows/site.yml`](https://github.com/pocketonehq/pocketone/blob/main/.github/workflows/site.yml) checks that the site builds from your README. Run everything CI runs on your pull request, locally, from the repository root: ```bash go run ./.github/extensions test # what you changed since origin/main, committed or not go run ./.github/extensions test ext/ # or name the modules ``` When it ends with `ok`, CI passes too. Tests that need an external tool (MinIO, Docker) skip themselves when it isn't installed, so they don't block CI. - **Dependencies stay in your module.** Heavy libraries go in your extension's `go.mod`, never in core's. - **Standalone first.** Where it makes sense, an extension works on one standalone app, and adds more on a multisite host. - **MIT**, like PocketBase and the rest of this repo. ### Changelogs Each extension keeps its changelog in its own folder, `ext//CHANGELOG.md`, so a change to it touches nothing else. The root [CHANGELOG.md](https://github.com/pocketonehq/pocketone/blob/main/CHANGELOG.md) is for the rest: core, the `pocketone` binary, the site. - **A user-visible change adds its line under `## Unreleased`** in the same commit, grouped under `### Upgrading` (steps for anything breaking), `### Added`, `### Changed` or `### Fixed`. One line per change, written for someone running an app, with the command, flag or config key. - **Don't raise `version:` yourself.** Each PocketOne release raises the version of every extension with lines under its `## Unreleased`: minor when it has `### Upgrading` lines, otherwise patch. It renames that section to the new version and lists the extension in the release's notes, linked to its changes (`go run ./.github/extensions release vX.Y.Z`). ```markdown # My Extension changelog ## Unreleased ### Added - `myext.retries` in `pocketone.yaml`: how many times to retry a failed delivery (default 3). ``` ### Blocked work An extension may keep a `TODO.md` in its folder: the work on it that waits for something else to exist first (a contract, another extension's change, a host feature). Each item says what it waits on, under a `**Waits on:**` line, and what to do once that lands; delete the item when it's done. Work that isn't blocked doesn't go here: do it, or leave it out. So a look across `ext/*/TODO.md` shows what each missing piece would unblock. The file isn't published: pocketone.dev skips it. ### Ownership Every extension and every contract has owners, listed in its README's front matter (GitHub handles); an extension also has a version there. Whoever submits an extension or first creates a contract owns it, so an author who adds a contract with their extension owns both. Who approves an outside pull request: | What it changes | Who approves | |---|---| | PocketBase's own code, the standard extensions, the site, docs, examples, CI | a maintainer | | A community extension | one of its owners, or a maintainer | | A contract | one of its owners, or a maintainer | | A new extension or a new contract | a maintainer | Owners are read from the base branch, never from the pull request, so a pull request can't make its author an owner and approve itself. Nothing merges unless the checks pass. An extension's version goes up when PocketOne releases with changes to it ([Changelogs](#changelogs)), and its Go module tag (`ext//vX.Y.Z`) follows that version. A planned extension (a README and no code yet) stays at `0.0.0`. ```bash go run ./.github/extensions approvers origin/main HEAD # who may approve each area a change touches ``` ## Planned extensions Our own extensions live in this repo under [`ext/`](https://github.com/pocketonehq/pocketone/tree/main/ext), each as its own Go module (`pocketone.dev/ext/`). See [ext/README.md](https://github.com/pocketonehq/pocketone/blob/main/ext/README.md). --- Source: https://pocketone.dev/docs/extensions/billing/install # Add Billing to your app Billing and the processors aren't in the stock `pocketone` binary. You add them in a small Go program that builds your own: every standard extension, plus Billing and the processors you sell through. Your `pb_hooks`, `pb_pages` and `pb_migrations` work exactly as before. ## 1. Make the program In your app's folder, next to `pb_data`: ```sh go mod init example.com/myapp go get pocketone.dev/ext/standard pocketone.dev/ext/billing pocketone.dev/ext/stripe ``` ```go // main.go package main import ( "log" "ganigeorgiev.com/pocketbase/pocketbase" "pocketone.dev/ext/billing" "pocketone.dev/ext/jsvm" "pocketone.dev/ext/standard" "pocketone.dev/ext/stripe" ) func main() { set := standard.New() set.Add( billing.New(billing.Config{}), stripe.New(stripe.Config{}), ) app := set.NewApp(pocketbase.Config{}, jsvm.Config{HooksDir: "pb_hooks"}) if err := app.Start(); err != nil { log.Fatal(err) } } ``` Swap `stripe` for `paddle` (`pocketone.dev/ext/paddle`) or `creem` (`pocketone.dev/ext/creem`), or add more than one. Billing needs the Settings and KV extensions, which the standard set already has. To read `pocketone.yaml` the way the stock binary does, build the app with `standard.AppFromConfig` as [Standard extensions](https://pocketone.dev/docs/extensions/standard) shows. ## 2. Run it ```sh go run . serve ``` The first start adds Billing's collections: `_billing_products`, `_billing_items` (one per subscription, order or manual grant), `_billing_events` (every webhook) and `_billing_checkouts`. `$billing` is now in your pages and `pb_hooks`. Build it for a server the usual Go way (`GOOS=linux GOARCH=amd64 go build -o myapp .`) and run `./myapp serve` where you ran `pocketone serve`. ## 3. Set it up in the dashboard Open the dashboard and go to **Billing → Settings**. | Setting | What it does | |---|---| | Checkout processor | Which installed processor takes new checkouts. Leave it empty when only one is installed. | | Owner collection | The auth collection whose records buy (`users`). | | Signed-out checkout (pay first) | Visitors can buy before they have an account. See [Pay first](https://pocketone.dev/docs/extensions/billing/checkout#pay-first). | | Success URL, Cancel URL | Where the processor sends buyers back. Both default to the Application URL. | | Proration | How quantity and plan changes are charged when the caller doesn't say: now, at the next period, or not at all. | | API URL | The base of webhook and checkout-page URLs when the Application URL doesn't reach this app's API. | | Reconcile daily | Re-reads every item that hasn't ended from its processor once a day and fixes anything that drifted. | Each processor's section is on the same page: its keys, a **Test** button, and the webhook URL to paste into the processor's dashboard. Follow your processor's page: [Stripe](https://pocketone.dev/docs/extensions/stripe), [Paddle](https://pocketone.dev/docs/extensions/paddle) or [Creem](https://pocketone.dev/docs/extensions/creem). Then add what you sell: [Products and prices](https://pocketone.dev/docs/extensions/billing/products). --- Source: https://pocketone.dev/docs/extensions/billing/products # Products and prices A product is one thing a buyer can check out: a plan, an add-on, a one-time pack. Add them in the dashboard under **Billing → Products**. They live in the `_billing_products` collection. | Field | What it holds | |---|---| | `key` | The name your code uses: `pro`, `team`, `extra-seats`. | | `name`, `description` | What the dashboard shows. | | `kind` | `subscription` (renews) or `order` (paid once). | | `prices` | The price at each processor: `{"stripe": "price_123", "paddle": "pri_01h..."}`. | | `grants` | What one unit grants: `{"instances": 1}`, `{"seats": 5, "storage_gb": 100}`. | | `active` | Only active products can be checked out. Turning one off leaves existing buyers alone. | The price itself (amount, currency, billing period, trial) is set at the processor. Billing stores only its id, so change a price at the processor and nothing changes in your app. **Check prices** asks each processor whether every price exists and matches the product's kind: a subscription needs a recurring price, an order a one-time one. ## Grants and quantity A product's `grants` count per unit. Buy `team` (`{"seats": 5}`) with quantity 3 and the user's `seats` entitlement goes up by 15. Entitlements from different products add up: `pro` plus an `extra-seats` add-on gives one total. [Gating features with entitlements](https://pocketone.dev/docs/extensions/billing/entitlements) shows how to read them. ## One product, several processors `prices` can name a price at each processor you install. The checkout processor (Billing → Settings) is the one new checkouts use; the others' prices matter only when you switch. See [Payment processors](https://pocketone.dev/docs/extensions/billing/processors). --- Source: https://pocketone.dev/docs/extensions/billing/checkout # Selling: checkout A checkout sells one product to one buyer. Your app asks Billing for a checkout, sends the browser to the URL it returns, and the buyer pays on the processor's page. The processor's webhook tells Billing, Billing reads the purchase back, and the buyer's item and entitlements are there by the time they land on your success page, or moments after. ## From page code `$billing` acts as the auth record you give it, with that user's rights. In [Pages](https://pocketone.dev/docs/extensions/pages/overview), that's `ctx.auth`: ```ts // pb_pages/checkout/[product].ts: POST /checkout/pro starts a checkout for "pro" module.exports = { async post(ctx) { if (!ctx.auth) return ctx.res.redirect('/login') const { url } = await $billing.checkout.async(ctx.auth, { product: ctx.params.product, quantity: 1, successUrl: 'https://example.com/welcome', }) return ctx.res.redirect(url) }, } ``` ```html
``` `checkout` and `portal` call the processor, so page code awaits their `.async` forms. `entitlements` and `items` read your own database and are fine to call directly. ## From the browser Billing's API is the [billing/v1](https://pocketone.dev/docs/contracts/billing/v1) contract at `/api/_c/billing/v1/`. With the PocketBase JS SDK, signed in: ```js const { url } = await pb.send('/api/_c/billing/v1/checkout', { method: 'POST', body: { product: 'pro', quantity: 2 }, }) location.href = url ``` ## From Go ```go res, err := billingv1.Contract.Must(app).Checkout(ctx, auth, billingv1.CheckoutInput{Product: "pro", Quantity: 2}) // res.URL is where to send the browser ``` `billingv1` is `pocketone.dev/ext/contracts/billing/v1`; `auth` is the buyer's `extkit.Auth`. Go code can also set `Server`, which a checkout over the wire or from `$billing` never carries, so only the app decides it. Use it to move a customer from another processor without charging them twice: ```go in := billingv1.CheckoutInput{Product: "pro", Quantity: 2, Server: billingv1.CheckoutServer{ TrialDays: 12, // first charge in 12 days, when the old plan would renew Metadata: map[string]string{"replaces": "sub_old"}, // on the purchase at the processor (Stripe: the subscription) AllowOffSalePurchase: true, // the product may be bought while off sale (a retired plan they keep) }} ``` Billing's own metadata keys (`checkout`, `owner`, `owner_collection`) win over the app's. The new item's `data` holds the processor's object, metadata included, for the app's `OnItemChanged` handler. ## What a checkout takes | Field | What it does | |---|---| | `product` | The product's key. | | `quantity` | How many units; default 1. | | `email` | Signed out: fills in the processor's form. | | `discount` | A discount or promotion code the processor knows. | | `successUrl`, `cancelUrl` | Where the buyer goes after paying or giving up. Default: Billing's settings. | The result has `url` (send the browser there) and `processor` (which one took it). ## Pay first With **Signed-out checkout (pay first)** on in Billing → Settings, a visitor can buy before signing up. Pass `null` as the auth record: ```ts // pb_pages/buy.ts module.exports = { async post(ctx) { const { url } = await $billing.checkout.async(ctx.auth, { product: 'lifetime', email: ctx.req.body().email }) return ctx.res.redirect(url) }, } ``` When the payment comes in, Billing gives the purchase to the user whose email matches the checkout email (ignoring case). A buyer with no account gets one only if your app makes it: what a new account needs is up to the app, so Billing asks through the `OnOwnerNeeded` hook. The handler runs inside the purchase's transaction; save the record with `e.App` and set `e.Owner`. Without a handler, or with no `Owner` set, the purchase waits until a user with that email exists. ```go billingv1.OnOwnerNeeded(app).BindFunc(func(e *billingv1.OwnerEvent) error { user := core.NewRecord(e.Collection) user.SetEmail(e.Email) user.SetRandomPassword() if err := e.App.Save(user); err != nil { return err // the processor sends the webhook again } e.Owner = user.Id return e.Next() }) ``` Once the purchase is saved, welcome the buyer, for example with a sign-in link, from the `OnGuestPurchase` hook (`e.Created` is true when your handler made the account): ```go billingv1.OnGuestPurchase(app).BindFunc(func(e *billingv1.GuestEvent) error { if e.Created { user, err := e.App.FindAuthRecordByEmail("users", e.Email) if err != nil { return err } if err := mails.SendRecordPasswordReset(e.App, user); err != nil { return err } } return e.Next() }) ``` With pay first off, a signed-out checkout is refused. ## After the checkout The buyer lands on your success URL. The webhook usually arrives first; if it hasn't yet, show "Payment received, setting up your account" and read entitlements again in a moment. Nothing your app does is needed for the purchase to be recorded. --- Source: https://pocketone.dev/docs/extensions/billing/entitlements # Gating features with entitlements An entitlement is a named number: `instances`, `seats`, `storage_gb`. Each product grants some per unit, and a user's entitlements are the sums over their **active** items: subscriptions that are paid, trialing, or past due while the processor retries the card; paid one-time orders (partly refunded ones too); and manual grants that haven't ended. A cancelled subscription keeps counting until its paid period ends; a refunded order stops counting at once. ## Read them ```ts // pb_pages/projects/new.ts module.exports = { load(ctx) { if (!ctx.auth) return ctx.res.redirect('/login') const { totals } = $billing.entitlements(ctx.auth) const used = ctx.app.countRecords('projects', $dbx.hashExp({ owner: ctx.auth.id })) if (used >= (totals.projects ?? 0)) return ctx.res.redirect('/pricing') return {} }, } ``` ```go ent, err := billing.For(app).Entitlements("users", userId) if err != nil { return err } if ent.Totals["projects"] <= used { return apis.NewForbiddenError("Upgrade to add more projects", nil) } ``` A name the user has none of is missing from `totals`, so read it with a default (`?? 0` in TypeScript; Go's map gives 0). `sources` lists where each total comes from: one entry per item and entitlement. From the browser: ```js const { totals } = await pb.send('/api/_c/billing/v1/entitlements') ``` ## List purchases `items` lists a user's subscriptions, orders and grants, newest first, with `product`, `quantity`, `status`, `active`, `renewsAt` and `endsAt`. Use it for an account page: ```ts const items = $billing.items(ctx.auth) // [{ product: "pro", status: "active", renewsAt: "2027-01-03T...", ... }] ``` ## React when something changes `OnItemChanged` runs after every change to an item, from a webhook, an action in the dashboard, a grant or the daily reconcile. It carries the item before and after and the owner's entitlements before and after, so you can provision or tear down what was paid for: ```go billingv1.OnItemChanged(app).BindFunc(func(e *billingv1.ItemEvent) error { before, after := e.EntitlementsBefore["instances"], e.EntitlementsAfter["instances"] if after < before { // stop the owner's instances above the new limit } return e.Next() }) ``` In `pb_hooks`, the item records themselves have the usual record hooks: ```js onRecordAfterUpdateSuccess((e) => { const owner = $app.findRecordById(e.record.getString('owner_collection'), e.record.getString('owner')) const { totals } = $billing.entitlements(owner) // ... e.next() }, '_billing_items') ``` A webhook delivered twice runs the hook twice with the same result, so compare before and after rather than act on every call. --- Source: https://pocketone.dev/docs/extensions/billing/customers # Managing customers ## Users manage their own A signed-in user can manage their own items through Billing's API. Each call acts on one item (its `id` from `items`), and a user can only touch their own. | Call | What it does | |---|---| | `portal` | A link to the processor's customer portal: cards, invoices, receipts. Links are short-lived, so make one per click. | | `cancel` | Cancels a subscription now, or at the end of the paid period with `atPeriodEnd: true`. | | `resume` | Undoes a cancel scheduled for the end of the period. | | `quantity` | Changes how many units a subscription bills for. | | `plan` | Moves a subscription to another product. | ```ts // pb_pages/account/billing.ts: "Manage cards and invoices" module.exports = { async post(ctx) { if (!ctx.auth) return ctx.res.redirect('/login') return ctx.res.redirect(await $billing.portal.async(ctx.auth, { returnUrl: 'https://example.com/account' })) }, } ``` ```js // from the browser, signed in await pb.send('/api/_c/billing/v1/cancel', { method: 'POST', body: { item: itemId, atPeriodEnd: true } }) await pb.send('/api/_c/billing/v1/quantity', { method: 'POST', body: { item: itemId, quantity: 5 } }) await pb.send('/api/_c/billing/v1/plan', { method: 'POST', body: { item: itemId, product: 'team', proration: 'now' } }) ``` `proration` is `now` (charge or credit the difference at once), `next_period` (add it to the next bill) or `none` (bill the new amount from the next period). Leave it out to use Billing's setting. Each call changes the subscription at the processor, then reads it back, so the item and entitlements are current when it returns. ## The Billing page The dashboard's **Billing** page is for you and your support team: - **Overview**: the latest changes to items, webhook errors, and **Reconcile** (with a dry run). - **Customers**: every owner who bought something. A customer's page shows their entitlements and every item with its actions, and a form to grant a product. - **Products**: your products and **Check prices**. - **Events**: every webhook Billing received and what it did with it. - **Settings**: Billing's settings and each processor's. On a subscription, a superuser can cancel (at the period end or now), resume, and set the quantity. On a paid item, **Sync** reads it from the processor again and **Refund** asks the processor to refund it in full. Some processors approve refunds themselves, so a refund can stay pending until they do; the item changes when their webhook arrives. A partial refund is a call from code: `refund` with an `amount` in minor units (cents). ## Manual grants A grant gives a user a product without a payment: a comp, a partner, a support credit. On a customer's page, press **Grant**, pick the product and quantity, and add a note saying why. A grant counts toward entitlements like a purchase until you **Revoke** it, or until its end date when you set one from code (`endsAt`). From Go: ```go billingv1.Contract.Must(app).Grant(ctx, extkit.Internal, billingv1.GrantInput{ Owner: userId, Product: "team", Quantity: 1, Note: "conference speaker", }) ``` ## Reconcile With **Reconcile daily** on, Billing reads every item that hasn't ended from its processor once a day and fixes any that drifted, for example after a webhook was missed while your app was down. A superuser can run it on demand with a dry run first (`POST /api/_c/billing/v1/reconcile {"dryRun": true}`) to see what it would change. --- Source: https://pocketone.dev/docs/extensions/billing/processors # Payment processors Billing works the same with every processor: the same products, checkout call, entitlements and dashboard. What differs is who sells to the buyer and what each processor can do. | | [Stripe](https://pocketone.dev/docs/extensions/stripe) | [Paddle](https://pocketone.dev/docs/extensions/paddle) | [Creem](https://pocketone.dev/docs/extensions/creem) | |---|---|---|---| | Merchant of record | You, or Stripe with Managed Payments | Paddle | Creem | | Sales tax and VAT | Yours to file, or Stripe's with Managed Payments | Paddle's | Creem's | | Checkout | Stripe Checkout page | Paddle.js overlay on a page Billing serves | Creem's checkout page | | Refunds | Full or partial, at once | Full or partial, approved by Paddle | Full only | | Disputes | Opened and closed | Opened and closed | Opened | | Local webhooks | `stripe listen` | A tunnel | A tunnel | Each is its own extension and Go module: `pocketone.dev/ext/stripe`, `pocketone.dev/ext/paddle`, `pocketone.dev/ext/creem`. Install only the ones you use ([Add Billing to your app](https://pocketone.dev/docs/extensions/billing/install)). ## Several at once Install more than one and **Billing → Settings → Checkout processor** picks the one that takes new checkouts. Every installed processor keeps receiving webhooks and serving the items sold through it: renewals, cancels, refunds and the customer portal all go to the processor that made the sale. ## Moving to another processor 1. Install the new processor alongside the old one and set its keys and webhook. 2. Add its price to each product's `prices`: `{"stripe": "price_123", "paddle": "pri_01h..."}`. **Check prices**. 3. Switch **Checkout processor** to the new one. New buyers pay through the new processor. Existing subscriptions keep renewing through the old one until they end; keep it installed until then. Your code doesn't change: entitlements add up across processors. ## Other processors A processor is any extension that provides the [payments/v1](https://pocketone.dev/docs/contracts/payments/v1) contract: checkout, read a subscription or order, cancel, change, refund, portal, and parse a signed webhook. See [Writing an extension](https://pocketone.dev/docs/writing-an-extension) to add one. --- Source: https://pocketone.dev/docs/contracts/api-tokens.verify/v1 # api-tokens.verify/v1 Another server checks one of an app's API tokens. A host in front of an app's accounts (a PocketHost edge in front of the mothership) is handed a token by a client and asks the app that issued it who the token acts as and what it may do. Companion to [api-tokens/v1](https://pocketone.dev/docs/contracts/api-tokens/v1): whatever provides that provides this. A wire contract ([verify.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/api-tokens/verify/v1/verify.go)). ## Use | Operation | HTTP | Who | |---|---|---| | Verify | `POST /api/_c/api-tokens.verify/v1` `{"token", "ip"}` | superusers (`api_tokens_verify`) | `ip` is the client's address, recorded as the token's last use; leave it out to leave the last use alone. A valid token: ```json {"valid": true, "grant": {"tokenId": "...", "name": "ci", "ownerCollection": "users", "ownerId": "...", "scopes": ["instances=abc123"]}} ``` `scopes` empty means the owner's full rights; a scope with a value (`instances=abc123`) holds it for that value only (see [api-tokens/v1](https://pocketone.dev/docs/contracts/api-tokens/v1)). A token that isn't valid is an answer, not an error, so a caller can tell a refused token from an outage: `{"valid": false, "reason": "invalid"}` (unknown, malformed or revoked) or `"expired"`. In Go, from the other server: ```go c := verifyv1.NewClient("https://app.example.com", superuserToken, nil) res, err := c.Verify(ctx, extkit.Auth{}, verifyv1.Input{Token: token, IP: ip}) if err != nil { /* the app is unreachable: don't treat the token as refused */ } if !res.Valid { /* 401: res.Reason */ } if !res.Grant.HasScopeFor("instances", id) { /* 403 */ } ``` Cache answers briefly if you verify on every request: a revoked token then stops working once its entry expires. ## Provide Implement `verifyv1.Verifier` over the same tokens as your `api-tokens/v1` provider. Never return an error for a token that isn't valid: return `Valid: false` and a reason. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### verify Checks an API token and says who it acts as and what it may do (its scopes, with their values). A token that isn't valid is an answer (Valid false), not an error, so callers can tell a refused token from an outage. | | | |---|---| | REST | `POST /api/_c/api-tokens.verify/v1` | | CLI | `pocketone remote api-tokens verify --token --ip ` | | MCP | `api-tokens_verify_verify` | | Token scope | `api_tokens_verify` | | Input field | Flag | Type | |---|---|---| | `token` | `--token` | string | | `ip` | `--ip` | string | ## Extensions | Extension | | |---|---| | [api-tokens](https://pocketone.dev/docs/extensions/api-tokens) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/api-tokens/v1 # api-tokens/v1 An app's API tokens, as other extensions use them. Tokens are scoped: a token limited to scopes works only on the requests those scopes reach. Extensions register their own scopes, read the token a request came with, and limit requests they make on someone's behalf, all through this package. A service with its own API ([tokens.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/api-tokens/v1/tokens.go)), served at `/api/_c/api-tokens/v1`. ## Use | HTTP | What it does | |---|---| | `GET /api/_c/api-tokens/v1/scopes` | the scopes a token may hold, and who may own tokens | | `GET /api/_c/api-tokens/v1` | your tokens (superusers: `?owner=`, `?ownerCollection=`) | | `POST /api/_c/api-tokens/v1` | create one (`{name, scopes, expires\|ttl}`); the secret is shown once | | `DELETE /api/_c/api-tokens/v1/{id}` | revoke one | | `POST /api/_c/api-tokens/v1/revoke-all` | revoke all of yours | In Go: ```go if tk, ok := tokensv1.Contract.Of(app); ok { tk.RegisterScope(tokensv1.Scope{Name: "notes:write", Description: "Change notes", Paths: []string{"/api/collections/notes/records"}, Methods: []string{"POST", "PATCH", "DELETE"}}) } g := tokensv1.FromRequest(e) // the request's token, or nil (a JWT, or none) ctx = tokensv1.WithScopes(ctx, []string{"notes:read"}) // requests made with ctx count as limited to these scopes ``` A scope registered with `Values` can be held for some values only: `name=value` in the token's scopes (`instances=abc123`), the bare name meaning every value. Paths don't see values, so the route checks them: ```go g := tokensv1.FromRequest(e) if g != nil && !g.HasScopeFor("instances", id) { return e.ForbiddenError("Not this instance.", nil) } vals, all := g.ScopeValues("instances") // all: every value ``` `HoldsScope`, `CoversScope`, `ValuesOf` and `IntersectScopes` do the same on a plain scope list. ## Provide Implement `tokensv1.Issuer` (`Verify`, `RegisterScope`, `Scopes`, `Reaches`), authenticate requests that carry a token (setting `tokensv1.RequestKey` to the `*Grant`), honour `WithScopes` limits, and serve the token API (the provider binds its own routes, `extkit.RouteBinder`). ## Commands and APIs Its own HTTP API under `/api/_c/api-tokens/v1/`, described above. It has no generated commands or MCP tools. [Remote CLI](https://pocketone.dev/docs/features/remote) explains how PocketOne apps are managed from afar. ## Extensions | Extension | | |---|---| | [api-tokens](https://pocketone.dev/docs/extensions/api-tokens) | provides | | [deploy](https://pocketone.dev/docs/extensions/deploy) | works with | | [mcp](https://pocketone.dev/docs/extensions/mcp) | works with | | [remotes](https://pocketone.dev/docs/extensions/remotes) | works with | ## License MIT --- Source: https://pocketone.dev/docs/contracts/billing/v1 # billing/v1 Selling from an app, whatever processor takes the money. The provider keeps who bought what (**items**: a subscription, an order or a manual grant, each owned by an auth record), turns processors' webhooks into item changes, sums what each owner's active items grant (**entitlements**, such as `instances = 5`), and raises an event after every change so the app can react. Processors are [payments/v1](https://pocketone.dev/docs/contracts/payments/v1) providers. A wire contract ([billing.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/billing/v1/billing.go)) at `/api/_c/billing/v1/`. Products and items are records in the provider's collections, edited with PocketBase's records API or the dashboard's Billing page. ## Use | Operation | HTTP | Who | |---|---|---| | Checkout | `POST /api/_c/billing/v1/checkout` `{"product": "pro", "quantity": 1}` | anyone; signed out only when the app allows pay-first | | Pay | `GET /api/_c/billing/v1/pay?checkout=` | anyone (the page some processors need) | | Portal | `POST /api/_c/billing/v1/portal` `{"item": ""}` | the owner, or a superuser | | Items | `GET /api/_c/billing/v1/items` | the owner (their own), or a superuser (`?owner=`) | | Entitlements | `GET /api/_c/billing/v1/entitlements` | the owner, or a superuser | | Cancel, Resume, Quantity, Plan | `POST /api/_c/billing/v1/cancel` (`resume`, `quantity`, `plan`) | the owner, or a superuser | | Webhook | `POST /api/_c/billing/v1/webhook?provider=stripe` | the processor (checked by its signature) | | Refund, Grant, Revoke, Sync, Reconcile | `POST /api/_c/billing/v1/refund` (`grant`, `revoke`, `sync`, `reconcile`) | superusers (`billing` scope) | | Check, Processors | `POST check`, `GET processors` | superusers (`billing:read`) | A signed-out checkout returns `claim`; keep it in the browser. When the purchase completes, the provider finds the owner by the checkout email; when none has it, it raises `OnOwnerNeeded`, where the app may make the account (inside the purchase's transaction). Then it raises `OnGuestPurchase`, where the app sends its own claim email. React to purchases in Go: ```go billingv1.OnItemChanged(app).BindFunc(func(e *billingv1.ItemEvent) error { if e.EntitlementsAfter["instances"] != e.EntitlementsBefore["instances"] { // apply the new allowance } return e.Next() }) ``` or in `pb_hooks`, with the action hooks every wire contract has (`onBillingCheckout`, `onBillingCancel`, ...). ## Provide Implement `billingv1.Billing`, provide it with `billingv1.Contract.ProvideDefault(app, impl)`, and declare `Implements` and `Requires: extkit.IDs("payments/v1")`. A provider: - re-reads the subscription or order an event names and writes what it finds, so the order events arrive in, and repeats, never matter; first-time work (a new purchase's handlers) is keyed by the order or checkout, not the event id; - lets an owner act only on their own items, and a superuser on anyone's; - raises `OnItemChanged` after each item is saved, with the owner's entitlements before and after, and `OnGuestPurchase` once a signed-out purchase's owner is known; when no owner has a signed-out purchase's email, it raises `OnOwnerNeeded` in the purchase's transaction and takes the owner the handler sets, never making one itself. ## Extensions | Extension | | |---|---| | [billing](https://pocketone.dev/docs/extensions/billing/extension) | provides (default) | ## License MIT --- Source: https://pocketone.dev/docs/contracts/bulkmail/v1 # bulkmail/v1 Campaigns to many recipients, sent at a pace the app's mail account can take. Campaigns are records in the provider's collection, created and edited with PocketBase's records API; this contract runs them. The list of addresses never to mail is [mail.suppression/v1](https://pocketone.dev/docs/contracts/mail.suppression/v1); providers' bounce and complaint reports are [mail.feedback/v1](https://pocketone.dev/docs/contracts/mail.feedback/v1). A wire contract ([bulkmail.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/bulkmail/v1/bulkmail.go)). ## Use | Operation | HTTP (`POST`) | Body | Token scope | |---|---|---|---| | Count | `/api/_c/bulkmail/v1/count` | `{"audience": {...}}` | `bulkmail:read` | | Start | `/api/_c/bulkmail/v1/start` | `{"campaign": "", "limit": 0}` | `bulkmail` | | Pause, Resume, Cancel | `/api/_c/bulkmail/v1/pause` (`resume`, `cancel`) | `{"campaign": ""}` | `bulkmail` | | Preview | `/api/_c/bulkmail/v1/preview` | `{"campaign": "", "email": ""}` | `bulkmail:read` | | Test | `/api/_c/bulkmail/v1/test` | `{"campaign": "", "to": ""}` | `bulkmail` | Campaign actions answer `{"campaign": }`. The audience's shape is the provider's (see [Bulk Mail](https://pocketone.dev/docs/extensions/bulkmail)). Only superusers may call these. Agents get them as MCP tools (`bulkmail_start`, ...); `pb_hooks` can hook each (`onBulkmailStart`). ## Provide Implement `bulkmailv1.Campaigns` and provide it in your extension's `Register`. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### count Says how many recipients an audience reaches, how many of them are suppressed, and a few sample addresses. | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/count` | | CLI | `pocketone remote bulkmail count --audience ` | | MCP | `bulkmail_count` | | Token scope | `bulkmail:read` | | Input field | Flag | Type | |---|---|---| | `audience` | `--audience` | json | ### start Queues a campaign's recipients and starts sending (Limit > 0: at most that many new recipients). | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/start` | | CLI | `pocketone remote bulkmail start --campaign --limit ` | | MCP | `bulkmail_start` | | Token scope | `bulkmail` | | Input field | Flag | Type | |---|---|---| | `campaign` | `--campaign` | string | | `limit` | `--limit` | int | ### pause Stops sending a campaign; Resume carries on. | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/pause` | | CLI | `pocketone remote bulkmail pause --campaign ` | | MCP | `bulkmail_pause` | | Token scope | `bulkmail` | | Input field | Flag | Type | |---|---|---| | `campaign` | `--campaign` | string | ### resume Carries on sending a paused campaign. | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/resume` | | CLI | `pocketone remote bulkmail resume --campaign ` | | MCP | `bulkmail_resume` | | Token scope | `bulkmail` | | Input field | Flag | Type | |---|---|---| | `campaign` | `--campaign` | string | ### cancel Stops a campaign for good; recipients not yet sent to are dropped. | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/cancel` | | CLI | `pocketone remote bulkmail cancel --campaign ` | | MCP | `bulkmail_cancel` | | Token scope | `bulkmail` | | Input field | Flag | Type | |---|---|---| | `campaign` | `--campaign` | string | ### preview Renders a campaign's message for one recipient (the first in its audience when Email is empty). | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/preview` | | CLI | `pocketone remote bulkmail preview --campaign --email ` | | MCP | `bulkmail_preview` | | Token scope | `bulkmail:read` | | Input field | Flag | Type | |---|---|---| | `campaign` | `--campaign` | string | | `email` | `--email` | string | ### test Sends a campaign's message to one address, marked as a test. | | | |---|---| | REST | `POST /api/_c/bulkmail/v1/test` | | CLI | `pocketone remote bulkmail test --campaign --to ` | | MCP | `bulkmail_test` | | Token scope | `bulkmail` | | Input field | Flag | Type | |---|---|---| | `campaign` | `--campaign` | string | | `to` | `--to` | string | ## Extensions | Extension | | |---|---| | [bulkmail](https://pocketone.dev/docs/extensions/bulkmail) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/cache.clear/v1 # cache.clear/v1 [cache/v1](https://pocketone.dev/docs/contracts/cache/v1) is for an app's own code. This contract lets the app's admins empty its buckets from outside that code, after a change that left stale entries behind: one bucket by name, or every bucket the app has. A wire contract at `/api/_c/cache.clear/v1` ([clear.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/cache/clear/v1/clear.go)), one provider: whoever provides cache/v1 provides this too. ## Use ```sh pocketone remote cache clear --bucket pages.render # one bucket pocketone remote cache clear # every bucket of the app curl -X POST -H "Authorization: " -d '{"bucket":"pages.render"}' https://your.app/api/_c/cache.clear/v1 ``` The answer says how many keys went (`keys`). ## Provide Implement `clearv1.Clearer` and provide it in `Register` beside your cache/v1 provider (`clearv1.Contract.Provide(app, c)`). Empty only the calling app's buckets, never another app's on a shared store. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### clear Empties one of the app's cache buckets, or every bucket it has. | | | |---|---| | REST | `POST /api/_c/cache.clear/v1` | | CLI | `pocketone remote cache clear --bucket ` | | MCP | `cache_clear_clear` | | Token scope | `cache` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | ## Extensions | Extension | | |---|---| | [cache](https://pocketone.dev/docs/extensions/cache) | provides (default) | ## License MIT --- Source: https://pocketone.dev/docs/contracts/cache/v1 # cache/v1 A place for an app and its extensions to keep what was expensive to compute: rendered pages, API answers, resized images. Code opens a **bucket** by name with the limits it wants and gets and sets keys in it. Who keeps the bytes (memory and disk in this process, or Redis or Memcached shared between servers) is up to the provider, so a new one replaces the old without any caller changing. A bucket has its own caps, inside whatever room the provider has in all: | Option | What it does | |---|---| | `Eviction` | Which of the bucket's entries go first when it's full: `lru` (default), `mru`, `fifo`, `lifo` | | `MaxItems` | Most entries the bucket holds | | `MaxMemory` | Most bytes of keys and values the bucket holds | | `TTL` | How long an entry lives unless `Set` says otherwise | Where entries live (memory, disk, another server) and how much room there is in all are the provider's and the operator's business, not the bucket's. The promise is a cache's: a provider may drop any entry at any time, and a `Get` may miss. It never returns a value that was deleted, cleared or replaced since, nor one past its TTL. Each app has its own buckets, on a multisite host too, even when the provider keeps every app's entries in one shared store. An app service contract, one provider ([cache.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/cache/v1/cache.go)). ## Use Open a bucket after registration (in a hook or at serve time), keep it, and use it: ```go b, err := cachev1.Open(app, "myext.answers", cachev1.Options{MaxItems: 1000, TTL: 10 * time.Minute}) if err != nil { return err } if v, ok, _ := b.Get(ctx, key); ok { return v } v := compute() _ = b.Set(ctx, key, v, 0) // 0 = the bucket's TTL ``` Name buckets after your extension (`myext.answers`) so two extensions never share one. Declare cache/v1 in `WorksWith`: when nothing provides it, `Open` returns a bucket that keeps nothing, so the same code runs uncached. When the value is expensive and many requests may ask for the same cold key at once, let `cachev1.Load` compute it: callers asking for the same key of the same bucket while it runs share one call, and all of them are released only after the value is stored. An error goes to the callers waiting then and is never stored; each caller waits on its own context, and the call keeps running for the others when one gives up (so bound its time yourself). ```go v, err := cachev1.Load(ctx, b, key, func(ctx context.Context) ([]byte, error) { return compute(ctx) }) ``` `Items` has the same `Load` for Go values. To empty every bucket the app has (after a change that left stale entries), call `cachev1.Clear(ctx, app)`; the app's admins can do the same from outside its code through [cache.clear/v1](https://pocketone.dev/docs/contracts/cache.clear/v1). ### Go values To cache a Go value (a parsed template, a compiled program) without turning it into bytes on every `Set` and back on every `Get`, make it a `cachev1.Item` and open the bucket with `OpenItems`: ```go type compiled struct{ /* ... */ } func (c *compiled) CacheSize() int64 { /* roughly the bytes it holds in memory */ } func (c *compiled) MarshalCache() ([]byte, error) { /* bytes decode turns back into an equal value */ } func (c *compiled) CacheVersion() string { return "compiled/2" } // change it when the bytes' format changes items, err := cachev1.OpenItems(app, "myext.compiled", cachev1.Options{MaxMemory: 64 << 20}, "compiled/2", func(b []byte) (*compiled, error) { /* ... */ }) if c, ok, _ := items.Get(ctx, key); ok { return c } c := compile() _ = items.Set(ctx, key, c, 0) ``` What a provider does with them: - **Each key holds its own item.** Nothing is shared between keys, buckets or apps: the code that owns the bucket owns its items, and every `Get` of a key returns that key's item, not a copy. `CacheSize` counts against the memory caps in place of a length. - **Only a `Marshaler` leaves memory.** `CacheSize` alone makes an item that lives in memory only: evicted, it's gone. `MarshalCache` promises bytes that decode back to an equivalent item; the provider calls it only when it moves the item (to disk, across a restart, to another server), and may keep identical bytes from many keys once, there. - **Versions keep old bytes out.** The provider keeps `CacheVersion` beside the bytes (bucket, key, version -> content), and a decoder of another version never sees them: a miss, so a code change that alters the format doesn't decode stale bytes. On a provider that keeps only bytes, `Items` marshals on `Set` (with the version in front) and decodes on `Get`, so the code is the same either way. ## Provide Implement `cachev1.Cache` (`Bucket`, `Clear`) and `cachev1.Bucket` (`Get`, `Set`, `Delete`, `Clear`), and provide it in `Register`, as the default if another provider should replace yours: ```go cachev1.Contract.Provide(app, myCache) ``` `Cache.Clear` empties every bucket the app has, including ones it hasn't opened since it started. Provide [cache.clear/v1](https://pocketone.dev/docs/contracts/cache.clear/v1) beside it. To keep Go values without marshaling them, have your buckets also implement `cachev1.ItemBucket` (`GetItem`, `SetItem`). Items and bytes share a bucket's keys: `Get` of a `Marshaler` returns its bytes (and misses on an item that can't marshal), and `GetItem` of bytes of the decoder's version returns them decoded, as the key's item from then on. Never hand one key's item to another key. A bucket that only keeps bytes needs nothing more: `Items` marshals for it. Keep each app's buckets apart: on a shared store (one per process, or Redis), prefix keys with `extkit.AppID(app)` and the bucket name. Treat `Options` as caps you keep as well as your storage allows (Redis has its own eviction), and say in your README which ones you honour. ## Extensions | Extension | | |---|---| | [cache](https://pocketone.dev/docs/extensions/cache) | provides (default) | | [mothership](https://pocketone.dev/docs/extensions/mothership) | requires | | [pages](https://pocketone.dev/docs/extensions/pages/extension) | works with | ## License MIT --- Source: https://pocketone.dev/docs/contracts/cli.commands/v1 # cli.commands/v1 The `pocketone` command tree. Every operation of every wire contract linked into the binary is a command under `remote`, with no code: `pocketone remote restore to --at -2h` calls restore/v1's `RestoreTo` on the project's remote. An extension replaces one of those commands by providing the same path, or adds commands of its own. One provider per path; when two extensions provide the same path, `pocketone.yaml` picks one. A keyed contract (by command path), in the developer's `pocketone` process ([commands.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/cli/commands/v1/commands.go)). ## Use The generated commands, for any contract: - **Path:** `remote`, the contract id's words, then the operation: restore/v1's `restore_to` is `remote restore to`, mail.suppression/v1's `check` is `remote mail suppression check`, remote/v1's `status` is `remote status` (`clicmdv1.PathOf`). - **Flags:** one per field of the operation's input (`--at`, `--email`, `--campaign`), plus `--json` for the whole input (`@file`, `-` for stdin) and `--remote` (a remote's name or a URL; default: the project's default remote). Times take RFC 3339, a local time (`2026-11-10 15:00`) or a duration from now (`-2h`). - **Output:** the answer as JSON; streams print one JSON line per entry until Ctrl-C. - **Auth:** the remote's saved login (`pocketone login`), or `P1_TOKEN` in CI. - **Not commands:** public operations that take or return a raw body (an unsubscribe page, a mail provider's webhook); they're for browsers and services. A remote that doesn't offer the contract answers "this remote doesn't offer restore/v1". ## Provide Provide a command in your extension's `Register`. The same path as a generated command replaces it; a new path adds one: ```go clicmdv1.Contract.Provide(app, clicmdv1.Command{ Path: "remote rehash", Short: "Rehash every stored password", Flags: func(fs *pflag.FlagSet) { fs.Bool("dry-run", false, "only count") }, Run: func(c *clicmdv1.Ctx, args []string) error { caller, err := c.Caller("rehash/v1") // the command's remote, with its login if err != nil { return err } return caller.Call(c, "POST", "", nil, nil) }, }) ``` and declare `Implements: extkit.IDs("cli.commands/v1")`. Two providers of one path fail the start until `pocketone.yaml` picks: ```yaml providers: cli.commands/v1: remote rehash: rehasher ``` A binary builds its tree with `clicmdv1.Mount(app, rootCmd)` once the app's contracts are sealed; the standard set does it in `Register`. Commands already on the tree (`remote add`, `remote whoami`) stay unless a provider replaces them. ## Extensions | Extension | | |---|---| | [desktop](https://pocketone.dev/docs/extensions/desktop/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/deploy/v1 # deploy/v1 A project's code on an app: its `pb_*` folders except `pb_data` (`pb_hooks`, `pb_migrations`, `pb_pages`, `pb_public`, `pb_templates`) and packages (`package.json`, the lockfile, `node_modules`). Clients send only the files the app lacks, then swap the new set in at once. Restart and logs are [remote/v1](https://pocketone.dev/docs/contracts/remote/v1)'s, which it requires. A routed contract ([deploy.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/deploy/v1/deploy.go)): its provider is an `http.Handler` serving the file API below. A multisite host can provide it for its instances. ## Use | HTTP | What it does | |---|---| | `POST /api/_c/deploy/v1/check` | which files the app lacks (JSON) | | `POST /api/_c/deploy/v1/blobs` | upload them (gzip bytes) | | `POST /api/_c/deploy/v1/commit` | swap the new code set in (JSON) | | `GET /api/_c/deploy/v1/files` | list deployed files | | `DELETE /api/_c/deploy/v1/files` | delete files | | `GET` / `PUT /api/_c/deploy/v1/files/raw` | read or write one file (raw bytes) | | `POST /api/_c/deploy/v1/files/bundle` | read many files at once (`{"paths"}` → a gzipped bundle, the upload's format) | | `GET /api/_c/deploy/v1/tree` | the app's code tree, for two-way sync (`deep=1`: every folder in one answer) | Token scopes: `deploy` (everything) and `deploy:read` (list, read, tree). The CLI: `pocketone deploy`, `dev`, `pull`. ## Provide Provide an `http.Handler` that serves the API under `deployv1.Prefix`: ```go deployv1.Contract.ProvideDefault(app, handler) ``` A host provides it for its instances with `deployv1.Contract.ProvideForInstances(host, factory)` and `extkit.HostRoutes(host, deployv1.Contract, multisite.InstanceID, next)` in its instance routes (`multisite.Host.InstanceRoutes`, after the gates). ## Commands and APIs Its own HTTP API under `/api/_c/deploy/v1/`, described above. It has no generated commands or MCP tools. [Remote CLI](https://pocketone.dev/docs/features/remote) explains how PocketOne apps are managed from afar. ## Extensions | Extension | | |---|---| | [deploy](https://pocketone.dev/docs/extensions/deploy) | provides (default) | ## License MIT --- Source: https://pocketone.dev/docs/contracts/gate/v1 # gate/v1 What admits requests on a multisite host before an instance is served here or forwarded to another server: a peer allow list, the real client IP behind a proxy, rate limits. Gates run in order and every one must admit; a gate may answer the request itself (429, 403). A host-scope service contract, many providers in order ([gate.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/gate/v1/gate.go)). ## Use Nothing to call: the host runs every gate on every request. Pick or order them in `pocketone.yaml`: ```yaml providers: gate/v1: [firewall] ``` ## Provide Implement `gatev1.Gate` (`AllowPeer` before routing, `Admit` per instance, returning a release function), and `gatev1.ClientIPResolver` if the gate knows the real client. Provide it in a host extension's `RegisterHost`: ```go gatev1.Contract.ProvideIn(h.Scope, myGate) ``` ## Extensions | Extension | | |---|---| | [firewall](https://pocketone.dev/docs/extensions/firewall) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/http.wrap/v1 # http.wrap/v1 Middleware around everything a multisite host serves: health, every instance, forwarded requests. Wrappers nest in provider order, the first outermost (a Server-Timing header first, so it measures everything inside it). A host-scope service contract, many providers in order ([wrap.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/http/wrap/v1/wrap.go)). ## Use Nothing to call: the host wraps its handler with every provider. Order them in `pocketone.yaml` if needed: ```yaml providers: http.wrap/v1: [servertiming] ``` ## Provide Implement `wrapv1.Wrapper` (`Wrap(next http.Handler) http.Handler`) and provide it in a host extension's `RegisterHost`: ```go wrapv1.Contract.ProvideIn(h.Scope, myWrapper) ``` ## Extensions | Extension | | |---|---| | [servertiming](https://pocketone.dev/docs/extensions/servertiming) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.fs/v1 # instance.fs/v1 An instance's code files, for extensions that read and write them: deploy today, a live file drive next. It answers where the instance's folder is, where an extension may keep files it can rebuild (its cache), the one lock every writer takes, whether the instance runs, and how to restart it around a change that mustn't happen under a running app. The code is the `pb_*` folders except `pb_data` and `pb_cache`, `package.json` and the bun lockfiles at the top, `patches/`, and the production `node_modules` tree at the top. **`pb_data` and `pb_cache` are never reachable through this contract.** A service contract ([fs.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/fs/v1/fs.go)), one provider. It holds no request lookup and no auth: callers say which instance by id, and decide for themselves who may call them. ## Use ```go files := fsv1.Contract.Must(app) // after registration: in a hook or at serve time f, err := files.Instance(ctx, fsv1.Self) // a single app's own files; a host passes the instance's id dir, _ := f.Dir(ctx) // the instance folder rel, path, err := fsv1.Resolve(dir, "pb_hooks/main.pb.js") // a client path, checked unlock, _ := f.Lock(ctx) // every write holds it defer unlock() startErr, err := f.Restart(ctx, func(ctx context.Context) error { /* swap files in */ return nil }) ``` The package also holds the code-path rules every user shares: - `IsCodePath(p)`: what a deploy may write or delete (never `pb_data` or `pb_cache`). - `IsReachable(p)`: what a file API may read or write (the code, `node_modules`, `patches/`; never `pb_data`, `pb_cache` or `.git*`). - `Resolve(dir, p)`: a client path to a file inside `dir`, refusing unreachable paths, symlink crossings and anything that lands outside the folder (`*PathError`). `CacheDir(ctx, name)` is the extension's folder for files it can rebuild, following PocketOne's `pb_cache` convention (`pb_cache/` in the app's folder on a single app; Pocker and Docker hosts keep it outside the instance folder, in the host's `pb_cache/instances//`): anything in it may be deleted at any time, it is never code and never reachable, and it is on the same filesystem as `Dir`, so an extension can stage files there and rename them in atomically. ## Provide Implement `fsv1.Files`: `Instance(ctx, id)` returns an `fsv1.FS` for each instance (`fsv1.Self` on a single app), or `fsv1.ErrNoInstance`. Return the same `FS` for the same instance every time: its `Lock` must be shared by every caller. `fsv1.Local` is an `FS` over a local folder to build on: give it the folder, and optionally a cache folder, whether it runs, how to stop it and how to start it again. - **Single app:** [deploy](https://pocketone.dev/docs/extensions/deploy) provides it as the default: the app's own folder. The app can't stop itself, so `Restart` applies the change while it runs (each rename is atomic) and then restarts the app. - **Host:** the host's runtime provides it on the host scope (`fsv1.Contract.ProvideIn`), one per host since a host runs one runtime: [pocker](https://pocketone.dev/docs/extensions/pocker) (`Manager.Files()`: stops the instance's app, starts it again) and [docker](https://pocketone.dev/docs/extensions/docker) (`Runtime.Files(dir)`: stops the container; the next request starts a fresh one). `fsv1.Instances` is the `Files` they build on: one `Local` per known instance, kept so its lock is shared. instance.fs/v1 isn't host-providable, so code inside an instance never reaches the host's provider. ## Extensions | Extension | | |---|---| | [docker](https://pocketone.dev/docs/extensions/docker) | provides | | [pocker](https://pocketone.dev/docs/extensions/pocker) | provides | | [deploy](https://pocketone.dev/docs/extensions/deploy) | provides (default) | | [deploy](https://pocketone.dev/docs/extensions/deploy) | requires | ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.lookup/v1 # instance.lookup/v1 A companion to [instance.source/v1](https://pocketone.dev/docs/contracts/instance.source/v1) for sources that don't hold every instance: the host asks on every request it can't route, and the provider answers from its cache or fetches. A host-scope service contract ([lookup.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/lookup/v1/lookup.go)). ## Use When something provides it on the host's scope, [ext/multisite](https://pocketone.dev/docs/extensions/multisite) routes every request's hostname through `Lookup(ctx, host)` instead of its directory. `Found: false` is 404; an error is 503 (the answer isn't known, for instance while the control plane can't be reached and the host isn't cached). ## Provide Implement `lookupv1.Lookup` and provide it in a host extension's `RegisterHost`, beside instance.source/v1: ```go lookupv1.Contract.ProvideIn(h.Scope, myLookup) ``` The source's `Watch` should still report changes to instances it handed out, so the runtime recycles or stops them. [ext/mothership/client](https://github.com/pocketonehq/pocketone/blob/main/ext/mothership/client/client.go) is the provider. ## Extensions | Extension | | |---|---| | [mothership](https://pocketone.dev/docs/extensions/mothership) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.resolve/v1 # instance.resolve/v1 How a control plane (a mothership) decides what a hostname serves for a given edge, from its own records. The watch server ([instance.watch/v1](https://pocketone.dev/docs/contracts/instance.watch/v1)) asks it on every watch and asks again after every write to a record an answer depends on, so a resolver only has to be right; it never tracks changes. A service contract on the mothership app ([resolve.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/resolve/v1/resolve.go)). ## Use `resolvev1.Contract.Must(app)` after registration: - `Resolve(ctx, Query{Edge, Host})`: the instance (`nil`: no such host) and its `Deps`. - `Standing(ctx, edge)`: instances the edge must hold whatever its traffic, with their deps. - `Edges(ctx)`: every edge, with the list's deps. - `Touches(ctx, record)`: the deps a write of the record touches besides its own record and collection. Deps are strings built with `resolvev1.Record(collection, id)`, `Collection(name)` (any record of it), `Host(name)` (whoever claims the name) and `Key(name)` (the resolver's own, such as which record is edge `lax-1`). ## Provide Implement `resolvev1.Resolver` and provide it on the mothership app. [ext/mothership](https://pocketone.dev/docs/extensions/mothership)'s `Schema` provides the default over its `edges` and `instances` collections; a control plane with its own collections provides its own, and one that only adds to the default's answers wraps it (`Contract.Wrap`). `Touches` should report only what a write changed (compare `rec.Original()`): a record written often, such as an edge's heartbeat, mustn't re-resolve every answer that merely looked it up. ## Extensions | Extension | | |---|---| | [mothership](https://pocketone.dev/docs/extensions/mothership) | provides (default) | | [mothership](https://pocketone.dev/docs/extensions/mothership) | requires | ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.source/v1 # instance.source/v1 The record of one instance on a multisite host: its id, hostnames, PocketBase version, folder, secrets, limits, superusers, per-extension settings, whether it's blocked or runs elsewhere. Every host contract reads the same record: runtimes run it, gates admit requests for it. A source supplies the records and streams changes. A host-scope service contract ([instance.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/source/v1/instance.go), [limits.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/source/v1/limits.go)). ## Use A host takes its records from whichever extension provides this contract: by default its `instances` file (`instances: { file: instances.yaml }`), or a control plane's mirror (ext/mothership). In Go the record is `sourcev1.Instance` (`multisite.Instance` is the same type). ## Provide Implement `sourcev1.Source`: `Snapshot(ctx)` returns every instance, `Watch(ctx)` streams changes (upserts and deletes) until ctx is done. Provide it on the host's scope in a host extension's `RegisterHost`: ```go sourcev1.Contract.ProvideIn(h.Scope, mySource) ``` In tests, [sourcetest](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/source/v1/sourcetest/sourcetest.go) provides it: `src, scope := sourcetest.Scope(instances...)` gives a sealed host scope with a fixed list, and `src.Set(inst)` / `src.Delete(id)` change it the way an edit to the instances file would. ## Extensions | Extension | | |---|---| | [mothership](https://pocketone.dev/docs/extensions/mothership) | provides | | [pocker](https://pocketone.dev/docs/extensions/pocker) | requires | ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.status/v1 # instance.status/v1 What a multisite host knows about the instances it runs, as it changes. The host supervises every start: it launches the instance through its runtime, asks the instance's health endpoint until it answers, and listens for the runtime's exit signal ([runtime/v1](https://pocketone.dev/docs/contracts/runtime/v1)'s `ExitNotifier`). A host-scope service contract ([status.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/status/v1/status.go)). ## Use Take it from the host's scope once the host is set up, and subscribe: ```go st := statusv1.Contract.MustIn(h.Scope) cancel := st.Subscribe(func(s statusv1.Status) { report(s.InstanceID, s.State) }) ``` `Current()` lists every instance that isn't idle, for sending the full picture again (after a control plane comes back, say). ## Provide [ext/multisite](https://pocketone.dev/docs/extensions/multisite) provides it by default on every host. Its runtime implements runtime/v1's `ExitNotifier` (and `RunningLister`, `HealthChecker` when it has them) so the states are right. ## Extensions No extension declares this contract yet. ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.tokens/v1 # instance.tokens/v1 A multisite host checks an API token one of its instances issued. `pocketone login` and `pocketone clone` sign in to the instance (its oauth/v1) and get the instance's own token. Where the host, not the instance, answers deploy/v1 and remote/v1, the host checks that token with this contract, so signing in works the same way on every host. A service contract ([tokens.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/tokens/v1/tokens.go)), one provider, on the host's scope. It holds no auth of its own: the host decides what an instance token may do there (for example, only the instance's superusers may deploy). ## Use ```go tk, ok := tokensv1.Contract.In(host.Scope) // after the host's seal res, err := tk.Verify(ctx, tokensv1.Input{Instance: id, Token: token}) switch { case errors.Is(err, tokensv1.ErrNoInstance): // not one of this runtime's instances, or it has no API tokens case err != nil: // the instance failed to start: not a refusal case !res.Valid: // res.Reason: "invalid" or "expired" default: // res.Grant: the owner (collection, id) and scopes, as api-tokens/v1 says } ``` The answer is [api-tokens.verify/v1](https://pocketone.dev/docs/contracts/api-tokens.verify/v1)'s `Result`. A token the instance didn't issue is `Valid: false`, never an error, so a host can tell a refused token from an instance that won't start. Verifying may start an instance that isn't running. ## Provide A runtime that can reach inside its instances provides it on the host scope (`ProvideIn`): look up the instance's app and ask its api-tokens/v1 (`Verify`), mapping `apitokensv1.ErrInvalid` and `ErrExpired` to `Valid: false`. A runtime that can't (stock PocketBase images) doesn't provide it. ## Extensions | Extension | | |---|---| | [pocker](https://pocketone.dev/docs/extensions/pocker) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/instance.watch/v1 # instance.watch/v1 An edge follows a mothership without holding every instance. It opens one stream; the first time a request names a hostname, it asks for it; from then on it hears every change to what that hostname serves, until it stops caring. Nothing is sent that no edge asked for, except the list of edges and the edge's standing set (instances it must hold whatever its traffic, such as a copy waiting to be made). A wire contract ([watch.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/instance/watch/v1/watch.go)) at `/api/_c/instance.watch/v1/`. Superusers only (scope `fleet`). ## Use | Operation | | | |---|---|---| | `stream` | `GET /stream?edge=` | Server-sent events, each `{kind, seq, ...}`: `hello` first (`conn`, `self`, `edges`, `standing`), then `host` (`host`, `answer`), `edges`, `standing`, and `ping` when idle | | `watch` | `POST /watch {conn, edge, host}` | Registers `host` on the stream `conn` and sends its answer there. With no live `conn`, the answer comes in the reply and nothing is watched | | `unwatch` | `POST /unwatch {conn, host}` | Stops changes for `host` on `conn` | The promise is in the order: - The hostname is registered before it is read, so no write between the two is missed. - The answer goes on the stream, never in the reply, so the answer and every later change arrive in the order they happened. A `host` event with no `answer` means the hostname couldn't be resolved (an error, not "not found"). - "No such host" is an answer (`found: false`), watched like any other: the instance that later takes the name arrives. - A change is sent only when the answer differs from the one sent last on that stream. - `seq` numbers a stream's events from 1; a gap means something was lost and the edge reconnects. - A dropped stream forgets every watch. An edge starts over on its next stream; what it cached before is unwatched. In Go, [ext/mothership/client](https://github.com/pocketonehq/pocketone/blob/main/ext/mothership/client/client.go) is the edge side: it is a multisite host's instance.source/v1 and [instance.lookup/v1](https://pocketone.dev/docs/contracts/instance.lookup/v1). ## Provide Implement `watchv1.Watcher` and provide it on the mothership app. [ext/mothership](https://pocketone.dev/docs/extensions/mothership)'s `Server` is the provider: it keeps each stream's watches in memory, indexes them by the deps [instance.resolve/v1](https://pocketone.dev/docs/contracts/instance.resolve/v1) returns, and resolves again after every committed write that touches them. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### stream Opens this edge's stream: a hello first, then answers and changes for the hostnames it watches, the edges list when it changes, and its standing set when that changes. | | | |---|---| | REST | `GET /api/_c/instance.watch/v1/stream` | | CLI | `pocketone remote instance watch stream --edge ` | | MCP | `instance_watch_stream` | | Token scope | `fleet` | | Answer | a stream of JSON entries (server-sent events); the command prints one line each | | Input field | Flag | Type | |---|---|---| | `edge` | `--edge` | string | ### watch Registers a hostname on a stream and sends its answer there (or, with no live stream, in the reply). | | | |---|---| | REST | `POST /api/_c/instance.watch/v1/watch` | | CLI | `pocketone remote instance watch --conn --edge --host ` | | MCP | `instance_watch_watch` | | Token scope | `fleet` | | Input field | Flag | Type | |---|---|---| | `conn` | `--conn` | string | | `edge` | `--edge` | string | | `host` | `--host` | string | ### unwatch Stops changes for a hostname on a stream. | | | |---|---| | REST | `POST /api/_c/instance.watch/v1/unwatch` | | CLI | `pocketone remote instance watch unwatch --conn --host ` | | MCP | `instance_watch_unwatch` | | Token scope | `fleet` | | Input field | Flag | Type | |---|---|---| | `conn` | `--conn` | string | | `host` | `--host` | string | ## Extensions | Extension | | |---|---| | [mothership](https://pocketone.dev/docs/extensions/mothership) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/kv/v1 # kv/v1 An app's key-value store: a name and a JSON value, kept without a collection or a migration. Use it for an app's settings, a feature's state, anything that is one blob rather than many records. Each value is a row in PocketBase's own `_params` table, so it rides along in backups. A wire contract ([kv.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/kv/v1/kv.go)) plus Go helpers ([helpers.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/kv/v1/helpers.go)). ## Use **From Go** (an extension, a hook), call the helpers. They need no provider and work inside a transaction when given one: ```go var s Settings found, err := kvv1.Get(app, "storytime/settings", &s) // found is false and s untouched when there's no value err = kvv1.Set(app, "storytime/settings", s) // any value json.Marshal takes err = kvv1.Delete(app, "storytime/settings") // no error when there was no value entries, err := kvv1.List(app, "storytime/") // by name prefix, sorted by name; "" lists all (private too) e, found, err := kvv1.Lookup(app, "storytime/settings") // the raw entry, with created and updated ``` Declare `WorksWith: extkit.IDs("kv/v1")` when you do. **From page code and pb_hooks**, the provider gives `$kv` (sync, local): ```js const settings = $kv.get("storytime/settings") ?? defaults // the parsed value, or null $kv.set("storytime/settings", { title: "Story Time", minutes: 10 }) $kv.delete("storytime/settings") $kv.list("storytime/") // [{ name, value, created, updated }] ``` **Over HTTP** (superusers, or an API token with the scope): | Operation | HTTP | Token scope | |---|---|---| | List | `GET /api/_c/kv/v1?prefix=storytime/` | `kv:read` | | Get | `GET /api/_c/kv/v1/get?name=storytime/settings` | `kv:read` | | Set | `POST /api/_c/kv/v1/set` with `{"name": "storytime/settings", "value": {...}}` | `kv` | | Delete | `POST /api/_c/kv/v1/delete` with `{"name": "storytime/settings"}` | `kv` | Get answers `404 not_found` for a name with no value. The same operations are `pocketone remote kv ...` commands and MCP tools (`kv_list`, `kv_get`, `kv_set`, `kv_delete`). **Names** are 1 to 128 characters: letters, digits and `_ - . : /`, starting with a letter or digit. Start yours with a prefix of your own (`storytime/`, `myext:`) so they stay apart from other apps' and extensions'. A value is any JSON up to 1 MiB. **Private names** start with `_` (`_myext/settings`): the Go helpers read and write them, but the wire API (HTTP, the CLI, MCP) and `$kv` refuse them (`403 private`) and leave them out of lists. Keep secrets there, such as API keys and signing keys, which a `kv:read` token must never see. **Moving an extension's own row:** an extension that kept a `_params` row of its own before kv/v1 moves it once with `kvv1.MoveParamOnce(app, "oldrow", "_myext/settings")` before reading (`MoveParam` for a one-off): the value and its times move to the name and the old row goes away. **Storage:** name `storytime/settings` is the `_params` row with id `kv:storytime/settings`, its value the row's `value`. The `kv:` prefix keeps every name apart from PocketBase's own params (`settings`) and from rows extensions keep there themselves. Write through the helpers, never the table, so the rules above hold. ## Provide **The wire API and `$kv`:** ext/kv provides `kvv1.Store` by default, over the helpers. Another provider implements `kvv1.Store` and provides it in `Register` (`kvv1.Contract.Provide(app, s)`); it must keep the storage above, since the helpers read and write it directly. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### list Returns the values whose names start with prefix (all of them when it's empty), sorted by name. Private names (starting with \_) are left out. | | | |---|---| | REST | `GET /api/_c/kv/v1` | | CLI | `pocketone remote kv list --prefix ` | | MCP | `kv_list` | | Token scope | `kv:read` | | Input field | Flag | Type | |---|---|---| | `prefix` | `--prefix` | string | ### get Returns one value. A name with no value is a not\_found error; a private name is a private error. | | | |---|---| | REST | `GET /api/_c/kv/v1/get` | | CLI | `pocketone remote kv get --name ` | | MCP | `kv_get` | | Token scope | `kv:read` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | ### set Stores a JSON value under a name, replacing any value it had. | | | |---|---| | REST | `POST /api/_c/kv/v1/set` | | CLI | `pocketone remote kv set --name --value ` | | MCP | `kv_set` | | Token scope | `kv` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | | `value` | `--value` | json | ### delete Removes a value. Deleting a name with no value is not an error. | | | |---|---| | REST | `POST /api/_c/kv/v1/delete` | | CLI | `pocketone remote kv delete --name ` | | MCP | `kv_delete` | | Token scope | `kv` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | ## Extensions | Extension | | |---|---| | [kv](https://pocketone.dev/docs/extensions/kv/extension) | provides (default) | | [api-tokens](https://pocketone.dev/docs/extensions/api-tokens) | works with | | [billing](https://pocketone.dev/docs/extensions/billing/extension) | works with | | [bulkmail](https://pocketone.dev/docs/extensions/bulkmail) | works with | | [creem](https://pocketone.dev/docs/extensions/creem/extension) | works with | | [llm](https://pocketone.dev/docs/extensions/llm/extension) | works with | | [llm-search](https://pocketone.dev/docs/extensions/llm-search) | works with | | [paddle](https://pocketone.dev/docs/extensions/paddle/extension) | works with | | [stripe](https://pocketone.dev/docs/extensions/stripe/extension) | works with | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.align/v1 # llm.align/v1 A model says when each line and each word of a known text is said in its audio. Nothing is transcribed or guessed: every word that comes back is one you sent, in order. For captions timed to a narration, karaoke-style highlighting, or finding a phrase in a recording. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.align/v1` ([align.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/align/v1/align.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr (`aligner-1`). ## Use In page code it's `$llm.align` (bound by the llm extension): ```js const r = await $llm.align.alignAsync({ model: "vultr/aligner-1", audio: speech.file, // { name: "story.mp3", data } text: "Once upon a time...\nEvery night...", mode: "speech", }) r.lines // [{ index, text, start, end, score, certain }], seconds from the start r.words // [{ line, text, start, end, score }] ``` Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Align | `POST /api/_c/llm.align/v1/align` | `{"model": "...", "audio": {"name": "story.mp3", "data": ""}, "text": "...", "mode": "speech"}` | `llm` | | Models | `GET /api/_c/llm.align/v1/models` | `?provider=` (optional) | `llm:read` | It answers `{"duration", "lines", "words", "unaligned", "model", "usage"}`. `text` has one line per line of the audio; a line in square brackets (`[Chorus]`) labels the lines under it and isn't timed. `mode` is `speech` for a voice recording, or `lyrics` (the provider's default) to separate a sung vocal from the music first. Lines the model couldn't place are listed in `unaligned`, not dropped. Vultr takes up to 25 MiB, 15 minutes and 12,000 characters per call. Errors: `bad_request` (no audio or text, an unknown mode), `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `alignv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/align/v1`). ## Provide Implement `alignv1.Align` and provide it in `Register` (`alignv1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't align, `unknown_model` for a missing model or provider, and `provider` with the cloud's own message (never its key) when the cloud refuses. Return only words of the text sent, in order. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### align Says when each line and word of the text is said in the audio. | | | |---|---| | REST | `POST /api/_c/llm.align/v1/align` | | CLI | `pocketone remote llm align --model --audio --text --mode --language --options ` | | MCP | `llm_align_align` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `audio` | `--audio` | json | | `text` | `--text` | string | | `mode` | `--mode` | string | | `language` | `--language` | string | | `options` | `--options` | json | ### models Lists the alignment models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.align/v1/models` | | CLI | `pocketone remote llm align models --provider ` | | MCP | `llm_align_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.chat/v1 # llm.chat/v1 A chat is a conversation with a language model that the provider stores: the app keeps only its id. Each question goes to [llm.text/v1](https://pocketone.dev/docs/contracts/llm.text/v1) with the chat's recent messages and a summary of the older ones, and both turns are saved. The cloud providers keep no conversations themselves (every call sends the whole conversation), which is what this contract is for. Chats aren't tied to users: an app that has them puts the user's id in the chat's `meta`, lists by it, and decides who may read what. A wire contract at `/api/_c/llm.chat/v1` ([chat.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/chat/v1/chat.go)), one provider. It requires llm.text/v1. The [llm-chat](https://pocketone.dev/docs/extensions/llm-chat) extension provides it. ## Use In page code (the [llm](https://pocketone.dev/docs/extensions/llm/extension) extension binds these on `$llm.chat` when a provider runs): ```js const id = $llm.chat.new({ title: "Support", meta: { user: ctx.auth.id } }) const chat = $llm.chat.open(id, { model: "vultr/glm-5.2", system: preamble, context: (q) => findExcerpts(q) }) const answer = await chat.sendAsync(question) // or sendAsync(question, { onText }) to stream it chat.history({ limit: 20 }) // [{ id, role, content, created }], oldest first $llm.chat.list({ meta: { user: ctx.auth.id } }) $llm.chat.forget({ meta: { user: deletedUserId } }) ``` Over HTTP (a superuser, or a token with the `chat` scope): | Operation | HTTP (`POST`) | Body | Token scope | |---|---|---|---| | New | `/api/_c/llm.chat/v1/new` | `{"title": "", "meta": {}}` | `chat` | | Send | `/api/_c/llm.chat/v1/send` | `{"id": "...", "text": "...", "model": "vultr/glm-5.2", "system": "", "window": 12, "summarizeEvery": 6, "context": ""}` | `chat` | | Send, streamed | `/api/_c/llm.chat/v1/send-stream` | as Send; server-sent events of llm.text/v1 chunks | `chat` | | Get | `/api/_c/llm.chat/v1/get` | `{"id": "..."}` | `chat:read` | | History | `/api/_c/llm.chat/v1/history` | `{"id": "...", "limit": 0, "before": ""}` | `chat:read` | | Update | `/api/_c/llm.chat/v1/update` | `{"id": "...", "title": "...", "meta": {}}` | `chat` | | List | `/api/_c/llm.chat/v1/list` | `{"meta": {"user": "..."}, "limit": 50, "offset": 0}` | `chat:read` | | Forget | `/api/_c/llm.chat/v1/forget` | `{"id": "..."}` | `chat` | | Forget by meta | `/api/_c/llm.chat/v1/forget-where` | `{"meta": {"user": "..."}}` | `chat` | `send` needs `model` and answers `{"answer": , "summarized": bool}`; it also takes `reasoning`, `schema`, `maxTokens` and `temperature`. A chat is `{id, title, summary, meta, messages, created, updated}`. `meta` filters match each top-level key exactly (strings, numbers, true/false, null). `context` is sent after the question; `history` shows the question alone, and later turns send it with its context again, so each prompt starts exactly like the last one did (which the providers' prompt caches reward). Errors: `not_found` (404) for an unknown chat, and llm.text/v1's. ## Provide Implement `chatv1.Chats` and provide it in `Register`. Keep chats in the app's own database (each instance of a host has its own) and call llm.text/v1 for answers and summaries. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### new Starts a chat and returns it; its id is how the app finds it again. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/new` | | CLI | `pocketone remote llm chat new --title --meta ` | | MCP | `llm_chat_new` | | Token scope | `chat` | | Input field | Flag | Type | |---|---|---| | `title` | `--title` | string | | `meta` | `--meta` | json | ### send Asks the chat a question: the provider sends the system text, the chat's summary, its recent messages and the question (with Context after it) to llm.text/v1, saves both turns, and folds older messages into the summary when it's due. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/send` | | CLI | `pocketone remote llm chat send --id --text --system --window --summarizeevery --context --schema --maxtokens --temperature --model --reasoning --enrich ` | | MCP | `llm_chat_send` | | Token scope | `chat` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | | `text` | `--text` | string | | `system` | `--system` | string | | `window` | `--window` | int | | `summarizeEvery` | `--summarizeevery` | int | | `context` | `--context` | string | | `schema` | `--schema` | json | | `maxTokens` | `--maxtokens` | int | | `temperature` | `--temperature` | json | | `model` | `--model` | string | | `reasoning` | `--reasoning` | string | | `enrich` | `--enrich` | json | ### send_stream Is Send with the answer as it's written: llm.text/v1 chunks, the last one with done and the result. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/send-stream` | | CLI | `pocketone remote llm chat send-stream --id --text --system --window --summarizeevery --context --schema --maxtokens --temperature --model --reasoning --enrich ` | | MCP | `llm_chat_send_stream` | | Token scope | `chat` | | Answer | a stream of JSON entries (server-sent events); the command prints one line each | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | | `text` | `--text` | string | | `system` | `--system` | string | | `window` | `--window` | int | | `summarizeEvery` | `--summarizeevery` | int | | `context` | `--context` | string | | `schema` | `--schema` | json | | `maxTokens` | `--maxtokens` | int | | `temperature` | `--temperature` | json | | `model` | `--model` | string | | `reasoning` | `--reasoning` | string | | `enrich` | `--enrich` | json | ### get Returns a chat. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/get` | | CLI | `pocketone remote llm chat get --id ` | | MCP | `llm_chat_get` | | Token scope | `chat:read` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | ### history Returns a chat's messages, oldest first: the last Limit before the message Before (all when 0 and ""). | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/history` | | CLI | `pocketone remote llm chat history --id --limit --before ` | | MCP | `llm_chat_history` | | Token scope | `chat:read` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | | `limit` | `--limit` | int | | `before` | `--before` | string | ### update Sets a chat's title or meta (fields left out stay). | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/update` | | CLI | `pocketone remote llm chat update --id --title --meta ` | | MCP | `llm_chat_update` | | Token scope | `chat` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | | `title` | `--title` | json | | `meta` | `--meta` | json | ### list Returns chats, most recently updated first; Meta keeps those whose meta has each of its top-level keys with that value. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/list` | | CLI | `pocketone remote llm chat list --meta --limit --offset ` | | MCP | `llm_chat_list` | | Token scope | `chat:read` | | Input field | Flag | Type | |---|---|---| | `meta` | `--meta` | json | | `limit` | `--limit` | int | | `offset` | `--offset` | int | ### forget Deletes a chat, its messages and the model's state for it. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/forget` | | CLI | `pocketone remote llm chat forget --id ` | | MCP | `llm_chat_forget` | | Token scope | `chat` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | ### forget_where Deletes every chat whose meta matches (as in List), e.g. all of a user the app deleted. | | | |---|---| | REST | `POST /api/_c/llm.chat/v1/forget-where` | | CLI | `pocketone remote llm chat forget-where --meta --limit --offset ` | | MCP | `llm_chat_forget_where` | | Token scope | `chat` | | Input field | Flag | Type | |---|---|---| | `meta` | `--meta` | json | | `limit` | `--limit` | int | | `offset` | `--offset` | int | ## Extensions | Extension | | |---|---| | [llm-chat](https://pocketone.dev/docs/extensions/llm-chat) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.embed/v1 # llm.embed/v1 A model turns texts into vectors, one per text, for search by meaning. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.embed/v1` ([embed.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/embed/v1/embed.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.embed` (bound by the llm extension): ```js const r = await $llm.embed.embedAsync({ model: "cf/@cf/baai/bge-base-en-v1.5", input: ["bedtime story", "lighthouse"] }) r.vectors[0] ``` Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Embed | `POST /api/_c/llm.embed/v1/embed` | `{"model": "...", "input": ["..."], "dimensions": 0}` | `llm` | | Models | `GET /api/_c/llm.embed/v1/models` | `?provider=` (optional) | `llm:read` | It answers `{"vectors": [[...]], "model", "usage"}`, in the inputs' order. Errors: `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `embedv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/embed/v1`). ## Provide Implement `embedv1.Embed` and provide it in `Register` (`embedv1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't do this kind, `unknown_model` for a missing model or provider, and `provider` with the cloud's own message (never its key) when the cloud refuses. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### embed Returns one vector per input text, in order. | | | |---|---| | REST | `POST /api/_c/llm.embed/v1/embed` | | CLI | `pocketone remote llm embed --model --input --dimensions --options ` | | MCP | `llm_embed_embed` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `input` | `--input` | strings | | `dimensions` | `--dimensions` | int | | `options` | `--options` | json | ### models Lists the embedding models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.embed/v1/models` | | CLI | `pocketone remote llm embed models --provider ` | | MCP | `llm_embed_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | | [llm-search](https://pocketone.dev/docs/extensions/llm-search) | works with | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.image/v1 # llm.image/v1 A model makes pictures from a prompt, and from reference pictures it's given. They come back as files. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.image/v1` ([image.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/image/v1/image.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.image` (bound by the llm extension): ```js const r = await $llm.image.generateAsync({ model: "vultr/z-image-turbo", prompt: "a lighthouse at dusk, watercolor", aspectRatio: "16:9" }) record.set("cover", $llm.file(r.files[0])) ``` `references` are pictures the model draws from: one to change as the prompt says, or one whose style and characters a new scene keeps. Paint an anchor picture first, then every other picture with it as the reference, and a story's pictures share one look: ```js const anchor = (await $llm.image.generateAsync({ model, prompt: "a red fox in a blue scarf and a small owl in round glasses, watercolor" })).files[0] const next = await $llm.image.generateAsync({ model, prompt: "Same style and characters as the reference. Show them rowing across a misty pond.", references: [anchor] }) ``` Only a model whose listing has the feature `"reference images"` takes references (`ModelInfo.Features`, from `models`); offer them only then. Any other model answers `not_supported`, or the provider's own error. Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Generate | `POST /api/_c/llm.image/v1/generate` | `{"model": "...", "prompt": "...", "n": 1, "size": "1024x1024", "references": [File]}` | `llm` | | Models | `GET /api/_c/llm.image/v1/models` | `?provider=` (optional) | `llm:read` | Generate answers `{"files": [File], "model", "usage"}`. A `File` is `{"name", "type", "data", "url"}`: `data` is the bytes (base64), `url` the provider's own copy when it keeps one. Errors: `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `imagev1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/image/v1`). ## Provide Implement `imagev1.Image` and provide it in `Register` (`imagev1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't do this kind, `unknown_model` for a missing model or provider, and `provider` with the cloud's own message (never its key) when the cloud refuses. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. List `"reference images"` (`llm.FeatureReferenceImages`) in a model's `Features` only when both the model and your provider take `references`; answer `not_supported` for references you can't send. ## Decisions - **References are a field of Generate, not an Edit operation** (Ben, 2026-11-24). Drawing a new scene from a reference isn't editing it, and providers treat both the same way: Vultr answers a generation with images as an edit. The earlier `Edit` operation and `EditInput` are gone. - **A feature says which models take them**, not `inputs` containing `"image"`: `inputs` is what the provider says the model reads, but whether `references` work also depends on the provider here (Cloudflare lists models that read images, and its driver sends none). ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### generate Makes pictures from a prompt, and from the reference pictures it's given. | | | |---|---| | REST | `POST /api/_c/llm.image/v1/generate` | | CLI | `pocketone remote llm image generate --model --prompt --n --size --aspectratio --references --options ` | | MCP | `llm_image_generate` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `prompt` | `--prompt` | string | | `n` | `--n` | int | | `size` | `--size` | string | | `aspectRatio` | `--aspectratio` | string | | `references` | `--references` | json | | `options` | `--options` | json | ### models Lists the image models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.image/v1/models` | | CLI | `pocketone remote llm image models --provider ` | | MCP | `llm_image_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.ledger/v1 # llm.ledger/v1 Every `llm.*` call that reaches a provider, and every call a limit refuses, is recorded in the app's ledger: its kind and model, whom it was for, the tokens and seconds it used and what it cost. This contract reads it: how much of each limit a user or guest has left, what someone has spent, totals by model, kind, subject or day, and the rows themselves. A wire contract at `/api/_c/llm.ledger/v1` ([ledger.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/ledger/v1/ledger.go)), one provider: the [llm](https://pocketone.dev/docs/extensions/llm/extension) extension, over its `_llm_calls` collection. A subject is whom calls were for: `user:/`, `guest:`, `guest:ip:
`, or a name an app's `$llm.onCall` handler gave it (`team:acme`). See `llm.WithSubject` in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). ## Use In page code it's `$llm.ledger` (bound by the llm extension). These are local reads, not provider calls, so they're plain. Through `$llm.for(ctx)`, `remaining` and `spent` answer about that request's user or guest: ```js const llm = $llm.for(ctx) llm.ledger.remaining() // [{ limit: "each guest, $0.10 a day", metric: "cost", used, amount, left, resets }], tightest first llm.ledger.spent("day") // { calls, refused, input, cached, output, seconds, costMicroUSD } $llm.ledger.summary({ by: "model", window: "month" }) // [{ key: "vultr/glm-5.3", calls, costMicroUSD, ... }] $llm.ledger.calls({ subject: "user:users/abc", limit: 20 }) // { calls: [...], more } ``` Over HTTP: | Operation | HTTP | Query | Who | |---|---|---|---| | Remaining | `GET /api/_c/llm.ledger/v1/remaining` | `subject` (optional) | anyone signed in: a user (or their API token) gets their own; a superuser (or a superuser's token) any subject | | Spent | `GET /api/_c/llm.ledger/v1/spent` | `subject`, `window` (`day`, `month`) or `since`/`until`, `kind`, `model` | as for Remaining | | Summary | `GET /api/_c/llm.ledger/v1/summary` | `by` (`model`, `kind`, `subject`, `day`), the window, `subject`, `kind`, `model`, `limit` | a superuser, or a superuser's token with `llm:read` | | Calls | `GET /api/_c/llm.ledger/v1/calls` | the window, `subject`, `kind`, `model`, `status` (`ok`, `refused`), `limit`, `offset` | a superuser, or a superuser's token with `llm:read` | Windows are UTC: `day` and `month` are the calendar day and month holding now, the same windows limits count in; `since` and `until` take RFC 3339 or `YYYY-MM-DD` (`until` is exclusive). Money is `costMicroUSD`, millionths of a US dollar, as in every result's `usage`. A guest can't ask over HTTP (an operation sees credentials, not the guest cookie); page code answers guests through `$llm.for(ctx)`. Errors: `bad_request` (an unknown window, `by` or `status`, a time it can't read), `unauthorized` (Remaining or Spent with no credentials), `forbidden` (a user asking about someone else). From Go: `ledgerv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/ledger/v1`). Name the subject in the input, or carry it in the context with `llm.WithSubject`. ## Provide Implement `ledgerv1.Ledger` and provide it in `Register` (`ledgerv1.Contract.Provide(app, impl)`), over the same record of calls the provider's limits count from, so `remaining` agrees with what the next refusal will say. Answer a non-superuser caller about their own subject only. Sort `remaining` tightest first (the smallest share left) and `summary` costliest first (by day, latest first). ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### remaining Is, for each limit in Settings → LLM that counts the subject's calls, how much is used and left in its current window, the tightest first. | | | |---|---| | REST | `GET /api/_c/llm.ledger/v1/remaining` | | CLI | `pocketone remote llm ledger remaining --subject ` | | MCP | `llm_ledger_remaining` | | Token scope | public | | Input field | Flag | Type | |---|---|---| | `subject` | `--subject` | string | ### spent Is what the subject's calls used in a window. | | | |---|---| | REST | `GET /api/_c/llm.ledger/v1/spent` | | CLI | `pocketone remote llm ledger spent --subject --window --since --until --kind --model ` | | MCP | `llm_ledger_spent` | | Token scope | public | | Input field | Flag | Type | |---|---|---| | `subject` | `--subject` | string | | `window` | `--window` | string | | `since` | `--since` | string | | `until` | `--until` | string | | `kind` | `--kind` | string | | `model` | `--model` | string | ### summary Is what calls used, grouped by model, kind, subject or day. | | | |---|---| | REST | `GET /api/_c/llm.ledger/v1/summary` | | CLI | `pocketone remote llm ledger summary --by --window --since --until --subject --kind --model --limit ` | | MCP | `llm_ledger_summary` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `by` | `--by` | string | | `window` | `--window` | string | | `since` | `--since` | string | | `until` | `--until` | string | | `subject` | `--subject` | string | | `kind` | `--kind` | string | | `model` | `--model` | string | | `limit` | `--limit` | int | ### calls Lists the ledger's rows, newest first. | | | |---|---| | REST | `GET /api/_c/llm.ledger/v1/calls` | | CLI | `pocketone remote llm ledger calls --window --since --until --subject --kind --model --status --limit --offset ` | | MCP | `llm_ledger_calls` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `window` | `--window` | string | | `since` | `--since` | string | | `until` | `--until` | string | | `subject` | `--subject` | string | | `kind` | `--kind` | string | | `model` | `--model` | string | | `status` | `--status` | string | | `limit` | `--limit` | int | | `offset` | `--offset` | int | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.music/v1 # llm.music/v1 A model makes music from a prompt (and lyrics). It takes a while, so it's a job. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.music/v1` ([music.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/music/v1/music.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.music` (bound by the llm extension): ```js const job = await $llm.music.createAsync({ model: "vultr/ace-step-1.5", prompt: "gentle lullaby", seconds: 60, wait: "5m" }) if (job.status === "done") record.set("music", $llm.file(job.files[0])) ``` Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Create | `POST /api/_c/llm.music/v1/create` | `{"model": "...", "prompt": "...", "lyrics": "", "seconds": 60, "wait": ""}` | `llm` | | Get | `POST /api/_c/llm.music/v1/get` | `{"id": "vultr:music_..."}` | `llm:read` | | Content | `POST /api/_c/llm.music/v1/content` | `{"id": "...", "index": 0}` | `llm:read` | | Models | `GET /api/_c/llm.music/v1/models` | `?provider=` (optional) | `llm:read` | `create` and `get` answer a job: `{"id", "status" (queued, running, done, failed), "progress", "files", "outputs", "error", "model", "usage"}`. With `wait` (`"5m"`) `create` returns once the job stops, its files included; without it, at once. The id carries the provider (`vultr:music_02a2…`), and the provider keeps the job. `content` returns one of a done job's files. Errors: `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `musicv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/music/v1`). ## Provide Implement `musicv1.Music` and provide it in `Register` (`musicv1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't do this kind, `unknown_model` for a missing model or provider, and `provider` with the cloud's own message (never its key) when the cloud refuses. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### create Starts making music. With Wait it returns once the job is done (or failed), its files included; otherwise at once, to follow with Get. | | | |---|---| | REST | `POST /api/_c/llm.music/v1/create` | | CLI | `pocketone remote llm music create --model --prompt --lyrics --seconds --wait --options ` | | MCP | `llm_music_create` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `prompt` | `--prompt` | string | | `lyrics` | `--lyrics` | string | | `seconds` | `--seconds` | float | | `wait` | `--wait` | string | | `options` | `--options` | json | ### get Says how a job is going. | | | |---|---| | REST | `POST /api/_c/llm.music/v1/get` | | CLI | `pocketone remote llm music get --id ` | | MCP | `llm_music_get` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | ### content Fetches one of a done job's files. | | | |---|---| | REST | `POST /api/_c/llm.music/v1/content` | | CLI | `pocketone remote llm music content --id --index ` | | MCP | `llm_music_content` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `id` | `--id` | string | | `index` | `--index` | int | ### models Lists the music models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.music/v1/models` | | CLI | `pocketone remote llm music models --provider ` | | MCP | `llm_music_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.search/v1 # llm.search/v1 Knowledge bases (buckets) an app searches with hybrid search, for retrieval-augmented generation (RAG). An app makes the bucket it needs (`ensure`); its admins fill it with sources, each one tracked unit however many documents it brings: a file, pasted text, a folder, a zip, a web page, a Git repository or one of the app's collections. Adding a source of the same name again replaces it (unchanged documents cost nothing, missing ones go); pages and repositories are read again on an interval, collections kept in sync. The provider splits each document into chunks that keep their source (document, section, lines, record), embeds them with the app's one embedding model (llm.embed/v1, picked automatically; identical chunks anywhere in the app are embedded once), and returns the best chunks for a query across the buckets asked for. It never answers the question itself; llm.text/v1 and llm.chat/v1 calls take `enrich` to add a search's passages to their prompt, through the [`Enrich`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/search/v1/enrich.go) helper every provider of those contracts uses. A wire contract at `/api/_c/llm.search/v1` ([search.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/search/v1/search.go)), one provider. The [llm-search](https://pocketone.dev/docs/extensions/llm-search) extension provides it. It brings the dashboard's **Search** screen ([ui/main.js](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/search/v1/ui/main.js)), which calls only this contract (and llm.embed/v1's model list), so it works whoever provides it. ## Use In page code it's `$llm.search` (bound by the llm extension), and `enrich` on `$llm` calls: ```js $llm.search.ensure({ name: "help", title: "Help center", description: "Our help articles." }) $llm.search.addURL({ bucket: "help", url: "https://github.com/acme/docs", every: "day" }) const r = await $llm.search.searchAsync({ buckets: ["help"], query: "export to PDF", limit: 5, viewer: ctx.auth }) const answer = await $llm.text.completeAsync({ model: "vultr/glm-5.3", prompt: question, enrich: ["help"] }) ``` Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Status | `GET /api/_c/llm.search/v1/status` | | `search:read` | | Set model | `POST /api/_c/llm.search/v1/set-model` | `{"model"}` (`""` picks one again) | `search` | | Buckets | `GET /api/_c/llm.search/v1/buckets` | | `search:read` | | Bucket | `GET /api/_c/llm.search/v1/bucket` | `?name=` | `search:read` | | Ensure | `POST /api/_c/llm.search/v1/ensure` | `{"name", "title", "description", "owner"}` | `search` | | Update | `POST /api/_c/llm.search/v1/update` | `{"name", "title"?, "description"?, "maxDocuments"?, "maxBytes"?}` | `search` | | Delete | `POST /api/_c/llm.search/v1/delete` | `{"name"}` | `search` | | Sources | `GET /api/_c/llm.search/v1/sources` | `?bucket=` | `search:read` | | Add | `POST /api/_c/llm.search/v1/add` | `{"bucket", "name", "text", "kind"?, "replace"?}` (a file or text) | `search` | | Upload | `POST /api/_c/llm.search/v1/upload` | `?bucket=&name=&replace=`, the file (or `.zip`) as the body | `search` | | Put | `POST /api/_c/llm.search/v1/put` | `{"bucket", "source", "path", "text", "replace"?}` (a folder's file) | `search` | | Prune | `POST /api/_c/llm.search/v1/prune` | `{"bucket", "source", "keep": [...]}` (ends a folder) | `search` | | Add URL | `POST /api/_c/llm.search/v1/add-url` | `{"bucket", "url", "kind"?, "every"?, "commits"?, "exclude"?}` | `search` | | Detect URL | `POST /api/_c/llm.search/v1/detect-url` | `{"url"}` → `{"kind"}`: `git` when the server answers the Git protocol, else `page` | `search:read` | | Follow | `POST /api/_c/llm.search/v1/follow` | `{"bucket", "collection", "fields": [...], "filter"?}` | `search` | | Add folder | `POST /api/_c/llm.search/v1/add-folder` | `{"bucket", "path", "include"?, "exclude"?, "url"?}` (a folder of the app's files on the server) | `search` | | Refresh | `POST /api/_c/llm.search/v1/refresh` | `{"bucket", "source"}` | `search` | | Remove | `POST /api/_c/llm.search/v1/remove` | `{"bucket", "sources": [...]}` | `search` | | Documents | `GET /api/_c/llm.search/v1/documents` | `?bucket=&source=&prefix=` | `search:read` | | Search | `POST /api/_c/llm.search/v1/search` | `{"buckets": [...], "query", "limit", "prefix", "viewer"}` | `search:read` | | Sample | `POST /api/_c/llm.search/v1/sample` | `{"buckets": [...], "count", "prefix"}`: chunks picked at random (no query, no embedding) | `search:read` | A source answers `{"bucket", "name", "kind", "url", "every", "commits", "exclude", "collection", "fields", "filter", "path", "include", "pageURL", "hash", "status", "error", "documents", "chunks", "embedded", "bytes", "pending", "costMicroUSD", "refreshed", "next"}` (`embedded` below `chunks`: embedding under way; documents carry the same); `kind` is `file`, `text`, `folder`, `dir` (a server folder), `zip`, `page`, `git` or `collection`, `status` is `reading`, `ready` or `error`, and `hash` is a file's or zip's sha256, to spot an exact duplicate under another name. `replace` names an existing source the new one replaces under its new name. Search answers `{"results": [{"bucket", "source", "document", "text", "heading", "startLine", "endLine", "record", "url", "score"}], "model", "usage"}`; no buckets searches every bucket. `viewer` (`{"collection", "id"}`, or `{}` for a guest) leaves out records it can't view by the collection's view rule. Status answers `{"model", "chunks", "embedded", "note"}`: `embedded` below `chunks` means embedding is under way. Errors: `not_found` (no such bucket or source), `bad_request` (a bad name, URL, collection or field, an empty query, binary content), `too_large` (over the bucket's limits, a document over 10 MB, a zip over 100 MB), `not_configured` (no embedding model), and llm.embed/v1's errors from embedding the query. From Go: `searchv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/search/v1`), and `searchv1.Enrich(ctx, app, enrich, query)` for the passages a model call adds. ## Provide Implement `searchv1.Search` and provide it in `Register` (`searchv1.Contract.Provide(app, impl)`). Keep these promises: - `Ensure` is idempotent: an existing bucket keeps its settings; only an empty title, description or owner is filled in. - A source is identified by its name within its bucket; adding one of the same name (or naming it in `replace`) replaces it, leaving sources in other buckets alone. Unchanged documents cost nothing; documents the new version doesn't have go. - One embedding model for the app, so any buckets can be searched together; vectors from two models are never compared, a new model embeds every chunk again, and a chunk's content is embedded once however many sources hold it. - A collection source's documents follow its records: saved, filtered out, deleted. Pages and repositories with an interval are read again when it comes round; a server folder is read again every few minutes. - A server folder's path stays inside the app's own folder (the one holding `pb_data`) and never reaches `pb_data`, by the path or by a link. - A result's `url`, when set, is where the passage is published: a page's URL, or a server folder's `url` pattern with `{path}` filled in and the section's heading id as the anchor. - With a `viewer`, no result comes from a record the viewer can't view. - Results are chunks with their source, best first, at most `limit` (default 5, at most 50); `score` orders them. - Searching is the only operation that waits on a model; adding and reading sources return before embedding is done. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### status Is the app's embedding model and how far embedding has got across every bucket. | | | |---|---| | REST | `GET /api/_c/llm.search/v1/status` | | CLI | `pocketone remote llm search status` | | MCP | `llm_search_status` | | Token scope | `search:read` | ### set_model Changes the app's embedding model ("provider/model" from llm.embed/v1's models; "" picks one again). Every bucket is embedded again in the background; until a chunk is, keywords still find it. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/set-model` | | CLI | `pocketone remote llm search set-model --model ` | | MCP | `llm_search_set_model` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | ### buckets Lists the app's buckets with their counts. | | | |---|---| | REST | `GET /api/_c/llm.search/v1/buckets` | | CLI | `pocketone remote llm search buckets` | | MCP | `llm_search_buckets` | | Token scope | `search:read` | ### bucket Returns one bucket with its counts. | | | |---|---| | REST | `GET /api/_c/llm.search/v1/bucket` | | CLI | `pocketone remote llm search bucket --name ` | | MCP | `llm_search_bucket` | | Token scope | `search:read` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | ### ensure Makes a bucket if it's missing and returns it. An existing bucket keeps its settings, except that an empty title, description or owner is filled in. Apps call it at startup for the bucket they need. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/ensure` | | CLI | `pocketone remote llm search ensure --name --title --description --owner ` | | MCP | `llm_search_ensure` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | | `title` | `--title` | string | | `description` | `--description` | string | | `owner` | `--owner` | string | ### update Changes a bucket's title, description or limits (fields left out stay). | | | |---|---| | REST | `POST /api/_c/llm.search/v1/update` | | CLI | `pocketone remote llm search update --name --title --description --maxdocuments --maxbytes ` | | MCP | `llm_search_update` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | | `title` | `--title` | json | | `description` | `--description` | json | | `maxDocuments` | `--maxdocuments` | json | | `maxBytes` | `--maxbytes` | json | ### delete Removes a bucket and everything in it. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/delete` | | CLI | `pocketone remote llm search delete --name ` | | MCP | `llm_search_delete` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `name` | `--name` | string | ### sources Lists a bucket's sources, by name. | | | |---|---| | REST | `GET /api/_c/llm.search/v1/sources` | | CLI | `pocketone remote llm search sources --bucket ` | | MCP | `llm_search_sources` | | Token scope | `search:read` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | ### add Puts a file or pasted text in a bucket as its own source (one document), replacing the source of that name. The same text again costs nothing; changed text embeds only its new chunks. It returns at once; the document is embedded in the background (its status says how far it got). | | | |---|---| | REST | `POST /api/_c/llm.search/v1/add` | | CLI | `pocketone remote llm search add --bucket --name --text --kind --replace ` | | MCP | `llm_search_add` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `name` | `--name` | string | | `text` | `--text` | string | | `kind` | `--kind` | string | | `replace` | `--replace` | string | ### upload Adds a file sent as the request body: ?bucket=<name>&name=<file name>[&replace=<source>]. A .zip is one source with a document per text file inside it; anything else is a file source. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/upload` | | CLI | `pocketone remote llm search upload --file ` | | Token scope | `search` | | Body | the raw upload, not JSON | ### put Adds one file to a folder source (made on the first one), the way the dashboard sends a dropped folder; Prune ends it. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/put` | | CLI | `pocketone remote llm search put --bucket --source --path --text --replace ` | | MCP | `llm_search_put` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `source` | `--source` | string | | `path` | `--path` | string | | `text` | `--text` | string | | `replace` | `--replace` | string | ### prune Removes the documents of a folder source that aren't in Keep: the files the folder no longer has. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/prune` | | CLI | `pocketone remote llm search prune --bucket --source --keep ` | | MCP | `llm_search_prune` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `source` | `--source` | string | | `keep` | `--keep` | strings | ### add_u_r_l Adds a web page or a Git repository as a source (named by its URL, replacing one of that name) and reads it in the background; Every keeps it current. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/add-url` | | CLI | `pocketone remote llm search add-u-r-l --bucket --url --kind --every --commits --exclude ` | | MCP | `llm_search_add_u_r_l` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `url` | `--url` | string | | `kind` | `--kind` | string | | `every` | `--every` | string | | `commits` | `--commits` | int | | `exclude` | `--exclude` | strings | ### add_folder Adds a folder of the app's own files on the server (named by its path, replacing one of that name): every text file in it, read in the background and read again every few minutes, so changed files are embedded again and removed ones leave. With URL, each result from it links to the page that file is published at. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/add-folder` | | CLI | `pocketone remote llm search add-folder --bucket --path --include --exclude --url ` | | MCP | `llm_search_add_folder` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `path` | `--path` | string | | `include` | `--include` | strings | | `exclude` | `--exclude` | strings | | `url` | `--url` | string | ### detect_u_r_l Says how AddURL would read a URL: as a Git repository when its server answers the Git protocol (any host, with or without .git), otherwise as a web page. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/detect-url` | | CLI | `pocketone remote llm search detect-u-r-l --url ` | | MCP | `llm_search_detect_u_r_l` | | Token scope | `search:read` | | Input field | Flag | Type | |---|---|---| | `url` | `--url` | string | ### follow Adds one of the app's collections as a source (named by the collection): each record the filter keeps is a document, kept in sync as records are saved and deleted. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/follow` | | CLI | `pocketone remote llm search follow --bucket --collection --fields --filter ` | | MCP | `llm_search_follow` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `collection` | `--collection` | string | | `fields` | `--fields` | strings | | `filter` | `--filter` | string | ### refresh Reads a source again now: fetches a URL or repository, rereads a collection, resplits a file or zip. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/refresh` | | CLI | `pocketone remote llm search refresh --bucket --source ` | | MCP | `llm_search_refresh` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `source` | `--source` | string | ### remove Takes sources out of a bucket, with their documents. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/remove` | | CLI | `pocketone remote llm search remove --bucket --sources ` | | MCP | `llm_search_remove` | | Token scope | `search` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `sources` | `--sources` | strings | ### documents Lists a bucket's documents (or one source's), by source and name. | | | |---|---| | REST | `GET /api/_c/llm.search/v1/documents` | | CLI | `pocketone remote llm search documents --bucket --source --prefix ` | | MCP | `llm_search_documents` | | Token scope | `search:read` | | Input field | Flag | Type | |---|---|---| | `bucket` | `--bucket` | string | | `source` | `--source` | string | | `prefix` | `--prefix` | string | ### search Returns the chunks that best match a query across the buckets named, best first. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/search` | | CLI | `pocketone remote llm search --buckets --bucket --query --limit --prefix --viewer ` | | MCP | `llm_search_search` | | Token scope | `search:read` | | Input field | Flag | Type | |---|---|---| | `buckets` | `--buckets` | strings | | `bucket` | `--bucket` | string | | `query` | `--query` | string | | `limit` | `--limit` | int | | `prefix` | `--prefix` | string | | `viewer` | `--viewer` | json | ### sample Returns chunks picked at random from the buckets named: material to draw from ("surprise me", a topic nobody asked about), not matches. No query, no embedding, so it costs nothing. Like Search without a viewer, it may return any chunk, a followed record's included. | | | |---|---| | REST | `POST /api/_c/llm.search/v1/sample` | | CLI | `pocketone remote llm search sample --buckets --bucket --count --prefix ` | | MCP | `llm_search_sample` | | Token scope | `search:read` | | Input field | Flag | Type | |---|---|---| | `buckets` | `--buckets` | strings | | `bucket` | `--bucket` | string | | `count` | `--count` | int | | `prefix` | `--prefix` | string | ## Extensions | Extension | | |---|---| | [llm-search](https://pocketone.dev/docs/extensions/llm-search) | provides | | [llm-chat](https://pocketone.dev/docs/extensions/llm-chat) | works with | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.speech/v1 # llm.speech/v1 A model reads text aloud and returns the audio as a file. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.speech/v1` ([speech.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/speech/v1/speech.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.speech` (bound by the llm extension): ```js const r = await $llm.speech.speakAsync({ model: "vultr/qwen3-tts-12hz-1.7b", text: page, voice: "vivian", instructions: "slow and calm" }) record.set("narration", $llm.file(r.file)) await $llm.speech.voicesAsync("vultr/qwen3-tts-12hz-1.7b") // a voice cloned from a stored clip: leave voice and instructions out await $llm.speech.speakAsync({ model: "vultr/qwen3-tts-12hz-1.7b", text: page, reference: { audio: $llm.fromRecord(clip, "audio"), text: clip.getString("passage") } }) ``` **Voice cloning.** `reference` (`{audio: File, text}`) asks the model to read in the voice of that clip; `text` is what the clip says, optional but closer with it. A model clones when one of its voices has `mode: "clone"` (`voices`), and a provider that doesn't clone answers `not_supported`. Nothing is saved at the provider: the clip goes with every call. `instructions` can't go with a `reference`. Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Speak | `POST /api/_c/llm.speech/v1/speak` | `{"model": "...", "text": "...", "voice": "", "format": "mp3"}` | `llm` | | Voices | `POST /api/_c/llm.speech/v1/voices` | `{"model": "..."}` | `llm:read` | | Models | `GET /api/_c/llm.speech/v1/models` | `?provider=` (optional) | `llm:read` | `speak` answers `{"file": File, "model", "usage"}`; `voices` answers `{"voices": [{"id", "name", "language", "mode", "description"}]}` (empty when the provider doesn't list them; `mode` is `builtin`, `design` or `clone` when it says). Errors: `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `speechv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/speech/v1`). ## Provide Implement `speechv1.Speech` and provide it in `Register` (`speechv1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't do this kind, `unknown_model` for a missing model or provider (and for a `reference` on a provider that can't clone), and `provider` with the cloud's own message (never its key) when the cloud refuses. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### speak Reads the text aloud and returns the audio. | | | |---|---| | REST | `POST /api/_c/llm.speech/v1/speak` | | CLI | `pocketone remote llm speech speak --model --text --voice --format --speed --instructions --reference --options ` | | MCP | `llm_speech_speak` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `text` | `--text` | string | | `voice` | `--voice` | string | | `format` | `--format` | string | | `speed` | `--speed` | float | | `instructions` | `--instructions` | string | | `reference` | `--reference` | json | | `options` | `--options` | json | ### voices Lists a model's voices, when the provider says. | | | |---|---| | REST | `POST /api/_c/llm.speech/v1/voices` | | CLI | `pocketone remote llm speech voices --model ` | | MCP | `llm_speech_voices` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | ### models Lists the speech models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.speech/v1/models` | | CLI | `pocketone remote llm speech models --provider ` | | MCP | `llm_speech_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.text/v1 # llm.text/v1 A language model answers a prompt or a conversation, whole or as it's written. With a JSON schema the answer's parsed value comes back as `data`. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.text/v1` ([text.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/text/v1/text.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.text` (bound by the llm extension): ```js const r = await $llm.text.completeAsync({ model: "vultr/glm-5.2", system: "Label the ticket.", prompt: body, reasoning: "off", schema: { type: "object", properties: { label: { enum: ["bug", "billing", "question"] } }, required: ["label"] } }) r.data.label await $llm.text.streamAsync({ model: "vultr/glm-5.2", prompt: question }, (piece) => { /* show it */ }) ``` Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Complete | `POST /api/_c/llm.text/v1/complete` | `{"model": "vultr/glm-5.2", "prompt": "...", "maxTokens": 200}` | `llm` | | Stream | `POST /api/_c/llm.text/v1/stream` | as Complete; server-sent events | `llm` | | Count | `POST /api/_c/llm.text/v1/count` | `{"text": "..."}` or `{"system": "...", "messages": [...]}` | `llm:read` | | Models | `GET /api/_c/llm.text/v1/models` | `?provider=vultr` (optional) | `llm:read` | `complete` takes `prompt` or `messages` (`[{"role": "user", "content": "..."}]`), and optionally `system`, `schema`, `maxTokens`, `temperature`, `stop`, `reasoning` (`"off"`, `"low"`, `"medium"`, `"high"`; thinking counts toward `maxTokens`) and `options` (the provider's own fields). It answers `text`, `data`, `reasoning` (the model's thinking, when the provider returns it), `stopReason`, `model` and `usage`. `stream` sends one `event: stream` per piece, `{"text": "..."}` (or `{"reasoning": "..."}`), then `{"done": true, "result": {...}}`. `count` estimates at about four characters a token. Errors: `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `textv1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/text/v1`). ## Provide Implement `textv1.Text` and provide it in `Register` (`textv1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't do this kind, `unknown_model` for a missing model or provider, and `provider` with the cloud's own message (never its key) when the cloud refuses. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### complete Answers a prompt or a conversation. | | | |---|---| | REST | `POST /api/_c/llm.text/v1/complete` | | CLI | `pocketone remote llm text complete --model --system --prompt --messages --schema --maxtokens --temperature --stop --reasoning --options --enrich ` | | MCP | `llm_text_complete` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `system` | `--system` | string | | `prompt` | `--prompt` | string | | `messages` | `--messages` | json | | `schema` | `--schema` | json | | `maxTokens` | `--maxtokens` | int | | `temperature` | `--temperature` | json | | `stop` | `--stop` | strings | | `reasoning` | `--reasoning` | string | | `options` | `--options` | json | | `enrich` | `--enrich` | json | ### stream Answers like Complete, sending the answer as it's written: a chunk with text (or reasoning) for each piece, then one with done and the whole result. | | | |---|---| | REST | `POST /api/_c/llm.text/v1/stream` | | CLI | `pocketone remote llm text stream --model --system --prompt --messages --schema --maxtokens --temperature --stop --reasoning --options --enrich ` | | MCP | `llm_text_stream` | | Token scope | `llm` | | Answer | a stream of JSON entries (server-sent events); the command prints one line each | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `system` | `--system` | string | | `prompt` | `--prompt` | string | | `messages` | `--messages` | json | | `schema` | `--schema` | json | | `maxTokens` | `--maxtokens` | int | | `temperature` | `--temperature` | json | | `stop` | `--stop` | strings | | `reasoning` | `--reasoning` | string | | `options` | `--options` | json | | `enrich` | `--enrich` | json | ### count Says about how many tokens a text or a conversation is, for budgeting what to send. | | | |---|---| | REST | `POST /api/_c/llm.text/v1/count` | | CLI | `pocketone remote llm text count --model --text --system --messages ` | | MCP | `llm_text_count` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `text` | `--text` | string | | `system` | `--system` | string | | `messages` | `--messages` | json | ### models Lists the text models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.text/v1/models` | | CLI | `pocketone remote llm text models --provider ` | | MCP | `llm_text_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | | [llm-chat](https://pocketone.dev/docs/extensions/llm-chat) | requires | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.transcribe/v1 # llm.transcribe/v1 A model writes down what's said in audio. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.transcribe/v1` ([transcribe.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/transcribe/v1/transcribe.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.transcribe` (bound by the llm extension): ```js const r = await $llm.transcribe.transcribeAsync({ model: "vultr/whisper-large-v3-turbo", audio: { name: "memo.mp3", data: base64Audio } }) r.text ``` Over HTTP (a superuser, or a token with the scope shown): | Operation | HTTP | Body | Token scope | |---|---|---|---| | Transcribe | `POST /api/_c/llm.transcribe/v1/transcribe` | `{"model": "...", "audio": {"name": "memo.mp3", "data": ""}, "language": "en"}` | `llm` | | Models | `GET /api/_c/llm.transcribe/v1/models` | `?provider=` (optional) | `llm:read` | It answers `{"text", "language", "model", "usage"}`. The audio's name (or type) tells the provider its format. Errors: `not_configured` (no providers), `unknown_model`, `not_supported`, `provider` (the cloud's own error), `timeout`. From Go: `transcribev1.Contract.Must(app)` (from `pocketone.dev/ext/contracts/llm/transcribe/v1`). ## Provide Implement `transcribev1.Transcribe` and provide it in `Register` (`transcribev1.Contract.Provide(app, impl)`). Route on the `provider/` prefix, answer `not_supported` for a provider that can't do this kind, `unknown_model` for a missing model or provider, and `provider` with the cloud's own message (never its key) when the cloud refuses. Fill `model` with the full `provider/model` that answered, and `usage` with what the provider reports. ## Commands and APIs Every operation is a REST endpoint, a `pocketone` command and an MCP tool, all generated from the contract and behind the same token scope check and hooks. See [Remote CLI](https://pocketone.dev/docs/features/remote), or the full [CLI](https://pocketone.dev/docs/reference/cli), [Extension APIs](https://pocketone.dev/docs/extensions/apis) and [MCP](https://pocketone.dev/docs/reference/mcp) references. ### transcribe Writes down what's said in the audio. | | | |---|---| | REST | `POST /api/_c/llm.transcribe/v1/transcribe` | | CLI | `pocketone remote llm transcribe --model --audio --language --prompt --options ` | | MCP | `llm_transcribe_transcribe` | | Token scope | `llm` | | Input field | Flag | Type | |---|---|---| | `model` | `--model` | string | | `audio` | `--audio` | json | | `language` | `--language` | string | | `prompt` | `--prompt` | string | | `options` | `--options` | json | ### models Lists the transcription models of every provider in Settings → LLM. | | | |---|---| | REST | `GET /api/_c/llm.transcribe/v1/models` | | CLI | `pocketone remote llm transcribe models --provider ` | | MCP | `llm_transcribe_models` | | Token scope | `llm:read` | | Input field | Flag | Type | |---|---|---| | `provider` | `--provider` | string | ## Extensions | Extension | | |---|---| | [llm](https://pocketone.dev/docs/extensions/llm/extension) | provides | ## License MIT --- Source: https://pocketone.dev/docs/contracts/llm.video/v1 # llm.video/v1 A model makes a video from a prompt (and a first frame). Like music, it's a job. Every call names its model as `provider/model`: a provider the app's admins added in Settings → LLM, a slash, and that provider's own id for the model. Shared types (`File`, `Usage`, `ModelInfo`, `Job`, the errors) are in [`pocketone.dev/ext/contracts/llm`](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/llm.go). A wire contract at `/api/_c/llm.video/v1` ([video.go](https://github.com/pocketonehq/pocketone/blob/main/ext/contracts/llm/video/v1/video.go)), one provider. The [llm](https://pocketone.dev/docs/extensions/llm/extension) extension provides it, over Vultr, Cloudflare Workers AI, OpenRouter and any OpenAI-compatible API. ## Use In page code it's `$llm.video` (bound by the llm extension): ```js const job = await $llm.video.createAsync({ model: "vultr/