# ContextBase TypeScript SDK

The TypeScript client for ContextBase, a platform for retrieval-augmented
generation over your own documents.

Install the release candidate from [npm](https://www.npmjs.com/package/contextbase-sdk).

```bash
npm install contextbase-sdk@next
```

Node 18 or newer, or any browser with `fetch`. The package ships ES modules,
CommonJS and its own type declarations, and depends on nothing.

## Quick start

A key is minted by a person in the web interface (or through
`POST /api/v1/auth/api-keys/`). A key that creates a space is granted `manage`
on it, so one key is enough for everything below. Set the key and the server's
address, then run this as it stands, as an ES module (`quick-start.mjs`):

```bash
export CONTEXTBASE_API_KEY=cb_...
export CONTEXTBASE_BASE_URL=https://contextbase.example.com
```

<!-- quick-start: scripts/smoke-live.mjs runs this block as is -->
```js
import { ContextBase } from "contextbase-sdk";

const client = new ContextBase();
await client.checkCompatibility();

const space = await client.spaces.create("Quick start", {
  llm_config: { model: "openai/gpt-4o" },
});
try {
  const facts = new Blob(["The capital of France is Paris."], { type: "text/plain" });
  const document = await space.documents.upload(facts, { filename: "facts.txt" });
  await space.documents.waitIndexed([document], { timeout: 120_000 });

  const answer = await space.query("What is the capital of France?");
  console.log("answer:", answer.answer);
  console.log("sources:", answer.sources.map((source) => source.text));

  for await (const event of space.queryStream("What is the capital of France?")) {
    if (event.type === "token") {
      process.stdout.write(event.delta);
    } else if (event.type === "done") {
      console.log("\nstreamed:", event.answer.sources.length, "sources");
    } else if (event.type === "error") {
      console.log("\nstream failed:", event.detail);
    }
  }

  for (const source of await space.search("capital", { top_k: 3 })) {
    console.log("found:", source.text);
  }
} finally {
  await space.delete();
}
```

Listings are async iterables that fetch the next page only when it is read:

```js
import { ContextBase } from "contextbase-sdk";

const client = new ContextBase();
for await (const space of client.spaces.list()) {
  console.log(space.id, space.name);
}
```

In a browser, pass the key and the address, since there is no environment to
read them from: `new ContextBase({ apiKey, baseUrl })`. A key in a browser is
visible to whoever uses the page; hand one out only with the grants that page
needs.

### Configuring a space and evaluating it

These need a key granted `manage` on the space; a key that created the space
has it. A key granted less is refused with `PermissionDeniedError`.

<!-- configure-and-evaluate: scripts/smoke-live.mjs runs this block as is -->
```js
import { ContextBase } from "contextbase-sdk";

const client = new ContextBase();
console.log("presets:", (await client.pipeline.presets()).map((preset) => preset.id));
const space = await client.spaces.create("Evaluated", {
  llm_config: { model: "openai/gpt-4o" },
});
try {
  const facts = new Blob(["The capital of France is Paris."], { type: "text/plain" });
  await space.documents.upload(facts, { filename: "facts.txt" });
  const hybrid = {
    ...(await space.config.get()),
    retrievers: [{ node: "bm25" }, { node: "dense" }],
    fusion: { node: "rrf" },
  };
  const report = await space.config.validate(hybrid);
  console.log("preflight:", report.status);

  const change = await space.config.apply(hybrid, {
    startTimeout: 60_000,
    timeout: 180_000,
    onProgress: (status) =>
      console.log(
        "rebuild:",
        status.representations.map((index) => `${index.kind} ${index.status}`).join(", "),
      ),
  });
  console.log("applied:", change.result.scope, "stale:", change.stale);

  const dataset = await client.evalDatasets.create({
    name: "Capitals",
    corpus: [{ id: "fr", text: "The capital of France is Paris." }],
    queries: [{ question: "What is the capital of France?", relevant_ids: ["fr"] }],
  });
  const run = await space.evaluations.run(dataset, {
    timeout: 240_000,
    onProgress: (run) => console.log("run:", run.status, run.progress.stage),
  });
  console.log("metrics:", JSON.stringify(run.metrics));
  for await (const outcome of space.evaluations.queries(run)) {
    console.log(outcome.position, outcome.question, outcome.answer);
  }
} finally {
  await space.delete();
}
```

`config.apply` and `config.reindex` wait for the rebuild they start, unless
`wait: false`: first for it to begin (`startTimeout`, a minute, else
`RebuildNotStartedError` -- no worker took it up), then for it to end
(`timeout`, half an hour, else `RebuildTimeoutError` with the last status).
An index left out of date with no worker on it is not waited for; it is named
in `change.stale`, and a `reindex` rebuilds it. A pass over storage this
platform did not make is reported as `change.storagePass` and runs on its own.
A configuration its preflight checks refuse throws `PreflightConflictError`
(409, a `ConflictError`) or `PreflightUnprocessableError` (422, an
`UnprocessableEntityError`), each carrying their `report`;
`isPreflightBlocked(error)` tells either apart from any other refusal. `evaluations.run` waits for the
run: a failed one throws `EvaluationFailedError` with the server's reason, one
still going at `timeout` throws `EvaluationTimeoutError` naming its stage and
how far it got. Both timeouts derive from `WaitTimeoutError`, as does
`IndexingTimeoutError` from `documents.waitIndexed` and `RebuildNotStartedError`. A dataset kept in a JSON
file of the same shape is `client.evalDatasets.create(JSON.parse(text))`.

Anything else the server offers -- the knowledge graph, a space's metadata
schema, its storage index, the chunk map, the agent graph -- is reached through
the generated operations, handed the client's `raw`:

```ts
import { ContextBase, operations } from "contextbase-sdk";

const client = new ContextBase();
const { data } = await operations.getGraphStatus({
  client: client.raw,
  path: { space_id: "..." },
});
```

### Typed inputs

Every payload the server defines is exported as a type under `types`, and
every call takes the server's own shape, with the server's field names. An
editor completes a filter or a configuration field by field:

```ts
import { ContextBase, type types } from "contextbase-sdk";

const supportOnly: types.MetadataFilter = {
  join: "all",
  conditions: [{ field: "team", operator: "eq", value: "support" }],
};

const client = new ContextBase();
const space = await client.spaces.get("...");
console.log((await space.search("refunds", { metadata_filter: supportOnly })).length);
```

One rule decides the spelling: a field the server defines keeps the server's
snake_case (`top_k`, `chunk_count`, `failure_reason`), so it reads the same here
as in the API reference; a name the client itself adds -- the options it takes
(`apiKey`, `startTimeout`, `onProgress`) and the fields it works out
(`document.indexed`, `change.stale`, `change.storagePass`) -- is camelCase.

### What the client does for you

- **Keys and addresses.** `new ContextBase({ apiKey, baseUrl })`, or
  `CONTEXTBASE_API_KEY` / `CONTEXTBASE_BASE_URL` where there is an environment.
  Without a key only `meta()` and `checkCompatibility()` work; everything else
  throws `MissingAPIKeyError` before sending anything.
- **Timeouts.** 60 seconds a request unless `timeout` (in milliseconds) says
  otherwise. A streamed answer is held to it only while connecting. Every wait
  (`waitIndexed`, `apply`, `run`) takes `timeout` and `interval` in
  milliseconds too.
- **Repeats.** A `GET`, `PUT` or `DELETE` the server answers with 429 or 503 is
  asked again, up to `maxRetries: 2` times, waiting as `Retry-After` asks or
  doubling from half a second. A question (`POST`) is never asked twice.
- **Listings.** `client.spaces.list()`, `space.documents.list()` and the
  evaluation listings walk every page, fetching the next only when it is read;
  leaving the loop early stops the listing.
- **Streams.** `space.queryStream()` yields `stage`, `check`, `token`, and then
  `done` or `error` events, told apart by `type`. Stage and check events preserve
  `attempt_id`; check events also identify `node_id`, phase, verdict and action.
  Leaving the loop early closes the connection. A refusal before the answer
  starts is thrown like any other.
- **Publication.** `answer.outcome` is `accepted` or `blocked`, for buffered
  queries and `done.answer` alike. Check it before treating an empty answer as
  success. `query_id` locates the authorized inspection record. `postgeneration`
  carries the server's redacted execution summary; rejected drafts and judge
  explanations remain behind the server's content-access controls. Old servers
  that omit these fields default to `accepted`, `null` and `null`.
- **Errors.** What the server or the connection causes derives from
  `ContextBaseError`; arguments no request can be made from (no address, bytes
  with no filename) throw `TypeError`. An error status is an `APIError` of its
  own class -- `AuthenticationError` (401), `PermissionDeniedError` (403),
  `NotFoundError` (404), `ConflictError` (409), `PayloadTooLargeError` (413),
  `RateLimitError` (429), `ServerError` (5xx) and the rest -- carrying `status`,
  `detail` (the server's sentences), `reason` (its machine name for the
  refusal) and `names`. A 404 for a path the server has no route for is an
  `UnknownEndpointError`, whose message suggests the server is older than this
  client. A configuration refused by the preflight checks is a
  `PreflightConflictError` or `PreflightUnprocessableError` -- still a
  `ConflictError` or an `UnprocessableEntityError` -- with the checks' `report`.
  Not reaching the server, or not hearing back in time, is an
  `APIConnectionError`.
- **Compatibility.** `client.checkCompatibility()` throws
  `IncompatibleServerError` for a server older than `MINIMUM_SERVER_VERSION` or
  speaking another API version. The server numbers its releases the Python way
  (PEP 440), and the client compares them that way.
- **Escape hatch.** `client.raw` is the generated client underneath, sharing
  the client's address, key, timeout and repeats, for an operation the client
  does not cover. Without a key there is no authenticated client to hand over,
  and asking for it throws `MissingAPIKeyError`. It reads each answer whole, so
  a stream is read through `queryStream` rather than through it.
- **Your own `fetch`.** `new ContextBase({ fetch })` sends through the `fetch`
  given -- a proxying one, or one a test stands in with.
- **Changing a space's settings** is left to a person: the server refuses it
  to every key, so the client has no call for it. The generated operation is
  `operations.updateSpace`, through `client.raw`.

## Developing the SDK

Everything below runs from `sdk/typescript/` and goes through one entry point,
`scripts/sdk.mjs`, also reachable as the npm scripts of the same names. The SDK
has its own `package.json` and lock, and shares nothing with the web app's.
Development needs Node 22; the package itself runs on 18 and newer.

```bash
npm ci                          # install from package-lock.json
npm run gen                     # regenerate the core from the snapshot
npm run check-stale             # refuse a committed core that is out of date
npm run lint                    # Biome and the TypeScript compiler
npm test                        # the unit suite, 100 % coverage
npm run build                   # ESM, CommonJS and declarations into dist/
npm run smoke-package           # pack, install into a fresh project, call meta()
npm run bump-check              # refuse a version that understates a breaking change
npm run verify                  # check-stale, lint and test: what the repository's gate runs
npm run release -- --dry-run    # see below
```

### What is written and what is generated

- `src/generated/` is generated by
  [@hey-api/openapi-ts](https://heyapi.dev) from `openapi/openapi.json` at the
  repository root, the same snapshot the web client and the Python SDK are
  generated from. Never edit it by hand. The generator is pinned exactly in
  `package.json`; its configuration is `openapi-ts.config.ts`, kept apart from
  the web app's, which wants the Next.js client and query hooks a library does
  not.
- Everything else under `src/` is written by hand.

The generated core is committed. `check-stale` refuses a package whose core is
not what a regeneration writes; how it compares is described at
`commandCheckStale` in `scripts/commands.mjs`. When the server's API changes,
the refusal of `scripts/check_openapi_snapshot.py` at the repository root says
how to refresh the snapshot, and `npm run gen` here follows it.

### oasdiff

`bump-check` judges schema changes with
[oasdiff](https://github.com/oasdiff/oasdiff), and only with release 1.32.1:
another release may classify a change differently, so the command refuses any
other. Install it with `brew install oasdiff` (while Homebrew ships 1.32.1) or
`go install github.com/oasdiff/oasdiff@v1.32.1`.

### Versions and releases

The SDK is versioned on its own, by SemVer. The version the next release will
carry is `version` in `package.json`; a release is the commit tagged
`sdk-ts/v<that version>`. The package's name is the `name` field there and
nowhere else; the install line above is held to it by a test.

`bump-check` compares `openapi/openapi.json` with the snapshot committed at the
newest final release tag older than the current version (pre-releases promise
nothing, so they are passed over). If oasdiff reports a breaking change, the
version must raise the major number -- before 1.0, the minor. With no earlier
final release there is nothing to compare, and any version passes.

`release` runs, in order and stopping at the first refusal:

1. the tag at `HEAD` (or the one named by `--tag`) points at `HEAD` and names
   the version in `package.json`;
2. `sdk/typescript/` and `openapi/` hold no change `git status` reports, since
   the build and `bump-check` read the working tree and the release is `HEAD`;
3. `bump-check`;
4. `test`;
5. `build`;
6. `npm publish --tag next --access public`.

Every release goes out under the dist-tag `next` until the package's name is
settled, so installing the bare name never picks one up. The token is read
from `NODE_AUTH_TOKEN`, and a release without one is refused before anything
runs. `--dry-run` runs every step with npm's own dry run as the last: npm packs
the package and reports what it would upload, and uploads nothing.

```bash
NODE_AUTH_TOKEN=npm_... npm run release
npm run release -- --dry-run
```

Record every release in `CHANGELOG.md`.

### On a live server

`scripts/smoke-live.mjs` runs the two marked blocks above, unchanged, against
the server `CONTEXTBASE_BASE_URL` names with the key `CONTEXTBASE_API_KEY`
holds, importing the package as a user would. Build first; it runs `dist/`.

```bash
npm run build
CONTEXTBASE_BASE_URL=http://localhost:8000 CONTEXTBASE_API_KEY=cb_... node scripts/smoke-live.mjs
```

### Supported Node versions

18 and newer. The suite runs under the Node `.nvmrc` names; the oldest is
checked by installing the packed package under it:

```bash
npm run smoke-package -- --node /path/to/node18/bin/node
```

## Licence

Apache License 2.0; see `LICENSE`.

### Canonical extraction volume

`Document.extracted_char_count` is the server's exact Unicode codepoint count
of canonical extracted text, including whitespace before chunking. It is
independent of the original byte `size`, chunk overlap, and indexing status.
A confirmed empty extraction has `0`; unknown legacy extraction has `null`.
An older server may omit the field; TypeScript then returns `undefined`,
preserving it separately from `null`.
Neither unknown nor absent values should be treated as zero. The field is
server-owned: owner metadata with the same key does not change it.

A search or query source exposes `document_id` independently of `locator`.
It is the canonical document UUID when the server verified the returned leaf
text against its Space-scoped canonical chunk. Missing offsets do not prevent
known identity, and known identity does not manufacture a locator, page or
section. Unknown provenance remains null (older servers may omit the field).
Do not parse document identity from source `id`, metadata or text. Parent text
and graph context remain separate evidence; this UUID identifies the leaf.

Sources optionally carry `bibliography` and `parent_bibliography`, independently
of a verified `locator`. `title` comes from the canonical contextual document
title; `author`, `year` and `url` are document-owner metadata, not
extractor-verified facts or model attributions:

```ts
import type { Answer } from "contextbase-sdk";

function showBibliography(answer: Answer): void {
  for (const source of answer.sources) {
    const citation = source.bibliography;
    if (citation) {
      console.log(citation.title, citation.author, citation.year, citation.url);
    }
  }
}
```

The URL is an owner-supplied bibliographic display reference. Syntax checks
cannot guarantee public access or absence of secrets in its contents, and known
original/media routes are recognised only on configured backend/storage origins.
Authenticated originals remain on the existing document download API;
bibliography does not grant file access. Older responses may omit these fields
and a response can explicitly return `null`; arbitrary metadata is not copied.

## Tracking document deletion

`documents.delete` accepts deletion; its return does not confirm physical cleanup.
For completion tracking, keep the operation ID returned by the explicit request
method. The operation remains readable by its space and ID after the document
is absent. An optional command UUID identifies a repeated deletion command.

```typescript
const operationId = await space.documents.requestDelete(document.id, { commandId });
const status = await space.documents.getOperation(operationId);
console.log(status.state);
```

A missing or malformed operation header raises `APIError` after acceptance;
the client does not repeat DELETE to obtain another ID.


## Document lifecycle commands

`activate`, `deactivate` and `reindex` require a caller-owned command UUID and
return `DocumentOperationStatus`. Keep that UUID for an explicit replay of the
same command; using it for another action is a conflict. POST commands are
never retried automatically, including after a 503 response.

```typescript
const commandId = crypto.randomUUID();
const operation = await space.documents.deactivate(document.id, { commandId });
const status = await space.documents.getOperation(operation.id);
```

Commands need write access; reading retained status needs read access. An
attached storage document is refused with a conflict; another space's document
is masked as not found. `succeeded`, `failed` and `cancelled` are terminal status
values. The required `document.is_active` describes settled managed visibility;
accepting a queued command does not flip it. `indexed` describes ingestion
status independently. Existing `delete` and `requestDelete` remain available.
