# SDK

## Explanation — what & why

The Vectros SDK is a typed client library for the platform's REST API. Rather
than hand-rolling HTTP requests, signing headers, and decoding paginated
envelopes, you construct one client and call typed methods grouped by resource:
`client.records.createRecord(...)`, `client.search.content(...)`,
`client.inference.ragInference(...)`, and so on.

The SDK is **generated from the API specification**, not written by hand. The
spec is the single source of truth: the same definition drives the API gateway,
the rendered API reference, and the SDK. That is why the method names, request
shapes, and response types in your editor match the API exactly — they are the
same artifact, expressed in TypeScript.

The SDK does the mechanical work you would otherwise repeat in every project:

- **Typed requests and responses** — your editor autocompletes fields and flags
  mistakes before you run anything.
- **Streaming as async iteration** — chat, RAG, and document-ask endpoints are
  server-sent-event streams; the SDK exposes them as async iterables you can
  `for await` over.
- **A uniform list envelope** — list, lookup, and version endpoints return a
  cursor-paginated envelope (see below) so draining a full result set is one
  loop, the same every time.

### Language coverage

The SDK is generated for **Node, Java, and Python**. Each has a smoke suite
(`smoke-tests/{,sdk-python/,sdk-java/}`) covering the same MVP surface (auth,
the list envelope, the error contract, chat/RAG streaming, and cross-context
isolation). The snippets here use Node idioms;
the Java and Python equivalents follow the same resource grouping and the same
wire contract. See the generated API reference for each language's exact idioms.

The three clients are **generated per language, not hand-aligned** — so the
client class and its constructor differ, and methods follow each language's
casing. Don't assume the Node shape transfers verbatim:

| Language | Install | Construct |
|---|---|---|
| Node | `npm install @vectros-ai/sdk` | `new VectrosClient({ token, environment })` |
| Python | `pip install vectros` | `VectrosApi(base_url=..., token=...)` |
| Java | `ai.vectros:vectros-sdk` (Maven Central) | `VectrosApiClient.builder().token(...).url(...).build()` |

Method names mirror the API operations in each language's idiom — Node and Java
camelCase (`createRecord`), Python snake_case (`create_record`). Runnable
Python and Java equivalents of the Node snippets below are in
[Python and Java](#python-and-java).

### The list envelope (cursor pagination)

List, lookup, and version endpoints return a uniform envelope:

```ts
{ data: T[], nextCursor: string | null }
```

To drain every page, feed `nextCursor` back as `startFrom` until it comes back
`null`:

```ts
const ids: string[] = [];
let cursor: string | null | undefined;
do {
  const page = await client.schemas.listSchemas(
    cursor ? { startFrom: cursor, limit: 100 } : { limit: 100 },
  );
  ids.push(...(page.data ?? []).map((s) => s.id!));
  cursor = page.nextCursor;
} while (cursor);
```

These endpoints are **not** enveloped and do not paginate this way:

- **`client.search.content(...)`** returns a results object directly (its hits
  are on `results`), with `limit`/`offset` for paging.
- **`getUsage`** returns its usage payload directly.
- **`GET /v1/models`** returns `models` and `defaultModel`, and **`GET /v1/admin/logs`** returns `entries`.

## How-to

### Install

```bash
npm install @vectros-ai/sdk
```

### Construct a client

The client takes a token and a target environment (the API base URL):

```ts
import { VectrosClient } from '@vectros-ai/sdk';

const client = new VectrosClient({
  token: process.env.VECTROS_API_KEY!,            // sk_*, ssk_*, or st_*
  environment: 'https://api.vectros.ai',
});
```

`token` accepts any of the three credential types — a root key (`sk_*`), a
scoped permanent key (`ssk_*`), or a short-lived scoped token (`st_*`). The
client makes no distinction; the platform enforces each credential's reach.

Sub-clients are grouped by resource tag:

| Sub-client | Covers |
|---|---|
| `client.records` | structured records |
| `client.schemas` | record/surface schemas |
| `client.documents` | documents (ingest, upload, retrieve) |
| `client.folders` | folder hierarchy |
| `client.search` | unified search |
| `client.inference` | chat, RAG, document-ask, model catalog |
| `client.agents` | stored agents (create, list, read, version, retire) and runs (start a streamed run, read it, cancel it; list runs from SDK 0.50); SDK 0.49+ |
| `client.identity` | users, identity entities (namespaced — `org`/`client` are reserved names, registered like any other), namespaces |
| `client.scripts` | versioned script source: push, list, retrieve, delete, and synchronous execution |
| `client.triggers` | async trigger rules, and the trigger-failure listing |
| `client.compliance` | erasure requests and their certificates |
| `client.public` | the anonymous public routes: public records and public search, read with a publishable key. |
| `client.public`: search near a place | public search also finds records near a place: send the `near.lat`, `near.lon` (decimals with at most 6 decimal places) and `near.radius` (whole metres, up to 200000) query parameters together, with no `q` for nearest first or with a `q` to keep only the matches inside the radius; each result then carries `distanceMeters`. Location search needs the Geocoding waiver, signed for the tenant by an owner of the account in the developer portal. **SDK 0.50+.** |
| `client.public`: filters with no `q` | public search with at least one `filter.<field>` and no `q` lists the type's published records that match the filters, in a fixed order, the same on every page, while at most 2,000 index entries match (a long document, or a record edited moments ago, can be more than one). If more match, or a search limit stops it, the page carries `incompleteResults: true`. It is billed as one text search and uses 12 tokens of the key's rate limit, plus 1 for each 40 of `offset`. If its page is flagged `incompleteResults` and has no results, it is not billed. `mode` must be left out or be `text`, and the type must offer `text`. Search reaches at most the first 240 results of a request; to read every published record of a type, use its public list (by a lookup field; on a type that publishes by a field, by that field, once per published value), which pages with a cursor. **SDK 0.51+.** |
| `client.public`: order by a field, filter an instant | public search with `sortBy` (the id of a filterable `number`, `date` or `instant` field the type publishes) and optionally `order` (`asc`, the default, or `desc`) returns the matches in that field's order, records without a value last. With no `q`, records with the same value come in the same order on every page. With a `q`, they are ordered by relevance. `q` is optional with it. With `sortBy`, `mode` must be left out or be `text`, and the type must offer `text`. A filter on an `instant` field takes a moment as `YYYY-MM-DDTHH:MM:SS.sssZ`: exact, a range (both bounds inclusive; a day runs from its first millisecond to its last) or a set. An ordered search is billed as one text search. It uses 12 tokens of the key's rate limit, plus 1 for each 40 of `offset`. If its page is flagged `incompleteResults` and has no results, it is not billed. It puts at most 2,000 matching index entries in order. With a `q`, these are the most relevant. If more match, or a search limit stops it, the page carries `incompleteResults: true`. Records that belong on the page may then be missing. Search reaches at most the first 240 results of a request. **SDK 0.51+.** |
| `client.public` without a token | the three public reads send no `Authorization` header: construct the client with no `token` (Python: `VectrosApi(base_url=...)`; TypeScript: `new VectrosClient({ environment })`) and pass the publishable key as `k`. A list by a lookup field sends that field as an extra query parameter (`requestOptions.queryParams` in TypeScript, `request_options={"additional_query_parameters": ...}` in Python). For pages and apps, `createPublicClient` in `@vectros-ai/react/public` binds the key once and refuses any credential that is not a publishable key. |
| `client.auth` | ping, scoped-token mint, and related auth calls |

### First call — define a schema, write a record, read it back

```ts
// 1. Define a record type. HYBRID indexing = keyword + semantic.
const schema = await client.schemas.createSchema({
  body: {
    typeName: 'patient',
    displayName: 'Patient Record',
    indexMode: 'HYBRID',
    allowedSurfaces: ['record'],
    fields: [
      { fieldId: 'name', fieldType: 'string', required: true, searchable: true },
      { fieldId: 'notes', fieldType: 'string', searchable: true },
      { fieldId: 'department', fieldType: 'string', filterable: true },
      { fieldId: 'email', fieldType: 'string', required: true },
    ],
    lookupFields: [{ fieldName: 'email', unique: true }],
    capabilities: { auditHistory: true },
  },
});

// 2. Write a record. (Synthetic, clearly-fictional data only.)
const record = await client.records.createRecord({
  body: {
    typeName: 'patient',
    schemaId: schema.id!,
    payload: {
      name: 'Jane Doe',
      notes: 'presents with hypertension and complains of chest pain',
      department: 'cardiology',
      email: 'jane.doe@example.test',
    },
  },
});

// 3. Read it back.
const loaded = await client.records.getRecord({ id: record.id! });
```

**Expected result:** `createRecord` returns immediately with
`indexStatus: 'PENDING_INDEX'`; indexing is asynchronous. `getRecord` returns
the stored record, and once indexing completes `indexStatus` becomes
`'INDEXED'`.

### Search across records and documents

`searchContent` is unified — it returns both record and document hits unless you
narrow with `contentTypes`. It is not enveloped; read `results`.

```ts
const results = await client.search.content({
  query: 'hypertension chest pain',
  mode: 'HYBRID',          // TEXT | SEMANTIC | HYBRID
  limit: 50,
});
for (const hit of results.results ?? []) {
  console.log(hit.documentId, hit.semanticScore, hit.textScore);
}
```

### Stream a RAG answer

Streaming endpoints are async iterables. Each yielded event has an `event`
discriminator (`search_results`, `content_delta`, `done`, and so on; plus
`reasoning_delta` if you ask for it, below):

```ts
const stream = await client.inference.ragInference({
  query: 'What treatment is recommended for stage 1 hypertension?',
  search: { mode: 'HYBRID', limit: 5 },
  maxTokens: 1024,
});

let answer = '';
for await (const ev of stream) {
  if (ev.event === 'content_delta') answer += ev.delta ?? '';
  if (ev.event === 'done') console.log('charged (milli-cents):', ev.inferenceBalanceCentsChargedMilli);
}
```

Plain chat (`client.inference.chatInference`) and document-scoped ask
(`client.inference.documentAsk`) follow the same async-iterable pattern.

Chat, RAG, and document-ask also take an optional `reasoning`: `'omit'` (the default) or
`'stream'`. With `'stream'`, a model that reasons sends its reasoning as `reasoning_delta`
events (each with a `delta`) before the answer's `content_delta` events; a model that does not
reason sends none, and a request that omits the field gets the same stream as before. Do not
append reasoning to the answer text. It counts against `maxTokens` and is billed as output
whether or not you stream it, and a request routed through `providerAlias` ignores the field.

```ts
for await (const ev of stream) {
  if (ev.event === 'reasoning_delta') reasoning += ev.delta;   // only with reasoning: 'stream'
  if (ev.event === 'content_delta') answer += ev.delta ?? '';
}
```

A streaming call can be refused before the stream starts. The SDK throws, and the error body
carries an `errorCode` you can branch on: `402` means the inference balance is short, while a
`429` with `BALANCE_BUSY` or a `503` with `BALANCE_UNAVAILABLE` means the balance step did not
complete: do not top up, and retry after the seconds in the `Retry-After` header.

Chat, RAG, and document-ask requests also take an optional `providerAlias`, the alias
of a model provider config your account has activated (`vectros provider-config`; see
[cli.md](cli.md)). Without it, the call is served by the platform-hosted model path.
With it, that one call is processed where your own provider processes it and leaves the
Vectros perimeter; the platform refuses it with a `403` unless your account has an active
provider config and holds a granted risk-acceptance waiver for it (and, if your account has
accepted the Business Associate Agreement with Vectros in the developer portal, the config has a current attestation from an
owner). When the waiver is the cause, the `403` carries an `errorCode` that says which case it is:
`WAIVER_NOT_SIGNED` (never signed), `WAIVER_TEXT_CHANGED` (the waiver version in force for your account is older
than the version Vectros requires), or `WAIVER_REVOKED` (an account owner revoked it). An account owner resolves all three in the
developer portal (Model Providers); retrying the call does not help. If the platform cannot open a stored
provider key, the call is refused with a `503` before the stream starts and nothing is sent to your provider;
retry shortly, and if it persists enter the key again in the developer portal. When `providerAlias` is set,
`model` names a model in your provider's own id space.

```ts
const stream = await client.inference.ragInference({
  query: 'What treatment is recommended for stage 1 hypertension?',
  providerAlias: 'my-provider',
});
```

### Streams: unknown events and fields

The API can add an event type to a stream, or a field to an existing event, without breaking a
client that is already written. Write your stream loop so that it **ignores an event type it does
not recognise and a field it does not use**, and so that it stops on the terminal event: a stream
ends with `done`, or with `error` if the call fails after it opens, and a stream that ends without
either is incomplete.

What each SDK does when the stream carries something it has no type for (checked against the
current release; the SDKs are generated, so re-check after upgrading):

| Case | TypeScript | Python | Java |
|---|---|---|---|
| An event type the SDK does not know | Delivered as a plain object that carries its own `type` and fields. Give your `if` or `switch` a branch that ignores it. | **Not delivered.** The SDK logs a warning through the standard `logging` module and carries on. | Delivered as an **unknown** member with no content: `_isUnknown()` is true. Ignore it. |
| A field the SDK does not know on a known event | Kept on the event object. | Kept in the event's `model_extra`. | Kept in `getAdditionalProperties()`. |
| An unknown event in place of `done` | Delivered, so you can see it. | **Not delivered**: the stream ends without `done`. | Delivered as an unknown member, with no content to read. |
| A keepalive comment line | Ignored. | Ignored. Once a frame has carried an `id:` line, each comment after it also logs a warning; the chat, RAG and document-ask streams carry no `id:` line. | Ignored. |

The API does not send a damaged frame. These rows describe what each SDK does if a proxy or the
network damages the stream:

| Case | TypeScript | Python | Java |
|---|---|---|---|
| A frame whose data is not valid JSON | The iteration **throws a `SyntaxError` and ends**; events already delivered are kept. | The frame is skipped and warnings are logged. | The frame is skipped. |
| A frame whose data is valid JSON but not an object | Delivered as it is: `null` or an array. | Skipped, with a warning. | `null` is delivered as a `null` element; an array is skipped. |
| The connection is cut mid-stream | The iteration throws a `TypeError`. | The iteration raises an `httpx.RemoteProtocolError`. | The iteration ends **without an exception**. |

So test for completion rather than for an exception: remember whether you have seen `done`, treat a
stream that ended without it as incomplete, and keep your loop from assuming that every delivered
item is an object.

```ts
const stream = await client.inference.chatInference({
  messages: [{ role: 'user', content: 'Summarise the intake note.' }],
});
let answer = '';
let finished = false;
try {
  for await (const ev of stream) {
    if (ev?.event === 'content_delta') answer += ev.delta ?? '';
    else if (ev?.event === 'done') finished = true;
    // anything else is ignored, including event types added later
  }
} catch (err) {
  // a damaged or cut stream can throw here, depending on the SDK
}
if (!finished) { /* the stream ended without `done`: retry or report it */ }
```

### Ingest a document and `externalId`

`externalId` on a document is unique **per schema**. `ingestDocument` and
`uploadDocument` therefore refuse (`400`) a request that supplies an `externalId`
without a `schemaId`, unless the request sets `confirmUntyped`. Pass the `schemaId` of
the typed document you mean, or set `confirmUntyped` to confirm that an untyped
document is what you intend:

```ts
await client.documents.ingestDocument({
  confirmUntyped: true,
  body: {
    title: 'Release notes',
    text: 'What changed in this release...',
    indexMode: 'HYBRID',
    externalId: 'release-notes-2026-10',
  },
});
```

A request with neither `externalId` nor `schemaId` is unaffected. In Python the
argument is `confirm_untyped=True`; in Java, `IngestDocumentRequest.builder()...
confirmUntyped(true)`.

### Drain a paginated list

See the envelope loop in the Explanation section above — that is the canonical
drain pattern for any `list*`, `lookup*`, or `get*Versions` call.

### Update strategies — full replace vs. partial patch (SDK 0.26+)

The default update is a **full replace** (PUT-style): you send the complete
desired body.

```ts
await client.records.updateRecord({
  id: record.id!,
  body: {
    typeName: 'patient',
    schemaId: schema.id!,
    payload: { name: 'Jane Doe', notes: 'updated note', department: 'cardiology', email: 'jane.doe@example.test' },
  },
});
```

A **partial patch** (RFC-7386 merge-patch) is available on records, documents,
and folders **with SDK 0.26+**: send only the fields you want to change; omitted
fields are left untouched, and an explicit `null` deletes a field.

```ts
// (SDK 0.26+) — patch only the notes field.
await client.records.patchRecord({
  id: record.id!,
  body: { payload: { notes: 'patched note' } },
});
```

`patchDocument` takes the fields **beside `id`**, with every field optional, rather
than under `body` (TypeScript and Java). In Python the keyword arguments are the same
except that `title` is optional and `index_mode` and `external_id` are removed, so a call that passes
them raises `TypeError`. The patch request has no `externalId` or `indexMode`:

```ts
await client.documents.patchDocument({ id: doc.id!, title: 'New title' });
```

In Java, build a `DocumentPatchRequest` directly
(`DocumentPatchRequest.builder().title("New title").build()`) and pass it to
`patchDocument` with the document id; there is no wrapping `DocumentRequest`.

### Create a record by type name or by schema id (SDK 0.26+)

With **SDK 0.26+**, `createRecord` accepts **either** `typeName` **or**
`schemaId` (you no longer need both) — supply whichever you have on hand.
Earlier SDK pins expect both; the first-call example above passes both, which
works on every version.

### Python and Java

The snippets above are Node. The Python (`vectros` on PyPI) and Java
(`ai.vectros:vectros-sdk` on Maven Central) SDKs are generated from the same
spec and cover the same surface; the install, client construction, and method
casing differ per language. Each block below is the cross-language twin of the
*Construct a client* + *first call* (define a schema, write a record, read it
back) above.

#### Python

```bash
pip install vectros
```

```python
import os
import vectros
from vectros import VectrosApi

# Note: the keyword is `base_url` in Python — NOT Node's `environment`.
client = VectrosApi(
    base_url="https://api.vectros.ai",
    token=os.environ["VECTROS_API_KEY"],     # sk_*, ssk_*, or st_*
)

# 1. Define a record type. HYBRID indexing = keyword + semantic.
schema = client.schemas.create_schema(
    type_name="patient",
    display_name="Patient Record",
    index_mode="HYBRID",                     # HYBRID | SEMANTIC | TEXT
    allowed_surfaces=["record"],
    fields=[
        vectros.FieldDef(field_id="name", field_type="string", required=True, searchable=True),
        vectros.FieldDef(field_id="email", field_type="string", required=True),
    ],
    lookup_fields=[vectros.LookupDef(field_name="email", unique=True)],
)

# 2. Write a record. (Synthetic, clearly-fictional data only.)
record = client.records.create_record(
    type_name="patient",
    schema_id=schema.id,
    payload={"name": "Jane Doe", "email": "jane.doe@example.test"},
)

# 3. Read it back.
loaded = client.records.get_record(record.id)
```

Streaming inference is an iterator of discriminated events (`event` =
`content_delta`, `done`, ...), the same shape as Node:

```python
stream = client.inference.chat_inference(
    messages=[vectros.ChatMessage(role="user", content="Say hello.")],
    max_tokens=1024,
)
answer = "".join(ev.delta or "" for ev in stream if ev.event == "content_delta")
```

Sub-clients (`client.records`, `client.schemas`, `client.documents`,
`client.folders`, `client.search`, `client.inference`, `client.agents`, `client.identity`,
`client.scripts`, `client.triggers`, `client.compliance`, `client.public`, `client.auth`) and the
list envelope (`page.data` / `page.next_cursor`) match the Node grouping. API errors raise `vectros.core.api_error.ApiError`
(`err.status_code` carries the HTTP status).

#### Java

Maven:

```xml
<dependency>
  <groupId>ai.vectros</groupId>
  <artifactId>vectros-sdk</artifactId>
  <version>0.51.0</version>
</dependency>
```

Gradle:

```groovy
implementation 'ai.vectros:vectros-sdk:0.51.0'
```

(The version above is the current published release; confirm the latest on
Maven Central.)

```java
import ai.vectros.VectrosApiClient;
import ai.vectros.types.FieldDef;
import ai.vectros.types.FieldDefFieldType;
import ai.vectros.types.LookupDef;
import ai.vectros.types.RecordRequest;
import ai.vectros.types.SchemaRequest;
import ai.vectros.types.SchemaRequestAllowedSurfacesItem;
import ai.vectros.types.SchemaRequestIndexMode;
import java.util.List;
import java.util.Map;

VectrosApiClient client = VectrosApiClient.builder()
    .token(System.getenv("VECTROS_API_KEY"))   // sk_*, ssk_*, or st_*
    .url("https://api.vectros.ai")
    .build();

// 1. Define a record type. HYBRID indexing = keyword + semantic.
var schema = client.schemas().createSchema(SchemaRequest.builder()
    .typeName("patient")
    .displayName("Patient Record")
    .indexMode(SchemaRequestIndexMode.HYBRID)   // HYBRID | SEMANTIC | TEXT
    .allowedSurfaces(List.of(SchemaRequestAllowedSurfacesItem.RECORD))
    .fields(List.of(
        FieldDef.builder().fieldId("name").fieldType(FieldDefFieldType.STRING).required(true).searchable(true).build(),
        FieldDef.builder().fieldId("email").fieldType(FieldDefFieldType.STRING).required(true).build()))
    .lookupFields(List.of(LookupDef.builder().fieldName("email").unique(true).build()))
    .build());

// 2. Write a record. (Synthetic, clearly-fictional data only.)
var record = client.records().createRecord(RecordRequest.builder()
    .typeName("patient")
    .schemaId(schema.getId().orElseThrow())
    .payload(Map.of("name", "Jane Doe", "email", "jane.doe@example.test"))
    .build());

// 3. Read it back.
var loaded = client.records().getRecord(record.getId().orElseThrow());
```

Java request DTOs live under `ai.vectros.types.*`; per-endpoint request wrappers
(e.g. `ChatRequest`, `ListRecordsRequest`) under
`ai.vectros.resources.<area>.requests.*`. Sub-clients are accessor methods
(`client.records()`, `client.inference()`, ...), responses use `Optional`
getters (`record.getId().orElseThrow()`), and streaming is an `Iterable` of
discriminated events (`event.isContentDelta()` / `event.getDone()`). API errors
throw `ai.vectros.core.VectrosApiApiException` (`ex.statusCode()`).

## Reference

### Client construction

| Option | Type | Notes |
|---|---|---|
| `token` | string | `sk_*`, `ssk_*`, or `st_*`. Required. |
| `environment` | string | API base URL, e.g. `https://api.vectros.ai`. Required. |

### Sub-clients (by tag)

`records`, `schemas`, `documents`, `folders`, `search`, `inference`, `agents`,
`identity`, `scripts`, `triggers`, `compliance`, `public` (`public_()` in Java, where `public` is a reserved word), `auth`. Method names mirror the API operations
(`createRecord`, `getRecord`, `updateRecord`, `patchRecord`, `deleteRecord`,
`listRecords`, `lookupRecords`, `getRecordVersions`, `getRecordTombstone`,
`createSchema`, `ingestDocument`, `uploadDocument`, `getDocument`,
`createFolder`, `chatInference`, `ragInference`, `documentAsk`,
`listInferenceModels`, `createUser`, `createEntity`/`listEntities`/`lookupEntities`
(namespace-parameterized — `org`/`client` are reserved names among any you
register, see [identity-access/reference.md](../identity-access/reference.md)),
`registerNamespace`, `ping`, and so
on). The complete, exhaustive list of methods, parameters, and field types is in
the generated API reference — link to it by name rather than recreating it here.

### Envelope shape

| Field | Type | Meaning |
|---|---|---|
| `data` | `T[]` | The page of items. |
| `nextCursor` | `string \| null` | Pass back as `startFrom` for the next page; `null` means no more pages. |

Applies to `list*`, `lookup*`, and `get*Versions`. **Does not** apply to
`search.content` or `getUsage`.

On `list*` and `lookup*`, treat `nextCursor` as an **opaque, encrypted token**,
not a value to construct: pass back exactly what the previous page returned,
never a hand-built or reused `startFrom` — the API rejects one it did not issue
with a 400. Keep every other parameter identical while paging: a cursor reused with parameters that read elsewhere (another folder, owner or lookup mode) is refused with a 400, but not every change to the other parameters is detected, and a cursor reused after one returns pages that match neither query.
`get*Versions` shares the same envelope but resumes from a **plain row id**
rather than a sealed cursor — echo `nextCursor` back the same way, but it is
not encrypted, and (unlike `list*`/`lookup*`) a caller-supplied id is the
expected shape there rather than a rejected one. On every one of these, a page
filled to `limit` is not itself a signal to keep going — the only
continue-or-stop signal is whether `nextCursor` came back `null`.

### Index modes

`HYBRID` (keyword + semantic), `SEMANTIC` (meaning-based only), `TEXT` (keyword
only), and `NONE` (store-only: persisted and readable by id and lookup, never
indexed or returned by search). Declared per schema (records) or per document at
ingest. A record with no resolvable mode is stored but not indexed, and a document
with none is rejected, so declare the mode you want.

### Concurrency

Record and document updates accept an optional `expectedVersion` in the body for optimistic
concurrency; a mismatch is rejected with HTTP 409. Without it, the update applies to the item
as it stands when the update starts. Independently of `expectedVersion`, an update or `upsert`
of a record, document, folder, entity, trigger rule, schema, app context, role or namespace
(and the resend of an invitation) that meets another change to the same item at the same moment
returns `409` with `errorCode` `VERSION_CONFLICT`, and nothing is written: re-read the item and
retry. A record create that meets another write to something it depends on at the same moment
returns the same `409` with `errorCode` `VERSION_CONFLICT`, and nothing is written: retry the
request. An update of an item deleted a moment earlier returns `404`. A delete that meets
another write to the same item also returns a retryable `409`.

### Version reality (read before pinning)

- The API spec / SDK is at version **0.51.0** (this figure is sourced from
  the live release at build time, so it always reflects the current version). The
  generated Node SDK is a continuous-integration artifact built from that spec — it
  is **not committed** to this repository, so you install it from the package
  registry.
- Among the in-repo consumers — the **CLI**, **MCP server**, and the reference web apps
  (**admin-app**, **app-vectros-ai**) — all currently pin the same SDK release; the
  **React toolkit**'s dev/test pin tracks it too, though the toolkit itself (an auth/UI
  library, not a data client) accepts any SDK `>=0.9.0` via its peer dependency. These
  pins are **not guaranteed to move together** release-to-release — a consumer can be
  repinned independently of the others — so if you depend on a specific consumer's
  bundled SDK, check that consumer's own `package.json` for its exact pin rather than
  trusting a snapshot figure in this doc.
- **0.26+ surface** — these require SDK 0.26 or newer and are absent on older pins:
  - `patchRecord` / `patchDocument` / `patchFolder` (RFC-7386 merge-patch).
  - `createRecord` with **`typeName` *or* `schemaId`** (the either-or form).
    Passing both works on all versions.
  - All in-repo consumers (CLI, MCP server, and the reference web apps) are past 0.26,
    so these are reachable everywhere today, including through the reference apps' own UI.
- **0.27 added** an optional lower-cost global-region path for inference
  (`allowGlobalRegion` on chat / RAG / document-ask) for tenants entitled to it;
  see [Search and RAG reference](../search-rag/reference.md).
- **0.37 added** schema lineage (`basedOn` — a schema customizing another schema sharing
  its `typeName`; see [data model reference](../data-model/reference.md#schema-fields)),
  `specificityRank` on namespaces, `contextId`-targeted token minting (root-key-only),
  `userId`/`scope` selectors on document lookup, and `externalId`/`hasMore` on search
  results (see [Search and RAG reference](../search-rag/reference.md)). It also replaced
  the `400 AMBIGUOUS_RECORD_TYPE` on a cross-owner `typeName` collision with ownership-
  shadowed resolution — see the data model reference for the full `basedOn` contract.
- **0.38 added composite (multi-field) lookups**, and with it the one
  compile-breaking change in this release for typed clients:
  `lookupFields[].fieldName` on `LookupDef` is now **optional**. A lookup
  declares either `fieldName` (one field) or the new `fieldNames` (2–3 fields
  indexed together, in a fixed declared order). Code that reads `fieldName` off
  a schema response must handle it being absent — a multi-field lookup reports
  `fieldNames` instead — and a GET-modify-PUT round-trip on a composite lookup
  must carry `fieldNames` through, or the update is rejected. Query a composite
  lookup with a comma-joined field name plus the new `values` array parameter
  (alongside the existing singular `value`); `sortFrom`/`sortTo` narrow an
  exact match to a window of the sort key and, on a composite lookup, need a
  value for every declared field — a partial (grouped) match has no single
  ordering to window. A composite lookup can't be `unique` or `rangeEnabled`,
  and only applies to `record` schemas. `RecordLookupResponse` was also renamed
  to `RecordLookupPage` (SDK type name only — the JSON wire shape is unchanged,
  so a client reading raw JSON needs no change).
- **0.38 defines** a `Vectros-Version` request header for pinning a call's
  response shape to a specific API version. **The SDKs do not send it** —
  every SDK call falls back to the calling credential's own `wire_version_pin`
  (stamped at mint time, not your account's current setting), and from there to
  the platform floor, regardless of the SDK version you're on. Don't assume the
  SDK negotiates or pins a wire version.
- **0.46 changed** document ingest and the document patch request, and added
  BYO model routing:
  - `ingestDocument` and `uploadDocument` refuse an `externalId` without a `schemaId`
    unless `confirmUntyped` is set (see *Ingest a document and `externalId`* above).
  - `patchDocument` takes its fields beside `id` in TypeScript and a
    `DocumentPatchRequest` in Java, so existing calls need updating to compile.
  - Chat, RAG, and document-ask take an optional `providerAlias`.
  - `hasMore` is a required field of the RAG `search_results` event in the generated
    types, and a RAG `search.limit` outside 1-100 returns `400`.
  - The model alias `claude-opus-4-8` is retired in favor of `claude-opus-5-5`.
  - Creating an app context past 100 (live and test counted separately) returns `402`
    (`SUBSCRIPTION_LIMIT_EXCEEDED`).
- **0.48 added** no operations. It adds the optional `reasoning` request field and the
  `reasoning_delta` stream event on chat, RAG, and document-ask (see *Stream a RAG answer*),
  and changes some responses (see *Concurrency* and the `providerAlias` section):
  - A `providerAlias` call refused for the provider waiver returns `403` with an `errorCode`
    (`WAIVER_NOT_SIGNED`, `WAIVER_TEXT_CHANGED` or `WAIVER_REVOKED`), and
    one whose stored provider key cannot be opened returns `503`.
  - A streaming call whose balance step did not complete returns `429` (`BALANCE_BUSY`) or `503`
    (`BALANCE_UNAVAILABLE`), both with `Retry-After`, instead of a `402`; of the balance-step outcomes, `402` now means
    only a short balance.
  - Updates and upserts answer `409` (`VERSION_CONFLICT`) when they meet a concurrent change,
    with or without `expectedVersion`; a delete that meets a concurrent write answers a retryable
    `409` instead of `500`; and `DELETE /v1/schemas/{id}` also answers `409` while users or entities
    bound to the schema exist.
  - An item whose schema no longer exists is no longer served: reading it returns an error, and
    lists and lookups leave it out. Delete the item.
  - A request body that is not valid JSON or has the wrong shape returns `400` with a fixed message,
    and a body over 8 KB to `POST /v1/auth/token/exchange` returns `413`.
- **0.49 added** the `agents` sub-client: stored agents (`createAgent`, `listAgents`, `getAgent`,
  `updateAgent`, `deleteAgent`, `listAgentVersions`) and runs of them (`createRun`, a streamed
  run, plus `getRun` and `cancelRun`). See [Agents and runs](../agents-runs/reference.md).
  It also changes some responses and types:
  - **Inference amounts are in milli-cents** (1 cent = 1000). `inferenceBalanceCentsChargedMilli` on the `done`
    event of chat, RAG and document-ask replaces `inferenceBalanceCentsCharged`, and `balanceCentsMilli` in the usage
    report's `inference` section replaces `balanceCents`. Code that reads a removed field gets nothing: read the
    `...Milli` field and divide by 1000 for cents. Amounts you send stay in whole cents.
  - **Prompt-cache pricing.** A model in `listInferenceModels` that has prompt-cache prices carries `cachePricing`
    (credits per 1K tokens for a cache read, a 5-minute cache write and a 1-hour cache write, for each region). The
    `done` event can carry `cacheReadTokens` and `cacheCreateTokens`, and the usage report counts them per endpoint.
  - **`actingVia` on version-history entries.** An entry for a change made by an agent run names it in `actingVia`
    (`kind`, `actorId`, `runId` and, when the run used a tool, `tool`) beside `changedBy`; the same object appears on
    access-log entries. `kind` is an open set, so treat a value you do not recognize as valid. An entry for a change made
    directly with a credential carries none.
  - **Documents.** A file-uploaded document carries `extraction` (`outcome`, `truncated`, `message`); branch on
    `outcome`. `getDocumentText` takes `offset` and `limit` (in characters) and reports `totalLength` and
    `nextOffset`; `listDocuments` takes `type`, which applies to each page as it is read, so keep paging until
    `nextCursor` is null.
  - **Optional fields on update bodies.** A request body shared by a create and an update no longer marks as
    required the fields an update keeps when you omit them (for example `FolderRequest.name`, `DocumentRequest.title`,
    `SchemaRequest.typeName`); a create without one is still refused with `400`. In TypeScript and Python these
    fields become optional. **Java: the getters of those fields return `Optional`** (on `EntityRequest`,
    `FolderRequest`, `DocumentRequest`, `UserRequest`, `AppContextRequest`, `RoleRequest`, `NamespaceRequest`,
    `SchemaRequest`, `TriggerRuleRequest` and `AccessProfileRequest`), and their builders are plain builders instead
    of staged ones. A chain such as `EntityRequest.builder().externalId("x").name("n").build()` compiles unchanged;
    code that reads one of those getters, or names a staged-builder interface such as `FolderRequest.NameStage`,
    needs a change.
- **0.50 added** `listRuns` on `agents`; end-user account deletion on `compliance` (`requestSelfErasure`,
  `getPendingSelfErasure`, `getSelfErasure`, `cancelSelfErasure`; `requestSelfErasure` is refused with `SELF_ERASURE_NOT_ENABLED` unless
  the app context allows it); and the public-access operations (the `public` sub-client, publishable keys on `auth`,
  `republishSchemaPublicView`, `getSchemaRepublish`, `getRecordPublicView`). **Java:** `SearchRequest.getQuery()` and
  `FileUploadRequest.getFileType()` return `Optional<String>`, because neither field is required any more; builder
  chains compile unchanged, code that reads the getter needs a change.
- **0.51 requires** `size` on `uploadDocument`: the file's exact length in bytes, at least 1 (an empty file cannot be
  uploaded). A call without it is refused with `400` `SIZE_REQUIRED`. In TypeScript and Python the field is required, so
  code that omits it needs a change. **Java:** `size` is a step of `FileUploadRequest`'s builder right after `fileName`
  (`FileUploadRequest.builder().fileName("a.pdf").size(48213L)...`), so a chain that omits it, or sets another field between
  the two, needs a change; `getSize()` returns `long` instead of `Optional<Long>`, so code that reads it needs a change.
  The PUT to `uploadUrl` must send every header in `requiredHeaders`, which always includes the `Content-Type` the URL was
  signed for.

### Notes & limits — what the SDK does NOT do

- **Schemas have no patch.** Schemas update through `PUT` only; there is
  no `patchSchema`.
- **Folders cannot be moved or reparented** after creation. There is no move
  operation.
- **There is no identity patch.** Users and identity entities update through `PUT`;
  a field you omit keeps its stored value.
- **`search.content` and `getUsage` are not paginated by the cursor envelope** —
  do not look for `nextCursor` on them.
- **Indexing is asynchronous.** A freshly created/ingested item is
  `PENDING_INDEX` and not immediately searchable; poll its status (or its
  appearance in search) before asserting it is queryable.
- **All three SDKs (Node, Java, Python) have a smoke suite** — see
  `smoke-tests/{,sdk-python/,sdk-java/}`.

## Where to go next

- [cli.md](cli.md) — provision schemas, contexts, and scoped keys from the
  terminal instead of writing this by hand.
- [mcp.md](mcp.md) — expose these same operations to an agent as tools.
- [blueprints.md](blueprints.md) — declare a whole schema set + access profile in
  one file.
- The generated API reference — the exhaustive, per-endpoint contract the SDK is
  generated from.
