Skip to content

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.

d

nirholasbec3ce00482b
diff --git a/3d-demo/.prettierrc b/3d-demo/.prettierrc
new file mode 100644
index 000000000..adeaa28fb
--- /dev/null
+++ b/3d-demo/.prettierrc
@@ -0,0 +1,10 @@
+{
+ "printWidth": 140,
+ "tabWidth": 2,
+ "useTabs": false,
+ "semi": false,
+ "singleQuote": true,
+ "trailingComma": "none",
+ "bracketSpacing": true,
+ "jsxBracketSameLine": true
+}
\ No newline at end of file
diff --git a/3d-demo/package.json b/3d-demo/package.json
new file mode 100644
index 000000000..ff7db0096
--- /dev/null
+++ b/3d-demo/package.json
@@ -0,0 +1,35 @@
+{
+ "name": "basic-demo",
+ "version": "1.0.0",
+ "description": "Shows how to form self-contained components with their own state and user interaction.",
+ "keywords": [
+ "interaction",
+ "pointer-events"
+ ],
+ "main": "src/index.js",
+ "dependencies": {
+ "@react-three/drei": "9.108.4",
+ "@react-three/fiber": "8.16.8",
+ "@types/three": "0.166.0",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "react-scripts": "5.0.1",
+ "three": "0.166.1",
+ "@react-three/postprocessing": "2.16.2",
+ "postprocessing": "6.35.6",
+ "r3f-perf": "7.2.1"
+ },
+ "devDependencies": {},
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test --env=jsdom",
+ "eject": "react-scripts eject"
+ },
+ "browserslist": [
+ ">1%",
+ "not dead",
+ "not ie <= 11",
+ "not op_mini all"
+ ]
+}
\ No newline at end of file
diff --git a/3d-demo/public/index.html b/3d-demo/public/index.html
new file mode 100644
index 000000000..42ae2d2dc
--- /dev/null
+++ b/3d-demo/public/index.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+ <meta name="theme-color" content="#000000">
+ <!--
+ manifest.json provides metadata used when your web app is added to the
+ homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
+ -->
+ <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
+ <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
+ <!--
+ Notice the use of %PUBLIC_URL% in the tags above.
+ It will be replaced with the URL of the `public` folder during the build.
+ Only files inside the `public` folder can be referenced from the HTML.
+
+ Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+ work correctly both with client-side routing and a non-root public URL.
+ Learn how to configure a non-root public URL by running `npm run build`.
+ -->
+ <title>React App</title>
+</head>
+
+<body>
+ <noscript>
+ You need to enable JavaScript to run this app.
+ </noscript>
+ <div id="root"></div>
+ <!--
+ This HTML file is a template.
+ If you open it directly in the browser, you will see an empty page.
+
+ You can add webfonts, meta tags, or analytics to this file.
+ The build step will place the bundled scripts into the <body> tag.
+
+ To begin the development, run `npm start` or `yarn start`.
+ To create a production bundle, use `npm run build` or `yarn build`.
+ -->
+</body>
+
+</html>
\ No newline at end of file
diff --git a/3d-demo/src/App.js b/3d-demo/src/App.js
new file mode 100644
index 000000000..ead7211b7
--- /dev/null
+++ b/3d-demo/src/App.js
@@ -0,0 +1,76 @@
+// https://discourse.threejs.org/t/meshes-push-away-from-mouse-hover/68397
+
+import * as THREE from 'three'
+import { useRef, useMemo } from 'react'
+import { Canvas, extend, useFrame } from '@react-three/fiber'
+import { OrbitControls, Instances, Instance } from '@react-three/drei'
+import { EffectComposer, N8AO, Bloom } from '@react-three/postprocessing'
+import { RoundedBoxGeometry } from 'three-stdlib'
+import { easing } from 'maath'
+
+extend({ RoundedBoxGeometry })
+
+export default function App() {
+ return (
+ <Canvas shadows gl={{ antialias: false }} camera={{ position: [15, 15, 15], fov: 25 }}>
+ <color attach="background" args={['#151520']} />
+ <ambientLight intensity={Math.PI / 2} />
+ <spotLight position={[-10, 20, 20]} angle={0.15} penumbra={1} decay={0} intensity={2} castShadow />
+ <Cubes gap={0.1} stride={4} displacement={3} intensity={1} />
+ <EffectComposer>
+ <N8AO aoRadius={1} intensity={1} />
+ <Bloom mipmapBlur luminanceThreshold={1} levels={7} intensity={1} />
+ </EffectComposer>
+ <OrbitControls />
+ </Canvas>
+ )
+}
+
+function Cubes({ gap = 0.1, stride = 4, displacement = 3, intensity = 1 }) {
+ const cursor = new THREE.Vector3()
+ const oPos = new THREE.Vector3()
+ const vec = new THREE.Vector3()
+ const dir = new THREE.Vector3()
+ const ref = useRef()
+
+ const positions = useMemo(() => {
+ const temp = []
+ const center = stride / 2 - stride * gap + gap
+ for (let x = 0; x < stride; x++)
+ for (let y = 0; y < stride; y++)
+ for (let z = 0; z < stride; z++) temp.push([x + x * gap - center, y + y * gap - center, z + z * gap - center])
+ return temp
+ }, [stride, gap])
+
+ useFrame(({ pointer, camera, clock }, delta) => {
+ cursor.set(pointer.x, pointer.y, 0.5).unproject(camera)
+ dir.copy(cursor).sub(camera.position).normalize()
+ cursor.add(dir.multiplyScalar(camera.position.length()))
+ let count = 0
+ for (let child of ref.current.children) {
+ oPos.set(...positions[count++])
+ dir.copy(oPos).sub(cursor).normalize()
+ const dist = oPos.distanceTo(cursor)
+ const distInv = displacement - dist
+ const col = Math.max(0.5, distInv) / 1.5
+ const mov = 1 + Math.sin(clock.elapsedTime * 2 + 1000 * count)
+ easing.dampC(child.color, dist > displacement * 1.1 ? 'white' : [col / 2, col * 2, col * 4], 0.1, delta)
+ easing.damp3(
+ child.position,
+ dist > displacement ? oPos : vec.copy(oPos).add(dir.multiplyScalar(distInv * intensity + mov / 4)),
+ 0.2,
+ delta
+ )
+ }
+ })
+
+ return (
+ <Instances key={stride} limit={stride * stride * stride} castShadow receiveShadow frames={Infinity} ref={ref}>
+ <roundedBoxGeometry args={[1, 1, 1, 2, 0.15]} />
+ <meshLambertMaterial />
+ {Array.from({ length: stride * stride * stride }, (v, n) => (
+ <Instance key={n} position={positions[n]} />
+ ))}
+ </Instances>
+ )
+}
diff --git a/3d-demo/src/index.js b/3d-demo/src/index.js
new file mode 100644
index 000000000..bbad08026
--- /dev/null
+++ b/3d-demo/src/index.js
@@ -0,0 +1,5 @@
+import { createRoot } from 'react-dom/client'
+import './styles.css'
+import App from './App'
+
+createRoot(document.getElementById('root')).render(<App />)
diff --git a/3d-demo/src/styles.css b/3d-demo/src/styles.css
new file mode 100644
index 000000000..c15822261
--- /dev/null
+++ b/3d-demo/src/styles.css
@@ -0,0 +1,16 @@
+* {
+ box-sizing: border-box;
+}
+
+html,
+body,
+#root {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ background: #f0f0f0;
+}
diff --git a/3d-demo/thumbnail.png b/3d-demo/thumbnail.png
new file mode 100644
index 000000000..6cf7a2c97
Binary files /dev/null and b/3d-demo/thumbnail.png differ
diff --git a/agent-embed.html b/agent-embed.html
index 6a14ad6df..2c0643b8f 100644
--- a/agent-embed.html
+++ b/agent-embed.html
@@ -232,6 +232,43 @@
}
await viewer.load(glbUrl, '', new Map());
+ if (bg !== 'transparent') {
+ const { Clouds, Cloud } = await import('./src/cloud.js');
+ // Midnight-blue atmosphere — set three.js scene background to match body
+ viewer.scene.background.set('#070b18');
+
+ const clouds = new Clouds({ limit: 350 });
+
+ // Deep background sweep — wide, slow, anchors the scene
+ const back = new Cloud({ seed: 1, segments: 40, bounds: [14, 5, 4], volume: 4, color: '#7a9ad8', fade: 32, opacity: 0.9, speed: 0.012 });
+ back.position.set(0, 1.5, -9);
+ clouds.add(back);
+
+ // Mid left — cool blue wisps
+ const left = new Cloud({ seed: 7, segments: 25, bounds: [6, 2.5, 2], volume: 3, color: '#b8ccff', fade: 20, opacity: 0.65, speed: 0.038 });
+ left.position.set(-3.5, 0.8, -5);
+ clouds.add(left);
+
+ // Mid right — slightly warmer, offset depth
+ const right = new Cloud({ seed: 13, segments: 25, bounds: [6, 2, 2], volume: 3, color: '#ccd8ff', fade: 22, opacity: 0.6, speed: 0.05 });
+ right.position.set(3.2, 1.2, -6);
+ clouds.add(right);
+
+ // Foreground haze — etheral and close, fades fast
+ const fore = new Cloud({ seed: 42, segments: 15, bounds: [4, 1.5, 1], volume: 2, color: 'white', fade: 7, opacity: 0.28, speed: 0.07 });
+ fore.position.set(0, -0.8, -2);
+ clouds.add(fore);
+
+ // Upper accent — gives vertical depth
+ const top = new Cloud({ seed: 99, segments: 18, bounds: [8, 2, 2], volume: 3.5, color: '#a0b8f0', fade: 25, opacity: 0.5, speed: 0.025 });
+ top.position.set(-1, 4, -7);
+ clouds.add(top);
+
+ viewer.scene.add(clouds);
+ if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];
+ viewer._afterAnimateHooks.push((dt) => clouds.update(viewer.activeCamera, dt));
+ }
+
const avatarCtl = new AgentAvatar(viewer, protocol, identity);
avatarCtl.attach();
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 2d6113352..0fb418d71 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -9,6 +9,7 @@ import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js
const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens
const REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens
const SESSION_TTL_SEC = 60 * 60 * 24 * 30; // 30d browser sessions
+const SESSION_REFRESH_WINDOW_SEC = 60 * 60 * 24 * 7; // rotate when < 7d remain
// Lazy: env.JWT_SECRET throws if unset, so defer encoding until first use.
let _jwtKey;
@@ -118,6 +119,16 @@ function readSessionCookie(req) {
return m ? decodeURIComponent(m[1]) : null;
}
+/**
+ * Issue a new session and revoke the old one. Returns the new plaintext token.
+ * @param {{ currentSid: string, userId: string, userAgent: string|null, ip: string|null }} opts
+ */
+export async function rotateSession({ currentSid, userId, userAgent, ip }) {
+ const newSecret = await createSession({ userId, userAgent, ip });
+ await sql`update sessions set revoked_at = now() where id = ${currentSid}`;
+ return newSecret;
+}
+
export async function createSession({ userId, userAgent, ip }) {
const secret = randomToken(32);
const hash = await sha256(secret);
diff --git a/api/api-keys.js b/api/api-keys.js
new file mode 100644
index 000000000..ea7a29e22
--- /dev/null
+++ b/api/api-keys.js
@@ -0,0 +1,78 @@
+import { randomToken, sha256 } from './_lib/crypto.js';
+import { sql } from './_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';
+import { cors, json, error, wrap, method, readJson } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { parse } from './_lib/validate.js';
+import { z } from 'zod';
+
+const ALLOWED_SCOPES = new Set([
+ 'avatars:read',
+ 'avatars:write',
+ 'avatars:delete',
+ 'profile',
+]);
+
+const createSchema = z.object({
+ name: z.string().trim().min(1).max(80),
+ scope: z
+ .string()
+ .optional()
+ .default('avatars:read avatars:write')
+ .transform((s) => s.trim()),
+ expires_at: z.string().datetime().optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'profile'))
+ return error(res, 403, 'insufficient_scope', 'requires profile scope');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const rows = await sql`
+ select id, name, prefix, scope, last_used_at, expires_at, revoked_at, created_at
+ from api_keys
+ where user_id = ${userId} and revoked_at is null
+ order by created_at desc
+ `;
+ return json(res, 200, { data: rows });
+ }
+
+ // POST — create
+ const body = parse(createSchema, await readJson(req));
+
+ // Validate requested scopes are all known
+ const requestedScopes = body.scope.split(/\s+/).filter(Boolean);
+ const invalid = requestedScopes.filter((s) => !ALLOWED_SCOPES.has(s));
+ if (invalid.length)
+ return error(res, 400, 'validation_error', `unknown scopes: ${invalid.join(', ')}`);
+
+ const token = `sk_live_${randomToken(32)}`;
+ const prefix = token.slice(0, 14); // "sk_live_" + 6 chars
+ const tokenHash = await sha256(token);
+
+ const [row] = await sql`
+ insert into api_keys (user_id, name, prefix, token_hash, scope, expires_at)
+ values (
+ ${userId},
+ ${body.name},
+ ${prefix},
+ ${tokenHash},
+ ${requestedScopes.join(' ')},
+ ${body.expires_at ?? null}
+ )
+ returning id, name, prefix, scope, expires_at, created_at
+ `;
+
+ // token is returned only on creation — not stored in plaintext
+ return json(res, 201, { data: { ...row, token } });
+});
diff --git a/api/api-keys/[id].js b/api/api-keys/[id].js
new file mode 100644
index 000000000..98ddf3c6a
--- /dev/null
+++ b/api/api-keys/[id].js
@@ -0,0 +1,32 @@
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, error, wrap, method } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['DELETE'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'profile'))
+ return error(res, 403, 'insufficient_scope', 'requires profile scope');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const { id } = req.query;
+
+ const [row] = await sql`
+ update api_keys
+ set revoked_at = now()
+ where id = ${id} and user_id = ${userId} and revoked_at is null
+ returning id
+ `;
+
+ if (!row) return error(res, 404, 'not_found', 'API key not found or already revoked');
+
+ return json(res, 200, { data: { id: row.id, revoked: true } });
+});
diff --git a/lobehub-plugin/dev/index.html b/lobehub-plugin/dev/index.html
index 77993a6cb..075281e91 100644
--- a/lobehub-plugin/dev/index.html
+++ b/lobehub-plugin/dev/index.html
@@ -173,6 +173,10 @@
<label style="width: 80px">Agent ID</label>
<input type="text" id="agent-id-input" placeholder="agent-xyz-123" />
</div>
+ <div class="row">
+ <label style="width: 80px">GLB URL</label>
+ <input type="text" id="src-input" placeholder="optional — bypasses agent API (e.g. /avatars/cz.glb)" />
+ </div>
<div class="row">
<label style="width: 80px">API Origin</label>
<input type="text" id="origin-input" value="https://3dagent.vercel.app" />
@@ -253,13 +257,17 @@
function loadAgent() {
agentId = document.getElementById('agent-id-input').value.trim();
apiOrigin = document.getElementById('origin-input').value.trim();
- if (!agentId) {
- alert('Enter an Agent ID first.');
+ const srcVal = document.getElementById('src-input').value.trim();
+ if (!agentId && !srcVal) {
+ alert('Enter an Agent ID or GLB URL first.');
return;
}
isReady = false;
statusDot.className = 'status-dot';
- const url = `${apiOrigin}/lobehub/iframe/?agent=${encodeURIComponent(agentId)}&host=${encodeURIComponent(location.origin)}`;
+ const base = apiOrigin.replace(/\/$/, '');
+ let url = `${base}/lobehub/iframe/?host=${encodeURIComponent(location.origin)}`;
+ if (srcVal) url += `&src=${encodeURIComponent(srcVal)}`;
+ if (agentId) url += `&agent=${encodeURIComponent(agentId)}`;
frame.src = url;
appendLog(`→ Loading ${url}`);
}
diff --git a/public/lobehub/iframe/boot.js b/public/lobehub/iframe/boot.js
index d8bda8edb..4185b2857 100644
--- a/public/lobehub/iframe/boot.js
+++ b/public/lobehub/iframe/boot.js
@@ -24,6 +24,7 @@ function isDev(origin) {
const params = new URL(location.href).searchParams;
const agentId = params.get('agent') || '';
+const srcParam = params.get('src') || '';
// ?host=<encoded-origin> restricts accepted parent to one origin.
let allowedOrigin = null;
@@ -80,10 +81,12 @@ function setStatus(text) {
if (statusEl) statusEl.textContent = text;
}
-if (agentId) {
+if (srcParam) {
+ el.setAttribute('src', decodeURIComponent(srcParam));
+} else if (agentId) {
el.setAttribute('agent-id', agentId);
} else {
- setStatus('No agent specified — add ?agent=<id> to the URL.');
+ setStatus('No agent specified — add ?agent=<id> or ?src=<glb-url> to the URL.');
}
el.addEventListener('agent:ready', (ev) => {
@@ -132,7 +135,7 @@ async function dispatchAction(op, payload, replyId) {
try {
switch (op) {
case 'speak':
- await el.say?.(payload.text || '', { sentiment: payload.sentiment });
+ el.speak?.(payload.text || '', { sentiment: payload.sentiment ?? 0 });
break;
case 'gesture':
if (payload.name === 'wave') {
diff --git a/public/lobehub/iframe/index.html b/public/lobehub/iframe/index.html
index 285a7033e..ac90ba666 100644
--- a/public/lobehub/iframe/index.html
+++ b/public/lobehub/iframe/index.html
@@ -34,16 +34,16 @@
}
</style>
<!--
- Loads the <agent-3d> web component from the 3D Agent CDN.
- For local development, run `npm run build:lib` and serve dist-lib/ under
- /agent-3d/latest/ so this path resolves without hitting the CDN.
+ Loads the <agent-3d> web component. In production loads from CDN; in dev
+ loads from the local Vite dev server so local changes are reflected immediately.
LobeChat's sandbox CSP must allow module scripts from this origin.
-->
- <script
- type="module"
- src="https://3dagent.vercel.app/agent-3d/latest/agent-3d.js"
- crossorigin
- ></script>
+ <script type="module">
+ const CDN = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';
+ const h = location.hostname;
+ const isLocal = h === 'localhost' || h === '127.0.0.1' || h.endsWith('.github.dev') || h.endsWith('.local');
+ import(isLocal ? '/src/lib.js' : CDN);
+ </script>
</head>
<body>
<div id="status">Loading…</div>
diff --git a/scripts/seed-agent.mjs b/scripts/seed-agent.mjs
new file mode 100644
index 000000000..00e0c6650
--- /dev/null
+++ b/scripts/seed-agent.mjs
@@ -0,0 +1,19 @@
+import { neon } from '@neondatabase/serverless';
+
+const sql = neon('postgresql://neondb_owner:npg_4nWXZhq2Hjse@ep-rapid-surf-ak9p7occ-pooler.c-3.us-west-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require');
+
+const [user] = await sql`
+ INSERT INTO users (email, display_name, email_verified)
+ VALUES ('[email protected]', 'Seed User', true)
+ ON CONFLICT (email) DO UPDATE SET display_name = EXCLUDED.display_name
+ RETURNING id
+`;
+
+const [agent] = await sql`
+ INSERT INTO agent_identities (user_id, name, description, home_url)
+ VALUES (${user.id}, 'Demo Agent', 'Seed agent for dev harness testing', 'https://3dagent.vercel.app')
+ RETURNING id
+`;
+
+console.log('user_id: ', user.id);
+console.log('agent_id:', agent.id);
diff --git a/src/cloud.js b/src/cloud.js
new file mode 100644
index 000000000..fd6abd105
--- /dev/null
+++ b/src/cloud.js
@@ -0,0 +1,164 @@
+import {
+ Color,
+ DynamicDrawUsage,
+ InstancedBufferAttribute,
+ InstancedMesh,
+ Matrix4,
+ MeshLambertMaterial,
+ Object3D,
+ PlaneGeometry,
+ SRGBColorSpace,
+ TextureLoader,
+ Vector3,
+} from 'three';
+
+const CLOUD_TEXTURE =
+ 'https://rawcdn.githack.com/pmndrs/drei-assets/9225a9f1fbd449d9411125c2f419b843d0308c9b/cloud.png';
+
+// mulberry32 — fast, seeded, deterministic
+function seededRand(seed) {
+ let s = seed >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let t = Math.imul(s ^ (s >>> 15), 1 | s);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/**
+ * Cloud — data container, child of Clouds.
+ * @param {object} opts
+ * @param {number} opts.seed seeded randomisation (default 0)
+ * @param {number} opts.segments sprite count (default 20)
+ * @param {number[]} opts.bounds [x,y,z] distribution box (default [5,1,1])
+ * @param {number} opts.scale uniform scale multiplier (default 1)
+ * @param {number} opts.volume sprite size factor (default 6)
+ * @param {number} opts.speed rotation speed (default 0)
+ * @param {number} opts.fade camera-distance fade radius (default 10)
+ * @param {number} opts.opacity base opacity (default 1)
+ * @param {string} opts.color tint color (default 'white')
+ */
+export class Cloud extends Object3D {
+ constructor({ seed = 0, segments = 20, bounds = [5, 1, 1], scale = 1, volume = 6, speed = 0, fade = 10, opacity = 1, color = 'white' } = {}) {
+ super();
+ this._cfg = { seed, segments, bounds, scale, volume, speed, fade, opacity, color: new Color(color) };
+ this._segs = [];
+ this._build();
+ }
+
+ _build() {
+ const { seed, segments, bounds, scale, volume, speed } = this._cfg;
+ const rand = seededRand(seed);
+ const [bx, by, bz] = Array.isArray(bounds) ? bounds : [bounds.x, bounds.y, bounds.z];
+ this._segs = Array.from({ length: segments }, () => ({
+ pos: new Vector3((rand() - 0.5) * bx, (rand() - 0.5) * by, (rand() - 0.5) * bz),
+ rot: rand() * Math.PI * 2,
+ size: (0.4 + rand() * 0.6) * volume * scale,
+ rotSpeed: (rand() - 0.5) * speed,
+ }));
+ }
+}
+
+/**
+ * Clouds — container that renders all child Cloud instances in one draw call.
+ *
+ * Usage:
+ * const clouds = new Clouds();
+ * clouds.add(new Cloud({ segments: 40, bounds: [10,2,2], volume: 10, color: 'white' }));
+ * scene.add(clouds);
+ * // in animation loop:
+ * clouds.update(camera, delta);
+ *
+ * @param {object} opts
+ * @param {string} opts.texture custom texture URL (default: drei cloud asset)
+ * @param {number} opts.limit max total segments across all clouds (default 200)
+ * @param {object} opts.material custom THREE.Material override
+ */
+export class Clouds extends Object3D {
+ constructor({ texture, limit = 200, material } = {}) {
+ super();
+ this._limit = limit;
+ this._mat = material || null;
+ this._url = texture || CLOUD_TEXTURE;
+ this._mesh = null;
+ this._elapsed = 0;
+ // pre-allocated temps — no per-frame GC
+ this._dummy = new Object3D();
+ this._tmp = new Vector3();
+ this._col = new Color();
+ this._inv = new Matrix4();
+ this._load();
+ }
+
+ _load() {
+ new TextureLoader().load(this._url, (tex) => {
+ tex.colorSpace = SRGBColorSpace;
+ const mat =
+ this._mat ||
+ new MeshLambertMaterial({
+ map: tex,
+ transparent: true,
+ depthWrite: false,
+ side: 2, // DoubleSide
+ });
+ this._mesh = new InstancedMesh(new PlaneGeometry(1, 1), mat, this._limit);
+ this._mesh.instanceMatrix.setUsage(DynamicDrawUsage);
+ this._mesh.instanceColor = new InstancedBufferAttribute(new Float32Array(this._limit * 3), 3);
+ this._mesh.count = 0;
+ this._mesh.frustumCulled = false;
+ this.add(this._mesh);
+ });
+ }
+
+ /**
+ * Call once per frame inside your animation loop.
+ * @param {THREE.Camera} camera
+ * @param {number} delta seconds since last frame
+ */
+ update(camera, delta = 0.016) {
+ if (!this._mesh) return;
+ this._elapsed += delta;
+
+ // World→Clouds-local matrix so instance matrices stay in parent space
+ this.updateWorldMatrix(true, false);
+ this._inv.copy(this.matrixWorld).invert();
+
+ const camPos = camera.position;
+ let idx = 0;
+
+ for (const child of this.children) {
+ if (!(child instanceof Cloud)) continue;
+ child.updateWorldMatrix(true, false);
+ const { fade, opacity, color } = child._cfg;
+
+ for (const seg of child._segs) {
+ // segment in world space
+ this._tmp.copy(seg.pos).applyMatrix4(child.matrixWorld);
+
+ // billboard: face camera
+ this._dummy.position.copy(this._tmp);
+ this._dummy.lookAt(camPos);
+ this._dummy.rotation.z = seg.rot + this._elapsed * seg.rotSpeed;
+
+ // distance fade — scale to 0 beyond fade radius
+ const dist = this._tmp.distanceTo(camPos);
+ const vis = fade > 0 ? Math.max(0, 1 - dist / fade) : 1;
+ this._dummy.scale.setScalar(seg.size * vis);
+ this._dummy.updateMatrix();
+
+ // convert world-space matrix → Clouds-local for instance
+ this._dummy.matrix.premultiply(this._inv);
+ this._mesh.setMatrixAt(idx, this._dummy.matrix);
+
+ this._col.copy(color).multiplyScalar(opacity);
+ this._mesh.setColorAt(idx, this._col);
+ idx++;
+ }
+ }
+
+ this._mesh.count = Math.min(idx, this._limit);
+ this._mesh.instanceMatrix.needsUpdate = true;
+ if (this._mesh.instanceColor) this._mesh.instanceColor.needsUpdate = true;
+ }
+}
diff --git a/src/element.js b/src/element.js
index c5696ae89..a60a9dfc5 100644
--- a/src/element.js
+++ b/src/element.js
@@ -12,7 +12,7 @@ import { resolveAgentById, resolveByAgentId, AgentResolveError } from './agent-r
import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolver.js';
// BEGIN:EMBED_BRIDGES_IMPORT
import { EmbedActionBridge } from './embed-action-bridge.js';
-import { protocol } from './agent-protocol.js';
+import { protocol, ACTION_TYPES } from './agent-protocol.js';
// END:EMBED_BRIDGES_IMPORT
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
@@ -947,6 +947,11 @@ class Agent3DElement extends HTMLElement {
return this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
}
+ // Emit speak directly on the protocol bus — triggers avatar animation without going through LLM.
+ speak(text, opts = {}) {
+ protocol.emit(ACTION_TYPES.SPEAK, { text, sentiment: opts.sentiment ?? 0 });
+ }
+
async ask(text, opts = {}) {
const reply = await this.say(text, opts);
return reply?.text || '';