Cadenya Widgets
A Widget binds one Agent to its own host (info.host, such as k7m2xq9fp4wn.widgets.cadenya.com) and an origin allowlist. Your backend mints a Widget Session with the workspace API key and gives the browser only the session's short-lived token and host. Conversations, tool calls and event streams then go straight from the browser to the Widget host.
Never send the workspace API key, or anything that holds it, to the browser. Only credentials.token and credentials.host (plus the two expiry times) leave your server. Keep the key in CADENYA_API_KEY in server-side env (.env.local, Vercel env, a secret manager). Do not log or store the token.
For raw HTTP routes and the error envelope, see cadenya-api. For client setup, pagination and APIError, see cadenya-typescript-sdk.
Checklist
- A published Agent (
STATE_PUBLISHED) with a variation and its Tool Sets. - A Widget, created server-side (key with
widgets:manage), with the exact origins of every page that embeds it. - A backend route that authenticates the visitor and calls
widgetSessions.create(key withwidget_sessions:manageandobjectives:manage). - A page that renders
CadenyaWidgetProviderwith the returned host and token, and agetTokenthat calls that route again. - Revocation on logout, and
tenants.deletefor erasure requests. - Check: a message sent from an allowlisted origin gets a reply.
1. Prerequisites: the Agent and the Widget
widgets.createrejects an archived Agent (archived agents cannot serve a widget; unarchive the agent first), but it accepts a draft Agent. Every conversation on a draft Agent then fails withagent must be published to create an objective. Runclient.agents.publish(id)first.spec.variationIdis an optional pin. It must belong to the Agent. Without it, the Agent's variation selection mode chooses a variation for each conversation.spec.originAllowlistholds up to 32 exact origins that match^https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?$. Paths, trailing slashes and wildcards are not allowed. The edge compares the browser'sOriginheader to each entry as a string, so write entries in lowercase and leave out default ports (https://app.example.com, nothttps://App.example.com:443). Each Vercel preview URL is a separate origin.- A new hostname can take up to a minute to start serving. Until it does, the host answers
404 {"error":"unknown widget"}. - Changing a Widget's Agent or variation affects new sessions only. A session copies the Agent binding when it is minted.
- Widgets count toward the account's plan limit. An archived Widget does not count.
import Cadenya from "@cadenya/cadenya"; // reads CADENYA_API_KEY and CADENYA_WORKSPACE_ID
const client = new Cadenya();
const widget = await client.widgets.create({
metadata: { name: "Support chat", externalId: "support-chat" },
spec: {
agentId: "external_id:support-agent",
originAllowlist: ["http://localhost:3000", "https://app.example.com"],
},
});
// widget.info.host is the hostname. Never build it from the ID or DNS label.
The CLI equivalent is cadenya widgets create --name … --agent-id … --origin-allowlist … --dry-run (see cadenya-cli; repeat --origin-allowlist for each origin).
To change the origins, send the whole list. The update replaces it:
const current = await client.widgets.retrieve("external_id:support-chat");
await client.widgets.update("external_id:support-chat", {
spec: { agentId: current.spec.agentId, originAllowlist: [...(current.spec.originAllowlist ?? []), "https://staging.example.com"] },
updateMask: "spec.originAllowlist",
});
2. Mint a Widget Session (server only)
- Scopes. Creating a session takes
widget_sessions:manage. The session also inherits the minting key's scopes, frozen at mint. Visitors cannot start or continue conversations unless the key holdsobjectives:manage. Without it, the browser gets403 Session cannot create or continue conversations, orWidget session cannot read conversationswithoutobjectives:read. Mint with an API key: a session minted with a user login gets no scopes and cannot converse. - Tenant and subject are required. Use
spec.tenant.idfor your organization ID andspec.subject.idfor your user ID: 1 to 64 characters of[A-Za-z0-9._-], plus an optionalnameof up to 64 characters. The mint creates or updates the tenant and subject records. Take both IDs from your own authenticated session, never from the request body. - Lifetime. The token lasts 15 minutes (
credentials.tokenExpiresAt). The session lasts 24 hours unlessspec.expiresAt(an RFC 3339 string, which must be in the future) sets a different deadline. Nothing extends that deadline. A session also ends after 200 visitor messages (STATE_EXHAUSTED). - Every call mints a new session, with no dedupe. One subject can hold at most 10 live sessions per Widget, and minting an eleventh revokes the oldest.
- Optional trusted context, all fixed at mint:
secrets: [{ name, value }](top level, besidespec): encrypted, never returned, and used ahead of workspace and Tool Set secrets with the same name. Tool Set headers reference them as{{ secrets.NAME }}.spec.pinnedParameters: up to 32 tool arguments that the model cannot see or override.metadata.labels.
// app/api/widget-session/route.ts (Next.js; any server framework works the same way)
import Cadenya from "@cadenya/cadenya";
const client = new Cadenya();
export async function POST() {
const user = await requireUser(); // your auth; respond 401 if signed out
const session = await client.widgetSessions.create({
spec: {
widgetId: process.env.CADENYA_WIDGET_ID!, // e.g. external_id:support-chat
tenant: { id: user.orgId, name: user.orgName },
subject: { id: user.id },
},
});
const c = session.credentials; // returned only by create
if (!c) return new Response("Widget Session returned no credentials", { status: 502 });
return Response.json(
{ host: c.host, token: c.token, tokenExpiresAt: c.tokenExpiresAt, sessionExpiresAt: c.sessionExpiresAt },
{ headers: { "Cache-Control": "no-store" } },
);
}
Read credentials. The spec.token, spec.tokenExpiresAt and info.host fields hold the same values on create. Reads and lists never return a token.
3. Render with the React UI kit
npm install @cadenya/cadenya @cadenya/widgets-ui-react @radix-ui/themes
"use client";
import "@radix-ui/themes/styles.css";
import "@cadenya/widgets-ui-react/styles.css";
import { useCallback, useEffect, useState } from "react";
import { Theme } from "@radix-ui/themes";
import { CadenyaWidgetProvider, ConversationsPanel } from "@cadenya/widgets-ui-react";
type Creds = { host: string; token: string };
const mint = async (): Promise<Creds> => {
const r = await fetch("/api/widget-session", { method: "POST" });
if (!r.ok) throw new Error(`widget session ${r.status}`);
return r.json();
};
export function SupportChat() {
const [creds, setCreds] = useState<Creds | null>(null);
useEffect(() => { mint().then(setCreds, console.error); }, []);
const getToken = useCallback(async () => (await mint()).token, []);
if (!creds) return null;
return (
<Theme accentColor="teal" radius="large" style={{ height: "100%" }}>
<CadenyaWidgetProvider host={creds.host} token={creds.token} getToken={getToken}>
<ConversationsPanel />
</CadenyaWidgetProvider>
</Theme>
);
}
- The provider calls
https://{host}. When a request returns 401, it callsgetTokenonce and retries. Open streams survive the token change. - Each
getTokencall mints a new session for the same tenant and subject. Conversation history carries over, because history belongs to the identity, not to the session. Your route decides each time whether this visitor still gets access. - The panel fills its container, so give the container a definite height.
- The Widgets Tools template (
<WidgetTools>from@cadenya/widgets-ui-react/widget-tools) and page tools must share onePageToolsProviderwith the panel. See the Widget quickstart. Client tools are in Widgets: page tools and client tools. - For a custom UI, use
@cadenya/widgets(a dependency of the kit):new CadenyaWidgets({ apiKey: token, baseURL: `https://${host}` }). - To renew a token without going back to your backend, call
client.session.renewWidget({ workspaceId })on thatCadenyaWidgetsclient beforetokenExpiresAt. It returns new credentials. The client'sapiKeyis fixed at construction, so passfetch: auth.fetchfrom the kit'screateAuthFetch({ token })and callauth.setToken(renewed.token).workspaceIdis the session'smetadata.workspaceId, so return it from your mint route. Renewal accepts a token at most 60 seconds past expiry, allows 30 renewals per minute, and keeps the same session and deadline. The React kit does not call it.
4. Tenant and subject isolation
- Sessions with the same tenant and subject on the same Widget and Agent share conversation history. A hard-coded subject such as
"guest"puts every visitor in one shared history. Use a distinct subject ID for each person. - Subject IDs are scoped to their tenant, so
user-42in tenant A is a different subject fromuser-42in tenant B. - The browser cannot choose the tenant, subject, Agent, secrets or pinned parameters. Every conversation inherits them from the session. A conversation ID outside the session's identity returns 404, the same as one that does not exist.
- To scope tool calls to the visitor's own records, pin the ID instead of trusting the model:
pinnedParameters: { accountId: user.orgId }.
5. Revocation and cleanup
| Goal | Call | Effect |
|---|---|---|
| End all of a user's sessions (logout) | list({ tenantId: "external_id:<org>", subjectId: "external_id:<user>", state: "STATE_ACTIVE" }), then revoke each |
Covers every Widget; add widgetId to limit it to one. subjectId in the external-ID form needs tenantId. Every re-mint is a new session, so revoke them all. |
| End one session now (incident) | widgetSessions.revoke(id) |
STATE_REVOKED. Its tokens fail with 401 and its secrets are deleted. Repeat calls succeed. |
| Remove a session record | widgetSessions.delete(id) |
Its conversations are kept but no longer linked to any session, so a later deleteTenant does not erase them (tenants.delete still does). |
| Delete a tenant's widget data | widgetSessions.deleteTenant({ tenantId: "external_id:<org>" }) |
Deletes the tenant's sessions and their conversations on every Widget. The tenant and subject records (with their names) remain. Each call deletes at most 10,000 sessions, so repeat until sessionsDeleted is 0. |
| Erasure request for a tenant | tenants.delete("external_id:<org>") (key with tenants:manage) |
Erases the tenant, its subjects, its sessions and every conversation tied to it, in the background. It returns STATE_ERASING; tenants.retrieve returns 404 when done. Mints for that tenant fail meanwhile. This cannot be undone. |
| Turn off a Widget | widgets.archive(id) |
The host returns 404 and its sessions are revoked. unarchive does not restore them, so mint new sessions. |
Ending your app's own login does not invalidate widget tokens. End your app session first, so the mint route refuses the user, then revoke; otherwise getToken mints a new session. If the user never opened a Widget, list returns 400 validation failed (tenant does not exist in this workspace or subject does not exist in this workspace); treat that as nothing to revoke.
for await (const s of await client.widgetSessions.list({
tenantId: `external_id:${orgId}`,
subjectId: `external_id:${userId}`, state: "STATE_ACTIVE",
})) await client.widgetSessions.revoke(s.metadata.id);
6. Origins, CSP and transport
- The page's origin must be on the allowlist. A non-GET request without an
Originheader is refused, and the host accepts HTTPS only. - With a Content Security Policy, add
https://<info.host>toconnect-src. The kit and@cadenya/widgetssend every request and event stream withfetchto that host, and use no iframe,EventSourceor WebSocket. - Assistant messages render markdown images, and the Widgets Tools details card renders
image.url. Both URLs come from the model, so a strictimg-srcblocks them. Decide which image hosts to allow. - CORS allows the
GET,POSTandOPTIONSmethods and theAuthorization,Content-TypeandLast-Event-IDheaders. Widgets use bearer tokens, never cookies.
Troubleshooting
| Symptom (exact string) | Cause and fix |
|---|---|
Browser shows a CORS error; the preflight returns 403 {"error":"origin not allowed"} |
The page origin is not an exact entry. Add it with widgets.update, matching scheme, case and port. |
403 {"error":"origin required"} |
A POST was sent without Origin (for example from a server or curl). Call the Widget host from the browser. |
403 {"error":"https required"} |
The request used http://. Use https://{host}. |
404 {"error":"unknown widget"} |
Wrong host, Widget archived or deleted, or a new Widget that is still propagating (up to a minute). |
400 validation failed, spec.widgetId: widget does not exist in this workspace / archived widgets cannot mint sessions; unarchive the widget first |
Wrong workspace or ID, or the Widget is archived. |
400 validation failed on spec.tenant or spec.subject |
One of them is missing or does not match [A-Za-z0-9._-]{1,64}. |
400 Session expiry must be in the future |
spec.expiresAt is in the past. |
429 the account has reached its plan's limit of N for widgets (ENTITLEMENT_LIMIT_REACHED) |
Archive or delete an unused Widget, or raise the plan. An unclaimed temporary account gets REQUIRES_CLAIM instead. |
400 validation failed, agent_id: agent must be published to create an objective |
The Widget's Agent is a draft. Publish it. |
403 Session cannot create or continue conversations / Widget session cannot read conversations |
The minting key lacks objectives:manage / objectives:read. Add the scope and mint a new session; the old session keeps its frozen scopes. |
401 Widget access token expired (TOKEN_EXPIRED) |
The token is past its expiry. Provide getToken, or renew before tokenExpiresAt. |
401 right after a revoke or an eviction (more than 10 live sessions) |
Revocation rotates the session's signing key, so its tokens fail the signature check. The kit then calls getToken; mint again only if the visitor is still allowed. |
403 Widget session expired (SESSION_EXPIRED) |
The session's deadline passed. Mint a new session. |
403 with SESSION_REVOKED (Widget session revoked, Widget session authorization revoked) |
The session was revoked, or its Widget, workspace or minting API key no longer authorizes it (archived, deleted, disabled, or removed from the workspace). Mint with a valid key on an active Widget. |
429 Widget session has spent its message allowance or Widget session exhausted (SESSION_EXHAUSTED) |
The session reached 200 messages. Minting a new session is an explicit app decision. |
Widget session requires tenant and subject identity; create a new session |
A legacy session without identity. Mint a new one. |
429 Widget session renewal rate limit exceeded (RATE_LIMITED) |
More than 30 renewals per minute. Wait for the RetryInfo delay in the error details; browsers cannot read the Retry-After header cross-origin. |
503 This assistant is temporarily unavailable. Please try again later. |
The account's plan refused the visitor's request. Check the plan and usage. |
Server-side 403 with reason SCOPE_MISSING |
The key lacks the scope for that call: widgets:read/:manage or widget_sessions:read/:manage. |
Match the google.rpc.ErrorInfo reason (domain api.cadenya.com), not the message text. The edge's {"error": …} bodies have no reason.
End-to-end check
client.agents.retrieve(agentId)returnsstate: "STATE_PUBLISHED".client.widgets.retrieve(widgetId)returnsstate: "STATE_ACTIVE"and your origin inspec.originAllowlist.curl -X POSTyour mint route while signed in. It returnshostandtoken, and returns 401 when signed out.- Open the page on an allowlisted origin and send a message. The reply streams into the panel.
- Call
widgetSessions.retrieve(sessionId). It returnsstate: "STATE_ACTIVE"and a nonzeroinfo.messageCount. Revoke the session and confirm that it returnsSTATE_REVOKED.
