Docs React & UI components
DocsSDKs & UIReact & UI components

Embed an agent in your UI

Drop a customer-isolated, approval-gated agent straight into your React or web app in 20 lines—with composable primitives, live tool-call timelines, Generative UI, and file uploads.

Browser-safenrl_bt_... scoped token@norilu/react · @norilu/client
View Markdown
On this page
Live component previewspace: org_acmetoken: nrl_bt_...cap: $0.04 / $0.50v2 pinned
You · usr_42

Refund invoice #1042 for Acme—duplicate charge.

billing-support · v2
Input (redacted){ "invoice_id": "in_1042" }
Output{ "status": "paid", "amount_cents": 4900, "customer": "acme.io" }
Approval requiredstripe.create_refund · call_01J9K

Issue a $49.00 refund to billing@acme.io for duplicate invoice in_1042.

How embedded auth works

Your browser never holds your secret key (NORILU_SECRET_KEY, nrl_sk_...), never needs a separate public API key, and never needs a custom SSE proxy. agentId (agt_...) is a safe public identifier that grants zero access on its own, and browser endpoints (/api/embed/v1/*) accept only short-lived browser tokens (nrl_bt_...) while actively rejecting secret keys with 403:

  1. Your backend authenticates your signed-in user and calls norilu.tokens.create() to mint a short-lived, revocable nrl_bt_... token scoped strictly to (space, user, agent, permissions).
  2. Your frontend passes getToken to <NoriluProvider> or @norilu/client.
  3. Streaming, reconnects, live tool-call details, inline Approve/Deny cards, Generative UI, scoped file uploads & artifacts, and issue reporting flow directly between your UI and Norilu over exact-origin CORS.

1. Mint a scoped token on your backend

Add one authenticated route in your backend. Never trust a space or user ID sent from the browser—derive both from your own session.

// app/api/norilu-token/route.ts
import { Norilu } from "@norilu/server";

const norilu = new Norilu();

export async function POST(req: Request) {
  const { orgId, userId, canApprove } = await requireAppSession(req);

  const { token } = await norilu.tokens.create({
    agentId: "agt_billing_01",
    space: orgId,
    user: userId,
    permissions: canApprove
      ? ["run", "approve", "upload", "feedback"]
      : ["run", "upload", "feedback"],
    ttlSeconds: 300,
  });

  return Response.json({ token });
}
# FastAPI example
from norilu import Norilu

norilu = Norilu()

@app.post("/api/norilu-token")
def create_norilu_token(session = Depends(require_app_session)):
    perms = (
        ["run", "approve", "upload", "feedback"]
        if session.can_approve
        else ["run", "upload", "feedback"]
    )
    result = norilu.tokens.create(
        agent_id="agt_billing_01",
        space=session.org_id,
        user=session.user_id,
        permissions=perms,
        ttl_seconds=300,
    )
    return {"token": result.token}
// net/http handler
func handleNoriluToken(w http.ResponseWriter, r *http.Request) {
	session := requireAppSession(r)
	perms := []norilu.TokenPermission{
		norilu.PermissionRun,
		norilu.PermissionUpload,
		norilu.PermissionFeedback,
	}
	if session.CanApprove {
		perms = append(perms, norilu.PermissionApprove)
	}

	tok, err := client.Tokens.Create(r.Context(), norilu.CreateTokenParams{
		AgentID:     "agt_billing_01",
		Space:       session.OrgID,
		User:        session.UserID,
		Permissions: perms,
		TTLSeconds:  300,
	})
	if err != nil {
		http.Error(w, "token unavailable", http.StatusBadGateway)
		return
	}
	_ = json.NewEncoder(w).Encode(map[string]string{"token": tok.Token})
}

On user logout, call norilu.tokens.revoke({ space: orgId, user: userId }) so active browser tokens fail closed immediately.

2. Drop in <AgentThread />

Install @norilu/react and mount <AgentThread /> inside <NoriluProvider>:

npm install @norilu/react
import { NoriluProvider, AgentThread } from "@norilu/react";

export function SupportCopilot() {
  return (
    <NoriluProvider
      getToken={async () => {
        const res = await fetch("/api/norilu-token", { method: "POST" });
        const { token } = await res.json();
        return token;
      }}
    >
      <AgentThread
        agentId="agt_billing_01"
        allowFeedback
        components={{
          InvoiceSummary: ({ invoiceId, amountCents, status }) => (
            <MyAppInvoiceCard id={invoiceId} amount={amountCents} status={status} />
          ),
        }}
      />
    </NoriluProvider>
  );
}

<AgentThread /> handles the entire agent lifecycle in one composable surface:

  • 60fps streaming & reconnects — selector-based state updates stream tokens smoothly without re-rendering message history, and recover safely from disconnects.
  • Collapsible tool-call details — live step-by-step tool timeline showing tool name, status, duration, and redacted input/output summaries (never leaking secrets or internal prompts).
  • Inline Approve / Deny cards — renders the exact pending destination and arguments, verified server-side on submission.
  • Generative UI (components) — streams rich interactive cards and tables straight into your own React components.
  • File uploads & scoped artifacts — drag-and-drop file/image attachments in the composer and scoped preview/download cards for generated outputs.
  • Closed-loop feedback — optional thumbs-down reporting feeds bad runs straight into your Norilu regression tests.

3. Compose primitives or build with selector hooks

Need a sidebar thread switcher, a custom layout, or your own composer? Compose Norilu’s individual UI primitives (<ThreadList />, <AgentMessages />, <ToolCallList />, <ApprovalCard />, <AgentUI />, <ArtifactCard />, <AgentComposer />)—or bind directly to granular selector hooks (useThreads, useThreadMessages, useActiveStream, useToolCalls, usePendingApproval):

import {
  ThreadList,
  AgentMessages,
  ToolCallList,
  ApprovalCard,
  AgentUI,
  AgentComposer,
  useActiveStream,
  usePendingApproval,
} from "@norilu/react";

export function CustomCopilotWorkspace() {
  const [threadId, setThreadId] = useState<string>();
  const stream = useActiveStream(threadId);
  const approval = usePendingApproval(threadId);

  return (
    <div className="copilot-shell">
      <ThreadList agentId="agt_billing_01" activeId={threadId} onSelect={setThreadId} />

      <main>
        <AgentMessages
          threadId={threadId}
          renderToolCalls={(calls) => <ToolCallList calls={calls} collapsible />}
          renderUI={(doc) => <AgentUI document={doc} components={myComponents} />}
        />

        {stream?.toolCalls.length ? <ToolCallList calls={stream.toolCalls} live /> : null}
        {approval && <ApprovalCard approval={approval} />}

        <AgentComposer threadId={threadId} allowFiles allowPasteImages />
      </main>
    </div>
  );
}

For non-React frameworks (Vue, Svelte, vanilla JS), import the same selector-based store directly from @norilu/client. All styling tokens are exposed as CSS custom properties so embedded agents inherit your typography, colors, and brand with zero iframe friction.

Component props reference

ComponentKey propsPurpose
<NoriluProvider>getToken, baseUrl?, theme?Manages short-lived nrl_bt_... token caching, automatic expiry refresh, and shared thread store context.
<AgentThread>agentId, threadId?, allowFeedback?, allowFiles?, components?Drop-in full agent UI with streaming, collapsible tool calls, inline approvals, Generative UI, and composer.
<ThreadList>agentId, activeId?, onSelect, allowDelete?Multi-thread sidebar/switcher scoped strictly to the signed-in (space, user).
<AgentMessages>threadId, renderToolCalls?, renderUI?, renderArtifact?Virtualized message list with sanitized markdown, syntax-highlighted code blocks, and Copy buttons.
<ToolCallList>calls, collapsible?, live?Step-by-step tool timeline displaying label, live status, elapsed duration, and redacted input/output summaries.
<ApprovalCard>approval, approveLabel?, denyLabel?, onDecided?Inline Approve/Deny review card bound to the exact pending turnId, callId, and arguments.
<AgentUI>document, components?Renders schema-validated Generative UI cards using built-in primitives or your own React components.
<ArtifactCard>artifact, onDownload?Scoped preview and Bearer-authenticated download card for thread outputs.
<AgentComposer>threadId, allowFiles?, allowPasteImages?, placeholder?Prompt composer with drag-and-drop/paste attachments, inline stop/cancel button, and keyboard shortcuts.

Theming with platform-agnostic JSON tokens

Norilu themes are defined as platform-agnostic JSON design tokens (hex colors and numeric radii/sizes) so the same brand configuration works identically across @norilu/react, @norilu/widget, and mobile clients (React Native, Flutter, iOS, Android).

Pass a typed theme object directly to <NoriluProvider> (zero FOUC, SSR-safe, auto-computed WCAG contrast foregrounds) or set theme="space" to load your Customer Space’s dashboard-managed branding at runtime:

<NoriluProvider
  getToken={getToken}
  theme={{
    mode: "auto",
    colors: {
      background: "#fafaf8",
      surface: "#ffffff",
      border: "#e3e1dc",
      text: "#18181b",
      accent: "#4338ca",
    },
    radius: { sm: 6, md: 10, lg: 14 },
  }}
>
  <AgentThread agentId="agt_billing_01" />
</NoriluProvider>

@norilu/react scopes all styles under CSS @layer norilu so host resets never clash while Tailwind/Shadcn components inside components={{ ... }} work natively. You can also override any mapped --norilu-* variable in CSS:

.my-copilot-theme {
  --norilu-bg: #fafaf8;
  --norilu-surface: #ffffff;
  --norilu-border: #e3e1dc;
  --norilu-text: #18181b;
  --norilu-muted: #52525b;
  --norilu-accent: #4338ca;
  --norilu-radius-md: 10px;
  --norilu-font-sans: var(--font-sans);
  --norilu-font-mono: var(--font-mono);
}
Still have a question? Talk to usRead as Markdown

Search documentation

Find a guide, endpoint or concept.

↑ ↓ to navigate · ↵ to openSearch stays in your browser