nori TypeScript SDK
@sebastianmora/nori-sdk is the client for nori's apps API (/apps/*): the API an app builds its own chat on.
Sessions, turns streamed over server-sent events, host tools, tool confirmations, connectors, artifacts, memory and
voice, typed from the api's OpenAPI document.
- Safe to ship to a browser. The client holds only the publishable key and the person's identity; whatever needs
a secret lives in
@sebastianmora/nori-sdk/server and refuses to run in a browser.
- Retries, timeouts and typed errors built in, with an idempotency key on every send so a retry never runs a turn
twice.
- No runtime dependencies: it only needs
fetch. ESM, with its own declarations.
Every method is listed in api.md. Upgrading from 0.4 or 0.5: MIGRATION.md.
Contents
- Install
- Usage
- Authentication and end users
- Security
- Streaming
- Host tools and confirmations
- Errors
- Retries
- Timeouts
- Cancellation
- Pagination
- The raw response
- Files
- Logging
- Runtimes
- Versioning
Install
npm install @sebastianmora/nori-sdk
Usage
import { Nori } from "@sebastianmora/nori-sdk";
const nori = new Nori({
baseURL: "https://nori.example.com", // defaults to NORI_BASE_URL
apiKey: "aip_live_…", // the key's publishable key; defaults to NORI_API_KEY
endUser: { token: accessToken }, // who is using your app (see below)
});
const session = await nori.sessions.create({ agentId: "agent_…" });
const stream = await nori.sessions.messages.send(session.id, { content: "Hola" });
for await (const event of stream) {
if (event.type === "assistant_delta") process.stdout.write(event.delta);
}
The client keeps no conversation state: your app keeps its own and calls these. Resources mirror the API's paths
(/apps/sessions/{id}/messages is nori.sessions.messages), and the verbs are always the same: list, create,
retrieve, update, delete. More in examples/.
Authentication and end users
Every request carries the key's publishable key (aip_live_…) as X-Api-Key. A key that verifies end users
also needs to know who the person is, through endUser. Pick the mode the key is configured for:
endUser |
When |
What your backend does |
{ token } |
The key trusts your OIDC issuer (Cognito, Auth0…) |
Nothing: pass the person's access token |
{ id, hash } |
The key uses HMAC identity |
Computes hash = HMAC-SHA256(identity secret, id) and hands both to the client |
{ getClientSecret } |
The key has a server secret |
Mints a short-lived client secret with mintEndUserSession |
The client secret flow keeps every secret on your backend:
// Your backend
import { mintEndUserSession } from "@sebastianmora/nori-sdk/server";
const { clientSecret } = await mintEndUserSession({
person: { externalUserId: user.id, email: user.email, emailVerified: true },
}); // reads NORI_BASE_URL, NORI_API_KEY and NORI_SERVER_SECRET
return Response.json({ clientSecret });
// The browser
const nori = new Nori({
baseURL: "https://nori.example.com",
apiKey: "aip_live_…",
endUser: { getClientSecret: async () => (await (await fetch("/api/nori-session")).json()).clientSecret },
});
The client asks for a secret once and caches it. When the api answers end_user_session_expired, it asks again
(passing the old one) and retries that request once.
Mint only for a person your backend has authenticated: whoever can call that endpoint gets a session as the user id
you pass.
withOptions returns a client with some options changed, for example another person:
nori.withOptions({ endUser: { token: otherToken } }).
Security
What the SDK guarantees, so that nothing leaks through it. Each point has a test in test/security.test.ts.
- Secrets never reach a client. A server secret (
nss_…, nori-sk-…) is refused as apiKey and as what
getClientSecret returns. mintEndUserSession throws when it detects a browser; dangerouslyAllowBrowser exists
only for a backend that runs with a window (Electron's main process, a test environment).
- Credentials go only to your api. Requests use
redirect: "error", so a redirect to another host never carries
X-Api-Key or the person's identity, and credentials: "omit", so no cookie is sent.
- Only https.
baseURL must be https: (plain http: only for localhost, 127.0.0.1, [::1] and
*.localhost), with no query, fragment or user:password@.
- The identity can't be overridden.
defaultHeaders and per-request headers can't replace X-Api-Key,
Authorization, X-End-User-Id or X-End-User-Hash, and a header value with a line break is refused before any
request.
- Ids stay in their place. Every path parameter is encoded, and an empty id,
. or .. is refused, so no id can
reach another route.
- Nothing sensitive is logged or thrown. Log lines redact credential headers and
token query parameters. Errors
carry the api's status, code, message and request id, never the request's headers, and their message is capped.
- Bounded memory. A streamed message larger than
maxMessageSize (8 MiB by default) stops the stream with a
StreamError instead of growing without limit.
- Safe file names. Downloaded files' names are reduced to a base name without path separators or control
characters.
- Nothing it receives is followed. URLs in responses (a connector's
authorizationUrl, the speech-to-text
socket, an export's file) are handed to your app as data. Open them only after checking they point where you
expect.
Never put a server secret or an identity secret in client code, in defaultHeaders, or in a URL.
Streaming
messages.send resolves once the turn's stream is open, so a refusal (a turn already running, a model the agent
does not offer) rejects there, before any event. The stream is an async iterable of AppEvents:
| Event |
Meaning |
assistant_delta, thinking_delta, tool_input_delta |
Text arriving |
assistant, thinking |
A complete message |
tool_use, tool_result |
A tool call and its result |
session.computer_status |
The sandbox is preparing, ready or failed |
error |
The turn failed |
result |
The turn ended |
const text = await (await nori.sessions.messages.send(id, { content: "Summarize" })).finalText();
finalText() reads the whole turn and returns the reply's text, or rejects with a StreamError on an error
event.
A stream can be iterated once. Leaving the loop (break, return, a throw) or calling stream.abort() stops
reading and frees the connection. The turn itself runs to its end on the server; stop it with
nori.sessions.interrupt(id). If the connection drops, resume from the last event you saw:
const resumed = await nori.sessions.events.stream(id, { afterSequence: lastSequence });
While a turn runs, messages.send answers ConflictError. To send anyway, use messages.queue: it returns the
turn's stream if it started now, or the message's place in the queue.
Host tools and confirmations
Host tools run in your app (fill a form, read the page). Declare them when you create the session; the agent is
offered only those. When the agent calls one, the turn pauses holding the call; your app runs it and answers. The
answer with continue: true resumes the turn and returns its stream:
const session = await nori.sessions.create({ agentId, clientCapabilities: { hostTools: ["calendar_create"] } });
// …after a turn's stream ends:
for (const call of (await nori.sessions.hostTools.pending(session.id)).calls) {
const answer = await nori.sessions.hostTools.submitResult(session.id, call.sequence, {
outcome: "ok",
output: await runTool(call.tool, call.arguments),
continue: true,
});
if (answer.kind === "stream") for await (const event of answer.events) render(event);
}
A tool that needs the person's approval (approvalMode: "manual", or a call that deletes files) waits the same
way: list it with sessions.toolConfirmations.pending and answer with
sessions.toolConfirmations.answer(id, sequence, { result: "allow" | "allow_always" | "deny" }).
Errors
Every error extends NoriError. A non-2xx response is an APIError with status, code (the api's machine code,
e.g. end_user_session_expired), message, body, headers and requestId (include it when you report a
problem). Each status has its own class:
| Status |
Class |
| 400 |
BadRequestError |
| 401 |
AuthenticationError |
| 403 |
PermissionDeniedError |
| 404 |
NotFoundError |
| 409 |
ConflictError |
| 422 |
UnprocessableEntityError |
| 429 |
RateLimitError |
| ≥ 500 |
InternalServerError |
| No response |
APIConnectionError (APIConnectionTimeoutError for a timeout) |
| Your signal aborted |
APIUserAbortError |
| A stream failed or was too large |
StreamError |
import { APIError, NotFoundError } from "@sebastianmora/nori-sdk";
try {
await nori.sessions.retrieve(id);
} catch (error) {
if (error instanceof NotFoundError) return null;
if (error instanceof APIError) console.error(error.status, error.code, error.requestId);
throw error;
}
Retries
A failed request is retried up to maxRetries times (default 2) when repeating it is safe:
GET, PUT and DELETE: after a connection error, a timeout, or a 408, 429, 500, 502, 503 or 504.
POST and PATCH: only after a 429, unless the request carries an idempotency key, in which case they are
retried like a GET.
messages.send and messages.queue always carry one (generated when you pass none), so a retried send never
runs a turn twice. A ConflictError on a retry means the first attempt landed.
- A 409 is never retried, and the api can forbid a retry with
x-should-retry: false.
The client waits what the api asks (retry-after-ms, Retry-After up to 60 s), or else backs off exponentially
from 0.5 s up to 8 s, with jitter.
const nori = new Nori({ maxRetries: 0 }); // for every request
await nori.sessions.retrieve(id, { maxRetries: 5 }); // for one
Timeouts
A request that gets no response headers within timeout (default 60 s) is aborted with an
APIConnectionTimeoutError and retried as above. A stream's body is not timed, only its headers: a long turn is
never cut off.
const nori = new Nori({ timeout: 20_000 });
await nori.agents.info({}, { timeout: 5_000 });
Cancellation
Pass an AbortSignal. Aborting rejects the call with APIUserAbortError (never retried) and, for a stream, stops
reading it:
const controller = new AbortController();
const stream = await nori.sessions.messages.send(id, { content }, { signal: controller.signal });
stopButton.onclick = () => controller.abort();
Pagination
sessions.list returns a page you can also iterate: for await walks every page, fetching the next one as it
goes.
for await (const session of nori.sessions.list({ limit: 50 })) console.log(session.title);
const page = await nori.sessions.list({ limit: 50 });
page.data; // this page's sessions
if (page.hasNextPage()) await page.getNextPage();
The raw response
Every method returns an APIPromise: await it for the data, or ask for the HTTP response. The request is sent once
either way.
const { data, response, requestId } = await nori.sessions.retrieve(id).withResponse();
const raw = await nori.sessions.retrieve(id).asResponse(); // body not read
Files
Upload a Blob (or File) as an attachment, then send its id with a message. Downloads return
{ blob, filename }:
const attachment = await nori.sessions.attachments.upload(id, file, "report.pdf");
await nori.sessions.messages.send(id, { content: "Summarize this", attachmentIds: [attachment.id] });
const { blob, filename } = await nori.sessions.generatedFiles.retrieve(id, fileId);
Logging
The client writes warnings (retries, refusals) to console by default. Choose the level with logLevel or the
NORI_LOG environment variable (off, error, warn, info, debug), and the destination with logger.
Credentials are redacted at every level.
const nori = new Nori({ logLevel: "debug", logger: myLogger }); // error, warn, info and debug methods
Runtimes
Any runtime with fetch, AbortController, ReadableStream and TextDecoder: browsers, Node.js 20+, Deno, Bun,
Cloudflare Workers, Vercel Edge and React Native (with a streams polyfill for turns). Pass your own fetch when you
need a proxy or a polyfill: new Nori({ fetch }).
@sebastianmora/nori-sdk/server is for server runtimes only.
Versioning
The package follows semantic versioning. Until 1.0, a minor version (0.5 → 0.6) can break the API; each breaking
change is in the CHANGELOG, with the steps in MIGRATION.md. What counts as
public is what the package root and /server export; anything under internal/ and every member starting with _
may change in any release.
Generated files
openapi.json (the public surface only, keys sorted) and src/generated/schema.ts (openapi-typescript) are
committed. pnpm --filter @sebastianmora/nori-sdk generate rebuilds both from the api in-process, with no server and
no database. CI and test/drift.test.ts fail when they differ from a fresh generation, and test/coverage.test.ts
fails when a documented route has no method. api.md is written by build.