@protobase/cli 0.22.12 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +2 -0
- package/dist/package.js +1 -1
- package/dist/skill/install.js +29 -0
- package/dist/skill/register.js +14 -0
- package/package.json +8 -7
- package/skills/protobase/SKILL.md +89 -0
- package/skills/protobase/references/getting-started.md +78 -0
- package/skills/protobase/references/guides/api-functions.md +240 -0
- package/skills/protobase/references/guides/billing-page.md +288 -0
- package/skills/protobase/references/guides/create-page.md +108 -0
- package/skills/protobase/references/guides/deploy.md +52 -0
- package/skills/protobase/references/guides/export-a-list.md +44 -0
- package/skills/protobase/references/guides/field-type.md +131 -0
- package/skills/protobase/references/guides/first-composed-page.md +230 -0
- package/skills/protobase/references/guides/first-plugin.md +166 -0
- package/skills/protobase/references/guides/import-records.md +43 -0
- package/skills/protobase/references/guides/plugin-build.md +64 -0
- package/skills/protobase/references/guides/record-card.md +70 -0
- package/skills/protobase/references/guides/remote-resources.md +185 -0
- package/skills/protobase/references/guides/table-to-admin.md +205 -0
- package/skills/protobase/references/guides/theme-an-app.md +87 -0
- package/skills/protobase/references/reference/access.md +115 -0
- package/skills/protobase/references/reference/ai.md +106 -0
- package/skills/protobase/references/reference/api.md +231 -0
- package/skills/protobase/references/reference/architecture.md +63 -0
- package/skills/protobase/references/reference/assistant.md +157 -0
- package/skills/protobase/references/reference/auth.md +462 -0
- package/skills/protobase/references/reference/blocks.md +341 -0
- package/skills/protobase/references/reference/bottom-bar.md +44 -0
- package/skills/protobase/references/reference/cli.md +493 -0
- package/skills/protobase/references/reference/client.md +38 -0
- package/skills/protobase/references/reference/comments.md +83 -0
- package/skills/protobase/references/reference/custom-components.md +285 -0
- package/skills/protobase/references/reference/data-config.md +266 -0
- package/skills/protobase/references/reference/email.md +166 -0
- package/skills/protobase/references/reference/events.md +121 -0
- package/skills/protobase/references/reference/files.md +291 -0
- package/skills/protobase/references/reference/forms.md +133 -0
- package/skills/protobase/references/reference/history.md +86 -0
- package/skills/protobase/references/reference/jobs.md +174 -0
- package/skills/protobase/references/reference/layouts.md +126 -0
- package/skills/protobase/references/reference/plugins.md +328 -0
- package/skills/protobase/references/reference/remote-resources.md +198 -0
- package/skills/protobase/references/reference/sidebar.md +51 -0
- package/skills/protobase/references/reference/theme.md +132 -0
- package/skills/protobase/references/reference/ui-config.md +880 -0
- package/skills/protobase/references/reference/user-menu.md +38 -0
- package/skills/protobase/references/reference/versioning.md +91 -0
- package/skills/protobase/references/reference/webhooks.md +136 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/ai.mdx: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# AI fields and actions
|
|
4
|
+
|
|
5
|
+
Fields a model fills from a prompt after each write, and buttons that have the model write a field of the record, as the user, on the assistant's model settings.
|
|
6
|
+
|
|
7
|
+
A model can write fields of a record for the people using the app, in two ways:
|
|
8
|
+
|
|
9
|
+
- An **AI field**, `.ai({ prompt })`, is filled by a job after a create, and again after an update that changes a field its prompt reads.
|
|
10
|
+
- An **AI action**, `a.ai(name, { label, prompt, writes })`, is a button in the record's action rail that has the model write the field `writes` now.
|
|
11
|
+
|
|
12
|
+
Both write through the API as the user who wrote or clicked, so their access rules, validation and write hooks apply, and the value lands in a field the user can see. Nothing is written anywhere else.
|
|
13
|
+
|
|
14
|
+
```ts title="config/tickets.ts"
|
|
15
|
+
import { f, l, resource, view } from '@protobase/schema'
|
|
16
|
+
|
|
17
|
+
// A helpdesk's tickets: a job sums each one up after it is written, and agents ask the model for a priority or a translation.
|
|
18
|
+
|
|
19
|
+
/** support.tickets */
|
|
20
|
+
export const tickets = resource('tickets')
|
|
21
|
+
.table('support.tickets')
|
|
22
|
+
.fields({
|
|
23
|
+
id: f.integer().readOnly().filterable().sortable(),
|
|
24
|
+
title: f.text(),
|
|
25
|
+
description: f.text().optional(),
|
|
26
|
+
priority: f.enum(['low', 'normal', 'urgent']).optional(),
|
|
27
|
+
// empty until the job fills it, after a create and after a change of the title or description
|
|
28
|
+
summary: f.text().optional().ai({ prompt: 'Summarise this support ticket in one sentence.\n\nTitle: {title}\n\n{description}' }),
|
|
29
|
+
})
|
|
30
|
+
.primaryKey((r) => r.id)
|
|
31
|
+
|
|
32
|
+
export const ticketsView = view<typeof tickets>('tickets')
|
|
33
|
+
.names({ singular: 'Ticket', plural: 'Tickets' })
|
|
34
|
+
.title((r) => r.title)
|
|
35
|
+
.layout((r) => [l.section('Ticket', [r.title, r.description, r.priority, r.summary])])
|
|
36
|
+
.actions((a) => [
|
|
37
|
+
a.ai('translate', { label: 'Translate to English', icon: 'file-text', prompt: 'Translate into English:\n\n{description}', writes: 'description' }),
|
|
38
|
+
a.ai('triage', { label: 'Suggest priority', icon: 'tag', prompt: 'How urgent is this support ticket?\n\n{title}\n{description}', writes: 'priority', confirm: 'Replace the priority?' }),
|
|
39
|
+
])
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```ts title="protobase.config.ts"
|
|
43
|
+
import { defineConfig } from '@protobase/server'
|
|
44
|
+
import * as config from './tickets'
|
|
45
|
+
|
|
46
|
+
// The model comes from PROTOBASE_ASSISTANT_API_KEY; the summaries are filled by the app's workers.
|
|
47
|
+
export default defineConfig({ config })
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Prompts
|
|
51
|
+
|
|
52
|
+
A prompt names fields of the record as `{field}`, at least one. The model gets a fixed instruction to answer with the value only, and the prompt with each `{field}` replaced by the record's value as text: text as it is, numbers and booleans written out, json as JSON, an empty value as nothing. For an enum field, the prompt ends with the values the answer must be one of. Nothing else of the record or the app is sent. The answer is trimmed, and validated as any write is, so an enum value the field does not have, or text over its `.max()`, is refused.
|
|
53
|
+
|
|
54
|
+
When every field the prompt reads is empty, the model is not asked: an AI field is cleared to `null` and an AI action answers `422`. A summary of nothing is never invented.
|
|
55
|
+
|
|
56
|
+
## AI fields
|
|
57
|
+
|
|
58
|
+
An AI field is `f.text()` or `f.enum()`, `.optional()` (it is empty until the job fills it), not `.readOnly()` (the job writes it through the API) and not `.sensitive()`. Its prompt reads fields of the same resource that are neither sensitive, nor the field itself, nor another AI field, so one fill never sets off another. A config that breaks one of these does not load.
|
|
59
|
+
|
|
60
|
+
The job `ai.fill` fills it:
|
|
61
|
+
|
|
62
|
+
- after a create, when the field is empty and a field the prompt reads holds something;
|
|
63
|
+
- after an update that changes a field the prompt reads, unless the same write changed the AI field itself: a person's own edit wins, and the job's own write never sets off another;
|
|
64
|
+
- as the user who wrote, with the roles they had then, in their tenant; a writer who may not update the AI field, or read the fields its prompt reads, gets no fill, and neither does a visitor sending a [public form](forms.md)).
|
|
65
|
+
|
|
66
|
+
Quick edits in a row leave one waiting job per record and field, with the latest writer. When a field the prompt reads changes while the model answers, the job writes nothing and the newer job fills it; a record deleted since is skipped. A model that fails is retried, up to five tries, the first retry after 30 seconds and each later one twice as long; then the job shows on the [failed jobs page](jobs.md#failed-jobs-page)). Four fills run at once per worker.
|
|
67
|
+
|
|
68
|
+
Only writes through the API fill a field: a row written with SQL, or an import that goes around the API, gets no fill.
|
|
69
|
+
|
|
70
|
+
## AI actions
|
|
71
|
+
|
|
72
|
+
`a.ai(name, { label, prompt, writes, icon?, confirm? })` names an action of the view, shown in the record page's action rail and runnable from a composed page's `<Action name="..." />` like any [named action](layouts.md#named-actions)). `writes` is a text or enum field of the resource that is not read-only, and the prompt may read that field too, to rewrite or translate it in place. With `confirm` the button asks first. While the model answers the button shows that it is busy; then the record reloads and a toast says it is done, or why it failed.
|
|
73
|
+
|
|
74
|
+
Who may run one:
|
|
75
|
+
|
|
76
|
+
- a signed-in user; a visitor never spends model calls;
|
|
77
|
+
- whose view of the resource has the action, so [views per role](ui-config.md#actions-and-views-per-role)) decide who has which;
|
|
78
|
+
- who may read the fields the prompt reads, and update the field it writes on this record; otherwise the button is not offered or is disabled.
|
|
79
|
+
|
|
80
|
+
`/api/meta` sends the action without its prompt, which stays on the server.
|
|
81
|
+
|
|
82
|
+
The action runs at `POST /api/v1/{resource}/{key}:generate` with `{ "action": "<name>" }` (the client's `generate(resource, key, action)`), and answers the record as an update does. The record is read, the model answers, and the field is written with the ETag that was read, so an edit made while the model answered is not overwritten: the action answers `412` and writes nothing. Its problems:
|
|
83
|
+
|
|
84
|
+
| Status | Type | When |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `400` | `invalid-action` | The body names no action. |
|
|
87
|
+
| `403` | `ai-needs-user` | The caller is not signed in. |
|
|
88
|
+
| `404` | `not-found` | The caller's view has no AI action of that name, or there is no such record. |
|
|
89
|
+
| `403` | `ai-forbidden` | The caller may not read a field the prompt reads, or update the field it writes. |
|
|
90
|
+
| `422` | `ai-no-value` | Every field the prompt reads is empty, or the model answered nothing. |
|
|
91
|
+
| `502` | `ai-unavailable` | The model failed or took more than 60 seconds. The user sees only that; the endpoint's message goes to the app's error reporting (`onUnhandledError`). |
|
|
92
|
+
| `503` | `ai-not-configured` | No model is set; startup normally catches this first. |
|
|
93
|
+
|
|
94
|
+
Every check is made before the model is asked.
|
|
95
|
+
|
|
96
|
+
## The model
|
|
97
|
+
|
|
98
|
+
AI fields and actions use the [assistant's model settings](assistant.md#which-backend)): `PROTOBASE_ASSISTANT_API_KEY`, with `PROTOBASE_ASSISTANT_BASE_URL` and `PROTOBASE_ASSISTANT_MODEL`, or the same keys of `options.assistant`. They use them also when `PROTOBASE_ASSISTANT_URL` names a chat backend elsewhere, which replaces the chat, not the model, and when `options.assistant` is `false`, which turns off the chat only. On OpenRouter they ask for little reasoning.
|
|
99
|
+
|
|
100
|
+
`protobase dev` and `protobase serve` do not start when a resource has an AI field or a view an AI action and no key is set; `PROTOBASE_STARTUP_CHECKS=false` skips that check, as it does the others. Other commands, such as `protobase migration`, run without a key.
|
|
101
|
+
|
|
102
|
+
Every click and every write that calls for a fill is one model call on that key, paid to its provider.
|
|
103
|
+
|
|
104
|
+
## The jobs schema
|
|
105
|
+
|
|
106
|
+
AI fields are filled by jobs, so a project with one needs the [`jobs` schema](jobs.md#the-jobs-schema)), which [`protobase migration`](cli.md#migration)) writes, and the app's workers. AI actions run in the request and need neither.
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/api.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# REST API
|
|
4
|
+
|
|
5
|
+
The REST API that @protobase/server generates, with its routes, access, filters, writes, batches and errors.
|
|
6
|
+
|
|
7
|
+
`@protobase/server` turns resource definitions into a Hono app that follows Google's API design conventions ([AIP-131 to 136](https://google.aip.dev/131), [158](https://google.aip.dev/158), [160](https://google.aip.dev/160)). It uses Web APIs only and runs on Node and Workers; the Node adapter lives in the example.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { configExports, createAdmin } from '@protobase/server'
|
|
11
|
+
import { auth, authenticate } from './auth/auth' // Better Auth, see /reference/auth/
|
|
12
|
+
import * as config from './config'
|
|
13
|
+
|
|
14
|
+
const { resources, views } = configExports(config) // splits a config's index.ts exports
|
|
15
|
+
const admin = createAdmin({
|
|
16
|
+
resources,
|
|
17
|
+
views, // optional, served by /meta
|
|
18
|
+
db, // Kysely<any> on Postgres
|
|
19
|
+
authenticate, // required: no development mode; anonymous only with that role
|
|
20
|
+
auth, // optional: mounts login at /api/auth/*
|
|
21
|
+
functions, // optional: your own endpoints at /api/functions/<name>, see /guides/api-functions/
|
|
22
|
+
options: { statementTimeoutMs: 15_000, scanGuard: { mode: 'reject' } },
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Run the ERP example with `bun run --cwd examples/erp serve` (port 8787, Better Auth login, organization 1 as tenant; `REQUEST_LOG=true` logs requests). Interactive reference: `/api/docs`; like `/api/openapi.json` it needs a bearer token, because the document lists what the caller may see and do. Every route answers `401` without a valid token; get one with `protobase token you@example.com`. A project whose roles define [`anonymous`](access.md#anonymous-access)) serves the resources API to requests without a token as that role.
|
|
27
|
+
|
|
28
|
+
## Routes
|
|
29
|
+
|
|
30
|
+
`/api/v1/*` is resources only, so a table may be called `meta` or `docs`. The system endpoints (`/api/meta`, `/api/openapi.json`, `/api/docs`), the app's own [API functions](../guides/api-functions.md)) (`/api/functions/<name>`), [file downloads](files.md#downloads)) (`/api/files/<provider>/<path>`), [public forms](forms.md#routes)) (`/api/forms/<name>`) and login (`/api/auth/*`) live beside it; the parent of `options.basePath` is where the system endpoints go.
|
|
31
|
+
|
|
32
|
+
Under `/api/v1`:
|
|
33
|
+
|
|
34
|
+
| Route | |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| `GET /{resource}` | list: `filter`, `order_by`, `page_size` (50, max 500), `page_token`, `fields`, `labels`, `photos`, `photos_order_by`, `count=exact` |
|
|
37
|
+
| `POST /{resource}:search` | same parameters as a JSON body (`fields` and `labels` arrays), for long filters |
|
|
38
|
+
| `GET /{resource}/{key}` | one record, with `ETag`; composite keys are `part,part`, each part percent-encoded |
|
|
39
|
+
| `POST /{resource}` | create, `201` with `Location` and `ETag` |
|
|
40
|
+
| `PATCH /{resource}/{key}` | partial update, `If-Match` required |
|
|
41
|
+
| `DELETE /{resource}/{key}` | soft delete when the resource has one ([AIP-135](https://google.aip.dev/135)); `If-Match` optional |
|
|
42
|
+
| `POST /{resource}:upload?field=&name=` | one file for a [file field](files.md#uploading)), as the raw body or one multipart file part; `201 { value, file, derived, corrected? }`, where `value` is the ticket a write sends as the field's value; `413` over the field's `maxSize`, `415` for a type it does not take |
|
|
43
|
+
| `POST /{resource}/{key}:reveal` | `{ "field": "iban" }` gives `{ field, value }` of one [sensitive field](#sensitive-fields-and-audit), with `Cache-Control: no-store`, and publishes an audit event |
|
|
44
|
+
| `GET /{resource}/{key}:history` | the record's changes, newest first, for a resource with [history](history.md)): `page_size` (20, max 100), `page_token`; see [Record history](#record-history) |
|
|
45
|
+
| `GET`, `POST /{resource}/{key}:comments`, `GET /{resource}/{key}:mentionable?q=` | the record's comments, newest first, adding one, and whom it may mention, for a resource with [comments](comments.md)); see [Record comments](#record-comments) |
|
|
46
|
+
| `POST /{resource}/{key}:generate` | `{ "action": "<name>" }` runs an [AI action](ai.md#ai-actions)) of the caller's view: the model writes its field, with the ETag the record was read with, and it answers the record as an update does |
|
|
47
|
+
| `POST /{resource}/{key}:undelete` | restores a soft-deleted record ([AIP-164](https://google.aip.dev/164)); `If-Match` optional; `409` when not deleted, `400` on hard-delete resources |
|
|
48
|
+
| `POST /api/v1:batchWrite` | many writes in one transaction, see [Batch writes](#batch-writes) |
|
|
49
|
+
| `GET /{resource}:facets?field=&filter=&limit=&label=` | `{ field, facets: [{ value, count }] }`, the `limit` most frequent values (100 by default, at most 1,000), never all of them; with `label`, a relation's facets carry the related record's name as `label`, as in [Related names](#related-names) |
|
|
50
|
+
| `GET /{resource}:aggregate?group_by=&sum=&average=&filter=` | `{ group_by, groups: [{ value, count, sum }] }`: the records the whole filter finds, per value of `group_by`, each with its count and, with `sum` or `average` (one of the two), that of a numeric field, `null` when no record of the group has one. Values come largest first, the first `limit` (100 by default, at most 1,000), with `label` as in `:facets`. A date or timestamp `group_by` is bucketed like `:series` instead (`granularity` `hour` to `year`, `range` or `from` and `to`, `time_zone`), empty buckets included, and each `value` is the bucket's start; the response adds `granularity` and `time_zone`. With `split_by` (a filterable field of values), a date `group_by` also splits each bucket: the response adds `split_by` and `splits` (the `split_limit` largest values over the range, 8 by default and at most 100, ranked by the sum, else by count; `split_label` names a relation's values), and each group lists its `splits` with their count and sum or average. Unlike `:facets`, the filter's terms on `group_by` apply too, so the groups add up to what the filter finds |
|
|
51
|
+
| `GET /{resource}:series?field=&range=&granularity=&time_zone=&filter=` | `range` is `7d`, `30d`, `90d`, `1y`, `all`, or `from` and `to` (ISO) |
|
|
52
|
+
| `GET /{resource}:histogram?field=&buckets=&filter=` | equal-width buckets of a numeric field |
|
|
53
|
+
| `GET /{resource}:map?latitude=&longitude=&zoom=&filter=&order_by=&fields=&labels=&photos=&photos_order_by=` | the records in a map's view, the bounding box being in `filter` (`lat >= 51.9 AND lat <= 52.1 AND lng >= 4.2 AND lng <= 4.5`), as `{ items, buckets, total_size }`; see [Maps](#maps) |
|
|
54
|
+
| `GET /{resource}:seek?position=&order_by=&filter=&page_size=&fields=&labels=&photos=&photos_order_by=` | the page at a row position (scrollbar jumps), with `next_page_token` and `prev_page_token`; same items as a list |
|
|
55
|
+
| `GET /api/meta` | resource, view and page models (fields carry `default`: `{ value }` or `{ db: true }`) and the caller's `permissions`; the `ETag` hashes both, so it differs per user; `If-None-Match` gives `304` |
|
|
56
|
+
| `POST /api/files:cleanup` | runs the [scheduled file deletes](files.md#deleting-files)) that are due, for an admin; `{ deleted, kept }` |
|
|
57
|
+
| `GET /api/openapi.json`, `GET /api/docs` | OpenAPI 3.1 for the caller (only the resources, fields and operations their roles allow), and the Scalar reference |
|
|
58
|
+
|
|
59
|
+
Every response carries `X-Meta-Version`, the hash of the models and of the caller's roles; a client that sees it change (a model edit, a role change) refetches `/meta`.
|
|
60
|
+
|
|
61
|
+
`show_deleted=true` on list, `:search` (body) and get also returns soft-deleted records (soft-delete resources only, `400` otherwise).
|
|
62
|
+
|
|
63
|
+
A list returns `{ items, next_page_token, total_size_estimate }`, the estimate being the planner's, which reads no rows. `count=exact` adds `total_size`, counted through the indexes but no further than 10,000 matches: above that `total_size` is left out and the estimate stands. `next_page_token` is `""` on the last page, and a token only continues the `filter` and `order_by` it came from: with others the request fails with `400 invalid-cursor`. Items use field names, dates as ISO 8601 text, 64-bit integers and decimals as strings.
|
|
64
|
+
|
|
65
|
+
### Record history
|
|
66
|
+
|
|
67
|
+
`GET /{resource}/{key}:history` answers `{ items, next_page_token }` for a resource with `.history()`, and `404` for one without. It needs what a get needs, a soft-deleted record included. Each item is `{ id, at, operation, changed, before?, after?, actor, database_role }`: `before` and `after` hold only the fields the caller may read, never a sensitive or file field, `changed` names the changed fields the caller may read, and an update of only other fields is left out. `actor` is `{ id, name? }` for a write through the API, the name when the project's Better Auth knows the user, and `null` otherwise; `database_role` is the role that wrote. See [Record history](history.md)).
|
|
68
|
+
|
|
69
|
+
### Record comments
|
|
70
|
+
|
|
71
|
+
For a resource with `.comments()`, and `404` for one without; each needs what a get needs. `GET /{resource}/{key}:comments` answers `{ items, next_page_token }`, newest first, a soft-deleted record included, with `page_size` (20, max 100) and `page_token`. Each item is `{ id, created_at, body, author, mentions }`, where `author` and each of `mentions` is `{ id, name? }`, the name when the project's Better Auth knows the user. `POST` with `{ "body": "...", "mentions": ["<user id>"] }` adds the caller's comment to a record that is not deleted and answers `201` with it: `body` is trimmed, `mentions` names at most 20 users, the caller dropped, and each is emailed. `GET /{resource}/{key}:mentionable?q=` answers `{ items: [{ id, name }] }`: at most 8 users whose name contains `q`, by name, who may read the record, without the caller. Its problems: `403 comment-needs-user` to a caller who is not signed in, on the `POST` and on `:mentionable`; `400 invalid-comment` for an empty body or one over 10,000 characters; `400 invalid-mention` for a mention of someone who may not read the record, which keeps nothing. See [Record comments](comments.md)).
|
|
72
|
+
|
|
73
|
+
### Related names
|
|
74
|
+
|
|
75
|
+
A list holds a relation as the key of the record it points at. `labels` names those records in the same answer: `labels=place_id.name,agency_id.name` on a list, `:search`, `:seek` or `:map` adds `labels: { "place_id": { "12": "Amsterdam" }, "agency_id": { ... } }`, the `name` of each place and agency the page's items point at, by key as text. Each entry is a relation among the returned fields, to a resource with a single-field key, and the field of that resource that names its records, neither a file nor JSON; anything else is a `400`. The related records are read as the caller lists that resource, in one query per relation: its tenant, row filter, soft delete and readable fields apply. A record they cannot list, or whose field they cannot read, is not in `labels`, and neither is an empty name, so it goes by its key; a field they cannot read or that does not exist answers the same, so `labels` never tells it exists.
|
|
76
|
+
|
|
77
|
+
### Card photos
|
|
78
|
+
|
|
79
|
+
A list can bring each record's first photos in the same answer, as a cards display's [`photos`](ui-config.md#card-photos)) shows them: `photos=listing_photos.listing_id.photo&photos_order_by=position` on a list, `:search`, `:seek` or `:map` adds `photos: { "12": [{ "uri": "public:…", "url": "…", "placeholder": "…" }, …] }`, the `photo` files of the first ten records of `listing_photos` whose relation `listing_id` points at each item, by its key as text, in `photos_order_by` order (their primary key breaking ties). An item without photos is not in `photos`. The entry names a resource, its relation to the listed one and its file field; a malformed entry, or `photos_order_by` without it, is a `400`.
|
|
80
|
+
|
|
81
|
+
The photos are read as the caller lists that resource, in one query for the whole page: its tenant, row filter, soft delete and readable fields apply, each file comes as that resource's list returns it, with its placeholder when the caller may read that field, and the [scan guard](#safety) checks the lookup like a list. A caller who cannot list the resource, or read and use the relation, the file field or the sorted fields, gets `photos: {}`, as they would for a resource or field that does not exist, so `photos` never tells it exists; so does a list of a resource with a composite key.
|
|
82
|
+
|
|
83
|
+
### Maps
|
|
84
|
+
|
|
85
|
+
`:map` answers a map of a resource's records at their position, two filterable number fields in decimal degrees (`latitude` and `longitude` name them) and MapLibre's `zoom`, a whole number from 0 to 22. The map's bounding box is part of the AIP-160 `filter`, with the list's own filter: `(rooms >= 3) AND lat >= 51.9 AND lat <= 52.1 AND lng >= 4.2 AND lng <= 4.5`, or `(lng >= 170 OR lng <= -170)` across the antimeridian. When up to 200 records match, or from zoom 16 on, `items` holds them (at most 200, in `order_by` order) as a list returns them, and `buckets` is empty. Otherwise `buckets` counts them per cell of a grid about 64 pixels across at the zoom, square on a Web Mercator map and fixed as it pans, the fullest 1,000 cells, each as `{ count, latitude, longitude, bounds: { south, west, north, east } }`: the records' mean position and the bounds around them, which a map zooms to when the bucket is chosen. `items` is then empty, and records without a position are in no bucket. `total_size` counts the matches either way, up to 10,000 when `items` holds them, as `count=exact` does, the planner's estimate above that. Postgres counts and groups the records, so an index on the position serves the bounding box.
|
|
86
|
+
|
|
87
|
+
## Access
|
|
88
|
+
|
|
89
|
+
Access is resolved once per request and resource ([`resolveAccess`](https://docs.protobase.net/api/schema/functions/resolveaccess/)), see [Login with Better Auth](auth.md)) for roles and capabilities), and everything downstream uses the result:
|
|
90
|
+
|
|
91
|
+
- **Operations**: a denied operation is `403`; a resource the caller can do nothing with does not exist for them (`404` everywhere, absent from `/meta` and the OpenAPI document).
|
|
92
|
+
- **Readable fields**: the caller works with a restricted model that has only the fields they may read. `filter`, `order_by`, `fields`, `search(...)`, `:facets`, `:aggregate`, `:histogram`, `:series`, `:map`, `:seek` and `:search` bodies are checked against it, so a hidden field is refused exactly like an unknown one (same status, same message and hint, nothing that says it exists). List, get, create, update and delete responses contain readable fields only, and queries select only those columns.
|
|
93
|
+
- **Sensitive fields** are readable fields that no response carries and no request may name, except `:reveal`; they can be written. See [Sensitive fields and audit](#sensitive-fields-and-audit).
|
|
94
|
+
- **Writable fields**: only fields the caller may write (and read) are accepted; any other is `400`, worded as unknown (hidden) or read-only. Nobody writes a field blind.
|
|
95
|
+
- **Row filters**: a rule that returns a filter (`.own`, `.team`) narrows every read (list, get, aggregates) and the rows a write may target; the database applies it, so it may use columns the caller cannot see. A row outside it is a `404`.
|
|
96
|
+
- **Record-level rules** (a rule that needs the record, such as `status != 'locked'`) run in the write transaction with the stored record; a filter they return is checked in the database against the row as written, and a miss rolls the write back with `403`.
|
|
97
|
+
- **`.own` on create**: when the create rule is limited to rows, the owner field is set to the caller unless given, and a row owned by someone else is refused with `403`.
|
|
98
|
+
- **Seeking**: `:seek` resolves a row position to a page on the server, inside the caller's tenant, row filter and filter. No anchor value, column statistic or boundary token is ever returned (table-wide statistics include rows the caller may not see), only the page and the tokens of its own rows.
|
|
99
|
+
- **ETags**: with a read-only `version` or `updated_at` column the ETag is a hash of that column's exact text, so it never shows a hidden value yet moves on every change. Without one it is a hash of the fields the caller may read, sensitive ones excluded: a change to a field they cannot read, or to a sensitive field, does not change their ETag.
|
|
100
|
+
- **Errors** never contain values of fields the caller cannot read; database errors leave out constraint and column names.
|
|
101
|
+
|
|
102
|
+
`options.roles` (from `defineRoles`) makes an operation without an explicit rule need the matching capability (`orders.update`), and limits each role to the [fields and rows](access.md#capabilities)) its capabilities list; `options.defaultAccess: 'allow' | 'deny'` overrides the capability check. Without either, operations without a rule are allowed (single-admin projects).
|
|
103
|
+
|
|
104
|
+
### Record permissions
|
|
105
|
+
|
|
106
|
+
Get responses carry `permissions: { update, delete, fields }`, where `fields` maps each readable field to `edit` or `read` for this record (hidden fields are not listed). List items carry `permissions: { update, delete }` too, decided in the database in one extra query per page; turn it off for a resource with `options.rowPermissions: { except: ['resource'] }` (or `false` for all). They only inform the UI: every write is checked again. A resource cannot have a field named `permissions` or `etag`.
|
|
107
|
+
|
|
108
|
+
### `/meta` and OpenAPI per caller
|
|
109
|
+
|
|
110
|
+
`/meta` returns, per caller: the resources they can do anything with as restricted models (hidden fields absent, `readOnly` unless writable), the view for their roles ([`pickView`](https://docs.protobase.net/api/schema/functions/pickview/))) with every reference to a hidden field removed (columns, sort, search, filters, layout, chart, title, search result) and the [related sections](ui-config.md#related-records)) they cannot use, `permissions[resource]` as `{ read, create, update, delete, conditional }`, the [user menu](user-menu.md)) as `userMenu` and the [bottom bar](bottom-bar.md)) of their active role as `bottomBar`, each without the resources and pages they cannot see, and the [composed pages](layouts.md#access)) as `pages`, each without the elements that name what they cannot see or do, and, for a caller with the `admin` or `ai` role, the [assistant](assistant.md#who-sees-it)) backend as `assistant: { url }` when the app has one, and, for a caller with the `admin` role, the [runtime updates](versioning.md#runtime-updates)) endpoint as `runtime: { url }` when the app has one, and, for everyone, the style of the record page's [maps](ui-config.md#maps)) as `maps: { style }` when the app has one. `conditional` lists the operations allowed only for some records (a row filter or a record-level rule decides). A view's sidebar group ([`nav.recent`](sidebar.md#recent-records))) is dropped when it uses a field they cannot read. The ETag hashes all of it, so it differs per user and per roles. The OpenAPI document is generated the same way: record and body schemas have only the readable and writable fields, and methods the caller may not use are left out. Its `servers` are relative to the document (`v1` for the resources, `.` for the system endpoints), and `/api/docs` loads `openapi.json` beside it, so both are right on any host and under any prefix the API is reached at.
|
|
111
|
+
|
|
112
|
+
## Sensitive fields and audit
|
|
113
|
+
|
|
114
|
+
A field declared [`.sensitive()`](data-config.md#sensitive-fields)) is in `/meta` (marked `sensitive: true`), in record `permissions.fields` and in create and update bodies, but in no list, get, `:search`, `:seek`, write or batch response, and `filter`, `order_by`, `fields` and the aggregates refuse it like an unknown field. `POST /{resource}/{key}:reveal` with `{ "field": "<name>" }` returns one record's value. It needs read access to the record and the field: another tenant's record, a row outside the caller's row filter or a key that does not exist is a `404`, a field the caller cannot read or that is not sensitive a `400`.
|
|
115
|
+
|
|
116
|
+
Before answering, the server publishes an audit event to `options.audit`, and when publishing fails the reveal fails (`500`), so no value leaves without its event. The event never holds the value:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
type AuditEvent = {
|
|
120
|
+
type: 'field.revealed'
|
|
121
|
+
at: string // ISO 8601
|
|
122
|
+
actor: { id: string | number; roles: string[] }
|
|
123
|
+
tenant?: string | number // the caller's organization, for tenant-scoped resources
|
|
124
|
+
resource: string
|
|
125
|
+
recordKey: string // as in the record's URL
|
|
126
|
+
field: string
|
|
127
|
+
origin: { userAgent?: string; forwardedFor?: string } // from the request headers
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
With [organizations](auth.md#organizations)), someone with a global role switching into an organization they are not a member of publishes `{ type: 'organization.entered', at, actor, organization, origin }` first, where `actor.roles` are their global roles; a failed publish refuses the switch. `AuditEvent` is the union of the two.
|
|
132
|
+
|
|
133
|
+
### Audit events
|
|
134
|
+
|
|
135
|
+
`options.audit` is an `AuditQueue`, `{ publish(event): Promise<void> }`, set in `protobase.config.ts` (`options: { roles, audit }`). The default, `consoleAuditQueue()`, prints each event to the console as one `[audit] {...}` JSON line and keeps nothing; a queue that stores or forwards events replaces it there.
|
|
136
|
+
|
|
137
|
+
## Filters
|
|
138
|
+
|
|
139
|
+
`filter` and `order_by` are AIP-160 and AIP-132 text, checked against the model (filterable and sortable fields only). Functions: `in(field, v, ...)`, `search("text")` and bare words (every word, ignoring case, anywhere inside one of the resource's search fields, so `port` finds "Portfolio"; `%`, `_` and `\` are literal; a [`digitsEnd`](data-config.md#resource)) field matches only the end of its digits), `similar(field, "text")`, `regex(field, "pattern")`, `isNull(field)`, `now()` with offsets such as `now() - 7d`. A filter is capped at 10,000 characters in a query string and 200,000 in a `:search` body.
|
|
140
|
+
|
|
141
|
+
## Writes
|
|
142
|
+
|
|
143
|
+
Create, update and delete share one pipeline (`write-pipeline.ts`):
|
|
144
|
+
|
|
145
|
+
1. the caller is authenticated and, for tenant-scoped resources, has a tenant (`403` otherwise);
|
|
146
|
+
2. unknown fields, read-only fields and the tenant column in the body are refused, each value is validated by its field's zod schema (an empty string for a text field without `.optional()` counts as missing: `required`, or its default on a create), then the resource's `.validate()` rules run (`400` with `errors: [{ field, code, message }]`);
|
|
147
|
+
3. one transaction with `SET LOCAL statement_timeout`; the row is locked with `FOR UPDATE`; another tenant's key, or a soft-deleted row, is a `404`;
|
|
148
|
+
4. the access rule runs, then `If-Match` is compared with the ETag (`428` when missing on PATCH, `412` when stale);
|
|
149
|
+
5. the write, then `writeHooks` inside the same transaction (a hook that throws rolls the write back). Audit logging and the admin store plug in here.
|
|
150
|
+
|
|
151
|
+
**ETag**: the `version` or `updated_at` column when the resource has a read-only one (bumped on every update, so no trigger is needed; the ETag keeps the column's full microsecond text), otherwise a hash of the exposed fields. It is computed from the row itself, so lists need no extra query.
|
|
152
|
+
|
|
153
|
+
**`etag` property**: every record in a get, list, `:search`, create or update response carries its current version as `etag` (the value of the `ETag` header, [AIP-154](https://google.aip.dev/154)), so a grid row can be updated or deleted without a get. It survives `fields` selection. A resource cannot have a field named `etag` (startup error); a body containing `etag` is a `400` that points at `If-Match`.
|
|
154
|
+
|
|
155
|
+
**If-Match** is required on PATCH (`428` without it). On DELETE it is optional: without it the current version is deleted. When sent it must match, otherwise `412`; `*` matches whatever the current version is (RFC 9110).
|
|
156
|
+
|
|
157
|
+
**Prefer**: create and update return the record by default; `Prefer: return=minimal` returns no body (`201`/`204`). Delete returns `204`, or the record with `Prefer: return=representation`.
|
|
158
|
+
|
|
159
|
+
The rules behind these steps are described under [Access](#access).
|
|
160
|
+
|
|
161
|
+
## Batch writes
|
|
162
|
+
|
|
163
|
+
`POST /api/v1:batchWrite` takes `{ ops: [...] }` (`{ operations: [...] }` is accepted too), at most 500, run in order inside ONE transaction, so check constraints and triggers see one consistent state. Each operation goes through the same write pipeline as a single write (validation, access with row filters and record-level rules, tenant, ETags, hooks), access is checked per operation, and the operations may span resources.
|
|
164
|
+
|
|
165
|
+
| `op` | fields |
|
|
166
|
+
| --- | --- |
|
|
167
|
+
| `create` | `resource`, `data`, `ref?` |
|
|
168
|
+
| `update` | `resource`, `key`, `etag` (required, `*` allowed), `data` |
|
|
169
|
+
| `delete` | `resource`, `key`, `etag?` |
|
|
170
|
+
| `reorder` | `resource`, `field`, `keys` (in final order), `etags` (per key text) |
|
|
171
|
+
|
|
172
|
+
- **Keys** are the URL text (`a,b` when composite), a number, a list of parts, or a reference.
|
|
173
|
+
- **`$ref`**: `ref: 'invoice'` on a create names the record; later operations use `{ "$ref": "invoice" }` as a key, a key part, or a value in `data` (it stands for that record's key, or with `{ "$ref": "invoice", "field": "number" }` a readable field's value). A ref must come after its create.
|
|
174
|
+
- **`reorder`** sets `field` to 1, 2, 3, ... in the order of `keys`, and writes only the records whose value changes, each as an ordinary update (so each needs its `etags` entry, and hooks see each). To work with a non-deferrable unique index such as `(invoice_id, position)`, the changing records are first moved out of the range in use, in the same transaction and without touching their ETags: above the highest value of the column, or, when a check constraint refuses that (checked with a savepoint), below the lowest one. Then they get their final values, which collide with nothing. The field must be an integer the caller may write; the keys must all exist and be visible to the caller.
|
|
175
|
+
- **Result**: `{ results: [...] }`, one entry per operation in order: `create` and `update` give `record` and `etag`, `delete` gives `deleted: true`, `reorder` gives `records` (every key in order, with its etag).
|
|
176
|
+
- **Failure**: nothing is written. The problem is the failing operation's own (`400`, `403`, `404`, `409`, `412`, `428`, ...) with `operation` (its index), `op` and `resource` added. A stale ETag anywhere is a `412` for the whole batch.
|
|
177
|
+
|
|
178
|
+
## Authentication
|
|
179
|
+
|
|
180
|
+
Real login is [Better Auth](auth.md)). Lower level:
|
|
181
|
+
|
|
182
|
+
`authenticate(request)` returns `{ user: { id, roles }, tenant? }` or throws `unauthorized(...)` (a `401` problem), or `new MissingCredentials(...)` (also a `401`) when the request carries no credential at all. Shipped: `jwtAuthenticator({ jwksUrl | keys, issuer?, audience?, rolesClaim?, tenantClaim?, tenant? })`, which verifies a bearer token with `jose` (`sub` is the user id; `tenant` fixes the tenant instead of reading a claim), and `betterAuthAuthenticator` on top of it ([Login with Better Auth](auth.md))). No code path treats a request as a user without verifying a credential; the one exception is the [anonymous role](access.md#anonymous-access)), which the resources API gives a request that has none, when the project defines it.
|
|
183
|
+
|
|
184
|
+
## CORS
|
|
185
|
+
|
|
186
|
+
The API sends no CORS headers until it has something to allow: other websites in `options.cors` (a list of origins, or `'*'` for any), which defaults to `PROTOBASE_CORS_ORIGINS` (`*` or comma separated origins), or other [origins of the app](auth.md#several-origins)), which are always allowed.
|
|
187
|
+
|
|
188
|
+
- It covers `/api/*` but Better Auth's `/api/auth/*`, which checks origins itself, and [API functions](../guides/api-functions.md)) with a `cors` of their own.
|
|
189
|
+
- An allowed origin gets `Access-Control-Allow-Origin` with its name and `Vary: Origin`, or `*` with `'*'`. No credentials: browser code calls the API with a bearer token.
|
|
190
|
+
- Preflights are answered before authentication, for `authorization`, `content-type`, `if-match` and `if-none-match`, and kept for 10 minutes. `Location`, `ETag`, `X-Meta-Version` and `X-Protobase-Warning` are exposed.
|
|
191
|
+
- An API whose resources another app draws as [remote resources](remote-resources.md#cors)) lists that app's origin here.
|
|
192
|
+
|
|
193
|
+
## Safety
|
|
194
|
+
|
|
195
|
+
- Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 15 s); a timeout is `504`. List, search, get, histogram, series, map and seek transactions are read-only.
|
|
196
|
+
- **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field and a facet's or an aggregate's grouped field read:
|
|
197
|
+
- Comparisons, `in`, null checks, sorts and facets need a btree index with the column as a key, every key before it pinned by the query: by `=` or `in` in the filter (outside `OR` and `NOT`), by the tenant or by soft delete. `(for_sale, status, published_at desc)` serves `for_sale = true AND status = "available"` sorted by `published_at desc`, but not `status` alone. `=` on text may use a pg_trgm index instead.
|
|
198
|
+
- Patterns (`name = "*port*"`), `regex()`, `similar()` and `search()` need a pg_trgm (GIN or GiST) index on each column they read, a `digitsEnd` search field one on its digits; JSON `field:value` needs a GIN index.
|
|
199
|
+
- A partial index counts for nothing, and a resource on a plain view or a foreign table, which has no indexes of its own, is not checked.
|
|
200
|
+
|
|
201
|
+
A column without one is a `400` `expensive-query` problem that names it, with `columns` (each `{ field, column, use, need, suggestion }`) and a `create index` `suggestion`; `scanGuard: { mode: 'warn' }` answers with an `X-Protobase-Warning` header instead, `'off'` disables it. The indexes are read when a table is first queried and kept for the process lifetime, so restart the server after adding one. [`protobase doctor`](cli.md#doctor)) judges every read the config makes by the same rule against the database's indexes, so a missing index fails it before a deploy instead of a page after.
|
|
202
|
+
|
|
203
|
+
## Errors
|
|
204
|
+
|
|
205
|
+
Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to `options.onUnhandledError` and, when it is set, the [error tracker](#error-reporting).
|
|
206
|
+
|
|
207
|
+
| Status | Slugs |
|
|
208
|
+
| --- | --- |
|
|
209
|
+
| 400 | `invalid-filter`, `invalid-order-by`, `invalid-parameter`, `invalid-key`, `invalid-record`, `malformed-json`, `expensive-query`, query-layer codes |
|
|
210
|
+
| 401 | `unauthenticated` |
|
|
211
|
+
| 403 | `access-denied`, `tenant-required` |
|
|
212
|
+
| 404 | `not-found` |
|
|
213
|
+
| 409 | `conflict` |
|
|
214
|
+
| 412 / 428 | `precondition-failed` / `precondition-required` |
|
|
215
|
+
| 503 | `read-only`: the database refuses writes, as during a deploy's write freeze; send the write again after `Retry-After` |
|
|
216
|
+
| 504 | `statement-timeout` |
|
|
217
|
+
|
|
218
|
+
### Error reporting
|
|
219
|
+
|
|
220
|
+
An app can send its errors to an error tracker of its own: [Sentry](https://sentry.io) or one that speaks its protocol, such as [Bugsink](https://www.bugsink.com) or [GlitchTip](https://glitchtip.com). It is off until a DSN, the address the tracker gives a project, is set in `options.errorReporting` or `PROTOBASE_SENTRY_DSN`; without one nothing is loaded or sent.
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
export default defineConfig({
|
|
224
|
+
options: { errorReporting: { dsn: 'https://<key>@errors.example.com/42', environment: 'staging' } },
|
|
225
|
+
})
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
- **Server:** every `500` with the request it failed, under `dev`, `serve` and the runtime, besides `options.onUnhandledError` or the console. Under `serve`, the runtime and `worker`, an uncaught exception or unhandled rejection too, which then still ends the process with exit code 1.
|
|
229
|
+
- **Admin app:** uncaught errors and the errors of components that fail to draw. `/api/meta` names the DSN to every signed-in caller, as a browser app always shows its own.
|
|
230
|
+
- Errors only, with no performance tracing. Before an event leaves, the values of authorization headers, cookies, passwords, tokens and other credentials, in fields and in URLs, are replaced by `[Filtered]`.
|
|
231
|
+
- `environment` names the deployment in the tracker; without it the tracker's default, `production`. `errorReporting: false` turns reporting off whatever the environment says. A DSN that is no `http(s)` URL with a key and a project id stops startup.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/architecture.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Architecture
|
|
4
|
+
|
|
5
|
+
How the packages are laid out, which package may import which, and where tests and stories live.
|
|
6
|
+
|
|
7
|
+
A Bun workspace of npm packages under the `@protobase` scope, in `packages/<name>`, all released together at one version. `examples/*` are workspace members that consume the packages; `website` is this documentation site (Astro with Starlight), also a workspace member. The workspace root is private and is not published.
|
|
8
|
+
|
|
9
|
+
## Packages
|
|
10
|
+
|
|
11
|
+
| Package | Folder | Entry points | Runs in | Depends on |
|
|
12
|
+
| --- | --- | --- | --- | --- |
|
|
13
|
+
| `@protobase/schema` | `packages/schema` | `@protobase/schema` | anywhere | no other `@protobase` package |
|
|
14
|
+
| `@protobase/layout` | `packages/layout` | `@protobase/layout`, `@protobase/layout/jsx-runtime`, `@protobase/layout/jsx-dev-runtime` | anywhere | `schema` |
|
|
15
|
+
| `@protobase/query` | `packages/query` | `@protobase/query` | server | `schema` |
|
|
16
|
+
| `@protobase/client` | `packages/client` | `@protobase/client` | anywhere with `fetch` | `schema`, `layout` |
|
|
17
|
+
| `@protobase/ui` | `packages/ui` | `@protobase/ui`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
|
|
18
|
+
| `@protobase/server` | `packages/server` | `@protobase/server` | server | `schema`, `layout`, `query` |
|
|
19
|
+
| `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`) | Node and Bun | `schema`, `layout`, `query`, `server`, `ui` |
|
|
20
|
+
| `@protobase/presets` | `packages/presets` | none: private, `bun run presets:write` writes a project per preset | Bun | none; each preset depends on the `@protobase` packages of the major it is written at, locked at that version |
|
|
21
|
+
| `examples/*` | | none | any | `@protobase/*` entry points only |
|
|
22
|
+
|
|
23
|
+
The presets are written from `examples/erp`, `examples/real-estate` and `examples/scratch` (from scratch) by `bun run presets:write <version> <dir>`, run from a clone of this repository; they are not on npm. Each is a standalone copy with the `@protobase` packages in the range of `<version>`'s major, `>=0.y.z <1` below 1.0 (where `^0.y.z` would cover only that minor) and `^x.y.z` from 1.0, so an app takes updates within that major, and its own `bun.lock` at exactly `<version>`. The three declare the same dependencies, so one `node_modules` fits them all, and their `db:migrate` (the auth schema's migrations included), `typecheck` and `test` scripts take their settings from the environment, or a `.env` beside them, and reach nothing outside the project.
|
|
24
|
+
|
|
25
|
+
The JSX runtime belongs to `@protobase/layout` because a layout file names one package in `@jsxImportSource @protobase/layout`, and TypeScript and Vite look up `jsx-runtime` and `jsx-dev-runtime` under it. Each field type is split along the same lines: its Zod builder is `packages/schema/src/fields/<type>.ts` and its SQL parameter conversion `packages/query/src/fields/<type>.ts`.
|
|
26
|
+
|
|
27
|
+
Every package lists the packages it imports in its `package.json` (`workspace:*` for its `@protobase` dependencies), so it installs and works on its own. Rules, enforced by `bun run check:boundaries` (`.dependency-cruiser.cjs`):
|
|
28
|
+
|
|
29
|
+
- A package imports only the `@protobase` packages in the table above, so `@protobase/ui` never reaches `query`, `server` or `cli`, and `@protobase/layout` only `schema`: layouts are built in the config, checked on the server and rendered in the browser.
|
|
30
|
+
- A package imports another by its name and entry point, never by a path into its source.
|
|
31
|
+
- A package's code (not its tests and stories) imports only what its `package.json` lists in `dependencies`.
|
|
32
|
+
- Examples, their tests and `test-support/` import the packages by name, never by path.
|
|
33
|
+
- No circular dependencies.
|
|
34
|
+
|
|
35
|
+
In this repository, entry points export TypeScript source directly and the CLI runs its source on Bun, or on Node through [tsx](https://tsx.is), so nothing needs a build. The published packages are built to JavaScript in `dist` by `bun run build` and `bun pm pack` (`scripts/publish.mjs`) (see [CLI](cli.md#how-it-runs))). The other builds are for deployment: the serve runtime, `packages/cli/src/serve/main.ts` bundled with its dependencies into `dist/protobase-serve.js` by `protobase build-serve`, the shell, a production build of the admin app (`packages/ui/src/app`) shipped in `@protobase/ui`'s `dist/shell` and the protobase image, and a project's bundle, its config module plus a copy of the shell and the project's `protobase.ui.tsx` built as a [plugin](plugins.md)), by `protobase build` (see [CLI](cli.md#build))).
|
|
36
|
+
|
|
37
|
+
## Tests and stories
|
|
38
|
+
|
|
39
|
+
- Unit tests: `*.test.ts` next to the code, run by Vitest in a node environment.
|
|
40
|
+
- Tests that use a database, a subprocess or the network: `packages/<name>/tests/`, mirroring the source path, and the examples' in `tests/examples/`. Most database tests are snapshot tests, which replay SQL recorded from Postgres (`<test>.sql.json`); the fixtures, the recording and replay, and the setup they share are in `test-support/` at the root.
|
|
41
|
+
- Stories: `*.stories.tsx` next to the component in `packages/ui/src`; Storybook config lives in `.storybook/`.
|
|
42
|
+
- Packing leaves tests, stories and their fixtures out of a package (`files` in its `package.json`).
|
|
43
|
+
|
|
44
|
+
## Contract
|
|
45
|
+
|
|
46
|
+
`packages/schema/src/model.ts` is the contract between packages. Change its types deliberately; every package builds against them.
|
|
47
|
+
|
|
48
|
+
## Filters
|
|
49
|
+
|
|
50
|
+
Filters are Google AIP-160 text. Parsing, printing, `order_by` and the generic checker come from the standalone `aip-parsers` library (published on npm, entry points `aip-parsers/filter` and `aip-parsers/order-by`). `packages/schema/src/filter/` is the Protobase profile on top of it:
|
|
51
|
+
|
|
52
|
+
- `profile.ts` registers Protobase's functions (`in`, `search`, `similar`, `regex`, `isNull`, `now`) and turns a `ResourceModel` into the library's schema.
|
|
53
|
+
- `parse.ts` / `lower.ts` turn the generic tree into `FilterExpr`; `lift.ts` / `print.ts` go back.
|
|
54
|
+
- `check.ts` runs the library checker, then `check-model.ts` for value formats (decimal, bigint, uuid, date, ...), traversal and search fields. `search(...)` and bare words need `.search((r) => [...])` on the resource.
|
|
55
|
+
- `where.ts` builds typed filters in code.
|
|
56
|
+
|
|
57
|
+
`ResourceModel.search` is authoritative for server-side search; `ViewModel.list.search` only seeds the UI's search box.
|
|
58
|
+
|
|
59
|
+
## Documentation
|
|
60
|
+
|
|
61
|
+
`website/` is this site. `bun run docs:dev` serves it on port 4321; `bun run docs:build` writes `website/dist/` and fails on a broken internal link or anchor, so CI runs it on every pull request, followed by `bun run docs:check`, which opens every page in Chromium and fails on a console error or a failed request. Pages are Markdown or MDX in `website/src/content/docs/`, and the sidebar is listed in `website/astro.config.mjs`.
|
|
62
|
+
|
|
63
|
+
Every push to `main` builds the site and deploys it, and so does running the workflow by hand (`gh workflow run docs.yml`); either way it deploys to the Cloudflare Pages project `protobase-docs`, served at `docs.protobase.net` (`.github/workflows/docs.yml`). The workflow reads the Cloudflare account id from the repository variable `CLOUDFLARE_ACCOUNT_ID` and a token with Cloudflare Pages edit permission from the repository secret `CLOUDFLARE_API_TOKEN`.
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/assistant.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Assistant
|
|
4
|
+
|
|
5
|
+
The chat beside the admin, who sees it, and its built-in backend on OpenRouter or another OpenAI-compatible endpoint.
|
|
6
|
+
|
|
7
|
+
The admin app can show an assistant: an **Assistant** button at the end of the top bar opens a chat beside the page. The app only draws what a backend sends and sends back what the user types and clicks; the backend decides everything else. Protobase ships one backend, built in, which answers questions about the app, reads its data and proposes changes the user approves. Another backend can take its place by URL.
|
|
8
|
+
|
|
9
|
+
## Who sees it
|
|
10
|
+
|
|
11
|
+
`/api/meta` names the backend as `assistant: { url }`, and only for a caller with the `admin` or `ai` role. The app shows the button when `/meta` has it, so without a backend, or for anyone else, nothing shows. Give someone the assistant without making them an admin by adding `ai` to the project's roles (`createAuth({ roles: ['admin', 'ai', ...] })`, see [Roles](auth.md#roles))) and to their user (`protobase users set-role me@example.com sales,ai`).
|
|
12
|
+
|
|
13
|
+
The built-in backend checks the role again on every request.
|
|
14
|
+
|
|
15
|
+
## Which backend
|
|
16
|
+
|
|
17
|
+
| Set | `/meta` names |
|
|
18
|
+
| --- | --- |
|
|
19
|
+
| `PROTOBASE_ASSISTANT_URL` | that URL: a backend elsewhere, such as a hosted one |
|
|
20
|
+
| otherwise `PROTOBASE_ASSISTANT_API_KEY` | `/api/assistant`, the built-in backend |
|
|
21
|
+
| neither | no assistant |
|
|
22
|
+
|
|
23
|
+
Each variable can also be set in code, as `options.assistant` of `createAdmin` (in `protobase.config.ts`, `export default { ..., options: { assistant: { ... } } }`), which wins over the variable. `assistant: false` turns the assistant off whatever the environment says. A value that is no `http(s)` URL stops the server at startup. The model settings also serve [AI fields and actions](ai.md#the-model)), even with a backend elsewhere or `assistant: false`.
|
|
24
|
+
|
|
25
|
+
| Variable | Option | |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `PROTOBASE_ASSISTANT_URL` | `url` | an external backend |
|
|
28
|
+
| `PROTOBASE_ASSISTANT_API_KEY` | `apiKey` | the model endpoint's API key; turns on the built-in backend |
|
|
29
|
+
| `PROTOBASE_ASSISTANT_MODEL` | `model` | the model; default `openrouter/auto` on OpenRouter, required elsewhere |
|
|
30
|
+
| `PROTOBASE_ASSISTANT_BASE_URL` | `baseUrl` | an OpenAI-compatible endpoint; default `https://openrouter.ai/api/v1` |
|
|
31
|
+
| `PROTOBASE_ASSISTANT_CHATS` | `chats` | the directory the built-in backend keeps conversations in; default `.protobase/chats` |
|
|
32
|
+
|
|
33
|
+
### With OpenRouter
|
|
34
|
+
|
|
35
|
+
Create a key at [openrouter.ai](https://openrouter.ai/keys) and set it, with a model of your choice:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
PROTOBASE_ASSISTANT_API_KEY=sk-or-v1-...
|
|
39
|
+
PROTOBASE_ASSISTANT_MODEL=anthropic/claude-sonnet-5.5 # optional; OpenRouter picks one without it
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
On OpenRouter the built-in backend asks for low reasoning effort and marks the system prompt and the earlier chat for prompt caching, so models that cache, such as Anthropic's, bill the repeated part of each request as a cheaper cache read.
|
|
43
|
+
|
|
44
|
+
### With another OpenAI-compatible endpoint
|
|
45
|
+
|
|
46
|
+
Any endpoint that serves `POST <base URL>/chat/completions` with streaming and tool calls works: OpenAI itself, a gateway, or a local server such as Ollama or vLLM. Name the model:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
PROTOBASE_ASSISTANT_BASE_URL=http://localhost:11434/v1
|
|
50
|
+
PROTOBASE_ASSISTANT_API_KEY=ollama # sent as the bearer token; a local server may ignore it
|
|
51
|
+
PROTOBASE_ASSISTANT_MODEL=llama3.3
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The model needs tool calling for the queries. A refused key, an exhausted account or a wrong model shows in the chat as a red card with the endpoint's own message, such as `The model endpoint https://openrouter.ai/api/v1 answered 401: No auth credentials found (check the API key)`.
|
|
55
|
+
|
|
56
|
+
## The built-in backend
|
|
57
|
+
|
|
58
|
+
It lives at `/api/assistant` on the app's own origin and answers with the user's token like the rest of the API. Its system prompt describes the resources, tables and fields the user can see in `/meta`. It has two tools of its own, and [the app's](#the-apps-own-tools):
|
|
59
|
+
|
|
60
|
+
- **`run_read_only_query`** runs one `SELECT` (or `VALUES`, or a `WITH` query) and shows its rows as a table in the chat. It runs in a `READ ONLY` transaction that is always rolled back, with a statement timeout of 5 seconds and at most 200 rows. The statement is sent with a parameter, so every Postgres driver uses the extended protocol, where Postgres refuses a text with more than one command: the statement cannot `COMMIT` its way out, and Postgres refuses every write inside (`SET TRANSACTION READ WRITE`, writable CTEs, `nextval`, `DO` blocks, functions that write). Settings it changes go with the rollback.
|
|
61
|
+
- **`propose_write_query`** never runs on its own. It shows the statement and a summary on a card with **Approve** and **Reject**. Only Approve runs it, as one statement in a read-write transaction; Reject, or no answer within 10 minutes, runs nothing. The model gets the returned rows, or that nothing ran. Statements are `INSERT`, `UPDATE` or `DELETE` with a `RETURNING` clause.
|
|
62
|
+
|
|
63
|
+
Both run as the app's database role, **outside Protobase's access rules and tenant scoping**: whoever has the `admin` or `ai` role can read, and with approval change, everything that role can. Give the app a database role without superuser rights, and those roles only to people who may see all of the data.
|
|
64
|
+
|
|
65
|
+
### The app's own tools
|
|
66
|
+
|
|
67
|
+
`options.assistant.tools` adds tools of the app's own, which the built-in backend offers after its two. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the option does nothing there.
|
|
68
|
+
|
|
69
|
+
`context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, and `records`: `get(resource, key)`, `create(resource, data)` and `update(resource, key, data, { etag? })` (without an ETag it updates any version) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. Each answers `{ record, etag }`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
|
|
70
|
+
|
|
71
|
+
A tool with a [widget](#widget-parts) creates or finds what it is about, shows a widget with its id, and returns the id and the state at that moment:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
// config/assistant/propose-task.ts
|
|
75
|
+
import { defineTool, widget } from '@protobase/server'
|
|
76
|
+
|
|
77
|
+
export const proposeTask = defineTool({
|
|
78
|
+
name: 'propose_task',
|
|
79
|
+
description: 'Proposes a task; someone approves or declines it on its card, now or later. Read it again before relying on its status.',
|
|
80
|
+
parameters: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] },
|
|
81
|
+
run: async (args, { records, show }) => {
|
|
82
|
+
const { record } = await records.create('tasks', { title: args.title, status: 'proposed' })
|
|
83
|
+
show(widget('TaskProposal', { taskId: record.id }, { fallback: { title: `Task proposal: ${String(record.title)}` } }))
|
|
84
|
+
return JSON.stringify({ taskId: record.id, status: 'proposed' })
|
|
85
|
+
},
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
// protobase.config.ts: export default { ..., options: { assistant: { tools: [proposeTask] } } }
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```tsx
|
|
92
|
+
// components/task-proposal.tsx, exported from protobase.ui.tsx: export { TaskProposal } from './components/task-proposal'
|
|
93
|
+
export const TaskProposal = ({ taskId }: { taskId: number }) => {
|
|
94
|
+
const task = useRecord('tasks', taskId)
|
|
95
|
+
const update = useUpdateRecord('tasks', taskId)
|
|
96
|
+
if (!task.data) return <ActionCard title="Task proposal" note={task.error ? 'Could not load the task' : 'Loading'} />
|
|
97
|
+
const { record, etag } = task.data
|
|
98
|
+
return (
|
|
99
|
+
<ActionCard title={String(record.title)} badge={String(record.status)}
|
|
100
|
+
note={record.status === 'proposed' ? undefined : `${String(record.status)} by ${String(record.decidedBy)}`}
|
|
101
|
+
actions={record.status === 'proposed' ? [{ id: 'approved', label: 'Approve', style: 'primary' }, { id: 'declined', label: 'Decline' }] : []}
|
|
102
|
+
onAction={(status) => update.mutate({ patch: { status }, etag })} />
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The tool and its component live apart, joined by the name, since the server config cannot import `@protobase/ui` and the browser must not get server code; put shared prop types in a file both import with `import type`. Whoever may update the task decides on it, now or next month, from the chat or the task's own page, and a write hook can stamp who did from `event.user`; when two decide at once, the ETag makes the second write fail and the widget shows the first decision. The chat is not told: the model learns of the change by reading the record again, which the description asks it to do.
|
|
108
|
+
|
|
109
|
+
Each message carries the page the user is on, such as `/orders/42`, which the model reads with it.
|
|
110
|
+
|
|
111
|
+
There is one conversation per user, shared by their tabs. The server keeps it as a file, `<chats>/<user>/chat.jsonl` (see `PROTOBASE_ASSISTANT_CHATS`), with the chat and everything the model read, so a restart keeps it and the app only ever sends the new message. The directory is made on the first message and must be writable: in a container, point it at a volume. With several instances, send each user's requests to the same one.
|
|
112
|
+
|
|
113
|
+
## Another backend
|
|
114
|
+
|
|
115
|
+
A backend elsewhere replaces the built-in one through `PROTOBASE_ASSISTANT_URL`. It receives the user's API token as `Authorization: Bearer <token>`, verifies it against the app's key set (`/api/auth/jwks`), and allows the app's origin with CORS. It can be built from the building blocks `@protobase/server` exports (the protocol's routes, the turn loop with tool calling, tools, approvals, the query tools and a conversation store interface to keep chats elsewhere, such as in a database) with its own prompt and tools; the built-in backend's source, `packages/server/src/assistant/built-in-assistant.ts`, is the reference.
|
|
116
|
+
|
|
117
|
+
## Widget parts
|
|
118
|
+
|
|
119
|
+
Besides text, tables and cards, a backend can show a **widget**: a part that one of the app's own React components draws. The chat keeps only the component's name and a small JSON of props, such as `{ "taskId": 12 }`, and the component fetches what it shows when it is drawn, so a chat from last month shows the record as it is today, including a decision someone else made since.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { widget } from '@protobase/server'
|
|
123
|
+
|
|
124
|
+
show(widget('TaskProposal', { taskId: record.id }, { fallback: { title: `Task proposal: ${record.title}` } }))
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`widget(name, props, { id?, fallback? })` builds the part `{ type: 'widget', id, name, props, fallback? }`. The name must be PascalCase, and the props a JSON object of at most 2 KB, or it throws: pass ids and settings, not the state the widget shows. Without an `id` the part gets a new one; showing a part with the same id again replaces it. `fallback` is drawn as a plain card where the app has no component by that name. The part never reaches the model, which reads only the tool's result.
|
|
128
|
+
|
|
129
|
+
### How the dock draws them
|
|
130
|
+
|
|
131
|
+
The dock draws a widget part with the component the app's `protobase.ui.tsx` exports under that name, the same components [composed pages](custom-components.md#components)) use, giving it the part's props. The component reads what it shows when it is drawn, as the signed-in user: the dock is mounted only while it is open, so each opening, and each page load, reads it again. Its buttons call the app's API or the backend directly; they need no turn of the chat, so they work after a restart, from any tab and for any user who may make the call.
|
|
132
|
+
|
|
133
|
+
- **No component by that name**, such as in an app built before the component was added: the dock draws the fallback as a plain card noting "This version of the app cannot show it live", or, without a fallback, a muted line naming the component.
|
|
134
|
+
- **A component that throws** is caught on its own: the dock draws the fallback noting "It could not be drawn", without the error, and the rest of the chat stays.
|
|
135
|
+
|
|
136
|
+
Docks from before widget parts skip them; rebuild the app on a release that has them.
|
|
137
|
+
|
|
138
|
+
### Reading the backend from a widget
|
|
139
|
+
|
|
140
|
+
A widget about the app's own data uses the usual hooks (`useRecord`, `useList`, `useUpdateRecord`, `useClient`). A widget about the backend's own data, such as a hosted backend's tasks, uses `useBackendData` from `@protobase/ui`:
|
|
141
|
+
|
|
142
|
+
```tsx
|
|
143
|
+
const Task = ({ taskId }: { taskId: string }) => {
|
|
144
|
+
const path = `/api/assistant/tasks/${encodeURIComponent(taskId)}`
|
|
145
|
+
const task = useBackendData<{ title: string; status: string }>(path, { refreshMs: (data) => (data?.status === 'running' ? 5000 : false) })
|
|
146
|
+
if (!task.data) return <ActionCard title="Task" note={task.error ? 'Could not load the task' : 'Loading'} />
|
|
147
|
+
return <ActionCard title={task.data.title} badge={task.data.status} note={task.error?.message} actions={[{ id: 'decline', label: 'Decline' }]} onAction={(action) => void task.post(`${path}/actions`, { action })} />
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
It returns `{ data, error, reload, post(path, body) }`. It reads `path` when the widget mounts, and again every `refreshMs` while that is a number; `post` sends JSON and its answer replaces `data`. A failed read or post sets `error`, an `ApiError` carrying the backend's problem detail, and keeps the last `data`. The path resolves against the backend's URL from `/meta` and goes through the dock's client (`AssistantClient.fetch`), with the same bearer token as the chat; a path on any other origin is refused before a request is made, so props a model wrote cannot send the user's token elsewhere. It works only in a widget the dock draws.
|
|
152
|
+
|
|
153
|
+
Breaking change: `AssistantPart` now includes `AssistantWidgetPart`, so code that switches over part types must handle `widget`, for instance by drawing its `fallback`.
|
|
154
|
+
|
|
155
|
+
## In the UI
|
|
156
|
+
|
|
157
|
+
The dock is `AssistantDock` from `@protobase/ui`, built from primitives that custom components and [shell slots](custom-components.md#shell-slots)) can use too: `SidePanel`, `ChatThread`, `ChatMessage`, `Composer`, `ActionCard`, `FieldList`, `StepList`, `DiffView` and `CompactTable`. `ActionCard` takes `frameless` to draw its content, note, buttons, hints and confirm dialog without the bordered card and title row, for a page that is already framed; the title still labels the section for screen readers. `useApiToken()` returns the signed-in user's API token, renewed before it expires, for calling another service as them.
|