LumiBaseDocs

Hono API Specification — LumiBase

For AI agents: This page is also available as clean Markdown. Append /index.md to any LumiBase docs URL.

Base URL: https://api.<your-site>.lumibase.dev (or http://localhost:1989 in local dev)

All endpoints are versioned under /api/v1. Every request must include:

  • Authorization: Bearer <token> — login token, or an API key (lbk_…)
  • X-Lumi-Site: <siteId> — site identifier (or resolved via subdomain routing)

Response envelope

All responses follow this structure:

json
{
  "data": <T>,
  "meta": {
    "total": 123,
    "page": 1,
    "pageSize": 50,
    "filter_count": 50
  }
}

Error response:

json
{
  "errors": [
    {
      "code": "PERMISSION_DENIED",
      "message": "You don't have permission to read field 'secret'.",
      "path": ["fields", "secret"],
      "extensions": { "reason": "field_policy" }
    }
  ]
}

Error codes

CodeHTTPDescription
PERMISSION_DENIED403Policy check failed
RECORD_NOT_FOUND404Item does not exist or not visible to this role
VALIDATION_FAILED400Input schema validation error
CONFLICT409Unique constraint violated
RATE_LIMITED429Rate limit exceeded — honour Retry-After
RATE_LIMIT_UNAVAILABLE503Rate limiter's backing cache is unavailable and the deployment runs the throttle in fail-closed mode (LUMIBASE_RATE_LIMIT_FAIL_CLOSED=true). Transient — retry with backoff. Not emitted in the default fail-open configuration
SITE_NOT_FOUND404X-Lumi-Site header resolves to unknown tenant
TOKEN_EXPIRED401JWT has expired — refresh and retry
SKILL_DENIED403AI skill requires a capability the session lacks
HITL_REQUIRED202Dangerous operation gated for human approval
VALIDATION400Organization payload validation failed
SCOPE_NOT_ALLOWED400Organization keys must be minted through the organization API
ORGANIZATION_FORBIDDEN403Credential scope or organization role does not allow this action
ORG_SIGNUP_DISABLED403Organization signup is disabled for this caller
SITE_NOT_IN_ORGANIZATION403Selected site does not belong to the organization key
ORGANIZATION_NOT_EMPTY409Organization must have no sites before deletion
LAST_OWNER409At least one owner must remain
REQUESTER_REVOKED409Requester no longer holds live organization authority
APPROVAL_ALREADY_DECIDED409A conflicting approval decision is already committed

Deprecation signalling. A retiring endpoint returns the IETF Deprecation and Sunset response headers (RFC 8594) plus a Link rel="deprecation" to the changelog. Clients should log these and migrate before the Sunset date. See docs/en/security/owasp-api-top-10-audit.md (API9).


Standard query parameters (list endpoints)

ParameterExampleDescription
fieldsfields=id,title,author.nameSelect specific fields + nested relations
filterfilter[status][_eq]=published or filter={"status":{"_eq":"published"}}Filter using rule operators — see Filter forms
sortsort=-updated_at,titleComma-separated, - prefix for DESC
pagepage=2Page number (1-indexed)
limitlimit=25Items per page (max 200)
aggregate[count]aggregate[count]=*Aggregate functions
groupBygroupBy=statusGroup aggregation results
deepdeep[author][fields]=name,avatarNested relation query params

Full-text search is a separate endpoint, GET /api/v1/search (MeiliSearch), not a list-endpoint parameter. It supports single-collection and cross-collection (omit collection) queries and is diacritics-insensitive for Vietnamese. See features/search.md.

Filter operators

OperatorDescription
_eqEquals
_neqNot equals
_lt, _lte, _gt, _gteComparison
_in, _ninIn / not in array
_null, _nnullIs null / not null
_contains, _icontainsContains (case-sensitive / insensitive)
_starts_with, _ends_withString prefix/suffix
_betweenRange (two-element array)
_and, _orLogical grouping
_json_containsJSONB @> — value/sub-object/array-membership containment
_has_keyThe JSON object has this key
_has_any_keys, _has_all_keysThe JSON object has any / all of these keys (string array)
_near, _within_bboxgeopoint fields: within { lat, lng, radius } metres / inside [minLng, minLat, maxLng, maxLat] — see Geopoint fields

Searching inside JSON. A filter field key may be a dotted path into a nested JSON/JSONB field — e.g. filter={"metadata.author.country":{"_eq":"VN"}} compiles to a data #>> '{metadata,author,country}' lookup. Path segments are restricted to [A-Za-z0-9_] and bound as parameters (injection-safe); depth is capped at 8. The _json_contains / _has_* operators run against the JSONB and use the existing GIN index. Top-level keys and structural fields behave exactly as before.

Typed comparisons (Cast_Rule). Item values are stored as JSONB, so a naive comparison is textual ('10' > '9' is false). _eq, _neq, _in, _nin, _gt, _gte, _lt and _lte therefore cast both sides by type:

Field / valueComparison
Top-level field of type integer, bigInteger, decimal, floatnumeric
Top-level field of type booleanboolean
Top-level field of type date, datetime, timestamptimestamptz
Nested path, json field or unknown key with a JSON number / boolean valuenumeric / boolean, inferred from the value
Anything else (string, text, uuid, string values on nested paths)text, as before

The stored side uses a guarded cast: a row whose value does not look like the type (for example "n/a" in a decimal field) compares as NULL and drops out, instead of failing the query. A filter value that cannot be cast (for example {"price":{"_gt":"cheap"}}) is rejected with 400 INVALID_FILTER. String operators (_contains, _starts_with, _ends_with) always compare text. Sorting on a top-level numeric, boolean or date field uses the same cast, so sort=-price orders numerically. Structural fields (id, status, sort, created_at, …) keep their native column types.

code
GET /api/v1/items/products?filter={"price":{"_gt":10}}&sort=-price
GET /api/v1/items/products?filter={"metadata.rating":{"_gte":4.5}}

To make a typed filter on a hot path use an index, ask the index advisor for matching DDL.

Filter forms

List endpoints accept the filter query parameter in two equivalent forms — use whichever is more convenient. Both produce the same filter object server-side.

1. Bracket form — ergonomic for hand-written URLs and HTML forms:

code
GET /api/v1/items/articles?filter[status][_eq]=published&filter[views][_gte]=100
  • Nesting maps directly: filter[field][_op]=value.
  • Values are coerced: true/false → boolean, null → null, clean integers/decimals → number (leading-zero strings like 007 stay strings), everything else → string.
  • Array operators (_in, _nin, _between) accept comma-separated values: filter[status][_in]=published,scheduled.
  • Logical groups use an index segment: filter[_and][0][status][_eq]=published.

2. JSON form — better for complex/programmatic filters and the SDK:

code
GET /api/v1/items/articles?filter={"status":{"_eq":"published"}}

If both are supplied on the same request, the JSON form wins. A malformed JSON filter returns 400 VALIDATION; a malformed bracket key is ignored rather than failing the whole request.


1. Auth

MethodPathAuthDescription
POST/api/v1/auth/loginpublicExchange Logto auth code or username/password for an access JWT + rotating refresh token
POST/api/v1/auth/registerpublicSelf-service subscriber sign-up (generic 202, anti-enumeration, rate-limited)
POST/api/v1/auth/verify-emailpublicActivate a self-service account from the emailed token
POST/api/v1/auth/resend-verificationpublicRe-send the activation email (generic 202, rate-limited)
POST/api/v1/auth/forgot-passwordpublicEmail a password-reset link (generic 202, rate-limited)
POST/api/v1/auth/reset-passwordpublicConsume a reset token, set new password, revoke refresh tokens
POST/api/v1/auth/refreshpublicRotate the refresh token (cookie or body) → fresh access JWT + new refresh token
POST/api/v1/auth/logoutpublicRevoke the presented refresh token's family + clear the cookie
POST/api/v1/auth/verify-totppublicSecond leg of a two-step Studio login — exchange an MFA challenge token + TOTP (or recovery) code for a session
GET/api/v1/auth/mebearerGet current user profile
GET/api/v1/me/tfabearerTOTP enrollment status ({ enabled, enrolledAt, recoveryCodesRemaining })
POST/api/v1/me/tfa/setupbearerBegin enrollment (password step-up) → one-time secret + otpauthUrl
POST/api/v1/me/tfa/confirmbearerConfirm enrollment with a live code → single-use recovery codes
POST/api/v1/me/tfa/recovery-codesbearerRegenerate recovery codes (password + TOTP code)
DELETE/api/v1/me/tfabearerDisable TOTP (password + either a TOTP code or a recovery code); revokes sessions and bumps tokenVersion
POST/api/v1/auth/passkey/optionspublicPasskey authentication options: with challengeToken = second factor, without = passwordless staff sign-in → { ceremonyId, options }
POST/api/v1/auth/passkey/verifypublicFinish a passkey ceremony → same session payload as login (amr contains webauthn, tfaVerified)
GET/api/v1/me/passkeysbearerThe caller's passkeys + recoveryCodesRemaining, totpEnabled, available
POST/api/v1/me/passkeys/registration-optionsbearerBegin passkey registration (password step-up) → { ceremonyId, options }
POST/api/v1/me/passkeysbearerFinish registration → { passkey, recoveryCodes } (codes only for a first factor)
PATCH/api/v1/me/passkeys/:idbearerRename a passkey
DELETE/api/v1/me/passkeys/:idbearerRemove a passkey (password); the last second factor revokes sessions and bumps tokenVersion
POST/api/v1/me/passkeys/recovery-codesbearerRegenerate recovery codes (password + a passkey-opened session)
POST/api/v1/me/change-passwordbearerVerify current password, set new hash, revoke refresh tokens + bump tokenVersion
GET/api/v1/me/sessionsbearerList the caller's active sessions (live refresh tokens, redacted)
DELETE/api/v1/me/sessions/:idbearerRevoke one of the caller's sessions
DELETE/api/v1/me/sessionsbearerRevoke all of the caller's sessions; ?scope=others keeps the current session
GET/api/v1/me/security-historybearerThe caller's own security events (sign-ins, new devices, password/MFA changes, revocations), redacted; ?cursor=&limit=&scope=site|account — see Security history
GET/api/v1/me/security-history/exportbearerDownload the same history; ?format=json|csv&scope= (max 5,000 rows, 10 exports / 15 min)
GET/api/v1/auth/social/providerspublicSocial login providers enabled for the site
POST/api/v1/auth/social/:provider/startpublicBegin Google / Apple / GitHub sign-in (PKCE) → authorizationUrl
GET/POST/api/v1/auth/social/callback/:siteId/:providerproviderProvider callback (POST = Apple form_post); redirects to the allow-listed URI with a one-time code
POST/api/v1/auth/social/exchangepublicRedeem the one-time code with the client codeVerifier → session (aud: frontend)
GET/api/v1/me/identitiesbearerLinked login identities + hasPassword
POST/api/v1/me/identities/:provider/linkbearerBegin linking a provider to the signed-in account
POST/api/v1/me/identities/completebearerFinish linking (one-time code + codeVerifier)
DELETE/api/v1/me/identities/:idbearerUnlink a provider (never the last login method)
GET/api/v1/admin/social-providerssite-adminPer-site social provider configuration (secrets write-only)
PUT/DELETE/api/v1/admin/social-providers/:providersite-adminConfigure / remove a provider — see Social login
POST/api/v1/users/subscriber-accesssite-adminGrant subscribers read on a collection (Policy DSL)
GET/DELETE/api/v1/users/subscriber-access[/:collection]site-adminList / revoke subscriber read grants
GET/api/v1/me/preferencesbearerCurrent user's preferences blob (identity-global)
PATCH/api/v1/me/preferencesbearerShallow-merge a preferences patch
GET/api/v1/me/consentsbearerList the current user's consent decisions
PUT/api/v1/me/consents/:typebearerGrant or withdraw a consent (GDPR Art. 7, PDPD)
GET/api/v1/me/data-exportbearerDownload the current user's personal data (GDPR Art. 15/20)
GET/api/v1/me/restrictionbearerCurrent restriction-of-processing state (GDPR Art. 18)
PUT/api/v1/me/restrictionbearerSet restriction of processing ({ restricted, reason? })
GET/api/v1/me/automated-decisionsbearerAgent-authored revisions on the user's content (GDPR Art. 22)
GET/api/v1/retentionadminReport configured retention horizons
POST/api/v1/retention/runadminPrune activity + handled notifications past horizons

Cookie-sourced /auth/refresh + /auth/logout require the X-LumiBase-Refresh header (CSRF brake). Refresh tokens are delivered both as an httpOnly cookie and in the response body; see docs/en/security/user-management.md §4d for per-realm TTLs and the cross-domain cookie env (REFRESH_COOKIE_SAMESITE/_DOMAIN/_SECURE).

Account erasure (GDPR Art. 17) and Subject Access Requests are served by the regulated-content-readiness feature at /api/v1/admin/erasure and /api/v1/admin/sar.

Two-factor login (TOTP). Optional and per-user. When a user with TOTP enrolled logs into the Studio realm, POST /api/v1/auth/login does not return a session. It returns a challenge instead:

jsonc
// POST /api/v1/auth/login  →  200
{ "data": { "status": "mfa_required",
            "challengeToken": "eyJ…",   // aud: mfa-challenge, 5 min TTL
            "expiresIn": 300 } }

// POST /api/v1/auth/verify-totp  →  200 (same shape as a normal login)
{ "challengeToken": "eyJ…", "code": "123456" }
// …or, if the authenticator is lost:
{ "challengeToken": "eyJ…", "recoveryCode": "XXXX-XXXX-XXXX" }

The challenge token carries the mfa-challenge audience, so it cannot be replayed as a session JWT, and its jti is single-use (tracked in the cache provider). Verification is rate-limited per user and per IP. A successful verify issues the access JWT with amr: ["pwd", "totp"]. Policy-driven step-up (anomalyAction: 'require_mfa') uses the same challenge flow when the user has TOTP enrolled, and still returns 401 MFA_REQUIRED when they do not.

Enrollment is a two-step, password-stepped-up flow: POST /me/tfa/setup returns the base32 secret and otpauthUrl once (never re-readable), then POST /me/tfa/confirm proves possession with a live code and returns eight single-use recovery codes. The TOTP seed is persisted only as a KeyProvider AEAD envelope, so enrollment requires ENCRYPTION_KEY in production; recovery codes are stored as PBKDF2 hashes. Set LUMIBASE_TOTP_ISSUER to control the label shown in authenticator apps (default LumiBase).

Key availability is reported explicitly rather than as a 500: setup returns 503 ENCRYPTION_NOT_CONFIGURED when the deployment has no active key, and verify / regenerate return 409 TFA_KEY_UNAVAILABLE when the key that wrapped that particular seed is no longer configured. In the latter case DELETE /me/tfa accepts a recovery code in place of a TOTP code, so the user can remove an enrollment whose seed can no longer be decrypted. See Encryption key operations.

Passkeys (WebAuthn). When the user also (or only) has passkeys, the mfa_required response adds methods (["totp"], ["webauthn"] or both), and the challenge can be finished with POST /auth/passkey/options + POST /auth/passkey/verify instead of verify-totp. The same two endpoints without a challengeToken give a passwordless staff sign-in. See Passkeys.

Consent management (:type ∈ marketing · analytics · personalization · functional · sale_share):

jsonc
// PUT /api/v1/me/consents/marketing
{ "granted": true, "source": "preference_center", "version": "v1" }

// Response
{ "data": { "consentType": "marketing", "granted": true,
            "grantedAt": "2026-06-24T10:00:00.000Z", "withdrawnAt": null,
            "source": "preference_center", "version": "v1",
            "updatedAt": "2026-06-24T10:00:00.000Z" } }

Each change writes a consent_granted / consent_withdrawn audit event. Only user principals (not API keys) can manage consent. Current state is stored per (site_id, user_id, consent_type) in user_consents; full history lives in the audit log.

Email unsubscribe & suppression (CAN-SPAM):

MethodPathAuthDescription
GET/api/v1/email/unsubscribe?token=…publicOne-click unsubscribe (renders HTML confirmation)
POST/api/v1/email/unsubscribepublicRFC 8058 one-click (token in query or form body)
GET/api/v1/email/suppressionsadminList suppressed addresses
POST/api/v1/email/suppressionsadminAdd an address ({ email, reason? })
DELETE/api/v1/email/suppressions/:emailadminRemove an address (re-subscribe)

The unsubscribe token is a stateless HS256 JWT ({ siteId, email }, no expiry) signed with JWT_SECRET. Marketing sends (EmailModuleService.send({ category: 'marketing' })) filter recipients against email_suppressions before dispatch. Unsubscribe/suppression changes audit email_unsubscribed / email_suppressed / email_unsuppressed.

Preferences & save action. PATCH /api/v1/me/preferences shallow-merges a validated patch into users.preferences (other sections like language / keybindings are preserved). Send { "saveAction": "stay" | "return" | "create_new" } to set the Studio editor's post-save navigation; send { "saveAction": null } to fall back to the site default (sites.default_save_action, set via PATCH /api/v1/site). Invalid enum → 400.

Email identity policy

users is identity-global (one row per human across sites), so the rule that decides whether two addresses are the same account is set in two tiers. A site can only be stricter than the instance, never looser.

MethodPathAuthDescription
GET/api/v1/admin/email-identitysite-admin{ instanceMode, siteStrict, effective } for the active site
PUT/api/v1/admin/email-identity/instancebootstrap adminChange the instance mode — body { mode: "exact" | "root", dryRun? }
PUT/api/v1/admin/email-identity/sitesite-adminToggle per-site strict — body { strict: boolean, dryRun? }
  • Instance mode (exact default, root). exact keeps every distinct address as its own account. root makes one root mailbox one account instance-wide: +tag is stripped on every domain, and for Gmail the local part also loses its dots and googlemail.com folds to gmail.com. Stripping +tag on every domain is a policy choice, not a guarantee that the alias reaches the same mailbox (sub-addressing is a provider convention). It is chosen in the Setup Wizard (emailIdentityMode in the POST /api/v1/setup/complete body; omitted → exact) and changed later only by the bootstrap admin — a user principal, never an API key (403 FORBIDDEN otherwise).
  • Site strict (false default). Under exact, a strict site allows one membership per root mailbox, enforced by a unique index on (site_id, identity_key) rather than a check-then-insert. Under root the site flag is a no-op (effective: "root").
  • Tightening (exact → root, strict: false → true) first checks the existing data and answers 409 IDENTITY_COLLISION with the colliding accounts — nothing changes. Loosening always succeeds. dryRun: true runs the same transaction and rolls it back.
jsonc
// PUT /api/v1/admin/email-identity/instance  { "mode": "root" }  →  409
{ "errors": [{ "code": "IDENTITY_COLLISION",
               "message": "Existing accounts share a root mailbox; resolve them before tightening the policy.",
               "collisions": [{ "root": "[email protected]",
                                "accounts": [{ "userId": "u_1", "email": "[email protected]" },
                                             { "userId": "u_2", "email": "[email protected]" }] }] }] }

// …after resolving the duplicates  →  200
{ "data": { "previous": "exact", "current": "root", "changed": true, "dryRun": false } }

Every applied change writes an audit event (email_identity_mode_changed / site_email_identity_changed). Effects on the other endpoints:

  • POST /api/v1/auth/register keeps the identical generic 202 when the address — or, under root, any alias of it — already exists, or when a strict site already has a member with the same root mailbox. The account and its membership commit in one transaction, so a refused membership never leaves an orphan account.
  • POST /api/v1/auth/login, /forgot-password and /resend-verification resolve the account under the instance mode: under root, any alias reaches the account. Lockout is tracked on the resolved account row, so rotating aliases does not reset or dodge it.
  • POST /api/v1/users/invite looks the account up case-insensitively (and by root mailbox under root) and returns public fields only. Inviting an alias of an existing member of a strict site answers 409 EMAIL_IDENTITY_CONFLICT.
  • SCIM (/scim/v2/Users) answers 409 with scimType: "uniqueness" when the address resolves to an existing account or collides on a strict site.

External JWT authentication

A site can trust JWTs issued by an external IdP (Okta, Entra, Auth0, Logto, Keycloak, Cloudflare Access…). Present the token as Authorization: Bearer <jwt> with X-Lumi-Site. The auth chain verifies it against the issuer's public JWKS (between the API-key and internal-JWT branches): it matches the token's iss to a trusted issuer registered for that site, verifies the signature + aud/exp/nbf with the issuer's allowed (asymmetric-only) algorithms, maps role claims to LumiBase roles (default-deny — no mapping means 403, never implicit admin), enforces that any siteId claim equals the request site, and optionally JIT-provisions the user. A token whose iss isn't trusted is ignored (falls through to internal auth); once an issuer matches, verification is fail-closed.

Admin CRUD for trusted issuers (admin-only):

MethodPathDescription
GET/api/v1/admin/auth/issuersList trusted external issuers
POST/api/v1/admin/auth/issuersRegister an issuer
GET/api/v1/admin/auth/issuers/:idGet one
PATCH/api/v1/admin/auth/issuers/:idUpdate
DELETE/api/v1/admin/auth/issuers/:idRemove

Issuer config: { issuer, jwksUri | discoveryUrl, audience, algorithms (RS*/ES* only), claimMapping: { email, roles, siteId?, externalId? }, roleMapping: { "<claim role>": { roleId | systemKey } }, defaultRoleId?, jitProvisioning, clockSkewSeconds (≤300), enabled }. Errors: VALIDATION_FAILED (422, incl. an HS*/none algorithm), ISSUER_ALREADY_EXISTS (409), NOT_FOUND (404).

Login request:

json
{
  "email": "[email protected]",
  "password": "your-password"
}

Login response: a single bearer token plus the user profile. Send the token as Authorization: Bearer <token> on subsequent requests.

json
{
  "data": {
    "token": "eyJ...",
    "user": {
      "id": "usr_abc123",
      "email": "[email protected]",
      "firstName": "Admin",
      "lastName": "User",
      "avatar": null
    }
  }
}

For long-lived server-to-server access, create an API key (POST /api/v1/api-keys, token prefix lbk_) instead of using a login token.


1b. Organizations (ADR-013)

Organization requests use the authenticated identity and the target organization, without X-Lumi-Site. An organization key (lbo_) is bound to one organization and has its fixed admin role, except that it cannot change who holds authority: PATCH /orgs/:orgId, member writes and organization-key writes require a user session and return 403 ORGANIZATION_FORBIDDEN to a key. A key requests those changes through organization MCP, where a human approves them. Staff identities use current organization membership. Site keys (lbk_), publishable keys (lbk_pub_), and frontend sessions cannot enter this plane. Missing membership or a resource outside the selected organization returns 404 NOT_FOUND.

MethodEndpointAuthority / payload
GET/api/v1/orgsList the caller's organizations; an organization key returns exactly its organization
POST/api/v1/orgsBootstrap operator, or Studio user with LUMIBASE_ALLOW_ORG_SIGNUP=true; { name, slug }; caller becomes owner
GET/api/v1/orgs/:orgIdorg:read; includes the caller's role
PATCH/api/v1/orgs/:orgIdorg:settings:write; { name?, slug?, settings? }; only owner can change slug
DELETE/api/v1/orgs/:orgIdOwner; X-Confirm-Delete: <orgId>; organization must have no sites
GET/api/v1/orgs/:orgId/sitesorg:read
POST/api/v1/orgs/:orgId/sitesorg:sites:create; { name, id?, slug? }; id and slug must agree if both supplied
DELETE/api/v1/orgs/:orgId/sites/:siteIdOwner; X-Confirm-Delete: <siteId>
POST/api/v1/orgs/:orgId/sites/:siteId/transferThe same human must own both organizations; { toOrganizationId }
GET/api/v1/orgs/:orgId/membersorg:read
POST/api/v1/orgs/:orgId/membersorg:members:manage; { userId?, email?, role }; exactly one identity field
PATCH/api/v1/orgs/:orgId/members/:userIdorg:members:manage; { role }
DELETE/api/v1/orgs/:orgId/members/:userIdorg:members:manage
GET/api/v1/orgs/:orgId/keysorg:read; metadata only
POST/api/v1/orgs/:orgId/keysorg:keys:manage; { name, description?, expiresAt? }; plaintext returned at creation
POST/api/v1/orgs/:orgId/keys/:keyId/rotateorg:keys:manage; old token stops working; plaintext returned at rotation
DELETE/api/v1/orgs/:orgId/keys/:keyIdorg:keys:manage; revoke the key
GET/api/v1/orgs/:orgId/approvalsHuman owner/admin only; summaries omit result secrets
GET/api/v1/orgs/:orgId/approvals/:approvalIdHuman owner/admin only; a minted key is never stored or returned again (tokenRedacted: true)
POST/api/v1/orgs/:orgId/approvals/:approvalId/decideHuman owner/admin; { decision: "approved" } / { decision: "rejected" }; operation-specific owner checks still apply; approving org:create_org_key returns the plaintext key in this response only

Create operations return 201, other successful operations return 200, using the standard data envelope. Organization roles are owner, admin, billing, and member. Admins cannot add/change/remove owners; the final owner cannot be removed or demoted. Owner/admin inherit site administrator authority on owned sites; billing/member do not. Organization keys are always admin and can never execute owner-only operations themselves. A member email that has no identity creates an invited identity; organization membership is separate from the staff account activation flow.

Site creation uses the same provisioning as setup. settings replaces the settings object when supplied, so preserve unrelated fields. Slug default can be renamed by its owner and is then available again. POST /api/v1/api-keys remains site-scoped and rejects scope="organization"; an organization key may mint site keys only for sites in its organization.

Organization MCP approvals

Organization MCP is off until settings.contentOs.mcp.allowOrganizationTools=true; LUMIBASE_MCP_ORG_TOOLS=off overrides it. Every organization mutation creates a pending approval with a real organization parent. confirm=true cannot approve it, and no REST fallback exists for these MCP tools. The agent receives pending_approval, approvalId, organizationId, and a run id; it never receives a newly minted organization key.

Approval rechecks live requester access and the human decider's authority. Execution and the receipt commit atomically. Repeating the same decision returns the existing receipt; a conflicting decision returns 409 APPROVAL_ALREADY_DECIDED. A revoked requester cannot be approved (409 REQUESTER_REVOKED), but can be rejected. Deleting a transfer destination does not prevent rejecting its pending request or replaying an already committed receipt. Pending transfer execution still requires both organizations and their human owner. Disabling MCP blocks approval (403 MCP_DISABLED) without blocking rejection. Discovery with MCP disabled returns 404 MCP_DISABLED. See Organization settings and MCP.

Organization errors additionally include 400 VALIDATION, 400 SCOPE_NOT_ALLOWED, 403 ORGANIZATION_FORBIDDEN, 403 ORG_SIGNUP_DISABLED, 403 SITE_NOT_IN_ORGANIZATION, 404 NOT_FOUND, 409 LAST_OWNER, 409 ORGANIZATION_NOT_EMPTY, and 409 CONFLICT.


2. Schema Admin

Collections

MethodPathDescription
GET/api/v1/collectionsList all collections
POST/api/v1/collectionsCreate a new collection
GET/api/v1/collections/:nameGet collection detail
PATCH/api/v1/collections/:nameUpdate collection meta (display name, icon, note)
DELETE/api/v1/collections/:nameSoft-delete collection
GET/api/v1/collections/:name/schemaExport collection schema as JSON
PUT/api/v1/collections/:name/schemaApply schema (idempotent, diff-aware)
POST/api/v1/collections/diffCompare bundle schema vs current
GET/api/v1/collections/:name/index-advice?path=&cast=JSON path index advisor (read-only, schema:read)
GET/api/v1/collections/:name/form-layoutItem form layout: tabs, groups, dividers, conditions (schema:read); see Form layout
PUT/api/v1/collections/:name/form-layoutReplace (or with null remove) the form layout (schema:update)

Create collection request:

json
{
  "name": "articles",
  "displayName": "Articles",
  "icon": "article",
  "note": "Blog articles",
  "singleton": false,
  "status_field": "status",
  "sort_field": "sort"
}

JSON path index advisor

GET /api/v1/collections/:name/index-advice?path=<dot.path>[&cast=numeric|boolean|timestamp|text] returns CREATE INDEX DDL whose expression matches exactly what the filter builder emits for that path and cast, so Postgres can use it for typed _eq/_in/range filters. The index is partial on the collection (WHERE collection_id = … AND deleted_at IS NULL). cast defaults to the declared type of a top-level field; it is required for nested or json paths. The endpoint never runs the DDL: an operator reviews it and runs it outside a transaction (CONCURRENTLY). timestamp returns ddl: null, because timestamptz casts are not IMMUTABLE and Postgres refuses to index them.

json
{
  "data": {
    "path": "price",
    "cast": "numeric",
    "indexName": "items_products_price_numeric_idx",
    "expression": "(case when (data ->> 'price') ~ '…' then (data ->> 'price')::numeric end)",
    "ddl": "CREATE INDEX CONCURRENTLY IF NOT EXISTS items_products_price_numeric_idx ON lumibase_items ((…)) WHERE collection_id = '…' AND deleted_at IS NULL;",
    "notes": ["Run outside a transaction (CONCURRENTLY).", "…"]
  }
}

Errors: 400 VALIDATION (missing/invalid path, unknown cast, or no cast for a nested path), 404 NOT_FOUND (collection or top-level field).

Fields

MethodPathDescription
GET/api/v1/fields/:collectionList fields in a collection
POST/api/v1/fields/:collectionAdd a field
GET/api/v1/fields/:collection/:fieldGet field detail
PATCH/api/v1/fields/:collection/:fieldUpdate field config
DELETE/api/v1/fields/:collection/:fieldRemove field

Create field request:

json
{
  "field": "title",
  "type": "string",
  "interface": "input",
  "display": "raw",
  "options": { "placeholder": "Article title" },
  "required": true,
  "sort": 1
}

Relations

MethodPathDescription
GET/api/v1/relationsList all relations
POST/api/v1/relationsCreate relation
PATCH/api/v1/relations/:idUpdate relation
DELETE/api/v1/relations/:idRemove relation

Code-First Configuration (Config Manifest)

Export / diff / apply a site's schema configuration — collections, fields, relations, settings and webhooks — as a single declarative, version-controllable JSON manifest (lumibase.config@v1). Built for CI/CD and environment sync (à la Directus schema snapshot/apply). Admin-only. Does not include content items, secrets, or access control (use /api/v1/access/* for the latter).

MethodPathDescription
GET/api/v1/config/export?scope=all|schema|settings|webhooksExport the config manifest
POST/api/v1/config/import?dryRun=true&mode=<mode>Validate + diff a manifest (no write)
POST/api/v1/config/import?mode=<mode>&allowDestructive=trueApply a manifest in one transaction

mode ∈ merge (create/update only — never deletes), replace-managed (also deletes resources within the manifest's managedScopes), replace-all (full sync — deletes anything absent from the manifest). High-risk destructive changes (dropping a collection/field with data, changing a field type, widening a relation's onDelete to cascade) are rejected unless allowDestructive=true.

Export response ({ data: ConfigManifest }):

json
{
  "data": {
    "version": "lumibase.config@v1",
    "exportedAt": "2026-06-22T00:00:00.000Z",
    "collections": [{ "name": "articles", "label": "Articles", "versioning": true }],
    "fields": [{ "collection": "articles", "field": "title", "type": "string", "interface": "input" }],
    "relations": [],
    "webhooks": [],
    "settings": [{ "key": "login_security_policy", "value": { } }],
    "managedScopes": ["articles"]
  }
}

Dry-run / apply response ({ data: { valid, errors, diff, applied? } }): the diff lists per-resource create | update | unchanged | delete counts and a top-level risk (low | medium | high). On apply, applied reports { created, updated, deleted }. Validation errors use codes UNSUPPORTED_MANIFEST_VERSION, DANGLING_REFERENCE, DUPLICATE_KEY; a blocked destructive apply returns HTTP 409 DESTRUCTIVE_BLOCKED.

CLI: pnpm --filter @lumibase/cms config export|diff|apply — see docs/en/contributing/code-first-config.md.


3a. Pages (Delivery page-builder rows)

Studio-authenticated CRUD over lumibase_pages (consumed by GET /api/v1/deliver/page/:site_id/:slug). Create and slug rename clear matching negative-cache tombstones immediately.

MethodPathDescription
GET/api/v1/pagesList pages for the active site
POST/api/v1/pagesCreate { slug, title, layoutConfig? }
GET/api/v1/pages/:idGet one page
PATCH/api/v1/pages/:idPartial update (slug / title / layoutConfig)
DELETE/api/v1/pages/:idDelete page

Slug shape matches the Delivery guard (^[a-z0-9]+(?:[/_-][a-z0-9]+)*$, ≤200).

Admin cache purge (control-plane): POST /api/v1/utils/cache/purge with { tags?: string[], keys?: string[] } — every tag/key must include the active siteId.


3. Items (Generic CRUD)

MethodPathDescription
GET/api/v1/items/:collectionList items (paginated, filterable)
POST/api/v1/items/:collectionCreate item (or array for bulk)
GET/api/v1/items/:collection/exportStream the collection as CSV or JSON (Data export)
GET/api/v1/items/:collection/:idGet single item
PATCH/api/v1/items/:collection/:idPartial update
PUT/api/v1/items/:collection/:idFull replace
DELETE/api/v1/items/:collection/:idDelete item — 409 if blocked by dependents
GET/api/v1/items/:collection/:id/dependentsList records that reference this item
POST/api/v1/items/:collection/:id/resolve-dependentsBatch-resolve a relation's dependents
POST/api/v1/items/:collection/:id/moveMove an item and its subtree in a tree collection; list with ?tree=children|subtree|ancestors (Hierarchical collections)
GET/api/v1/items/:collection/:id/revisionsList revisions
POST/api/v1/items/:collection/:id/revertRevert to revision
GET/api/v1/items/:collection/:id/versionsList named draft versions (each has a mainChanged flag)
POST/api/v1/items/:collection/:id/versionsCreate a version { key, name } (snapshots current main)
GET/api/v1/items/:collection/:id/versions/:keyGet a version
PATCH/api/v1/items/:collection/:id/versions/:keyUpdate a version { data?, name? } (does not touch main)
DELETE/api/v1/items/:collection/:id/versions/:keyDelete a version
GET/api/v1/items/:collection/:id/versions/:key/compareField diff vs main → { main, version, changes }
POST/api/v1/items/:collection/:id/versions/:key/promoteApply version to main (writes a revision); meta.mainDiverged

Dependent records. Because item references live in JSONB (not physical FK columns), a relation's onDelete is enforced in the application layer. On DELETE, if a relation declared restrict still has records pointing at the item, the delete is blocked with 409 DEPENDENT_RECORDS_EXIST and a dependents array. (set null/cascade are not auto-applied on soft-delete — that would break soft-delete's recoverability; the editor clears them explicitly.) GET …/dependents returns { data: { blocking, dependents: [{ relation, collection, field, onDelete, count, sample }] } }. POST …/resolve-dependents takes { action: "set_null"|"delete"|"reassign", relation, newTargetId?, hard? } and runs transactionally (delete delegates to the normal item-delete path). Errors: DEPENDENT_RECORDS_EXIST (409), FIELD_REQUIRED (409, set_null on a required field), INVALID_TARGET (422, reassign), NOT_FOUND (404).

Export. GET /items/:collection/export?format=csv|json&fields=&locales=&relations=id|slug|embed&filter=&sort=&status= streams every matching row (keyset-paged, so any size). It uses the caller's read permission and the list filter/sort syntax, runs the extensions' items.export.before hook per row, and writes an items_exported audit entry. CSV writes one field.locale column per locale of a translatable field and neutralises spreadsheet formulas; JSON is { collection, format: "lumibase-export@1", exportedAt, fields, locales, relations, items: [{ id, status, sort, created_at, updated_at, data }] }. Errors before streaming: 400 VALIDATION / 400 UNKNOWN_FIELD / 400 INVALID_FILTER, 403 FORBIDDEN, 404 NOT_FOUND. See Data export.

Imports. Background jobs that read the export formats back:

MethodPathDescription
POST/api/v1/imports?collection=&format=csv|json&mode=create|upsertUpload a file (multipart file or raw body) → 202 { data: job }
GET/api/v1/imports?collection=&status=&limit=Recent jobs (own; site admins see all)
GET/api/v1/imports/:idJob progress and counters
GET/api/v1/imports/:id/errorsRow errors; ?format=csv downloads them
POST/api/v1/imports/:id/cancelStop a queued or running job

Bad files fail with 400 VALIDATION / 413 PAYLOAD_TOO_LARGE before a job is created; missing create (or update for upsert) permission is 403. See Data import.

List pagination & totals. GET /items/:collection accepts limit (1–200, default 25), offset, and meta:

  • meta=total_count (default) — response is { data, meta: { total, limit, offset } }.
  • meta=none — skips the count(*) aggregate for a cheaper query; response is { data, meta: { limit, offset } } (no total). Use for infinite-scroll / feed views that never render a total page count.

The default is unchanged, so existing clients keep receiving meta.total. The @lumibase/sdk readItems accepts the same meta option.

Optional headers:

  • X-Lumi-Draft: true — fetch draft version
  • X-Lumi-Locale: vi — apply translation server-side

Create item:

json
{ "title": "Hello World", "status": "draft", "author": "usr_abc123" }

Bulk create (array body):

json
[
  { "title": "Article 1", "status": "published" },
  { "title": "Article 2", "status": "draft" }
]

3b. Content Releases

A Release collates specific item revisions across collections into a named bundle that publishes all at once — manually or scheduled for a date/time (à la Directus Releases). Publish delegates to the item update path, so the editorial gate, validation, permissions and hooks all apply.

MethodPathDescription
POST/api/v1/releasesCreate a release (draft, or scheduled if publishAt set)
GET/api/v1/releasesList releases (?status=&page=&limit=)
GET/api/v1/releases/:idRelease detail + its items
PATCH/api/v1/releases/:idUpdate meta, addItems/removeItems, set publishAt
POST/api/v1/releases/:id/publishPublish now (manual)
DELETE/api/v1/releases/:idDelete release (items cascade)

Create / patch body:

json
{
  "name": "Spring launch",
  "atomicityMode": "all_or_nothing",
  "publishAt": "2026-07-01T09:00:00Z",
  "maintenanceWindow": { "windows": [{ "dow": 1, "start": "09:00", "end": "17:00" }] },
  "addItems": [
    { "collection": "articles", "itemId": "itm_1", "targetStatus": "published", "revisionId": "rev_3" }
  ]
}

atomicityMode: all_or_nothing (pre-flight checks every item is publishable — exists, not deleted, editorial gate satisfiable — and publishes nothing if any is blocked) or best_effort (publishes each independently, recording a per-item outcome). revisionId pins a specific revision's snapshot; omit it to publish the item's live state at publish time.

Publish response ({ data: { release, status, outcomes } }): status is published | partially_failed | failed; each outcome is { collection, itemId, outcome: 'published'|'skipped'|'failed', reason? }. A partial/failed publish still returns HTTP 200 with the outcomes.

Error codes: EMPTY_RELEASE (422), ALREADY_PUBLISHED (409), RELEASE_IMMUTABLE (409, editing a published release's items), ITEM_NOT_FOUND (404), REVISION_STAGED (409, pinning an uncommitted revision), VALIDATION_FAILED (422, incl. publishAt in the past). Per-item publish blockers surface as outcome reasons EDITORIAL_GATE_REQUIRED / ITEM_DELETED.

Scheduled releases publish via the shared content-scheduler tick (sweepDueReleases) — idempotent and maintenanceWindow-aware.


4. Permissions, Roles & Policies

MethodPathDescription
GET/api/v1/permissions/meEffective permission matrix for current user
POST/api/v1/permissions/checkDebug: evaluate a policy rule
GET/POST/PATCH/DELETE/api/v1/rolesRole CRUD
GET/POST/PATCH/DELETE/api/v1/policiesPolicy CRUD
GET/POST/DELETE/api/v1/policies/:id/permissionsPermission rules in a policy
POST/api/v1/policies/:id/attachAttach policy to a role, user, or team

Permission rule shape:

json
{
  "collection": "articles",
  "action": "read",
  "fields": ["id", "title", "status"],
  "conditions": { "status": { "_eq": "published" } }
}

5. Users & Teams

MethodPathDescription
GET/POST/api/v1/usersList / create users
GET/PATCH/DELETE/api/v1/users/:idGet / update / delete user
POST/api/v1/users/inviteSend invitation email
POST/api/v1/users/:id/impersonateImpersonate (admin only)
GET/api/v1/users/:id/sessionsList active sessions
DELETE/api/v1/sessions/:idRevoke a session
GET/POST/PATCH/DELETE/api/v1/teamsTeam CRUD

6. Files & Assets

MethodPathDescription
POST/api/v1/files/presigned-urlGet presigned R2/S3 PUT URL
POST/api/v1/filesRegister file metadata after upload
GET/api/v1/filesList files (filterable)
GET/api/v1/files/:idFile metadata
PATCH/api/v1/files/:idUpdate metadata (title, tags, folder)
DELETE/api/v1/files/:idDelete file
GET/api/v1/assets/:idServe/transform image (query params below)
POST/api/v1/media/:keyUpload raw media bytes (RBAC media:create; upload guard applies)
GET/api/v1/media/:keyDownload media (served as attachment + nosniff); with transform params → 302 to derivative
DELETE/api/v1/media/:keyDelete media object
GET/api/v1/transform-presetsList named image-transform presets (RBAC media:read)
POST/api/v1/transform-presetsCreate a preset { key, name, dsl } (RBAC media:create)
PATCH/api/v1/transform-presets/:idUpdate a preset (RBAC media:update)
DELETE/api/v1/transform-presets/:idDelete a preset (RBAC media:delete)
GET/api/v1/uploads/configEffective upload policy + type catalogue (any member)
PUT/api/v1/uploads/configUpdate allowlist / size cap (site admin)

Image transform DSL (/api/v1/media/:key and /api/v1/assets/:id):

code
?width=800&height=600&format=webp&quality=80&fit=cover&focal=0.5,0.5
?preset=thumbnail

On /media/:key, transform params are validated against transformDslSchema (@lumibase/contracts; MAX_DIM=5000) and the request 302-redirects to the runtime image URL (CF Image Resizing / Imgproxy). No params → the original bytes. ?preset=<key> resolves a saved transform_presets row for the site. See .kiro/specs/image-transform-dsl.

Upload policy (/api/v1/uploads/config). Enforced by the file-upload-policy guard on every upload surface (POST /api/v1/files, PUT /api/v1/files/upload/:key, POST /api/v1/media/:key): a public role cannot upload; the body is size-capped on its true byte length; the declared MIME must be in the allowlist and match the filename extension; raw bytes are content-sniffed (magic bytes) and executables / active-content SVGs are rejected; raster images are scanned for an embedded script/executable payload (polyglot) and rejected. The allowlist + cap resolve per-site DB (settings key upload_policy) → env (FILE_UPLOAD_*) → default. See the feature spec .kiro/specs/upload-file-controls/ and docs/en/security/runtime-security-guards-plan.md §3 for the full guarantees.

code
GET  /api/v1/uploads/config
→ { data: { maxBytes, allowedMimeTypes[], allowedExtensions[], catalogue[] } }

PUT  /api/v1/uploads/config           # site admin only
{ "maxBytes": 5242880, "allowedMimeTypes": ["image/png","image/jpeg"] }

6b. View presets (collection views + bookmarks)

MethodPathDescription
GET/api/v1/presets/effective?collection=Effective default view (precedence user > role-chain > global), with sourceScope
GET/api/v1/presets/bookmarks?collection=Named bookmarks visible to the principal, each with sourceScope
GET/api/v1/presetsList presets (optional ?collection=)
POST/api/v1/presetsCreate a preset/bookmark; user-scope self-managed, role/global require admin
PATCH/api/v1/presets/:idUpdate (authorized against the row's current scope)
DELETE/api/v1/presets/:idDelete (user owns own; role/global require admin)

Scope is derived from ownership columns: userId set → user, roleId set → role, neither → global. Role presets inherit down the roles.parentId chain. See .kiro/specs/presets-inheritance.

6c. Translation memory

MethodPathDescription
GET/api/v1/tm?source=&target=&entrySource=&limit=&offset=List TM entries (paginated; meta { total, limit, offset })
POST/api/v1/tmUpsert an entry
PATCH/api/v1/tm/:idEdit target/quality/source (siteId-scoped, 404 cross-tenant)
DELETE/api/v1/tm/:idDelete an entry (siteId-scoped)
POST/api/v1/tm/lookupBest fuzzy match { query, sourceLang, targetLang, threshold? } → { match }
POST/api/v1/tm/translateMT pipeline { text, from, to } (TM → glossary → provider)

TM_DEFAULT_THRESHOLD = 75 (@lumibase/contracts). Learn-TM (Studio) upserts human translations on save when translations.learnTm is enabled. See .kiro/specs/translation-memory-ui.


7. Flows / Automation

MethodPathDescription
GET/api/v1/flows/operationsRegistered operation keys + option hints (editor palette / validateGraph knownKeys)
GET/api/v1/flowsList flows (filter by status, trigger)
POST/api/v1/flowsCreate a new flow (validates graph when active; schedule flows require a valid cron)
GET/api/v1/flows/:idGet flow detail + graph
PATCH/api/v1/flows/:idUpdate flow (graph, status, options)
DELETE/api/v1/flows/:idDelete flow
POST/api/v1/flows/:id/runManual trigger with body as input
POST/api/v1/flows/:id/triggerWebhook trigger — no CMS session; authenticate with the per-flow token (x-flow-token header or Bearer), compared constant-time. Input = { body, headers, query } (credential headers stripped). 404 for non-webhook/inactive flows; 401 WEBHOOK_NOT_CONFIGURED/UNAUTHENTICATED
GET/api/v1/flows/:id/runsExecution history
GET/api/v1/flows/:id/runs/:runIdSingle run detail (steps output)

Save-time gates: an active flow must pass the shared graph validation — 400 with GRAPH_DANGLING_EDGE / GRAPH_CYCLE / GRAPH_NO_ENTRY / GRAPH_UNKNOWN_OPERATION (+ nodeId) otherwise; drafts may hold invalid work-in-progress. Schedule flows validate triggerOptions.cron (5-field, UTC): 400 CRON_INVALID on a malformed expression, 400 CRON_REQUIRED when activating without one; next_run_at is computed on save and advanced by the scheduler sweep before each enqueued run (idempotent).

Triggers: event flows fire on item create/update/delete via the flow-events queue (triggerOptions.collection / .action filter, string or array, missing = all); schedule flows are swept every scheduler tick; webhook flows use the endpoint above; manual runs inline via /run.

Trigger a flow:

bash
POST /api/v1/flows/flw_abc123/run
Content-Type: application/json
Authorization: Bearer <token>

{ "userId": "usr_xyz", "action": "welcome" }

Response:

json
{
  "data": {
    "runId": "run_def456",
    "status": "running",
    "startedAt": "2026-06-07T00:00:00Z"
  }
}

7c. Deployments

Per-site deployment targets (Vercel / Netlify), manual deploy triggers, build status and logs (spec deployment-integrations), plus environments, promotion and deploy approvals (#743, see docs/en/features/deployment-environments.md). Every route except the inbound webhook needs a site admin or a deploy:* capability (lumibase_deploy:<scope> permission rows): 400 TENANT_REQUIRED without a resolved site, 403 FORBIDDEN without either. Target create/update/delete, PUT /environments and GET /:id/logs stay site-admin only (requireSiteAdmin). Provider tokens are encrypted on write and never returned. Bodies are validated with DeploymentTargetCreateSchema / DeploymentTargetUpdateSchema / DeployTriggerSchema (@lumibase/contracts); a failed parse returns 400 VALIDATION. 400 UNKNOWN_PROVIDER means the stored target names a provider that is not registered in this deployment (only vercel and netlify are).

MethodPathDescription
GET/api/v1/deployments/targetsList targets for the site (token columns omitted)
POST/api/v1/deployments/targetsCreate { provider (vercel|netlify), name, projectId, token, defaultBranch?, productionUrl? } → 201. The token is verified against the provider before anything is stored: 400 TOKEN_INVALID
PATCH/api/v1/deployments/targets/:idUpdate { name?, projectId?, token?, defaultBranch?, productionUrl?, status? (active|inactive) }. A token is re-verified and re-encrypted (rotation). 404 NOT_FOUND, 400 TOKEN_INVALID, 400 UNKNOWN_PROVIDER (only when a token is sent)
DELETE/api/v1/deployments/targets/:idDelete a target (its deployments cascade) → { data: null }. 404 NOT_FOUND
POST/api/v1/deployments/targets/:id/deployTrigger a build { branch?, reason? } → 201 with the new deployment row (triggerSource: "manual"). Needs deploy:trigger:<targetId>, deploy:trigger:<env> of an environment containing it, or deploy:trigger:*; when one of those environments has requiresApproval the response is 202 { data: { status: "pending_approval", environment, approval } } and nothing is dispatched. 403 FORBIDDEN, 404 NOT_FOUND, 400 TARGET_INACTIVE, 400 UNKNOWN_PROVIDER, 429 RATE_LIMITED, 502 TRIGGER_FAILED (provider call failed; an error row is still recorded)
GET/api/v1/deploymentsList deployments, newest first (createdAt descending, id descending as tie-breaker). Filter ?targetId=&status=&limit=. limit must be a non-negative integer: it defaults to 50 when absent or empty, 0 returns an empty list, and values above 200 are capped at 200. Any other value (abc, -5, 1.5) returns 400 VALIDATION. No meta
GET/api/v1/deployments/:idGet one deployment. 404 NOT_FOUND
GET/api/v1/deployments/:id/logsFetch the build log from the provider, secrets masked → { data: { log } }. 404 NOT_FOUND when the deployment does not exist or has no provider id yet, 400 UNKNOWN_PROVIDER when its target or provider is unavailable
POST/api/v1/deployments/:id/refreshForce a status sync from the provider (no-op once the status is terminal). 404 NOT_FOUND when the deployment does not exist. With no provider id yet, or with an unavailable target or provider, the row is returned unchanged (200, never UNKNOWN_PROVIDER)
GET/api/v1/deployments/accessThe caller's { admin, capabilities, humanDecider, environments: [{ key, canTrigger, canApprove }] }
GET/api/v1/deployments/environmentsThe environment map (settings key deployment.environments, defaults preview / staging → production / production with requiresApproval). 500 ENVIRONMENTS_INVALID when the stored map does not validate
PUT/api/v1/deployments/environmentsSite admin. Replace the map { environments: [{ key, name, targetIds, requiresApproval, promotesTo }] } (DeploymentEnvironmentsUpdateSchema). 400 VALIDATION (duplicate key, unknown promotesTo), 400 UNKNOWN_TARGET
POST/api/v1/deployments/environments/:key/deployDeploy every target of the environment { branch?, reason? }. Needs deploy:trigger:<key> (or on every target, or *). 201 { data: { status: "dispatched", environment, results: [{ targetId, ok, deployment, error? }] } }, or 202 { data: { status: "pending_approval", environment, approval } } when requiresApproval. 403 FORBIDDEN, 404 ENVIRONMENT_NOT_FOUND, 409 NO_TARGETS
POST/api/v1/deployments/environments/:key/promotePromote the environment's newest ready deployment (or { deploymentId }) into its promotesTo environment { deploymentId?, reason? }; same build where the provider can promote, else the same commit re-triggered. Needs the trigger grant on the destination. 201 / 202 as above. 404 NOT_FOUND (deployment not in the environment), 409 NO_PROMOTION_TARGET, 409 SOURCE_NOT_READY
GET/api/v1/deployments/approvalsDeploy approvals, newest first, default ?status=pending (status=all for every status), each with canDecide for the caller
POST/api/v1/deployments/approvals/:id/decide{ decision: "approved" | "rejected", reason? } (DeployApprovalDecisionSchema). Approve needs a signed-in person, not the requester, holding deploy:approve:<env> or deploy:approve:*; the requester may reject (withdraw) their own. 403 HUMAN_APPROVER_REQUIRED / SELF_APPROVAL_FORBIDDEN / FORBIDDEN, 404 NOT_FOUND, 409 APPROVAL_ALREADY_DECIDED / APPROVAL_EXPIRED / REQUESTER_REVOKED / PLAN_STALE

Public (no session; signature-verified):

MethodPathDescription
POST/api/v1/deployments/webhook/:provider/:siteIdInbound status webhook (vercel | netlify) with path tenant (works on the shared API host without X-Lumi-Site). 404 UNKNOWN_PROVIDER, 400 TENANT_INVALID / TENANT_MISMATCH, 401 INVALID_SIGNATURE; otherwise 200 { data: null }, including when the body matches no deployment
POST/api/v1/deployments/webhook/:providerInbound status webhook (vercel | netlify). Tenant comes from withTenant (X-Lumi-Site or host mapping). 404 UNKNOWN_PROVIDER, 401 INVALID_SIGNATURE; otherwise 200 { data: null }, including when the body matches no deployment

Target shape (data of the target routes): { id, provider, name, projectId, defaultBranch, productionUrl, status, createdAt, updatedAt }.

Deployment shape (data of the deployment routes and the trigger): { id, siteId, targetId, provider, providerDeploymentId, status (queued|building|ready|error|canceled), branch, commitSha, commitMessage, url, triggeredBy, triggerSource (manual|auto|agent), errorMessage, logExcerpt, createdAt, updatedAt, completedAt }.

Trigger rate limit: each target has a two-tier budget, 5 triggers per 60 s and 30 per 3600 s, keyed by site and target (apps/cms/src/services/deployment/trigger-rate-limit.ts). It applies to every triggerSource (manual, auto, agent). A coalesced auto trigger reuses a recent build and does not consume budget. When the limiter backend is unreachable the trigger is allowed (fail-open). A rejected trigger creates no row and returns:

json
{
  "errors": [
    {
      "code": "RATE_LIMITED",
      "message": "Too many deploy triggers for this target. Please try again later.",
      "retryAfterSeconds": 42
    }
  ]
}

with a matching Retry-After: 42 header.

Webhook signatures: the secret is the per-site setting deployment.webhook.<provider> (value { "secret": "…" }), never a request header. An empty or missing secret rejects every request (fail-closed). Vercel sends x-vercel-signature, the lowercase hex HMAC-SHA1 of the raw body. Netlify sends x-webhook-signature, a compact JWS (HS256) whose sha256 claim must equal the SHA-256 hex digest of the raw body (a JWS whose payload is the raw body itself is also accepted). Both comparisons are constant-time.

Trigger a deploy:

bash
POST /api/v1/deployments/targets/dpt_abc123/deploy
Content-Type: application/json
Authorization: Bearer <token>
X-Lumi-Site: <siteId>

{ "branch": "main", "reason": "Homepage copy update" }

Response (201, abridged):

json
{
  "data": {
    "id": "dep_def456",
    "targetId": "dpt_abc123",
    "provider": "vercel",
    "status": "queued",
    "branch": "main",
    "triggerSource": "manual"
  }
}

8. AI Copilot

MethodPathDescription
POST/api/v1/ai/chatSend natural-language instruction to AI Copilot
GET/api/v1/ai/approvalsList pending HITL approvals
POST/api/v1/ai/approvals/:id/decideApprove or reject a pending action
GET/api/v1/ai/conversationsList conversation history
GET/api/v1/ai/conversations/:id/messagesGet messages in a conversation
DELETE/api/v1/ai/conversations/:idDelete a conversation
POST/api/v1/ai/decisionsAsk the decision model (TypeSafe Jev or equivalent) typed questions
GET/api/v1/ai/review-profilesList active draft review profiles (?collection=)
GET/api/v1/ai/review-profiles/:keyGet a review profile (?version= for an older one)
POST/api/v1/ai/review-profilesCreate version 1 of a review profile (admin)
POST/api/v1/ai/review-profiles/:key/versionsPublish the next version of a review profile (admin)
POST/api/v1/ai/reviewsReview an item or an unsaved draft with a profile (suggest-only)
GET/api/v1/ai/reviews?collection=&itemId=List the review runs of an item
GET/api/v1/ai/reviews/:idGet a review run with its staleness
POST/api/v1/ai/reviews/:id/feedbackRecord accept / edit / reject on a run's answers
GET/api/v1/ai/reviews/rollout?collection=Draft-review pilot mode of a collection: off, baseline or assisted
POST/api/v1/ai/reviews/sessionsRecord one editor review session on a pilot collection (timing)
GET/api/v1/ai/reviews/metrics?from=&to=Draft-review pilot metrics (admin)
GET/api/v1/ai/automation/templatesJev automation flow templates (admin)
POST/api/v1/ai/automation/templates/:key/buildBuild a draft manual flow from a template; writes nothing (admin)
GET/api/v1/ai/automation/actionsAutomation action history with its audit chain (admin)
GET/api/v1/ai/automation/actions/:idOne automation action with its audit chain (admin)
POST/api/v1/ai/automation/actions/:id/feedbackAccept / override / reject the decision behind an action (admin)
POST/api/v1/ai/automation/actions/:id/revertRestore the value before an applied action (admin)
GET/api/v1/ai/automation/metrics?from=&to=Shadow precision and coverage in the auto-action zone (admin)

Chat request:

json
{ "message": "Create a collection called 'products' with title, price, and status fields" }

Safe skill response:

json
{
  "data": {
    "status": "executed",
    "data": { "collectionName": "products", "fieldsCreated": 3 }
  }
}

HITL required (dangerous skill) response:

json
{
  "data": {
    "status": "pending_approval",
    "approvalId": "apr_ghi789",
    "message": "Creating a collection requires admin approval."
  }
}

Decide on an approval:

json
{ "decision": "approved" }

Decision request (POST /api/v1/ai/decisions) — Experimental in 1.0.0 (along with /api/v1/ai/review-profiles*, /api/v1/ai/reviews*, and /api/v1/ai/automation*; outside the 1.0 semver freeze per contributing/versioning-policy.md until live-data validation #548 completes). 1–32 questions keyed by [A-Za-z0-9_-]{1,64}; noul = yes/no, choice = 2–255 options, score = 2–10 rubric levels (lowest first). state is a string, object or array. The whole request (state, instructions, criteria and nesting) must fit the input budget: ≤ DECISION_MAX_INPUT_BYTES UTF-8 bytes (default 131,072) and ≤ DECISION_MAX_INPUT_TOKENS estimated tokens (default 24,000), checked before the provider is called. Read-only, so no HITL approval:

json
{
  "state": { "title": "Summer sale", "body": "Buy now!!!" },
  "questions": {
    "spam": {
      "type": "noul",
      "instructions": "Is this post spam?",
      "criteria": { "true": "spam", "false": "legitimate" }
    },
    "topic": {
      "type": "choice",
      "instructions": "Pick the topic",
      "criteria": { "promo": "Promotion", "news": null }
    },
    "quality": {
      "type": "score",
      "instructions": "Rate editorial quality",
      "criteria": ["poor", "ok", "great"]
    }
  }
}

Decision response — calibrated is false when DECISION_PROVIDER=llm, because those probabilities are self-reported by the LLM. usage.inputTokens / usage.outputTokens are null when the provider did not report them (unknown, never a made-up 0):

json
{
  "data": {
    "provider": "typesafe",
    "model": "jev-1.13",
    "calibrated": true,
    "answers": {
      "spam": { "type": "noul", "noul": 0.12 },
      "topic": { "type": "choice", "choice": "promo", "probabilities": { "promo": 0.9, "news": 0.1 }, "confidence": 0.9 },
      "quality": { "type": "score", "score": 1.4, "legend": { "0": "poor", "1": "ok", "2": "great" }, "probabilities": { "0": 0, "1": 0.6, "2": 0.4 }, "confidence": 0.6 }
    },
    "usage": { "inputTokens": 120, "outputTokens": 0 }
  }
}

Errors: 403 FORBIDDEN (no ai:decide, or the caller is a publishable API key or a frontend session), 403 DECISION_DISABLED, 422 DECISION_FIELD_NOT_ALLOWED, 429 DECISION_QUOTA_EXCEEDED / DECISION_CONCURRENCY_LIMITED, 503 DECISION_QUOTA_UNAVAILABLE (see Governance below), 400 VALIDATION, 413 DECISION_INPUT_TOO_LARGE (over the byte or token budget; the message gives sizes only), 503 DECISION_NOT_CONFIGURED (no DECISION_PROVIDER), 429 DECISION_RATE_LIMITED, 503 DECISION_UNAVAILABLE (upstream overloaded or unreachable), 504 DECISION_TIMEOUT, 499 DECISION_CANCELLED (the client closed the request), 422 DECISION_VALIDATION, 502 DECISION_AUTH / DECISION_UPSTREAM / DECISION_PARSE_FAILED.

Deadlines and retries: one decision has a total deadline (DECISION_TIMEOUT_MS, default 20 s) that includes every retry and backoff, and each upstream attempt has its own timeout (DECISION_ATTEMPT_TIMEOUT_MS, default 8 s, capped by what remains of the deadline). Only 429/503/529, network errors and attempt timeouts are retried, at most DECISION_MAX_RETRIES times (default 2), with full-jitter exponential backoff that honours Retry-After. A wait that would run past the deadline is not started. Auth, validation and parse failures are never retried. When the client disconnects, the in-flight upstream call is aborted and no retry follows. The llm provider is bounded by the same deadline and budget but makes a single call; the deadline and a client disconnect abort that LLM request.

The token count is an estimate, not the provider's tokenizer: about 4 ASCII characters per token, and every non-ASCII code point (e.g. Vietnamese diacritics) as one token. It over-counts on purpose; the 24,000 default leaves 25% headroom under Jev's 32,000-token context.

The CMS validates upstream answers before returning them: required values must be finite and in range, Choice/Score distributions must include exactly the declared options/levels and sum to 1 within an absolute tolerance of 1e-6, and Score must lie in 0..N-1. Missing or malformed answers return 502 DECISION_PARSE_FAILED; values are never clamped or defaulted into decisions. Confidence is required for Choice/Score and is not inferred from the winning probability. The LLM provider uses the same validation.

DECISION_PROVIDER=llm is an equivalent provider you select by configuration; it is not an automatic failover, and nothing switches to it when Jev fails. It calls LLM_PROVIDER in structured decision mode: a dedicated decision system prompt, no Copilot skills and no tool calling. A Score answer from the LLM is the weighted expected level Σ i·p(i) computed from its validated level probabilities, on the same 0..N-1 scale as Jev and never rounded; the level the model names is ignored, so one distribution yields one score on every adapter. Because the probabilities are uncalibrated, thresholds tuned for Jev must not be reused for llm as-is. Tool-only or non-JSON replies fail with 502 DECISION_PARSE_FAILED. With llm, the estimated size of the complete answer is also checked against DECISION_LLM_MAX_OUTPUT_TOKENS before the call (413 DECISION_INPUT_TOO_LARGE), a 2xx reply that is not JSON or has the wrong envelope is 502 DECISION_PARSE_FAILED (as with Jev), an unreachable provider is 503 DECISION_UNAVAILABLE, upstream HTTP statuses map to the same codes as Jev, and upstream error bodies are never logged or returned.

Governance (#511). Every gate below runs before the provider is called, in this order, and a request that fails one never reaches it:

  1. Capability ai:decide. Grant it with a policy permission create on the reserved collection lumibase_ai_decisions; site admins already satisfy it. That permission grants nothing else (no items:write). Without it → 403 FORBIDDEN. Anonymous callers, members without the capability and principals of another site are all refused here. Publishable API keys (lbk_pub_…) and frontend-audience sessions are always refused here with 403 FORBIDDEN, even when a role or policy grants create on lumibase_ai_decisions or admin access (#562). Those credentials live in browsers and apps, so paid decision calls must come from Studio users or from a server that holds a secret API key. The refusal comes before the body is read. It applies to every ai:decide route (decisions, review profiles, reviews, feedback, rollout, sessions) and to Flows ai:decision nodes. Refusals at this step are audited in aggregate, not one event per request (see the audit paragraph below).
  2. Provider configured → otherwise 503 DECISION_NOT_CONFIGURED.
  3. Site opt-in. The site sends content to the provider only after a site admin stores the aiDecisions setting with enabled: true (POST /api/v1/settings). It is off by default, and a malformed value reads as off. Setting it back to false (or deleting the key) is the per-site kill switch: the next request gets 403 DECISION_DISABLED. Only the decision endpoints, draft review and Flows ai:decision nodes read this setting, so editing, publishing and Copilot chat are unaffected. Unsetting DECISION_PROVIDER is the platform-wide switch.
  4. Field allowlist. With allowedStateFields set, state must be an object whose top-level keys are all listed; otherwise 422 DECISION_FIELD_NOT_ALLOWED.
  5. Input budget → 413 DECISION_INPUT_TOO_LARGE (above).
  6. Site quota, accounted atomically with the runtime counter (Redis INCRBY on Docker, the per-site PageviewCounter Durable Object on Cloudflare): admitted decisions per hour, decisions in flight, and estimated tokens per UTC day. The token reservation is the worst case, every attempt the provider can send included: with Jev/OpenRouter, (estimated input + estimated output) × (DECISION_MAX_RETRIES + 1); with llm, which sends one request and never retries, estimated input + the output cap sent upstream (thinking headroom included). Once the provider answers, the site is charged the reported usage plus an estimate for each earlier failed attempt, and the rest is refunded. An unknown count is charged at the estimate, never as free. A timeout or failure after attempts were sent is charged per attempt; a request that never reached the provider is fully refunded. A limit that would be exceeded → 429 DECISION_QUOTA_EXCEEDED or 429 DECISION_CONCURRENCY_LIMITED with Retry-After. A request whose worst-case reservation alone exceeds the daily token budget can never be admitted, so its 429 DECISION_QUOTA_EXCEEDED carries no Retry-After. If the counter backend is down or answers with a non-numeric value, the request fails closed with 503 DECISION_QUOTA_UNAVAILABLE. Retry-After is listed in Access-Control-Expose-Headers, so cross-origin callers (Studio on Pages, the desktop shell, browser SDK) can read it.

The site aiDecisions setting can tighten the platform ceilings, never raise them:

json
{ "key": "aiDecisions", "value": { "enabled": true, "allowedStateFields": ["title", "body"], "requestsPerHour": 100, "maxConcurrent": 2, "budgetPerDay": 200000 } }

Each admitted call, and each call refused after this first step, writes one ai_decision audit event with the request ID, the principal (type and ID), provider, model, a rubric fingerprint (sha256: of the questions, so the same rubric gives the same version), question types, outcome, HTTP status, latency, reported usage, attempts, and reserved and charged tokens. It never records state, instructions, criteria, answers, the actor's email or the client IP. Audit rows follow the audit log retention (LUMIBASE_AUDIT_RETENTION_DAYS, default 90 days). POST /ai/decisions stores no decision content. Draft review runs (below) store the answers, never the reviewed content. What the provider keeps is governed by the provider's own terms.

Refusals are audited in aggregate (#564). A 403 FORBIDDEN from step 1 does not write one event per request, so a flood of refused requests cannot flood the audit log. Refusals are counted per site, refusal reason and subject: the principal (type and ID), or a keyed hash of the client IP when there is no principal. The first refusal in each DECISION_REFUSAL_AUDIT_WINDOW_SECONDS window (default 300 s) writes an event with refusal.count: 1. Later refusals in the same window write again only at counts 10, 100, 1000, and so on. The first event of the next window carries refusal.previousWindowCount, the exact count of the window before. If no refusal follows, the last event's count is a lower bound, and the metric lumibase_ai_decision_refusals_total{reason,principal,audit} has the exact number of every refusal. If the counter store is unavailable, every refusal writes an event (evidence is never dropped). 0 turns aggregation off. Each refusal event has metadata.refusal (reason, count, dedup: first / checkpoint / unbounded, windowStart, windowSeconds) and clientIpHash: HMAC-SHA256 of the site and IP keyed by JWT_SECRET, 16 hex characters, or null when the IP is unknown. The ip column stays empty. Rotating JWT_SECRET changes the hashes. refusal.reason is one of publishable_api_key, frontend_session, unclassified_caller, capability_missing, principal_unresolved, principal_site_mismatch, principal_not_found, principal_inactive, principal_not_member, api_key_revoked, api_key_expired, dev_principal_forbidden, principal_denied, other. A key of another site is reported as principal_not_found.

Abuse bounds for /api/v1/ai/* (#564). Every request under /api/v1/ai counts against a per-client-IP, per-site limit, LUMIBASE_AI_IP_RATE_LIMIT (default 300 per minute, 60-second window, 0 = off). It runs after the site check and before authentication, so a blocked request costs no token or API-key check, no quota reservation, no provider call and no audit event. Over the limit → 429 RATE_LIMITED with Retry-After (listed in Access-Control-Expose-Headers); the counter is lumibase_ai_ip_rate_limited_total. If the limiter store is unavailable, the request passes, or gets 503 RATE_LIMIT_UNAVAILABLE when LUMIBASE_RATE_LIMIT_FAIL_CLOSED=true (the same rule as the other limiters). The limit is skipped when the client IP cannot be resolved. On Docker behind a reverse proxy, the proxy must overwrite CF-Connecting-IP with the real client IP: the CMS trusts that header as sent, so a client-supplied value must never pass through.

As an outer defence, add a Cloudflare WAF rate-limiting rule in front of the Worker or the Docker origin: expression (http.request.uri.path wildcard "/api/v1/ai/*") (optionally and http.request.method eq "POST"), counting by IP, for example 120 requests per 1 minute, action Block for 1 minute (block, not a challenge, because callers are APIs). The CMS limits stay in force behind it.

Draft review (#512). A review profile is a versioned rubric: the top-level fields a review reads and the Decision questions it asks (same shapes as above). A review run applies one profile version to one item, or to an unsaved draft, through the governed path above (so the ai:decide capability, site opt-in, field allowlist, budgets and the ai_decision audit event all apply), and stores the answers with their provenance. Reviews only suggest: no endpoint here changes an item.

  • Profiles. Reading needs ai:decide; creating and versioning need a site admin. Rows are immutable: POST /review-profiles/:key/versions inserts version + 1 and archives the previous active version in one transaction, so a run always points at the exact questions it was answered against. A profile may be bound to one collection (others get 422 REVIEW_COLLECTION_MISMATCH) and may set minConfidence.
  • Presets. taxonomy is a choice over presetOptions.categories plus other and unknown. brand-voice scores tone match and clarity on atomic 5-level rubrics (against presetOptions.voice) and adds a needs_review flag. brief-alignment compares the content with the sourceField (a brief or source the editor supplies). Without a sourceField it only checks internal coherence and the profile stores the note no source — not a fact-check. No preset claims to verify facts.
  • Reading content. With itemId, the server reads the profile's fields with the caller's own row and field permissions. Fields the caller cannot read are not sent and are listed in omittedFields. With snapshot (an unsaved draft), each key must be one of the profile's fields and one the caller may read and write (create, or update when itemId is also given). Otherwise the request fails with 422 REVIEW_FIELD_NOT_ALLOWED before any provider call. Content travels only in state and the questions come from the stored profile, so text inside the content cannot change what is asked.
  • Provenance and staleness. A run records the actual provider, model, calibrated, the profile key and version, the latest live revision, the principal, latency, usage and contentHash (sha256: of the canonical JSON of the reviewed fields). GET /reviews/:id recomputes the hash and revision. When either changed, the run comes back stale: true with staleReason content_changed, revision_changed or item_unavailable. A caller who can no longer read a field the run reviewed gets 404. Snapshot runs are visible only to their author and admins.
  • Abstention. status is abstained when every choice answer is other/unknown, or when a confidence is below the profile's minConfidence.
  • Idempotency. Keys are scoped to the caller: the same idempotencyKey (body) or Idempotency-Key header from the same principal returns the same run (200) with no second provider call, while another principal using the same key gets its own run. A run that ended in error is retried in place, so it never becomes a second row. The retry re-reads the item and rebinds the run (content hash, revision, profile version, omitted fields) to what it actually reviewed. A run still running five minutes after it started (its process died) is reclaimed the same way; until then a replay returns it as running. If the original call does finish after that, its answers are discarded: a run is completed only by the attempt that holds the current claim, so the response of the late call is the run as stored.
  • Feedback. POST /reviews/:id/feedback takes entries of { questionKey, verdict: accept | edit | reject, editedValue? }. It stores one row per run, question and principal; a retried submission adds none and returns the stored rows. The first verdict is final: resubmitting a different verdict (or editedValue) for the same question does not overwrite it, and the response carries the stored verdict, so compare it with what you sent. accept or edit on a stale run returns 409 REVIEW_STALE unless the body says acknowledgeStale: true, so a review is never silently applied to a different revision. For snapshot runs, send the current draft's contentHash to get the same check. reject is always accepted.
  • Retention. The hourly job deletes runs older than DECISION_REVIEW_RETENTION_DAYS (default 180), and their feedback with them. Profiles are kept.
  • Pilot rollout (#516). The aiDecisions setting has a review object: { enabled, pilotCollections, mode: 'baseline' | 'assisted' }. It is off when absent or malformed. POST /reviews and new feedback need the collection in the pilot in assisted mode (which also needs aiDecisions.enabled); otherwise they return 403 DECISION_DISABLED before any content is read. GET /reviews/rollout?collection= reports the mode (ai:decide). Turning the pilot off deletes nothing: runs, feedback and sessions stay readable.
  • Flows (#517). A flow node ai:decision runs one review with a pinned profileVersion on one item and returns branch: true/false/unknown for a noul question (noulThreshold), the option key or unknown for a choice question (minConfidence, abstention), or error. It needs the aiDecisions setting to have both enabled: true and flows: true; flows is off by default. When the node executes, the server re-resolves the principal that started the run, checks ai:decide on that live grant and re-reads both switches, so a revoked grant or a later kill switch stops queued runs too. Only manual runs (POST /flows/:id/run) carry a principal; event, schedule and webhook runs are refused (FORBIDDEN). A failure (forbidden, disabled, quota, timeout, cancel, provider error) takes the node's error branch when one is mapped and otherwise fails the node (onError); it is never true. The review idempotency key is flow:<flowRunId>:<nodeId>, so re-executing a run replays the stored decision with no second provider call. See Flows.
  • Sessions. POST /reviews/sessions (ai:decide, signed-in users only: API keys and the dev principal get 403 FORBIDDEN) records { collection, itemId?, mode, runId?, viewedQuestions?, durationMs, locale? }: one editor session from opening the editor to the first save. The mode must match the collection's current mode (409 REVIEW_SESSION_MODE_MISMATCH), the collection must be in the pilot (403 DECISION_DISABLED), and a runId must be the caller's own run on the same collection and item, with viewedQuestions it answered (422 REVIEW_SESSION_RUN_INVALID). No content is stored. The run retention purge sets run_id to null and keeps the session.
  • Metrics. GET /reviews/metrics?from=&to= (site admin, window at most 366 days, default the last 30) returns time per item (baseline vs assisted p50/p95), accept/edit/reject/no-action rates over viewed suggestions only with 95% Wilson intervals, coverage, abstention, error rate, latency p50/p95, tokens per run, splits by locale, provider and profile version, sample counts (with distinct editors and items per mode), and the pre-registered criteria of protocol jev-pilot-v1 with insufficientSample flags. Only sessions and verdicts of user principals count. Run counts are operational denominators, never user value. See Draft-review pilot.
  • Automation (#518). Flow nodes ai:apply-tags and editorial:route read an upstream ai:decision and record one row per flow run, node and item in lumibase_ai_automation_actions. They are shadow by default: the proposal is recorded and nothing is written. A proposal is live only when aiDecisions.automation has mode: 'live', a gate (approvedBy, approvedAt, evidenceRef) and a threshold for the item's locale and the action whose provider, model, profileKey, profileVersion and questionKey match the decision (read from the stored review run, which must be about the node's item), and the confidence is at or above its minConfidence; anything else (including a malformed block) is shadow. A live proposal goes through the governed harness (updateItem, agent jev-automation, autonomyCap: 1), so it becomes an approval or is refused at L0; automation never writes directly. The updateItem call carries expect: { <field>: <value the proposal was computed from> }, which the harness re-checks when the approved write runs; a field a human changed in between fails the approval with ITEM_PRECONDITION_FAILED and nothing is written (row denied, reason stale_at_approval). expect is an optional updateItem argument for any caller. Only the target field is proposed, never status, deletes or schema; the submit_review transition is proposed only. Stale decisions, decisions an editor overrode, pinned or unreadable fields are skipped and recorded. /api/v1/ai/automation/* is control plane (site admin). POST /automation/actions/:id/revert restores previous of an applied action through the caller's ItemService, and refuses with 409 AUTOMATION_REVERT_CONFLICT when the field changed since. GET /automation/metrics reports precision and coverage in the auto-action zone with insufficientSample and shadowRequired; it switches nothing on. See Jev automation.
json
POST /api/v1/ai/reviews
{ "profile": "spam-check", "collection": "posts", "itemId": "itm_1", "idempotencyKey": "review-itm_1-0001" }

Errors: 403 FORBIDDEN, 404 REVIEW_PROFILE_NOT_FOUND / REVIEW_ITEM_NOT_FOUND / REVIEW_RUN_NOT_FOUND, 409 REVIEW_PROFILE_EXISTS / REVIEW_PROFILE_CONFLICT / REVIEW_STALE / REVIEW_NOT_COMPLETE, 422 REVIEW_FIELD_NOT_ALLOWED / REVIEW_COLLECTION_MISMATCH / REVIEW_SESSION_RUN_INVALID, 409 REVIEW_SESSION_MODE_MISMATCH, 400 VALIDATION, plus every decision error above.

Agent API (Content OS)

All routes mount under the authenticated chain; the token's roles are the capability set.

MethodPathDescription
GET/POST/api/v1/agent/goalsList / create goals (execution: 'async' enqueues a queued run)
POST/api/v1/agent/goals/:id/decomposePlanner: create role-scoped sub-goals inheriting remaining budget
POST/api/v1/agent/goals/:id/settleSettle a parent goal from its children's terminal states
POST/api/v1/agent/runs/:id/retryRe-execute a failed/cancelled run as a new queued run (retryOfRunId → the original), enqueued on agent-runs under the requester's re-resolved rights. Only the goal's latest attempt, only while nothing on the goal is in flight — at most one new execution per request. 201 { goalId, runId, agentName, status, retryOfRunId }; 404 unknown or other-tenant run; 409 not retryable, in flight, effect already recorded (RUN_EFFECT_RECORDED), superseded, goal closed or busy, intent not active, or task unrecoverable; 423 frozen; 400 no queue adapter; 503 enqueue failed. See agent harness
GET/POST/PATCH/DELETE/api/v1/agent/roles[/:name]Agent role library CRUD (admin) — seeded with Planner, Writer, …
GET/api/v1/agent/autonomyTrust ledger: grants + open incidents
GET/POST/api/v1/agent/autonomy/promotions[...]Promotion proposals; POST :id/decide is the only path to a higher level (admin)
GET/POST/api/v1/agent/staged[...]Veto window: pending stagings enriched with approvalId/collection/itemId/patch/agentRole from the staging revision (null fields when the staging is gone); POST :id/veto discards a staging
GET/api/v1/agent/approvalsApproval inbox (status filter; defaults to pending)
POST/api/v1/agent/approvals/:id/decideHuman decision on a parked action. Body { decision: 'approved' | 'rejected', reason? }; needs approvals:decide (403 otherwise), 404 for an unknown or other-tenant id, 409 when the approval already left pending. On approved the harness owns the state transition, so execution and the status write happen once. Execution re-resolves the requester's current rights and runs with requester ∩ decider: an approval whose requester was since revoked, demoted or removed is denied, and one with no recorded requester (parked before provenance existed) is denied with APPROVAL_PROVENANCE_MISSING. An approval stored with approvalPolicy: human_required (every external-action tool) is released only by a signed-in user: an API key, a connector token or an agent gets 409 EXECUTION_FAILED carrying HUMAN_APPROVAL_REQUIRED, and the approval stays pending
POST/api/v1/agent/approvals/:id/reopenReturn a failed approval to pending so it can be decided again. Body { reason } is required and audited; needs approvals:decide. A skill that reached a service and then failed is parked rather than re-offered, because retrying could repeat a non-idempotent write — this is the deliberate way back. A veto approval whose staged patch is already live (a commit that died after applying it) answers 409 VETO_ALREADY_APPLIED instead, since reopening would apply it twice
POST/api/v1/agent/approvals/:id/agent-decideAgent-as-reviewer decision (needs review:<domain>; self-review forbidden)
GET/api/v1/agent/questionsaskUser clarification questions, newest first. ?status=pending (default) | answered | expired | cancelled | all. Each item: { id, runId, goalId, toolCallId, agentName, question, options, allowFreeText, context, status, expiresAt, createdAt, answer, answeredAt, answeredBy }. Questions are not listed by /approvals, and /approvals/:id/decide and /reopen answer 409 NOT_AN_APPROVAL for a question id. See agent harness
GET/api/v1/agent/questions/:idOne question; 404 for an unknown or other-tenant id
POST/api/v1/agent/questions/:id/answerAnswer a question and resume its waiting_user run. Body { answer } (1–2000 chars, trimmed; one of options when allowFreeText is false). Only a signed-in user answers: any API key, site- or organization-scoped and whatever its capabilities, gets 403. Allowed for a holder of approvals:decide (or control-plane admin) and for the run's requesting user; today only site administrators reach the route (control-plane guard), so the requester rule takes effect once backlog B207 moves it out of the control plane. The claim and the resume are one transaction. 200 with the answered question (run succeeded); 400 VALIDATION / ANSWER_INVALID / ANSWER_NOT_AN_OPTION; 403; 404; 409 ALREADY_ANSWERED, EXPIRED, QUESTION_CLOSED, RUN_NOT_WAITING, REQUESTER_REVOKED (the requester lost access; the run is failed); 423 FROZEN (the run is cancelled)
GET/POST/api/v1/agent/constitution[...]Versions, draft, /compile (NL→evaluators), :id/dry-run, :id/activate
*/api/v1/agent/skills[...]Site Skills — playbooks injected into matching agent runs: CRUD by id or slug, :id/activate|archive|draft, :id/versions, :id/versions/:version/restore, /import, /export, /match. Every write needs a control-plane admin (403 FORBIDDEN otherwise; there is no delegated author and riskClass is a label only). PATCH takes expectedVersion and status actions take version (409 VERSION_MISMATCH); DELETE refuses a skill that was ever active (409 SKILL_HAS_BEEN_ACTIVE); /import refuses content changes to active skills unless updateActive: true (ACTIVE_SKILL_CHANGE). See features/site-skills.md
GET/PUT/DELETE/api/v1/agent/tool-secrets[/:name]Secrets of external-action tools, per site. GET lists names, key version and timestamps; PUT /:name with { value } (8 to 8192 characters) stores or replaces; DELETE /:name removes. No route returns a value. All need a signed-in site administrator: an API key or connector token gets 403 FORBIDDEN even with administrative rights. 400 for an invalid name or value, 404 deleting an unknown name, 503 KEYS_UNAVAILABLE when no KeyProvider is configured. See features/external-action-tools.md
GET/POST/api/v1/agent/kill-switch[/lift]Four-scope stop (run/intent/role/site); freezes need agents:freeze. Freezing a role or the site, pausing an intent and cancelling a run also cancel runs waiting on an askUser question in that scope (stopReason: frozen) and close their questions
*/api/v1/agent/intents[...]Content intents CRUD, `:id/pause
POST/api/v1/intents/:id/scanOne reconciliation cycle: { scan, reconcile, dispatch }. dispatch advances each reconciler goal one step (draft → promote → verify) and reports dispatched/completed/skipped/blocked plus queueUnavailable on runtimes without a queue adapter. See reconciler repair loop. When the intent has semantic rules, scan.semantic reports the separately budgeted semantic pass (status ran/off/unavailable, counts, completed, cursor), and scan.semanticOrphansResolved counts rows of removed semantic rules it resolved. Updating an intent so a stored semantic rule changes profile, question, context or fields without a version bump returns 422 SEMANTIC_RULE_VERSION_REQUIRED; see semantic drift
POST/api/v1/mcpMCP server (Streamable HTTP, JSON-RPC 2.0) — gated by contentOs.mcp flag. Besides tools/*, prompts/list and prompts/get expose the site's active skills to control-plane admins (empty for any other caller). A tools/call of askUser returns a normal tool result with status: "waiting_user", questionId and runId
POST/api/v1/mcp/sites/:siteIdSame MCP server, site taken from the path (for hosted OAuth connectors that cannot send X-Lumi-Site)
GET/.well-known/oauth-protected-resource/api/v1/mcp[/sites/:siteId]RFC 9728 Protected Resource Metadata (public; 404 unless MCP is on and a trusted issuer lists the resource URI in audience) — see OAuth connector
GET/DELETE/api/v1/items/:collection/:id/pins[/:field]Law Zero pins: list / release
GET/api/v1/deliver/llms.txt/:site_idPublic llms.txt index per site

9. Realtime (WebSocket)

Endpoint: wss://api.<your-site>.lumibase.dev/api/v1/realtime

Auth (ticket exchange): browsers cannot send Authorization on the WS handshake, so exchange the session for a short-lived (1 min) ticket first: POST /api/v1/realtime/ticket (studio) or POST /api/v1/realtime/audience-ticket (end-user), then connect:

code
wss://...realtime?ticket=<ticket>

The studio ticket embeds the collections the principal can read; the hub rejects any other subscribe with { "type": "error", "code": "SUBSCRIBE_FORBIDDEN" }.

Subscribe to collection (optional Directus-style filter, evaluated server-side over the event envelope collection/action/itemId):

json
{ "type": "subscribe", "collection": "articles", "filter": { "action": { "_eq": "delete" } } }

Server event — signal-only: no row data on the wire (clients re-fetch via /items, which enforces RBAC + field masking):

json
{ "type": "event", "collection": "articles", "action": "update", "itemId": "art_001", "payload": null }

Server notification frame (push-noti feature) — broadcast to every session for the site (not collection-scoped):

json
{ "type": "notification", "notification": { "id": "…", "kind": "approval", "severity": "info", "title": "…", "body": "…", "deepLink": "/mission-control/inbox?entry=approval:…", "entityId": "…", "ts": "2026-06-23T01:00:00Z" } }

See features/websockets-realtime.md for full protocol reference.


9b. Push notifications

Web Push (VAPID) + in-app realtime for agent events. Tenant-scoped; the VAPID key is a shared deployment resource. See features/push-notifications.md.

MethodPathDescription
GET/api/v1/push/vapid-public-keyApplication-server public key (404 PUSH_NOT_CONFIGURED when unset). Same key for every tenant.
GET/api/v1/push/status{ vapidConfigured, realtimeAvailable, subscriptions } for the active site.
POST/api/v1/push/testDispatch a one-off test notification to the active site (both transports).
POST/api/v1/push/subscriptionsUpsert a browser subscription: { endpoint, keys: { p256dh, auth } }.
DELETE/api/v1/push/subscriptionsRemove a subscription by { endpoint }.

10. Settings

MethodPathDescription
GET/api/v1/settingsGet all site settings
PATCH/api/v1/settingsUpdate multiple settings
GET/api/v1/settings/:keyGet single setting by key
PUT/api/v1/settings/:keySet single setting
POST/api/v1/settings/exportExport settings as JSON bundle
POST/api/v1/settings/applyApply settings bundle

Site configuration

The active site's identity, branding and theme defaults live on the sites row (not the key/value settings table). Scoped to the active tenant via the X-Lumi-Site header.

MethodPathDescription
GET/api/v1/siteGet the active site's configuration
PATCH/api/v1/siteUpdate site identity / branding / theme (partial)

PATCH /api/v1/site accepts any subset of: name, displayTitle, siteUrl, descriptor, domain, defaultLanguage, defaultAppearance (auto|light|dark), defaultSaveAction (stay|return|create_new — the site-wide default save action a user's personal preference overrides), branding ({ logoUrl, faviconUrl, brandColor }), themeOverrides ({ light, dark } maps of whitelisted CSS tokens → H S% L% values), and customCss. An empty string clears a nullable field. A duplicate domain returns 409 { errors: [{ code: 'DOMAIN_TAKEN' }] }.

Theme model: the site holds the global defaults; per-user appearance/theme/ language overrides (resolved client-side) take precedence.


10b. Regulated / sensitive content (admin)

Opt-in capability set (spec: regulated-content-readiness). All admin routes require the admin role; field-level decryption additionally requires the read_decrypted permission. Sensitive pii/phi field reads are recorded in field_access_log; decrypt failures fail closed (500 DECRYPTION_FAILED) and are audited — never a placeholder.

Encryption — keys & envelope mode

Key material lives only in the runtime KeyProvider (Workers Secrets / env: ENCRYPTION_KEY_<id> + ENCRYPTION_ACTIVE_KEY_ID); these surfaces record metadata + audit and drive migrations.

MethodPathDescription
GET/api/v1/admin/encryption/keysList configured key metadata (id/status/algo).
POST/api/v1/admin/encryption/keys/rotatePromote a provisioned key to active; retires the previous. Body { keyId }. Audits encryption_key_rotated. 422 KEY_NOT_PROVISIONED if the bytes are absent.
POST/api/v1/admin/encryption/keys/rewrapRe-encrypt retired-key ciphertext (and re-wrap per-record DEKs) onto the active key. Idempotent, resumable, bounded per call.
GET/api/v1/admin/encryption/envelopeCurrent envelope-mode setting + migration progress.
POST/api/v1/admin/encryption/envelopeToggle envelope (per-record DEK) mode. Body { enabled, password } — step-up auth re-verifies the admin password (401 INVALID_CREDENTIALS on mismatch). Records encryption.envelope, audits envelope_mode_changed, enqueues the background migration and drains a bounded inline batch.
POST/api/v1/admin/encryption/envelope/migrateDrain more migration batches (resumable). Poll until { done: true }.

Editorial review → publish

Mounted at /api/v1/editorial. Per-collection toggle via collection meta.editorialWorkflow; meta.requireSeparateReviewer enforces a different reviewer than the author. Transitions audit editorial_transition.

MethodPathDescription
GET/api/v1/editorial/reviewsList review requests (filter by status/assignee).
POST/api/v1/editorial/:collection/:id/submit-reviewMove draft → in_review; assign a reviewer.
POST/api/v1/editorial/:collection/:id/approvein_review → approved (→ publish per workflow).
POST/api/v1/editorial/:collection/:id/rejectin_review → rejected. Body { reason }.

GDPR erasure (dual-control)

Mounted at /api/v1/admin/erasure. Crypto-shreds (drops per-record DEK) or hard-deletes items + revisions while preserving the tamper-evident data_erased audit (no cascade). Dual-control via erasureDualControl setting.

MethodPathDescription
POST/api/v1/admin/erasureCreate an erasure request. Body { collection, filter } + reason. Stores a subject hash, never plaintext.
POST/api/v1/admin/erasure/:id/confirmSecond-admin confirmation (dual-control).
POST/api/v1/admin/erasure/:id/executeExecute the confirmed erasure; audits data_erased with recordCount.

Field access log & Subject Access Request

MethodPathDescription
GET/api/v1/admin/field-access-logQuery decrypted-read audit of pii/phi fields (never values).
POST/api/v1/admin/sar/exportSubject Access Request: export one subject's decrypted records + provenance. Forces a field_access_log entry (Req 13.2).

11. Extensions

MethodPathDescription
GET/api/v1/extensionsList installed extensions
POST/api/v1/extensions/uploadUpload extension bundle (multipart)
POST/api/v1/extensions/:id/enableEnable extension
POST/api/v1/extensions/:id/disableDisable extension
POST/api/v1/extensions/:id/capabilitiesGrant capabilities
GET/api/v1/extensions/ui/manifestUI manifest for dynamic Studio import

Signing & official extensions. Every install/load path (marketplace install, generic CRUD POST /extensions, the dynamic endpoint mount, and hook dispatch) routes through a shared verifier. Detached Ed25519 signatures are checked against publisher keys resolved from MARKETPLACE_PUBLIC_KEYS (env) merged with the lumibase_publisher_keys table (DB overrides env for official/revoked). isOfficial is derived server-side (name in the lumibase- namespace and a signature by an official key) — never from a manifest claim. Official extensions are fail-closed: an unverifiable bundle never loads. Third-party enforcement follows LUMIBASE_EXT_SIGNATURE_POLICY (require default, or warn). The lumibase- namespace is reserved: community /marketplace/submit rejects it, and official extensions with autoInstall/enabledByDefault are installed during setup / on site-create by the reconciler. Sign bundles with the @lumibase/extension-cli (lumibase-ext keygen|sign|verify).


11a. Pageviews (visitor counting)

Public beacon + authenticated read for the built-in pageview module. Per-site config lives in the pageviews settings key (scope: 'module'): strategy (db-rollup default | hot-counter | cdc | hll), userTable, respectConsent, botFilter, hashSalt, flushIntervalS. Authenticated hits are attributed to a user only with analytics consent; anonymous hits use a salted hash (never a raw IP). Counters flush to lumibase_pageview_daily every 5 minutes.

MethodPathDescription
POST/api/v1/pageviews/:site_id/hitPublic beacon; bot/DNT/GPC-filtered, rate-limited; returns 204
GET/api/v1/pageviews/stats?from=&to=&path=Authenticated daily views/uniques for a range

11b. Email (templates, layouts, send)

Site-admin scope (requireSiteAdmin). Backed by the shared EmailService (SMTP / MailChannels) + a site-scoped template/layout store. Full guide: docs/en/features/email-service.md.

MethodPathDescription
GET/api/v1/email/capabilitiesTransport availability + default from
GET/api/v1/email/layoutsList layouts
POST/api/v1/email/layoutsCreate layout (HTML shell with {{content}})
PATCH/api/v1/email/layouts/:idUpdate layout
DELETE/api/v1/email/layouts/:idDelete layout
GET/api/v1/email/templatesList templates
POST/api/v1/email/templatesCreate template
PATCH/api/v1/email/templates/:idUpdate template
DELETE/api/v1/email/templates/:idDelete template
POST/api/v1/email/templates/:key/previewRender without sending
POST/api/v1/email/sendRender (if templateKey) + send — extension entry point
POST/api/v1/email/testSend a one-off test mail

POST /api/v1/email/send body: { to[], cc?, replyTo?, variables?, and exactly one of templateKey or inline: { subject, html?, text? } }. Returns 502 DELIVERY_FAILED, 404 NOT_FOUND (template), or 503 EMAIL_NOT_CONFIGURED (degraded mode).


12. Firebase Sync

Sync content (items) to a Firebase target — Cloud Firestore or Realtime Database — in real time. All endpoints require site-scoped admin. Firebase credentials are write-only (supplied on create/update, encrypted at rest with ENCRYPTION_KEY, never returned). See features/firebase-sync.md.

MethodPathDescription
GET/api/v1/firebase-sync/pipelinesList sync pipelines for the active site
POST/api/v1/firebase-sync/pipelinesCreate a pipeline
GET/api/v1/firebase-sync/pipelines/:idPipeline detail (credentials omitted)
PATCH/api/v1/firebase-sync/pipelines/:idUpdate config / rotate credentials
DELETE/api/v1/firebase-sync/pipelines/:idDelete pipeline (cascades its log)
GET/api/v1/firebase-sync/pipelines/:id/logRecent sync attempts
POST/api/v1/firebase-sync/pipelines/:id/backfillPush all matching items to Firebase now

Create a pipeline (Firestore):

bash
POST /api/v1/firebase-sync/pipelines
Content-Type: application/json
Authorization: Bearer <token>
X-Lumi-Site: <siteId>

{
  "name": "blog-to-firestore",
  "target": "firestore",
  "projectId": "my-firebase-project",
  "credentials": {
    "project_id": "my-firebase-project",
    "client_email": "[email protected]",
    "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
  },
  "collections": ["articles", "authors"],
  "targetPath": "content/{collection}",
  "syncOnCreate": true,
  "syncOnUpdate": true,
  "syncOnDelete": true
}

For target: "rtdb", credentials is { "databaseUrl": "https://<project>.firebaseio.com", "secret": "<rtdb-secret>" }.

Response (201):

json
{
  "data": {
    "id": "V1StGXR8_Z5jdHi6B-myT",
    "name": "blog-to-firestore",
    "target": "firestore",
    "status": "active",
    "projectId": "my-firebase-project",
    "collections": ["articles", "authors"],
    "targetPath": "content/{collection}",
    "syncOnCreate": true,
    "syncOnUpdate": true,
    "syncOnDelete": true,
    "lastSyncAt": null,
    "lastSyncItemCount": null,
    "createdAt": "2026-06-17T00:00:00Z",
    "updatedAt": "2026-06-17T00:00:00Z"
  }
}

Backfill response:

json
{ "data": { "scanned": 120, "pushed": 118, "failed": 2, "truncated": false } }

Error codes specific to this section: ENCRYPTION_KEY_REQUIRED (400 — ENCRYPTION_KEY not configured, cannot encrypt credentials), VALIDATION_ERROR (400 — body / credential shape does not match the selected target).


12a. Translation Memory

Reusable translations feeding the MT pipeline (TM → glossary → provider).

MethodPathDescription
GET/api/v1/tmList entries; filters ?source=&target=&entrySource=; paginated ?limit=&offset= → { data, meta: { total, limit, offset } }
POST/api/v1/tmUpsert a TM entry
PATCH/api/v1/tm/:idUpdate targetText/quality/context/source
DELETE/api/v1/tm/:idDelete an entry
POST/api/v1/tm/lookupFuzzy match (threshold default 75, shared TM_DEFAULT_THRESHOLD)
POST/api/v1/tm/translateFull pipeline (TM → glossary → MT provider)

12b. Insights (Dashboards)

User-built dashboards of aggregate panels over collections. Panel queries are executed safely: every referenced field must be in the collection's field whitelist and the query is scoped to the active site — no user input reaches SQL identifiers.

MethodPathDescription
GET/api/v1/dashboardsList dashboards
POST/api/v1/dashboardsCreate dashboard { name, icon?, color?, note? }
GET/api/v1/dashboards/:idGet dashboard
PATCH/api/v1/dashboards/:idUpdate dashboard
DELETE/api/v1/dashboards/:idDelete dashboard
GET/api/v1/dashboards/:id/panelsList panels
POST/api/v1/dashboards/:id/panelsCreate panel { name, type, position, query }
PATCH/api/v1/dashboards/:id/panels/:panelIdUpdate panel (incl. position for layout)
DELETE/api/v1/dashboards/:id/panels/:panelIdDelete panel
POST/api/v1/dashboards/:id/panels/:panelId/dataRun a panel → { data, meta: { executedAt, rowCount, durationMs } }
POST/api/v1/dashboards/:id/panels/previewDry-run a PanelQuery (editor preview)

PanelQuery (shared contract @lumibase/contracts): { collection, aggregate (count|sum|avg|min|max), field?, groupBy?, filter? (condition rule), dateRange?, limit? }. field is required for non-count aggregates. A field outside the collection whitelist returns 400 { errors: [{ code: 'INVALID_FIELD' }] }.

Activation milestones

MethodPathDescription
GET/api/v1/activationThe active site's milestone funnel → { data: { siteId, milestones, reached, total } }. Site admins only (403 FORBIDDEN).

Each entry of milestones is { key, reachedAt, source, secondsSinceSiteCreated } with key one of site_created, item_published, delivery_request, agent_run. Milestones are write-once and site-scoped. See Activation milestones and usage telemetry.


12c. Git Integration (GitHub / GitLab)

Per-site connections to source repositories: track pull requests + CI, view/store CI logs, post a content-validation status back, reconcile declarative intents (GitOps), and run auto preview environments. Authenticated routes require site admin and ENCRYPTION_KEY (tokens are stored encrypted, never returned).

MethodPathDescription
GET/api/v1/integrations/gitList integrations for the site
POST/api/v1/integrations/gitCreate { provider (github|gitlab), repoFullName, displayName, authMethod (app|pat), token?, installationId? } → 409 on duplicate (provider, repo)
GET/api/v1/integrations/git/:idGet one
PATCH/api/v1/integrations/git/:idUpdate display name / token / status / sync config
DELETE/api/v1/integrations/git/:idDisconnect (forgets token)
POST/api/v1/integrations/git/:id/rotate-secretRotate the webhook secret
GET/api/v1/integrations/git/:id/oauth/authorizeReturns { authorizeUrl } (single-use cache state)
GET/api/v1/integrations/git/:id/pull-requestsList cached PRs
POST/api/v1/integrations/git/:id/pull-requests/refreshPull PRs live from the provider (upsert cache)
GET/api/v1/integrations/git/:id/pull-requests/:number/ciCI runs for the integration
POST/api/v1/integrations/git/:id/pull-requests/:number/validateValidate config + post lumibase/content-validation commit status
GET/api/v1/integrations/git/:id/ci-runs/:runId/logsFetch + cache CI log (blob storage)
POST/api/v1/integrations/git/:id/gitops/syncReconcile lumibase/intents.json into content intents (+ drift scan/reconcile)
GET/api/v1/integrations/git/:id/provenanceProvenance ?collection=&itemId= — which commit/PR changed an item

Public (no session; signature-verified or single-use state):

MethodPathDescription
GET/api/v1/integrations/git/oauth/:provider/callbackOAuth code → token exchange (bound to cache state)
POST/api/v1/integrations/git/webhook/:provider/:siteId/:integrationIdWebhook receiver — GitHub HMAC-SHA256 (X-Hub-Signature-256) / GitLab token (X-Gitlab-Token); idempotent by delivery id

Preview environments are opt-in per integration (sync_config.preview = true): on PR open/sync LumiBase seeds an ephemeral site (${siteId}__pr-${number}) served at /api/v1/deliver/page/${ephemeralSiteId}/...; on close/merge it is torn down. CI failure records an agent_incident (role git-sync) + a git_ci_failed audit entry.


13. Delivery (Public)

No Authorization header needed. Permission applied via public role.

MethodPathDescription
GET/api/v1/deliver/page/:slug1-roundtrip page hydration
GET/api/v1/deliver/items/:collectionPublic item list
GET/api/v1/deliver/menu/:keyMenu config

HTTP caching (GET /deliver/page/:site_id/:slug): responses without credentials are shared-cacheable so any CDN/proxy can absorb repeat reads.

RequestResponse headers
No credentials (default)Cache-Control: public, s-maxage=60, stale-while-revalidate=300 · ETag: W/"…" · Vary: X-Lumi-Site
Authorization header presentCache-Control: private, no-store (no shared ETag)
Page not found404 + Cache-Control: no-store
Identifier shape invalid (site_id / slug)404 + Cache-Control: no-store (identical body to a real miss — not 400)
Client IP over LUMIBASE_DELIVER_RATE_LIMIT429 + Retry-After + Cache-Control: no-store

Conditional requests: send If-None-Match with the last ETag; a match returns 304 Not Modified with an empty body and skips section hydration entirely. The ETag is a site-level content fingerprint — any item write (or a scheduled publish/unpublish taking effect) rotates it, so a stale 304 is never served at the cost of a lower revalidation hit-rate.

Tunables (env): LUMIBASE_DELIVER_SMAXAGE (seconds, default 60, 0 disables public caching), LUMIBASE_DELIVER_SWR (seconds, default 300), LUMIBASE_NEGATIVE_CACHE_TTL (seconds, default 30, 0 disables tombstones), LUMIBASE_DELIVER_RATE_LIMIT (req/min/IP, default 1200, 0 disables). See Caching — penetration.


14. Utility endpoints

MethodPathDescription
GET/api/v1/utils/healthHealth check (DB, cache, storage, search, queue)
GET/api/v1/utils/versionAPI version info
POST/api/v1/utils/render-templateRender a display template server-side
POST/api/v1/utils/jsonata/testEvaluate JSONata expression
GET/api/v1/metricsPrometheus metrics (Docker mode only)
GET/api/v1/openapi.jsonLive OpenAPI 3.1 document for the caller's site and permissions — 404 until enabled
GET/api/v1/openapi/configRead the live OpenAPI switch (site admin)
PUT/api/v1/openapi/config{ enabled, realms } — enable it and choose realms (site admin, audited)

The live OpenAPI document is described in Live OpenAPI document.

Health response:

json
{
  "data": {
    "status": "healthy",
    "checks": {
      "database": "ok",
      "cache": "ok",
      "storage": "ok",
      "search": "ok",
      "queue": "ok"
    },
    "version": "1.0.0",
    "runtime": "cloudflare"
  }
}

15. Rate limits

ScopeLimit
Auth endpoints30 req/min per IP
Items write600 req/min per user
Items read6,000 req/min per user
File upload100 req/min per user
Realtime connections50 concurrent per site
AI Chat60 req/min per user
AI routes (/api/v1/ai/*), before auth300 req/min per client IP per site (LUMIBASE_AI_IP_RATE_LIMIT)

Rate limit headers:

code
X-RateLimit-Limit: 600
X-RateLimit-Remaining: 598
X-RateLimit-Reset: 1749254460

16. Versioning

Breaking changes get a new path prefix (/api/v2). The previous version is maintained for at least 12 months.

Send X-Lumi-API-Version: 1 to pin to a specific API version. Default is the latest stable.

Change Feed (/api/v1/cdc — spec cdc-extension-integration)

Mounted on the authenticated api app BEFORE the ClickHouse CDC control-plane router. Frontend-realm tokens are rejected on every route (ADR-011).

MethodPathGuardDescription
GET/cdc/eventscapability cdc:subscribe (admin implies)Keyset-paginated change events. Query: cursor, collections (CSV), operations (CSV), limit (≤500), wait (long-poll seconds ≤25 — holds an empty first read until an event arrives). Returns { data, meta: { nextCursor, hasMore } }. Envelope type is <resource>.<operation> (items.* content, collections.*/fields.* schema). 400 malformed cursor; 410 CURSOR_EXPIRED + earliestCursor past retention.
GET/POST/cdc/subscriptionssite adminList (with per-subscription lag) / create (max 50 per site → 403; duplicate name → 409; kind=webhook requires a webhook with a secret → 400).
GET/PATCH/DELETE/cdc/subscriptions/:idsite adminDetail / update filters + pause/resume (invalid transition → 409) / delete (audited).
POST/cdc/subscriptions/:id/ackcapability cdc:subscribeCommit a pull checkpoint. Forward-only — rewind → 409 ACK_REGRESSION.
POST/cdc/subscriptions/:id/replaysite adminRewind inside retention ({cursor} xor {occurred_after}); resets dead/stale → active. Audited.
POST/cdc/subscriptions/:id/dispatchsite adminOn-demand dispatch (no-queue fallback). 202.
GET/cdc/subscriptions/:id/deliveriessite adminDelivery-attempt history, newest first (limit, page; meta.total).

Webhook deliveries are signed: X-LumiBase-Signature: t=<unix>,v1=<hmac_sha256_hex> over `${t}.${rawBody}` — see docs/en/features/cdc-change-feed.md for the verify snippet and envelope reference.

Last modified: 15/11/2026