Brain Docs

Reference

TypeScript SDKInstallationHTTP clientWire client
ErrorsRetriesPagination
Brain/Docs
✦ ASKBrain on GitHubDashboard
TypeScript SDKWire client

Wire client

BrainClient over the BRN0 protocol — connect, ClientConfig, the two auth methods, act_as, multiplexing, the connection pool, and the id helpers.

PURPOSE

BrainClient speaks Brain's native binary protocol: a 32-byte BRN0 frame header, a CBOR payload, and an optional trailing little-endian f32 vector section, over TCP. One connection multiplexes many concurrent requests. This page documents connecting, configuring, authenticating, and the two things the HTTP tier cannot do — act_as and transactions.

BrainClient.connect

Handshake credentialstable
static connect(host: string, port: number, config: ClientConfig): Promise<BrainClient>

The handshake runs inside connect: HELLO, version negotiation, AUTH. A server that negotiates a version the client did not offer rejects with VersionMismatch rather than proceeding.

ClientConfig

ParameterTypeRequired
authAuthrequired

The credential. See below.

clientIdstringoptional

Identifies the client to the server. Defaults to "brain-db-sdk-typescript".

supportedVersionsnumber[]optional

Wire versions this client accepts. Defaults to [1] — the only version Brain speaks today.

capabilitiesHelloCapabilitiesoptional

What the client supports. Defaults to { streaming: true, compressionZstd: false, serverPush: false }.

connectTimeoutMsnumberoptional

Deadline for the connect and handshake. Defaults to 10_000.

requestTimeoutMsnumberoptional

Deadline for an ordinary request. Defaults to 30_000.

derivedWriteTimeoutMsnumberoptional

Deadline for an encode under WaitMode.Derived only. Defaults to DEFAULT_DERIVED_WRITE_TIMEOUT_MS — 120 s. It exists because the 30 s request timeout would fire before the derivation pipeline finished.

Auth

A discriminated union with two arms:

type Auth =
  | { kind: "token";  token: Uint8Array }
  | { kind: "mtls";   certFingerprint: Uint8Array; assertedSubject: string };
ParameterTypeRequired
{ kind: "token", token }Uint8Arrayrequired

A bearer token as bytes, not a string — encode it yourself with new TextEncoder().encode(...).

{ kind: "mtls", certFingerprint, assertedSubject }—optional

Mutual TLS: the client certificate's fingerprint plus the subject it claims. The server checks the assertion against the presented cert.

import { BrainClient } from "@brain-db/sdk";

const client = await BrainClient.connect("127.0.0.1", 9090, {
  auth: { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) },
  requestTimeoutMs: 15_000,
});

try {
  // ... verbs
} finally {
  await client.close();   // sends BYE, then closes
}

ConnectionInfo

What the handshake established, available on client.connection with no round trip:

FieldTypePresence
namespacestringalways
The authenticated namespace.
spaceIdUint8Arrayalways
The bound space.
serverIdstringalways
Which server answered.
chosenVersionnumberalways
The negotiated wire version.
connectionIdUint8Arrayalways
This connection's id.
boundShardIdnumberalways

Which shard the connection is pinned to. A request for data on another shard is WrongShard, not a transparent redirect.

permissionsSpacePermissionsalways
What the credential may do.
serverFeaturesServerFeaturesalways
What the server supports.

client.namespace, client.spaceId and client.isClosed are shorthands.

Multiplexing

One connection carries many concurrent requests, demultiplexed by stream_id. You do not manage streams — issue calls concurrently and the MuxConnection underneath sorts the responses out.

const [answer, entities, caps] = await Promise.all([
  client.recall(recallReq),
  client.listEntities(listReq),
  client.capabilities(),
]);

Streaming verbs — anything with a …Frames form, plus subscribe — each occupy one stream for their duration. cancelStream(streamId) ends one early; see Subscriptions.

act_as

Every tenant-scoped wire request carries an optional actAs selector:

interface ActAs {
  namespace: string;
  space: string;
  grant?: number;   // ActAsGrant.SchemaUpload (1 << 4) | ActAsGrant.Admin (1 << 5)
}

It is what lets one connection serve many spaces. The credential fixes the namespace; act_as selects the space per request. The builders expose it as .actAs(namespace, space); hand-built requests set the field directly.

act_as is a grant, not a claim

A principal without the canActAs grant — or one naming a namespace outside its allowlist — gets ActAsDenied (0x0033). isActAsDenied(err) is the predicate. The two optional grant bits, SchemaUpload and Admin, are requested per call and must also be held.

This is the mechanism behind per-tenant isolation at scale: one pooled connection, a storage-key prefix per end user, and no credential per user. See Namespaces.

Pool

A fixed-size set of connections handed out round-robin.

ParameterTypeRequired
Pool.connect(host, port, size, config)Promise<Pool>required

Opens size connections, each running its own handshake. Every member shares the credential, so the server binds them to the same agent; they stay individually identifiable by session id. size < 1 throws. On a mid-open failure it closes the members already opened and re-throws.

pool.get()BrainClientrequired

The next connection, round-robin. No liveness check.

pool.getHealthy()Promise<BrainClient>required

The next connection, reconnected first if its socket died. Concurrent callers landing on the same dead slot share one reconnect rather than opening a socket each.

pool.size()numberoptional
How many members.
pool.close()Promise<void>optional

BYE and close every member, best-effort.

Prefer getHealthy for anything long-lived

A pooled member outlives any single request, so a server restart leaves every borrower holding the same dead socket until the process is bounced. get() will hand it to you; getHealthy() dials a replacement in place. Requests already in flight on the old connection fail either way.

Id helpers

ParameterTypeRequired
newId()Uint8Arrayrequired

A fresh random 16-byte id. Use it for requestId and txnId on hand-built requests; the builders call it for you.

deriveSpaceId(namespace, space)Uint8Arrayoptional

The space id the server derives at ingress: UUIDv5(UUIDv5(ROOT, namespace), space). Folding the namespace in is what makes equal space strings under different namespaces diverge. The seed is frozen and pinned by a golden test on both sides.

Do not let the derived space id leave Brain

Clients only ever send the space string. deriveSpaceId exists for the rare local case — naming the effective space by its resolved id in a subscription filter. It is Brain's internal identifier, not your control-plane's; using it as an external key couples two id spaces that are deliberately separate. See Namespaces.

See also
HTTP clientTransactionsSubscriptions

Was this page helpful?

HTTP client

BrainHttpClient — construction, Bearer auth, base URL, timeouts, the camelCase-to-snake_case seam, and the full verb map.

encode

Store a memory from text — the write verb, its wait modes, and the deduplication result.

On this page

BrainClient.connectClientConfigAuthConnectionInfoMultiplexingact_asPoolId helpers
Suggest an editOpen in Playground