Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
<agent-3d> Web Component API Reference
<agent-3d> is a custom HTML element that ships the entire three.ws stack in a single script tag. Drop the loader, use the element — no build step, no framework required.
<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"
integrity="sha384-…" crossorigin="anonymous"></script>
<agent-3d src="agent://base/42" style="width:400px;height:500px"></agent-3d>
All four layout modes, voice I/O, the LLM brain, persistent memory, and an extensible skill system are built in. Every feature is opt-in: a bare <agent-3d body="https://three.ws/avatars/default.glb"> renders a silent 3D viewer with no API key and no external calls beyond the GLB itself.
Boot lifecycle
The element is designed to be zero-overhead until it is needed.
- Element added to DOM —
connectedCallbackfires. Shadow DOM shell (canvas container, chat chrome, poster, loading indicator) is rendered immediately. - IntersectionObserver starts watching the element. Nothing else happens until at least one pixel is visible in the viewport. Add the
eagerattribute to skip this and boot immediately on connection. - Manifest resolved: the element reads its source attributes (
src,agent-id,manifest, orbody) in priority order and fetches or constructs an agent manifest. See Source attributes for the priority chain. - Embed policy checked — if the manifest maps to a backend agent ID, the element fetches the agent's embed policy and refuses to continue if the current origin is not permitted.
- Viewer constructed — a three.js renderer is created inside the shadow DOM canvas. The GLB referenced by
manifest.body.uriis loaded. - Memory, skills, and runtime initialized — the memory store is opened, skills listed in the manifest are installed, and the LLM runtime is wired up (or a null provider is used if
brainisnoneor omitted). agent:readyfires on the element with{ agent, manifest }. The loading indicator is hidden and the poster fades out.
If any step throws, agent:error fires and an error overlay is shown in place of the canvas.
HTML attributes
Source attributes (pick one)
These tell the element what to load. When multiple are set, priority is src > agent-id > manifest > body.
| Attribute | Form | Example |
|---|---|---|
src |
On-chain URI | src="agent://base/42" |
agent-id |
Numeric id (pair with chain-id) |
agent-id="42" chain-id="8453" |
agent-id |
CAIP-10 + token | agent-id="eip155:8453:0xReg…:42" |
agent-id |
Shorthand onchain: | agent-id="onchain:8453:42" |
agent-id |
Backend account ID | agent-id="a_abc123" |
manifest |
IPFS or HTTPS manifest URL | manifest="ipfs://bafy…/manifest.json" |
body |
Bare GLB URL (ad-hoc agent) | body="https://three.ws/avatars/default.glb" |
Using body with no manifest creates an ad-hoc agent. Its name, instructions, and brain model can be provided as additional attributes:
<agent-3d
body="https://three.ws/avatars/default.glb"
name="Guide"
instructions="You are a friendly 3D guide."
brain="claude-opus-4-7"
></agent-3d>
Scene and rendering
| Attribute | Type | Default | Description |
|---|---|---|---|
background |
transparent | dark | light |
transparent |
Canvas clear color. transparent lets the page background show through. |
poster |
URL | — | Image shown while the model loads. Fades out on completion. |
framing |
full | portrait |
full |
Camera framing. portrait frames the head and shoulders. |
clip |
clip name | — | Animation clip to play on load. |
Lighting, camera orbit, and environment are managed by the built-in viewer; they are not attribute-configurable. For AR placement, use the dedicated AR surfaces described in AR below.
Brain (LLM runtime)
| Attribute | Type | Default | Description |
|---|---|---|---|
brain |
model ID | from manifest | LLM model to use, e.g. claude-opus-4-7. Set to none to disable the brain entirely. |
instructions |
URL or inline text | from manifest | System prompt. Can be a URL ending in .md or an inline string. Overrides manifest.brain.instructions. |
api-key |
string | — | API key injected directly. Development use only. Prefer key-proxy for any page that will be public. |
key-proxy |
URL | — | URL of your backend that injects API keys into outbound LLM requests. |
Voice
| Attribute | Type | Default | Description |
|---|---|---|---|
voice |
string | on if manifest configures voice | Voice mode. Set to livekit for the LiveKit realtime voice pipeline; TTS/STT providers otherwise come from the manifest. |
Sign language (ASL)
| Attribute | Type | Default | Description |
|---|---|---|---|
sign-language |
boolean | off | The avatar signs every assistant reply in American Sign Language: words in the lexicon are signed, the rest are fingerspelled, in one continuous motion. Any value except off or false enables it, at boot or toggled at runtime. Requires a rig with finger bones; one without is refused with an explanation rather than signing wrong. |
<agent-3d agent-id="your-agent" chat sign-language></agent-3d>
// Toggle it from your own UI at any time.
const el = document.querySelector('agent-3d');
el.setAttribute('sign-language', ''); // on
el.removeAttribute('sign-language'); // off
Signing rides the same SPEAK event as spoken replies, so it works identically
in the hosted app and in an embed. A runnable page is
examples/sign-language.html; the engine and its
vocabulary are documented in Sign language, and the
alphabet is browsable at /asl-alphabet.
Hand control, no camera
| Attribute | Type | Default | Description |
|---|---|---|---|
sonar |
boolean | off | Permits acoustic hand control on this element. The speakers emit a tone above hearing and the microphone reads how a hand bends it on the way back, so a viewer can drive the agent by waving at their laptop with the camera shut. Any value except off or false permits it; removing the attribute stops a session already running. |
The attribute only permits the capability. Nothing starts until the page calls
startSonar(), and that call needs a real user gesture behind it, because it
prompts for the microphone and puts a tone into the viewer's room. An embed that
never calls it ships none of the sensing code: the modules load on first use.
<agent-3d agent-id="your-agent" sonar></agent-3d>
const el = document.querySelector('agent-3d');
document.querySelector('#wave-at-me').addEventListener('click', async () => {
try {
await el.startSonar({ mode: 'swipe' });
} catch (err) {
// A denied or unavailable microphone. err.message is written to be shown.
show(err.message);
}
});
Out of the box a sweep steps the agent through its gesture vocabulary, a push moves the camera in and a pull eases it back out, and a held lift turns the camera around the agent. To map the gestures to your own behaviour instead, cancel the event:
el.addEventListener('sonar-gesture', (e) => {
e.preventDefault(); // suppress the built-in response
if (e.detail.gesture === 'swipe') e.detail.direction > 0 ? nextSlide() : prevSlide();
});
Say plainly wherever you ship this that the carrier sits near 20 kHz, which cats and dogs can hear. The technique, its three gestures, what it needs from the room, and why running more than one gesture at a time needs a mode are all in Sonar.
Skills and memory
| Attribute | Type | Default | Description |
|---|---|---|---|
skills |
comma-separated URIs | — | Additional skill URIs to install on top of manifest skills. |
skill-trust |
any | whitelist | owned-only |
owned-only |
Controls which skill URIs are allowed to install. owned-only allows only skills whose author matches the agent's ownerAddress. |
memory |
local | ipfs | encrypted-ipfs | none |
from manifest | Memory storage mode. |
memory-key |
string | agent ID or name | Namespace under which memory is persisted. Useful when embedding the same agent in multiple contexts. |
Layout
| Attribute | Type | Default | Description |
|---|---|---|---|
mode |
inline | floating | section | fullscreen |
inline |
Layout mode. See Display modes. |
position |
bottom-right | bottom-left | top-right | top-left | bottom-center |
bottom-right |
Corner anchor for floating mode. |
offset |
CSS length pair | 24px 24px |
Distance from the edge in floating mode (vertical horizontal). |
width |
CSS length | 100% inline, 320px floating |
Element width. |
height |
CSS length | 480px |
Element height. |
responsive |
boolean | on | Applies clamp()-based shrinking on small viewports. Disable with responsive="false". |
On-chain identity
| Attribute | Type | Description |
|---|---|---|
chain-id |
number | Numeric chain ID, e.g. 8453. Required when agent-id is a bare number. |
registry |
0x address |
Override the deployed registry contract (for CAIP-10 precision). |
Developer and display options
| Attribute | Description |
|---|---|
eager |
Boot immediately on DOM connection, bypassing the IntersectionObserver lazy-load. |
kiosk |
Hides all UI chrome: chat input, mic button, validator panel, editor links. Use for display contexts where end users should not interact. |
name-plate |
Controls the name overlay. Set to "off" to hide it. |
JavaScript properties
Access these after the element is connected. Properties that depend on the runtime return null before agent:ready fires.
const el = document.querySelector('agent-3d');
el.manifest // The loaded agent manifest object
el.runtime // The Runtime instance (LLM brain + tool loop)
el.memory // The Memory instance
el.skills // Array of installed Skill objects
el.manifest — The resolved manifest object as loaded from manifest.json, the on-chain registry, or constructed from body/instructions attributes. Available after agent:ready.
el.runtime — The Runtime instance that drives the LLM tool loop. Emits its own events (brain:thinking, brain:message, voice:*, memory:write) which are re-dispatched on the element.
el.memory — The Memory instance. Supports read(key), write(key, value), and export() for portability.
el.skills — Array of all currently installed Skill objects. Updated live as skills are installed or uninstalled.
el.sonarRunning - Read-only boolean, true while the microphone is open and hand gestures are being read. See startSonar().
Methods
All methods are safe to call before agent:ready — those that need the runtime will wait internally.
say(text, opts?)
Send a text turn to the agent's LLM brain. The agent processes the message, runs any tools, and may speak a reply.
await el.say('Hello, what animations do you have?');
// With voice output enabled:
await el.say('Tell me about this product.', { voice: true });
| Parameter | Type | Description |
|---|---|---|
text |
string | The user message to send. |
opts.voice |
boolean | Force voice output for this turn, overriding the voice attribute. |
Returns a Promise that resolves when the agent's reply is complete.
ask(text, opts?)
Convenience wrapper around say() that resolves to the agent's reply text as a string.
const reply = await el.ask('What can you help me with?');
console.log(reply); // "I can walk you through the product..."
Returns Promise<string>.
wave(opts?)
Plays the avatar's wave animation.
await el.wave({ style: 'enthusiastic' });
lookAt(target)
Points the avatar's gaze at a target.
await el.lookAt('user'); // face the viewer
await el.lookAt('camera'); // face the camera directly
await el.lookAt('model'); // look at another element in the scene
play(name, opts?)
Plays a named animation clip from the loaded GLB.
await el.play('idle_wave');
await el.play('dance', { loop: true });
| Parameter | Type | Description |
|---|---|---|
name |
string | Clip name as it appears in the GLB's animation list. |
opts.loop |
boolean | Whether to loop the clip. |
opts.duration |
number | Override playback duration in seconds. |
playClip(name, opts?)
Plays a clip from the platform's shared animation library, retargeted onto whatever skeleton the loaded GLB carries. Unlike play(), which needs a clip that already exists inside the GLB, this resolves names from the public clip manifest at /animations/manifest.json, so the same call works on a Mixamo rig, a VRM, a body scan, or a mesh you generated a minute ago.
const clips = await (await fetch('https://three.ws/animations/manifest.json')).json();
el.playClip(clips[0].name, { userInitiated: true });
| Parameter | Type | Description |
|---|---|---|
name |
string | Clip name from the manifest, e.g. idle, facepalm, av-idle-breath. |
opts.fade_ms |
number | Cross-fade into the clip, in milliseconds. Defaults to 400. |
opts.userInitiated |
boolean | Play even when the visitor has prefers-reduced-motion set. Pass true only when a real user gesture asked for the motion; ambient autoplay stays suppressed. |
The method honors each clip's own loop flag: looping clips loop, one-shot clips play once and settle back into idle without a snap at the boundary.
sign(text)
Performs text in American Sign Language on the avatar without sending it to a brain. Words in the lexicon are signed, everything else fingerspells, in one continuous motion. Turns the engine on if the sign-language attribute has not already.
const result = await el.sign('happy to meet you');
if (result) {
console.log(result.signed); // words that came from the lexicon
console.log(result.spelled); // words that fingerspelled
}
| Parameter | Type | Description |
|---|---|---|
text |
string | The utterance to perform. |
Resolves once the motion finishes, with { signed, spelled }, or with null when the loaded rig has no finger bones to sign with. Use it for captions, accessibility overlays, and any surface that has its own text; the sign-language attribute covers the conversational case, where every assistant reply is signed automatically.
startSonar(opts?)
Starts reading hand gestures from the microphone. Requires the sonar attribute and a real user gesture behind the call.
const started = await el.startSonar({ mode: 'push' });
| Parameter | Type | Description |
|---|---|---|
opts.mode |
'swipe' | 'push' | 'lift' | 'all' |
Which gesture is live. Default 'swipe'. |
opts.amplitude |
number | Speaker level for the carrier, 0 to 1. Default 0.08. |
opts.tone |
number | Carrier in Hz. Omit it: the sensor measures the candidates against the machine's own hardware and keeps the best. |
Only one gesture is live at a time because they are not separable at the hardware level: the microphone senses distance, so a sweep passing it is an approach followed by a retreat, which is exactly what a push and a pull look like. 'all' runs every detector and misreads more often.
Resolves true once sensing has begun, or false when the sonar attribute is absent, a session is already running, or the browser has no Web Audio microphone input. Rejects with a user-showable message when the microphone is denied or unavailable.
stopSonar()
Silences the tone and releases the microphone, which is what turns the browser's recording indicator off. Safe to call when nothing is running. Removing the sonar attribute does this for you, and so does removing the element from the page.
speakAudio(audio, opts?)
Plays audio you supply and drives the avatar's mouth from it. The built-in voice pipeline already lip-syncs its own TTS; this is the way in for audio synthesized somewhere else, a recorded clip, or a line you cached. The audio is routed through the same analyser the internal path uses, so the visemes follow the real waveform rather than approximating it from the text.
const res = await fetch('https://three.ws/api/v1/ai/tts', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ text: 'Give your AI a body.', voice: 'nova' }),
});
const { data } = await res.json();
await el.speakAudio(`data:${data.content_type};base64,${data.audio}`);
| Parameter | Type | Description |
|---|---|---|
audio |
string | HTMLAudioElement | Audio URL in any format the browser plays, or an audio element you already control. |
opts.volume |
number | Playback volume, 0 to 1. Defaults to 1. |
Resolves when playback finishes. The mouth returns to neutral on end, on error, and when a second call supersedes the first. A cross-origin URL has to be CORS-readable or the browser refuses to analyse it, in which case the clip still plays and only the visemes are lost; a data: URL (what the text-to-speech API returns) is always readable.
speak(text, opts?)
Triggers a speak animation on the avatar (lip-sync / talking gesture) without sending the text to the LLM. Use this to drive the avatar from your own logic.
el.speak('Welcome to my portfolio!');
The method selects the best available talking animation (talk → yes → wave fallback) and plays it for a duration proportional to the word count of text.
clearConversation()
Resets the LLM conversation history. Subsequent say() calls start a fresh context.
el.clearConversation();
installSkill(uri)
Dynamically installs a skill at runtime.
await el.installSkill('ipfs://bafy…/dance/');
Returns a Promise that resolves to the installed Skill instance. Throws if the skill's author does not pass the current skill-trust policy.
uninstallSkill(name)
Removes an installed skill by name.
el.uninstallSkill('dance');
expressEmotion(trigger, weight?)
Fires an emotion stimulus on the avatar's Empathy Layer. The emotion blends into the avatar's continuous facial state and decays naturally over time.
el.expressEmotion('celebration', 0.9);
el.expressEmotion('concern'); // weight defaults to 0.7
| Parameter | Type | Description |
|---|---|---|
trigger |
string | Emotion name: celebration, concern, curiosity, empathy, patience. |
weight |
number | Intensity from 0 to 1. Defaults to 0.7. Clamped to [0, 1]. |
Returns true if the element is mounted, false if it has not booted yet.
setMode(mode)
Changes the layout mode at runtime. Equivalent to setting the mode attribute.
el.setMode('floating');
el.setMode('fullscreen');
setPosition(position, offset?)
Updates the floating anchor position.
el.setPosition('bottom-left', '16px 16px');
setSize(width, height)
Updates the element's width and height.
el.setSize('400px', '520px');
pause()
Suspends the runtime (LLM stream, mic, voice).
el.pause();
destroy()
Tears down the element completely: disposes the WebGL renderer, disconnects all observers, destroys the runtime. Use when removing the element from the DOM programmatically.
el.destroy();
Events
All events bubble and are composed: true, meaning they cross shadow DOM boundaries and are catchable on any ancestor element.
Lifecycle events
| Event | Detail | When |
|---|---|---|
agent:ready |
{ agent, manifest } |
Fully booted: manifest loaded, skills installed, brain connected. The body is already on screen holding its first clip (idle, or the clip attribute): the element keeps its canvas hidden until that pose has rendered, so a bind-pose T-pose is never shown. This is the event to swap out your own placeholder image on. |
agent:load-progress |
{ phase, pct } |
Incremental boot progress. phase is one of "manifest", "body", "memory", "skills", "brain". pct is 0–1. |
agent:error |
{ phase, error } |
A fatal error occurred during boot or at runtime. |
Brain events
| Event | Detail | When |
|---|---|---|
brain:message |
{ role, content } |
Each completed turn: role is "user" or "assistant". |
brain:thinking |
{ content } |
Streamed thinking tokens (only when extended thinking is enabled). |
Voice events
| Event | Detail | When |
|---|---|---|
voice:speech-start |
{ text } |
TTS playback begins. |
voice:speech-end |
{} |
TTS playback ends. |
voice:listen-start |
{} |
Microphone opens. |
voice:transcript |
{ text, final } |
STT chunk received. final: true means the utterance is complete. |
Hand control events
| Event | Detail | When |
|---|---|---|
sonar-gesture |
{ gesture, ... } |
A hand gesture was recognised. Cancelable: preventDefault() suppresses the built-in response and leaves the gesture entirely to your handler. Bubbles and crosses the shadow boundary. |
detail.gesture is "swipe", "push" or "lift", each carrying what its own response needs:
| Gesture | Detail fields |
|---|---|
swipe |
direction (1 next, -1 previous) and slot, the gesture slot the agent is about to play. |
push |
action (3 on the push, -1 per step of the paced return, 0 as it lands back at rest) and factor, the camera dolly it maps to. |
lift |
radians turned this frame and the current velocity. Fires per animation frame while a hand is held up, so treat it as a stream, not an event. |
Skill events
| Event | Detail | When |
|---|---|---|
skill:loaded |
{ name, uri } |
A skill was successfully installed during boot. |
skill:tool-called |
{ tool, args, result } |
The LLM invoked a tool. result has shape { ok, ... }. |
Memory events
| Event | Detail | When |
|---|---|---|
memory:write |
{ key, type } |
A memory entry was written. |
AR
<agent-3d> itself does not expose an AR API. AR placement lives on the platform's dedicated AR surfaces:
/avatars/:id/ar— every avatar has a full-screen AR page. It selects the right method per device automatically: iOS Quick Look (with in-browser GLB→USDZ conversion when no pre-generated USDZ exists), Android Scene Viewer, or WebXR.- Viewer AR button — the avatar viewer and Forge result toolbar include a View in AR control; on desktop it shows a QR code that opens the AR session on a phone.
To offer AR from a page that embeds the component, link to the avatar's /avatars/:id/ar page. For methods, platform compatibility, and troubleshooting, see the AR & WebXR guide.
Listening example
const el = document.querySelector('agent-3d');
el.addEventListener('agent:ready', () => {
console.log('Agent is live');
});
el.addEventListener('brain:message', (e) => {
if (e.detail.role === 'assistant') {
console.log('Agent said:', e.detail.content);
}
});
el.addEventListener('skill:tool-called', (e) => {
console.log(`Tool ${e.detail.tool} called with`, e.detail.args);
});
el.addEventListener('agent:error', (e) => {
console.error('Boot failed at phase', e.detail.phase, e.detail.error);
});
postMessage bridge (iframe embeds)
When <agent-3d> is hosted inside an <iframe>, the host page communicates with the embed using a structured postMessage protocol. All messages share a versioned envelope:
{ "v": 1, "type": "<direction>.<category>", "id": "optional", "payload": {} }
vis the protocol version integer (currently1).typeuseshost.*for host-to-embed messages andembed.*for embed-to-host messages.idis used to correlate request/response pairs.- Messages missing
vortypeare malformed and silently discarded.
Handshake
The embed sends embed.ready as soon as it boots. The host should send host.hello after the iframe's load event fires.
Host Embed (inside iframe)
| |
| <iframe src="…" loads> |
| | boots → sends embed.ready
| ← embed.ready ────────────── |
| |
| ─── host.hello ────────────► |
embed.ready (embed → host):
// Received by the host page:
window.addEventListener('message', (e) => {
if (e.data.type === 'embed.ready') {
const { agentId, version, capabilities } = e.data.payload;
console.log('Agent ready:', agentId, version);
}
});
host.hello (host → embed):
iframe.contentWindow.postMessage({
v: 1,
type: 'host.hello',
payload: {
hostName: 'my-site.com',
hostVersion: '1.0',
hostOrigin: window.location.origin
}
}, '*');
Host → embed messages
type |
Payload | Description |
|---|---|---|
host.hello |
{ hostName, hostVersion, hostOrigin, userId?, userName? } |
Initiates the handshake after iframe load. |
host.chat.message |
{ role, text, messageId } |
Delivers a chat turn. role is "user" or "assistant". |
host.action |
{ action, args? } |
Triggers a named agent action. |
host.theme |
{ mode } |
Updates visual theme. mode is "dark" or "light". |
host.response |
{ result? } or { error? } |
Reply to an embed.request, matched by id. |
Sending a chat message:
iframe.contentWindow.postMessage({
v: 1,
type: 'host.chat.message',
payload: {
role: 'user',
text: 'What can you help me with?',
messageId: 'msg_001'
}
}, '*');
Triggering an action:
// Make the agent wave
iframe.contentWindow.postMessage({
v: 1,
type: 'host.action',
payload: { action: 'emote.wave', args: {} }
}, '*');
// Make the agent speak
iframe.contentWindow.postMessage({
v: 1,
type: 'host.action',
payload: { action: 'speak', args: { text: 'Welcome back!' } }
}, '*');
Embed → host messages
type |
Payload | Description |
|---|---|---|
embed.ready |
{ agentId, version, capabilities } |
Agent fully booted. |
embed.event |
{ event, data? } |
Agent lifecycle event. Common events: agent.speaking, agent.idle, agent.emote, agent.error. |
embed.request |
{ method, params? } |
Ask the host for data. Host replies with host.response matching id. |
embed.error |
{ code, message } |
Protocol-level error (malformed message, unsupported action). |
Listening for agent events:
window.addEventListener('message', (e) => {
if (!e.data?.type?.startsWith('embed.')) return;
switch (e.data.type) {
case 'embed.ready':
console.log('Agent capabilities:', e.data.payload.capabilities);
break;
case 'embed.event':
if (e.data.payload.event === 'agent.speaking') {
console.log('Agent said:', e.data.payload.data?.text);
}
break;
}
});
Security
- The embed validates
e.source === window.parentbefore processing any message. - The host should validate that
e.sourceis the expected iframe'scontentWindow. - Neither side should
eval()ornew Function()message content.
Display modes
All four modes run the same agent runtime — only the layout differs. Switch at any time with el.setMode() or by changing the mode attribute.
inline (default)
Fills its container. Set dimensions via CSS on the element or via the width/height attributes.
<agent-3d src="agent://base/42" style="width:100%;height:480px"></agent-3d>
When only width is set and responsive is on, the element automatically maintains a 3:4 portrait aspect ratio via CSS aspect-ratio.
floating
Fixed-position bubble. Does not affect document flow. Defaults to the bottom-right corner.
<agent-3d
src="agent://base/42"
mode="floating"
position="bottom-right"
offset="24px 24px"
width="320px"
height="420px"
></agent-3d>
On viewports narrower than 480 px (when responsive is on), the floating bubble automatically collapses to a 56 px pill. Tapping the pill expands it into a bottom-sheet. Swiping down or tapping outside collapses it again.
section
Fills a parent container with aspect-ratio preservation. Suited for hero sections and feature rows.
<section class="hero">
<agent-3d src="agent://base/42" mode="section"></agent-3d>
</section>
fullscreen
Takes over the full viewport (position: fixed; inset: 0).
<agent-3d src="agent://base/42" mode="fullscreen"></agent-3d>
Kiosk mode
The kiosk attribute strips all interactive chrome: the chat input, mic button, validator overlays, and editor entry points are all hidden. The 3D canvas fills the element. Use this for signage, product displays, and presentation contexts where end-user interaction is not desired.
<agent-3d
src="agent://base/42"
kiosk
style="width:100%;height:600px"
></agent-3d>
Kiosk mode is applied at element construction time. Toggling the kiosk attribute after boot has no effect on the existing shadow DOM — destroy and recreate the element if a runtime toggle is needed.
CSS custom properties
Themeable properties are exposed on the :host. They apply to the chat surface, input row, and mic button.
agent-3d {
--agent-bubble-radius: 16px; /* corner radius (floating mode) */
--agent-accent: #3b82f6; /* button + focus color */
--agent-surface: rgba(17, 24, 39, 0.92); /* chat/input background */
--agent-on-surface: #f9fafb; /* chat text color */
--agent-chat-font: system-ui, -apple-system, sans-serif;
--agent-mic-glow: #22c55e; /* mic button active glow */
--agent-shadow: 0 20px 60px rgba(0,0,0,0.3); /* floating mode shadow */
}
The host page's stylesheet cannot leak into the shadow DOM beyond these properties.
Shadow DOM slots
Content placed inside <agent-3d> is rendered as a fallback when JavaScript is disabled or the script fails to load.
<agent-3d src="agent://base/42">
<!-- Shown if JS is blocked or unavailable -->
<img src="./leo-poster.webp" alt="Coach Leo (requires JavaScript)" />
</agent-3d>
The element also accepts named slots:
| Slot | Purpose |
|---|---|
poster |
Shown during load; fades out when the model is ready. |
error |
Shown if loading fails. Replaces the default error overlay. |
ar-button |
Custom AR launch button. Use this to replace the default button with your own styling. The element receives disabled when AR is unavailable and aria-busy while a WebXR session is starting. |
chat |
Full chat UI override — host your own chat surface and subscribe to events. |
CSP and sandboxing
<agent-3d> is compatible with strict Content Security Policies:
- No inline
<script>tags are injected into the host page. - No
eval()ornew Function(). - External resources (GLB, HDRI, manifests) are loaded only from URLs you provide in attributes.
- WASM decoders (DRACO, KTX2) are fetched from configurable CDN paths; a self-hosted mode is supported.
- LLM API calls route through
key-proxywhen set — no API keys in client-side markup.
When embedding in a sandboxed <iframe>, include at minimum:
<iframe
src="https://three.ws/a/8453/42/embed"
sandbox="allow-scripts allow-same-origin"
></iframe>
allow-same-origin is required for WebGL context creation. allow-scripts is required for the element to run at all.
Framework integration
<agent-3d> is a standard custom element and works in any framework that renders HTML.
React
TypeScript users need to declare the element type to suppress JSX warnings.
// Declare once, e.g. in global.d.ts
declare namespace JSX {
interface IntrinsicElements {
'agent-3d': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
src?: string;
'body'?: string;
'agent-id'?: string;
'chain-id'?: string;
mode?: string;
brain?: string;
kiosk?: boolean;
eager?: boolean;
};
}
}
// Usage
import '@three-ws/sdk';
function AgentCard() {
return (
<agent-3d
src="agent://base/42"
style={{ width: '400px', height: '500px' }}
/>
);
}
Attach event listeners via useEffect and a ref:
import { useEffect, useRef } from 'react';
function AgentCard() {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
const handler = (e: Event) => {
const ce = e as CustomEvent;
console.log('Agent said:', ce.detail.content);
};
el.addEventListener('brain:message', handler);
return () => el.removeEventListener('brain:message', handler);
}, []);
return <agent-3d ref={ref} src="agent://base/42" style={{ width: '400px', height: '500px' }} />;
}
Vue 3
Tell the Vue compiler that agent-3d is a custom element so it does not try to resolve it as a Vue component.
// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
isCustomElement: (tag) => tag === 'agent-3d'
}
}
})
]
});
<template>
<agent-3d
src="agent://base/42"
style="width: 400px; height: 500px"
@agent:ready="onReady"
/>
</template>
<script setup>
import '@three-ws/sdk';
function onReady(e) {
console.log('ready', e.detail.manifest.name);
}
</script>
Svelte
Svelte handles custom elements natively. No configuration needed.
<script>
import '@three-ws/sdk';
let el;
function onReady(e) {
console.log('ready', e.detail.manifest.name);
}
</script>
<agent-3d
bind:this={el}
src="agent://base/42"
style="width:400px;height:500px"
on:agent:ready={onReady}
/>
Vanilla JS (ESM)
import 'https://three.ws/agent-3d/1.5.2/agent-3d.js';
const el = document.querySelector('agent-3d');
el.addEventListener('agent:ready', async () => {
const reply = await el.ask('Hello!');
console.log(reply);
});
UMD (no ES modules)
<script src="https://three.ws/agent-3d/1.5.2/agent-3d.umd.cjs"></script>
Multi-agent scenes (<agent-stage>)
To render multiple agents in a single WebGL context, wrap <agent-3d> elements in <agent-stage>. Each agent keeps its own brain, memory, and voice pipeline; the stage manages shared renderer resources.
<agent-stage formation="row" style="width:100%;height:540px">
<agent-3d
id="leo"
name="Coach Leo"
body="https://three.ws/avatars/xbot.glb"
instructions="You are Coach Leo."
eager
></agent-3d>
<agent-3d
id="mira"
name="Mira"
body="https://three.ws/avatars/realistic-female.glb"
brain="none"
eager
></agent-3d>
</agent-stage>
const stage = document.querySelector('agent-stage');
stage.addEventListener('stage:agent-joined', (e) => console.log('joined:', e.detail.agentId));
stage.addEventListener('stage:message', (e) => console.log('msg:', e.detail));
// Broadcast a protocol event to all agents in the stage
stage.broadcast('narrator', { kind: 'cue', text: 'Action!' });
Resource usage
- Lazy mount — the element does nothing until it intersects the viewport. Add
eagerto override. - Pause off-screen — the RAF render loop pauses when the element is fully off-screen and resumes on re-entry.
- Tab visibility — mic and LLM streaming suspend when the tab is hidden; the scene render loop pauses.
- Single WebGL context — the framework enforces one renderer per element.
<agent-stage>shares one context across all its agents.
CDN versioning
Three URL channels are available. Pick based on how strictly you need to control updates.
| Path | Cache | Use when |
|---|---|---|
/agent-3d/<MAJOR>.<MINOR>.<PATCH>/agent-3d.js |
immutable |
Production. Pin exact bytes. Combine with SRI. |
/agent-3d/<MAJOR>.<MINOR>/agent-3d.js |
5 min at the CDN, up to 1 h in a browser | Follow the newest code on this minor line. |
/agent-3d/<MAJOR>/agent-3d.js |
5 min at the CDN, up to 1 h in a browser | Follow the newest code on this major line. |
/agent-3d/latest/agent-3d.js |
5 min at the CDN, up to 1 h in a browser | Demos and prototypes only. Never in production. |
The moving channels send max-age=3600, s-maxage=300: the CDN revalidates every five minutes, but a browser that already holds the file may keep it for an hour, so a fix on a moving channel can take up to an hour to reach a returning visitor.
What "immutable" guarantees
A MAJOR.MINOR.PATCH URL serves the same bytes for as long as that release exists, so
an integrity hash taken from it never goes stale. Each version is cut exactly once:
npm run release:libbuilds the library, uploadsagent-3d.jsandagent-3d.umd.cjsto a write-once archive (gs://three-ws-lib-releases/agent-3d/<version>/, public athttps://storage.googleapis.com/three-ws-lib-releases/agent-3d/<version>/), and records their SRI hashes indata/agent-3d-releases.json. It refuses to re-cut a version that already exists with different bytes: bumppackage.jsoninstead.- Every deploy (
scripts/publish-lib.mjs, insidebuild:gcp) serves each released version from that archive, after checking the bytes against the recorded hash. It never writes a version directory from the current build. - The moving channels (
<MAJOR>.<MINOR>,<MAJOR>,latest) serve the build that is currently deployed, which can be newer than the newest release.versions.jsonmarks them"build": "current"and lists that build's hashes undercurrentBuild; do not pin those hashes, because the next deploy replaces them. check:distfails a build when a released file indist/does not hash to its recorded value, whenversions.jsonadvertises anything else, or when a documentedintegritypin in the docs or skills disagrees with the release it names.npm run check:sri-pins -- --fixrewrites stale documented pins from the ledger, and the same check runs undernpm test.
Before 2026-10-01 the version directory was rebuilt on every deploy while the version
string stayed at 1.5.2, so its bytes, and therefore its hash, changed under every pinned
embed. 1.5.2 is now frozen at the bytes production served on that date
(sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q); a pin taken
from an earlier deploy has to be updated to that value once.
Current SRI hashes are at /agent-3d/<version>/integrity.json. The full release manifest is at /agent-3d/versions.json, or from the origin API at /api/agent-3d/versions, which serves the identical JSON with an ETag:
curl -s https://three.ws/api/agent-3d/versions
# {"latest":"1.5.2","channels":{"1.5.2":{"integrity":{…},"immutable":true,…},…},"currentBuild":{…},"publishedAt":"…"}
# Poll cheaply: an unchanged manifest answers 304 with no body.
curl -s -o /dev/null -w '%{http_code}\n' \
-H 'If-None-Match: "9yN2NE81wIeacx634mP3ShqfkuR"' \
https://three.ws/api/agent-3d/versions
Both are CORS-open (access-control-allow-origin: *) and cached for 60 seconds.
Recommended production snippet:
<script
type="module"
src="https://three.ws/agent-3d/1.5.2/agent-3d.js"
integrity="sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q"
crossorigin="anonymous"
></script>
Custom tag name
If you need to ship the element under your own brand name, call defineElement with a custom tag:
import { defineElement } from 'https://three.ws/agent-3d/1.5.2/agent-3d.js';
defineElement('my-agent');
// <my-agent src="agent://base/42"></my-agent>
defineElement is a no-op if the tag is already registered.
Browser compatibility
- Chrome, Edge, Firefox, Safari — modern evergreen versions with WebGL 2 support.
- No framework dependency — works in React, Vue, Svelte, Angular, plain HTML, WordPress, Webflow, Framer, Notion embeds, and Shopify.
- iOS Safari — WebXR is not supported. AR falls back to Quick Look (USDZ).
- Browsers without
IntersectionObserver(very old) boot immediately rather than lazily. - Browsers without
SpeechRecognition(window.SpeechRecognition || window.webkitSpeechRecognition) — mic/STT silently no-ops. Voice output (TTS) still works.
Related
- SDK & Library: installing the bundle, building from source, programmatic imports
- JavaScript API: the viewer and validator classes under the hood
- Embedding guide: iframe patterns, CSP, and platform-specific embeds
- Widgets: the no-code alternative to hand-writing this element