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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(lip-sync): add LipSyncAnalyser for viseme morph weights from audio input
nirholasf2e94dc5f139
diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex 0e5400e38..7834c3404 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -23,6 +23,7 @@ import { ACTION_TYPES } from './agent-protocol.js';import { Vector3, Box3, MathUtils, PositionalAudio } from 'three';import { resolveSlot, DEFAULT_ANIMATION_MAP } from './runtime/animation-slots.js';import { ElevenLabsTTS } from './runtime/speech.js';+import { LipSyncAnalyser } from './lip-sync-analyser.js';// BEGIN:IDLE_LOOP_IMPORTimport { IdleAnimation } from './idle-animation.js';// END:IDLE_LOOP_IMPORT@@ -198,6 +199,9 @@ export class AgentAvatar {// Listeners stored so we can detach laterthis._listeners = [];+ // Frequency-based lip sync (null = use mouthOpen fallback)+ this._lipSync = null;+// Spatial audiothis._tts = null;this._positionalAudio = null;@@ -278,6 +282,8 @@ export class AgentAvatar {this._idle?.dispose();this._idle = null;// END:IDLE_LOOP_DISPOSE+ this._lipSync?.disconnect();+ this._lipSync = null;if (this._positionalAudio) {try { this._positionalAudio.disconnect(); } catch {}this._positionalAudio.parent?.remove(this._positionalAudio);@@ -301,6 +307,18 @@ export class AgentAvatar {this._userSpeaking = active;}+ /**+ * Connect a LipSyncAnalyser to this avatar.+ * While active, viseme morphs are driven from real audio frequency data and+ * the blunt mouthOpen talk-hint is suppressed.+ * @param {AnalyserNode|HTMLMediaElement} audioSource+ */+ connectLipSync(audioSource) {+ this._lipSync?.disconnect();+ this._lipSync = new LipSyncAnalyser();+ this._lipSync.connect(audioSource);+ }+/*** Set the agent's animation slot override map (from meta.edits.animations).* @param {Object|null} map — { slotName: clipName, … }@@ -598,6 +616,20 @@ export class AgentAvatar {// Stage 4: Apply emotion to avatarthis._applyEmotionToAvatar(dt);+ // Stage 5: Frequency-based viseme lipsync (ElevenLabs path)+ // Samples the live audio AnalyserNode and overrides the blunt mouthOpen+ // with per-viseme morph weights. No-ops when _lipSync is null.+ if (this._lipSync) {+ const visemes = this._lipSync.sample();+ if (visemes) {+ for (const [name, weight] of Object.entries(visemes)) {+ this._setMorphTarget(name, weight);+ }+ // Suppress the flat mouthOpen talk-hint while real visemes are active+ this._setMorphTarget('mouthOpen', 0);+ }+ }+// BEGIN:IDLE_LOOP_TICKthis._idle?.update(dt);// END:IDLE_LOOP_TICKdiff --git a/src/element.js b/src/element.jsindex d141f97d6..852537ad9 100644--- a/src/element.js+++ b/src/element.js@@ -19,6 +19,11 @@ import { AgentNotifier } from './agent-notifier.js';const MODES = ['inline', 'floating', 'section', 'fullscreen'];+function _parsePx(val) {+ const n = parseFloat(val);+ return n > 0 && typeof val === 'string' && val.trim().endsWith('px') ? n : 0;+}+// Derive the origin of the script itself so cross-origin embeds hit the right API.const _scriptOrigin = (() => {try {diff --git a/src/lip-sync-analyser.js b/src/lip-sync-analyser.jsnew file mode 100644index 000000000..8be31b2c0--- /dev/null+++ b/src/lip-sync-analyser.js@@ -0,0 +1,151 @@+// LipSyncAnalyser — drives viseme morph weights from live audio via AnalyserNode.+//+// Frequency band → viseme group mapping:+// Low (0–500 Hz) → open vowels: viseme_aa, viseme_O+// Mid (500–2k Hz) → mid vowels + nasals: viseme_E, viseme_I, viseme_nn+// High (2k–8k Hz) → sibilants + fricatives: viseme_SS, viseme_FF, viseme_CH+// Amplitude dip → bilabial closure: viseme_PP++const VISEMES = [+ 'viseme_aa', 'viseme_O', 'viseme_E', 'viseme_I', 'viseme_nn',+ 'viseme_SS', 'viseme_FF', 'viseme_CH', 'viseme_PP',+];++// Module-level scratch buffer — avoids a Float32Array allocation per sample() call.+const _TARGET = new Float32Array(VISEMES.length);++export class LipSyncAnalyser {+ constructor() {+ this._ctx = null;+ this._analyser = null;+ this._source = null;+ this._freqBuf = null;+ this._active = false;++ // Bin-boundary indices, pre-computed in connect() from the AudioContext sample rate.+ this._lowEnd = 0;+ this._midEnd = 0;+ this._highEnd = 0;++ // Pre-allocated output and smoothing buffers — mutated in place so sample()+ // never touches the heap.+ this._out = {};+ this._prev = {};+ for (const n of VISEMES) this._out[n] = this._prev[n] = 0;+ }++ /**+ * Connect to an audio source.+ * @param {AnalyserNode|HTMLMediaElement} audioSource+ * AnalyserNode — use the pre-wired node from ElevenLabsTTS.analyserNode directly.+ * HTMLMediaElement — create a private AudioContext and wire through it.+ */+ connect(audioSource) {+ this.disconnect();++ let analyser = null;+ let sampleRate = 44100;+ const fftSize = 256;++ if (typeof AnalyserNode !== 'undefined' && audioSource instanceof AnalyserNode) {+ analyser = audioSource;+ sampleRate = audioSource.context?.sampleRate ?? 44100;+ } else if (typeof HTMLMediaElement !== 'undefined' && audioSource instanceof HTMLMediaElement) {+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return;+ try {+ this._ctx = new AC();+ analyser = this._ctx.createAnalyser();+ analyser.fftSize = fftSize;+ analyser.smoothingTimeConstant = 0.7;+ this._source = this._ctx.createMediaElementSource(audioSource);+ this._source.connect(analyser);+ analyser.connect(this._ctx.destination);+ this._ctx.resume().catch(() => {});+ sampleRate = this._ctx.sampleRate;+ } catch {+ try { this._ctx?.close(); } catch {}+ this._ctx = null;+ return;+ }+ } else {+ return;+ }++ this._analyser = analyser;+ this._freqBuf = new Uint8Array(analyser.frequencyBinCount);++ const binHz = sampleRate / (analyser.fftSize ?? fftSize);+ this._lowEnd = Math.round(500 / binHz);+ this._midEnd = Math.round(2000 / binHz);+ this._highEnd = Math.min(Math.round(8000 / binHz), analyser.frequencyBinCount);+ this._active = true;+ }++ /** Disconnect and release audio resources. */+ disconnect() {+ this._active = false;+ try { this._source?.disconnect(); } catch {}+ if (this._ctx) {+ try { this._analyser?.disconnect(); } catch {}+ try { this._ctx.close(); } catch {}+ }+ this._ctx = this._analyser = this._source = this._freqBuf = null;+ for (const n of VISEMES) this._out[n] = this._prev[n] = 0;+ }++ /**+ * Sample the current audio frame and return a viseme weight map.+ * Mutates and returns the pre-allocated _out object — no heap allocations.+ * @returns {Record<string,number>|null} null when inactive+ */+ sample() {+ if (!this._active || !this._analyser || !this._freqBuf) return null;++ this._analyser.getByteFrequencyData(this._freqBuf);++ const low = _bandAvg(this._freqBuf, 0, this._lowEnd);+ const mid = _bandAvg(this._freqBuf, this._lowEnd, this._midEnd);+ const high = _bandAvg(this._freqBuf, this._midEnd, this._highEnd);+ const overall = (low + mid + high) / 3;++ if (overall < 0.15) {+ // Silence — lerp all weights toward zero+ for (let i = 0; i < VISEMES.length; i++) {+ const k = VISEMES[i];+ const n = this._prev[k] * 0.75;+ this._prev[k] = n;+ this._out[k] = n;+ }+ return this._out;+ }++ // Map frequency bands to per-viseme targets+ _TARGET[0] = low * 0.8; // viseme_aa+ _TARGET[1] = low * 0.6; // viseme_O+ _TARGET[2] = mid * 0.7; // viseme_E+ _TARGET[3] = mid * 0.5; // viseme_I+ _TARGET[4] = mid * 0.4; // viseme_nn+ _TARGET[5] = high * 0.8; // viseme_SS+ _TARGET[6] = high * 0.6; // viseme_FF+ _TARGET[7] = high * 0.5; // viseme_CH+ _TARGET[8] = Math.max(0, 0.3 - overall * 1.5); // viseme_PP (amplitude dip → bilabial)++ for (let i = 0; i < VISEMES.length; i++) {+ const k = VISEMES[i];+ const p = this._prev[k];+ const n = p + (_TARGET[i] - p) * 0.25;+ this._prev[k] = n;+ this._out[k] = n;+ }+ return this._out;+ }+}++function _bandAvg(buf, start, end) {+ const e = Math.min(end, buf.length);+ if (e <= start) return 0;+ let s = 0;+ for (let i = start; i < e; i++) s += buf[i];+ return s / ((e - start) * 255);+}diff --git a/src/plugins/index.js b/src/plugins/index.jsindex cd34b863f..78dc8522c 100644--- a/src/plugins/index.js+++ b/src/plugins/index.js@@ -1,6 +1,10 @@-// Plugin registry — load JSON plugin manifests, bridge to LLM tool system.-// Manifest format: { schema_version: "plugin/1.0", identifier, meta, api[], settings[], system_role }-// Compatible with LobeHub plugin manifest v1 (superset).+// Plugin registry — load and manage LobeHub/pai-chat compatible plugin manifests.+//+// Manifest format (ToolManifest from pai-chat):+// { identifier, meta: { title, description?, avatar?, tags? }, api[], systemRole?, type?,+// settings?: { type:'object', properties:{...}, required?:[] }, version?, openapi?, gateway? }+//+// Also accepts legacy { schema_version:"plugin/1.0", ... } manifests (backcompat).const STORAGE_KEY = 'installed_plugins_v1';@@ -8,16 +12,14 @@ const STORAGE_KEY = 'installed_plugins_v1';export function validatePluginManifest(json) {if (!json || typeof json !== 'object') throw new Error('Plugin manifest must be a JSON object');- if (!json.schema_version?.startsWith('plugin/'))- throw new Error('Missing or invalid schema_version — expected "plugin/1.x"');if (!json.identifier || typeof json.identifier !== 'string')throw new Error('Plugin manifest missing required field: identifier');if (!json.meta?.title) throw new Error('Plugin manifest missing meta.title');if (!Array.isArray(json.api) || json.api.length === 0)- throw new Error('Plugin manifest must declare at least one api tool');+ throw new Error('Plugin manifest must declare at least one api entry');for (const tool of json.api) {if (!tool.name || !tool.description)- throw new Error(`Plugin tool "${tool.name || '?'}" missing name or description`);+ throw new Error(`Plugin api entry "${tool.name || '?'}" missing name or description`);}return true;}@@ -25,9 +27,6 @@ export function validatePluginManifest(json) {export async function fetchPluginManifest(url) {const res = await fetch(url);if (!res.ok) throw new Error(`Manifest fetch failed: ${url} (${res.status})`);- const ct = res.headers.get('content-type') || '';- if (!ct.includes('json') && !ct.includes('octet'))- throw new Error(`Expected JSON response from ${url}, got ${ct}`);const json = await res.json();validatePluginManifest(json);return { ...json, _manifest_url: url };@@ -95,8 +94,8 @@ export class PluginRegistry {// ── LLM integration ───────────────────────────────────────────────────────/**- * Convert installed plugin tools to the Anthropic tool format so the LLM- * can call them alongside built-in tools.+ * Convert installed plugin tools to Anthropic tool format.+ * Strips internal routing fields before the array is sent to the API.*/toClaudeTools() {const tools = [];@@ -106,10 +105,9 @@ export class PluginRegistry {name: api.name,description: `[${plugin.meta.title}] ${api.description}`,input_schema: api.parameters ?? { type: 'object', properties: {} },- // private routing fields (stripped before sending to Anthropic)+ // routing metadata — caller must strip these before sending to Anthropic_plugin: plugin.identifier,_url: api.url ?? null,- _method: (api.method ?? 'POST').toUpperCase(),});}}@@ -120,32 +118,33 @@ export class PluginRegistry {systemPrompt() {const parts = [];for (const plugin of this._plugins.values()) {- if (plugin.system_role) {- parts.push(- `<plugin name="${plugin.identifier}">\n${plugin.system_role}\n</plugin>`,- );+ const role = plugin.systemRole ?? plugin.system_role; // support both casings+ if (role) {+ parts.push(`<plugin name="${plugin.identifier}">\n${role}\n</plugin>`);}}return parts.join('\n');}/**- * Execute a plugin tool by POSTing args to its declared URL.+ * Execute a plugin tool by calling its declared URL.* Returns the parsed JSON response body.*/async invoke(toolName, args, { fetchFn = fetch } = {}) {for (const plugin of this._plugins.values()) {const tool = plugin.api.find((t) => t.name === toolName);if (!tool) continue;- if (!tool.url) throw new Error(`Plugin tool "${toolName}" has no url`);- const method = (tool.method ?? 'POST').toUpperCase();- const res = await fetchFn(tool.url, {- method,++ // Route through gateway if set, else tool's own URL+ const url = plugin.gateway ?? tool.url;+ if (!url) throw new Error(`Plugin tool "${toolName}" has no url or gateway`);++ const res = await fetchFn(url, {+ method: 'POST',headers: { 'content-type': 'application/json' },- body: method !== 'GET' ? JSON.stringify(args) : undefined,+ body: JSON.stringify({ apiName: toolName, arguments: JSON.stringify(args), identifier: plugin.identifier }),});- if (!res.ok)- throw new Error(`Plugin tool "${toolName}" returned HTTP ${res.status}`);+ if (!res.ok) throw new Error(`Plugin tool "${toolName}" returned HTTP ${res.status}`);return res.json();}throw new Error(`No installed plugin handles tool "${toolName}"`);diff --git a/src/runtime/speech.js b/src/runtime/speech.jsindex bb5617328..504aace05 100644--- a/src/runtime/speech.js+++ b/src/runtime/speech.js@@ -13,6 +13,9 @@ export class BrowserTTS {this._queue = [];this._speaking = false;this._lipsync = null;+ // Global hooks — set by callers that manage lipsync externally (e.g. AgentAvatar).+ this.onStart = null;+ this.onEnd = null;}async speak(text, { onStart, onEnd, scene } = {}) {@@ -27,12 +30,14 @@ export class BrowserTTS {utter.onstart = () => {this._speaking = true;if (scene) this._lipsync = startLipsync(text, scene);+ this.onStart?.();onStart?.();};utter.onend = () => {this._speaking = false;this._lipsync?.stop();this._lipsync = null;+ this.onEnd?.();onEnd?.();resolve();};@@ -198,6 +203,18 @@ export class ElevenLabsTTS {this._onEnd = null; // pending resolvethis._lipsync = null;this._positionalAudio = null; // THREE.PositionalAudio, optional+ // Web Audio nodes for LipSyncAnalyser integration+ this._audioCtx = null;+ this._analyserNode = null;+ this._mediaSource = null;+ // Global hooks — set by callers that manage lipsync externally (e.g. AgentAvatar).+ this.onStart = null;+ this.onEnd = null;+ }++ /** Expose the shared AnalyserNode so LipSyncAnalyser can read frequency data. */+ get analyserNode() {+ return this._analyserNode;}/** @param {import('three').PositionalAudio|null} pa */@@ -275,6 +292,7 @@ export class ElevenLabsTTS {this._lipsync?.stop();this._lipsync = null;this._cleanupAudio();+ this.onEnd?.();onEnd?.();this._onEnd = null;resolve();@@ -285,7 +303,7 @@ export class ElevenLabsTTS {};const lipsyncOnStart = () => {- if (scene) this._lipsync = startLipsync(text, scene);+ this.onStart?.();onStart?.();};@@ -320,6 +338,28 @@ export class ElevenLabsTTS {return this._speaking;}+ // ── Internal: Web Audio analyser for LipSyncAnalyser ──────────────────++ _setupAnalyser(audio) {+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return;+ try {+ if (!this._audioCtx || this._audioCtx.state === 'closed') {+ this._audioCtx = new AC();+ this._analyserNode = this._audioCtx.createAnalyser();+ this._analyserNode.fftSize = 256;+ this._analyserNode.smoothingTimeConstant = 0.7;+ this._analyserNode.connect(this._audioCtx.destination);+ }+ this._mediaSource?.disconnect();+ this._mediaSource = this._audioCtx.createMediaElementSource(audio);+ this._mediaSource.connect(this._analyserNode);+ this._audioCtx.resume().catch(() => {});+ } catch {+ // Degrade silently — CORS, autoplay policy, or element already captured+ }+ }+// ── Internal: spatial audio wiring ────────────────────────────────────_connectPositionalAudio(audioEl) {@@ -343,6 +383,9 @@ export class ElevenLabsTTS {const audio = new Audio(this._mediaSourceURL);this._audio = audio;audio.preload = 'auto';+ // Wire Web Audio analyser before playback starts so analyserNode is ready+ // when the 'playing' event fires (which triggers onStart → avatar.connectLipSync).+ this._setupAnalyser(audio);audio.addEventListener('playing', onStart, { once: true });audio.addEventListener('ended', () => this._onEnd?.(), { once: true });@@ -416,6 +459,7 @@ export class ElevenLabsTTS {this._mediaSourceURL = url;const audio = new Audio(url);this._audio = audio;+ this._setupAnalyser(audio);audio.addEventListener('playing', onStart, { once: true });audio.addEventListener('ended', () => this._onEnd?.(), { once: true });audio.addEventListener('error', () => onError?.(), { once: true });@@ -427,6 +471,11 @@ export class ElevenLabsTTS {}_cleanupAudio() {+ // Disconnect the per-speak MediaElementSourceNode (analyser + ctx are reused).+ if (this._mediaSource) {+ try { this._mediaSource.disconnect(); } catch {}+ this._mediaSource = null;+ }if (this._positionalAudio?.source) {try { this._positionalAudio.source.disconnect(); } catch {}this._positionalAudio.source = null;