TypeScript & JavaScript
@nicia-ai/client@0.2.0 is pure ESM with zero runtime dependencies. It runs on
Node.js 22 and later, Bun, Deno, and Cloudflare Workers. TypeScript picks up the
included OpenAPI-generated types.
Install
Section titled “Install”npm install @nicia-ai/clientFor plain JavaScript, use the same imports in an .mjs file and run it
with node example.mjs. The examples below use JavaScript and need no build
step or type annotations. In TypeScript, use the same code in an ESM module.
Provision a space and scope access
Section titled “Provision a space and scope access”Use NiciaOrgClient in your provisioning backend with an organization key
(nsk_…). putSpace creates or updates a stable handle, the address used
under /v1/brains/{handle} in the HTTP API. mintSpaceKey returns a scoped
key (nbk_…). Keep the organization key in your backend and store the new
secret when you receive it. Replaying a mint with the same idempotency key
returns the existing record with a null secret.
import { NiciaOrgClient, NiciaSpaceClient } from "@nicia-ai/client";
const baseUrl = "https://api.nicia.ai";const handle = "tenant:acme";const managementKey = process.env.NICIA_MANAGEMENT_KEY;if (!managementKey) throw new Error("Set NICIA_MANAGEMENT_KEY first.");
const org = new NiciaOrgClient({ baseUrl, managementKey });await org.putSpace(handle, { name: "Acme" });
const { secret } = await org.mintSpaceKey(handle, { name: "Knowledge pipeline", capabilities: ["read", "write"],});if (!secret) throw new Error("Load the existing space key from your secret store.");
const space = new NiciaSpaceClient({ baseUrl, handle, spaceKey: secret });spaceKey accepts either an nbk_ space key or an nsk_ organization key.
Use a space key with only read for a deployed reader. See
Authentication.
Write a document and cite it in a record
Section titled “Write a document and cite it in a record”Keep a stable document ID so later uploads update the same address. Wait for
indexed before citing the exact passage in a record. The default
nicia-base schema includes the rule kind.
const documentId = "renewal-policy";const policy = "Acme renewals require finance approval before a quote goes out.";await space.writeDocuments({ id: documentId, text: policy });
for (let attempt = 0; ; attempt++) { const { document } = await space.getDocument(documentId); if (document.status === "indexed") break; if (attempt === 9 || document.status === "rejected") { throw new Error(`Document status: ${document.status}`); } await new Promise((resolve) => setTimeout(resolve, 1000));}
const recordId = "acme-renewal-approval";await space.mergeRecord(recordId, { kind: "rule", label: "Get finance approval before quoting an Acme renewal", fields: { status: "active", body: policy }, evidence: [{ document: { id: documentId }, quote: policy }],});The space’s admission policy determines whether the record is accepted or staged for Review. See Records.
Read context and check its receipt
Section titled “Read context and check its receipt”Save the receipt alongside your agent’s answer so you can check what changed since Nicia served that read.
const { text, citations, receipt } = await space.getContext({ prompt: "Who needs to approve an Acme renewal quote?",});console.log({ text, citations, receipt });
const { changed } = await space.getReceiptChanges(receipt);console.log(changed);getContext calls /context. getReceiptChanges is the SDK method for
GET /v1/brains/{handle}/receipts/{receiptId}/now. Use the key that
made the read or a key with admin to access the receipt. See
Context and Receipts.
Update a record with If-Match
Section titled “Update a record with If-Match”Once the record is accepted, pass its opaque token as ifMatch. The SDK formats it as an
If-Match header. If the record changed since your read, the request fails
with 409 conflict. Read the record again and reconcile before retrying.
const { record } = await space.getRecord(recordId);await space.mergeRecord(recordId, { label: "Finance approval for renewal quotes" }, { ifMatch: record.token });See record concurrency for conditional create and batch writes.
Paginate results
Section titled “Paginate results”iterateDocuments yields individual documents and fetches each page as needed.
For other list calls, withPageCursor adds the next cursor to your query and
collect gathers the mapped items into one array. Pass maxPages to bound
the number of requests.
import { collect, withPageCursor } from "@nicia-ai/client";
for await (const document of space.iterateDocuments({ limit: 100 })) { console.log(document.id);}
const spaces = await collect( async (cursor) => { const { spaces, nextCursor } = await org.listSpaces(withPageCursor({ limit: 100 }, cursor)); return { items: spaces, nextCursor }; }, { maxPages: 5 },);console.log(spaces.map((entry) => entry.handle));Export a space
Section titled “Export a space”An export starts a background job. Poll with the same key that started it.
waitForExport returns the job when it completes or fails, and throws
NiciaJobTimeoutError if the polling window ends first. Keep the job ID to
resume polling after a timeout. downloadExport returns a ZIP as a
Response. This Node.js example streams its body to a file.
import { createWriteStream } from "node:fs";import { pipeline } from "node:stream/promises";
import { NiciaJobTimeoutError } from "@nicia-ai/client";
const { export: job } = await space.startExport({ idempotencyKey: "acme-export-v1" });try { const { export: finished } = await space.waitForExport(job.id, { intervalMs: 2_000, timeoutMs: 60_000, }); if (finished.status === "failed") throw new Error(finished.error ?? "Export failed"); const archive = await space.downloadExport(job.id); if (!archive.body) throw new Error("Export response had no body"); await pipeline(archive.body, createWriteStream("acme-export.zip"));} catch (error) { if (error instanceof NiciaJobTimeoutError) { console.error("Resume polling", job.id, error.lastStatus); } throw error;}Branches and proposals
Section titled “Branches and proposals”A branch keeps edits separate from main. The example creates a branch after the cited rule has been accepted. Compare the branch, then open a proposal to bring the delta into the main space’s Review workflow.
const { branch } = await space.createBranch( {}, { idempotencyKey: "acme-renewal-draft-v1", },);await space.writeBranchRecords( branch.branchId, { nodes: [ { kind: "rule", id: recordId, properties: { slug: recordId, label: "Finance approval for renewal quotes", status: "active", body: "Finance approves the renewal quote.", }, }, ], }, { idempotencyKey: "acme-renewal-branch-write-v1" },);const comparison = await space.compareBranch(branch.branchId);console.log(comparison);await space.createProposal({ source: { kind: "branch", branchId: branch.branchId }, intent: "Clarify who approves renewal quotes",});Handle errors and retries
Section titled “Handle errors and retries”Use isNiciaApiError to narrow an error to NiciaApiError and read its
kind, status, requestId, operationId, retryable, and attempts.
Keep the request ID for troubleshooting. The SPACE_OPERATIONS manifest
lists each operation’s authorization, required capabilities, and stability.
import { isNiciaApiError, SPACE_OPERATIONS } from "@nicia-ai/client";
console.log(SPACE_OPERATIONS.createSpaceWebhook.stability); // "preview"
try { await space.getRecord(recordId);} catch (error) { if (isNiciaApiError(error)) { console.error(error.kind, error.status, error.requestId); } throw error;}The client honors Retry-After and retries eligible failures on GETs and
requests carrying an idempotency key. For operations with replay protection,
store one idempotencyKey per logical write and reuse it for retries. See
Errors and Idempotency.