Skip to content
NavodPeirisPublic

About

The easiest way to build an AI assistant into your product. One kit wires the server, the screen and everything between.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

nitrolus

The kit for building an AI assistant into your product. It handles the code between the chat window and the model: page context, tool contracts, verified ask-the-user steps, server-side threads, usage limits, sealed fields, files and a typed tool UI. It builds on the Vercel AI SDK (ai@7); it doesn't replace it.

pnpm add nitrolus ai zod
# React apps also need react; nitrolus/query needs @tanstack/react-query
Entry point For
nitrolus Tool contracts, sealed fields, the manifest, context
nitrolus/server createChat, stores (memory, Postgres, Redis), allowances, attachments, the recorder and replays, long-chat compaction, workflows, AG-UI, realtime
nitrolus/artifacts, nitrolus/artifacts/react Generated HTML pages: validation, sandboxed viewing, revisions, templates
nitrolus/openui, /openui/react, /openui/build OpenUI Lang as the artifact format: prompt, checks, stored pages, native rendering, runtime build
nitrolus/retrieval Chunking, embeddings, pgvector, indexing and hybrid search
nitrolus/memory Working memory per user, with a remember tool
nitrolus/judge Rubric grading, decisions, classifiers, guardrails, answer grading
nitrolus/agents Agent configs with prompt templates, picked per page, with admin routes; helper agents as tools
nitrolus/compress Compressing tool results for the model, with retrieval of the originals
nitrolus/engine Model middlewares: record/replay/fork, fail-fast tool calls, prompt cache, routing, tracing, evals
nitrolus/builtins Ready-made tools and the built-in UIs' schemas (server-safe, no React)
nitrolus/client Framework-free: tool views, the chat transport, actions, uploads, sample data from schemas
nitrolus/react The generic chat shell, typed tool registry, fast chat store, your own components as generative UI
nitrolus/vue, nitrolus/svelte The tool part component and chat store for Vue; the chat store for Svelte; the built-in panel mounted in either
nitrolus/ui The assistant panel and sheet, built-in tool UIs, the inspector, previews of every state, plus nitrolus/ui/styles.css
nitrolus/ui/mount The built-in panel in any page, without writing React (React runs inside)
nitrolus/query Data refresh after tools run (TanStack Query)
nitrolus/codegen, nitrolus CLI Client types and samples from the manifest, card scaffolds, screen and compatibility checks, evals over recordings, AI SDK migration

Why

UI kits cover the chat window. Agent frameworks cover the server. The wiring between them is left to every team, and it's where most of the hand-written code and the bugs live:

  • client types that drift from the server's tools;
  • per-tool labels, renderers and "refresh that data after" lists;
  • answers to questions the server asked, which must be verified;
  • history sent by the browser, which can be forged;
  • answers and secrets in tool outputs that reach the browser;
  • usage limits with refunds, file uploads, aborts on disconnect.

nitrolus owns that wiring. You describe each tool once, on the server; the client gets its types, labels, effects and shortcuts from a generated module.

Quick start: a chat endpoint

import {
  createChat,
  postgresThreadStore,
  postgresAllowance,
  memoryAttachmentStore,
} from "nitrolus/server";

export const chat = createChat({
  authenticate: async (req) => getUser(req), // null → 401
  context: page, // defineContext(...), checks access
  tools: [bookmark, quiz, askSize],
  toolContext: ({ user, page }) => ({ user, page, db }),
  model: openai("gpt-5"),
  system: ({ page }) => `The user is on ${page.title}.`,
  threads: postgresThreadStore(pool), // or knexQuery(knex), prismaQuery(prisma)
  allowance: postgresAllowance(pool, { limit: 50, period: "day" }),
  attachments: { store: myS3Store, maxBytes: 10_000_000 },
  onTurnEnd: ({ outcomes }) => track(outcomes),
  engine: "single-pass", // optional: nitrolus's own loop
});

// Hono / Next / Workers:   app.all('/api/chat/*', (c) => chat.fetch(c.req.raw))
// Express / Nest:          app.use('/api/chat', toNodeHandler(chat.fetch))

chat.fetch serves every endpoint by path: POST / sends a message, GET / returns history, POST /action runs a card action, POST /upload and GET /file handle attachments, GET /stream follows a live reply and GET /manifest serves the manifest. Each is also available alone (chat.handler, chat.history, ...).

What it does per turn:

  • Server-side history. The client sends only the new message. History lives in the ThreadStore, so it can't be forged.
  • Verified answers. An answer to a human tool is accepted only for a question the stored thread is waiting on, and only if it matches the tool's output schema.
  • Usage limits. A new message is counted before any work; an answer to a question isn't. An empty reply is refunded, and tokens are recorded.
  • Disconnects. When the client goes away the model stops, unless onDisconnect: 'continue' keeps the reply running so it can resume.
  • Taint and approvals. Calls made after untrusted content entered the context follow their tool's taintPolicy.
  • One reply at a time. A message sent while a reply streams queues, interrupts it, or steers it.
  • Page state. The readables the client sends (useChatReadable) go to the model at the start of the turn's message, never saved with the thread. readables: false ignores them.
  • @ items. The items the user attached with @ (useAssistant({ mentions })) go to the model with the latest message: by default their kinds, titles and ids, as data. The client only says which items, so look them up: mentions: { resolve: (item, turn) => ({ title, details }) } gives each item's details from your data (its content, or how to read it with a tool) and drops the ones it returns nothing for, such as ids the user can't see. Without it the model gets only the client's titles. mentions: (items, turn) => note writes the whole note yourself. mentions: false ignores them.
  • Outcomes. onTurnEnd gets outcomes: how each outcome: 'execution' tool call ended, decided by the call, never by the model's text.

On the client:

import { useChat } from "@ai-sdk/react";
import { chatTransport, loadHistory } from "nitrolus/client";

const transport = chatTransport({
  api: "/api/chat",
  context: () => ({ lessonId }),
});
const { messages, sendMessage } = useChat({
  id: threadId,
  transport,
  messages: await loadHistory("/api/chat", threadId),
});

React: an assistant panel

Two pieces make a working assistant: useAssistant (the behaviour) and AssistantPanel (the layout). Everything else is optional. Against the createChat endpoint above:

import { useAssistant } from "nitrolus/react";
import { AssistantInspector, AssistantPanel } from "nitrolus/ui";
import "nitrolus/ui/styles.css";
import { manifest } from "./tools.gen"; // nitrolus generate

function Helper({ lessonId }: { lessonId: string }) {
  const assistant = useAssistant({
    api: "/api/chat",
    context: () => ({ lessonId }), // checked by createChat's `context`
    tools: manifest, // built-in tool cards, `/` commands
  });
  return (
    <>
      <AssistantPanel
        assistant={assistant}
        brand="Helper"
        empty={{ title: "Ask me anything" }}
      />
      {import.meta.env.DEV && <AssistantInspector assistant={assistant} />}
    </>
  );
}

That panel already has a header with new chat and fullscreen buttons, the empty state, a thread whose tool calls show with the built-in cards, a message box with Enter-to-send and Stop, follow-up suggestions (data-suggestion parts), and a conversation that survives the panel closing and reopening. A question the model asks continues the turn once answered. Each request carries the page context, the chat's title, the page's readables (useChatReadable, which createChat gives the model with that turn only) and the turn's toolChoice.

A runnable example is in examples/tutor/nitrolus: a lesson page with a SQL tutor beside it (21 tools, real queries, code walkthroughs), offline with a demo model or live through OpenRouter. The same app is rebuilt with Mastra, CopilotKit, the AI SDK and TanStack AI next to it: each took 5.5 to 6 times the code (examples/tutor/COMPARISON.md).

AssistantInspector is a developer panel for one assistant: its state, each message's parts, every request with its body and status, each turn's timeline (model and tool calls on one axis, time to first token, tokens, cache reuse and cost, with createChat({ trace: true })), the chat's recordings, and what the page sends. Render it in development only.

useAssistant options, all optional but api:

Option What it does
chatKey Where the conversation is kept, e.g. lesson:42: each key has its own, and a new one starts a new chat
context: () => page The page the user is on, sent as context with each request
tools: manifest The generated manifest: tool cards in the default thread, / commands, answered questions continue the turn
body: () => ({ ... }) Extra request data, read at each send
headers Request headers; a function is called per request (fresh tokens)
request: "messages" Send the whole transcript with id, for a stateless server (default thread: only the new message)
initial: { messages, title, chatId } Start from a conversation; a chatId alone loads it from the server
persist: false Start fresh on every mount
allowed Whether the user may send (e.g. their plan); onRefused says why a send didn't go out
clientTools Handlers for tools that run in the browser (execution: 'client'), by name: clientTools<ToolTypes>({ 'open-size-guide': ({ productId }) => ui.open(productId) }). The result goes back to the server, which checks it like an answer, and the turn continues; a handler that throws fails the call and the model hears why
commands The / commands (by default each tool's command: its hint beside the name, and an icon and colour that fit, or its own icon and tone); prefill(text, toolChoice) picks one by name
mentions What @ can add to a message ({ id, title, source }), or 'server' to load it from createChat's mentions.list for the page, so it's defined once. Picked items show as chips on the message and go to the server on metadata.mentions
attachments: { policy, upload, fileUrl, toolChoice } Check, read and upload files before the turn goes out, and show sent ones. chatAttachments(api) sets upload and fileUrl for a createChat endpoint with attachments on. Without attachments, the panel has no attach button
emptyReply, busy, sendAutomaticallyWhen Retry empty replies; hold sends while a question waits for its answer; continue after tool answers
beforeSend Check or prepare a turn before it goes out; resolve false to keep it
onSend, onData, onFinish, onFailure Analytics, data parts, each turn's outcome, failures with a retry

It returns the chat state (messages, status, isStreaming, uploading, suggestions, canType, canSend) and its actions: send(text, { files, toolChoice }), submit() (the message box), prefill, edit, stop, answer (a question tool call), newChat, setMessages, and the panels: history (open, toggle, select(conversation or id), which loads an id from the server), outputs and stage (open, close, fullscreen, and a context for results in the thread).

Out of the box the panel looks like a finished product:

  • Panel and header: a soft glow falls from the top of the panel, and the header shows the avatar beside a text brand.
  • Empty state: the avatar sits above the greeting with a halo behind it.
  • Messages: the user's messages are lit bubbles with copy and, on the latest one, edit. The assistant's replies are open markdown with copy.
  • Tool calls and reasoning: a reasoning model's thinking shows as a live "Thinking..." step (then "Thought it through"), so a long think isn't a blank wait. Each run of steps folds into one line showing the latest step, with +N to expand to all of them, as AB does. An activity tool is always a line. A tool with a card shows as a line while it runs or if it fails; once done its line stays in the steps and its card follows them. Lines use the tool's ui.labels (builtinUi(component, { labels }) for card tools), or labels made from its name. Only final results show as cards, as in AB: a tool marked ui.lookup (a fetch, a search, a query on the way to an answer) stays a line while the reply streams and whenever a later call shows another tool's card or asks a question.
  • While waiting: a thinking line shows the avatar, or the /command the turn was sent with. A button brings you back to the latest message after you scroll up.
  • Message box: MessageComposer in a glowing ring, with the hook's / commands, attachments, dictation and the reply's suggestions as chips.

avatar replaces the default spark, or pass null for none. AssistantThread is the same thread on its own, for a layout of your own.

AssistantPanel takes your own part wherever the product needs one:

<AssistantPanel
  assistant={assistant}
  brand={<Logo />}
  meta={<CreditsLeft />}
  actions={{ fullscreen: isDesktop }}
  renderers={{ "add-to-cart": CartCard }} // or conversation={<Thread />}
  Markdown={ReplyText} // the assistant's text; the built-in Markdown by default
  composer={<MyComposer composer={assistant.composer} onSubmit={assistant.submit} />}
  empty={{ title: "Hi!", starters }}
  history={<HistoryList onSelect={assistant.history.select} />}
  outputs={{ items: results, render: (r) => <Card result={r} />, empty: "Nothing yet" }}
  stage={(item, close) => <Player item={item} onClose={close} />}
/>

On a phone, or anywhere the chat shouldn't take a column, AssistantSheet puts the same panel in a sheet that a floating button opens. It slides in from the right on a wide screen and up from the bottom on mobile, where the handle drags it between heights. It takes AssistantPanel's props, plus open/onOpenChange to drive it yourself, launcher={false} for no button and modal for a backdrop. The page stays usable by default, so the assistant can read what the user does there. It opens when a turn starts (e.g. a button on the page calls assistant.send). Closing only hides it: a reply keeps streaming. With mobile, an opened result such as a walkthrough fills the chat window in the thread's place instead of opening beside it, and the fullscreen button is hidden:

AssistantLauncher is that floating button on its own, to open an AssistantPanel in a layout of yours. Keep the open state in your page and both work the same way:

const mobile = useMediaQuery("(max-width: 800px)"); // nitrolus/react
const assistant = useAssistant({ api: "/api/chat", mobile });
const [open, setOpen] = useState(false);
const panel = { assistant, brand: "Tutor", empty: { title: "Ask me" } };

if (mobile) return <AssistantSheet {...panel} open={open} onOpenChange={setOpen} />;
return open ? (
  <aside className="chat">
    <AssistantPanel {...panel} onClose={() => setOpen(false)} />
  </aside>
) : (
  <AssistantLauncher label="Open Tutor" onClick={() => setOpen(true)} />
);

The pieces underneath are exported too, for a layout of your own: ChatShell (the layout, with theme and layout), ChatHeader with chatHeaderActions, ChatEmptyState, ChatOutputs, ChatTranscript, ChatComposer, and the hooks useAssistant builds on:

  • useChatSession(initialMessages, context): which conversation is open, its title, and the history panel, kept in a session cache.
  • useAssistantChat({ id, transport, ... }): a SharedChat with empty-reply retries, failed turns offered back as a Retry, uploads before sending, and the session cache kept current.
  • useChatStage({ chatId, mobile }): fullscreen and a result opened beside the thread (in its place with mobile); Escape closes the stage first.
  • useComposerState(): the message box's text, files, pasted snippets, / command and @ mentions, with prefill, message() and reset().

Page context for the model: useChatReadable({ description, value }) from nitrolus/react registers what a component shows, getChatReadables() collects it for the request, and the server's withChatContext(messages, pageContext, pageState) (nitrolus/server, with renderReadables and promptBlock) puts it in the conversation without touching the cached system prompt.

For app-owned message renderers, ChatTranscript supplies stable message keys and identifies the streaming message and most recent user message. ChatComposer provides a controlled textarea with Enter-to-send and a stop action while streaming; both accept app renderers and class names:

import { ChatComposer, ChatTranscript } from "nitrolus/react";

<ChatTranscript
  messages={messages}
  status={status}
  renderMessage={(message, state) => (
    <ProductMessage
      message={message}
      isStreaming={state.isStreaming}
      isLastUserMessage={state.isLastUserMessage}
    />
  )}
/>;

<ChatComposer
  value={input}
  onChange={setInput}
  onSubmit={handleSubmit}
  status={status}
  onStop={stop}
/>;

Tools

import * as z from "zod";
import { defineTool, sealed, createManifest } from "nitrolus";

export const quiz = defineTool({
  name: "quiz",
  description: "Asks the user a quiz question about the lesson.",
  input: z.object({ topic: z.string() }),
  output: z.object({
    question: z.string(),
    options: z.array(z.string()),
    correctIndex: sealed(z.number()), // never reaches the model or the browser
    answered: z.number().optional(),
  }),
  execute: async ({ topic }, { db }: Ctx) => db.makeQuestion(topic),
  outcome: "execution",
  actions: {
    // A card button. It runs on the server against the stored output.
    grade: {
      input: z.object({ choice: z.number() }),
      output: z.object({ correct: z.boolean() }),
      run: async ({ choice }, { output, update }) => {
        update({ ...output, answered: choice });
        return { correct: choice === output.correctIndex };
      },
    },
  },
  ui: { kind: "card" },
  effects: { invalidates: ["progress"] },
  command: { slash: "quiz", hint: "Test yourself", icon: "question", tone: "warning" },
  availableOn: ["lesson"],
});

const manifest = createManifest([quiz /* , ... */]);

What each field does:

  • No execute: a tool without execute is a human tool, which the user answers in the chat. With execution: 'client' it runs in the browser instead (useAssistant({ clientTools })): opening a panel, scrolling to an item, reading the page.
  • approval: ask the user first: true always, or a rule over the input and the tool's context, approval: (input, ctx) => ctx.price(input) > 500. The call waits in awaiting-approval; the server accepts only the approval it issued.
  • sealed(...) fields: they are stored, but removed from what the model sees, from what is streamed to the browser, from history, and from the generated client types.
  • Sealed tickets: sealed(z.string(), { ticket: true }) gives the model a ticket (sealed:...) in the value's place. A tool whose input field is also sealed(z.string(), { ticket: true }) gets the real value, swapped in on the server, and only for tickets from the same conversation; a made-up ticket fails the call. A card number found by one tool can be charged by another without the model or the browser seeing it. Set createChat({ sealKey }) so tickets stay the same across restarts (and the prompt cache holds).
  • actions: each one is typed from its own input schema. The client calls one with toolActions<ToolTypes>({ api })('quiz', 'grade', { threadId, toolCallId, input }).
  • byRef: for large outputs, byRef: { summary: (o) => \${o.rows.length} rows` }gives the model only a summary and a ref.createChatadds aninspect` tool so the model can read paths, list pages or stretches of text, while the client still gets everything.
  • Input schemas sent to the model: Nitrolus trims $schema, generic safe-integer bounds, and the UUID regex to reduce prompt tokens. Explicit constraints (for example .min(1)) stay in the model-facing schema, and the original Zod validator still checks tool inputs.

Compression (nitrolus/compress)

Tool results are often most of a prompt: query rows, logs, search output, pages. createChat({ compress: true }) gives the model a compressed version of every tool result. The browser and the stored thread keep the full output. Each compressed result says how to read the rest with inspect (ref, path, offset, limit, find).

Each kind of content has its own compressor:

Content What the model gets Saved on samples
Long JSON arrays The first and last items, error items, numeric outliers and an even sample (15 by default), plus per-field statistics. Duplicates are removed and long strings shortened 93–98%
Logs Runs of the same message collapse into one line with a count; errors, warnings and stack frames are kept with context ~99% on repetitive logs
Search results (file:line:text) Grouped by file, a few matches each, with counts 63%
Diffs Changed lines and headers; unchanged context collapses 97%
HTML The text and links, without markup, scripts or styles 80%
CSV and Markdown tables The header and representative rows, with column statistics 94%
Plain text The start and end; the middle is omitted, with a note Cut, not compressed

Sample savings are estimated tokens, measured on synthetic payloads. Each took under 6 ms.

  • Safety rules:
    • Content under 250 tokens is left alone.
    • A result that saves less than 10% is sent unchanged.
    • Tools listed in skip are never compressed.
  • Cache-safe: compression is deterministic. A result compresses the same way every turn, so the history stays byte-identical and keeps the prompt cache.
  • Without createChat: use the compressToolResults({ store }) middleware with memoryCompressionStore(). Add inspectTool((ref) => store.get(ref)) to your tools.

The approach follows Headroom: content-aware compression, markers, and retrieving originals on demand. Headroom compresses prose with a learned model; nitrolus uses only deterministic rules and adds no dependencies.

Code mode: programs that call tools

createChat({ ..., codeMode: true }); // or { route, lazy, limits }
// pnpm add quickjs-emscripten-core @jitl/quickjs-wasmfile-release-sync

The model writes a short JavaScript program that calls tools (run-code), run in a fresh QuickJS sandbox per call: no network, files, timers or modules; limits on time, CPU, memory, calls and sizes. One call does what took several (parallel lookups with Promise.all, filtering, exact arithmetic), and the model only reads what the program returns.

  • The cache holds. The tool list is fixed: the direct tools plus run-code (whose description holds the callable tools as TypeScript signatures), and discover-tools when some are lazy. Lazy tools are listed by name; their signatures come back as a tool result, so finding a tool never changes the tool list or anything earlier in the prompt.
  • What runs where (route): server tools are called from code. Questions, approvals, client tools, page-specific tools, tools whose tainted calls need approval, and tools with a card stay direct, so a chart or a plan still renders. A lookup card tool or a tool with a / command is both.
  • The chat sees every call. A program's calls stream as preliminary results and show as steps in the steps line (ui.innerCalls), and they are stored with the reply. Sealed fields never reach the program.
  • Use it with a capable model. Small models write weaker programs than tool calls; turn it on per chat where it pays.
  • It pays where calls chain and results needn't reach the model. run-code's description costs input tokens on every call. In the tutor example (21 tools, most of them shown as cards, so they stay direct), code mode moved only 3 tools into programs and cost about 35% more input tokens and an extra model call, measured on real DeepSeek turns. Prompts that name a tool which now runs only in code make the model call it directly anyway. It suits agents with many lookups that never show a card, or turns that chain several of them.

Many tools: discovery that keeps the cache

createChat({ ..., discovery: { core: ['search', 'explain'] } });

The model starts with the core tools and find-tools. Tools it finds stay loaded for the thread and are added after the existing ones, never in between, so the cached prompt prefix keeps matching. Choosing tools afresh each turn breaks that prefix, which was measured at about 40% more cost.

Safety: taint and approvals

const fetchPage = defineTool({ name: 'fetch-page', source: 'untrusted', annotations: { readOnly: true }, ... });
const sendEmail = defineTool({ name: 'send-email', annotations: { openWorld: true }, ... });       // approve when tainted
const deleteAccount = defineTool({ name: 'delete-account', taintPolicy: 'deny', ... });             // never when tainted

Once untrusted content is in a step's context, every tool call in that step is tainted. That content is output of a source: 'untrusted' tool or, by default, an attached file. Taint is coarse on purpose, because nobody can follow it through the model's reasoning.

A tainted call follows its tool's taintPolicy:

  • allow: it runs. This is the default for readOnly tools and any tool not covered below.
  • approve: it waits for the user's approval. This is the default for destructive and openWorld tools.
  • deny: it fails, and the model is told why.

Approvals work the way questions do. The call stops in awaiting-approval, and the registry shows ToolApproval (from nitrolus/ui). The user's answer goes back through onApprove, which is addToolApprovalResponse with useChat. The server accepts it only for the approval id it issued. A tool can also ask whatever the taint, with its approval rule (true, or a function of the input and the tool's context).

Speculative prefetch

defineTool({
  annotations: { readOnly: true, idempotent: true }, // required for prefetch
  input: z.object({ query: z.string(), filters: Filters.optional() }),
  prefetch: {
    when: ["/query"],
    run: (partial, ctx) => search(partial.query!, { signal: ctx.signal }),
  },
  execute: async ({ filters }, { prefetched }) =>
    applyFilters(await prefetched, filters),
});

The work starts once /query has finished streaming, while the model is still writing the rest. execute reuses it when the final input matches on the when paths. Otherwise it is cancelled and run again. onResult reports the hit rate and the time saved.

Live replies: other tabs, observers, resume and steering

  • One reply at a time per thread. A message sent while a reply streams waits for it by default (mode: 'queue'). mode: 'interrupt' stops the running reply and starts the new one. mode: 'steer' adds the message to the running reply at its next step, without restarting it (single-pass engine).
  • Others can follow a live reply. GET /stream?threadId= replays what was streamed so far and then follows live. Each chunk is encoded once and written to every follower. This serves another tab, a dropped client resuming (useChat({ resume: true })) or an observer. threadEvents(api, threadId) from nitrolus/client follows every reply on the thread.
  • Shared threads. access: (user, thread) => 'participant' | 'observer' | null lets others in. Participants write, answer and approve; observers only read. Sealed fields stay sealed for everyone. This needs a ThreadStore with find (memory and Postgres have it).
  • Disconnects. onDisconnect: 'continue' keeps a reply running after the sender disconnects, so it can resume.
  • Several servers. The run hub is in memory per process by default. live: redisRunHub(ioredisPort(redis)) follows replies across servers: one reply at a time per thread whichever server gets the message, and any server can follow, stop or steer it. A crashed server's lock expires (lockMs).
  • Saves never overwrite each other. A save based on a stale copy is refused (ThreadConflictError), and a turn puts its messages on top of the newer thread.

Engine: ai-sdk or single-pass

createChat({ engine: 'single-pass' }) runs nitrolus's own loop. Each step is one model call, and its parts become UI chunks in one pass. Tools start as soon as their input is complete, and the stored message is built along the way. Approvals, answers and steering messages are read at step boundaries.

Like streamText, it keeps each part's provider metadata (Anthropic's thinking signatures, Gemini's thought signatures, OpenAI's reasoning ids) on the stored parts and sends it back on the next step and the next turn, and it tries a model call again on a retryable error (rate limit, overload, a 5xx) after the provider's retry-after (maxRetries, default 2, on both engines). A tool's input is kept as text while it streams and parsed once, when the call is complete: a 1,600-field input took 17 ms of server work against about 620 ms through streamText, which parses the whole input on every delta.

Both engines pass the same test suite. On 20,000 streamed chunks the single-pass engine took about 73 ms against about 355 ms through streamText (warm runs, Node, mock model). The default is still ai-sdk.

Context

import { defineContext } from "nitrolus";

const page = defineContext({
  schema: z.object({ questionId: z.string(), userId: z.string().optional() }),
  reserved: ["userId"], // set by the server; a client value is dropped
  resolve: async ({ questionId }, req) =>
    questions.forUser(questionId, req.user), // checks access
});

Storage and limits (nitrolus/server)

Export What it does
postgresThreadStore(db), postgresThreadSchema() Threads in Postgres: only the owner reads or replaces a thread, and a continuation is taken once, atomically
knexQuery(knex), prismaQuery(prisma) Run the Postgres stores on Knex or Prisma (any { query(text, params) } works, e.g. pg or PGlite)
memoryAllowance, postgresAllowance(db, { limit, period }) Allowances per day, week or month, with a limit per user or plan. Parallel requests can't go past the limit
memoryAttachmentStore(), AttachmentStore Attachments are stored under the hash of their bytes. Uploads are checked by type, size and first bytes. The model gets a signed URL or the bytes; the thread keeps only the reference
defineWorkflow, workflowRunner(store), postgresRunStore Long tasks in steps. Step results are stored, so after a restart finished steps don't run again. Steps can retry, and a run can waitFor a person
threadPolicies, verifiedHumanTools, Meter, pickFields, renderPromptTemplate, firstStepTools The lower-level pieces createChat is built from, for custom endpoints
redisThreadStore(port), redisRunHub(port) Threads in Redis (versioned saves, a continuation taken once, optional ttlSeconds) and live replies across servers. ioredisPort(client) or nodeRedisPort(client, subscriber) adapt the client; memoryRedisPort() is one in memory for tests
drizzleQuery(db) Run the Postgres stores on Drizzle (node-postgres, PGlite or postgres.js underneath)
toAgUiEvents, agUiResponse Serve a run over the AG-UI protocol, for AG-UI clients such as CopilotKit
realtimeTools(tools, context) The same server tools for a realtime voice session. Input is checked, and sealed fields stay out of what is spoken

nitrolus/server runs on Node. On Workers or Deno, createChat needs node:crypto (nodejs_compat); toNodeHandler is Node-only.

Feature modules

Ready-made versions of the features most in-product assistants end up building by hand. Each has a store port with memory and Postgres implementations; the Postgres ones work through pg, Knex or Prisma.

HTML artifacts (nitrolus/artifacts, nitrolus/artifacts/react)

The model makes interactive pages: a chart, a cheat sheet, a small calculator.

const runtime = artifactRuntime({ theme: myTheme }); // your design tokens, light and dark
const { tools } = artifactTools({
  store: postgresArtifactStore(pool, { blobs: myR2 }),
  runtime,
  model,
  templates: [chartTemplate],
});
// toolContext: ({ user }) => ({ ownerId: user.id, threadId, artifactTurn: artifactTurn() })
  • Generate → validate → repair. The model writes a whole page, or fills a reviewed template with data. Problems go back to it as diagnostics: three tries for pages, two for templates. Page repairs come back as SEARCH/REPLACE edit blocks, so a fix costs a few hundred tokens instead of the whole page again (applyEdits). Edits that can't be placed are reported by number. Input, output and time budgets come back as plain failures, never thrown errors.
  • What the validator checks (on the tree a browser builds, via parse5):
    • It's a complete document. A fenced page is taken from the prose around it, prose after </html> is dropped, and missing boilerplate (doctype, lang, title, viewport) is filled in instead of costing a repair.
    • Markup slips are normalized the way the browser fixes them; duplicate ids and markup nested deeper than 256 levels are errors.
    • Nothing loads from outside; images are inline data: only.
    • No frames, forms, on* handlers or meta http-equiv.
    • Scripts don't use network, navigation, storage, eval or Function, found with a scope-aware walk of the parsed script (acorn), so a local const top = 4 is fine.
    • CSS doesn't redefine the theme variables or use prefers-color-scheme (read with a spec-compliant tokenizer).
    • Each diagnostic has a log-safe rule and a message for the model.
  • What prepareArtifact injects:
    • Libraries first (e.g. a chart library), then the theme layer: variables, base type and zero-specificity components (<prefix>-card, -btn, -table, -callout, -stat, -field...), and window.Artifact.color() / onThemeChange(). Chart.js, when present, follows the theme.
    • A readability guard that switches theme when text is unreadable.
    • A content security policy before them that allows only the page's scripts, by hash of their normalized text.
  • Storage:
    • Revisions with conflict checks and idempotent tool calls.
    • Integrity checks on read.
    • Optional object storage with an upload-intent and cleanup queue (sweep()).
  • Viewing:
    • viewerShellHtml() and VIEWER_SHELL_HEADERS run the page inside two nested sandboxes with an opaque origin.
    • ArtifactViewer adds revisions, theme switching and download.
    • artifactCard is the tool card: by default a lit card (name, revision) that opens the page in a modal dialog, as AB shows pages; display: "inline" puts the viewer in the thread. ArtifactOpenCard and ArtifactDialog are exported for your own.
  • Routes: artifactRoutes covers list, read, revisions, content, rename and delete.
  • Budget and deadline per turn:
    • artifactTurn({ deadline }) shares one call budget (artifactCallBudget(), 5 by default) across every create and revise in a chat turn. Retries count, so asking again never starts a fresh budget.
    • No call starts that couldn't finish before the turn ends (a deadline failure). Each call's limit is cut to the time left.
    • A 429 or 5xx is retried once, after the provider's retry-after (retryDelay).
    • When repairs run out, one fresh, simpler pass is told the problems (recovery).
    • Repair prompts drop the conversation and page data.
    • reasoningOff resends an attempt once without reasoning when reasoning ate the whole output budget. needsReasoning (default needsCalculation, a word-list heuristic) keeps reasoning for requests that need it.
    • onRun reports calls, tokens (cached input included) and cost per request.
  • One visual per question: createVisualTurnGuard() in the tool context lets the first of a code walkthrough or a visual explainer claim the turn. The other comes back as { success: false, skipped: 'duplicate-visual' }, counts as neither a success nor a failure, and artifactCard renders nothing for it.

Scene kit: animated explainers

With artifactRuntime({ kit: true }), a page can be an autoplaying explainer instead of hand-built HTML. The model writes one JSON scene script (<script type="application/json" id="<prefix>-scenes">) and, when a step needs one, small drawings registered with Kit.register('name', async (ctx, args) => …). The kit plays it as a film, a step-by-step walkthrough or a single snapshot. It has captions, pause, scrubbing, replay, reduced motion and a phone layout, so pages stop reimplementing players and controls.

artifactRuntime({ kit: true });                                    // core: charts of stated numbers, code, drawings, 3D
artifactRuntime({ kit: { packs: [dataPack()] } });                 // + tables computed with a PostgreSQL subset, datasets, distributions, compare
artifactRuntime({ kit: { packs: [dataPack({ datasets: mine })], global: 'Kit', three: false } });
  • One compiler (compileStoredScript) runs in the validator and in the browser, so both accept exactly the same scripts. The data pack computes every table result, so the model never writes results by hand. Limits are errors, never truncation. Without a pack, a script that uses its objects gets a diagnostic naming the pack.

  • Validation:

    • every called drawing is registered with a literal name;
    • no timers (motion goes through ctx.wait, ctx.tween and ctx.animate, so pause and seek stay deterministic);
    • no endless loops;
    • motion longer than the per-drawing limit is rejected;
    • 3D needs <meta name="<prefix>-kit" content="three"> and draws through ctx.three.

    Diagnostics have log-safe rules such as kit-scene-column:unknown-column@objects.on.

  • Injection:

    • The runtime goes in only for pages that use it, after the theme layer. Three.js goes in only for 3D scenes, and a 3D page leaves out libraries whose declared global it doesn't read, to stay under 1 MiB.
    • The runtime version records it (…/kit@1/three@0.186.1/<prefix>-html-v1).
    • Pages without the kit are prepared byte for byte as before.
  • Prompt: generation adds kitInstructions(names, { packs }) for new pages and explainer revisions. Drawing rules are added only when the request or a draft draws (needsDrawing, drawsCustom). A test keeps the prompt in step with the compiler.

  • Viewer timeline: the page reports playback (<namespace>:playback, numbers only). ArtifactViewer shows the steps as a segmented timeline in its header, and the page then hides its own progress. Older viewers keep the in-page progress.

  • Names: KitNames (global, prefix, namespace, themeGlobal) follow the runtime, with the Nitrolus defaults Kit, nl (--nl-*, #nl-scenes), so an app that sets its own keeps them in its pages.

  • Building: after changing src/artifacts/kit/{core,runtime,three}, run pnpm build:kit and commit the generated JSON. A test fails while it is stale.

OpenUI pages (nitrolus/openui, nitrolus/openui/react, nitrolus/openui/build)

Instead of writing a whole HTML page, the model can write a short OpenUI Lang program against your component catalog. Measured on one production app with a fast model, against HTML:

  • less than half the output tokens and cost;
  • about twice as fast;
  • programs parsed without errors.

Most failures of the HTML path were models wrapping the page in prose. extractFenced now handles that for both paths.

// In the app that owns the components (build step):
const spec = librarySpec(openuiLibrary, { version: 1 });        // → library.spec.json
// vite.openui.config.ts: build the entry below with openuiRuntimePlugin({ runtime: spec.runtime }) → runtime.json
mountOpenUIStandalone({ library: openuiLibrary, catalogVersion: 1 });

// On the server:
const format = openuiFormat({ spec, runtime, preamble: myProductPreamble });
artifactTools({ store, runtime: artifactRuntime(), model, format, templates: [chartTemplate],
  providerOptions: (attempt, { name, request }) => attempt === 1 && !needsCalculation(`${name} ${request}`) ? noReasoning : lowReasoning });

// In the app:
<ArtifactViewer ... renderNative={openuiNative({ library: openuiLibrary, catalogVersion: 1 })} />
  • The prompt is generated from the catalog by lang-core. Edit Mode is always on, so the prompt is the same for every request and caches. Default rules forbid queries, mutations and outside actions: buttons only use @Set/@Reset, and pages work offline.

  • Checks: the catalog's parser, an existing root, and all names defined. Forbidden steps are found in the parsed tree, so a step named in a string doesn't count. There's a 64 KiB limit. Problems go back as OpenUI <code>: .... Revisions and repairs are Edit Mode patches merged by statement name.

  • Storage: a self-contained page. The program is JSON in #openui-program, the standalone runtime is inlined, and a hash-only CSP allows just that runtime. It works as a download, and the viewer renders the program natively in the app with its theme.

  • Kinds in artifactTools:

    • custom uses the format, and is the default;
    • html stays for bespoke visuals;
    • templates are listed by name.

    A revision keeps its kind unless another is asked for. Converting between kinds sends the old page as sourceArtifact.

  • Catalog versions: props are positional, so reordering them breaks old programs; bump the catalog version when you do. Pages made with a newer catalog ask for a reload.

  • Install: OpenUI is optional. Install @openuidev/lang-core (server) and @openuidev/react-lang (app) to use it. lang-core sends install telemetry from a postinstall script unless OPENUI_TELEMETRY_DISABLED=1 or DO_NOT_TRACK=1 is set.

Retrieval (nitrolus/retrieval)

const embed = embedder({
  model: openrouter.embedding("qwen/qwen3-embedding-8b"),
  dimensions: 1536,
  queryPrefix: "Query: ",
});
const index = indexer({ embedder: embed, store: pgvectorStore(pool) });
await index.index({
  type: "lesson",
  id,
  header: `Lesson: ${title}`,
  text: transcript,
}); // skipped if unchanged
const results = await hybridSearch(query, {
  embedder: embed,
  store,
  keyword: myTagSearch,
  refine: { relevance: { model: fast }, rerank },
});
  • Chunking: sentence-aware, with overlap.
  • Embedding: batched; query embeddings are cached and have a timeout.
  • Change detection: a content hash means only changed items are re-embedded.
  • Stores: memory, or pgvector with an HNSW index.
  • Hybrid search: vector results merged with your own keyword, tag or full-text scores. An optional relevance check by a model and a reranker both fail open.

Working memory (nitrolus/memory)

const memory = defineMemory({
  schema: LearnerProfile,
  store: postgresMemoryStore(pool),
  notes: { kinds: ["struggle", "milestone", "fact"] },
});
tools: [memory.tool()]; // `remember`: merge patches, null forgets, notes by id
const block = await memory.prompt(user.id); // put it in the messages, not the system prompt
  • Schema-checked: every update is checked against the schema and a size limit.
  • Concurrent writes: retried on a version number, so parallel turns don't lose updates.
  • Notes: capped, and de-duplicated.
  • Never blocks a turn: loading memory fails open.

Judging (nitrolus/judge)

Export For
defineRubric, evaluate Rubric grading: per-criterion scores with evidence and feedback. The weighted total and pass mark are computed in code
defineDecisions Several questions about one input in one call: yes/no with a probability, a choice, or a score. Covers guardrails, safety gating and triage. You choose whether failure lets the request through or blocks it, and set a timeout and a cache
defineClassifier, guardrail Pick one label, with a confidence. guardrail plugs into createChat({ guards }) and refuses a message before anything is counted
gradeAnswers Batched grading of short written answers. If it fails, every answer counts as wrong

Generation (nitrolus/generation)

Export For
repairLoop Generate, check and repair a result with diagnostics between tries
retryUntil Retry a checkable operation up to a fixed attempt count
createAttemptBudget Track failed attempts by key while leaving results product-owned

Agents (nitrolus/agents)

const agents = agentRegistry({ store: postgresAgentStore(pool) });
const { agent, system } = await agents.promptFor(
  page.kind,
  `${page.kind}:${page.id}`,
  () => loadTemplateData(page),
);
app.use(
  "/admin/agents",
  toNodeHandler(agentAdminHandler(agents, { authorize: isAdmin })),
);
  • What an agent holds: prompt templates (Handlebars), the pages it serves, a default flag, a model id, allowed tools and settings.
  • Lookup: the default agent for the page, then the most recently updated, then the general agent.
  • Cached prompts: rendered prompts are cached per page and cleared on every save.
  • Admin routes: list, read, save, delete and preview. The preview reports template variables the sample data is missing.

Chat hooks

  • guards: refuse a message before any work, with HTTP 422.
  • enrich: add data parts once the reply is done, such as suggestions or a mood, stored with the reply.

Helper agents

import { helperAgent } from "nitrolus/agents";

const returns = helperAgent({
  name: "returns-specialist",
  description: "Checks whether an order can be returned.",
  model: openai("gpt-5-mini"),
  system: "You check return eligibility. Report what you found in two sentences.",
  tools: [orderLookup, returnPolicy],
});
createChat({ tools: [returns, ...], ... });

The main agent hands a job to a specialist as a tool call and stays the voice the user talks to: the helper runs with its own instructions, model and tools, its calls show as steps in the chat while it works, and the main agent reads its answer. Its tools get the main turn's tool context (and its permission checks). Stopping the main reply stops the helper.

Long chats

createChat({ compact: true }) condenses a long thread instead of cutting it off. Once the history the model reads passes maxTokens (24,000 by default), the messages before the last keep (6) become a summary, written by the chat's model or a cheaper model, or by your own summarize. The summary is stored on the thread; the screen still shows every message. The model then reads the summary and the recent messages, which stay the same until the next compaction, so the prompt cache keeps matching.

Recorder: replay, rewind and keep as a check

createChat({
  ...,
  recorder: { store: postgresRecordingStore(pool), sample: 1, access: (user) => user.isStaff },
  trace: process.env.NODE_ENV !== "production", // timelines in AssistantInspector
  pricing: { input: 0.3, cachedInput: 0.03, output: 1.2 }, // $ per million tokens
});
  • Every turn is kept (or a sample): its messages, a tape of every model and tool call, and its timeline, tokens, cache use and cost. redact takes out what shouldn't be kept. chat.report(threadId) labels a thread's latest turn reported, from your own "report a problem" endpoint.
  • Developers read them at GET /recordings?threadId= (or ?label=reported, ?since=), allowed by access. AssistantInspector's Trace tab lists the open chat's recordings and saves one as a check.
  • Replay with rerun(recording): the recorded replies stand in for the model (free, the same every time), with your tools' current code if you pass tools. Pass model and system to try a fix, and forkAt to replay up to the step that went wrong and go live from there. It returns what the run did and how it differs (diff).
  • Keep it as a check: an eval file is a recording plus what it must do (expect: { calls, neverCalls, says, neverSays, atMostSteps, atMostTokens }). nitrolus eval runs a folder of them; without expect, a case reports whether the run changed.
nitrolus recordings --url https://app.example.com/api/chat/recordings --since 7d \
  --header "Authorization: Bearer $TOKEN" --out evals/last-week
nitrolus eval evals/last-week --config fix.mjs           # try a fix on last week's real conversations
nitrolus eval evals --out report.json --baseline main.json --max-drop 0.05   # CI: block a worse release

fix.mjs's default export sets { model, system, tools, checks } for the run, or is a function of each recording that returns them.

Engine (nitrolus/engine)

AI SDK model middlewares and wrappers. Use them with wrapLanguageModel.

Export What it does
recordModel(tape), recordTools(tools, tape) Record a run, including every model call and tool result, as JSON
replayModel(tape), replayTools(tools, tape) Replay it with no network and no tool running, so a bug report becomes a test
replayModel(tape, { atStep, live }), diffTapes(a, b) Fork a real conversation at a step with a new prompt or model, and diff what changed. CLI: nitrolus diff a.json b.json
failFast({ tools, guards }) Checks each value of a streaming tool call, at any depth, as soon as it's complete; guards can target nested paths like /steps/*/lessonId. On the first bad value it cancels the request and re-runs the step with the problem, instead of paying for the whole call
cacheLayout(), cacheStats(onStats), lintPromptCache(...) A stable tool order and cache breakpoints (Anthropic, Bedrock, OpenRouter), the cache hit ratio per call, and a lint for what breaks caching
route({ primary, backups, hedge, failover }) Hedged requests: a backup starts when the first token is late, the first answer wins, the other is cancelled. Failover before or during an answer; a cut-off answer is continued in the same text part
traceModel, traceTools, toOtel(tracer) Spans for model calls (time to first token, tokens, cached tokens) and tool calls, plain or OpenTelemetry
runEvals(cases, run), expectRun.* Behaviour budgets (calls this tool, never says that, at most N steps or tokens), run against live models or tapes

Client

Generate the client module from the server's manifest:

npx nitrolus generate --manifest https://api.example.com/api/chat/manifest --out src/ai/nitrolus.gen.ts
import { createToolRegistry, groupParts } from "nitrolus/react";
import { builtinRenderers, ActivityLine } from "nitrolus/ui";
import { useToolEffects } from "nitrolus/query";
import { manifest, type ToolTypes } from "./nitrolus.gen";
import "nitrolus/ui/styles.css";

const { ToolPart, isGrouped } = createToolRegistry<ToolTypes>(
  manifest,
  { quiz: QuizCard }, // only tools with a custom card need a renderer, each typed
  { builtins: builtinRenderers, Activity: ActivityLine },
);

Every call has the same lifecycle (status): streaming-input, running or awaiting-answer, then done, failed or denied.

Your own tool runtime? Describe each tool as a ToolContract (name, description, input, and optionally output, ui, effects, command) and serve createManifest(contracts): no defineTool needed. Wording a template can't express goes in the registry's labels, by tool: createToolRegistry(manifest, renderers, { labels: { bookmark: ({ status, input }) => ... } }).

Effects refresh what a finished call changed. A tag can carry conditions, { tag: 'decks', when: { 'output.success': true }, unless: { 'output.action': 'list' } }, and a tag whose {{placeholder}} has no value is skipped. Without a manifest, pass useToolEffects (or createToolEffects) a plain { tool: tags } map.

Calls waiting for approval show Approval (ToolApproval from nitrolus/ui); pass onApprove to ToolPart.

Other frameworks:

  • Shared core: createToolResolver(manifest) from nitrolus/client says how each part shows (custom, builtin with props, activity with its label, approval, fallback or hidden). The React registry is built on it.
  • Vue: nitrolus/vue has createToolPart(manifest, { components, builtins }) and useSharedChat(chat).
  • Svelte: nitrolus/svelte has chatStore(chat), a Svelte store, plus the resolver.
  • Built-in UIs: the built-in components are React. Any app gets the whole panel with mountAssistant(element, { options, panel }) from nitrolus/ui/mount; Vue has it as <NitrolusAssistant :options :panel /> (with send exposed) and Svelte as <div use:assistant={props} />. React runs inside and loads only when it mounts.

Long threads: SharedChat (from nitrolus/client) and useSharedChat keep the chat in a store that copies only the parts that changed. The AI SDK's React state deep-clones the message on every chunk. Streaming 2,000 deltas after a 300 KB tool output took 2,836 ms that way, and 5 ms here (pnpm bench, one run, Node). Unchanged parts keep their identity, so memoized part components don't re-render.

Chat UI and theming (nitrolus/ui)

Ready-made pieces for a chat thread, styled on the --nl-* variables:

  • Card (with CardBody, CardHeader, CardTitle, CardImage, CardSection, CardPoints, CardProgress), ResourceCard, StageReferenceCard;
  • Chip, LevelChip, TopicChips, IconTile;
  • ResultTable (sorting, show more, copy as cells, rows that appear while the model streams) and readTable for half-streamed input;
  • SingleChoiceQuestion, MultiChoiceQuestion, TextQuestion;
  • StatusLine, StepsGroup with uniqueSteps, ThinkingIndicator and TypingDots;
  • ChatHeader, chatHeaderActions, ChatEmptyState and ChatOutputs for the panel around them;
  • MessageComposer: the message box, with / commands and @ mentions (menu and chips), pasted code and markdown as cards (coloured through the kit's codeLines), attached files, dictation (useSpeechInput from nitrolus/react) and Stop while a reply streams; SuggestionChips, MentionChip and PastedSnippetCard on their own;
  • Attachments with Attachment, AttachmentPreview, AttachmentInfo and AttachmentRemove (grid, inline or list); private files resolve through the kit's useAttachmentUrl.

The composer and attachments keep their defaults in @layer nitrolus, so an app's own classes for their parts always win over them.

Markdown

Markdown renders the assistant's replies in AssistantPanel's default thread and the quiz's text. It's built on TanStack Markdown, about 7 KB gzipped with no dependencies of its own.

  • Safe: it renders React elements, never innerHTML. Raw HTML shows as text, and unsafe link protocols such as javascript: are removed.
  • Streaming: each top-level block is memoized, so while a reply streams only the block being written renders again. An open code fence shows as code as it arrives, and a half-started list item or heading is held back. An unclosed ** or link shows as typed until it closes.
  • Supported syntax: headings, emphasis, strikethrough, inline code, code blocks, lists and task lists, tables (they scroll inside the message), blockquotes, links, images and footnotes. It isn't a complete CommonMark or GFM parser.
  • Links: they open in a new tab.
  • inline: renders a single paragraph without a <p>, for titles and labels.
  • components: replaces the element for any tag (a, pre, table, ...).

Code blocks are plain unless you pass a highlighter. TanStack Highlight adds about 5 KB gzipped for six languages; import only the ones you need. Its colours follow the theme through the --nl-code-* variables:

import { createHighlighter } from '@tanstack/highlight/core';
import { sql } from '@tanstack/highlight/languages/sql';
import { createTanStackMarkdownHighlighter } from '@tanstack/highlight/markdown';
import { AssistantPanel, Markdown } from 'nitrolus/ui';

const highlighter = createTanStackMarkdownHighlighter(createHighlighter({ languages: [sql] }));
// Defined outside render, so the thread keeps its memoized blocks.
const ReplyText = ({ value }: { value: string }) => <Markdown value={value} highlighter={highlighter} />;

<AssistantPanel assistant={assistant} brand="Tutor" Markdown={ReplyText} empty={{ title: 'Ask me' }} />;

Pass any other renderer as Markdown instead, such as Streamdown or your editor's viewer.

nitrolus/openui/explainer builds an OpenUI catalog for interactive explanations: explainerCatalog() is the general core (text, callouts, code in 22 languages, tables, charts, stats, steps, tabs, controls, quizzes), and explainerCatalog({ packs: [dataExplainerPack] }) adds data analysis (@Join, @GroupBy, set-operation Venn diagrams, join row tones). Render a catalog with createExplainerLibrary(catalog) from nitrolus/openui/explainer/react. fullExplainerCatalog and explainerLibrary are core + data, unchanged from before. Load nitrolus/openui/explainer.css with it.

Restyle at three levels:

  1. Variables. Map your design tokens to --nl-* on :root. The defaults have zero specificity, so your mapping always wins.
    • Defaults: zinc neutrals with a violet accent, in light and dark.
    • --nl-glow and --nl-glow-strong: colour the panel's glow, the message box ring, the send key and the avatar.
    • --nl-surface-sheen and --nl-card-shadow: give cards, starters, menus and bubbles their lit edge.
    • .nl-gradient-text: fades a word into the glow, e.g. the assistant's name in the greeting.
    • Pointer spotlight: cards and built-in tool UIs light up near the pointer, with a coloured ring inside the border and a soft wash of colour. One shared listener updates every card in a single frame. Use SpotlightFrame or useSpotlight for elements of your own, or pass your own UiKit.CardFrame to replace it.
  2. Class names. Add your own classes to a part with UiKit.classNames, e.g. { card: 'my-card', 'explainer.code': 'my-code' }.
  3. Parts. Inject your router link, image, card frame, button, tooltip, icons, and the explainer's select, switch, tabs, progress, badge, chart plot and code colouring:
import { UiKitProvider } from 'nitrolus/ui';
import 'nitrolus/ui/styles.css';

<UiKitProvider kit={{ Link: ({ href, ...p }) => <RouterLink to={href} {...p} />, icons: { check: CheckIcon } }}>
  <Chat />
</UiKitProvider>;

Built-in tool UIs

Question tools in every chat. As in AB's chat, createChat gives every chat single-choice-question, multi-choice-question and text-input-question (inputCollectionTools): no execute, so the turn pauses on a card until the user answers, then goes on. They're offered on every step, and beside a forced tool on its first step (toolChoice: "required"), so a slash command can ask what it needs before running instead of guessing. The client knows them even when its manifest is built by hand. A tool of yours with the same name wins; inputCollection: false leaves them out.

Component Role Use it for
option-list The user answers Pick one or several options
text-prompt The user answers A short written answer
approval The user answers Approve or deny an action, with a destructive variant
question-flow The user answers Several questions, one step at a time
single-choice The user answers One question, pick one option (A, B, C... cards)
multi-choice The user answers One question, pick one or more options
text-input The user answers One question answered in words
walkthrough Shows output A code walkthrough played step by step (walkthroughTool(), as AB has it): the code with the running lines lit and the data after each step; a card opens it beside the thread
plan Shows output A checklist with statuses
link-list Shows output Links with context
data-table Shows output Formatted, sortable rows
stats Shows output Key figures with change
chart Shows output A bar or line chart (SVG, with a table for screen readers)
citations Shows output Numbered sources with the quoted passage
code-diff Shows output A line-by-line change to code or text
image-gallery Shows output Images in a grid; select one to see it large
import { askTools, builtinUi, showTool, planSchema } from 'nitrolus/builtins';

const askFormat = askTools.optionList({ name: 'ask-format', description: 'Ask which export format.' });
// Also askTools.singleChoice, .multiChoice and .textInput (output { value }, { values }, { text }, null when skipped).
const studyPlan = defineTool({ ..., output: planSchema, ui: builtinUi('plan') });

// Generative UI from a catalog: the model composes blocks, checked per component.
const show = showTool({ name: 'show', components: ['chart', 'data-table', 'citations'] });

Designing a tool's card, state by state

A call goes through up to seven states: filling in, waiting for an OK, waiting for an answer, working, done, didn't work, declined. Design only the ones that make the tool special; the rest are built in (a status line while it fills in and runs, the approval prompt, the error with Try again, a line when it's declined):

const renderers = toolRenderers<ToolTypes>({
  "add-to-cart": {
    approval: ({ call }) => <ConfirmOrder input={call.input} onAnswer={call.approve} />,
    done: ({ call }) => <CartLine item={call.output!.addedItem} />,
  },
});
<AssistantPanel assistant={assistant} renderers={renderers} />;
  • Every state at once: <ToolPreview tools={manifest} tool="add-to-cart" renderers={renderers} /> shows a card in each state with sample data made from its schemas (sample overrides it), and <ToolGallery> every tool. Put them on a dev route or in a story: designers check cards without the model or the server.
  • A starting point: nitrolus scaffold add-to-cart --manifest <url> --out src/cards writes a typed card with the states that tool needs.
  • Test data: nitrolus generate ... --samples src/ai/samples.ts writes typed sample input and output for every tool; sampleToolPart(tool, status) makes a part in any state.
  • Try again: in AssistantPanel, a failed call in the latest reply offers it (call.retry), which asks for the tool again.

Your own components

Tag the components the model may render, and generate a catalog of their props:

/** @nitrolus.render A step-by-step learning roadmap */
export function RoadmapCard(props: { title: string; steps: RoadmapStep[] }) { … }
npx nitrolus components --src src/components --out src/ai/components.json
// server: props are checked against each component's schema
const render = renderTool({ catalog });
// client: components listed in `streaming` render while their props stream in
builtins: { ...builtinRenderers, render: componentRenderer({ RoadmapCard }, { streaming: ['RoadmapCard'] }) }

Callbacks, React nodes and refs are left out of the schema, because the model can't write them.

Checking changes

nitrolus check --after <manifest> --client src/ai/nitrolus.gen.ts --src src checks the screen against the server before a release: whether the generated module is current (a field the server removed or renamed is listed with the lines that still use it) and whether every card tool has a renderer, with the scaffold command that makes one. It exits 1 when something breaks:

BREAKING  add-to-cart output.quantity: was renamed to "count"; clients that show it will break. 2 place(s) still use "quantity": src/cards/Cart.tsx:14, src/cards/Cart.tsx:31
BREAKING  track-order ui: is a card tool with no screen piece yet. Run "nitrolus scaffold track-order" to create one

nitrolus check --before old-manifest.json --after new-manifest.json lists changes that would break clients built for the old manifest. It exits 1 on a breaking change, so it can run in CI. Breaking changes include:

  • a removed tool, field, action or component prop;
  • a changed type;
  • a newly required field in something the client sends, such as an answer or an action input;
  • prefetch on a tool that isn't readOnly and idempotent.

How they behave:

  • Answering: components the user answers show their controls, then stay as a receipt of the answer.
  • States: while the props are streaming they show a placeholder. Props that don't match the component's schema show as "couldn't be shown", never as something wrong.
  • Styling: no Tailwind or shadcn is needed. Override the --nl-* variables; light and dark mode work through prefers-color-scheme or data-theme.
  • Accessibility: every built-in is checked with axe-core in the tests. Real screen-reader testing is still worth doing in your app.
  • Prop names: props follow assistant-ui's tool-ui field names where they overlap.

Moving from the AI SDK

nitrolus migrate src shows how it would rewrite the AI SDK's tool({ ... }) definitions as defineTools, and --write does it. It gives each tool its name, renames inputSchema, outputSchema and needsApproval, maps abortSignal to signal, and fixes the imports. It lists what it left for you to check, such as a tool without execute (a question or a browser tool now) or tools kept in an object (createChat takes an array).

Status

Version 0.5, not yet published. 847 tests pass, and the 93 server tests pass again with NITROLUS_TEST_ENGINE=single-pass. They include end-to-end turns on mock models, Postgres and pgvector (PGlite), a Node HTTP server, React and Vue in jsdom, and axe-core checks. Real models were tried by hand (the tutor example on DeepSeek through OpenRouter), not in the test suite; the single-pass engine's provider metadata and retries are tested with mock models only.

Not built:

  • Native Vue and Svelte built-in UIs: Vue and Svelte mount the React panel (NitrolusAssistant, use:assistant); there are no Vue or Svelte versions of the components.
  • Rewinding inside the inspector: forking a recording at a step is rerun(recording, { model, forkAt }) in code; the inspector lists and saves recordings but doesn't replay them.
  • Resuming in useAssistant: after a reload, useChat({ resume: true }) with chatTransport follows a reply that is still streaming (with onDisconnect: 'continue' on the server); useAssistant loads the saved conversation but doesn't follow a reply in progress.
  • assistant-ui and MCP: there is no assistant-ui runtime adapter (only the card props share tool-ui's names) and no MCP client or server.
  • The single-pass engine as the default: engine: 'ai-sdk' is still the default.
  • A Redis test against a real server: the Redis hub and store are tested against memoryRedisPort, which emulates their scripts rather than running the Lua.

Speed checks

pnpm bench measures the numbers behind the comparison with the AI SDK, in one process, against the AI SDK path. pnpm bench:check fails when a metric is more than 5% slower than bench/baseline.json (make it on the machine that checks, with NITROLUS_BENCH_UPDATE=1 pnpm bench). The client figures for the AI SDK path use a stand-in that copies the message on every update the way @ai-sdk/react's state does; the server figures run the AI SDK's own streamText, against nitrolus's single-pass engine. One run on a Windows desktop, Node 26:

nitrolus AI SDK path
Server work per streamed word 3.7 µs 15.9 µs
Client work for one long answer after a 300 KB tool result 5 ms 2,836 ms
Client work while a 400-field form fills in 47 ms 437 ms
Stopping the model after the user leaves 0.04 ms
Data sent with the 20th message 0.1 KB 20 KB
Server work while a 1,600-field tool input streams (bench/engine.bench-test.ts) 17 ms 617 ms

Development

pnpm install
pnpm test        # vitest
pnpm bench       # speed checks (bench:check gates on bench/baseline.json)
pnpm typecheck
pnpm build       # dist/

About

The easiest way to build an AI assistant into your product. One kit wires the server, the screen and everything between.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages