Skip to Content
Baseera Docs

Core

The framework-agnostic Baseera client, the chat controller and the protocol types, for apps that do not use React.

@baseera/core is the client that @baseera/react is built on. It needs only fetch: no React, no DOM. It runs in browsers, in Node 20 or later, in workers and in edge runtimes.

If you use React, install @baseera/react instead. It includes this package.

import { createBaseeraClient, createChatController, BaseeraError } from "@baseera/core";

Create a client

import { createBaseeraClient } from "@baseera/core";

const client = createBaseeraClient({
  publishableKey: "pk_your_publishable_key", // never a secret key
  baseUrl: "https://runtime.example.com", // required for now
  getUserToken: () => fetch("/api/baseera-token", { method: "POST" }).then((r) => r.json()).then((b) => b.token),
});

createBaseeraClient throws if the key starts with sk_, if it is not pk_ plus 48 hex characters, or if baseUrl is missing or not an http(s) URL. It also accepts a fetch option to replace the global fetch.

The user token is requested lazily, and again when the cached one has less than a minute left or the runtime says it expired.

Stream a turn

import { BaseeraError, type SequencedEvent } from "@baseera/core";

try {
  const { sessionId } = await client.startSession({ locale: "ar" });

  const turn = client.sendTurn(sessionId, { message: { text: "Is invoice 1042 paid?" }, tools: [] });
  for await (const event of turn) {
    if (event.type === "text.delta") process.stdout.write(event.delta);
    if (event.type === "error") console.error(event.error.code); // yielded, not thrown
  }
} catch (error) {
  if (error instanceof BaseeraError) console.error(error.code, error.status, error.retryAfter);
  else throw error;
}
  • A stream is an AsyncIterable<SequencedEvent>. Each event is { type, ...data, seq }. A stream ends after turn.awaiting_tools, turn.done or error. Unknown event types are skipped.
  • Pass { signal } as the last argument to stop a stream. Aborting ends the loop quietly and does not reconnect.
  • If a stream drops before its last event, the client reconnects once, with Last-Event-ID, and continues without repeating events. A second failure throws a BaseeraError with code network_error.

Client methods

MethodPurpose
startSession(request?)Starts a session. request.locale is a BCP 47 tag.
resumeSession(sessionId)Returns a SessionSnapshot after a reload.
sendTurn(sessionId, request, options?)Sends a message and streams the turn.
postToolResults(sessionId, request, options?)Posts tool results and streams how the turn continues.
getSourceLink(source)Returns a signed link, valid about 5 minutes, to the original of a cited source.
sendFeedback(sessionId, messageId, rating, reason?)Rates an assistant message. Needs a user token.
recordFinish, appendImmersiveEvents, runAiChecksImmersive mode.
getTheme(), getLogo(id)The theme and logo the owner published.

The chat controller

createChatController is the framework-free state machine behind @baseera/react. It owns the session, the messages, the tool loop and the approvals, and exposes them as an observable store with subscribe and getSnapshot, which fit useSyncExternalStore, Vue, Svelte or plain DOM code.

import { createBaseeraClient, createChatController, type RegisteredTool } from "@baseera/core";

const tools: RegisteredTool[] = [
  {
    spec: { name: "invoices.list", description: "List invoices", kind: "read", inputSchema: { type: "object" } },
    run: async () => [{ id: "inv_1042", status: "overdue" }],
  },
];

const controller = createChatController({
  client: createBaseeraClient({ publishableKey: "pk_your_publishable_key", baseUrl: "https://runtime.example.com" }),
  getTools: () => tools, // read fresh on every request, so tools can follow the page
  storage: window.sessionStorage, // optional: keeps only the session id
  getContext: () => ({ page: location.pathname }), // optional
});

controller.subscribe(() => render(controller.getSnapshot()));
await controller.hydrate(); // resume after a reload
await controller.send("Which invoices are overdue?");
  • getSnapshot() returns { sessionId, messages, status, error, pendingApprovals }. It is a new object after every change and the same object while nothing changed.
  • read tools run on their own. draft and write tools wait in pendingApprovals until approve(callId) or reject(callId, reason?). Approved ones then run in call order.
  • Tool results are checked before they go out: a failing validate or a throwing run becomes { error }, output that is not JSON becomes an error, and undefined becomes null.
  • stop() aborts the request and goes idle. reset() also forgets the session. send while the status is not idle or error does nothing.
  • Keys, tokens and tool inputs or outputs are never logged.

Other exports

The package also exports helpers the Baseera platform uses, such as eval, agent configuration and review types. They are not part of the integration surface and are not documented here. The integration surface is the client, the chat controller, the protocol types, the theme, citation and validation helpers, and redactForLog.

Only a publishable key (pk_) belongs in browser code. Keep secret keys (sk_) out of browsers, bundles and public environment variables.

Next steps

On this page