@anam-ai/agent-widget
v0.6.1
Published
Embeddable video agent widget for Anam AI
Readme
@anam-ai/agent-widget
Embeddable video agent widget for Anam AI. Add a conversational AI avatar to any website with a single HTML snippet.
Quick Start
Add two lines to your HTML:
<anam-agent agent-id="your-persona-id"></anam-agent>
<script src="https://unpkg.com/@anam-ai/agent-widget" async></script>The widget auto-registers the <anam-agent> custom element on load. No build step required.
Allowed origins: Your persona must have an allowed origin configured in Anam Lab widget settings for the domain you're embedding on, or "Allow everywhere" must be enabled. Without this, the widget will be blocked by default.
Installation
CDN (recommended for embedding)
<script src="https://unpkg.com/@anam-ai/agent-widget" async></script>Also available via jsDelivr:
<script src="https://cdn.jsdelivr.net/npm/@anam-ai/agent-widget" async></script>npm (for bundlers)
npm install @anam-ai/agent-widgetimport { registerWidget } from '@anam-ai/agent-widget';
registerWidget(); // registers <anam-agent>
registerWidget('my-agent'); // or use a custom tag nameAttributes
Configure the widget entirely via HTML attributes. All are optional except agent-id.
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| agent-id | string | — | Persona ID from Anam Lab. Required for streaming. |
| session-token | string | — | Pre-created session token. Skips the /v1/auth/widget call when set (used by Lab preview). |
| api-base-url | string | https://api.anam.ai | API endpoint override. |
| layout | inline | floating | floating | Inline renders in-flow; floating overlays the page. |
| initial-state | minimized | expanded | expanded | Floating layout only. Start as orb or expanded sheet. |
| position | string | bottom-right | Corner preset (bottom-right, bottom-left, top-right, top-left) or custom bracket syntax. |
| ui-mute-button | true | false | true | Show microphone mute toggle. |
| ui-text-input | true | false | true | Show text message input. |
| ui-captions | true | false | false | Show conversation captions. |
| ui-transcript | true | false | true | Show the expandable transcript pane during a call. |
| call-to-action | string | Talk to our assistant | Text on the start button. |
| avatar-url | string | — | Override avatar thumbnail image URL. |
| avatar-video-url | string | — | Override avatar preview video URL. |
| agent-name | string | — | Override persona name displayed in the CTA. |
Custom Positioning
Beyond the four corner presets, use bracket syntax for pixel-level control:
<anam-agent agent-id="..." position="[top-20,right-0]"></anam-agent>
<anam-agent agent-id="..." position="[bottom-100,left-40]"></anam-agent>Layout Modes
Floating (default)
Renders as a fixed-position overlay. Starts expanded or as a clickable orb depending on initial-state.
<anam-agent
agent-id="your-persona-id"
layout="floating"
initial-state="minimized"
position="bottom-right"
></anam-agent>Inline
Renders in the normal document flow, filling its parent container.
<div style="width: 400px; height: 600px;">
<anam-agent agent-id="your-persona-id" layout="inline"></anam-agent>
</div>Configuration Priority
The widget merges configuration from three sources (highest priority wins):
- HTML attributes — per-instance overrides set by the embedder
- Server config — persona settings from Anam Lab (fetched via API)
- Widget defaults — built-in fallbacks
How It Works
- On load: The widget fetches persona metadata (avatar image, name, display config) from
GET /v1/personas/:id/widget - On user click: Requests a session token from
POST /v1/auth/widget, then starts a WebRTC stream via the Anam JS SDK - During session: Real-time video avatar with voice input, optional text input, and mute controls
- On close: Stops the stream and cleans up resources
Startup recovery
Startup has a 45-second deadline through token acquisition and usable video
playback. If it expires, the widget shows network guidance and emits
anam-agent:error with code STARTUP_TIMEOUT. The existing retry control
starts a new attempt. Closing or removing the widget also cancels startup.
An abandoned attempt stops its own SDK client, including sessions allocated
after cancellation. If signalling never became ready, it sends a best-effort
POST /api/sessions/:id/release to api-base-url with the original session
token in the Authorization header and no cross-origin cookies. Same-origin
preview requests retain their deployment-gateway cookie. The server verifies that
the token created that exact session. Tokens are never included in widget
events or logs. A late callback cannot change the replacement call.
Deploy the companion Lab release endpoint with widget support and CORS before publishing this package. Verify the alpha package in Build preview before publishing stable for customer embeds. Existing pinned package versions keep their current behavior until upgraded.
Events
The widget dispatches custom DOM events on the <anam-agent> element:
| Event | Payload | Description |
|-------|---------|-------------|
| anam-agent:session-started | { sessionId } | Stream connected |
| anam-agent:session-ended | { sessionId, reason } | Stream ended |
| anam-agent:message-received | { role, content } | Message from user or assistant |
| anam-agent:message-sent | { content } | Text message sent |
| anam-agent:expanded | {} | Widget expanded from orb |
| anam-agent:collapsed | {} | Widget collapsed to orb |
| anam-agent:transcript-opened | {} | Transcript pane opened |
| anam-agent:transcript-closed | {} | Transcript pane closed |
| anam-agent:error | { code, message } | Error occurred |
| anam-agent:mic-muted | {} | Microphone muted |
| anam-agent:mic-unmuted | {} | Microphone unmuted |
| anam-agent:tool-call-started | { toolName, toolCallId, toolType, toolSubtype?, arguments } | Agent invoked a tool |
| anam-agent:tool-call-completed | { toolName, toolCallId, toolType, toolSubtype?, result, executionTime, documentsAccessed? } | Tool call finished (executionTime in ms; documentsAccessed is RAG-only) |
| anam-agent:tool-call-failed | { toolName, toolCallId, toolType, toolSubtype?, errorMessage, executionTime } | Tool call failed (executionTime in ms) |
document.querySelector('anam-agent').addEventListener('anam-agent:session-started', (e) => {
console.log('Session started:', e.detail.sessionId);
});Reacting to tool calls
When your agent invokes a client-side tool (e.g. redirect, add_to_cart), the
widget surfaces it as a DOM event so your page can act on it — no SDK wiring
required. The toolType field distinguishes client-side tools from server-side
ones, so you can react only to the ones meant for the browser:
document.querySelector('anam-agent').addEventListener('anam-agent:tool-call-started', (e) => {
const { toolName, toolType, arguments: args } = e.detail;
if (toolType !== 'client') return; // server-side tools run on Anam's side
if (toolName === 'redirect') {
window.location.href = args.url;
}
});Note: for client tools, only tool-call-started is guaranteed — the SDK emits
tool-call-completed only when a tool-call handler is registered, which the
widget deliberately does not do. Key your integration off tool-call-started.
Built-in tools
Tool names starting with the reserved anam_ prefix are Anam built-ins.
When a built-in is enabled for a persona in the Anam Lab (Build → Embed tab),
the Lab injects the tool definition into widget sessions server-side, and the
widget renders calls to it as a native block in the transcript. No integration
code is required on the host page.
Current built-ins:
| Tool name | Enabled by | Input schema | Rendered as |
|-----------|-----------|--------------|-------------|
| anam_show_link | "Show links in chat" (requires transcript) | { url: string (https:// or mailto:), label: string } | Clickable link card in the transcript; the pane auto-opens when a card arrives |
Behavior notes:
- URLs are validated before rendering: only
https:andmailto:schemes produce a card. Invalid or non-allowlisted URLs render nothing. - Every tool call — built-in or not — still dispatches the
anam-agent:tool-call-*DOM events above. Host pages that want to ignore built-ins can filter withtoolName.startsWith('anam_'). - Widgets older than a built-in's introduction render nothing for it but still dispatch the DOM events (graceful degradation).
- A built-in's argument shape is a stable contract: it is never repurposed. New behavior means a new tool name.
Adding a built-in (for contributors): add a parser entry to
BUILTIN_TOOL_PARSERS and a renderer to BLOCK_RENDERERS in
src/widget/builtinBlocks.tsx, plus CSS. The server-side tool definition
(description prompt, injection flag) lives in the Lab codebase
(src/lib/builtin-tools/widget-tools.ts), so prompt tuning ships without a
widget release.
Development
Prerequisites
- Node.js 18+
- pnpm 10+
Setup
pnpm installDev Server
pnpm devOpens the playground at http://localhost:5173/playground/ with HMR. The playground provides a sidebar with controls for all widget attributes and a live preview area.
Set VITE_ANAM_AGENT_ID in .env to pre-fill the agent ID input.
Build
pnpm buildOutputs dual-format bundles to dist/:
dist/index.js— ESM (for bundlers)dist/index.umd.js— UMD (for script tags)
All dependencies are bundled into the output (zero runtime externals).
Preview Production Build
pnpm previewBuilds and serves at http://localhost:4173/playground/preview.html using the UMD bundle.
Type Check
pnpm typecheckTests
pnpm testThe lifecycle suite covers deadline expiry, cancellation during token minting, late engine allocation, stale callbacks after retry, and playback failure.
Lint
pnpm lintArchitecture
- Preact — lightweight UI rendering (~4KB)
- Preact Signals — fine-grained reactive state for session lifecycle
- Shadow DOM — full CSS isolation from host page styles
- Web Components —
<anam-agent>custom element viapreact-custom-element - Tailwind CSS — compiled and inlined into the Shadow DOM (no external stylesheets)
- Vite — library-mode build with esbuild minification
Browser Support
Modern browsers with Web Components and WebRTC support:
- Chrome / Edge 80+
- Firefox 63+
- Safari 13.1+
