Skip to content

@nlqdb/sdk

Class Description
NlqdbApiError Thrown on every failure path (non-2xx, transport, abort, non-JSON proxy body). Branch on err.code — the stable contract is code / httpStatus / body. Treat err.message as debug text only: its format varies by path (e.g. "nlqdb: /v1/ask → 429 rate_limited" vs "nlqdb: /v1/ask network error"), so a surface that renders it verbatim gets unstable copy — render body.message / a code-derived CTA instead (GLOBAL-012). httpStatus === 0 signals a transport-level failure (network / abort) — no response was received.
Type Alias Description
ApiErrorBody JSON body the API returns on every non-2xx response; surfaced as NlqdbApiError.body. code / message / action / retryable are rendered server-side from the @nlqdb/errors registry (SK-ERR-001) so a surface renders them verbatim instead of keeping its own copy table; params carries the code’s declared, secret-free cause fields.
ApiErrorCode The wire’s error.code values. Kept literal-for-literal in step with the @nlqdb/errors registry (SK-ERR-001) — a compile-time guard in packages/errors/test/sdk-parity.test.ts fails the build if either side gains a code the other lacks. Still open-ended via (string & {}) so a newer API than the installed SDK doesn’t break consumer compiles.
AskCreateResult SK-HDC-001 / SK-ASK-009: when kind=create (or 0 DBs with kind= query
AskDiff Plain-English preview of a destructive plan. Values are derived server-side (validator + EXPLAIN) — surfaces never compute a “this will affect N rows” themselves; that would be a silent-lie risk under GLOBAL-011.
AskOk Success envelope from /v1/ask — the query/write branch of AskResponse, carrying rows + trace.
AskRequest Request body for client.ask() / askStream() — the plain-English goal plus optional routing hints.
AskResponse Discriminator: AskOk carries status: "ok", AskCreateResult carries kind: "create". Callers narrow on whichever fits.
AskStreamOptions Second arg to askStream() — abort signal plus the per-step trace listener that feeds live UIs.
ByollmCredential SK-SDK-010 — the caller’s own provider key, dispatched at 0% markup per GLOBAL-026. Server-side this is the <provider>:<model>:<key> header (SK-LLM-021); the SDK takes the parts separately so the colon-joining (and its escaping hazards) live in one tested place. The key never leaves the caller’s process except in the request to /v1/ask, and only when this is set.
ByollmProvider BYOLLM (SK-PREMIUM-008) provider slugs the API accepts on the x-nlq-byollm-key lane — the AI Gateway compat-endpoint providers (SK-LLM-021, verified 2026-05). OpenRouter is listed in SK-PREMIUM-008 but not yet on the compat endpoint, so it is not here. Open-ended so a new slug doesn’t force an SDK bump to compile; the trade-off is that an unrecognised slug surfaces as the server’s one-sentence 400, not at construction — the SDK validates shape, not the evolving provider allowlist it would otherwise have to track.
ByollmSetResult setByollm() echo — provider/model/last4 only; never the key.
ByollmStatusResponse getByollmStatus() result. { configured: false } is the empty “add your key” state — distinct from a thrown error (a 503 byollm_unavailable means the deployment can’t store keys at all).
ByollmStoredCredential SK-SDK-011 — account-stored BYOLLM credential, the persistent counterpart to the per-request byollm option (SK-SDK-010). The option attaches a key to each ask() over x-nlq-byollm-key; these verbs persist one credential server-side (sealed at rest per GLOBAL-031) so every later session dispatches through it without re-sending the key. One credential per account; setByollm upserts. The key is write-only — it is never returned by any verb (last4 is the sole display affordance, SK-APIKEYS-002).
CandidateDb SK-ASK-009: candidate-DB ranking carried on ambiguous_db 409 envelopes. Surface uses these to render an explicit picker.
CatalogModelOption -
CatalogPreset -
CatalogProvider -
ChatAssistantError Error branch of ChatAssistantResult — a persisted assistant turn whose API call failed.
ChatAssistantResult Persisted outcome of one chat turn; surfaces narrow on kind to render success rows vs an error chip.
ChatAssistantSuccess Mirrors apps/api/src/chat/types.ts. Keep these definitions in sync when the API’s wire shape changes — truncated and kind are not optional, callers narrow off result.kind.
ChatMessage One persisted chat turn; the role discriminant narrows to a user prompt vs an assistant result.
ClarifyOption SK-ASK-026: one re-sendable interpretation offered on a destructive_ambiguous clarify (the “clear db” family). Re-send goal (dropping any pinned dbId when forceNoPin) exactly as you’d send a fresh ask — no special endpoint. Surfaces render these as chips (web) / numbered choices (CLI) / structured options (MCP).
ClearByollmResult clearByollm() result. Idempotent: cleared: false when there was nothing stored, so retrying scripts don’t have to special-case it.
ClientOptions Argument to createClient(); the union picks one auth mode at compile time so a server bearer cannot ride a browser cookie.
ConnectDatabaseRequest SK-DBCONN-001 — body for client.databases.connect(). Connect a bring-your-own Postgres / ClickHouse: the server seals the connection_url (GLOBAL-031), introspects the schema, and returns a live, queryable DB. connectionUrl is the same trust class as a BYOLLM key — HTTPS-only, sent ONLY in the request body, never logged.
ConnectDatabaseResult SK-DBCONN-001 — response from client.databases.connect(). pkLive is the freshly-minted publishable per-DB key; schemaPreview is the rendered schema text the surface shows as the connect confirmation.
CreateDatabaseRequest Body for client.createDatabase() — goal-first (goal drives the engine classifier) with an optional explicit engine override.
CreateDatabaseResult Response from client.createDatabase() — surfaces the new dbId, the resolved engine, and the publishable per-DB key.
DatabaseSummary One DB row in a listDatabases response. pkLive is the publishable per-DB key used to inline into <nlq-data> snippets (SK-WEB-007); when null the surface falls back to the anonymous device’s pk_live (SK-ANON-006).
Engine SK-DB-010 — engine the create path resolved (classifier-default or explicit override). Surfaces echo it back to the caller; the CLI renders it after nlq new, the chat surface stores it on the rail row, the MCP tool returns it per row from nlqdb_list_databases.
FetchLike Minimal fetch shape — just the call signature, not the runtime- specific static methods (Bun’s typeof globalThis.fetch requires a preconnect method that test stubs shouldn’t have to provide).
GrantMintResult mintGrant() result — the minted grant, always active. priceModel is echoed only when set.
GrantRecord One row in listGrants() — both sides of the marketplace in one list: grants the caller sold (role: "owner") and grants it holds (role: "grantee"). revokedAt is non-null on revoked rows; active rows sort before revoked (one contiguous slice per section, same contract as the keys list).
KeyRecord SK-APIKEYS-010 — one row in listKeys(). Plaintext is never present (SK-APIKEYS-002); last4 is the only display affordance. Per-type claim fields are nullable: dbId is populated for pk_live, (mcpHost, deviceId) for sk_mcp, name is the optional human label for sk_live. revokedAt is non-null on revoked rows — surfaces group active + revoked from the same slice.
KeyStatus SK-MCP-014 — DO revalidation probe. apps/mcp/’s McpAgent caches the resolved sk_mcp_* key for 1 s and refreshes via this method. Server-side endpoint is GET /v1/keys/:hash/status — session-only, scoped to the key owner’s tenant.
KeyType SK-APIKEYS-001 — three key types. The wire-level discriminant on KeyRecord. Open-ended so a new type added server-side doesn’t force an SDK bump to compile.
MintGrantRequest SK-EKP-008 — the cross-tenant read-grant control plane (EK-06). A grant lets the owner sell a grantee read-only query access to one named hosted knowledge DB — revocable, fail-closed, per-query metered. These verbs are session-only, the same threat model as the key verbs: a leaked sk_live_ must never open one tenant’s data to another, so they ride a first-party cookie (withCredentials: true), never a bearer. Enforcement of the grant on the buyer’s /v1/ask (scope, role, metering) is EK-06 box 2, server-side. POST /v1/grants mint request. scope enumerates the bare table names the grantee may read and is authoritative — schema widening never widens it. priceModel is an opaque tag the private selling surface (SK-EKP-003) writes and interprets; the public core never reads it and no fee logic, fee %, or Stripe call lives here (SK-EKP-002).
MintKeyRequest SK-APIKEYS-007 — POST /v1/keys mint. sk_live carries an optional human name; sk_mcp carries (host, device) claims per SK-APIKEYS-004. The plaintext lands here exactly once (SK-APIKEYS-002) — surfaces must copy on the same render or it is gone for good.
MintKeyResult Response from client.mintKey() — the plaintext key is present here exactly once (SK-APIKEYS-002).
ModelCatalog -
ModelPreset SK-PREMIUM-013 / SK-PREMIUM-015 — the model catalog served by GET /v1/models. Shape only: the actual model strings live in @nlqdb/llm (built live from models.dev) and arrive over the wire, so no surface (this SDK included) hardcodes them (SK-PREMIUM-003). presets is the goal-first `auto
NlqClient The typed client returned by createClient — the only HTTP surface per GLOBAL-001. Every method throws NlqdbApiError on every failure path; discriminate on err.code (SK-SDK-002). Recoverable failures (transport, transient 5xx) retry up to 3× automatically (SK-SDK-008); a 401 on a withCredentials client refreshes and retries silently (SK-SDK-005), so surfaces never see one. Mutations auto-generate and reuse an Idempotency-Key across retries (SK-SDK-006).
OAuthBridgeRedemption SK-MCP-013 — cross-Worker bridge. apps/mcp/’s bridgeHandler redeems the one-shot code minted by apps/api/’s POST /v1/oauth/mcp-callback. The code itself is the auth proof (128-bit random, 60 s TTL, delete-on-read).
PinnedDb SK-ASK-014: surfaced on clarify_required 409 envelopes — the DB the caller had pinned when the classifier decided kind=create. Null when the pinned id couldn’t be resolved (stale URL param).
PremiumInterestResult registerPremiumInterest() result — a constant ack; the interest is recorded server-side (founder notification), nothing to render beyond a “you’re counted” state.
RememberEntityPayload -
RememberEpisodePayload -
RememberFactPayload E-02 — the agent-memory write verb. client.remember() materialises a typed row into an agent_memory_v1 preset DB (no LLM in the loop). The MCP nlqdb_remember tool and nlq remember (fast-follow) wrap this.
RememberRequest -
RememberResult Response from client.remember() — the materialised row’s identity.
RevokeGrantResult DELETE /v1/grants/:id response. Idempotent: a re-DELETE on an already-revoked grant returns alreadyRevoked: true rather than 404, so retrying scripts don’t special-case it. 404 (grant_not_found) fires only on an unknown / not-yours id — no cross-tenant existence leak.
RevokeKeyResult SK-APIKEYS-011 — DELETE response. Idempotent: a re-DELETE on an already-revoked key returns alreadyRevoked: true rather than 404, so caller scripts that retry don’t have to special-case “is the 404 because someone else got there first?”. 404 only fires on “key id is unknown / not yours” (key_not_found).
RunSqlRequest SK-SDK-009 — raw-SQL escape hatch (GLOBAL-015); same allow-list as ask(), DDL still rejected.
RunSqlResult Response from client.runSql() — same row/trace shape as AskOk minus the NL summary.
SelectedDbEcho SK-ASK-009: response echo when the API auto-targeted a DB on the caller’s behalf (single-DB auto-target OR LLM disambiguator pick ≥ 0.7 confidence). Surfaces render attribution + a one-click switch.
Trace SK-TRUST-002 — every successful /v1/ask response carries this block. The compiled SQL + cache state live here, not at the top level. Surfaces render it as an always-present (collapsed by default) trace pane.
TraceEvent One event from the askStream() trace channel; surfaces narrow on type to drive the live trace pane.
TraceStep Per-step trace event, mirrors the API’s OrchestrateEvent set extended with a confirm_required step for the destructive gate. Surfaces wire onTrace into the live trace UI; SK-SDK-007 is the canonical contract for this shape.
Function Description
createClient Build the typed NlqClient — the only entrypoint consumers call directly, and the only HTTP surface per GLOBAL-001. Pick exactly one auth mode at construction (SK-SDK-001): { apiKey } for a server-side bearer (never ship to a browser bundle — it leaks) or { withCredentials: true } for a browser cookie session; passing both throws. Omitting both leaves calls anonymous. The session-only verbs (setByollm / getByollmStatus / clearByollm) and the byollm option require withCredentials: true and throw otherwise (SK-SDK-010 / SK-SDK-011). Optional baseUrl and a custom fetch round out the options.