Every InventDB instance serves this HTTP API directly: SQL, record CRUD, pre-built queries, bulk writes, vector search, index management, the relationship graph, the workflows engine and per-record attachments. Every example below is copy-paste and fully working against a real property-management dataset (the pms namespace). Your instance also serves an interactive version at /api/docs (Scalar) and /api/docs/swagger (try-it-out), plus the raw spec at /api/openapi.json.
Base URL: https://<slug>.sandbox.inventdb.comAuth: Authorization: Bearer <JWT>Get a token: POST /api/auth/loginOpenAPI 3.1: /api/openapi.json
Product family.InventDB SOAR (AI Platform) is InventDB Serverlessplus the AI/LLM endpoints (InventDB SOAR only). InventDB Serverless serves everything except those. Each instance’s own /api/openapi.json is filtered to its tier.
Authentication
Session and credential endpoints for InventDB. Exchange a username and password for a JWT via login, then send that token as Authorization: Bearer <token> on every protected request. get_current_user resolves the caller's identity and role (globally or per-app), change_password rotates the caller's own credential, forgot_password kicks off an out-of-band reset, and auth_health reports whether auth enforcement is on for the instance.
Exchanges a username and password for a signed JWT. Use the returned token as Authorization: Bearer <token> on every subsequent protected call, and read user for the caller's id, global role, and email. On bad credentials the endpoint returns 401 with ok:false and an error message (token is null). This is the entry point for every API session; no token is required to call it.
Returns the identity behind the bearer token: id, username, role, email, and active flag. Without ?app= the role field is the user's global role from _system.users. Pass ?app=<software_id> (for example ?app=pms) to get the per-app role from app_roles[<id>] instead, though a global superadmin/admin always wins (RBAC bypass). A missing or expired token yields 401.
Path & query parameters
Name
In
Type
Description
app
query
string
Optional app/software id, e.g. pms. When set, role is the per-app role and globalRole carries the raw global role. Empty role means the user is not provisioned for that app.
Rotates the password of the currently authenticated user. Supply the current_password for verification and the desired new_password; both fields are snake_case. On success the endpoint returns { "ok": true }. If the current password is wrong it returns 401, and if the user record can't be found it returns 404; both carry ok:false plus an error string.
Requests a password-reset link for an account, identified by verified email (common path) or by username (for accounts with no email on file, relayed via cmgmt). Anonymous, no JWT required. To avoid leaking which addresses are registered, it always returns 200 with { "ok": true } whether or not a user matched; when a match is found and a delivery channel is wired, the recovery link is sent out-of-band and email_dispatched may be present.
Reports whether authentication is enforced on this instance. Anonymous and cheap; use it from a client bootstrap to decide whether to prompt for login, or from a monitor to confirm the auth subsystem is up. Responds 200 with { "enabled": true } when a bearer token is required for protected routes.
Anonymous pre-check used by the accept page: says whether an invite token is still usable and, if so, which username it sets a password for. The token must be alphanumeric (at most 128 characters), match an active user's stored invite hash, and not be past its 7-day expiry. Always answers 200: valid false comes with a plain reason. Does not consume the token. No credential needed; a stale Bearer token sent along is still rejected with 401. A usable token adds username; an unusable one adds reason.
Anonymous; the token in the body is the credential. Sets the password of exactly the user whose row holds the token and consumes the token in the same write, so a link works once. new_password must be at least 8 characters (note the snake_case field name). Returns the username but no session token: sign in with POST /api/auth/login afterwards. 400 when the password is too short or the token is invalid, already used, belongs to an inactive user, or has expired.
Liveness and schema-discovery endpoints. Use /health for uptime and first-run detection, then walk the data plane top-down: list the namespaces you can see, drill into the types inside one, and pull per-type record counts and storage telemetry. These are the calls the InventDB Console uses to render its Browser tab.
Anonymous liveness check: no token required, and callable while the server is still in setup mode. Returns the running engine version plus setupRequired, which is derived from DB state (whether an active superadmin/admin exists in _system.users) rather than from config.json. Poll this from load balancers and uptime monitors, or read setupRequired to decide whether to route a new operator into the first-run wizard.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/health'
Lists the namespaces (databases) the caller can see, as a bare sorted JSON array of names. RBAC filters the result to only the namespaces the caller's grants admit; superadmin and admin see everything. Pass ?includeSystem=false to hide the engine's _-prefixed system namespaces (such as _system and _soar), leaving just your application namespaces like pms.
Path & query parameters
Name
In
Type
Description
includeSystem
query
boolean
Include _-prefixed system namespaces such as _system/_soar. Default true. Set false to return only application namespaces like pms.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/namespaces?includeSystem=false' \
-H 'Authorization: Bearer $TOKEN'
Response 200
[
"pms"
]
With the default includeSystem=true, the same caller (superadmin) also sees the engine's internal namespaces:
Lists the types (tables) inside a namespace. By default returns a bare array of type names such as ["owners", "properties", …]; pass ?metadata=true to instead get an array of {name, recordCount, …} objects. RBAC filters to the types the caller can read, and engine-internal _* types (attachments, embeddings, relationships) are hidden from non-admins.
Path & query parameters
Name
In
Type
Description
namespace
path
string
The namespace to inspect, e.g. pms.
metadata
query
boolean
If true, the response is an array of TypeInfo objects ({name, recordCount, …}) instead of bare name strings. Default false.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/namespaces/pms/types' \
-H 'Authorization: Bearer $TOKEN'
Returns every type in a namespace with its per-type record count plus storage stats: the call that powers the InventDB Console "Browser" tab. For admin/superadmin the response includes dataSizeBytes, idLocatorSizeBytes, indexSizeBytes, and totalSizeBytes. Non-admin callers get only {namespace, typeName, recordCount}; the storage telemetry is stripped. Use it to build a namespace overview or to spot which types dominate on-disk footprint.
Path & query parameters
Name
In
Type
Description
namespace
path
string
The namespace to summarize, e.g. pms.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/pms' \
-H 'Authorization: Bearer $TOKEN'
Returns the build identity of this server. Anonymous callers, and any caller without detail, get only the public subset: product, version (from the nearest git tag) and released (commit date). An authenticated admin or superadmin who passes detail=true also gets commit (short sha), built_at (compile time, UTC) and dirty (uncommitted changes at build time); detail from anyone else is silently ignored rather than refused. Answers 503 setup_required until first-run setup is complete. No credential needed, but a Bearer token that is sent must be valid (an expired one gets 401).
Parameters
Name
In
Type
Description
detail
query
boolean
true to include commit, built_at and dirty. Honoured only for an authenticated admin or superadmin.
The same merged OpenAPI 3.1 document served at /api/openapi.json (generated operations plus the hand-maintained extras), serialized as YAML with Content-Type application/yaml. Built once at server start. Anonymous and available before first-run setup completes, so the API can be explored without a credential; each operation's own security still applies when it is called.
Response 200
openapi: 3.1.0
info:
title: InventDB AI Platform (SOAR) — HTTP API
license:
name: Proprietary
version: 0.1.0
paths:
/health:
get:
tags:
- system
summary: Health check endpoint
operationId: health_check
SQL
Direct SQL execution via POST /sql. This is the primary read path into the InventDB engine: SELECT-only on the data plane today (writes go through db / bulk). The caller's JWT principal is enforced as a row-level-security (RLS) scope over every referenced table, and an optional ?metrics flag wraps the rows in a server-side timing envelope.
POST/sqlBearerInventDB SOAR + InventDB Serverless
Executes a SQL query against the InventDB engine and returns the matching rows. Use it for every read: filtered SELECTs, multi-table JOINs, GROUP BY aggregates, ORDER BY / LIMIT windowing, text search with FULLTEXT(), FUZZY() and SEARCH(), and search by meaning with MEANING(). RLS is applied automatically from the caller's principal (superadmin / admin / setup bypass it). Append ?metrics=1 to get a { rows, metrics } wrapper with server-side timing instead of the bare array. CRUD (INSERT / UPDATE / DELETE) is rejected here; those belong on /db/:namespace/:type/*.
Result keys mirror your SELECT list verbatim. A bare qualified column such as p.property_id is returned under the qualified key "p.property_id" (kept intact so JOINed tables that share a column name don't collide). Add an explicit alias, SELECT p.property_id AS property_id, whenever you want clean, unqualified keys in the response.
Path & query parameters
Name
In
Type
Description
metrics
query
string
Optional. 1 or true switches the response from a bare JSON array to a { "rows": [...], "metrics": {...} } wrapper carrying elapsedMs, count, truncated, and rowCap. Omit it (or any other value) for the legacy bare-array shape.
Request body
Name
In
Type
Description
sql
body
string
Required. The SQL text, executed verbatim under the caller's RLS scope. Identifiers are namespace.type (e.g. pms.properties). SELECT-only. MEANING(text_col) = 'phrase' / LIKE routes through the embedded MiniLM-L6-v2 semantic search (falls back to text-equality if no embedder is loaded).
parameters
body
object | null
Optional / reserved. Placeholder for prepared-statement binds. The engine inlines literals today; put values directly in sql.
Request: filtered SELECT
curl -s -X POST 'https://acme.sandbox.inventdb.com/sql' \
-H 'Authorization: Bearer $TOKEN' \
-H 'content-type: application/json' \
-d '{ "sql": "SELECT property_id, city, state, type, beds, baths, market_rent, market_value, status FROM pms.properties WHERE state = '\''VA'\'' AND status = '\''Occupied'\'' ORDER BY market_rent DESC LIMIT 3" }'
{
"sql": "SELECT property_id, city, state, type, beds, baths, market_rent, market_value, status FROM pms.properties WHERE state = 'VA' AND status = 'Occupied' ORDER BY market_rent DESC LIMIT 3"
}
curl -s -X POST 'https://acme.sandbox.inventdb.com/sql?metrics=1' \
-H 'Authorization: Bearer $TOKEN' \
-H 'content-type: application/json' \
-d '{ "sql": "SELECT p.property_id, p.city, l.tenant_name, l.contract_rent, l.status FROM pms.properties p JOIN pms.leases l ON l.property_id = p.property_id WHERE l.status = '\''Active'\'' ORDER BY l.contract_rent DESC LIMIT 3" }'
{
"sql": "SELECT p.property_id, p.city, l.tenant_name, l.contract_rent, l.status FROM pms.properties p JOIN pms.leases l ON l.property_id = p.property_id WHERE l.status = 'Active' ORDER BY l.contract_rent DESC LIMIT 3"
}
Response 200: { rows, metrics } wrapper
JOIN result columns are returned under their alias.column keys (e.g. p.property_id, l.tenant_name). The metrics block reports elapsedMs (parse + plan + execute + serialize; excludes network RTT), count (rows after RLS, equal to rows.length), and the unbounded-read guard (truncated / rowCap).
curl -s -X POST 'https://acme.sandbox.inventdb.com/sql?metrics=1' \
-H 'Authorization: Bearer $TOKEN' \
-H 'content-type: application/json' \
-d '{ "sql": "SELECT city, COUNT(*) AS units, AVG(market_rent) AS avg_rent, SUM(market_value) AS portfolio_value FROM pms.properties GROUP BY city ORDER BY portfolio_value DESC LIMIT 5" }'
{
"sql": "SELECT city, COUNT(*) AS units, AVG(market_rent) AS avg_rent, SUM(market_value) AS portfolio_value FROM pms.properties GROUP BY city ORDER BY portfolio_value DESC LIMIT 5"
}
Response 200: aggregated rows
Aggregates come back as JSON numbers (AVG / SUM as floats, COUNT as an integer) under the projected column alias. Text keys group case-insensitively, like every text comparison in InventDB, so "Reston" and "RESTON" are one group, and each group's key (city) shows a spelling stored in the records.
Three functions search text through the word index (BM25 ranking, no model needed). FULLTEXT(col [, col2 ...], 'query' [, 'all' | 'any']) finds rows holding every word (or any, with 'any'), with words stemmed and case ignored. FUZZY(col [, col2 ...], 'query') does the same and forgives typos: one edit for words of 3 to 5 characters, two for longer ones. SEARCH(col [, col2 ...], 'query') is made for search boxes: it matches any word, forgives typos, treats the last word as a prefix while it is being typed, and also ranks by meaning when the column has embeddings. Count with FULLTEXT or FUZZY, not SEARCH. Pass * for every word-indexed column.
The query text works like a web search: plain words, "an exact phrase", -word to exclude, prefix*, and OR. When the call is an AND term of the WHERE clause, rows come back best first and carry a _score you can select; the rest of the WHERE clause and your row rules still apply to every hit. A row is searchable as soon as its write returns.
MEANING(col) = 'phrase' matches by meaning (cosine distance below 0.5), and MEANING(col) LIKE 'phrase' is more lenient (below 0.7). It reads the column's distinct-value embeddings, which an admin builds with GET /api/vectors/{namespace}/{type}/{property}/regenerate; a row with a new distinct value is found after the next regenerate. Until they are built, MEANING matches the phrase as a case-insensitive substring. LEVENSTEINDISTANCE(col, 'text') (spelled without an "h") gives the edit distance, for WHERE LEVENSTEINDISTANCE(city, 'Herndn') <= 1.
Request: full-text search, best first
curl -s -X POST 'https://acme.sandbox.inventdb.com/sql' \
-H 'Authorization: Bearer $TOKEN' \
-H 'content-type: application/json' \
-d '{ "sql": "SELECT property_id, street, city, _score FROM pms.properties WHERE FULLTEXT(street, city, '\''stone mill'\'') LIMIT 10" }'
curl -s -X POST 'https://acme.sandbox.inventdb.com/sql' \
-H 'Authorization: Bearer $TOKEN' \
-H 'content-type: application/json' \
-d '{ "sql": "SELECT property_id, street, city, status FROM pms.properties WHERE FUZZY(street, '\''magnolai'\'') AND status = '\''Occupied'\''" }'
"rid" is still being typed, so it matches "Ridge" as a prefix. Because SEARCH matches any word and forgives typos, "rid" also reaches "Rd", one edit away, and those rows rank lower.
Parses one SELECT with the engine's own parser (the same preprocessing as /sql) and returns its structure WITHOUT executing it or touching storage: sources (alias -> namespace.type; isPrimary for the FROM table; idColumn is _id for the primary source and <alias>._id for joined ones), columns (output key, owning source alias - null for an unqualified or computed column - and property), isAggregate (GROUP BY or an aggregate in the SELECT list: rows have no single-record identity), hasJoins, joinTypes (inner, left, right, full, ...), hasWildcard (* / t.*), limit, offset, and warnings (derived tables, subquery bodies, UNION: treated as opaque / not editable). namespace fills bare table names. Powers the AI Canvas data-viewer card (which record each row and column belongs to, for inspect / edit / delete). Same read check as /sql: a non-admin needs read on every table named (403 {"ok": false, "error": ...}). 400 for empty SQL, a parse error or a non-SELECT statement. No LLM; works on every tier.
Request
{
"sql": "SELECT p.property_id, p.city, o.name AS owner_name FROM pms.properties p JOIN pms.owners o ON p.owner_id = o.owner_id LIMIT 50",
"namespace": "pms"
}
A single JSON-RPC 2.0 dispatcher at POST /mcp that lets any MCP-speaking client (Claude Desktop, Cursor, ChatGPT connectors, Gemini, or your own agent) drive the database directly. It is a peer of the SQL and REST surfaces on this page rather than a wrapper over them: the tools call the engine in-process, under the same RBAC and row-level-security scope as the caller's principal.
All 51 tools are present on both InventDB SOAR and InventDB Serverless.tools/list is not filtered by product, role, or tier: every client sees the same 51 definitions. The only product-dependent behaviour is inside a workflow step that calls an LLM (e.g. llm_extract): on InventDB Serverless that step fails when the run executes rather than when the tool is called. Reports, workflow authoring, and workflow runs themselves need no LLM and work identically on both.
Four JSON-RPC methods are served. resources/list and prompts/list answer with empty arrays (declared, unsupported); anything else returns -32601. Every response is HTTP 200, including parse and RBAC failures; the outcome lives in the JSON-RPC body, never in the status line.
The one endpoint. Accepts a JSON-RPC 2.0 request envelope and returns a JSON-RPC 2.0 response envelope. Interactive clients authenticate with OAuth 2.1 + PKCE and dynamic client registration, with discovery at /.well-known/oauth-authorization-server and /.well-known/oauth-protected-resource, with the flow served from /oauth/register, /oauth/authorize, /oauth/token and /oauth/revoke. Unattended callers (CI, scripts, the examples below) may present a plain Authorization: Bearer JWT from a service account instead.
Request envelope
Name
In
Type
Description
jsonrpc
body
string
Optional in practice; the server does not reject a missing or mismatched value. Send "2.0".
id
body
any
Correlation id, echoed verbatim on the response. Defaults to null when omitted.
method
body
string
Required. One of initialize, ping, tools/list, tools/call, resources/list, prompts/list.
params
body
object
Method arguments. For tools/call this is { name, arguments }.
Request: the full envelope, once
Every per-tool example further down shows only the params object. This is the wrapper they all go inside.
A successful tools/call returns content (the result JSON-stringified into a text block, for models that read text) alongside structuredContent (the same value as real JSON, for code). Read structuredContent. Binary tools replace the text block with MCP resource blocks.
A tool that fails still returns result with isError: true; this is the MCP contract, so the model sees the error as content and can retry. A transport or protocol failure uses the JSON-RPC error channel instead. Both arrive as HTTP 200.
Capability handshake. The client sends this first; the server answers with the protocol revision it implements and which capability families it advertises. Parameters are accepted and ignored; the response is constant for a given server build.
{
"protocolVersion": "2025-03-26",
"capabilities": {
"tools": { "listChanged": false },
"resources": { "listChanged": false, "subscribe": false },
"prompts": { "listChanged": false },
"logging": {}
},
"serverInfo": {
"name": "inventdb",
"version": "0.594.0",
"title": "InventDB — Local-First Data Layer"
},
"instructions": "InventDB is a schemaless, local-first data store. Use tools/list to discover available operations. ..."
}
listChanged: false on tools is load-bearing: the tool set is static for the life of the process, so a client may cache tools/list and will never receive a change notification.
Enumerates all 51 tools with their JSON Schema inputSchema. The list is a constant: it is not filtered by product, tier, role, or namespace grants, so a read-only user and a superadmin on InventDB SOAR and InventDB Serverless alike all receive the same 51 definitions. Authorisation is applied when a tool is called rather than when it is listed.
{
"tools": [
{
"name": "schema",
"description": "List all namespaces in this InventDB and the types (record classes) within each, with record counts. ...",
"inputSchema": {
"type": "object",
"properties": {
"include_system": { "type": "boolean", "description": "Include system namespaces (prefixed with '_'). Default false." }
}
}
}
/* … 50 more … */
]
}
Invokes one tool. params.name is the tool name; params.arguments is its argument object. Every call runs as the authenticated principal: RBAC decides whether the namespace and type are reachable, RLS filters the rows, and mutations land in the audit log attributed to that user.
Name
In
Type
Description
name
params
string
Required. One of the 51 tool names below. Unknown names return -32601.
arguments
params
object
Tool arguments, matching that tool's inputSchema. Defaults to {} when omitted.
Lists every namespace and the types inside it with record counts. This is the intended first call of a session: it is how an agent discovers that pms exists and what lives in it. System namespaces (leading _) are omitted unless asked for.
Name
Type
Required
Description
include_system
boolean
no
Include _-prefixed system namespaces (_attachments, _reports, _system…). Default false; rarely needed.
Returns the observed shape of a type by sampling real records. InventDB is schemaless: there is no declared schema, no required-field list, no enums. Everything here is inferred from data, so a property missing from the sample is not proof it never occurs. Use it before writing SQL: guessing column names is the most common agent failure.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
type
string
yes
e.g. properties.
sample_size
integer
no
Records to sample. Default 500, min 1, max 5000. Raise it when a type is known to be heterogeneous.
Structured equality search over one type. Builds a parameterised query under the hood, so values are safely quoted; prefer this over hand-writing SQL whenever the filter is plain equality. All where conditions are AND-ed. For ranges, OR, or LIKE, use the sql tool.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
type
string
yes
e.g. leases.
where
object
no
{field: value}, all AND-ed as equality. Omit to match everything.
fields
string[]
no
Project only these properties (the id is always included). Cuts token cost sharply on wide records.
Fetches one record by id. Returns the record as JSON, or null when it does not exist or RLS hides it; the two cases are deliberately indistinguishable so the tool cannot be used to probe for hidden ids.
Executes a read-only SQL query with the same engine and grammar as POST /sql, including JOIN, GROUP BY, aggregates, and MEANING() semantic search. Identifiers are namespace.type. Writes are rejected: mutations go through the two-phase propose/commit tools so the user sees them before they land.
Name
Type
Required
Description
query
string
yes
A SELECT statement. Note the argument is named query here, not sql as on the REST endpoint.
Call: aggregate over transactions
{
"name": "sql",
"arguments": {
"query": "SELECT account_category, COUNT(*) AS n, SUM(amount) AS total FROM pms.transactions WHERE type = 'Income' GROUP BY account_category ORDER BY total DESC LIMIT 3"
}
}
{
"name": "sql",
"arguments": {
"query": "SELECT p.property_id AS property_id, p.city AS city, l.tenant_name AS tenant_name, l.contract_rent AS contract_rent FROM pms.properties p JOIN pms.leases l ON l.property_id = p.property_id WHERE l.status = 'Active' ORDER BY l.contract_rent DESC LIMIT 3"
}
}
structuredContent
Alias every projected column. A bare qualified column such as p.property_id comes back under the literal key "p.property_id", which is awkward to consume from an agent.
No MCP tool writes in one step. Each mutation is proposed, returning a proposal_id and a preview, and nothing changes until commit is called with that id. Proposals expire after 5 minutes. This shape is defined by the tools themselves, so it holds for every client regardless of configuration: an agent cannot silently edit data. Every committed mutation writes an audit entry, and every audit entry is reversible via undo.
Stages a partial update. patch is sparse: only the fields you name change; everything else is left alone. The response carries a before/after diff so the change can be reviewed before commit.
Applies a pending proposal. This is the only call in the write path that changes data. It writes an audit entry whose id can later be handed to undo. A proposal older than 5 minutes returns -32003; re-propose and commit again.
{
"content": [ { "type": "text", "text": "proposal 'prop_7f3c1a9e' not found or expired" } ],
"isError": true,
"errorCode": -32003,
"errorMessage": "proposal 'prop_7f3c1a9e' not found or expired"
}
Discards a pending proposal without applying it. Proposals also expire on their own after 5 minutes, so this is a courtesy; use it when the user rejects a staged change so the agent's state stays honest.
Attachment bytes never pass through the model's context unless you explicitly ask for them. attach_search answers content questions from server-side extracted text and returns signed URLs; the upload tools hand the browser a drop-zone so files go browser → server directly. Record-bound files use the parent record_id; type-level files use the reserved _vault id.
The primary attachment tool; use it first for any question about uploaded files, whether about content, metadata, listing, or ranking. It queries the five system tables behind attachments (_attachments, _attachment_text, _attachment_chunks, _attachment_versions, _attachment_embeddings) coherently, and bytes never leave the server.
Modes.keyword matches filename and description; fulltext matches extracted text; semantic runs MEANING() over chunk embeddings and returns nothing if embeddings have not been generated yet; combined (the default) runs all three with weights 0.2 / 0.3 / 0.5. Pass query: "*" to list rather than search.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
query
string
yes
Natural-language query, exact phrase, or "*" (empty string is an alias) to list everything matching the filters.
Returns raw bytes as an MCP resource block, for in-sandbox analysis: opening an XLSX with pandas, parsing a custom binary, rendering an image. Expensive: bytes expand roughly 1.33× under base64, so a 1 MiB cap is on the order of 1.4M output tokens. Prefer attach_read or attach_url unless you truly need the bytes.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
att_id
string
yes
Attachment id.
max_bytes
integer
no
Hard cap. Default 1048576 (1 MiB), max 10485760 (10 MiB).
byte_range
integer[2]
no
[start, end_exclusive] slice to read just a header or footer. Still capped by max_bytes.
Lists the attachments on one record. Equivalent to attach_search with query: "*" plus type and record_id, but cheaper and simpler when you already know the record.
Mints a signed absolute URL the user can click in a browser. The URL embeds a one-hour token, so no bearer header is needed. Use it when you already hold an att_id and need a fresh link; attach_search already returns one per result.
The preferred upload path for any file, local or remote. Returns a one-time browser drop-zone URL; the user drops a file and the bytes travel browser → server directly, never through the model's output tokens. Poll upload_check with the returned token to learn the outcome.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
type
string
yes
e.g. inspections.
record_id
string
no
Parent record. Omit for type-level files; the server defaults to _vault.
filename_hint
string
no
Default filename if the upload does not carry one.
{
"upload_url": "https://acme.sandbox.inventdb.com/upload/u_3f9d1c47",
"upload_token": "u_3f9d1c47",
"expires_at_secs": 3600,
"instructions": "Give this link to the user. It accepts one file, once."
}
Same drop-zone mechanism as attach_upload_url, but the dropped file is parsed and imported as records rather than stored as an attachment. This is the preferred bulk-import path when the file is on the user's machine.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
type
string
yes
Target type, e.g. transactions.
format
string
no
csv | tsv | txt | json | jsonl | xlsx | xls | xlsb | ods | auto. Auto-detected from the extension when omitted.
Polls an upload token issued by attach_upload_url or bulk_upload_url. Call it after handing the link to the user to find out whether the file landed and what came of it.
Uploads an attachment from a path on the server's filesystem. Only useful when the client and server share a machine (self-hosted). Base64 / inline uploads were removed deliberately: shuttling bytes through model context is slow and expensive, so attach_upload_url is the general answer.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
type
string
yes
e.g. inspections.
record_id
string
yes
Parent record id.
path
string
yes
Absolute path on the server.
filename
string
no
Override the stored filename. Defaults to the basename of path.
Lists every version of an attachment with full per-version metadata. Versions are 1-based and immutable; re-uploading over an attachment mints a new one rather than overwriting.
Fetches raw bytes of a specific version, with the same delivery model as attach_download. Ask for several versions at once with versions; each becomes its own resource block, and token cost multiplies accordingly, so keep the per-version cap tight.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
att_id
string
yes
Attachment id.
version
integer
no
Single version (min 1). Mutually exclusive with versions.
Promotes a past version to current: a non-destructive rollback. The chosen historical version is copied forward as a new latest version; nothing is deleted.
Name
Type
Required
Description
namespace
string
yes
e.g. pms.
att_id
string
yes
Attachment id.
version
integer
yes
Historical version number to promote (min 1).
comment
string
no
Note recorded on the new version explaining the rollback.
Call
{ "name": "attach_version_promote", "arguments": { "namespace": "pms", "att_id": "att_c81f2d05", "version": 1, "comment": "v2 was the wrong scan" } }
Three routes in, by where the data lives. Records the agent already holds go through bulk_insert (capped at 20, because each record costs output tokens). A file on the user's machine goes through bulk_upload_url. A file on the server goes through bulk_insert_preview → bulk_insert_commit, which infers column types and lets the user correct them before anything is written.
Inserts a small number of records the agent already knows field by field. Hard cap of 20; each record's full JSON is emitted as part of the tool call, so this is the expensive path by design. Anything larger belongs in a file.
Parses a server-local file and stages it as a proposal without inserting. Returns the inferred per-column types and sample rows so the user can correct the schema before committing.
Applies a bulk_insert_preview proposal, optionally overriding the inferred column types and the strings treated as null. Pin a type when inference guessed wrong: a zero-padded account code inferred as integer, for instance, should be pinned to string.
Imports a server-local file directly, skipping the preview step. Advanced: only appropriate when the path is on the same machine as the server (self-hosted) and the user supplied that path. Prefer bulk_insert_preview so the user sees inferred types first.
Reverses a prior mutation by its audit entry id. An insert is undone by deleting the record; an update by restoring the prior state; a soft_delete by restoring the record. The undo is itself audited, so it can be undone in turn.
Opt-in authored policy rather than inference. A rule is an expression over record that must hold for writes to a type. Authoring follows the same propose-then-save shape as data writes: rules_propose dry-runs the expression across existing records and reports how many would fail, and only rules_save persists it.
Drafts a rule and dry-runs it over existing records, returning how many rows already violate it plus a sample. Nothing is persisted; pass the returned proposal_id to rules_save to keep it.
Name
Type
Required
Description
type
string
yes
Type the rule applies to.
expression
string
yes
Boolean expression over record, e.g. record.contract_rent > 0.
message
string
yes
Shown to the user when the rule fails.
severity
string
no
error blocks the write; warning allows it. Default warning.
Call
{
"name": "rules_propose",
"arguments": {
"type": "leases",
"expression": "record.deposit_held >= record.contract_rent",
"message": "Deposit held is below one month's contract rent.",
"severity": "warning"
}
}
Report templates are HTML plus SQL; no LLM is involved in saving or rendering one, which is why all four tools work identically on InventDB Serverless. Templates are stored in the _reports system namespace and are interchangeable with those authored in the Management Console. Rendering runs the template's SQL live against your data under the caller's RLS scope.
Requires admin or superadmin. Creates or updates a template. Two authoring shapes, mixable in one document: <script type="server"> blocks (full JS, needed for charts, conditional sections and custom formatting) and {{placeholder}} markers backed by a bindings map (quick KPIs and flat tables). Only {{name}} and {{TABLE:name}} are supported; {{SCALAR:}}, {{JSON:}} and {{#each}} render as literal text.
Name
Type
Required
Description
name
string
yes
Display name.
html
string
yes
HTML body. Wrapped in a print-ready skeleton with @page CSS if you do not supply <html>.
bindings
object
no
{placeholder: SQL}. Only needed for {{placeholder}} markers; server scripts query directly.
id
string
no
Existing id to update. Omit to create.
Call
{
"name": "report_template_save",
"arguments": {
"name": "Monthly Rent Roll",
"html": "<h1>Rent roll: active leases</h1>\n<p>Total monthly: ${{total_rent}}</p>\n<table>\n <thead><tr><th>Property</th><th>Tenant</th><th>Rent</th></tr></thead>\n <tbody>{{TABLE:rows}}</tbody>\n</table>",
"bindings": {
"total_rent": "SELECT SUM(contract_rent) AS value FROM pms.leases WHERE status = 'Active'",
"rows": "SELECT property_id AS \"Property\", tenant_name AS \"Tenant\", contract_rent AS \"Rent\" FROM pms.leases WHERE status = 'Active' ORDER BY contract_rent DESC"
}
}
}
Renders a saved template to print-ready HTML, running its SQL live. parameters supply values for :name references in the bindings (no leading colon in the key). A missing parameter causes the surrounding WHERE field op :name clause to be stripped, which is how a template is made to render both filtered and unfiltered. The response reports what did not resolve, so an agent can iterate.
Name
Type
Required
Description
template_id
string
yes
Template to render.
parameters
object
no
Values for :name references in the template's SQL.
Read, run, version and activate event-driven workflows. All seven are available on both products: authoring, listing and running a workflow needs no LLM, so these are available on InventDB Serverless as well, matching the REST surface. The single product-dependent case is a step that calls an LLM (such as llm_extract): on InventDB Serverless that step fails when the run reaches it, and workflow_runs reports the failure. Authoring a workflow from scratch is a REST operation; see Workflows.
Lists recent runs with status, timestamps, error and whether the run was sandboxed. Read-only. Because workflow_run is asynchronous, this is how you learn the outcome.
Fires a workflow once, by hand. Queues the run and returns an event_id immediately; execution is asynchronous, so poll workflow_runs for the outcome. Two optional modifiers: pin an older version, or force sandbox for this run only so side-effects are mocked.
Name
Type
Required
Description
workflow_id
string
yes
Workflow id.
version
integer
no
Run this version's frozen plan instead of the current one.
sandbox
boolean
no
Force this run to be sandboxed (mock side-effects) for this run only.
Rolls a workflow back to a previous version. Non-destructive: it mints a new latest version that copies the chosen old plan, so nothing in the history is lost.
Activates a workflow so it fires on its trigger, or pauses it. Independent of the sandbox flag; an active workflow can still be sandboxed, in which case it runs on schedule but mocks its side-effects.
Data-entry helpers. Instead of an agent interviewing the user field by field, it can hand over a real HTML form with FK typeahead and rule-aware validation. analyze_type_for_form → save_form_template → render_record_form is the authoring path; render_record_form alone auto-generates a basic form.
Returns the schema, FK relationships, cascade dependencies and display-field hints for a type: which fields need a lookup, which cascade from another, and what to show in a picker. Call this before authoring a form template.
Saves a reusable form template. The HTML uses {{field:…}} markers for inputs and {{lookup:…}} for FK typeahead. Note the argument is typeName here, not type as in most other tools.
Name
Type
Required
Description
name
string
yes
Template display name.
namespace
string
yes
e.g. pms.
typeName
string
yes
Target type, e.g. work_orders.
htmlTemplate
string
yes
HTML with {{placeholder}} syntax.
style
object
no
{ primaryColor, fontFamily }.
Call
{
"name": "save_form_template",
"arguments": {
"name": "New work order",
"namespace": "pms",
"typeName": "work_orders",
"htmlTemplate": "
Report an issue
\n{{lookup:property_id|label=Property|from=pms.properties|display=property_id}}\n{{field:issue|label=What is wrong?|type=text|required}}\n{{field:priority|label=Priority|type=select|options=low,normal,urgent}}",
"style": { "primaryColor": "#6A46C1" }
}
}
structuredContent
{ "saved": true, "template_id": "form_wo_new", "name": "New work order", "namespace": "pms", "typeName": "work_orders" }
Returns a self-contained HTML form. Template mode (preferred) renders a saved template with FK typeahead, cascade filters and SQL validation; find one with list_form_templates. Auto mode (namespace + type, no template_id) generates a basic form from the observed schema. Pass id to pre-populate for an edit.
Record CRUD over /db/:namespace/:type[/:id]. Insert, read, update, and delete individual documents in any type, plus a cheap id-listing walk. The engine is schemaless: new properties and new types are created on first write, no migration step. Writes stamp _id, _createdAt, _createdBy, _updatedAt, and _updatedBy from the JWT principal, validate _relationships referential integrity (409 on conflict), and enforce row-level security so you only touch rows your grants admit.
Insert a single document into :namespace.:type. The full JSON body is the document; there is no envelope. The engine assigns _id (UUID v4 unless you supply one) and stamps the created/updated audit fields from your token. New namespaces and types are created lazily on first write, and any new property is indexed on first sight. Indexing is not optional: every write updates the property and vector indexes before it returns, so reads are consistent immediately. Plan large loads around that cost.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms. Created lazily if new.
type
path
string
e.g. properties. Created lazily if new.
disableIndexing
query
boolean
Accepted and ignored; indexing cannot be disabled.
Update an existing document by _id, which MUST be present in the request body. The body you send becomes the new latest version (append-only at the storage layer; older versions stay readable via point-in-time queries). Row-level filters must accept both the pre-image and the post-image: you can neither edit a row you don't own nor move one out of your ownership scope. Missing _id is 400; no matching row is 404; a referential-integrity conflict is 409.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms.
type
path
string
e.g. properties.
disableIndexing
query
boolean
Accepted and ignored; indexing cannot be disabled.
Fetch a single document by _id. The response body is the document JSON itself with no envelope, including the system fields _id, _createdAt, and _updatedAt. RLS row filters apply: a row outside your scope returns 404 rather than 403, so the API never leaks whether an id you can't see exists.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms.
type
path
string
e.g. properties.
id
path
string
Document _id, e.g. 2bba668e-ad1c-447b-9e70-7cf9d9221b2c.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/db/pms/properties/2bba668e-ad1c-447b-9e70-7cf9d9221b2c' \
-H 'Authorization: Bearer $TOKEN'
Delete a document by _id. This is a soft delete: a tombstone supersedes the row for normal SELECTs, but earlier versions stay queryable for point-in-time reads. Any attachments owned by this _id are removed transactionally. A row protected by referential integrity (referenced by another type via _relationships) cannot be deleted until those references clear, and the call returns 409.
List all document _ids in a type. This is cheap: it walks the per-type id index only and reads no property values. RLS row filters still apply, so you only see the ids of rows you're allowed to read. For paged fetches of full rows, use POST /sql with LIMIT and ORDER BY instead of hydrating every id here.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms.
type
path
string
e.g. properties.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/db/pms/properties' \
-H 'Authorization: Bearer $TOKEN'
Convenience query wrappers that cover the most common single-type read patterns (substring search, numeric ranges, date ranges, and AND-composed multi-property filters) without hand-writing SQL. Each is a thin shim over the engine's SQL path (RLS row filters and per-table grants still apply), and every one returns a bare JSON array of full row objects. For OR semantics, joins, aggregation, or semantic MEANING() search, use POST /sql directly.
Substring search on a single string property. This is a convenience wrapper over SELECT * FROM ns.type WHERE prop LIKE '%q%'. It is fast on small types; for larger types prefer /sql with an explicit LIMIT. Use it for quick lookups like finding an owner by part of their name or a work order by a keyword in the issue text.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
Type / table name, e.g. owners
prop
query
string
String property to scan, e.g. name
q
query
string
Substring to match (LIKE-style), e.g. Whitfield
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/query/pms/owners/contains?prop=name&q=Whitfield' \
-H 'Authorization: Bearer $TOKEN'
Closed-interval numeric range query: lo <= prop <= hi. Both bounds are inclusive doubles. Use it to pull rows where a numeric column falls inside a window, for example properties whose market_rent is between two dollar amounts, or work orders in a cost band. Returns a bare array of full row objects.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
Type / table name, e.g. properties
prop
query
string
Numeric property to range over, e.g. market_rent
lo
query
number
Inclusive lower bound, e.g. 1500
hi
query
number
Inclusive upper bound, e.g. 1600
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/query/pms/properties/range?prop=market_rent&lo=1500&hi=1600' \
-H 'Authorization: Bearer $TOKEN'
Date / DateTime range query with inclusive bounds. Bounds are ISO 8601 strings; date-only literals are treated as midnight UTC, so to capture the entire end day pass a full timestamp such as end=2026-10-31T23:59:59Z. Use it for date-window reports like leases starting in a given month or transactions posted in a quarter. Returns a bare array of full row objects.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
Type / table name, e.g. leases
prop
query
string
Date / datetime property to filter, e.g. lease_start
start
query
string
Inclusive start (ISO 8601), e.g. 2025-10-01
end
query
string
Inclusive end (ISO 8601), e.g. 2025-10-31
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/query/pms/leases/daterange?prop=lease_start&start=2025-10-01&end=2025-10-31T23:59:59Z' \
-H 'Authorization: Bearer $TOKEN'
AND-composed multi-property filter with pagination and ordering: a convenience over /sql for the very common "filter on N properties, sort, paginate" case. Each entry in conditions becomes one WHERE prop OP value clause and all clauses are AND'ed together; for OR semantics use /sql directly. Sort with order_by + order_dir and page with limit / offset. Returns a bare array of full row objects.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
Type / table name, e.g. properties
conditions
body
array
Required. AND'ed list of { prop, op, value }. Empty list returns all readable rows (subject to RLS).
conditions[].op
body
string
One of eq, ne, gt, gte, lt, lte, like (SQL LIKE), contains (case-sensitive substring).
order_by
body
string?
Property to sort by, e.g. market_rent.
order_dir
body
string?
asc (default) or desc, case-insensitive.
limit
body
integer?
Max rows. No cap enforced if absent; use with care.
High-throughput, whole-batch operations against a type: insert many documents in one round-trip, and remove rows en masse by id, by filter, or all at once. Destructive endpoints layer on guard rails (referential-integrity checks, an explicit CONFIRM phrase, and admin-only type/namespace drops) so a single call can never quietly cascade.
Insert N documents in a single request instead of one POST per row. Accepts either a bare JSON array or an { "documents": [...] } envelope. RBAC and the writer's row-filter are validated once up front, then the batch streams into the engine; per-row failures are aggregated into error while the ids that landed are still returned. A successful insert responds 201 Created; an empty request (zero documents) is a 200 no-op. Indexing always runs as part of the write and cannot be turned off, so size large loads around that cost.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms. Created lazily on first write.
type
path
string
e.g. properties. Created lazily on first write.
disableIndexing
query
boolean
Accepted and ignored; indexing cannot be disabled. Every write indexes synchronously; budget for that on large loads.
Delete a set of documents by _id in one call. Referential integrity is validated for the entire batch before any row is removed: if any id is referenced by another type via _relationships, the whole call aborts with 409 and nothing is deleted. Ids that don't exist are skipped silently, so deletedCount may be less than ids.length. Returns 206 if some individual deletes errored after the RI gate passed.
Delete every row that matches a filter condition. The engine runs a SELECT _id with the filter applied, then deletes each matched row. The filter is a property→value map whose terms are AND'ed into a SQL WHERE clause; e.g. {"status": "void", "year": 2024} becomes WHERE status = 'void' AND year = 2024. Safer than deleteAll because the filter shape forces an explicit decision about what to drop.
Delete every row in a type: a truncate. The request body must carry the literal confirmation phrase "CONFIRM"; anything else refuses with 400 to guard against accidental cascades. The type folder, its properties, and history rows remain (use DELETE /api/:ns/:type to drop the type entirely). Requires delete access on the type.
Drop an entire type (its data directory, segments, indexes, and attachments) from disk. This is destructive and irreversible: unlike a soft-deleted row you cannot point-in-time-query it back. Admin / superadmin only. Use deleteAll instead if you only want to empty the rows but keep the type and its schema.
Drop an entire namespace and every type inside it; the whole namespace folder is removed. This is the most destructive operation in the API, equivalent to dropping every type sequentially. Admin / superadmin only. There is no undo and no point-in-time recovery once the folder is gone.
The universal vector embedding pipeline. Every user type with string properties is embedded automatically (MiniLM all-MiniLM-L6-v2, 384 dims); new writes are embedded inline and sealed segments are backfilled by a background worker. These admin-only endpoints report install status, give an aggregated per-segment overview for the Settings → Vector Indexes card, and trigger a one-shot backfill. You do not call them to search. Search by meaning in SQL with WHERE MEANING(type) LIKE 'apartment building', which reads the column's distinct-value embeddings (an admin builds them with the per-property regenerate endpoint under Vectors, per-property), or with SEARCH(), which ranks by words and meaning together. POST /sql describes both.
Returns whether the universal vector embedding pipeline is installed and loadable on this instance. Use it as a lightweight health probe before relying on MEANING() semantic search in SQL, or from the admin console to confirm the MiniLM model + tokenizer files were found at boot. Admin/superadmin only; a non-admin caller gets 403.
Path & query parameters
None. The status is instance-wide rather than scoped to a namespace or type.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/vectors/universal/status' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"embeddingGeneratorInstalled": true,
"modelFilesExist": true,
"note": "Universal vector embedding pipeline is active. New writes are auto-embedded; sealed segments are auto-backfilled in background."
}
Aggregates per-segment vector index counts across every user namespace.type (for example every table in the pms namespace) into a single round-trip for the Settings → Vector Indexes card. Cheap and lock-free: it walks each type's segments.json manifest from disk and tallies; it runs no DB queries. Use it to see how many sealed segments are still vectors_pending versus fully indexed. Admin/superadmin only.
Path & query parameters
None. Counts are aggregated across all user (non-_) namespaces and types.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/vectors/universal/overview' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"embeddingGeneratorInstalled": true,
"modelName": "all-MiniLM-L6-v2",
"modelDimensions": 384,
"typesTotal": 14,
"activeSegments": 14,
"sealedSegmentsTotal": 6,
"sealedSegmentsIndexed": 5,
"sealedSegmentsPending": 1,
"note": "Pipeline active. 1 sealed segment marked vectors_pending across pms.transactions; background worker will index it shortly."
}
Here typesTotal: 14 reflects the 14 pms tables (properties, owners, leases, tenants, transactions, work_orders, vendors, inspections, compliance, daily_tasks, …). Each type has exactly one active write segment, so activeSegments equals the number of types with data on disk. sealedSegmentsPending counts sealed segments the background backfill worker still needs to embed.
Triggers a one-shot, synchronous backfill across ALL types/segments tagged vectors_pending. A background thread already does this continuously, but this endpoint forces an immediate run from the admin console, useful right after a bulk import into pms.transactions or pms.leases when you want semantic search over the new rows without waiting for the worker. Returns the number of segments processed and wall-clock time. Admin/superadmin only; internal failure returns 500.
Path & query parameters
None. There is no request body; the backfill scope is every pending segment across all user types.
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/vectors/universal/backfill' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"processedSegments": 1,
"elapsedMs": 3
}
When nothing is pending (all sealed segments already indexed), the response is { "processedSegments": 0, "elapsedMs": 3 } and the call is effectively a no-op.
Indexes (admin)
Property B-tree index management: inspect per-property index statistics, run full rebuilds (Server-Sent Events stream), poll rebuild progress, consolidate (flush + fsync) indexes to disk, and pause/resume property indexing globally during bulk loads. Every endpoint is admin-only; the index files live on disk under <data_root>/<ns>/<type>/prop_*.tree.
Returns a status grid for every user-namespace type, with per-property B-tree statistics (tree height, leaf count, distinct values, estimated cardinality). Use it to power an admin index-health dashboard or to decide which types need a rebuild. Admin-only; internal _* namespaces are skipped.
indexStatus is active under normal operation; it reads rebuilding while a rebuild is in flight, or stale when property indexes lag the latest writes (usually self-heals on the next checkpoint).
Polling alternative to the SSE rebuild stream; returns a single snapshot of rebuild progress for one type. status is one of idle, rebuilding, completed, or failed. Poll this from tooling that can't (or shouldn't) hold an EventSource connection open while a rebuild runs.
While a rebuild is active the same shape carries live numbers, e.g. "status": "rebuilding", "progressPercent": 42.0, "recordsProcessed": 210, "totalRecords": 500.
Runs a full index rebuild for one type: it walks every row, drops the existing prop_*.tree files, and re-indexes from scratch. The response is a Server-Sent Events stream of progress frames; the terminal data: frame has status: completed or failed, followed by an event: done frame. Because EventSource can't send an Authorization header, pass the JWT via the ?token= query parameter instead.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
e.g. leases
token
query
string
JWT bearer token (EventSource has no header support).
POST variant of the SSE rebuild: same outcome as GET /api/indexes/:ns/:type/rebuild, but addressable via POST so tooling that can't open an EventSource connection can still kick off a rebuild. It runs as the system principal and streams the same progress frames back. Prefer this from scripts and background jobs; prefer the GET/SSE form for browser-driven admin consoles.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
e.g. leases
Request
curl -sN -X POST 'https://acme.sandbox.inventdb.com/api/pms/leases/reindex' \
-H 'Authorization: Bearer $TOKEN'
Flushes and fsyncs the indexes for one type to disk. Synchronous: the call returns only once every dirty page is durable. Use it before snapshotting the data directory or before a graceful shutdown so no index writes are lost.
Path & query parameters
Name
In
Type
Description
namespace
path
string
e.g. pms
type
path
string
e.g. properties
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/indexes/pms/properties/consolidate' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"ok": true,
"message": "Index consolidation completed for pms.properties - all data synced to disk"
}
Flushes and fsyncs every user-namespace type to disk in one call; it walks list_namespaces() → list_types(), skipping internal _* stores, and syncs each. Returns 200 when all types sync cleanly, or 206 if some fail, with a message that summarizes the count.
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/indexes/consolidate-all' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"ok": true,
"message": "Consolidated 20 type stores - all data synced to disk"
}
Response 206
{
"ok": false,
"message": "Consolidated 18 of 20 type stores - 2 failed to sync",
"error": "pms.transactions: disk I/O error"
}
Disabled by design: this endpoint is a no-op. It returns 200 with an explanatory message instead of deleting anything. The Rust engine rebuilds indexes incrementally from the source data, so an API-driven delete would leave a window of empty indexes with no safety net. To refresh indexes, use GET /api/indexes/:ns/:type/rebuild (or the POST /reindex variant) instead.
{
"ok": true,
"message": "Index deletion not recommended. Type pms.properties has 29 property indexes. Use /rebuild endpoint to refresh indexes instead."
}
Globally enables or disables property indexing. When disabled, every write skips index maintenance, the standard trick for speeding up large bulk loads. Afterwards, re-enable with this endpoint and then call POST /api/indexes/:ns/:type/consolidate (or run a full rebuild) so the indexes catch up with the loaded rows.
Path & query parameters
Name
In
Type
Description
enabled
query
boolean
true to re-enable indexing, false to pause it. Required.
Request
# pause indexing before a bulk load
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/indexing?enabled=false' \
-H 'Authorization: Bearer $TOKEN'
# ...bulk-load pms.properties, then re-enable...
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/indexing?enabled=true' \
-H 'Authorization: Bearer $TOKEN'
Blocks until all pending index work has drained, then returns 200. Handy in scripted workflows that bulk-load a type (e.g. pms.transactions) and then immediately query it by an indexed column; call this first to guarantee the indexes are caught up before the read.
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/indexing/wait' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"ok": true,
"message": "All indexing operations completed"
}
Clears the rebuild-progress history table, resetting the "Last rebuild" timeline shown in the admin console after maintenance. This is bookkeeping only; it has no effect on live data or on the indexes themselves.
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/indexes/clear-history' \
-H 'Authorization: Bearer $TOKEN'
Response 200
{
"ok": true,
"message": "Rebuild history cleared"
}
Recounts the records actually present in each type and corrects the maintained COUNT(*) counter wherever it has drifted (older binaries left some counters off, so COUNT(*) could over-report while row reads were correct). Changes counters only, never records, and is safe to re-run: a second call over unchanged data reports nothing. Covers the types currently loaded in this process (every type opened since the server started, system types included); a type not yet opened is not checked. Runs synchronously. Each delta is actual minus the old counter, so a negative delta means COUNT(*) had been over-reporting. No request body. Admin or superadmin required.
Lists every type in every non-system namespace with its record count, number of indexed properties, and the total index entries and distinct values summed over all of its property indexes. asyncStatus is always "idle". Any authenticated caller may read it: there is no role check and the list is not filtered by the caller's grants, so it exposes every user namespace's type names and record counts. Opens each type and walks each of its property indexes, so it costs more on instances with many types. Read-only.
The foreign-key graph for a namespace. Each edge is a property-to-property link between two types (e.g. pms.leases.property_id → pms.properties.property_id) carrying a cardinality hint and an enforce flag for referential integrity. Read the graph, replace it (admin only), drop it, auto-detect candidate edges from column-name heuristics plus data sampling, or fetch the per-type property schema that drives the Console's relationship designer.
Returns the full relationship graph for a namespace as a single graph record. Each entry in edges links a source property to a target property, with a cardinality hint (many-to-one, one-to-many, …), an enforce flag for referential integrity, and an optional human label. Use it to render join diagrams or to seed an edit before a PUT. An empty graph (edges: []) is returned when nothing is configured yet.
Path & query parameters
Name
In
Type
Description
namespace
path
string
Namespace whose graph to read, e.g. pms.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/relationships/pms' \
-H 'Authorization: Bearer $TOKEN'
Replaces the relationship graph for a namespace. Admin / superadmin only: the graph defines the data model itself (which types reference which, and on what columns), so a plain write grant is not enough. PUT semantics are wholesale: the supplied edges array fully replaces what was there, so GET first, edit the array, then send it back. The optional layout blob (node positions, zoom) is round-tripped verbatim.
Drops the relationship graph for a namespace. Requires admin permission on the namespace. The underlying edge records and the saved layout are removed, but the namespace's actual data (properties, leases, tenants, …) is left completely untouched; only the FK metadata goes away.
Auto-detects candidate relationships by combining column-name heuristics (*_id columns map to a matching type), data sampling (checks that the foreign-key values actually resolve in the target type), and an optional LLM assist for naming-mismatch links. Pass an optional types array to restrict the scan; omit it to scan every type in the namespace. The response is suggestions only; nothing is persisted. The user reviews them in the designer and PUTs the final set back via save_relationships.
Returns every non-system type in a namespace together with its recordCount and known properties[]. This drives the InventDB Console's relationship designer so the user can pick valid source and target columns (e.g. leases.property_id → properties.property_id). Property lists reflect what the schemaless engine has seen so far, so newer columns appear automatically as rows are written.
Path & query parameters
Name
In
Type
Description
namespace
path
string
Namespace whose type schema to list, e.g. pms.
Request
curl -s -X GET 'https://acme.sandbox.inventdb.com/api/relationships/pms/types-schema' \
-H 'Authorization: Bearer $TOKEN'
Event-driven workflows engine: workflow CRUD, the runs timeline, manual fire, run export, and lifecycle toggles (pause / resume / activate). A workflow pairs a trigger (cron, gmail, webhook, manual, …) with an ordered plan of steps (sql_query, render_report, llm_extract, send_email, notify_user, create_calendar_event, finish, …). Every workflow is owned by the caller and scoped by RLS. All endpoints require a Bearer token.
Create a new event-driven workflow owned by the caller. The body carries the display name, the trigger_kind + kind-specific trigger_spec, a short natural-language trigger_intent, and the ordered plan array of steps. New workflows land in pending_approval=true / active=false; call /activate (or the pause/resume toggles) to let the dispatcher fire them. sandbox defaults to true, so a fresh workflow never produces externally-visible side effects until you deliberately turn sandbox off.
Request body fields
Name
In
Type
Description
name
body
string
Display name (non-empty).
trigger_kind
body
string
cron | gmail | webhook | manual | …
trigger_spec
body
object
Kind-specific config, e.g. { "expr": "0 9 * * *", "tz": "Asia/Calcutta" } for cron.
trigger_intent
body
string
Short natural-language description of what should happen.
plan
body
array
Ordered WorkflowStep objects. Each needs idx, label, narration, kind and kind-specific fields (a notify_user step needs title + body; a sql_query step needs sql).
tools_allowed
body
array
Allowlist for LLM tool calls inside the run (empty = none).
budget
body
object
Optional ceiling, e.g. { "max_tool_calls": 25, "max_input_tokens": 50000 }.
sandbox
body
boolean
Defaults true; when true the run makes no externally-visible side effects (emails go to inbox staging only).
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/workflows' \
-H 'Authorization: Bearer $TOKEN' \
-H 'content-type: application/json' \
-d '{
"name": "Overdue Rent Alert",
"trigger_kind": "cron",
"trigger_spec": { "expr": "0 8 * * *", "tz": "Asia/Calcutta" },
"trigger_intent": "Every morning, find rent transactions and notify the operator.",
"plan": [
{ "idx": 1, "label": "Find rent activity",
"narration": "Pulls recent rent income rows for the portfolio.",
"kind": "sql_query", "save_as": "rent",
"sql": "SELECT property_id, amount FROM pms.transactions WHERE type = '\''Income'\'' AND account_category = '\''Rent'\'' LIMIT 50" },
{ "idx": 2, "label": "Notify operator",
"narration": "Posts an in-app notification with the rent summary.",
"kind": "notify_user", "title": "Rent summary ready",
"body": "Rent activity summary is ready to review." }
],
"tools_allowed": [],
"sandbox": true
}'
{
"name": "Overdue Rent Alert",
"trigger_kind": "cron",
"trigger_spec": { "expr": "0 8 * * *", "tz": "Asia/Calcutta" },
"trigger_intent": "Every morning, find rent transactions and notify the operator.",
"plan": [
{
"idx": 1,
"label": "Find rent activity",
"narration": "Pulls recent rent income rows for the portfolio.",
"kind": "sql_query",
"save_as": "rent",
"sql": "SELECT property_id, amount FROM pms.transactions WHERE type = 'Income' AND account_category = 'Rent' LIMIT 50"
},
{
"idx": 2,
"label": "Notify operator",
"narration": "Posts an in-app notification with the rent summary.",
"kind": "notify_user",
"title": "Rent summary ready",
"body": "Rent activity summary is ready to review."
}
],
"tools_allowed": [],
"sandbox": true
}
Response 200
{
"ok": true,
"data": {
"_id": "1f34ff78-55a0-40a8-9a55-3fb62d7e4bd2",
"name": "Overdue Rent Alert",
"owner_user_id": "7d4e1a90-52c1-4f38-949b-0decafc0ffee",
"trigger_kind": "cron",
"trigger_spec": { "expr": "0 8 * * *", "tz": "Asia/Calcutta" },
"trigger_intent": "Every morning, find rent transactions and notify the operator.",
"plan": [
{ "idx": 1, "label": "Find rent activity", "narration": "Pulls recent rent income rows for the portfolio.", "kind": "sql_query", "save_as": "rent", "sql": "SELECT property_id, amount FROM pms.transactions WHERE type = 'Income' AND account_category = 'Rent' LIMIT 50" },
{ "idx": 2, "label": "Notify operator", "narration": "Posts an in-app notification with the rent summary.", "kind": "notify_user", "title": "Rent summary ready", "body": "Rent activity summary is ready to review." }
],
"pending_approval": true,
"tools_allowed": [],
"budget": { "max_tool_calls": 25, "max_input_tokens": 50000, "max_runtime_secs": 1800, "max_parked_secs": 1209600 },
"sandbox": true,
"active": false,
"version": 1,
"created_at": "2026-07-13T11:12:24.314637900+00:00",
"updated_at": "2026-07-13T11:12:24.314637900+00:00",
"next_run_at": "2026-07-14T02:30:00+00:00",
"_createdBy": "7d4e1a90-52c1-4f38-949b-0decafc0ffee"
}
}
List every workflow owned by the caller, newest activity first. Each row includes the trigger kind, natural-language intent, lifecycle flags (active, pending_approval), and dispatch timestamps. Pass ?include_deleted=true to also surface soft-deleted rows for audit or undo flows.
Read a single workflow's full definition: the complete plan, trigger_spec, budget, lifecycle flags, and the natural-language message_context that built it. Use this to inspect or clone a workflow before editing it with PUT.
Update a workflow's metadata or plan. All fields are optional; send only what changed. When plan is included it is re-validated and any errors come back as 400 with an issues array describing each problem; non-plan edits (like a rename) skip validation to avoid unnecessary SQL probes. Each successful update bumps version.
Soft-delete a workflow. Past runs and their event history are preserved (they still show up under /runs and export), and the row can be surfaced again with ?include_deleted=true, but the workflow stops firing on new events. Use this instead of a hard delete so audit trails survive.
Activate a workflow: clears pending_approval and sets active=true. Idempotent for already-active rows. The optional body lets the AI canvas persist a sandbox value in the same click that approves the workflow; omit the body entirely to leave the persisted sandbox flag untouched.
Path & query parameters
Name
In
Type
Description
id
path
string
Workflow _id (uuid).
sandbox
body
boolean | null
Optional. When set, overrides the persisted sandbox flag before flipping active on. Omit to preserve the current value.
Pause a workflow: sets active=false. New trigger events queue but are not dispatched until you resume; any in-flight runs keep going to completion. No request body.
Path & query parameters
Name
In
Type
Description
id
path
string
Workflow _id (uuid).
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/workflows/1f34ff78-55a0-40a8-9a55-3fb62d7e4bd2/pause' \
-H 'Authorization: Bearer $TOKEN'
Resume a paused workflow: sets active=true again. Backlog events that arrived while it was paused are not replayed; they are marked with an ignored_reason. Only events that fire after resume will dispatch. No request body.
Path & query parameters
Name
In
Type
Description
id
path
string
Workflow _id (uuid).
Request
curl -s -X POST 'https://acme.sandbox.inventdb.com/api/workflows/1f34ff78-55a0-40a8-9a55-3fb62d7e4bd2/resume' \
-H 'Authorization: Bearer $TOKEN'
Manually fire a workflow once. This appends a synthetic manual event carrying the supplied sample_payload; the router picks it up on its next tick and creates a run. Set sandbox_override: true to force this single run to be non-side-effecting even if the workflow itself has sandbox off; this is exactly how the canvas "Test" button works.
Path & query parameters
Name
In
Type
Description
id
path
string
Workflow _id (uuid).
sample_payload
body
object
Optional payload injected as the synthetic manual event's data.
sandbox_override
body
boolean
Optional. Force this run to be non-side-effecting regardless of the workflow's own sandbox flag.
{
"ok": true,
"data": {
"event_id": "cc5097c6-269c-4b59-8f9d-3766f8e3d2d8",
"workflow_id": "1f34ff78-55a0-40a8-9a55-3fb62d7e4bd2",
"status": "pending",
"note": "Event queued. Dispatch happens once the router picks it up on its next tick."
}
}
List all runs of one workflow, newest first. Each entry is a run summary (status, start/end timestamps, sandbox flag, and any top-level error) without the per-step timeline. Fetch a single run's /runs/{id} to drill into its steps.
List every run across all workflows the caller owns, newest first. This is the global runs feed that powers the "recent activity" dashboard: one flat array of run summaries spanning all of your workflows.
Read a single run together with its full step timeline. Returns { run, steps } where steps is ordered by idx and includes each step's role (model_in, tool_call, tool_result), the tool_name, its tool_args, the tool_result, and timing. Use it to inspect exactly what a workflow did on a given run.
Dump a run, its steps, the original trigger event, and any notifications it produced: a single self-contained bundle for audit, debugging, or support hand-off. The run embeds a workflow_snapshot (the exact plan as it ran), and the versioned schema field (e.g. inventdb.workflow.run.v1) is the stable contract for consumers of the export.
Returns the caller's workflow's saved versions from _System.WorkflowVersions as a light projection (_id, workflow_id, version, name, trigger_intent, label, source_version, created_at), ordered by version descending and capped at 500, plus current_version from the live workflow row. A version is minted on create (label Created), on every PUT that changes the definition (trigger_spec, trigger_intent, plan, tools_allowed or budget; label Edited, or Edited via AI from the AI canvas), and on rollback (Rolled back from vN, with source_version set). Renames and sandbox/active toggles do not mint a version. A version's _id is {workflow_id}.v{version}. A workflow created before versioning existed can return an empty list until its first edit. Fetch the full plan of one version with GET /api/workflows/{id}/versions/{version}. 404 if the workflow does not exist or is not owned by the caller. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Workflow _id.
Response 200
{
"ok": true,
"data": {
"versions": [
{
"_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12.v3",
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"version": 3,
"name": "Lease expiry reminder",
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.",
"label": "Edited",
"source_version": null,
"created_at": "2026-10-27T09:41:52.774019+00:00"
},
{
"_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12.v2",
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"version": 2,
"name": "Lease expiry reminder",
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.",
"label": "Edited",
"source_version": null,
"created_at": "2026-10-22T16:18:03.115902+00:00"
},
{
"_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12.v1",
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"version": 1,
"name": "Lease expiry reminder",
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.",
"label": "Created",
"source_version": null,
"created_at": "2026-10-20T14:05:11.208431+00:00"
}
],
"current_version": 3
}
}
Hard-deletes all rows in _System.WorkflowVersions for this workflow except the one matching the live row's version. The live workflow definition, its runs and its notifications are untouched; only the view/rollback history is lost, and it cannot be undone. removed counts the versions the handler attempted to delete (individual delete errors are ignored, so it can over-report), and the scan is capped at 500 versions per call. The success payload nests its own ok inside data. Requires write permission on workflows (403 otherwise); 404 if the workflow does not exist or is not owned by the caller. No LLM involved.
Returns the full read-only snapshot stored for that version: name, trigger_kind, trigger_spec, trigger_intent, the complete plan, tools_allowed, budget, the authoring chat (message_context, [{role, content}]), and label / source_version when set. Runtime state (active, sandbox, schedule) is not part of a version. To run an old version without rolling back, pass version to POST /api/workflows/{id}/run. 404 workflow not found if the workflow is missing or not the caller's; 404 version not found if that version was never saved or was deleted. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Workflow _id.
version
path
integer
Version number (1-based integer). A non-integer value is rejected by the router with 400 before the handler runs.
Response 200
{
"ok": true,
"data": {
"_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12.v2",
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"version": 2,
"name": "Lease expiry reminder",
"trigger_kind": "cron",
"trigger_spec": {
"expr": "0 8 * * *",
"tz": "America/New_York"
},
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.",
"plan": [
{
"idx": 0,
"label": "Find expiring leases",
"narration": "Look up active leases ending in the next 30 days that have not had a reminder yet, with each tenant's name and email.",
"save_as": "expiring",
"kind": "sql_query",
"sql": "SELECT l._id, l.UnitNumber, l.EndDate, t.FullName, t.Email FROM pms.Leases l JOIN pms.Tenants t ON l.TenantId = t._id WHERE l.Status = 'active' AND l.DaysUntilEnd BETWEEN 0 AND 30 AND l.ReminderSent = false ORDER BY l.EndDate LIMIT 200"
},
{
"idx": 1,
"label": "Email each tenant",
"narration": "Send one reminder email per expiring lease.",
"kind": "send_email",
"to": "${expiring.Email}",
"subject": "Your lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}",
"body": "Hi ${expiring.FullName},\n\nYour lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}. Reply to this email or call the leasing office to talk about renewing.\n\nThanks,\nMaple Court Leasing Office"
},
{
"idx": 2,
"label": "Done",
"narration": "Record how many reminders went out.",
"kind": "finish",
"summary": "Sent ${expiring.length} lease-expiry reminders."
}
],
"tools_allowed": [],
"budget": {
"max_tool_calls": 25,
"max_input_tokens": 50000,
"max_runtime_secs": 1800,
"max_parked_secs": 1209600
},
"message_context": [
{
"role": "user",
"content": "Every morning at 8, email any tenant whose lease ends in the next 30 days and remind them to talk to us about renewing."
},
{
"role": "assistant",
"content": "Drafted 'Lease expiry reminder': a daily 08:00 cron that finds active leases ending within 30 days and emails each tenant."
}
],
"label": "Edited",
"created_at": "2026-10-22T16:18:03.115902+00:00",
"_createdBy": "a9b4e239-27ff-4f38-949b-38b332b3f8ed"
}
}
Deletes one saved version from a workflow's history. The current version cannot be deleted: roll back to another version first (400 otherwise). A version number that was never saved also answers 200 with deleted set. The success payload nests its own ok inside data. Requires write permission on workflows (403 otherwise); 404 when the workflow does not exist or is not owned by the caller.
Parameters
Name
In
Type
Description
id
path
string
Workflow _id.
version
path
integer
Version number to delete (integer). Must not be the workflow's current version.
Copies the chosen version's definition (name, trigger_kind, trigger_spec, trigger_intent, plan, tools_allowed, budget, message_context) onto the live workflow and saves it as a NEW latest version (current + 1, label Rolled back from vN, source_version = N). History is not rewritten, so a rollback can itself be rolled back. Runtime state is kept: active, sandbox and pending_approval do not change, so an active workflow keeps firing, now on the restored plan, from its next trigger. For a cron workflow, next_run_at is recomputed when the restored schedule differs. No request body. Returns the saved live workflow row. 400 rollback: version N not found when that version does not exist; 403 without write permission on workflows; 404 if the workflow is missing or not owned by the caller. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Workflow _id.
version
path
integer
Version number to restore (integer).
Response 200
{
"ok": true,
"data": {
"_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"name": "Lease expiry reminder",
"owner_user_id": "a9b4e239-27ff-4f38-949b-38b332b3f8ed",
"trigger_kind": "cron",
"trigger_spec": {
"expr": "0 8 * * *",
"tz": "America/New_York"
},
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.",
"plan": [
{
"idx": 0,
"label": "Find expiring leases",
"narration": "Look up active leases ending in the next 30 days that have not had a reminder yet, with each tenant's name and email.",
"save_as": "expiring",
"kind": "sql_query",
"sql": "SELECT l._id, l.UnitNumber, l.EndDate, t.FullName, t.Email FROM pms.Leases l JOIN pms.Tenants t ON l.TenantId = t._id WHERE l.Status = 'active' AND l.DaysUntilEnd BETWEEN 0 AND 30 AND l.ReminderSent = false ORDER BY l.EndDate LIMIT 200"
},
{
"idx": 1,
"label": "Email each tenant",
"narration": "Send one reminder email per expiring lease.",
"kind": "send_email",
"to": "${expiring.Email}",
"subject": "Your lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}",
"body": "Hi ${expiring.FullName},\n\nYour lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}. Reply to this email or call the leasing office to talk about renewing.\n\nThanks,\nMaple Court Leasing Office"
},
{
"idx": 2,
"label": "Done",
"narration": "Record how many reminders went out.",
"kind": "finish",
"summary": "Sent ${expiring.length} lease-expiry reminders."
}
],
"pending_approval": false,
"tools_allowed": [],
"budget": {
"max_tool_calls": 25,
"max_input_tokens": 50000,
"max_runtime_secs": 1800,
"max_parked_secs": 1209600
},
"sandbox": false,
"active": true,
"version": 4,
"message_context": [
{
"role": "user",
"content": "Every morning at 8, email any tenant whose lease ends in the next 30 days and remind them to talk to us about renewing."
},
{
"role": "assistant",
"content": "Drafted 'Lease expiry reminder': a daily 08:00 cron that finds active leases ending within 30 days and emails each tenant."
}
],
"created_at": "2026-10-20T14:05:11.208431+00:00",
"updated_at": "2026-10-27T14:20:06.390128+00:00",
"last_dispatched_at": "2026-10-27T12:00:00.519204+00:00",
"next_run_at": "2026-10-28T12:00:00+00:00",
"_createdBy": "a9b4e239-27ff-4f38-949b-38b332b3f8ed"
}
}
Asks the AI model to propose a fixed workflow from a failed run. The server builds diagnostics from the run (its error, plus every step whose result carries an error or mentions a failure, each trimmed to 700 characters) and sends them to the model with the workflow's current definition and its authoring chat, in one call. The fix is written by the GLM model family. The response holds the revised definition (normally name, trigger_intent, trigger_spec and plan) and the diagnostics the model was given. Nothing is saved: open revised in the editor and save it with PUT /api/workflows/{id}, which creates a new version. Model usage is metered under the workflow-fix feature. The run is not checked against the workflow, and a run with no step errors is described as The run failed without a specific step error. No request body. Errors: 403 without write permission on workflows; 404 workflow not found or run not found; 400 when no AI provider or key is configured (so on InventDB Serverless it answers 400, not 403); 500 when the model call fails or its reply is not a usable workflow.
Parameters
Name
In
Type
Description
id
path
string
Workflow _id.
run_id
path
string
_id of the failed run to learn from.
Response 200
{
"ok": true,
"data": {
"revised": {
"name": "Lease expiry reminder",
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.",
"trigger_spec": {
"expr": "0 8 * * *",
"tz": "America/New_York"
},
"plan": [
{
"idx": 0,
"label": "Find expiring leases",
"narration": "Look up active leases ending in the next 30 days that have not had a reminder yet, with each tenant's name and email.",
"save_as": "expiring",
"kind": "sql_query",
"sql": "SELECT l._id, l.UnitNumber, l.EndDate, t.FullName, t.Email FROM pms.Leases l JOIN pms.Tenants t ON l.TenantId = t._id WHERE l.Status = 'active' AND l.DaysUntilEnd BETWEEN 0 AND 30 AND l.ReminderSent = false ORDER BY l.EndDate LIMIT 200"
},
{
"idx": 1,
"label": "Email each tenant",
"narration": "Send one reminder email per expiring lease.",
"kind": "send_email",
"to": "${expiring.Email}",
"subject": "Your lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}",
"body": "Hi ${expiring.FullName},\n\nYour lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}. Reply to this email or call the leasing office to talk about renewing.\n\nThanks,\nMaple Court Leasing Office",
"for_each": "expiring"
},
{
"idx": 2,
"label": "Done",
"narration": "Record how many reminders went out.",
"kind": "finish",
"summary": "Sent ${expiring.length} lease-expiry reminders."
}
]
},
"diagnostics": "Run error: send_email: `to` rendered to empty. The template `${expiring.Email}` references variable `expiring` which is a 3-row array — if you meant to send one email per row, add `for_each: \"expiring\"` to the step. If you meant to send a single email to multiple recipients, change the template to a literal list (e.g. `to: [\"a@x.com\", \"b@x.com\"]`).\n[send_email] send_email: `to` rendered to empty. The template `${expiring.Email}` references variable `expiring` which is a 3-row array — if you meant to send one email per row, add `for_each: \"expiring\"` to the step. If you meant to send a single email to multiple recipients, change the template to a literal list (e.g. `to: [\"a@x.com\", \"b@x.com\"]`).\n"
}
}
The same fix as POST /api/workflows/{id}/fix-from-run/{run_id}, streamed as Server-Sent Events (text/event-stream) so the editor can show the model's reasoning as it arrives. Every event is named message, and its data is a JSON object whose type is reasoning (content is a chunk of the model's reasoning, at least about 120 characters; its executionTimeMs field holds an approximate token count for the chunk, not a time), revised (revised is the proposed definition and diagnostics the diagnostics text; the stream then ends) or error (content is the message; the stream then ends). A keep-alive comment is sent every 15 s. Nothing is saved. Checks made before the stream starts answer an ordinary JSON error: 403 without write permission on workflows, 404 when the workflow or run is not found, 400 when no AI provider or key is configured. A model failure after that arrives as an error event on a 200 stream.
Parameters
Name
In
Type
Description
id
path
string
Workflow _id.
run_id
path
string
_id of the failed run to learn from.
Response 200
event: message
data: {"type":"reasoning","content":"The failed step is send_email (idx 1). Its to is ${expiring.Email}, but expiring comes from the sql_query and is always an array, so the template renders empty. ","executionTimeMs":38}
: keep-alive
event: message
data: {"type":"reasoning","content":"The intent is one reminder per tenant, so the minimal fix is for_each: \"expiring\" on the send_email step; every other step stays identical.","executionTimeMs":35}
event: message
data: {"type":"revised","revised":{"name":"Lease expiry reminder","trigger_intent":"Every morning at 8:00, email each tenant whose active lease ends within the next 30 days.","trigger_spec":{"expr":"0 8 * * *","tz":"America/New_York"},"plan":[{"idx":0,"label":"Find expiring leases","narration":"Look up active leases ending in the next 30 days that have not had a reminder yet, with each tenant's name and email.","save_as":"expiring","kind":"sql_query","sql":"SELECT l._id, l.UnitNumber, l.EndDate, t.FullName, t.Email FROM pms.Leases l JOIN pms.Tenants t ON l.TenantId = t._id WHERE l.Status = 'active' AND l.DaysUntilEnd BETWEEN 0 AND 30 AND l.ReminderSent = false ORDER BY l.EndDate LIMIT 200"},{"idx":1,"label":"Email each tenant","narration":"Send one reminder email per expiring lease.","kind":"send_email","to":"${expiring.Email}","subject":"Your lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}","body":"Hi ${expiring.FullName},\n\nYour lease for unit ${expiring.UnitNumber} ends on ${expiring.EndDate}. Reply to this email or call the leasing office to talk about renewing.\n\nThanks,\nMaple Court Leasing Office","for_each":"expiring"},{"idx":2,"label":"Done","narration":"Record how many reminders went out.","kind":"finish","summary":"Sent ${expiring.length} lease-expiry reminders."}]},"diagnostics":"Run error: send_email: `to` rendered to empty. The template `${expiring.Email}` references variable `expiring` which is a 3-row array — if you meant to send one email per row, add `for_each: \"expiring\"` to the step. If you meant to send a single email to multiple recipients, change the template to a literal list (e.g. `to: [\"a@x.com\", \"b@x.com\"]`).\n[send_email] send_email: `to` rendered to empty. The template `${expiring.Email}` references variable `expiring` which is a 3-row array — if you meant to send one email per row, add `for_each: \"expiring\"` to the step. If you meant to send a single email to multiple recipients, change the template to a literal list (e.g. `to: [\"a@x.com\", \"b@x.com\"]`).\n"}
Hard-deletes the listed runs and every step row (_System.WorkflowRunSteps) recorded for each. It does NOT delete all runs: only the ids in the JSON body are touched, and {} or an empty ids list deletes nothing. The body must be sent with Content-Type: application/json even though this is a DELETE. Runs that are still running or parked are skipped (cancel them first), as are ids that do not exist or belong to another user. Each skipped id is reported with a reason: running_or_parked, not_found, lookup_failed or delete_failed. The trigger event and any notifications the run produced are kept. There is no batch-size limit. Requires write permission on workflows (403 otherwise). No LLM involved.
Hard-deletes the run row and all of its step rows (_System.WorkflowRunSteps). The trigger event and any notifications the run produced are kept. A run that is still running or parked is refused with 400 (run is still running or parked; cancel it first then delete). Requires write permission on workflows (403 otherwise); 404 if the run does not exist or is not the caller's. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Run _id (from GET /api/workflows/runs or /api/workflows/{id}/runs).
Sets the run's status to cancelled and stamps ended_at / last_active_at. Only running and parked runs can be cancelled (400 run is not cancellable in its current state otherwise). A cancelled parked run is never resumed: a later approval or reply for it is ignored. Cancelling a running run only rewrites the status row; it does not interrupt a step that is already executing, and the run's own completion can still overwrite the status with succeeded or failed. No request body. Requires write permission on workflows (403 otherwise); 404 if the run does not exist or is not the caller's. No LLM involved.
Returns a row from _System.WorkflowEvents: the source (cron, record_event, gmail, calendar, webhook, manual), occurred_at, the source-shaped payload, correlation_keys, and the routing decision: status (pending, dispatched, ignored, errored), dispatched_to ([{workflow_id, run_id}]), dispatched_at, and ignored_reason when the router skipped it. Use it to answer "why did (or didn't) this workflow fire?". A run's trigger_event_id points here, and POST /api/workflows/{id}/run returns the event_id it queued. Only events whose user_id is the caller are visible; anyone else's reads as 404. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Event _id (a run's trigger_event_id, or the event_id returned by POST /api/workflows/{id}/run).
Response 200
{
"ok": true,
"data": {
"_id": "c4e8f1a2-9b3d-4e5f-8a7b-6c5d4e3f2a1b",
"source": "cron",
"occurred_at": "2026-10-27T12:00:00.519204+00:00",
"payload": {
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"fired_at": "2026-10-27T12:00:00.519204+00:00",
"trigger_intent": "Every morning at 8:00, email each tenant whose active lease ends within the next 30 days."
},
"correlation_keys": {
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12"
},
"status": "dispatched",
"dispatched_to": [
{
"workflow_id": "3f6c2a1e-8b4d-4c7a-9e21-5d0b7f9a4c12",
"run_id": "7d21e9b0-4a6f-4f3e-b8c5-1e2f3a4b5c6d"
}
],
"dispatched_at": "2026-10-27T12:00:01.862077+00:00",
"user_id": "a9b4e239-27ff-4f38-949b-38b332b3f8ed",
"_createdBy": "a9b4e239-27ff-4f38-949b-38b332b3f8ed"
}
}
Outbound webhooks (change signals)
Push notifications for data changes: subscribe an HTTPS endpoint to one (namespace, type) scope and InventDB POSTs a signed, data-free signal whenever rows change; your receiver verifies the HMAC signature, then pulls fresh rows back over /sql, /db, or the /api/changes cursor feed. No row data ever leaves in the webhook itself. Deliveries are debounced per subscription, retried with exponential backoff on failure, and the subscription degrades (then goes dead) if your endpoint keeps failing. Available on both products; all endpoints require a Bearer token.
Create a subscription. The response carries the subscription and the signing secret; the secret is returned once and never again; store it in your receiver. Every delivery is signed X-InventDB-Signature: sha256=HMAC_SHA256(secret, "<timestamp>.<body>") with X-InventDB-Timestamp and X-InventDB-Delivery-Id headers.
Request body fields
Name
In
Type
Description
target_url
body
string
Your HTTPS receiver endpoint.
namespace / type
body
string
The single table scope the subscription watches.
ops
body
array
Subset of ["insert","update","delete"].
debounce_ms
body
number
Coalesce window; at most one delivery per window per subscription.
Edit target_url, ops, debounce_ms and/or active (set active:false to pause deliveries without losing the cursor). Changing the target does not rotate the secret.
Delivery health: cursor (last delivered change LSN) vs head (current change-log LSN), plus attempts, failed_deliveries, last_delivery_at and the dead/degraded flags. cursor < head with failures means your receiver is erroring and retries are backing off.
Fire one signed delivery immediately with "test": true in the body; verify the signature and return 200 without acting. Returns the transport error when the target is unreachable.
The pull side of eventing: cursor-based read of the change log for one scope. ?namespace=pms&type=maintenance_requests&since=<cursor>&limit=100 returns changed record ids (with op + LSN) and nextCursor. Ids are RLS-filtered: a caller only sees ids for rows their row filters permit. Webhook signals tell you when to read; this feed (or /db, /sql) is where you read.
A complete, tested flow: a tenant files an urgent maintenance request in InventDB; the webhook signal hits a small Python service (stdlib only, no frameworks) which verifies the signature, pulls the fresh rows, creates a work_orders record assigned to the on-call technician, and flips the request to dispatched.
import hashlib, hmac, json, sys, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
PORT, SECRET, INVENTDB, TOKEN = int(sys.argv[1]), sys.argv[2], sys.argv[3].rstrip("/"), sys.argv[4]
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never proxy API calls
def idb(method, path, body=None):
req = urllib.request.Request(f"{INVENTDB}{path}", method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"content-type": "application/json", "authorization": f"Bearer {TOKEN}"})
with OPENER.open(req, timeout=15) as r:
return json.loads(r.read() or b"null")
class Hook(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("content-length", 0)))
ts = self.headers.get("X-InventDB-Timestamp", "")
# 1) VERIFY: sha256=HMAC_SHA256(secret, "<timestamp>.<body>")
mine = "sha256=" + hmac.new(SECRET.encode(), f"{ts}.".encode() + raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(mine, self.headers.get("X-InventDB-Signature", "")):
self.send_response(401); self.end_headers(); return
signal = json.loads(raw)
if signal.get("test"): # test pings: verify + 200, no action
self.send_response(200); self.end_headers(); return
# 2) PULL: the signal is data-free; fetch the actual urgent requests.
rows = idb("POST", "/sql", {"sql":
"SELECT _id, unit, issue FROM pms.maintenance_requests "
"WHERE status = 'new' AND priority = 'urgent' ORDER BY _createdAt DESC LIMIT 10"})
# 3) ACT: dispatch a technician - one work order per request, then flip status.
for r in rows:
wo = idb("POST", "/db/pms/work_orders", {"request_id": r["_id"], "unit": r["unit"],
"issue": r["issue"], "assigned_to": "tech-on-call", "sla_hours": 4, "status": "dispatched"})
idb("PUT", "/db/pms/maintenance_requests", {"_id": r["_id"], "status": "dispatched"})
print(f"[DISPATCH] unit {r['unit']} -> work order {wo.get('id')}")
self.send_response(200); self.end_headers(); self.wfile.write(b'{"ok":true}')
HTTPServer(("0.0.0.0", PORT), Hook).serve_forever()
2 · Subscribe, then file a request
# subscribe (save the one-time secret into the receiver)
curl -s -X POST $BASE/api/webhooks/subscriptions -H "Authorization: Bearer $TOKEN" \
-H 'content-type: application/json' \
-d '{"target_url":"https://ops.example.com/hooks/inventdb","namespace":"pms",
"type":"maintenance_requests","ops":["insert","update"],"debounce_ms":1000}'
# a tenant files an urgent request; this is the trigger
curl -s -X POST $BASE/db/pms/maintenance_requests -H "Authorization: Bearer $TOKEN" \
-H 'content-type: application/json' \
-d '{"unit":"9F","issue":"Main door lock jammed, tenant locked out",
"priority":"urgent","status":"new","reported_by":"tenant-app"}'
3 · What actually happened (live transcript, v0.498)
[SIGNAL] verified delivery 49965c89bc1543b6bc33f3ec95a37475
scope=pms.maintenance_requests cursor=5673 hint={'changed': 1, 'ops': ['update']}
[PULL] 1 new urgent maintenance request(s)
[DISPATCH] unit 9F -> work order 43c3262f-78ef-4d60-8371-60459ba004e3
('Main door lock jammed, tenant locked out', SLA 4h)
request 9F → { "status": "dispatched" } ← flipped by the receiver
work order → { "unit": "9F", "assigned_to": "tech-on-call",
"sla_hours": 4, "status": "dispatched" } ← created by the receiver
subscription → { "cursor": 5680, "head": 5689, "dead": false } ← healthy, caught up
Attachments
Per-record file attachments: upload (multipart), list, fetch metadata, raw download, delete, and full-text / semantic / combined search over extracted text and embeddings. Storage is native: chunks, extracted text, and embeddings live in the _attachment* system types (_attachments, _attachment_text, _attachment_embeddings). Every attachment is owned by an existing record, addressed by that record's system _id.
Upload a file attachment against an existing record. The request is a multipart form; the file part carries the raw bytes. On upload the engine stores chunks, extracts text (PDF / DOCX / TXT / images via OCR), and, if the embedding model is loaded, generates semantic embeddings so the file becomes content-searchable. Small text files finish inline; larger files return Pending and the background worker advances processing_state to Ready.
Path & query parameters
Name
In
Type
Description
namespace
path
string
Namespace, e.g. pms
type_name
path
string
Type name, e.g. properties
record_id
path
string
Owning record's system _id (uuid), e.g. fe289741-574c-4311-9733-ad6be7e3ceb0
Request
Multipart form. Required part: file. Optional parts: description, tags (JSON array), custom_properties (JSON object), folder_path, analyze (true: also analyse an image or video with the instance's AI model once it is processed, InventDB SOAR only; the response then carries analysis_state, see POST .../analyze).
List every attachment owned by a single record. Returns metadata, tags, folder_path, and per-file processing_state / extraction_status, but not the bytes. Use this to render an attachment explorer for one property, lease, or work order, then fetch bytes via the /download sub-route.
Fetch a single attachment's metadata, tags, and extraction status. Bytes are not included; use the /download sub-route for the raw file. Handy for polling processing_state after a deferred upload until it reaches Ready.
Path & query parameters
Name
In
Type
Description
namespace
path
string
Namespace, e.g. pms
type_name
path
string
Type name, e.g. properties
record_id
path
string
Owning record's system _id
attachment_id
path
string
Attachment id, e.g. att_3a422f35-4abd-41af-86e3-55b29ca8c474
Download the current version of an attachment as raw bytes. The response sets Content-Type to the stored MIME type and Content-Disposition: attachment so browsers trigger a save dialog. Returns 404 if the attachment does not exist.
Delete an attachment: all versions plus stored bytes, extracted text, and embeddings. This is a hard delete with no soft-delete or undo. After this call the file no longer appears in list or search results.
Searches the files attached to one type's records. search_type selects the mode. keyword matches the whole query inside the file name, then the description. fulltext finds the query's words in the extracted text through the word index, ranked by BM25, with stemming, typo tolerance for unknown words, "phrases", -exclusions and prefix*. semantic ranks by meaning (the best-matching passage of each file) blended with the words, and needs the embedding model (503 without it). combined, the default, merges all three into one combined_score between 0 and 1. Each result carries a text_snippet of about 220 characters around the best match.
Optional fields: limit (default 10, at most 100), threshold (raises the meaning floor above its built-in 0.62), weights.fulltext and weights.semantic (the split between words and meaning in combined, 0.8 / 0.2 by default), filters.record_id (one record's files) and filters.min_size / filters.max_size in bytes. To search every type at once, or filter by folder, MIME type or tag, use POST /attach/_search. Files whose record the caller's row rules hide are left out.
Counts every attachment in every namespace by background content-processing state (ready, pending, processing, skipped, failed) and returns a sample of files: Pending/Processing first, then Failed, then Skipped, then Ready, newest updated_at first within each. Powers the Engine room's "Attachment Processing" card. Reads each namespace's _attachments system type through the system store (no row rules). Gate: the /attach path middleware reads _processing as a _* namespace, so admin / superadmin / setup pass and other roles get 403 unless they hold read on _processing. Read-only; no LLM, works on every tier.
Global file search behind the Files room and the agent's file tools. Fans out over every (namespace, type) that holds attachments and that the caller may read (RBAC read on that type; unreadable scopes are skipped silently and appear nowhere; _* namespaces and models are never searched), runs the same legs as POST /attach/{namespace}/{type_name}/search (search_type keyword | fulltext | semantic | combined, default combined), applies the folder / MIME / tag filters, drops files whose parent record the caller's row rules hide, then ranks and pages. Meaning and combined scores are fused over all scopes together (words share 0.6 semantic / 0.8 combined, +0.1 for a file-name match, scaled 0-1); ties sort newest first, then by namespace and id, so offset paging is stable. Browse mode (empty query or "*"): every visible file, newest updated_at first, no scores. Filters: namespaces / types (case-insensitive), folder (that folder and everything under it, case-insensitive), mime_types (exact application/pdf, family image/ or bare image), tags (a file must carry ALL of them). limit default 25 (1-100), offset, threshold (meaning floor; never below 0.62 similarity). total_matches counts before paging; folders aggregates the whole filtered result set (not just the page) by namespace, stored type and folder_path (path: "" = files at the type root). Each hit is the per-type result item plus namespace, _id, size_bytes, snippet and matched_sources. Semantic mode without the embedding model returns no hits (200, not 503). No LLM; works on every tier.
Built for answering with a language model from many files: returns the best passages, not one file's opening. 1) Candidates: the global combined search (RBAC + parent row rules, as POST /attach/_search) - the best files files (default 60, max 100), after skipping file_offset; or a scoped set: record_id (alias recordId) with exactly one namespace and one type = that record's files, attachment_ids (alias attachmentIds) with exactly one namespace = those files (up to 500). A scope missing its namespace or type yields no passages; it never widens. Every file passes the per-file access check again. 2) Every stored chunk of those files (the ~224-token chunks the embedder wrote) is scored by meaning (cosine with the query's MiniLM vector) and by words (BM25 over the candidates' chunks with the word index's rules: stopwords dropped, typos forgiven for unknown words, phrases and exclusions honoured); a file with no vectors yet is chunked the same way and ranked by words alone. 3) Chunks are ordered by reciprocal-rank fusion (k = 60) of the meaning rank, the words rank and the file's search rank, weighted by weights (default semantic 1, words 1, file 0.5; file 0 when scoped). 4) When the cross-encoder re-ranker is installed and the machine has 4+ cores (or INVENTDB_PASSAGE_RERANK=1), the best rerank_top fused chunks (default INVENTDB_PASSAGE_RERANK_TOP, else 6 per core between 16 and 50; max 100) are re-ordered by its score; rerank: false skips this. limit passages (default 8, max 50); per_file caps passages from one file (0 = no cap). char_offset / char_length are character positions in the file's extracted text; semantic is null for a file without vectors; rerank is null for chunks not re-ranked. 400 for an empty query. Local models only, no LLM; works on every tier.
{
"ok": true,
"passages": [
{
"namespace": "pms",
"attachment_id": "att_3f9c2a1e-8b4d-4c6e-9a7f-2d1b5e8c0a47",
"filename": "Lease-L-7039.pdf",
"record_type": "properties",
"record_id": "P-5001",
"folder_path": "leases/2026",
"chunk": 7,
"char_offset": 15872,
"char_length": 239,
"text": "PETS. Tenant may keep one (1) dog under 40 lbs. A refundable pet deposit of $400.00 is due at signing. The pet deposit is returned within 30 days of move-out, less the cost of repairing damage caused by the pet beyond normal wear and tear.",
"score": 0.040984,
"semantic": 0.6812,
"words": 9.4127,
"file_rank": 0,
"rerank": 7.214
}
],
"files": 60,
"chunks": 1843,
"timing": {
"search_ms": 151.2,
"score_ms": 88.4,
"rerank_ms": 172.9,
"total_ms": 412.5
}
}
Deletes the files of {namespace}.{type} whose folder_path is folder or lies under it (case-insensitive, outer slashes ignored); an omitted or empty folder deletes every file of the type, _vault and record-linked alike. Each delete removes all versions, chunks, extracted text and embeddings, and the namespace's attachment vector index is saved once per call. Gates: delete permission on (namespace, type), checked before anything is deleted (403 {"ok": false, "error": ...}, admin / superadmin / setup bypass); files whose parent record the caller's row rules hide are left alone and counted in skipped (with any per-file failures). limit deletes at most that many this call - loop until deleted is 0; remaining (only with limit) is how many deletable files are left. 400 when namespace or type is empty. Hard delete, no undo. No LLM; works on every tier.
The parents of one attachment: the primary record first (parents[0], from the file's metadata), then every copy-link added with POST /attach/{namespace}/_relink (mode copy). 404 when the attachment is not in this namespace; 400 without id. Gate: the /attach path middleware checks read on {namespace}._links, which admin roles or a namespace-wide read grant satisfy (a grant on one type does not). The parents' row rules are not checked. Read-only.
mode: "copy" (default) also attaches the file to target without moving it: one row in {namespace}._attachment_links; idempotent (the same target again returns the existing link). mode: "move" makes target the file's primary parent (its metadata's record_type and record_id are rewritten) and drops all of its copy-links. Moves stay inside the namespace: a different target.namespace answers 500 Failed to move attachment: ... Cross-namespace move is not supported ... Use copy-link (mode='copy') instead. The target record is not checked for existence in either mode. target accepts typeName / type_name / type and recordId / record_id. Response parents: primary first, then the copy-links. 400 for any other mode; 404 when the attachment is not in this namespace. Gate: the /attach path middleware checks write on {namespace}._relink (admin roles or a namespace-wide write grant).
Multipart upload with no record id: the file goes to the type's shared _vault bucket (record_id _vault; its parent row is created on first use) - the default the Canvas SDK and the agent's upload tools use. Form fields: file (required), description, tags (JSON array string), custom_properties (JSON object string), folder_path, analyze (true: AI analysis of an image or video, InventDB SOAR only, see POST .../analyze). A relative path in the file name (leases/2026/Lease-L-7039.pdf) becomes the folder_path (appended to any folder_path field). Returns as soon as the bytes are stored, processing_state Pending; the background worker then extracts text, embeds and indexes it, and content search finds it once Ready. A file with the same name already in the bucket gets a new version instead (description / tags / folder are not applied then). Uploading into a namespace that does not exist creates it, which only admin / superadmin may do (403 otherwise). 400 without a file part; 500 on store errors. RBAC write on the type. Local OCR / MiniLM only, no LLM; works on every tier.
Starts a background job (202) that generates MiniLM chunk embeddings for every file of the type, or only attachmentIds, skipping files that already have embeddings unless forceRegenerate is true, and files with no extracted text; it then rebuilds the namespace's attachment vector index from all stored embeddings - also when every file was skipped, which is the repair for an index out of step with its records. Normally the background attachment worker embeds each upload by itself; this is the backfill / repair tool. Body is JSON with camelCase fields; {} is accepted. Progress lives in memory (GET .../embeddings/progress, lost on restart); one run per (namespace, type) at a time (409 while one is generating). 503 when the embedding model is not available. RBAC write on the type. Local model, no LLM; works on every tier.
The current or last embedding run for this (namespace, type), from the in-memory tracker. status: idle (no run since the server started), generating, completed, cancelled or failed; currentFile while generating; progressPercentage 0-100; endTime once finished. Read-only.
Asks a running embedding run for this type to stop: it stops before the next file, still rebuilds the vector index from what exists, and ends cancelled. Embeddings already written stay. data is true when a run was generating, false otherwise. No body.
How many of the type's files have chunk embeddings: total, with, without, and coverage percentage. Counts every file of the type (no row-rule filter). A listing failure answers 200 with ok: false. Read-only.
Files directly in folder plus its immediate subfolders, each with the file count and total bytes of everything beneath it. Omit folder (or pass "" or "/") for the root, which holds the files with no folder_path. folder is compared exactly with the stored folder_path (no case or slash normalisation), so pass it as stored (e.g. leases/2026); note that a root-level subfolder's path in the response carries a leading slash (/leases) and only matches files whose folder_path was stored with one. RBAC read on the type; the record's row rules are not checked. 500 with ok: false on a storage error. Read-only.
The file's extracted content: text (English; the searchable text), native_text (the verbatim original-language text when it was translated, else ""), description (vision description of an image), language, extraction_method, pages (a PDF's pages as character ranges in text, so a reader can show the page a passage or citation is on; absent for other files and for PDFs extracted before pages were kept) and regions (OCR lines of an image or scan: character range in text, page, box and image size in pixels; absent for text-born files). data is null when nothing has been extracted yet. Access: RBAC read on the file's REAL parent type plus the parent record's row rules; a hidden or missing file answers 404, never 403, so it cannot be probed.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
record_id
path
string
Owning record _id (not checked by this route)
attachment_id
path
string
Attachment id (att_<uuid>)
Response 200
{
"ok": true,
"data": {
"text": "RESIDENTIAL LEASE AGREEMENT\nThis Lease is made on September 1, 2026 between Harbor Property Group LLC (\"Landlord\") and Dana Cole (\"Tenant\") for the premises at 1418 Oak Hollow Dr, Austin, TX 78745...",
"native_text": "",
"description": "",
"language": "",
"extraction_method": "text_extractor",
"pages": [
{
"page": 1,
"char_offset": 0,
"char_length": 2841
},
{
"page": 2,
"char_offset": 2841,
"char_length": 3102
}
]
}
}
A downscaled JPEG preview of an IMAGE attachment, fitted within size x size with the aspect ratio kept; the Files explorer uses it as the file's icon. Headers: Content-Type: image/jpeg, Cache-Control: private, max-age=3600. 404 with an empty body for non-images (PDFs and others: show a file-type icon and preview through /download), for decode failures, and for files the caller cannot see (same real-parent RBAC + row-rule gate as /text). Read-only.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Edits the attachment's metadata: description replaces the description, tags replaces the whole tag list, custom_properties merges its keys into the stored map; omitted fields are kept and updated_at is set. It does not rename the file (there is no filename field) and does not touch the bytes, text or embeddings. 404 when the attachment does not exist; 500 on a store error. Located by namespace + attachment_id; the /attach path middleware checks the caller's write permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Sets the file's folder_path; null or an omitted folder_path moves it to the root. The value is stored as given (no slash or case normalisation). Bytes, text, embeddings and links are unchanged. Errors, including an unknown attachment, answer 500 with ok: false. Located by namespace + attachment_id; the /attach path middleware checks the caller's write permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Re-runs text extraction (PDF, DOCX, OCR, ...) on the stored bytes, rewrites the extracted text and metadata, and regenerates the embeddings when the embedding model is loaded and text came out. For files uploaded while the OCR or embedding models were missing (extraction_status Failed): no re-upload needed. Runs inline on the request, so a large scan can take a while. No body. 500 with ok: false on failure. Located by namespace + attachment_id; the /attach path middleware checks the caller's write permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
POST/attach/{namespace}/{type_name}/{record_id}/{attachment_id}/analyzeBearerInventDB SOAR only
Analyses an image or video attachment with the instance's AI model (Settings → AI), or analyses it again; the same as uploading it with analyze=true. Runs in the background once the file's content processing is done. A video is read as frames (1 a second, 20 to a request, with their times); the model describes everything visible: the scene, each person (clothing and colours, age group, what they do), each vehicle (type, make, colour, readable plate), animals, notable objects, readable text and events. A person or vehicle keeps one entity_id across the whole video.
Each finding is a row in {namespace}._attachment_analysis, the system table beside the file's own ({namespace}._attachments), with this attachment_id and the file's record_type and record_id: row_typesummary (one per file: title, summary, topics, counts), segment (a video stretch: scene and counts), entity (one per unique person, vehicle, animal or object, with time_start / time_end), sighting (an entity in one segment), event and text. Plates are also stored as plate_norm (letters and digits only) for prefix search. With recorded_at in the upload's custom_properties (e.g. {"recorded_at":"2026-10-22T10:00:00+05:30","camera":"pump-1"}), or a video's own creation_time, every row with a time also gets the clock time: ts_start / ts_end (local to that offset), day, weekday, hour, ts_epoch; camera, site and location are copied onto every row. The summary and a timeline become the file's searchable text, so keyword, full-text and meaning search and Ask find it. A new analysis replaces the previous one. The rows belong to the file: deleting the file deletes them, deleting its record (by any route, or dropping the type) deletes the file and them, and moving the file to another record moves them. The work uses AI credits; tokens and cost are on the attachment. 202 with analysis_statePending; 400 when the file is not an image or video; 403 on InventDB Serverless or without write permission. Environment: INVENTDB_MEDIA_FPS, INVENTDB_MEDIA_SEGMENT_FRAMES, INVENTDB_MEDIA_MAX_SECONDS (1800).
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. cctv)
type_name
path
string
Type name. Drives the RBAC check; the file is found by namespace + attachment_id
-- every unique vehicle seen in a file, with its times
SELECT entity_id, label, color, make, plate, time_start, time_end
FROM cctv._attachment_analysis
WHERE attachment_id = '3f9c2a1e-8b4d-4c6e-9a7f-2d1b5e8c0a47' AND row_type = 'entity' AND kind = 'vehicle'
-- black BMWs with a plate starting EMC25 at pump-1 between 10 and 11 on Thursday 22 October
SELECT file_name, entity_id, plate, ts_start, ts_end
FROM cctv._attachment_analysis
WHERE row_type = 'entity' AND kind = 'vehicle' AND camera = 'pump-1' AND color = 'black' AND make = 'BMW'
AND plate_norm LIKE 'EMC25%' AND ts_start >= '2026-10-22T10:00:00' AND ts_start < '2026-10-22T11:00:00'
-- the findings with their file and the record it is attached to
SELECT a.filename, a.record_id, m.kind, m.label, m.plate, m.ts_start
FROM cctv._attachment_analysis m
JOIN cctv._attachments a ON m.attachment_id = a._id
WHERE m.row_type = 'entity' AND m.kind = 'vehicle'
The state of a file's AI analysis: the job (state Pending / Processing / Ready / Failed / Skipped, attempts, model, segments, entities, tokens, cost_usd, error), the attachment's analysis_state, the summary row, and the number of _attachment_analysis rows by row_type. Query {namespace}._attachment_analysis for the findings themselves. Checks read permission on the file's real parent type and row; 404 when hidden.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. cctv)
type_name
path
string
Type name. Drives the RBAC check; the file is found by namespace + attachment_id
Regenerates the file's chunk embeddings from its extracted text, then rebuilds the namespace's whole attachment vector index (every file's stored vectors are read again, under a per-namespace lock) before answering. data true = embedded; false = the file has no extracted text. 503 when the embedding model is not available; 500 on a store error. No body. Located by namespace + attachment_id; the /attach path middleware checks the caller's write permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Multipart upload (file required, optional comment) of new content for an existing attachment. The bytes become the new current version (version + 1; older versions stay in the history, subject to the retention policy) and the file is re-queued as Pending, so the background worker re-extracts and re-embeds it; content search returns the new text once it is Ready. The file name and content type come from the file part. 201 with the new version; 400 without a file part; 500 on store errors (an unknown attachment included). Located by namespace + attachment_id; the /attach path middleware checks the caller's write permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
record_id
path
string
Owning record _id (not checked by this route)
attachment_id
path
string
Attachment id (att_<uuid>)
Request
{
"file": "(binary) Lease-L-7039-countersigned.pdf",
"comment": "Countersigned by landlord"
}
The version history, oldest first: version number, file name, size, created_at, optional created_by and comment, and is_current. An attachment with no history answers 200 with an empty list; a store error 404 with ok: false. Located by namespace + attachment_id; the /attach path middleware checks the caller's read permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
One entry of the version history (same fields as the list). 404 Version not found / No versions found. Located by namespace + attachment_id; the /attach path middleware checks the caller's read permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Deletes a single version and frees its chunk bytes when no other version shares them. Deleting a non-current version leaves the current text, embeddings and search entries alone. Deleting the CURRENT version falls back to the newest remaining one and clears the removed version's text, embeddings and vectors so search can never return it; the fallback is re-extracted inline when the extractor and embedding model are available, else left Pending for the background worker. The only version cannot be deleted (409 - delete the attachment instead). Access: delete permission on the file's REAL parent type (403 with the RBAC message) plus the parent record's row rules (a hidden parent or missing file answers 404). 404 for an unknown version. Returns the attachment as it now stands.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
The raw bytes of that version, with Content-Type (the version's content type), Content-Disposition: attachment; filename="..." and Content-Length. Access: RBAC read on the file's REAL parent type plus the parent record's row rules; a hidden or missing file answers 404 Attachment not found. 404 Version not found for an unknown version; 500 on a storage error. Read-only.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Creates a NEW version (current + 1) holding that version's bytes, file name and content type - history is never rewritten - with comment as its comment (default Restored from version N). The file is re-queued Pending so the background worker re-extracts and re-embeds it. Needs a JSON body ({} is fine). 200 with the new version; errors, including an unknown version or attachment, answer 500 with ok: false. Located by namespace + attachment_id; the /attach path middleware checks the caller's write permission on the path's (namespace, type_name) only - unlike GET .../text and the downloads, this route does not re-check the file's real parent type or the parent record's row rules.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (e.g. pms)
type_name
path
string
Type name. Drives the RBAC check only; the file is found by namespace + attachment_id
Self-service user endpoints. Distinct from /api/users/* (admin) and /api/auth/* (auth state). The caller acts only on their own user row and only on the fields these endpoints expose: no role, activation, or password changes here.
Updates the email address on the calling user's own row and nothing else. This exists separately from the admin PUT /api/users/{userId} because scheduled-report delivery fails when a regular user's _system.users.email is blank, yet a non-admin cannot use the admin endpoint. The settings page posts here from its one-click "Use my Gmail address" button (shown when Gmail OAuth is connected and the stored email is empty). Scope is strictly the caller's own email field; no role or password mutation.
Path & query parameters
None. The target user is always the authenticated caller (derived from the Bearer token); there is no namespace, id, or query parameter.
Lists the CALLER's own dashboards for one namespace (documents in _System.Dashboards whose user_id is the caller; this holds for admins too), without the large widgets and history arrays. Up to 200 rows. Works for every role, because the endpoint reads _System on the caller's behalf after applying its own ownership rule. namespace is required (400 without it).
Parameters
Name
In
Type
Description
namespace
query
string
Namespace the dashboards belong to, e.g. pms. Required.
Lists the files of generated reports (attachments on _System.AIReports records, usually the rendered .html plus its .source.html), newest first, up to 500 files. An admin sees every report; a caller holding read on _System.AIReports (the analyst role, or a custom role) sees only the files they generated; anyone else gets an empty list, not an error. Listing and deleting need no LLM; generating reports does.
Response 200
{
"ok": true,
"rows": [
{
"_id": "att_5e1c9a7b20f34d6e",
"record_id": "rpt_20261026_rent_roll",
"filename": "October rent roll.html",
"description": "Rent roll by property for October 2026",
"content_type": "text/html",
"tags": [
"ai-report"
],
"created_at": "2026-10-26T16:12:48.330915+00:00"
},
{
"_id": "att_5e1c9a7b20f34d6f",
"record_id": "rpt_20261026_rent_roll",
"filename": "October rent roll.source.html",
"description": "Rent roll by property for October 2026",
"content_type": "text/html",
"tags": [
"ai-report",
"source"
],
"created_at": "2026-10-26T16:12:48.331702+00:00"
}
]
}
Deletes every file of one generated report (all attachments on that _System.AIReports record). Allowed for admins, and for callers holding write or delete on _System.AIReports when they generated every one of the report's files; a report that is someone else's answers 404 exactly like a missing one, and is never partly deleted. If a delete fails midway the call answers 500 saying how many files were removed. 403 for callers without the grant. Cannot be undone.
Parameters
Name
In
Type
Description
record_id
path
string
The report's record_id, as listed by GET /api/app-objects/ai-reports.
Reads one UI layout document from _System. kind is dashboards (id dash.<userId>.<namespace>[.<type>].<key>; readable by its owner or an admin, and the stored user_id must also be the caller), screens (id screen.<namespace>.<type>.<dimension>; needs read on that type) or form-templates (id <namespace>.<type>; needs read on that type). A document the caller may not read answers exactly like a missing one, 200 with doc null, so ids cannot be probed. 404 for an unknown kind.
Parameters
Name
In
Type
Description
kind
path
string
dashboards, screens or form-templates.
id
path
string
Document id in the shape the kind requires (URL-encode it).
Response 200
{
"ok": true,
"doc": {
"_id": "dash.1b37c660-8a99-4f08-a6ed-ae77d7948960.pms.k3x9q2",
"user_id": "1b37c660-8a99-4f08-a6ed-ae77d7948960",
"name": "Portfolio overview",
"scope": "namespace",
"namespace": "pms",
"type_name": "",
"widgets": [
{
"id": "w1",
"kind": "kpi",
"title": "Occupied properties",
"sql": "SELECT COUNT(*) AS v FROM pms.properties WHERE status = 'occupied'",
"span": 3
},
{
"id": "w2",
"kind": "bar",
"title": "Market rent by city",
"sql": "SELECT city, SUM(market_rent) AS v FROM pms.properties GROUP BY city",
"span": 9,
"money": true
}
],
"history": [],
"_createdBy": "1b37c660-8a99-4f08-a6ed-ae77d7948960",
"_updatedAt": "2026-10-26T15:41:09.220318+00:00"
}
}
Creates the document or replaces it whole (not a merge). The body must be a JSON object; the server sets _id from the path and, for dashboards, user_id to the caller (an admin editing someone's dashboard keeps it that user's). Write rules: dashboards only by their owner (the id must start with dash.<caller id>. and an existing document must be the caller's) or an admin; screens and form-templates need write on the type the id names. 403 when not allowed, 400 for a non-object body, 404 for an unknown kind. Writes are attributed to the caller. Returns the stored document.
Parameters
Name
In
Type
Description
kind
path
string
dashboards, screens or form-templates.
id
path
string
Document id in the shape the kind requires (URL-encode it).
Request
{
"name": "Portfolio overview",
"scope": "namespace",
"namespace": "pms",
"type_name": "",
"widgets": [
{
"id": "w1",
"kind": "kpi",
"title": "Occupied properties",
"sql": "SELECT COUNT(*) AS v FROM pms.properties WHERE status = 'occupied'",
"span": 3
},
{
"id": "w2",
"kind": "bar",
"title": "Market rent by city",
"sql": "SELECT city, SUM(market_rent) AS v FROM pms.properties GROUP BY city",
"span": 9,
"money": true
}
],
"history": []
}
Response 200
{
"ok": true,
"doc": {
"_id": "dash.1b37c660-8a99-4f08-a6ed-ae77d7948960.pms.k3x9q2",
"user_id": "1b37c660-8a99-4f08-a6ed-ae77d7948960",
"name": "Portfolio overview",
"scope": "namespace",
"namespace": "pms",
"type_name": "",
"widgets": [
{
"id": "w1",
"kind": "kpi",
"title": "Occupied properties",
"sql": "SELECT COUNT(*) AS v FROM pms.properties WHERE status = 'occupied'",
"span": 3
},
{
"id": "w2",
"kind": "bar",
"title": "Market rent by city",
"sql": "SELECT city, SUM(market_rent) AS v FROM pms.properties GROUP BY city",
"span": 9,
"money": true
}
],
"history": []
}
}
Deletes one UI layout document. Same rules as PUT: dashboards only by their owner or an admin, screens and form-templates with write on the type the id names; 403 otherwise. deleted says whether a document existed. 404 for an unknown kind.
Parameters
Name
In
Type
Description
kind
path
string
dashboards, screens or form-templates.
id
path
string
Document id in the shape the kind requires (URL-encode it).
Response 200
{
"ok": true,
"deleted": true
}
Reports Mixed tier
Report-template CRUD, SQL-driven HTML rendering, and LLM-assisted template authoring under /api/report-templates.
Persists a new SQL-driven HTML report template into _System.ReportTemplates. Body carries the complete html document (with <script type="server"> blocks), mode ("scheduled"|"interactive"), parameters, tags, and an optional per-template max_rows cap. version starts at 1 and createdBy is taken from the caller's JWT. Returns the stored document. No LLM involved.
Request
{
"name": "Monthly Rent Roll",
"description": "Active leases and market rent by property",
"category": "Operational",
"html": "<!DOCTYPE html><html><head><style>@page{size:A4;margin:14mm 12mm}</style></head><body><h1>Rent Roll</h1><table><thead><tr><th>Property</th><th>City</th><th>Market Rent</th></tr></thead><tbody><script type=\"server\">const r=query(\"SELECT property_id, city, market_rent FROM pms.properties WHERE status = :status\",{status:params.status});for(const row of r.rows){out.write('<tr><td>'+esc(row.property_id)+'</td><td>'+esc(row.city)+'</td><td>'+fmt.currency(Number(row.market_rent))+'</td></tr>');}</script></tbody></table></body></html>",
"mode": "scheduled",
"parameters": [
{
"name": "status",
"type": "string",
"label": "Status",
"required": true,
"default": "occupied"
}
],
"tags": [
"rent-roll",
"operational"
],
"max_rows": 5000
}
Returns a lightweight list of saved templates (SELECT _id, name, description, category, mode, version, createdBy … LIMIT 1000) from _System.ReportTemplates. The heavy html body is NOT included; use GET /{id} to fetch a full template. No LLM involved.
Fetches the full stored template document by id, including the complete html body, parameters, tags, and version. Returns 404 when the id does not exist. No LLM involved.
Shallow-merges the JSON body into the stored template (any field except _id, _createdAt, createdBy which are protected) and auto-increments version. Typically used to save html/parameters/name/tags edits. Returns 404 when the id is unknown. No LLM involved.
Loads the template and renders it server-side through the boa-backed report engine under the caller's RLS principal. Parameters are supplied via query string and coerced to the declared parameter types; the template's max_rows override is honoured. Charts render as inline SVG (email_safe_charts=false) for in-browser viewing. Rendering executes the template's SQL only; it does NOT invoke the LLM, so it works on the InventDB Serverless tier.
Parameters
Name
In
Type
Description
id
path
string
Template id to render.
status
query
string
Any declared template parameter, e.g. ?status=occupied (parameter names vary per template).
POST variant of the render endpoint: accepts a typed/nested JSON params object instead of query-string params, avoiding URL-encoding. email_safe_charts defaults to true (email/bulk-email use); the in-app viewer sends false to get SVG charts. Executes the template SQL under the caller's RLS principal; no LLM is invoked, so it works on InventDB Serverless.
Renders an arbitrary report-template html document supplied inline (not saved) through the same engine pipeline under the caller's RLS principal. Body is a RenderRequest: { html, params, mode?, limits?, email_safe_charts? }. Used by the AI Canvas / editor preview to render before saving. Returns 400 when html is empty, 422 when a server script crashes. Pure rendering with no LLM, so it works on InventDB Serverless.
Request
{
"html": "<!DOCTYPE html><html><body><script type=\"server\">const r=query(\"SELECT COUNT(*) AS value FROM pms.properties\");out.write('Total properties: '+fmt.number(r.rows[0].value));</script></body></html>",
"params": {},
"mode": "scheduled",
"email_safe_charts": false
}
Editor's inline data inspector: substitutes :name params into the given SQL (string values quoted/escaped), expands CURRENT_DATE, appends a LIMIT (default 500) for non-aggregate queries, and executes it. Returns the rows, row count, and execution time. Returns 400 when sql is missing or the query errors. Straight SQL execution with no LLM, so it works on InventDB Serverless.
Request
{
"sql": "SELECT property_id, city, state, market_rent, status FROM pms.properties WHERE status = :status",
"params": {
"status": "occupied"
},
"max_rows": 100
}
POST/api/report-templates/generateBearerInventDB SOAR only
Renders a report from either an inline html body or a saved template_id, merging params/parameters into the render. Listed among the AI report routes and gated on the AI tier: on an InventDB Serverless instance the whole report-templates nest requires AI to be enabled, so this returns 403 with the "AI features are not available on the Serverless Database tier." error. Requires html OR template_id (400 otherwise). 403 on the InventDB Serverless tier (this route calls the built-in LLM).
POST/api/report-templates/from-documentBearerInventDB SOAR only
Multipart upload (file + optional name/description). The built-in LLM (vision) reads the uploaded design (PDF/DOCX/XLSX/image) and authors a complete SQL-driven HTML report-template document bound to the customer's schema, returning { html, parameters, mode }. Invokes the built-in LLM, so it returns 403 on the InventDB Serverless tier. Also returns 400 when no file is sent, 422 on text-extract failure or non-JSON model output, 502 on LLM error. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Parameters
Name
In
Type
Description
file
query
file (multipart)
The design document to recreate (PDF, DOCX, XLSX, or image). Multipart form field rather than a query param.
POST/api/report-templates/{id}/layout/streamBearerInventDB SOAR only
SSE endpoint. The user gives a natural-language layout instruction (optionally with pasted images/attachments); the built-in LLM returns a COMPLETE replacement html document, which is validate-rendered under RLS and, if it renders, persisted (version bumped, parameters auto-derived). Streams start/reasoning/html/saved/done (or error) events. Invokes the built-in LLM, so it returns 403 on the InventDB Serverless tier. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Parameters
Name
In
Type
Description
id
path
string
Template id being edited.
Request
{
"instruction": "Add a bar chart of total market rent grouped by city, and use a teal accent.",
"messages": [],
"conversationMode": false,
"modelFamily": "claude"
}
Response 200
event: start
data: {"template_id":"tpl_8f21ac","current_version":3,"instruction":"Add a bar chart..."}
event: reasoning
data: {"content":"Composing the report… (8s)"}
event: html
data: {"html":"<!DOCTYPE html>...</html>","bytes":21044}
event: saved
data: {"template_id":"tpl_8f21ac","version":4}
event: done
data: {}
Promotes a rendered ad-hoc report attachment (under _System.AIReports) into a saved template. Prefers the source-tagged sibling attachment (which keeps the live <script type="server"> bindings), auto-detects interactive vs scheduled mode from the html, auto-derives parameters from params.<name> accesses, inserts the new template, and returns { id, editorUrl }. Reads attachments and inserts a record without any LLM call, so it works on InventDB Serverless. Returns 404/400 when the source attachment is missing/empty/non-UTF-8.
Natural-language AI agent: streaming analyst chat, NL-to-SQL, data/type/recipe generation, plus non-LLM helpers (model/config introspection, chat file staging, transactional change-set apply, and Analyze-thread persistence).
POST/ai/chat/streamBearerInventDB SOAR only
Runs the v3 tool-calling agent loop and streams progress as Server-Sent Events (each event data is a JSON AgentStep: {type, content, ...} plus tool results, SQL steps, widgets, forms, charts, and a final done). This is an alias for /ai/chat/v3/stream; the Console app calls it directly and the Tenantry proxy forwards to /ai/chat/v3/stream, so both converge on the same backend. AI config is read live from the encrypted DbSettings record; the per-message model_family (or the customer's configured default) resolves the provider/gateway path. Invokes the built-in LLM. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"messages": [
{
"role": "user",
"content": "Which owners have the highest total market_value across their properties?"
}
],
"conversationMode": true,
"modelFamily": "claude",
"theme": "light",
"timeZone": "America/New_York"
}
Response 200
data: {"type":"info","content":"Analyzing your question..."}
data: {"type":"sql","content":"Querying database...","sql":"SELECT o.owner_id, o.name, SUM(p.market_value) AS total_value FROM pms.properties p JOIN pms.owners o ON p.owner_id = o.owner_id GROUP BY o.owner_id, o.name ORDER BY total_value DESC LIMIT 5"}
data: {"type":"result","content":"Query returned 5 rows","rows":[{"owner_id":"O-1001","name":"Ridgeline Holdings","total_value":4820000}]}
data: {"type":"done","content":"","answer":"Ridgeline Holdings (O-1001) holds the highest total market value at $4.82M."}
POST/ai/chat/v2/streamBearerInventDB SOAR only
Legacy v2 agent loop that streams SSE AgentStep events. Uses the ToolRegistry two-tier loop with task management. AI config is read live from DbSettings; 400 if no provider/key is configured. Superseded by v3 (/ai/chat/stream) but kept for compatibility. Invokes the built-in LLM. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"messages": [
{
"role": "user",
"content": "Show me all open work orders for property P-5001"
}
],
"theme": "light"
}
Response 200
data: {"type":"info","content":"Analyzing your question..."}
data: {"type":"result","content":"Query returned 3 rows","rows":[{"property_id":"P-5001","status":"open","description":"HVAC repair"}]}
data: {"type":"done","content":""}
POST/ai/chat/v3/streamBearerInventDB SOAR only
The canonical v3 tool-calling agent loop. Identical backend to /ai/chat/stream. Streams SSE AgentStep events; resolves the model via apply_model_family so each family routes to its own gateway path (Claude -> Anthropic /messages, Sparkle -> OpenAI /chat/completions). 400 if no provider is configured. Invokes the built-in LLM. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"messages": [
{
"role": "user",
"content": "Vacate the tenant on lease L-7039 and start a new lease for the incoming tenant"
}
],
"modelFamily": "open"
}
Response 200
data: {"type":"info","content":"Analyzing your question..."}
data: {"type":"change_set","content":"Review the proposed changes","steps":[{"op":"update","typeName":"leases","recordId":"L-7039"}]}
data: {"type":"done","content":""}
POST/ai/chat/{tab_id}/respondBearerInventDB SOAR only
User's decision on a task that is in the awaiting_input state, keyed by the chat tab id. responseType is one of approve, deny, edit, cancel (also approve_all/answer). For edit/answer, value carries the edited SQL or answer text. Resumes (or cancels) the LLM-driven task and persists it. 403 if the caller is neither the task owner nor superadmin; 404 if no awaiting task exists for the tab. Sits behind the AI gate and resumes an LLM agent loop. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Parameters
Name
In
Type
Description
tab_id
path
string
Chat tab id whose awaiting_input task should be resumed
Request
{
"responseType": "edit",
"value": "SELECT * FROM pms.leases WHERE status = 'active' LIMIT 50"
}
Response 200
{
"status": "running",
"taskId": "task_9f2a"
}
POST/ai/generate-sqlBearerInventDB SOAR only
Turns a natural-language question into a SQL SELECT without running it. Tries fast tiers first (exact + template cache, then the NQC neural query compiler, then the optional PSI engine) and only calls the LLM (Tier 2, tool-calling) on a miss. inferenceSource in the response reports which tier answered (Cache / InventDB NQC / InventDB Inference / External Inference). Refinements pass base_sql (bypasses all fast tiers). context narrows the schema hint; model_family overrides the model. Because the LLM is the fallback path, this route is AI-gated (403 on serverless). 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"question": "list properties in Austin, TX with market_rent over 2000, most expensive first",
"context": {
"namespace": "pms",
"type": "properties"
},
"modelFamily": "claude"
}
Response 200
{
"sql": "SELECT property_id, city, state, market_rent, beds, baths FROM pms.properties WHERE city = 'Austin' AND state = 'TX' AND market_rent > 2000 ORDER BY market_rent DESC",
"inferenceSource": "External Inference"
}
POST/ai/sql-titleBearerInventDB SOAR only
Given a final SQL SELECT, returns a concise 3-7 word Title-Case label for a data-viewer grid, using the same permission-filtered schema context as the SQL generator. Results are cached per sql-hash (cached=true on a repeat hit). Best-effort: on LLM failure returns an empty title with 200 (the client falls back to its own heuristic). 400 if sql is empty. Invokes the built-in LLM on a cache miss. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"sql": "SELECT o.name, COUNT(*) AS property_count FROM pms.properties p JOIN pms.owners o ON p.owner_id = o.owner_id GROUP BY o.name ORDER BY property_count DESC"
}
Response 200
{
"title": "Properties by Owner",
"cached": false
}
POST/ai/generate-typesBearerInventDB SOAR only
Uses the LLM to draft a JSON array of type definitions (namespace, typeName, fields with name/type/description and optional FK references, recordCount) from a natural-language domain description. Used by the simulation/data-seeding wizard. 400 if description is empty; 500 if the model fails to return a valid JSON array (raw text echoed back). Invokes the built-in LLM. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"description": "A property management system with owners, properties, leases and tenants"
}
Streams LLM-generated realistic mock records for each supplied type definition as SSE AgentStep events. Processes parent (FK-target) types first so child records can reference real _id values; caps at 100K records/type and generates up to 50 template records per type via the model. humanReadableIds toggles CUST001-style ids vs UUIDs. Invokes the built-in LLM. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
data: {"type":"info","content":"Generating simulation data for: property management owners"}
data: {"type":"info","content":"Generating 50 template records for pms.owners..."}
data: {"type":"done","content":""}
POST/ai/generate-recipeBearerInventDB SOAR only
Phase 1 of the simulation flow: derives a deterministic data-generation recipe from the supplied type definitions using Rust-side heuristics (field-name + field-type patterns and built-in word pools) and returns it plus a 10-record-per-type preview for user approval. This route does not call the model, but it is part of the AI simulation feature, so it returns 403 on the InventDB Serverless tier. 400 if types is empty. 403 on the InventDB Serverless tier (part of the AI simulation feature).
POST/ai/execute-simulationBearerInventDB SOAR only
Phase 2 of the simulation flow: generates records from an approved recipe and bulk-inserts them into the database, streaming SSE progress (per-type preview, then generating events at every 1% boundary, then a final done_with_answer). FK linking is preserved by processing parent types first and reusing generated _id pools. Generation itself is deterministic (recipe-driven, no model call) but the route validates AI config and sits behind the AI gate (403 on serverless). 400 if the recipe is empty. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
data: {"type":"info","content":"Starting simulation: 1 types, 2500 total records"}
data: {"type":"generating","typeName":"properties","inserted":2500,"total":2500}
data: {"type":"done","content":"Simulation complete. Generated and inserted records across 1 types."}
Returns the configured model first (marked active), followed by provider-appropriate alternatives. For the InventDB gateway the alternatives are catalog-driven from the enabled model registry ('Family - LLM (Gateway)'); for direct anthropic/openai providers a small static list is returned. No LLM invocation, so this stays open on every tier.
Returns whether AI is configured, a masked API key, the base URL, the model, and the resolved default model family (claude / sparkle / sparkle-thinking) read live from DbSettings. Never exposes the raw key. No LLM invocation; open on every tier.
Multipart upload of one file into the per-session, disk-backed staging store. Returns a pending_id the client embeds in '[attached: ... pending: <id>]' markers; the agent reads bytes for vision/text peeks and the canvas form re-attaches on Create. No DB writes, no OCR, no embeddings; files expire after 30 min and are capped at 25 MB (413 if larger). 400 if no file field is present. No LLM invocation; open on every tier.
Returns the raw bytes of a staged file (cache-first, disk-fallback so it survives a restart). Used by the canvas form to re-attach the file to a newly created record. 404 if the pending file is missing or expired; 403 if the caller is not the uploader (superadmin may always fetch). No LLM invocation; open on every tier.
Parameters
Name
In
Type
Description
id
path
string
The pending_id (pf_...) returned by /ai/uploads/stage
Response 200
<raw file bytes; Content-Type + Content-Disposition set from the staged file>
Removes a staged file from the store and disk (called by the canvas form after a successful attach or when the user dismisses the form). Always returns 200 with a removed flag. No LLM invocation; open on every tier.
Parameters
Name
In
Type
Description
id
path
string
The pending_id (pf_...) of the staged file to remove
Runs an array of insert/update/delete steps inside a single InventDB transaction (all-or-nothing), then runs any attach steps post-commit (best-effort, outside the tx). This is the confirm-and-commit chokepoint for the AI canvas change-set card, so writes only land after explicit user consent. update merges partial fields over the current doc; record targets resolve by _id or by matchField business key. Returns per-step results and a transactionId. 400 if steps is empty or a data step fails (transaction rolled back); 409 on commit failure; 200 with ok:false if data committed but some attaches failed. No LLM invocation; open on every tier. An external agent authors the steps, this route just applies them.
Returns the caller's persisted Analyze/Workbench chat threads (newest first) from _system._SoarThreads, scoped by user_id. The server reads via a system principal (bypassing RLS) but enforces per-user scoping on user_id. No LLM invocation; open on every tier.
Creates or updates a single Analyze thread for the caller (the server stamps user_id from the bearer). The full thread payload (exchanges with artifacts + steps) is stored under the underscore-prefixed _exchanges blob field so a reload is a single round-trip and large payloads stay out of the index. 400 if id is missing; 500 on write failure. No LLM invocation; open on every tier.
Request
{
"id": "th_01",
"label": "Owner value analysis",
"created": "2026-06-20T14:03:00Z",
"exchanges": [
{
"question": "Top owners by market_value?",
"answer": "Ridgeline Holdings leads at $4.82M."
}
]
}
Deletes a single Analyze thread owned by the caller (ownership checked against user_id via the system principal). Always returns 200 with ok:true; a non-owned or missing id is a silent no-op. No LLM invocation; open on every tier.
Parameters
Name
In
Type
Description
id
path
string
Thread _id to delete (must be owned by the caller)
Response 200
{
"ok": true
}
POST/ai/docs/askBearerInventDB SOAR only
Answers the last user message from the caller's files. Finds the best passages with the POST /attach/_passages search (in process, within scope, every file access-checked), adds the other passages of the two best files (up to 4 each, in reading order), keys them S1, S2, ... and makes ONE short call to the configured model with the passages, up to 3 earlier turns and the question - no tools, no schema, not the agent. A follow-up (any earlier turn present) is first rewritten into a standalone search query by one more model call. Every quote in the answer is checked against the passage it cites, or the file text just around it: sources[].verified true / false. When the passages hold no answer the reply is exactly "The documents do not say."; strict: true also turns an answer without a verified quote into that text plus the 3 closest passages (unquoted). After a scoped ask that found nothing, a suggestions step offers "Search all my files" (chart.widen: true); a scope never widens by itself. scope: namespace, type (or typeName / type_name), recordId, attachmentIds, folder - a record scope needs namespace and type, a files scope a namespace. passages 1-20 (default 8); model_family / modelFamily picks the model. Response: server-sent events, one AgentStep JSON per data: line (the same shapes as /ai/chat/stream): info progress lines, then done with the answer in content and its sources (filename, attachmentId, preview, key, namespace, typeName, recordId, charOffset, charLength, quote, verified); an error step if the model call fails (plus suggestions with model_unavailable when that model is switched off). 400 {"error": "Ask a question."} without a user message; 400 when AI is not configured. The passages (document text) are sent to the configured model provider. Requires the AI Platform tier - returns HTTP 403 on the Serverless Database tier (this route invokes the built-in LLM). 403 on InventDB Serverless (this route calls the built-in LLM).
Request
{
"messages": [
{
"role": "user",
"content": "What is the notice period to vacate?"
}
],
"scope": {
"namespace": "pms",
"type": "properties",
"recordId": "P-5001"
},
"strict": false,
"passages": 8
}
Response 200
data: {"type":"info","content":"Searching the documents for \"What is the notice period to vacate?\"…"}
data: {"type":"info","content":"Reading 6 passages from 2 files…"}
data: {"type":"done","content":"Sixty days: \"Tenant shall give Landlord at least sixty (60) days written notice before vacating the Premises\" [S1] (Lease-L-7039.pdf).","sources":[{"filename":"Lease-L-7039.pdf","attachmentId":"att_3f9c2a1e-8b4d-4c6e-9a7f-2d1b5e8c0a47","similarity":0.0,"preview":"...TERMINATION. Tenant shall give Landlord at least sixty (60) days written notice before vacating the Premises. Notice must be delivered in writing to the address in Section 22...","key":"S1","namespace":"pms","typeName":"properties","recordId":"p-101","charOffset":18240,"charLength":1012,"quote":"Tenant shall give Landlord at least sixty (60) days written notice before vacating the Premises","verified":true}]}
POST/ai/sheet-assistBearerInventDB SOAR only
Turns a request about a sheet (a spreadsheet view of one collection) into ONE edit the grid can apply: add_formula (header + an Excel-style formula over [Header] references), add_chart (chart: type bar | line | stack | donut | scatter | kpi, dim, meas, agg sum | avg | min | max | count), set_total (total: footer aggregate on a column), build_sheet (columns + charts) or explain (prose only). One no-think model call that sees the collection name, the column headers, types and formulas and the question - no row values. Checked server-side before anything is returned: a formula naming a column the sheet lacks, a chart grouping or measuring a formula column, or summing a non-number column comes back as explain ("I didn't apply that - ..."). Always 200: AI not configured, a failed model call or an unreadable answer also come back as explain with a message; message is always set and shown verbatim. Fields: question (required), namespace, type_name, columns [{key, header, type (money | int | number are numeric), kind field | formula, formula}], model_family (snake_case only). Nothing is stored. Requires the AI Platform tier - returns HTTP 403 on the Serverless Database tier (this route invokes the built-in LLM). 403 on InventDB Serverless (this route calls the built-in LLM).
For a table outside an agent turn: decides each column's display kind - money (with an ISO currency, default the instance's currency, optionally currency_column), number or duration (optional unit), count, percent, date, datetime, month, text, id, boolean; optional decimals 0-4 - from the column names and value TYPES only (integer, decimal, boolean, text, date text, month text, timestamp text, list, object, empty; any other type is read as text), plus the optional question and sql. No values go to the model; the client applies the answer to the values it holds. One no-think call with a 25 s timeout; an error or timeout gives {"formats": {}} (show values plainly). Identical asks are cached in memory. Up to 40 columns; names cut at 128 characters, question at 1,000, SQL at 4,000. 400 when no column is named; 400 when AI is not configured. Requires the AI Platform tier - returns HTTP 403 on the Serverless Database tier (this route invokes the built-in LLM). 403 on InventDB Serverless (this route calls the built-in LLM).
Request
{
"columns": [
{
"name": "city",
"type": "text"
},
{
"name": "avg_market_rent",
"type": "decimal"
},
{
"name": "vacant_units",
"type": "integer"
}
],
"question": "average market rent and vacant units by city",
"sql": "SELECT city, AVG(market_rent) AS avg_market_rent, COUNT(*) AS vacant_units FROM pms.properties WHERE status = 'vacant' GROUP BY city"
}
OpenAI-compatible LLM API surface (/v1): chat completions proxied to the built-in model, model listing, and local MiniLM embeddings.
POST/v1/chat/completionsBearerInventDB SOAR only
Proxies an OpenAI-style chat request through the shared LlmClient (the same client the AI agent uses), which dispatches to the configured provider (Anthropic reshapes to /v1/messages; OpenAI / InventDB Gateway / llama-server keep the /v1/chat/completions shape). Requires the messages array; temperature defaults to 0.7. Because it invokes the built-in LLM it returns HTTP 403 on the InventDB Serverless tier. Returns an OpenAI chat.completion object (usage counters are zeroed). 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"messages": [
{
"role": "system",
"content": "You are a property-management assistant."
},
{
"role": "user",
"content": "Summarize the lease status for owner O-1001's properties."
}
],
"temperature": 0.7
}
Returns the configured external model in OpenAI list format. Reads model metadata from LlmRouter.external_config() and does NOT invoke the LLM, so it works on all tiers including InventDB Serverless.
Generates embeddings using the local all-MiniLM-L6-v2 runtime via LazyEmbeddingGenerator. Accepts a single string or an array of strings in the input field. This is the local embedding model (part of the serverless OCR+MiniLM carve-out), NOT the built-in chat/completion LLM, so it works on the InventDB Serverless tier. Returns 503 if the MiniLM model is not installed. Usage token counts are approximated by whitespace-split word count.
Request
{
"input": [
"Property P-5001 in Austin, TX with market_rent 2400",
"Owner O-1001 contact info"
]
}
Returns all persisted agent tasks owned by the authenticated user (scoped by claims.sub). Each task is a resumable, auditable record of a promoted 'full task mode' agent run: its state, steps, files created, iteration count, and token/time totals. Reads persisted records only; invokes no LLM, so it works on the InventDB Serverless tier.
Response 200
{
"tasks": [
{
"id": "3f2a9c14-7b0e-4d2a-9c1f-8e6b5a1d0042",
"chatTabId": "direct",
"chatMessageSeq": 0,
"owner": "maya@pmco.example",
"ownerRole": "admin",
"title": "Analyze vacant units and market rent by city",
"goal": "Give me a full analysis of vacant properties and their market rent across cities",
"state": "Done",
"steps": [],
"filesCreated": [],
"variables": {},
"maxIterations": 50,
"iterationCount": 8,
"timeoutSeconds": 300,
"confirmationPolicy": "Always",
"createdAt": "2026-07-13T09:12:04Z",
"updatedAt": "2026-07-13T09:13:41Z",
"completedAt": "2026-07-13T09:13:41Z",
"totalLlmTokens": 18422,
"totalExecutionTimeMs": 96540
}
]
}
Returns the full AgentTask record for the given task id, including its complete step audit trail, task-scoped variables, and any files created. Access is restricted to the task owner or an admin/superadmin (403 otherwise); an unknown id returns 404. Reads a persisted record only; no LLM is invoked, so it works on the InventDB Serverless tier.
Parameters
Name
In
Type
Description
id
path
string
The task UUID (from the list endpoint's `id` field).
Response 200
{
"id": "3f2a9c14-7b0e-4d2a-9c1f-8e6b5a1d0042",
"chatTabId": "direct",
"chatMessageSeq": 0,
"owner": "maya@pmco.example",
"ownerRole": "admin",
"title": "Analyze vacant units and market rent by city",
"goal": "Give me a full analysis of vacant properties and their market rent across cities",
"state": "Done",
"steps": [
{
"stepNumber": 1,
"toolName": "sql_query",
"input": {
"sql": "SELECT city, AVG(market_rent) FROM pms.properties WHERE status = 'vacant' GROUP BY city"
}
}
],
"filesCreated": [],
"variables": {},
"maxIterations": 50,
"iterationCount": 8,
"timeoutSeconds": 300,
"confirmationPolicy": "Always",
"createdAt": "2026-07-13T09:12:04Z",
"updatedAt": "2026-07-13T09:13:41Z",
"completedAt": "2026-07-13T09:13:41Z",
"totalLlmTokens": 18422,
"totalExecutionTimeMs": 96540
}
Marks the task as Cancelled and persists the change, stopping any further agent iterations for it. Restricted to the task owner or a superadmin (403 otherwise); an unknown id returns 404. This only flips persisted task state; it invokes no LLM and works on the InventDB Serverless tier.
Permanently deletes the persisted agent task record. Restricted to the task owner or a superadmin (403 otherwise); an unknown id returns 404. Deletes a stored record only; no LLM is invoked, so it works on the InventDB Serverless tier.
Returns whether the authenticated user has connected Gmail, and if so the connected email address and the Unix-seconds timestamp of when the connection was made. Reads the stored token record from _system.user_integrations keyed by gmail:{username}; never touches the built-in LLM.
Returns the Google OAuth client_id and the requested Gmail scopes (gmail.send + gmail.readonly) plus a configured flag indicating whether the server has both client_id and client_secret resolved (from DbSettings google_oauth, env fallback). The browser uses this to initialize Google Identity Services initCodeClient. No LLM involved.
Accepts the one-shot authorization code obtained by the browser via Google Identity Services (ux_mode popup, redirect_uri=postmessage), exchanges it at Google's token endpoint for an access + refresh token pair, fetches the connected Gmail address, and persists the tokens (encrypted at rest) in _system.user_integrations. Returns 503 if OAuth is not configured, 400 if the exchange fails or Google returns no refresh token. Pure OAuth connect flow; no built-in LLM call.
Best-effort revokes the stored refresh token at Google's revoke endpoint, then always deletes the local token record from _system.user_integrations for the current user. Idempotent: returns ok:true even if no tokens were stored. No LLM involved.
Sends one email through the user's connected Gmail. The RFC-2822 message is built server-side with an RFC 2047 encoded-word Subject and a deterministic Message-ID (<wf-<nonce>@inventdb.local>) for reply-thread correlation. Optional attachments reference existing InventDB attachments by namespace + attachment_id and are fetched from NativeAttachmentStore and MIME-embedded. When INVENTDB_DEMO_SAFE_EMAIL is set, recipients are overridden. Auto-refreshes the access token first (401 on failure), 503 if OAuth unconfigured, 502 on Gmail send failure. This is a direct Gmail API send rather than an LLM call.
Request
{
"to": "owner@acme-pm.com",
"cc": [],
"bcc": [],
"subject": "Past Due on Lease L-7011 at 42 Elm St",
"body_html": "<p>Hi Jane, rent for P-5001 (market_rent $2,150) is past due.</p>",
"attachments": [
{
"namespace": "pms",
"attachment_id": "att-9f2c",
"filename": "statement-P-5001.pdf",
"content_type": "application/pdf"
}
]
}
Accepts an emails array (each a fully substituted SendEmailInput) and dispatches them serially through the connected Gmail account to stay under Gmail's per-user send quota. Refreshes the access token once for the whole batch and returns a per-row success/failure result so the UI can surface cell-by-cell status. 400 if the array is empty, 503 if OAuth unconfigured, 401 on token refresh failure. Each send is a direct Gmail API call; no LLM involved (the frontend already rendered the bodies).
Request
{
"emails": [
{
"to": "owner1@acme-pm.com",
"subject": "Rent reminder P-5001",
"body_html": "<p>P-5001 market_rent $2,150 due for owner O-1001.</p>"
},
{
"to": "owner2@acme-pm.com",
"subject": "Rent reminder P-5002",
"body_html": "<p>P-5002 market_rent $1,875 due for owner O-1002.</p>"
}
]
}
Lists recent messages from the connected Gmail account within the last `days` window, optionally filtered by a Gmail search query (from:, to:, subject:, etc.). Each result carries decoded headers (RFC 2047 + mojibake-repaired), snippet, full decoded body (text/plain preferred, HTML stripped to plain), and correlation headers (rfc_message_id, in_reply_to, references). days is clamped 1-365, max clamped 1-50. Auto-refreshes token; 503 if OAuth unconfigured, 401 on refresh failure, 502 on Gmail list failure. Read-only Gmail API access; no LLM.
Parameters
Name
In
Type
Description
days
query
integer
Look-back window in days (default 7, clamped 1-365)
q
query
string
Optional Gmail search query appended to newer_than filter (e.g. from:owner@acme-pm.com)
max
query
integer
Max messages to fetch (default 20, clamped 1-50)
Response 200
[
{
"id": "18f3a2b9c1d4e5f6",
"thread_id": "18f3a2b9c1d4e5f6",
"from": "owner@acme-pm.com",
"to": "manager@acme-pm.com",
"subject": "Re: Past Due on Lease L-7011",
"date": "2026-06-20T14:03:00-07:00",
"snippet": "I can pay by Friday for P-5001...",
"body": "I can pay by Friday for P-5001. Please confirm the amount.",
"rfc_message_id": "<CAF123@mail.gmail.com>",
"in_reply_to": "<wf-1749600000123456789@inventdb.local>"
}
]
Fetches a single message by Gmail id (format=full), returning meta (headers, snippet, decoded body) plus separate body_text and body_html fields. Used by the expand action on the EmailSummaryCard. Auto-refreshes token; 503 if OAuth unconfigured, 401 on refresh failure, 502 on Gmail get failure. Read-only Gmail API access; no LLM.
Parameters
Name
In
Type
Description
id
path
string
Gmail internal message id
Response 200
{
"meta": {
"id": "18f3a2b9c1d4e5f6",
"thread_id": "18f3a2b9c1d4e5f6",
"from": "owner@acme-pm.com",
"to": "manager@acme-pm.com",
"subject": "Re: Past Due on Lease L-7011",
"date": "2026-06-20T14:03:00-07:00",
"snippet": "I can pay by Friday for P-5001...",
"body": "I can pay by Friday for P-5001. Please confirm the amount.",
"in_reply_to": "<wf-1749600000123456789@inventdb.local>"
},
"body_text": "I can pay by Friday for P-5001. Please confirm the amount.",
"body_html": "<div>I can pay by Friday for P-5001. Please confirm the amount.</div>"
}
Calendar Integration Any tier
Google Calendar integration: per-user OAuth connect plus list/create/update/delete events and free/busy; no built-in LLM involved.
Returns whether the authenticated user has a stored Google Calendar OAuth grant. When connected, includes the user's primary calendar email and the connect timestamp (unix seconds). Reads token record `_system.user_integrations` keyed by `gcal:{username}`. No LLM.
Returns the server-side Google OAuth client_id and requested Calendar scopes so the frontend can launch the consent popup. `configured` is false when no Google OAuth client is set (via DbSettings google_oauth or GOOGLE_OAUTH_*/GMAIL_OAUTH_* env). The OAuth client is shared with Gmail. No LLM.
Exchanges the OAuth `code` (from the postmessage popup flow) for tokens at Google, captures the primary calendar email, and persists a per-user CalendarTokens record keyed by `gcal:{username}`. Returns 503 when Google OAuth is not configured, and 400 when the exchange fails or Google returns no refresh_token (needs access_type=offline + prompt=consent). No LLM.
Best-effort revokes the stored refresh token at Google's revoke endpoint and deletes the local CalendarTokens record for the user. Always returns ok:true. No LLM.
Refreshes the access token if needed, then lists the user's calendars (minAccessRole=writer, up to 50) via Google's calendarList API. Returns 503 if OAuth not configured, 401 if Calendar not connected / token refresh fails, 502 on upstream Google errors. No LLM.
Lists events for a calendar (defaults to `primary`) between timeMin and timeMax (RFC 3339), expanding recurrences (singleEvents=true) and ordering by start time. Optional free-text `q` filter and `max` cap (1..250, default 50). Returns 503 if OAuth not configured, 401 if not connected, 502 on Google errors. No LLM.
Creates an event on the target calendar (defaults to `primary`), supporting timed or all-day events, IANA time_zone, attendees (sendUpdates=all so Google emails invites), and optional Google Meet link (add_meet). Under demo-safe mode all attendee addresses are rewritten to the configured safe address. Returns 503 if OAuth not configured, 401 if not connected, 502 on Google errors. No LLM.
Partially updates an event by id on the target calendar (defaults to `primary`). Any of summary/description/location/attendees may be set; start and end must be supplied together (Google rejects only-one) and all_day toggles date vs dateTime shapes. sendUpdates=all notifies attendees. Returns 503 if OAuth not configured, 401 if not connected, 502 on Google errors. No LLM.
Deletes an event by id from the target calendar (defaults to `primary`); sendUpdates=all cancels the invite for attendees. A Google 410 Gone (already deleted) is treated as success. Returns 503 if OAuth not configured, 401 if not connected, 502 on other Google errors. No LLM.
Creates a list of pre-rendered events sequentially against the user's calendar (sequential to respect Google's per-user write throttling). Returns per-item results with saved/failed counts. Rejects an empty events array with 400. Returns 503 if OAuth not configured, 401 if not connected. Each event uses the same CreateEventInput shape as POST /events. No LLM.
Bring-your-own-Twilio SMS integration: per-user credential storage, number listing, single/bulk SMS send, message history, and a public signature-verified inbound webhook.
Returns whether the authenticated user has stored Twilio credentials, along with the connected Account SID, Twilio friendly name, default 'From' number, whether an auth token is present (needed for webhook signature verification), and the connection timestamp. When not connected, all fields are null/false. No LLM involved.
Persists the user's Twilio credentials (encrypt-stored in _system.user_integrations keyed by twilio:{username}). Requires account_sid (must start with 'AC' and be 34 chars) plus EITHER an auth_token OR an api_key_sid+api_key_secret pair. Credentials are validated live against GET /Accounts/{SID}.json before persisting; a 401 is returned if Twilio rejects them. A previously-configured default_from is preserved across re-saves. Returns the same shape as /status. Configures an external provider (Twilio) rather than the built-in LLM.
Fetches up to 50 IncomingPhoneNumbers from the user's Twilio account (GET /Accounts/{SID}/IncomingPhoneNumbers.json), returning each number's SID, E.164 phone number, friendly name, and whether it is SMS-capable. Returns 401 if Twilio is not connected, 502 if the Twilio API call fails. No LLM involved.
Sets the default outbound 'From' number used by /send and /bulk-send when a message omits an explicit 'from'. Persists to the user's stored credentials. Returns 401 if Twilio is not connected. No LLM involved.
Sends one SMS via the user's Twilio account (POST /Accounts/{SID}/Messages.json). Body requires 'to' and 'body'; 'from' is optional and falls back to the stored default_from (error if neither is set). Returns the Twilio message SID, delivery status, resolved to/from numbers, and segment count. Returns 401 if not connected, 502 on Twilio API failure. Uses the external Twilio API rather than the built-in LLM, so it works on InventDB Serverless.
Request
{
"to": "+14155550188",
"from": "+18885550100",
"body": "Reminder: rent for P-5001 (Austin, TX) is due. Balance $2450."
}
Sends an array of SMS messages sequentially, each with its own to/body/optional from. Returns per-message results (ok flag, SID or error, segment count) plus aggregate sent/failed counts. Returns 400 if the messages array is empty, 401 if not connected. Individual message failures are captured in the results array rather than failing the whole request. External Twilio API, no built-in LLM, so it works on InventDB Serverless.
Request
{
"messages": [
{
"to": "+14155550188",
"body": "Rent reminder for owner O-1001."
},
{
"to": "+14155550190",
"from": "+18885550100",
"body": "Work order update for P-5001."
}
]
}
Lists recent messages from the user's Twilio account (GET /Accounts/{SID}/Messages.json), filtered by a rolling day window and optional from/to numbers. Returns SID, direction, from/to, body, status, date_sent, segment count, and price/price_unit per message. Returns 401 if not connected, 502 on Twilio failure. No built-in LLM, so it works on InventDB Serverless.
Parameters
Name
In
Type
Description
days
query
integer
Rolling window of days to look back (DateSent>=). Defaults to 7; minimum enforced as 1.
from
query
string
Optional filter; only messages sent from this E.164 number.
to
query
string
Optional filter; only messages sent to this E.164 number.
max
query
integer
Max rows to fetch (PageSize). Defaults to 50; clamped to 1..=100.
Public route (no JWT) that Twilio POSTs as application/x-www-form-urlencoded when one of the user's numbers receives an SMS. The user is identified via the AccountSid form field; the X-Twilio-Signature header is verified with HMAC-SHA1 over the full request URL plus sorted params keyed by the user's auth_token (honouring X-Forwarded-Proto/Host for reverse-proxy setups). On success a stripped record (account_sid, message_sid, from, to, body, num_segments, num_media, received_at, username) is persisted to _system.twilio_incoming as an audit/compliance log and an empty TwiML-equivalent 200 is returned. Missing AccountSid => 400; unknown account => 404; signature mismatch => 401. No built-in LLM involved.
Per-user opt-in toggle for the AI agent's web-search tool. Searches execute server-side via Amazon Bedrock AgentCore (no browser-side key, no client egress); the agent loop that consumes the results is the LLM-gated part.
Returns whether the AI agent's hosted web-search tool is enabled for the authenticated user, plus whether they have acknowledged the data-leaves-tenant consent dialog and when. Reads a single per-user document from _system.user_integrations keyed by websearch:{username}; if none exists, returns enabled=false/consented=false. Pure settings read; does not invoke the built-in LLM, so it works on the InventDB Serverless tier.
Turns on the opt-in web-search integration for the authenticated user. Sets enabled=true on the per-user _system.user_integrations document (creating it if absent). Records the consent timestamp the first time it is enabled and preserves that timestamp across later disable/re-enable cycles so the consent dialog is not re-shown. This only flips a settings flag that the agent loop later reads to decide whether to run server-side web search via Amazon Bedrock AgentCore; the route itself does not call the built-in LLM, so it works on the InventDB Serverless tier.
Turns off the web-search integration for the authenticated user by setting enabled=false on the per-user _system.user_integrations document. The original consent timestamp is preserved so the user is not re-prompted if they re-enable later. Settings-write only; does not invoke the built-in LLM, so it works on the InventDB Serverless tier.
Request
{}
Response 200
{
"ok": true,
"enabled": false
}
AI Usage Metrics Any tier
Read-only AI usage/cost analytics, per-user/type/model breakdowns and quota management; no LLM invoked, so it works on the InventDB Serverless tier (reports zero AI usage).
Rolls up _system.AIUsage into a single period summary: request count, input/output/cached token totals, cache hit rate, average latency, and USD cost rollups (total/input/output). Reports mode 'local' or 'external' depending on whether a local LLM router is registered. Totals are grouped by model over all recorded usage; the period param is accepted but does not filter the totals. Read-only reporting; invokes no LLM, works on serverless (reports zeros).
Parameters
Name
In
Type
Description
period
query
string
Lookback window token, e.g. 30d, 7d, 24h. Defaults to 30d. Currently echoed in the response but not applied to filtering.
Returns a per-day series (bucketed by the YYYY-MM-DD prefix of _createdAt) of request count, input/output/cached tokens, average latency, and total USD cost. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Lookback window token (30d/7d/24h). Defaults to 30d; echoed back but not applied to filtering.
Returns one row per model from _system.AIUsage (GROUP BY model): request count, input/output/cached token sums, total USD cost (rounded to 4 decimals) and average latency. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Lookback window token; defaults to 30d, echoed but not applied to filtering.
Lightweight health probe reporting whether a local LLM is available and the resulting mode ('local' vs 'external'). Does not query any table and does not invoke the LLM; works on serverless.
Same summary shape as /usage but sourced from the gateway's central AIGateway.Usage ledger, scoped to the calling customer via WHERE clientId = <jwt.sub> (RLS-enforced). Rows are post-filtered by the period threshold in memory and cost is computed on-read from the pricing rate cache. Missing table / RLS-deny degrades to zeroed metrics rather than a 500. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Window token: 24h/1d, 7d, 30d, 90d. Unrecognized tokens fall back to all-time. Defaults to 30d.
Daily series (bucketed by the YYYY-MM-DD prefix of the gateway's rfc3339 timestamp) from AIGateway.Usage, scoped to the calling customer via clientId and post-filtered by the period threshold. Cost computed on-read from the pricing cache. Missing table degrades to an empty series. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Window token: 24h/1d, 7d, 30d, 90d. Defaults to 30d; unrecognized falls back to all-time.
Per-model breakdown that, despite the name, reads THIS instance's own _system.AIUsage ledger (AIGateway.Usage is not written on an InventDB SOAR/customer instance). Raw (provider,model) variants are folded into one friendly model name; each row carries request count, token sums, average latency, total USD cost, and a 4-lever breakdown (Input / Cache read / Cache write / Output with tokens, per-1M rate, and subtotal). Sorted highest-spend first. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Window token: 24h/1d, 7d, 30d, 90d. When recognized it applies a WHERE timestamp >= threshold filter; otherwise all-time. Defaults to 30d.
Returns AI quota status from the quota subsystem. Admin/superadmin callers see full config (global + per-user limits), today's usage totals, and by-user / by-type breakdowns. Non-admins get a redacted view: global limit knobs and global totals are stripped, top-level quota-pct fields removed, byUser filtered to the caller's own row, and byType dropped. Read-only; no LLM, works on serverless.
Updates the global and per-user daily request/token limits and the enabled flag. Admin/superadmin only; returns 403 for any other role so a user with a domain write grant cannot raise their own AI limits. Returns the applied config. No LLM invoked; works on serverless.
Resets the current day's AI quota counter. Admin/superadmin only; returns 403 otherwise so a user cannot zero out their own usage to bypass the per-user cap. No LLM invoked; works on serverless.
Aggregates _system.AIUsage per database user in Rust: request count, input/output/cached tokens, total tokens (input+output) and average latency. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Lookback window token; defaults to 30d, echoed but not applied to filtering.
Aggregates _system.AIUsage per usageType (e.g. chat, report, extract) in Rust: request count, input/output/cached tokens, total tokens and average latency. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
period
query
string
Lookback window token; defaults to 30d, echoed but not applied to filtering.
Detailed analytics for THIS instance from _system.AIUsage (SELECT * LIMIT 200000, filtered by timestamp prefix in Rust). Default mode returns period totals (requests, tokens, cache hit rate, avg latency, success rate, dollars), a daily series, and byModel / byOperation / byUser / byProvider buckets, plus the current-month AI $ allowance from the cmgmt account cache (null on standalone instances). With ?day=YYYY-MM-DD it returns that day's per-request rows (newest first). With ?view=events it returns a filterable, paged event feed. Read-only reporting; no LLM, works on serverless.
Parameters
Name
In
Type
Description
month
query
string
Month window YYYY-MM. Defaults to the current UTC month.
day
query
string
Day drill-down YYYY-MM-DD; returns that day's per-request rows newest-first instead of the aggregate.
view
query
string
Set to 'events' for the month-scoped filterable/paged per-request event feed.
model
query
string
events view: exact-match filter on friendly model name.
provider
query
string
events view: exact-match filter on friendly provider name.
user
query
string
events view: exact-match filter on database user.
op
query
string
events view: exact-match filter on usageType/operation.
page
query
integer
events view: zero-based page index. Defaults to 0.
size
query
integer
events view: page size, clamped 1..500. Defaults to 50.
Persist a data-viewer card (its SQL + display config) as a reusable, listable Saved View, with deterministic custom-layout rendering and optional AI layout generation.
Persists a data-viewer card as a `_System.SavedViews` document: its authoritative `baseSql` plus display config (defaultMode, custom layout template link, attachment/search flags, column order, live browse filter, and the Ask-AI conversation that produced the SQL). `createdBy` is taken from the caller's JWT and `version` is forced to 1. Returns the stored document. Deterministic CRUD with no LLM, so it works on the InventDB Serverless tier.
Request
{
"name": "Active Vacant Properties",
"description": "Vacant units ordered by market rent",
"namespace": "pms",
"baseSql": "SELECT property_id, city, state, market_rent, status, beds, baths FROM pms.properties WHERE status = 'vacant' ORDER BY market_rent DESC",
"defaultMode": "table",
"attachmentsEnabled": false,
"searchAttachments": false,
"columns": [
"property_id",
"city",
"state",
"market_rent",
"status"
],
"search": "vacant",
"sort": {
"col": "market_rent",
"dir": "desc"
},
"tags": [
"properties",
"vacancy"
]
}
Response 201
{
"ok": true,
"data": {
"_id": "view_9f2a1c",
"name": "Active Vacant Properties",
"description": "Vacant units ordered by market rent",
"namespace": "pms",
"baseSql": "SELECT property_id, city, state, market_rent, status, beds, baths FROM pms.properties WHERE status = 'vacant' ORDER BY market_rent DESC",
"defaultMode": "table",
"customScope": "row",
"attachmentsEnabled": false,
"searchAttachments": false,
"columns": [
"property_id",
"city",
"state",
"market_rent",
"status"
],
"search": "vacant",
"sort": {
"col": "market_rent",
"dir": "desc"
},
"version": 1,
"createdBy": "u_1001",
"tags": [
"properties",
"vacancy"
]
}
}
Lists all saved views (summary columns only: _id, name, description, namespace, defaultMode, attachmentsEnabled, version, createdBy) ordered by name, capped at 1000. Deterministic read with no LLM, so it works on the InventDB Serverless tier.
Fetches one saved view's full document by id. Returns 404 when the id does not exist. Deterministic read with no LLM, so it works on the InventDB Serverless tier.
Parameters
Name
In
Type
Description
id
path
string
The saved view's _id (e.g. view_9f2a1c).
Response 200
{
"ok": true,
"data": {
"name": "Active Vacant Properties",
"description": "Vacant units ordered by market rent",
"namespace": "pms",
"baseSql": "SELECT property_id, city, state, market_rent, status, beds, baths FROM pms.properties WHERE status = 'vacant' ORDER BY market_rent DESC",
"defaultMode": "table",
"customScope": "row",
"attachmentsEnabled": false,
"searchAttachments": false,
"columns": [
"property_id",
"city"
],
"search": "vacant",
"sort": {
"col": "market_rent",
"dir": "desc"
},
"version": 1,
"createdBy": "7d4e1a90-52c1-4f38-949b-0decafc0ffee",
"tags": [
"properties",
"vacancy"
],
"_id": "5a1fcac6-7089-416a-aef3-57b7c73147ed",
"_createdAt": "2026-07-13T15:57:13.185793800+00:00",
"_updatedAt": "2026-07-13T15:57:13.185793800+00:00",
"_createdBy": "7d4e1a90-52c1-4f38-949b-0decafc0ffee"
}
}
Shallow-merges the JSON body into the existing saved-view document (any subset of fields), ignoring the immutable `_id`, `_createdAt`, and `createdBy` keys, and auto-increments `version`. Returns 404 if the view is missing. Deterministic mutation with no LLM, so it works on the InventDB Serverless tier.
Renders a view's custom (non-table) card layout for a single page. Windows `baseSql` server-side via the engine parser (no client SQL surgery), loads the linked `_System.ReportTemplates` template, runs it over that page with `params.viewSql` set to the windowed SQL, and returns `{ html, total, page, pageSize }` where `total` is the real full row count for accurate paging. Pure report-engine rendering with no model in the path, so it works on the InventDB Serverless tier (an AI-authored template renders with no LLM).
Request
{
"templateId": "tpl_7c33",
"baseSql": "SELECT property_id, city, state, market_rent, status, beds, baths FROM pms.properties WHERE status = 'vacant' ORDER BY market_rent DESC",
"page": 0,
"pageSize": 25
}
POST/api/saved-views/generate-layoutBearerInventDB SOAR only
Invokes the built-in LLM to produce report-engine HTML for a view's custom (non-table) card layout. Fresh generation designs a card layout from the schema + sample records; when `currentHtml` is supplied it EDITS that design applying only `instruction` (with `history` as context). Attached `pendingIds` (from /ai/uploads/stage) are passed as vision inputs (images, e.g. a mockup) or inlined text. The HTML reads its rows from `query(params.viewSql)` and may embed a leading `<!--VIEWSQL: SELECT … -->` directive; the response returns `{ html, sql }` (sql falls back to baseSql). This route calls the built-in LLM, so it returns HTTP 403 on the InventDB Serverless tier. 403 on the InventDB Serverless tier (this route calls the built-in LLM).
Request
{
"baseSql": "SELECT property_id, city, state, market_rent, status, beds, baths, sqft FROM pms.properties",
"namespace": "pms",
"instruction": "Property cards showing photo, city, beds/baths and rent, highest sqft first",
"modelFamily": "claude"
}
Response 200
{
"html": "<style>…</style><script type=\"server\">const r = query(params.viewSql); for (const row of r.rows) { out.write(`<div class=\"card\" data-surface=\"flat\" data-record-id=\"${esc(String(row._id))}\">…${esc(row.city)}…${fmt.currency(row.market_rent)}…</div>`); }</script>",
"sql": "SELECT * FROM pms.properties ORDER BY sqft DESC"
}
Forms Any tier
Schema-driven data-entry form engine: analyze a type's schema, build/store HTML form templates, render forms with FK typeahead lookups, run SQL validation rules, and submit records (create/update).
Samples records from the given namespace/type (default 100 rows) to infer each property's data type, FK targets (fields ending in _id whose target type exists), FK display fields, cascade relationships (e.g. unit_id cascades from property_id), and enum-like fields (2-20 distinct values). Returns the inferred property list, the type's display field, and total record count. Used by an external AI agent to design a form template; the route itself runs no LLM.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (database) name, e.g. 'pms'
type_name
path
string
Type (table) name, e.g. 'properties'
sample_size
query
integer
Number of records to sample for schema inference (default 100)
Searches a target type for a searchable FK picker. Matches the query against the detected display field(s) and _id via LIKE, optionally constrained by a cascade filter (filter=field:value). Returns up to 'limit' items (default 20, capped 200), each with _id, a composed display string, and the full record. No LLM involved.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (database) name, e.g. 'pms'
type_name
path
string
Target type to search, e.g. 'owners'
q
query
string
Search text matched against display field(s) and _id
filter
query
string
Cascade filter in the form field:value, e.g. 'property_id:P-5001'
Inserts a new form template into _System.FormTemplates with the supplied name, target namespace/type, HTML template body (with {{field:*}}, {{lookup:*}}, {{validate:*}} placeholders), bindings, and style. Stamps status='active', version=1, and created_by from the caller's claims. The template body is typically authored by an external AI agent; this route runs no LLM. Returns 201 with the new record id.
Loads the template, resolves {{field}}, {{lookup}}, {{section}}, {{row}}, {{hidden}}, {{validate}} placeholders into inputs, and returns a self-contained HTML page (embedded CSS + FormEngine JS) for creating a new record. Content-Type text/html. No LLM.
Parameters
Name
In
Type
Description
id
path
string
Form template record id
Response 200
<!DOCTYPE html><html lang="en">... New Property form ...</html>
Same as render but loads the target record (namespace/type from the template) and pre-fills inputs and lookup chips for editing. Submit label becomes 'Save Changes'. Returns a self-contained HTML page. No LLM.
Parameters
Name
In
Type
Description
id
path
string
Form template record id
record_id
path
string
Id of the record to edit, e.g. 'P-5001'
Response 200
<!DOCTYPE html><html lang="en">... Editing properties record P-5001 ...</html>
Substitutes :param placeholders in the supplied SQL with values from params (single-quote escaped), executes it against the database, and returns the resulting rows and count. Used by the form engine to enforce {{validate:*}} rules before submit. Executes SQL only; no LLM.
Request
{
"sql": "SELECT COUNT(*) AS c FROM pms.properties WHERE property_id = :property_id",
"params": {
"property_id": "P-5001"
}
}
Resolves the template's target namespace/type, stamps created_by and modified_by from the caller's claims, and inserts the submitted data as a new record. Returns 201 with the new id. No LLM.
Resolves the template's target namespace/type, stamps modified_by from the caller's claims, and updates the identified record with the submitted data. Returns 200 with the record id. No LLM.
Parameters
Name
In
Type
Description
id
path
string
Form template record id
record_id
path
string
Id of the record to update, e.g. 'P-5001'
Request
{
"market_rent": 2600,
"status": "occupied"
}
Response 200
{
"ok": true,
"id": "P-5001"
}
Transactions Any tier
Multi-statement ACID transaction lifecycle: begin, execute buffered CRUD/SQL operations, then commit or rollback.
POST/txBearerInventDB SOAR + InventDB Serverless
Opens a new server-side transaction and returns its generated transaction id. Subsequent execute/commit/rollback calls reference this id. No LLM involved.
Durably commits all buffered operations for the given transaction id. Returns 200 on success or 400 with an error message if the commit fails (e.g. conflict or unknown/expired txId). No LLM involved.
Discards all buffered operations for the given transaction id and releases it. Always returns 200 ok (rollback is idempotent/best-effort). No LLM involved.
Runs a single operation within the open transaction. The request body is tagged by an 'operation' discriminator: insert, update, delete, get, or query. insert/update run referential-integrity validation (returns 409 on RI violation); delete runs RI-for-delete validation (409 on violation). update/delete/get return 404 when the target document does not exist. query runs SQL within the transaction and returns the result rows array. Response carries ExecuteResponse { ok, data, id, error }; success uses HTTP 201 for insert and 200 for update/delete/get/query. No LLM involved; plain buffered CRUD/SQL.
Returns, in a single call, the calling user's identity plus the company, plan tier, and live AI-dollar allowance for THIS instance so the InventDB SOAR profile card and the Console settings page can show company/tier/credits without deep-linking back to the customer portal. The 'user' block is resolved from the caller's own _system.users row (self-introspection pinned to _id = JWT subject under a system principal), falling back to claims-only data for service-account subjects with no row. The 'customer' and 'allowance' blocks come from the cmgmt_account poller cache (HMAC-signed hourly pull from cmgmt); both serialize as null on a STANDALONE instance with no cmgmt configured, and the frontends degrade to user-only. NOT AI-gated: serverless instances still surface user + company + plan (the allowance just stays null/empty there since serverless has no built-in LLM budget). Auth-protected by the global AuthMiddleware (Bearer JWT).
List all users from _system.users. Admin only. Returns a flat JSON array of user objects directly (C#-API compatible, without a wrapper). Supports optional activeOnly and search (username/email substring, case-insensitive) query filters.
Parameters
Name
In
Type
Description
activeOnly
query
boolean
When true, only users with is_active=true are returned.
search
query
string
Case-insensitive substring match on username or email.
Create a new user in _system.users. Admin only. Hashes the password, generates a UUID _id, defaults role to 'reader'. 409 if the username already exists; 400 if username is empty or >64 chars. Returns the created user wrapped in {ok,user}.
Fetch one user by _id, or by username as a fallback (the Console passes the username). Admin only. Returns {ok,user}; 404 when neither _id nor username matches.
Update a user's email, role, and/or password (any subset). Admin only. Password is re-hashed if supplied. Returns the updated user in {ok,user}; 404 if not found.
Change the user's global (JWT primary) role. Admin only. Valid roles: reader, writer, analyst, admin, superadmin. Only a superadmin may grant the superadmin role (403 otherwise); invalid role => 400. Returns {ok,user}.
Set app_roles[<app>]=<role> on a user (dynamic-roles design). Admin only. Validates that (app, role) exists in _system.roles; '_global' is rejected as an app (400). Returns {ok,user}; 404 if the user is not found.
Parameters
Name
In
Type
Description
userId
path
string
User _id.
app
path
string
App id whose role catalog the role belongs to (e.g. inventdb-tenantry).
Check whether the CURRENT user has a given access level on a resource. Admin/superadmin short-circuit to has_permission=true. Delegates to the same rbac helpers the enforcement middleware uses (direct grants + role grants, case-insensitive, access-level hierarchy) so the UI never shows buttons that 403 on click. resource is either 'ns' or 'ns.type'.
Parameters
Name
In
Type
Description
resource
query
string
Namespace ('pms') or fully-qualified type ('pms.properties').
level
query
string
Access level to test: read|write|delete|admin (case-insensitive).
Return the flat array of direct permission grants for a user (Archivus-compatible shape). Admin only. Accepts username or _id in the path; storage is keyed by resolved _id. Enriches each grant with grantedByUsername (batched _id->username lookup). Returns [] when the user has no grants.
Grant a direct permission to a user. Admin only. accessLevel must be read|write|admin (400 otherwise); target user must exist (404, except the 'superadmin' pseudo-user). Optional rowFilter (v1 DSL) and rowFilterSql (v2 SQL) scope the grant to a row subset. Returns 201 with the created permission.
Revoke a single grant from a user by permission _id. Admin only. 404 if the user has no permissions doc or the permissionId is not present. Returns 204 No Content on success.
Create a legacy bundle-named role (_id = name; users opt in via roles[]). Admin only. Validates the name (1-64 chars, [A-Za-z0-9_-:], and that it is not a reserved name), every grant, and any rowFilter. 409 if the name already exists or is bundle-owned. Returns {ok:true,data:Role}.
Request
{
"name": "pms:owner",
"description": "Owner sees only their own properties",
"grants": [
{
"scope": "type",
"resource": "pms.properties",
"accessLevel": "read",
"rowFilter": "owner_id = :current_user"
}
]
}
Fetch one role by bare name (e.g. 'analyst', resolves the seeded role__global_<name> doc) or by fully-qualified internal _id. Admin only. Returns {ok:true,data:Role}; 404 if not found.
Delete a user-owned legacy role. Admin only. Refuses built-in roles (403) and bundle-owned roles (409). By default 409s if any users still carry the role in roles[] (lists them); pass ?force=true to auto-detach from all users first. Returns {ok:true}.
Parameters
Name
In
Type
Description
name
path
string
Role _id/name to delete.
force
query
boolean
When true, detach the role from every user first, then delete.
Attach one role to many users in a single admin call (idempotent). Provide exactly one of userIds (explicit _id list) or whereSql (a WHERE-clause body run as SELECT _id FROM _system.users WHERE <whereSql> under a system principal). 404 if the role does not exist; 400 if neither/both selectors given. Returns counts of attached/skipped plus per-user errors.
Attach a single legacy role to one user (adds to roles[], idempotent). Admin only. Accepts username or _id in the path. 404 if the role or user is not found. Returns {ok:true,data:{username,roles}}.
Remove a single legacy role from a user's roles[] array. Admin only. Accepts username or _id in the path; no-op if the user or role is absent. Returns {ok:true}.
Shows how many rows of one type a row rule would let a given person see, out of how many, before the rule is saved. The rule is rowFilter (v1 filter syntax) and/or rowFilterSql (v2 SQL boolean expression); when both are given they are AND-ed, exactly as the RLS rewriter does, and when neither is given visible equals total. Binds are taken from the target person's real account: :current_user (their _id), :current_username, :current_role, :user_<attribute> from their admin-set attributes (:current_app is empty here). Only the supplied rule is evaluated, not the person's existing grants. Both counts run as the system, so the result does not depend on what the calling admin can see. Nothing is saved. 400 when resource is not "Namespace.Type" or the rule does not parse; 404 when the user is unknown. Admin or superadmin required.
Emails an existing user a one-time link to choose their own password. Mints a random token, stores only its SHA-256 hash and a 7-day expiry on that user's own _system.users row (replacing any earlier invite, whose link stops working), and builds the link as <origin>/recover#invite=<token>; pass origin as the browser's own origin, otherwise the link is relative. The email is sent from a transport the customer owns: the inviting admin's connected Gmail first, else the instance's own saved SMTP sender; the platform relay is never used. With neither configured nothing is sent and the call still succeeds (sent false, error explains). A delivery failure also answers 200 with sent false and the error. The link is always returned to the admin so it can be shared by hand. email defaults to the address on the user's record (400 when there is none). The path takes the user's _id only; a username is not resolved. A JSON body is required ({} is enough). 404 when no user has that _id. Admin or superadmin required.
Returns every property that has a vector (distinct-value) embedding index for the given namespace/type, plus per-property vector count, source property, embedding dimension (384 for all-MiniLM-L6-v2), on-disk file size, and last rebuild time. Also returns the type's total record count. Admin/superadmin only (403 otherwise). Vector embeddings use the local MiniLM model rather than the built-in chat LLM, so this works on the InventDB Serverless tier.
Samples one document from the type and returns every non-system string property (skips names starting with '_', ending in 'Id', or equal to 'id') as a candidate for vectorization, flagging which ones already have an embedding index and their current embedding count. Also returns the total record count. Admin/superadmin only (403 otherwise). Returns 404 if the type does not exist. No built-in LLM involved.
Builds the distinct-value MiniLM embedding cache + HNSW index for a single property and streams progress as Server-Sent Events. Append-only (incremental) by default; pass ?force=true to wipe and rebuild from scratch. Accepts an optional ?token query param so an EventSource (which cannot set Authorization headers) can authenticate. Each SSE 'message' event carries a VectorRegenerationProgress JSON payload (status regenerating/completed/failed, totalRecords=distinct count, processedRecords=cached count, progressPercentage, timestamps, elapsedMs); a final 'done' event closes the stream. Admin/superadmin only (a non-admin caller receives a failed progress event rather than an HTTP 403). Uses the local MiniLM embedder rather than the built-in chat LLM.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (database) name, e.g. 'pms'.
type
path
string
Type (table) name, e.g. 'properties'.
property
path
string
Property to embed, e.g. 'city'.
token
query
string
Optional bearer token for EventSource auth (used in place of the Authorization header).
force
query
boolean
If true, wipe the existing cache and rebuild from scratch. Default false (incremental append-only build).
Returns the last-known VectorRegenerationProgress for a property's embedding build from the in-memory progress tracker; if no build has been tracked it returns an 'idle' snapshot. Used to poll batch regenerations that don't stream SSE. Always HTTP 200 (a non-admin caller gets status 'error' with error_message 'Admin access required' in the body rather than an HTTP 403). No built-in LLM involved.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (database) name, e.g. 'pms'.
type
path
string
Type (table) name, e.g. 'properties'.
property
path
string
Property whose build progress is queried, e.g. 'city'.
Deletes the distinct-value embedding cache file for a single property. Returns ok=true with vectorsDeleted=1 when a cache existed, ok=true with vectorsDeleted=0 when none existed, and 500 on I/O failure. Admin/superadmin only (403 otherwise). No built-in LLM involved.
Parameters
Name
In
Type
Description
namespace
path
string
Namespace (database) name, e.g. 'pms'.
type
path
string
Type (table) name, e.g. 'properties'.
property
path
string
Property whose embedding cache to delete, e.g. 'city'.
Queues incremental (append-only) embedding rebuilds for a list of properties, spawning a background build per property (skips any already regenerating). Returns immediately with the list of queued properties; poll the per-property /progress endpoint to track completion. Returns 400 if the properties list is empty. Admin/superadmin only (403 otherwise). Uses the local MiniLM embedder rather than the built-in chat LLM.
Marks every sealed segment of the given type vectors_pending and runs the backfill synchronously, rebuilding all per-segment HNSW vector indexes for that type. Returns the namespace/type, segments processed, and elapsed time; 500 if the rebuild task fails. Admin/superadmin only (403 otherwise). Uses the local MiniLM embedder rather than the built-in chat LLM.
Superadmin/admin configuration: built-in LLM provider/key/model, unbounded-read row cap and Google OAuth client.
GET/api/admin/ai-configBearerInventDB SOAR only
Returns the configured built-in LLM provider, effective and default base URL/model, whether an API key is stored (never the key itself) and where it resolves from (db/env/none), the sample-data toggle, the high-level model family, and Sparkle settings. On managed (hosted) instances the base URL points at the InventDB AI gateway, which routes Claude to regional Amazon Bedrock inference profiles pinned to your data-residency geo (us/eu/global) and runs web search server-side via Bedrock AgentCore; the model list you can pick from is the one staff have enabled for your account. Admin or superadmin required. 403 on the InventDB Serverless tier (built-in-LLM configuration).
Saves the built-in LLM provider, API key, base URL, model, sample-data toggle, and Sparkle settings. All fields are optional; an omitted field is left unchanged, an empty string clears (for provider/base_url/model/api_key it reverts to provider default or clears the key). On managed instances the model must be one of the models staff have enabled for your account (an unlisted model is rejected); self-hosted instances are unrestricted. Provider/key changes require a server restart to take effect for the running agent loop (restart_required:true). Admin or superadmin required. 403 on the InventDB Serverless tier (built-in-LLM configuration).
PUT/api/admin/ai-config/model-familyBearerInventDB SOAR only
Flips the customer-level default model family, preserving the gateway client key and host. 'claude' -> Anthropic adapter (Claude Opus 4.8 / Sonnet 5 on regional Amazon Bedrock via the AI gateway); 'sparkle'/'sparkle-thinking' -> InventDB Sparkle. The target family is validated against the models staff have enabled for your account; flipping to a family with no enabled model returns 400"… is not an enabled AI model — pick one that staff have enabled for your account". Only provider/base_url/model change; takes effect on the next AI call (no restart). Admin or superadmin required. 403 on the InventDB Serverless tier (built-in-LLM configuration).
Returns the unbounded-read row cap for this instance: the stored cap, the effective cap actually enforced by /sql (env MAX_QUERY_ROWS overrides the stored value), and whether an env override is masking the setting. This is a DATABASE feature, not AI-gated, so it works on the InventDB Serverless tier. Admin or superadmin required.
Sets the unbounded-read row cap (1..10,000,000) that bounds a single unpaginated SELECT via /sql, MCP, or the API; paginated reads (?page&pageSize) are unaffected. Live on the next read (no restart). Not AI-gated, so it works on the InventDB Serverless tier (cmgmt pushes the cap to serverless instances). Admin or superadmin required.
Returns the effective Google OAuth client_id (safe to surface), whether a client secret is stored (never returned), the source of the effective values (db/env/none), and whether the OAuth flow is fully configured. Env vars (GOOGLE_OAUTH_CLIENT_ID/_SECRET, legacy GMAIL_OAUTH_*) are a fallback until a DB value is saved. Not AI-gated (OAuth connect works without the built-in LLM), so it works on the InventDB Serverless tier. Admin or superadmin required.
Persists a fresh Google OAuth client_id/client_secret pair into the encrypted settings record; the OAuth flow picks it up on the next call. Each field is optional: omit to leave unchanged, empty string to clear the DB value and fall back to env, non-empty to overwrite. Returns the effective config. Not AI-gated, so it works on the InventDB Serverless tier. Admin or superadmin required.
Returns the SMTP sender this instance uses for its own mail (invites, workflow emails), with the password never returned (hasPassword says whether one is stored). source tells which sender is in effect: db = the customer saved their own; env = the instance still falls back to the relay handed down at provisioning; none = nothing can send. For env and none every sender field is blank, because the provisioning relay's host and account are not the customer's to see. Not AI-gated, so it works on the Serverless Database tier. Admin or superadmin required.
Saves the customer's own SMTP sender. Every field is optional and an omitted field keeps its stored value; an omitted or empty password keeps the stored password, so the form can be saved back without retyping it. An empty username removes the login and its password. An empty host removes the whole sender, password included (the instance then falls back to the provisioning relay, or to none). port 0 means 587. tls is "starttls" (default) or "none". Rejected with 400: tls other than those two; a fromEmail without @; username without password or the reverse; tls none together with a login (a password is never sent unencrypted); a no-login server with no fromEmail. Used from the next message on, no restart. Returns the saved sender in the GET shape. Not AI-gated. Admin or superadmin required.
Sends one real email (subject "InventDB test email") with the currently saved sender, to prove it works. to defaults to the calling admin's own account email. If the customer has not saved a sender but the provisioning relay is present (source env), the test goes out through that relay. A JSON body is required ({} is enough). 400 when there is no address to send to or no transport configured; 502 with the mail server's error when sending fails. Not AI-gated. Admin or superadmin required.
Current usage against the tier's capacity ceiling, as shown in the console's usage banner. records is the live tenant record count (the product's own namespaces excluded), recounted on every call; bytes is the sampled size of the data directory (records, indexes and attachments share one budget). maxRecords and maxBytes are the ceilings (0 = not enforced), pct is the worst utilisation across the enforced ceilings, warn turns true past the warning threshold, and enforced is true when any ceiling is set. Once a ceiling is reached, inserts are refused with HTTP 507. Not AI-gated. Admin or superadmin required.
Sets the tier's capacity ceiling. This is a full replace: maxRecords, maxBytes and warnPct each default to 0 when omitted, and 0 turns that ceiling off (warnPct 0 = engine default of 80). warnPct above 100 is rejected with 400. Applied immediately, no restart: the engine checks the limits on every insert, and a ceiling below current usage blocks new inserts (HTTP 507) at once. On a managed instance the control plane sets this at provisioning and on every plan change, so a value set by hand can be overwritten. Returns usage in the GET shape. Not AI-gated. Admin or superadmin required.
The workflow notification inbox under /api/workflows/notifications: approval requests and alerts raised by notify_user steps. List, read, mark read, resolve an approval to resume the waiting run, and delete one or many.
Returns the caller's inbox from _System.Notifications: items written by notify_user workflow steps, including approval requests that a parked run is waiting on, plus run-failure alerts. Each row carries title, body, the available actions ([{id, label, kind}], kind one of approve, decline, choice, form, dismiss), the workflow_id / run_id / step_idx that raised it, created_at, read_at, and resolved_action / resolved_at once acted on (null until then). Newest first, at most 1,000 rows. ?only_unread=true keeps only rows with no read_at. List rows omit continuation_token and resolved_payload; GET /api/workflows/notifications/{id} returns the full row. No LLM involved.
Parameters
Name
In
Type
Description
only_unread
query
boolean
When true, return only notifications that have not been marked read. Default false.
Response 200
{
"ok": true,
"data": {
"notifications": [
{
"_id": "e1f2a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b",
"audience_user_id": "a9b4e239-27ff-4f38-949b-38b332b3f8ed",
"title": "Approve renewal offer for unit 4B",
"body": "Priya Sharma's lease on unit 4B at Maple Court ends on 2026-11-30. Send the standard 12-month renewal offer at $2,150/month?",
"actions": [
{
"id": "approve",
"label": "Send offer",
"kind": "approve"
},
{
"id": "decline",
"label": "Skip this tenant",
"kind": "decline"
}
],
"workflow_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"run_id": "5b2c9d4e-1a3f-4e6b-8c7d-2f1e0a9b8c7d",
"step_idx": 2,
"created_at": "2026-10-27T13:15:42.006113+00:00",
"read_at": null,
"resolved_action": null,
"resolved_at": null
},
{
"_id": "b7c6d5e4-f3a2-4b1c-9d8e-7f6a5b4c3d2e",
"audience_user_id": "a9b4e239-27ff-4f38-949b-38b332b3f8ed",
"title": "Approve renewal offer for unit 2A",
"body": "Marcus Lee's lease on unit 2A at Maple Court ends on 2026-11-18. Send the standard 12-month renewal offer at $1,875/month?",
"actions": [
{
"id": "approve",
"label": "Send offer",
"kind": "approve"
},
{
"id": "decline",
"label": "Skip this tenant",
"kind": "decline"
}
],
"workflow_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"run_id": "8e7d6c5b-4a3f-4e2d-9c1b-0a9f8e7d6c5b",
"step_idx": 2,
"created_at": "2026-10-26T13:15:39.441870+00:00",
"read_at": "2026-10-26T15:02:11.318554+00:00",
"resolved_action": "approve",
"resolved_at": "2026-10-26T15:02:11.318554+00:00"
}
]
}
}
Returns the complete notification row, including the HMAC-signed continuation_token (the same token embedded in emailed Approve/Decline links) and, once resolved, resolved_action, resolved_at and any resolved_payload submitted with the action. Fields that are not set yet (read_at, resolved_*) are omitted. Reading does not mark it read. 404 if the notification does not exist or its audience is another user. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Notification _id.
Response 200
{
"ok": true,
"data": {
"_id": "e1f2a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b",
"audience_user_id": "a9b4e239-27ff-4f38-949b-38b332b3f8ed",
"title": "Approve renewal offer for unit 4B",
"body": "Priya Sharma's lease on unit 4B at Maple Court ends on 2026-11-30. Send the standard 12-month renewal offer at $2,150/month?",
"actions": [
{
"id": "approve",
"label": "Send offer",
"kind": "approve"
},
{
"id": "decline",
"label": "Skip this tenant",
"kind": "decline"
}
],
"workflow_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"run_id": "5b2c9d4e-1a3f-4e6b-8c7d-2f1e0a9b8c7d",
"step_idx": 2,
"continuation_token": "eyJyaWQiOiI1YjJjOWQ0ZS0xYTNmLTRlNmItOGM3ZC0yZjFlMGE5YjhjN2QiLCJzaWR4IjoyLCJuaWQiOiJlMWYyYTNiNC1jNWQ2LTRlN2YtOGE5Yi0wYzFkMmUzZjRhNWIiLCJhaWQiOm51bGwsImV4cCI6MTc2MjgzMjAwMH0.Xk3v9QhP2rTq8mWb0cLzN4yF7aJd6sUe1oGiHn5pRtA",
"created_at": "2026-10-27T13:15:42.006113+00:00",
"_createdBy": "a9b4e239-27ff-4f38-949b-38b332b3f8ed"
}
}
Same handler as POST /api/workflows/notifications/{id}/read: sets read_at to now if it is not already set and returns it. Any request body is ignored; this does NOT update the notification's other fields. Idempotent: an already-read notification keeps its original read_at. 404 if the notification does not exist or its audience is another user. No LLM involved.
Hard-deletes the inbox item from _System.Notifications. The run, its step timeline and the event history are not touched. Deleting an unresolved approval does not cancel or resume the run waiting on it: that run stays parked until its wait times out or it is cancelled with POST /api/workflows/runs/{id}/cancel. 404 if the notification does not exist, was already deleted, or its audience is another user. No LLM involved.
Sets read_at to the current time if it is not already set and returns the notification id with its read_at. No request body. Idempotent: an already-read notification keeps its original read_at. Resolving a notification also marks it read. 404 if the notification does not exist or its audience is another user. No LLM involved.
Records the caller's choice on the notification (resolved_action, resolved_at, resolved_payload, and read_at if unset), then queues a manual event on _System.WorkflowEvents that wakes the run parked on it. The event exposes the decision to later plan steps as ${<save_as>.approve} / .approved, .decline / .declined, .chosen (the action id), .action_kind, and .form_payload / .payload (the optional payload from this request, e.g. form field values). Body: action_id (required; one of the notification's actions[].id) and optional payload (any JSON). The run resumes asynchronously when the router picks the event up; resumed: true means the wake event was queued, not that the resumed steps have finished. A notification can be resolved only once (409 notification already resolved). Resuming can trigger the run's remaining side effects (emails, record writes). The notification is updated before the event is queued, so a 500 from the event write leaves it marked resolved. 400 unknown action id; 404 if the notification does not exist or its audience is another user. The emailed signed link (GET /n/{id}) resolves the same way without a session. No LLM involved.
Parameters
Name
In
Type
Description
id
path
string
Notification _id.
Request
{
"action_id": "approve",
"payload": {
"note": "Offer the 12-month term at the current rent."
}
}
Hard-deletes up to 500 notifications per call (400 too many ids: N (max 500 per request) above that). Body: ids (required array of notification _ids; a body without ids is rejected). Ids that do not exist, were already deleted, or belong to another user are counted in not_found and left alone; per-id storage errors are listed in failed as {id, error} without stopping the batch. As with the single delete, runs and event history are untouched and a parked run waiting on a deleted approval stays parked. No LLM involved.
Hot backups of the whole instance, backup history, restore, and scheduled backups. Backups go to the instance's private S3 folder when a bucket is configured, otherwise to local disk. Admin or superadmin only.
Starts a hot backup of the entire instance (every namespace, records plus id-index, and property indexes unless includeIndexes is false) and returns immediately with 202 and the new backupId; poll GET /api/backup/status/{backupId} for progress. When INVENTDB_BACKUP_S3_BUCKET is configured (managed instances) each file streams straight to s3://<bucket>/<customer-prefix>/<backupId>/ with server-side encryption and nothing is staged on local disk; an _INCOMPLETE marker object sits in that folder until the run completes cleanly. Without a bucket (self-hosted/dev) the copy goes to <data_dir>/../backups/backup_<timestamp> on local disk. The destination is always server-derived: targetDirectory in the body is accepted but ignored. A JSON body is required ({} is enough). The run keeps the instance awake (it is exempt from idle-stop) and records its outcome in _system.backups with trigger "manual". Admin or superadmin required.
Request
{
"description": "Before October rent-roll import",
"includeIndexes": true
}
Returns one backup's status. While the run is live (and for about 5 seconds after it ends) the numbers come from the in-memory progress tracker: state is one of Analyzing, CopyingIdIndex, CopyingRecords, CopyingIndexes, CopyingMetadata, and targetDirectory is still the local fallback path recorded at start. After that the stored _system.backups record is returned: state Completed, Failed, Cancelled or InProgress, targetDirectory is the final location (an s3:// URI when uploaded) and typeDetails carries a per-type file and byte breakdown. filesFailed above 0 means the backup is missing live data and is not a valid restore point; filesSkipped counts files the live database deleted during the run and is harmless. phaseDetails is always zero-filled and sourceDirectory is always empty (kept for console compatibility). Returns the status object directly (not wrapped). 404 when no backup has that id. Admin or superadmin required.
Parameters
Name
In
Type
Description
backupId
path
string
Backup id returned by POST /api/backup/start or listed by GET /api/backup/list.
Signals a backup that is running in this server process to stop. The run ends in state Cancelled; anything already uploaded stays in the bucket with its _INCOMPLETE marker (so it cannot be restored) until the backup is deleted or pruned by retention. Only backups held in this process's live tracker can be cancelled: a finished backup, or one orphaned by a restart, answers 404 "No active backup found with that ID". No request body. Admin or superadmin required.
Returns { backups: [...] }, one status object per _system.backups record (same shape as GET /api/backup/status/{backupId}). A backup that is still running is overlaid with its live progress, so its counters move during the run instead of reading 0 until the end. Records are returned in storage order (the handler does not sort) and cut at limit (default 50). Manual and scheduled runs both appear; trigger says which. Admin or superadmin required.
Returns { logs: [...] }, a compact history line per _system.backups record: start/end time, duration, state, final location, description, files and bytes copied, plus errorMessage and typeDetails when the record has them. Built from stored records only (no live overlay, so a running backup shows 0 copied). Storage order, cut at limit (default 20). Admin or superadmin required.
Deletes a backup's _system.backups record and then its stored data: every S3 object under its folder (aws s3 rm --recursive) or the local backup directory. The record is removed first and the storage cleanup runs in the background after the response, so a cleanup failure is only logged. Refused with 409 while the backup is genuinely running (status in progress and started under 15 minutes ago; cancel it first); an older record stuck in progress by a crash can be deleted. 404 when no backup has that id. Cannot be undone. Admin or superadmin required.
Prepares a full restore of the instance from one backup. The live data files are open, so nothing is swapped now: the backup is downloaded from S3 (or copied from its local directory) into <data_dir>/.restore/<backupId> on the data volume, validated, and a RESTORE_PENDING.json marker is written. The response waits until staging finishes, which for a multi-GB backup can take minutes, and needs free space on the data volume about the size of the backup. The swap happens the NEXT time the server starts, before the database opens: the current data is moved aside to <data_dir>/.pre-restore-<timestamp> and the backup's files take its place, so EVERYTHING written after the backup was taken, including writes made between this call and the restart, is replaced. The previous data is kept in that aside folder for manual recovery. This endpoint does not restart the server. Refusals: 404 unknown id; 409 backup not finished; 422 when the record shows filesFailed > 0, it has no stored location, or the staged copy fails validation (_INCOMPLETE marker present, backup_manifest.json missing, failed files in the manifest, or fewer files than the manifest lists); 500 when the download fails. No request body. Admin or superadmin required.
Parameters
Name
In
Type
Description
backupId
path
string
Id of a Completed backup with filesFailed = 0.
Response 200
{
"ok": true,
"pending": true,
"message": "Restore prepared. It will be applied when the service restarts."
}
Creates a backup schedule in _system.backup_schedules. name and frequency are required. frequency is hourly, daily, weekly or monthly (case-insensitive; any other value is stored but never runs and gets nextRunTime null). timeOfDay is "HH:mm" in the schedule's IANA timezone (default "00:00"); hourly uses only the minutes. dayOfWeek is an English day name for weekly (default sunday); dayOfMonth is 1-28 for monthly (default 1, larger values clamp to 28). timezone defaults to the customer's configured timezone, else UTC. includeIndexes and isEnabled default to true. retentionDays is misnamed: it is a COUNT of backups to keep (0 or absent = 14), and after each scheduled run the scheduler deletes older finished backups beyond that count across ALL backups, manual ones and other schedules' included. targetDirectory is accepted but ignored. The scheduler polls every 60 seconds and catches up once on a run missed while the instance was down. On a managed instance the new next-run time is reported to the control plane so a sleeping instance is woken for it. Returns 201 with the stored schedule and its computed nextRunTime (UTC). Admin or superadmin required.
Returns { schedules: [...] } with every backup schedule and its computed nextRunTime (UTC; null when disabled). A new instance is seeded with one schedule, "Daily backup" at 02:00 in the customer's timezone keeping 14 backups. isRunning is always false. Admin or superadmin required.
Returns one backup schedule (same shape as an entry of GET /api/backup/schedules) with its computed nextRunTime. lastError appears only when the last scheduled run recorded one. 404 when no schedule has that id. Admin or superadmin required.
Replaces a backup schedule with the body (same fields as create; name and frequency required). It is a full replace, not a merge: omitted includeIndexes and isEnabled reset to true, and omitted optional fields are cleared. createdAt and the last run time are preserved, and the stored timezone is kept when the body omits it. Any recorded lastError is dropped. Reports the new next-run time to the control plane on a managed instance. 404 when no schedule has that id. Admin or superadmin required.
Deletes a backup schedule. Backups it already produced are kept. If this leaves the instance with no schedules at all, the default "Daily backup" schedule is re-created on the next server start. The control plane's wake-up time is not refreshed by this call (it updates after the next backup or restart). 404 when no schedule has that id. Admin or superadmin required.
Sets a schedule's isEnabled flag without touching its other fields. Body {"isEnabled": false} disables it; a missing or non-boolean isEnabled enables it. A JSON body is required. The control plane's wake-up time is not refreshed by this call. 404 when no schedule has that id. Admin or superadmin required.
Parameters
Name
In
Type
Description
id
path
string
Schedule id (scheduleId).
Request
{
"isEnabled": false
}
Response 200
{
"ok": true
}
Storage Recovery Any tier
Storage health and repair: a quick per-type integrity report (active-segment count check plus sampled CRC-verified reads) and an on-demand repair of one type's id and property indexes. Admin or superadmin only.
Checks every type in every namespace (system namespaces included) and summarises the result. Each type's active segment gets an O(1) record-count vs id-index comparison and up to ten CRC-verified sample reads; nothing is scanned or repaired. pendingRepairs and totalCorruptions are both the number of types whose status is not ok, and typesAffected lists them as "namespace.type". Also reports the on-disk format version against the version this binary expects, whether the previous process shut down cleanly, and danglingOffsetHits (reads that hit an id-index entry pointing past the records file since this process started). Admin or superadmin required.
Returns the same check as the summary for one type: status (ok, degraded, error, or unopenable), live record count, segment count, and corruptions, a one-element list with the reason when status is not ok. A namespace/type that does not exist is not a 404: it answers 200 with status "unknown" and null counts. Read-only. Admin or superadmin required.
Repairs one type in two passes, in order: rebuilds the active segment's id-index from its records (safe because deletes leave tombstones, so deleted rows are not resurrected), then verifies the active segment's property indexes against those records and rebuilds any that disagree. Sealed segments are not touched. Runs synchronously inside the request, so on a large type the call can take a while. Returns what was done: idIndexRepaired, propertyIndexesRebuilt (repairedCount mirrors it), remainingIssue (the health check's reason if a problem is still present, else null) and errors; ok is false when either pass reported an error. 404 when the type cannot be opened. No request body. Admin or superadmin required.
Schema-level operations: drop a namespace, drop a type, and apply an app's schema/role/seed bundle to a namespace. Per-feature admin lives under its own tag (`indexes`, `relationships`, etc.).
Imports a vertical app's bundle (type definitions, roles, seed records) into a namespace, idempotently per bundle_version. If bundle_version equals the version last applied to this namespace (kept in _system.bundle_versions) nothing changes and applied is false. Otherwise: (1) types: each type's fields and indexes are stored as descriptive metadata in _system.bundle_schema as <namespace>.<type>; no schema is enforced, no records are created and no indexes are built, so types_added only means the type did not exist yet. (2) roles: the bundle owns roles under the prefix taken from bundle_version up to its first '-' or '.' (pms-2026.10.27-1 gives pms); each bundle role is written whole, bundle-owned roles the new bundle no longer lists are DELETED (shown in roles_replaced as "<name> (removed)"), and a role with the same name created by an admin is skipped with a warning. Grant scope must be namespace or type and accessLevel read, write, delete or admin; role rowFilter is validated. (3) seed_data: each entry's type is "Namespace.Type" and may name any namespace; a record needs _id, is inserted when absent, replaced when its integer version is higher than the stored one, otherwise skipped. Per-item failures are reported in warnings, not as an error status. Namespaces starting with '_' are refused (400). Admin or superadmin (or a system_app OAuth token, which carries the admin role) required.
Parameters
Name
In
Type
Description
namespace
path
string
Target namespace, e.g. pms. Must not start with '_'.
Exchange a username and password for a signed JWT at POST /api/auth/login, then send it as Authorization: Bearer <token> on every protected request. get_current_user resolves the caller's identity and role, globally or per app.
Can I run raw SQL over HTTP?
Yes. InventDB exposes full SQL over the HTTP API alongside record CRUD, pre-built queries and bulk operations, so you can pick whichever surface fits. You are not restricted to a REST-shaped abstraction over your own data.
How many MCP tools does InventDB expose?
51, on both InventDB SOAR and InventDB Serverless. An external agent (Claude Desktop, Cursor or your own) connects over the built-in MCP server and drives the database directly. tools/list is not filtered by product, tier or role, so every client sees the same 51 tools; see MCP for the full reference. Report rendering and workflow authoring need no LLM, so they work identically on both; only a workflow step that calls an LLM fails on InventDB Serverless, and it fails when the run reaches it rather than when the tool is called.
Does the API enforce row-level security?
Yes. Every call, over REST, SQL or MCP alike, is bounded by the calling principal's role and row-level rules. An agent acting for a user can never read past what that user is allowed to see.
How do I get notified when data changes?
Through outbound webhooks, the change-signal group in this reference, which post to your endpoint as records change. Workflows can also call out directly, and can park and wait for a human for up to 14 days.
What else does the API cover?
Vector embeddings and per-property vectors, indexes, relationships, attachments with OCR, transactions, saved views, forms, reports, users and permissions, an OpenAI-compatible LLM endpoint, and Gmail, Calendar, Twilio and web-search integrations, each documented above with working examples.