| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312 |
- # smartbotic-vectorapi
- > General-purpose REST API over smartbotic-database. **Multi-project**: every
- > collection and document lives under a named project supplied as a URL path
- > segment (e.g. `/api/v1/projects/{project}/collections`). **Multi-key**: each
- > API key carries a list of project grants (MySQL-style; `["*"]` for all); admin
- > keys additionally manage projects and keys. Auth: `Authorization: Bearer <KEY>`.
- > Machine-readable spec: `/openapi.json` (OpenAPI 3.1).
- ## Projects
- Requires a valid key. Admin-only operations are noted.
- - `GET /api/v1/projects` - List projects the key may access (admin sees all).
- - `POST /api/v1/projects` `{name}` - Create a project (admin).
- - `GET /api/v1/projects/{project}` - Get project info (collection/document counts).
- - `DELETE /api/v1/projects/{project}` - Drop a project (admin; the `default` project cannot be dropped).
- ## Keys (admin)
- All key-management endpoints require an admin key.
- - `GET /api/v1/keys` - List keys. Secret value is masked; returns `id`, `key_prefix`, `label`, `projects`, `admin`, `created_at`, and `scope` (if present). Use `id` to reference the key in PATCH/DELETE.
- - `POST /api/v1/keys` `{label, projects:[], admin?, scope?}` - Generate a new key. Returns the secret key value **once** (store it immediately) plus the stable `id`. Pass a `scope` object (see below) to create a capability-scoped key.
- - `PATCH /api/v1/keys/{id}` `{label?, projects?, admin?, scope?}` - Update grants for an existing key, identified by its `id` (not the secret). Pass `scope: null` to clear an existing scope.
- - `DELETE /api/v1/keys/{id}` - Revoke a key by `id`. Active sessions using it are immediately invalidated.
- ### Capability-scoped keys
- A non-admin key may carry a `scope` object that restricts what it can do. Scoped keys are designed to be safely embedded in untrusted clients (browser frontends, mobile apps, n8n workflows). A scoped key cannot manage collections or projects regardless of its project grants.
- `scope` fields:
- - `rules` (required, non-empty array) - Each rule specifies a `collection` name and the permitted `ops` array (`read`, `list`, `search`, `insert`, `update`, `delete`). A request succeeds only if a matching `{collection, op}` rule exists. A rule may also set `require_human_token: true` (see CAPTCHA below).
- - `origins` (array of strings, default empty) - Allowed `Origin` header values. When non-empty, requests without a matching `Origin` header are rejected with 403 (**fails closed** - no origin header means denied). Use this to pin a key to a specific domain.
- - `rate_limit_per_min` (integer, default 0 = unlimited) - Per-key request rate limit. When the limit is exceeded the server returns **429** with a `Retry-After: 60` header.
- - `expires_at` (integer, default 0 = never) - Unix epoch seconds after which the key is treated as expired; auth returns 401.
- ### CAPTCHA-gated operations
- A scope rule may set `require_human_token: true`. When this flag is active, the client must supply an `X-Captcha-Token` request header containing the CAPTCHA challenge response. The server verifies the token via the configured provider endpoint and returns **403** `captcha_required` if the token is absent, invalid, or if no provider is configured. Configure the provider via the settings API: `captcha_provider` (`"turnstile"` or `"hcaptcha"`), `captcha_secret` (server-side secret), and `captcha_verify_url` (full verify endpoint URL).
- Example scope (insert-only, origin-pinned, rate-limited, expiring):
- ```json
- {
- "rules": [{"collection": "designs", "ops": ["insert"]}],
- "origins": ["https://app.example.com"],
- "rate_limit_per_min": 60,
- "expires_at": 1893456000
- }
- ```
- ## Collections
- Project-scoped. A key must be granted the project.
- - `POST /api/v1/projects/{project}/collections` `{name, kind:"json"|"vector", vector_dimension?, embedding_model?}` - Create a collection. `vector_dimension` is required for `kind=vector`. `embedding_model` defaults to the server's `default_embedding_model` setting.
- - `GET /api/v1/projects/{project}/collections` - List collections with metadata (incl. `document_count`, `size_bytes`). Query params (all applied server-side): `q` (case-insensitive name substring filter), `sort` (`name`|`kind`|`documents`|`size`|`created_at`, default `name`), `desc` (bool).
- - `GET /api/v1/projects/{project}/collections/{name}` - Get collection metadata.
- - `DELETE /api/v1/projects/{project}/collections/{name}` - Drop a collection and all its documents.
- Collection names may not start with `_` or the reserved prefix `vectorapi_`.
- ## JSON documents
- Arbitrary JSON CRUD under a `kind=json` collection.
- - `POST /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` or `{...}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
- **Other slugs worth branching on.** From the database: `read_only` **503** (the database is refusing writes), `db_unavailable` **503**, `rate_limited` **429** raised by the DATABASE under pressure (distinct from a key's scope rate limit, same status), `message_too_large` **422** when a call is refused for size by the transport itself - it is **422 and not 429** because waiting cannot shrink a payload, and it is not named after your body because the limit applies in either direction: a stored document can grow past it through repeated PATCHes until it can no longer be read back, so you may have sent nothing large at all. The message carries both sizes and says which direction it was, `document_too_large` **422** when a write would make the STORED document bigger than a read could ever return - note a patch is judged on its MERGED result, so the body you sent may be small, `outcome_unknown` **504** when a WRITE timed out and may or may not have been applied (re-read before retrying; never blindly retry a non-idempotent write - this is deliberately NOT 503, which would mean "retry as-is"), and `memory_pressure` **429** when the database's admission control is refusing writes because IT is short of memory - the same remedy as a rate limit (wait, `Retry-After` is set) but deliberately a different slug, because `rate_limited` would have you throttle a client that was never the problem, `internal` **500**. On the routes: `exists` **422** (duplicate collection name), `bad_project` **422**, `last_admin` **422** (refusing to remove the last admin key), `not_vector` **422** (a vector op on a json collection), `dimension_mismatch` **422**, `ambiguous_body` **422**, `file_too_large` **422**, `vector_replace_unsafe` **422**, `vector_missing` **422** (a document inserted into a vector collection without `_vector` - it would read back fine and never be findable by a search, so it is refused rather than stored. **`text` does NOT satisfy it: this route does not embed.** Only `POST .../vectors` embeds, so send text there. The same refusal applies to `ctx.collections(...).insert()`, where `.store({text})` is the embedding path). On `/fn/*`: `function_error` **500** and `method_not_allowed` **405**. On function writes: `no_runner` and `runner_unreachable` both **503**; invoke answers **409** `function_invalid` or `function_disabled`. Inside a function: `jobs_unavailable` **503**, `job_depth_exceeded` **422**, `unsupported_combination` **422**, `body_too_large` **422**, `not_json` **422**, `embedding_timeout` **504**, `fetch_timeout` **504**.
- **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: **`field`** when one field collided or **`fields`** when several, **`values`** (an OBJECT of the colliding field/value pairs, not a bare `value`), `conflicting_document_id` (the document already holding it), and `relation` or `current_version` where they apply. A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing collection is **404** only when its absence is CONFIRMED: if the database cannot be reached the answer is **503**, never a 404, so a 404 is always safe to treat as definitive and unretryable. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write. **On a `kind=vector` collection, a PUT whose body carries no vector is refused **422** `vector_replace_unsafe`.** A replace discards the stored embedding and the caller cannot prevent it, because no read returns the vector - so there is nothing to put back. Use `PATCH` for fields, or `POST .../vectors` to store a document together with its vector.
- **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields.
- - `GET /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
- - `PUT /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. PUT does not take `?ttl_seconds=`; use POST with an `id` to create with an expiry.
- - `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
- **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.
- - `POST /api/v1/projects/{project}/collections/{name}/documents/{id}/increment` `{field: n, ...}` (or `{data:{...}}`) - **Atomic increment.** Adds each number to the named field in ONE locked server-side read-modify-write, so concurrent increments cannot lose each other. Dotted keys address nested fields (`counts.sent`). Returns **200** `{id, values}` where `values` holds the NEW value of every field you named. An absent or null field counts as 0. Integer + integer stays an integer (overflow is refused); anything else becomes a double. A field holding a non-number is **422** `validation` and **nothing at all is applied** - the whole set applies or none of it does. Needs the `update` grant (it is a write, so a read-only scope gets **403**); it is a separate route rather than a flag on PATCH because `{"calls":1}` means "set calls to 1" on PATCH and "add 1 to calls" here.
- - `GET /api/v1/projects/{project}/collections/{name}/export` - **Streaming backup, including stored vectors.** Answers **NDJSON** (`application/x-ndjson`): one JSON object per line, so the LINE is the unit of recovery and a truncated download loses the last row rather than the file. First line `{type:'header', collection, snapshot_at, vector_dimension, vector_dtype, rows_at_snapshot, batch_rows_cap, max_stream_seconds, include_vectors, vector_format}` (`snapshot_at` is server epoch seconds - "as of when" is the first question anyone asks of a backup, and a filesystem mtime does not survive a copy); then `{type:'row', id, document, vector_state, vector}` per document; then `{type:'trailer', rows_sent, last_id, complete, content_sha256}`. **`content_sha256` is over each row's id and its RAW VECTOR BYTES, not over the emitted text**, so it is IDENTICAL whichever `vector_format` you asked for - you can export as base64, restore, re-export as an array and still compare digests. It is omitted rather than empty if it could not be computed. **`rows_sent == rows_at_snapshot` with `complete: true` is your checksum** - one uninterrupted call is an exact snapshot with no row skipped or repeated, in id order. Needs BOTH the `list` and `read` grants: `list` alone could already learn the ids and must not get the contents, and `read` alone must not get an enumeration.
- **Params:** `include_vectors` (default **true** for a vector collection, and refused **422** `not_vector` on a json one), `vector_format` (`array` default, or `base64` for float32-little-endian). **Both are BIT-EXACT** - tested over 200k float32 values including denormals and the extremes - so choose on size, not on fidelity. `array` is the default because it restores directly (`_vector` on a document write takes exactly that shape) but it is ~3.7x larger: nlohmann prints a float32 widened to double with shortest-round-trip for DOUBLE, giving 16 digits where float32 needs 9, so it is verbose for precisely the same reason it is exact. Measured on 12447 rows at dim 4096: array 963 MiB, base64 261 MiB. **DO NOT ASK FOR GZIP ON VECTOR DATA.** Responses are compressible and the export inherits it, but measured at level 6 an array export costs ~121 s of SERVER CPU to save ~68 s of download, which is a net loss and a real cost on a shared host; base64 of float data compresses only 1.35x. Send `Accept-Encoding: identity` for a vector export. Gzip the json collections happily - document JSON compresses ~3.9x), `after_id` (resume), `batch_rows` (clamped, never refused).
- **`vector_state` is `present`, `none`, `missing` or `unknown`,** and a row that is not `present` carries NO `vector` field at all rather than an empty one - so a restorer cannot mistake "we do not have it" for "it is empty". **`missing` means the row HAD a vector and the entry is gone** (real data loss) and `unknown` means the row predates the database's marker, so neither should be restored as a plain document: re-embed from the source text instead, or you will store a row that reads back fine and can never be found by a search.
- **To restore:** replay each row as `PUT .../documents/{id}` with `document` plus `_vector` set to `vector`. The restored row gets FRESH metadata (`_version` restarts at 1, `_created_at` is the restore time); the originals are still in the exported `document` if you need them as data.
- **Resuming is skip-possible, never duplicate.** `complete: false` means the stream ended early - the server's `max_stream_seconds` cap, or your client disconnecting - and `last_id` is the cursor: call again with `after_id=<last_id>`. A resume starts a NEW snapshot strictly after that id, so it never repeats a row but can miss one inserted during the gap with an id sorting before the cursor. For an airtight copy take one uninterrupted stream.
- **A failure mid-stream emits a final `{type:'error', code, message, rows_sent, complete:false}` line** instead of simply stopping, because a stream that stops looks identical to a complete one whose trailer was lost. Treat a stream with no `trailer` AND no `error` line as failed.
- **It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
- - `DELETE /api/v1/projects/{project}/collections/{name}/documents/{id}` - Delete a document. Returns **409** `relation_restricted` (with `error.details.impacts`) if a restrict relation has children referencing it; see delete-impact below to preview this first.
- - `GET /api/v1/projects/{project}/collections/{name}/documents` - Find documents. Every row carries the same `_id`/`_version` metadata a single GET returns, so a filtered listing is a usable starting point for a conditional write without a second request per row.
- - `GET /api/v1/projects/{project}/collections/{name}/documents/{id}/delete-impact` - Preview what deleting this document would affect, without deleting it: `{would_be_blocked, impacts:[{relation, child_collection, child_field, on_delete, child_count, sample_child_ids, blocks}]}`. Read-only; follows the collection's read grant (a scoped key with a read rule may call it).
- **Filter grammar**: `field:op:value`, repeatable and ANDed. On documents it is the `?filter=` query param; on vector search it is the `filters` body array. The same grammar, operators and semantics apply to both, because the database evaluates them.
- Supported ops: `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `contains`, `exists`, `regex`, `search`.
- - `in` - value is a JSON array, e.g. `colour:in:["red","yellow"]`.
- - `contains` - **array membership**, not substring: it matches when the field is an array holding the value. `colour:contains:yellow` does NOT match the string `"yellow"`.
- - `search` - substring match on a string field, e.g. `colour:search:ell` matches `"yellow"`.
- - `regex` - regular-expression match.
- - `exists` - `field:exists:true` / `field:exists:false`.
- The value is parsed as JSON when it parses (numbers, booleans, arrays), otherwise it is taken as a string. Everything after the second `:` is the value, so a value may itself contain `:`. A malformed spec or unknown operator is rejected with **400** `bad_filter`.
- Example: `?filter=age:gte:30&filter=name:eq:Alice`.
- Additional query params: `limit` (default 20), `offset` (default 0), `sort` (field name), `desc` (bool).
- ## Indexes and facets
- Project-scoped, under a collection. Index create/drop require a full (non-scoped) key with project access - scoped keys cannot manage indexes.
- - `POST /api/v1/projects/{project}/collections/{name}/indexes` `{field, unique?}` - Declare an index on `field`, backfilling existing rows so it's usable immediately. Idempotent: re-declaring reports `already_existed: true`. With `unique: true`, refuses with **409** `duplicate_values` (`error.details.duplicate_examples`, up to five colliding document ids) if the field already holds duplicate values.
- - `POST /api/v1/projects/{project}/collections/{name}/indexes` `{fields:[...]}` - Declare a **composite unique constraint**: no two documents may hold the same COMBINATION of those fields, e.g. `{"fields":["chat_id","file_unique_id"]}`. Two or more fields, each named once; same `{rows_indexed, already_existed}` answer and the same **409** `duplicate_values` (with `duplicate_examples`) when existing rows already collide. A document in which ANY of the fields is absent or null does not participate (the SQL rule for a NULL in a unique key). It is always unique and backs no query, so `unique:false` is **422**. `field` and `fields` are two spellings of one request: sending **both** is **422** `ambiguous_body`, never resolved by precedence.
- - `GET /api/v1/projects/{project}/collections/{name}/indexes` - List indexes: `{indexes:[{field, distinct_values, entries, unique}], composite_unique:[{fields:[...], unique:true}]}`. `indexes` keeps exactly its old shape; composite constraints are reported under the separate `composite_unique` key because a composite has no `distinct_values`/`entries` and is named by a list rather than a field.
- - `DELETE /api/v1/projects/{project}/collections/{name}/indexes/{field}` - Drop a single-field index. Idempotent: dropping an index that is not there is **200**, the requested end state having been reached either way.
- - `DELETE /api/v1/projects/{project}/collections/{name}/indexes?fields=a&fields=b` - Drop a composite unique constraint, named by its **exact** field list (repeat `fields` once per field; order does not matter, and a missing or single-field list is **422**). Idempotent like the single-field drop, so a list naming no existing constraint is **200**, not 404. The list lives in a query param because it cannot live in the path: joining it would need a separator no field name may contain. Answers `{dropped_fields:[...]}`.
- - `GET /api/v1/projects/{project}/collections/{name}/indexes/{field}/values` - Distinct values with counts: `{values:[{value, count}]}`. Index-dependent by design (not an error): returns an empty list for a field with no index and for array-valued fields, whose index keys are elements rather than values. Query params: `limit` (1-1000, default 100), `order` (`asc`|`desc`, default `asc`; use `order=desc&limit=1` for the maximum). Follows the collection's read grant.
- ## Relations (admin)
- Relation names are per-project and **unqualified**: requests and responses always use the bare name; the internal `project:` prefix is never exposed. All relation endpoints require an admin key.
- - `POST /api/v1/projects/{project}/relations` `{name, child, child_field, parent, on_delete?, validate_on_write?}` - Create a relation: deleting a `parent` document affects `child` documents whose `child_field` references it. `on_delete` is one of `restrict` (default), `cascade`, `set_null`, `no_action`; anything else is 422.
- - `GET /api/v1/projects/{project}/relations` - List relations in the project.
- - `GET /api/v1/projects/{project}/relations/{name}` - Get a relation by name.
- - `DELETE /api/v1/projects/{project}/relations/{name}` - Drop a relation by name.
- - `GET /api/v1/projects/{project}/collections/{name}` also returns `relations_enforced` (bool). It is **absent** when the server could not determine it, which never means disabled.
- - `PUT /api/v1/projects/{project}/collections/{name}/relations-enforced` `{enforced}` - Enable/disable relation enforcement on a collection. **`relations_enforced` is read on the collection you are deleting FROM (the PARENT side of the relation), not on the child collection holding the reference.** Disabling it on the child has no effect on deletes issued against the parent; set it on the parent to let its deletes bypass restrict relations.
- ## RAG vectors
- Requires a `kind=vector` collection. Vectors are stored with cosine-similarity indexing.
- - `POST /api/v1/projects/{project}/collections/{name}/vectors` `{id?, text?, vector?, metadata?}` - Store a vector. Supply either `text` (the server embeds it, resolving the model as: the collection's `embedding_model` pin, else the project's embedding override, else the global default) or a pre-computed `vector` array. `vector` dimension must match the collection's `vector_dimension`. `metadata` is an arbitrary JSON object stored alongside the vector.
- - `POST /api/v1/projects/{project}/collections/{name}/search` `{query_text?, query_vector?, top_k?, min_score?, filters?}` - Cosine-similarity search. Supply either `query_text` or `query_vector`; neither is **422**. `top_k` caps the results, **default 5**. `min_score` (0-1) drops low-confidence matches, default 0. `filters` is an array of `field:op:value` strings applied to the vector's metadata, using the grammar and operators above - metadata is stored at the top level of the document, so a vector written with `metadata:{"colour":"red"}` is filtered as `colour:eq:red`. The response also carries **`scan_capped`** (and `scanned`, plus `scan_cap` when capped): a filtered search walks the ranking only `scan_cap` deep, so on a collection larger than that a filter whose matches lie deeper returns FEWER hits than match. `scan_capped: false` means the answer is complete - including the ordinary case of a filter matching fewer rows than `top_k`. **Check it before treating a filtered result set as exhaustive.** Inside a function the return stays an array and the warning goes to the run's console instead.
- Filtering is evaluated by the database, then intersected with the similarity ranking, so scores are identical with and without a filter and `min_score` means the same thing either way. The scan is bounded at 10000 candidates: within a collection of that size a filtered search returns exactly the true top-k, and beyond it a filter matching only very low-ranked vectors may return fewer.
- **Latency tip:** `query_text` triggers a synchronous server-side embedding call to the configured provider, which usually dominates request time (seconds for large models). Cosine search itself is sub-millisecond. If your client issues many searches (e.g. an LLM/n8n agent doing RAG), embed the query once on your side and pass `query_vector` to skip server-side embedding entirely.
- **Cache bypass:** Send `Cache-Control: no-store` on a `/vectors` or `/search` request to skip the server-side embedding cache - the text is re-embedded fresh and the result is not stored in the cache.
- ## Settings (admin)
- `PUT /api/v1/settings` also accepts **`function_egress_blocked_cidrs`** (an array of CIDRs, **422** `invalid_cidr` on a bad one) and **`function_egress_allow_private`** (a bool). The blocklist is **UNIONED** with the built-in defaults, never substituted for them, and `function_egress_allow_private` relaxes ONLY the private ranges - the metadata endpoint, link-local, multicast and the IPv6 spellings of an IPv4 address stay blocked whatever it is set to. **`max_file_bytes` is returned by GET but is NOT settable over the API**; it is read from the stored settings document.
- All settings endpoints require an admin key.
- - `GET /api/v1/settings` - Return current settings as JSON. `openai_api_key` is masked: the field is absent and `openai_api_key_set` (bool) indicates whether a key is configured.
- - `PUT /api/v1/settings` `{openai_api_base?, openai_api_key?, default_embedding_model?, cors_origins?, session_ttl_minutes?, webui_enabled?, default_project?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?, embedding_cache_size?, embedding_cache_ttl_sec?, embedding_cache_max_bytes?, embedding_cache_normalize?, embedding_client_pool_size?, captcha_provider?, captcha_secret?, captcha_verify_url?}` - Merge the supplied fields into the current settings and persist. Omit `openai_api_key` or `captcha_secret` (or pass an empty string) to keep the existing secret. Changes are hot-reloaded immediately; cache settings are applied instantly via `reconfigure()`.
- ## Project embedding settings
- A project can point its embeddings at its own provider endpoint, key and model, which is how per-customer usage gets metered at the provider. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused.
- Precedence for one embedding call: the collection's own `embedding_model` wins, then the project override, then the global default. The endpoint and key are the project override when set, otherwise the global ones.
- - `GET /api/v1/projects/{project}/settings/embeddings` - Return `{effective, inherited, overrides}`. Each carries `openai_api_base`, `default_embedding_model`, `openai_api_key_set` (bool), `embedding_connect_timeout_sec` and `embedding_read_timeout_sec`. The API key itself is never returned. In `overrides`, an empty string means an inherited string field and `null` an inherited timeout.
- - `PUT /api/v1/projects/{project}/settings/embeddings` `{openai_api_base?, openai_api_key?, default_embedding_model?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?}` - Omit a field to leave it unchanged; send `null` to clear the override and inherit the global value. The two timeouts are seconds and **narrowing only**: the effective value is `min(project, global)`, so a project can tighten but never lengthen how long it may hold a shared provider connection. A value above the global one is stored rather than refused, and becomes meaningful if an operator later lowers the global. An empty string is rejected with **422**. Setting `openai_api_base` without an `openai_api_key` for the same project is rejected with **422** `embedding_base_requires_key`, so the global credential is never sent to a foreign endpoint. A project key without a project base URL is allowed (own key, default endpoint).
- - `DELETE /api/v1/projects/{project}/settings/embeddings` - Drop every embedding override, timeouts included; the project inherits the global settings again. It does **not** touch the project's function policy or wall-time caps, which live in the same document but are admin-only.
- ## Project secrets
- The values a project's functions read as `ctx.env.<NAME>` - a bot token, a provider key, a webhook signing secret. Stored per project in the database, so filling `ctx.env` no longer needs shell access to the runner host.
- A secret value is **write-only**: no endpoint ever returns it, masked or otherwise. A `GET` reports the name, whether a value is set, and the timestamps.
- Writes are **admin-only**, like a function's policy: the value is a live credential every function in the project then runs with, and an overwrite cannot be undone by inspection. Listing and reading the metadata only needs a key granted the project (capability-scoped publishable keys are refused), because an author has to know which names their code may read.
- A `NAME` must match `[A-Z_][A-Z0-9_]*` and be at most 64 characters - the charset a POSIX environment variable can carry, so a stored secret and a host variable can never hold one name under two spellings. A value is at most 8192 bytes, and a project may hold at most 64 secrets.
- **Precedence:** a host variable `SVAPI_FN_<project>__<NAME>` in `runner.env` wins over a stored secret of the same name. The host file can only be written by someone on the runner host, so it stays the override that a stolen API credential cannot shadow - and nothing changes for a deployment that already keeps its secrets there.
- - `GET /api/v1/projects/{project}/secrets` - `{project, secrets:[{name, set, created_at, updated_at}], count, max_secrets, max_value_bytes}`. Names only.
- - `GET /api/v1/projects/{project}/secrets/{NAME}` - `{name, set, created_at, updated_at}`; **404** when the secret does not exist.
- - `PUT /api/v1/projects/{project}/secrets/{NAME}` `{value}` - **admin only**. **201** on a first write, **200** on a rotation; the response never carries the value. **422** for a bad name, an empty or oversized value, or `secret_limit` when the project is already at 64 secrets.
- - `DELETE /api/v1/projects/{project}/secrets/{NAME}` - **admin only**. **404** when there was no such secret.
- Deleting a project deletes its secrets, so a recycled project name inherits nothing.
- ### Per-project function limits
- - `GET|PUT /api/v1/projects/{project}/settings/functions` `{max_wall_time_ms}` (**admin only**) - The project's wall-time cap, now **per run kind**: `{"max_wall_time_ms": {"http": n|null, "job": n|null}}`. A bare integer is still accepted on PUT and sets BOTH kinds, and `null` clears both; an object sets only the keys it names. GET always returns the object form - a single number could not express "10 s for routes, 60 s for jobs", and leaving the old scalar in place would make a client that reads only it see `null` (no cap) while a cap was in force. Narrowing only: neither raises a ceiling.
- - `PUT /api/v1/projects/{project}/settings/functions` `{max_wall_time_ms: int|null}` **(admin)** - the ceiling a function here may ask for with its own `timeoutMs`. It can only NARROW: the effective budget is `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`. Admin-only because it decides how long one project may hold a pooled runtime, and so how long it can delay every other project's interactive routes.
- **A job run and an HTTP run have different ceilings.** An HTTP route answers a caller holding a socket open (seconds); a queue-claimed run has nobody waiting (minutes, 120 s by default) and draws from its own pool lane, so a slow scheduled job cannot take the runtime an interactive route needs.
- ## Project files
- Small named binary assets per project, so everything customer-specific (a logo, an e-mail signature image) is tenant **data** rather than something bundled into a function's source - a project can then be cloned for another customer by changing data only. Reads follow the scope rules under the reserved pseudo-collection **`_files`**; writes and deletes need a full (non-scoped) key with project access, because replacing a tenant's asset is a management act.
- - `PUT /api/v1/projects/{project}/files/{name}` - Store the **raw request body** under `name`, taking the content type from the `Content-Type` header (default `application/octet-stream`). Not base64 and not a JSON wrapper: a file is bytes. **201** for a new name, **200** for a replacement, and a replacement makes the old bytes unreadable. Answers `{name, content_type, size, checksum, created_at}`. An empty body is **422**; over the size cap is **422** `file_too_large` (default **2 MiB**, `max_file_bytes` in the global settings).
- - `GET /api/v1/projects/{project}/files/{name}` - The bytes, with the stored content type, plus `X-File-Checksum` and a `Content-Disposition` naming the file. **404** when there is no such file.
- - `GET /api/v1/projects/{project}/files/{name}/info` - Metadata only, without moving the bytes.
- - `GET /api/v1/projects/{project}/files` - `{files:[{name, content_type, size, checksum, created_at}]}`, newest first. `limit` (1-1000, default 100, clamped rather than refused) and `offset`.
- - `DELETE /api/v1/projects/{project}/files/{name}` - **404** when absent. Safe against content dedup: identical bytes stored under two names share storage and are reference-counted, so deleting one name leaves the other readable.
- - **A file name is an identifier, not a label.** Letters, digits, `.`, `-` and `_`, at most 128 characters, no leading `.`, no `..`, no path separator and no `:`. A bad name is **422** with the reason, never 404 - the name is unusable rather than missing, and a caller told "not found" would retry a name that can never work.
- - **Deleting a project deletes its files**, so a recycled project name does not inherit the previous tenant's assets.
- - In functions: `ctx.files.get(name)` -> `{name, content_type, size, checksum, created_at, base64}` or **null** when absent, `ctx.files.info(name)`, `ctx.files.list()`. Governed by the function policy under `_files`, exactly like a collection. **Read only** - a function cannot write or delete a file. A single `ctx.files.get()` is capped at **1 MiB** independently of the storage cap, because base64 inflates by a third and a run holds a pooled runtime with its own memory limit.
- ## Functions
- Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.
- ### Writing a function
- A function is an ES module exporting a trigger declaration and a default handler:
- ```js
- export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }; **`type` is `http` (the default), `cron`, `db` or `job`.** `cron` needs `schedule` (five-field) and optionally `tz`, an IANA zone validated against the host's time-zone database at PUSH time - an unknown zone is refused, never silently UTC. `db` needs `table` and `event` (INSERT/UPDATE/DELETE). `job` is reached only by being enqueued. **`singleFlight` defaults to TRUE for cron** and false otherwise.
- export default async function (ctx) {
- const docs = await ctx.collections('kb_chunks')
- .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
- const hits = await ctx.collections('kb_chunks')
- .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
- ctx.log('found', docs.length, 'documents');
- return { status: 200, body: { docs, hits } };
- }
- ```
- `on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
- `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
- - `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
- - **Write options**, previously undocumented. `ttl_seconds` is accepted by `.insert()`, `.update()`, `.patch()` and `.store()`; it sets or clears a document's expiry, and **absent is not zero** - omitting it leaves an existing expiry untouched while `0` clears it, so a plain `.patch()` cannot accidentally make a temporary document permanent. **`ifVersion: n`** makes the write conditional on the document still being at version `n` (as returned in `_version`); a lost race is **409** `version_conflict` carrying `current_version`, which means "someone else has it" and should be handled by dropping the work or re-reading, never by retrying the same write. `ifVersion` must be a positive integer - version 0 does not exist, since a first write produces 1. It is accepted by **`.update()` and `.patch()` only**: `.insert()` refuses it by name, because there is no existing version for a document that does not yet exist. `ttl_seconds` together with `ifVersion` is refused (`unsupported_combination`) rather than silently dropping one. A conditional `.update()` returns `{id, version}`; the unconditional form returns `{id}`.
- - Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters, embedTimeoutMs?})`, returning an **array** of hits, and `.store({text|vector, metadata, embedTimeoutMs?})`. Embedding resolves through the normal precedence, so a project's provider override applies.
- - **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. It applies identically to `.search()` and `.store()`: both resolve their vector through the same code, so there is no asymmetry between them. Exceeding it is **504** `embedding_timeout`. A non-integer or non-positive value is **422**: it is validated rather than ignored, because an option that is accepted and does nothing is worse than one that is refused.
- - **Its RESOLUTION IS ONE SECOND, and the effective floor is 1 s per phase.** The HTTP client underneath takes whole seconds and treats 0 as "no timeout", so every value below 1000 ms resolves to the same thing: 1 s to connect plus 1 s to read. `embedTimeoutMs: 1` therefore allows up to **2 s**, not 1 ms, and a provider that answers inside that second succeeds normally - which reads exactly like the option being ignored. It is not: a value of 1 and a value of 999 are genuinely indistinguishable, and tuning inside that range does nothing. Ask for **2000 or more** if you want the split to be meaningful, and expect a timeout to surface at a whole-second boundary rather than at the millisecond you named. Connect never takes more than HALF the available time, so a 4000 ms ask becomes roughly 2 s connect + 2 s read.
- - **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.
- - `ctx.fetch(url, {method, headers, body, timeoutMs, responseType})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
- - **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.
- - **The `ctx.fetch` response** carries `status`, `headers`, `body`, `bodyEncoding` and a `res.json()` helper. `res.json()` on a base64 response throws `not_json` rather than parsing bytes as text.
- - `ctx.files.list()` returns at most **100** entries and does not page. `ctx.crypto.hmacSha256` accepts `{base64:'...'}` for either `key` or `data`, not only strings.
- - `.insert(doc)` honours an **`id` inside the document object** - the idiom for an idempotent write.
- - `.store()` also accepts `id` and `ttl_seconds`. A `.filter(...)` accumulated on the chain is **appended** to an explicit `filters` array in `.search({...})`, never replaced by it.
- - `ctx.jobs.enqueue(functionId, payload, options?)` - put work on the job queue, returning the **job id as a plain string** (not an object). The project is NOT an argument: a function enqueues into its own project or not at all. **This is where slow work belongs** - a job run gets the job wall ceiling (far higher than an HTTP run's) and draws from its own pool lane, so it cannot starve interactive routes. Options: `runAt` (a `Date` or epoch milliseconds) **or** `delaySec`, never both - reconciling them would be a guess at what the author meant, so it is **422** `ambiguous_body`; and `dedupeKey`, a non-empty string of at most 512 characters that collapses repeated enqueues of the same logical work. An unknown option name is refused **by name** rather than ignored.
- - `ctx.jobs.cancel(id)` - cancel a job that has not been claimed yet. Returns a **boolean**: false when there was nothing cancellable.
- - **Job delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs AGAIN, so anything reached by a job, a cron or a database event must be idempotent. A function that throws is NOT retried (one attempt, the author's to fix); what re-runs work is reclaim. See the error table above for `version_conflict`, which is how a conditional claim reports losing the race.
- - `ctx.crypto.hmacSha256(key, data, encoding?)` - HMAC-SHA256, `encoding` being `hex` (default) or `base64`. For verifying a provider's webhook signature.
- - `ctx.crypto.timingSafeEqual(a, b)` - constant-time string comparison. Use it to compare a signature rather than `===`, which leaks the position of the first difference.
- - `ctx.crypto.randomUUID()` - a version 4 UUID.
- - `ctx.time.parts(epochMs, zone)` - civil fields for an instant in an IANA zone: `{year, month, day, hour, minute, second, weekday, offsetSec, zone}`. Available without `Intl` having to be loaded.
- - `ctx.time.fromParts(parts, zone)` - the reverse. It reports a local time that does not exist (the DST spring-forward gap) rather than inventing one, and tells you when a local time is ambiguous (the autumn repeat).
- - `ctx.time.zoneKnown(zone)` - whether the host's time-zone database knows that name. An unknown zone is a catchable error everywhere else, never a silent fall back to UTC.
- - `ctx.time.format(epochMs, zone, pattern, locale?)` - format an instant, e.g. `format(ms, 'Europe/Budapest', 'YYYY. MMMM D., dddd', 'hu')`. An unknown locale is refused rather than served in English.
- - `Intl.DateTimeFormat` also works inside a function, installed per context.
- - **`responseType: 'base64'` returns a BINARY response body** as base64. Needed for anything that is not text: the value handed to the engine is serialised as JSON, and a JSON string cannot hold a byte outside a valid UTF-8 sequence, so a non-text body is either base64 or it is refused. The refusal names this fix rather than surfacing a raw UTF-8 decode error.
- - **`timeoutMs` narrows the call, never widens it**, and is capped by what is left of the run's budget. There is no connection pooling: every call builds its own client, so there is no keep-alive socket to go stale.
- - **Exceeding the budget is 504 `fetch_timeout`, not `fetch_failed`.** The connect, read and write timeouts are set to the run's REMAINING budget, so a provider slower than that is cut off by us - and the underlying library words that as "Failed to read connection", which reads like a network fault. The error says how long the call took and how long it was allowed, so the two are distinguishable. A long provider call belongs on a **job** trigger, whose ceiling is far higher than an HTTP run's.
- - **Sending a BINARY request body is supported** - this was previously undocumented, and a consumer concluded it was missing. `body` is text (a JS string). For bytes use **`bodyBase64`** (a base64 string, decoded before sending) or **`bodyBytes`** (an array of 0-255 integers). Exactly ONE of the three, never two: supplying both is refused with `ambiguous_body` rather than resolved by precedence, because reading `body` and ignoring a `bodyBase64` beside it would silently send the wrong payload. Invalid base64 is **422**.
- - **`Content-Type` is defaulted to `application/json` only for the TEXT shape.** A binary body is never given a default: labelling arbitrary bytes as JSON would be a lie a provider then rejects or mis-parses, so a caller sending bytes must say what they are.
- - `ctx.env.<NAME>` - secrets for THIS project only, from two merged sources: the project's own secrets set over the API (see "Project secrets") and the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). A host variable wins over a stored secret of the same name. Never another project's, and never the runner's own configuration.
- - `ctx.log(...)` - captured into the run's `console`, bounded.
- **A denied collection access throws a catchable error** naming the collection and the operation, rather than returning an empty result - so a missing grant looks like a failure, not like missing data.
- **The return value shapes the response.** An object whose keys are a non-empty subset of `{status, headers, body}` is a response envelope; any other object is sent as a `200` body; an object MIXING envelope keys with other keys **fails the run** rather than being guessed at. Host calls are synchronous, so `await` is optional - it works because awaiting a non-promise is a no-op.
- **The id lives in the source, not in the URL.** A script exports `export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }`, and that `id` is the registry row's identity. `path` records where the author keeps the file and carries no meaning, so moving `kb-search.js` to `lib/search.js` keeps the same row - and the policy an admin granted travels with it.
- **Every write is compiled on a runner before it is stored.** The engine that validates is the engine that will execute. A compile failure is **422** `compile_failed` with the error; an `on` block with no id is **422** `missing_function_id`; no healthy runner is **503** `no_runner` and nothing is stored. Code is never stored unvalidated.
- **A code push can never widen access.** `policy` is server state: a `policy` field sent with a `POST`/`PUT` body is ignored (not merged, not consulted as a fallback), and `enabled` is likewise preserved, so re-pushing code does not re-enable a function an operator turned off. A first registration inherits the project's default policy, which currently grants **no collection at all** - the function runs, logs and can call out, but reaches no data until an admin grants it a rule.
- - `GET /api/v1/projects/{project}/functions` - List functions **without their sources**: `{functions:[{function_id, path, content_hash, descriptor, policy, enabled, valid, last_error, created_at, updated_at}], runners:{configured, healthy}, runs_kept}`. The `runners` counts let a client warn that a write will fail with **503** *before* an author writes a script, rather than only after the push: `configured: 0` is the common first state, because installing the runner package does not switch functions on - the server needs a `functions.runners` list. `runs_kept` is this server's configured run-log retention, so a client need not guess the default.
- - `POST /api/v1/projects/{project}/functions` `{source, path?}` - Register a new function; the id comes from the validated `on` block, so there is no `function_id` field to send. An id already in use is **409** `function_exists` (PUT it to update).
- - `GET /api/v1/projects/{project}/functions/{id}` - Get one function, **including** `source`.
- - `PUT /api/v1/projects/{project}/functions/{id}` `{source, path?}` - Push code. The id the script declares must equal the id in the URL; a mismatch is **422** `id_mismatch` (with `error.details.declared` and `error.details.url`) rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (**201**).
- - `DELETE /api/v1/projects/{project}/functions/{id}` - Delete the function, its code and its policy.
- - `PUT /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
- - `PUT /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
- - `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
- - `GET /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, headers, started_at}]}`. `headers` is omitted when the function set none, and is present so a stored run renders with the same shape as a fresh invoke envelope. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
- ### Calling a function
- - `ANY /fn/{project}/{path}` - **Unauthenticated.** This is where a published function is served; it takes no API key, because a function's HTTP route is public by design. The project is the first path segment and the rest is matched against that project's `on` routes, so `/fn/acme/kb/hungary` reaches the `acme` function declaring `route: '/kb/:topic'` with `topic = "hungary"`.
- - The function chooses the response: its returned `status`, `headers` and `body` are sent as-is. Returning a plain object with none of those keys sends it as a `200` body, and an object mixing them with other keys **fails the run** rather than being guessed at.
- - A path matching no function is **404**; a path that matches but not for this method is **405** with an `Allow:` header. Disabled and invalid functions are simply absent, so they are **404** too - a public caller learns nothing about what a project contains.
- - A function that threw is **500**, a wall-time timeout is **504** `function_timeout`, exceeding the memory ceiling is **500** `function_out_of_memory`, and no healthy runner is **503** `runner_unavailable` with `Retry-After`. **The function's error text is never returned** - a stack trace on an open endpoint is an information leak. The response carries `error.details.run_id`, and the message is in `GET .../functions/{id}/logs`.
- - Request `Cookie`, `Authorization`, `Proxy-Authorization` and `X-Captcha-Token` headers are **not** forwarded to the function. The web UI is served from this same origin, so forwarding `Cookie` would hand a logged-in admin's session to every function author in the project.
- - Repeated query parameters collapse to the last value (`?tag=a&tag=b` gives `tag = "b"`), and `HEAD` is not routable.
- ## Stats
- - `GET /api/v1/projects/{project}/stats` - Per-project stats (collections, document counts). Accessible to any key granted the project.
- - `GET /api/v1/stats` - Server-wide stats including `memory_pressure_level`, an `embedding` object with cache telemetry (`cache_size`, `cache_capacity`, `cache_hits`, `cache_misses`, `cache_hit_ratio`, `cache_bytes`), and `db_client_version`/`db_client_commit` (the smartbotic-database client library the dynamic linker actually bound at process startup, not necessarily what the binary was compiled against (2.4.x and 2.11.x share a SONAME, so a mismatched library can load silently and only crash on a later restart)). Admin only.
- ## Admin
- - `GET /api/v1/admin/readonly` - Get the server-wide (not per-project) read-only lock status: `{readonly, scope:"server", reason?}`. Reflects the database's own authoritative state - it can enter read-only by itself after a degraded/failed recovery, not only via the PUT below, so `readonly:true` does not necessarily mean an operator locked it; `reason` (DB-defined free text) is present only when non-empty. While locked, writes are rejected by the database and surfaced by vectorapi as **503**. Admin only.
- - `PUT /api/v1/admin/readonly` `{readonly}` - Set the server-wide read-only lock. Admin only.
- ## Ops
- Public (no auth required):
- - `GET /version` and `GET /api/v1/version` - `{name, version, commit, db_client}`. The root one needs **no credential**; the `/api/v1` one needs any valid key (a scoped key is fine), because everything under `/api/` is authenticated. Ask it rather than probing a behaviour to work out which server you are talking to.
- - `GET /healthz` - Liveness probe; always 200 while the process is running.
- - `GET /readyz` - Readiness probe; 200 when the database is reachable, 503 otherwise.
- - `GET /openapi.json` - OpenAPI 3.1 machine-readable spec.
- - `GET /llms.txt` - This file.
- - `GET /docs` - Rendered API reference page (RapiDoc over the spec above).
- Session login (used by the web UI):
- - `POST /ui/login` `{key}` - Exchange an API key for an HttpOnly session cookie (`svapi_session`). The cookie may be used in place of the `Authorization: Bearer` header for all `/api/v1/*` endpoints.
- - `POST /ui/logout` - Invalidate the session and clear the cookie.
- - `GET /ui/session` - Return `{ok, admin, projects}` for the caller's current session (cookie or bearer), or **401** when there is none. Sessions are held in memory, so a server restart invalidates every cookie; a client must call this before trusting any locally stored "logged in" state.
|