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(docs): add Platform Pages section to README with user-facing route details
nirholasf63c369399d2
diff --git a/README.md b/README.mdindex 08a5f689e..fe3c1bab6 100644--- a/README.md+++ b/README.md@@ -17,6 +17,7 @@ https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4- [Vision](#vision)- [Roadmap](#roadmap)- [Key Features](#key-features)+- [Platform Pages](#platform-pages)- [Screenshots](#screenshots)- [Architecture](#architecture)- [Tech Stack](#tech-stack)@@ -229,6 +230,35 @@ If you want to support the project — compute credits, grants, partnerships, or---+## Platform Pages++A map of every user-facing route. Full detail (source files, feature descriptions, hash-routes) is in [docs/internal/PAGES.md](docs/internal/PAGES.md).++| Section | Key URLs | What it does |+|---|---|---|+| **Landing** | `/`, `/features`, `/discover` | Marketing, public agent directory |+| **App / Core** | `/app`, `/create`, `/first-meet` | 3D viewer, agent creation wizard, onboarding |+| **Marketplace** | `/marketplace`, `/marketplace/agents/[id]` | Browsable agent marketplace |+| **Chat SPA** | `/chat` | Full Svelte AI chat with model selector, tools, artifacts, wallet |+| **Chat — Marketing** | `/chat#solutions/*`, `/chat#business/*` | Per-team and enterprise landing pages |+| **Chat — Features** | `/chat#features/*` | Feature detail pages (web-app, mobile-app, ai-design, ai-slides, browser-operator, wide-research, mail, skills) |+| **Chat — Resources** | `/chat#resources/*` | Blog, docs, trust center, updates, use cases |+| **Auth** | `/login`, `/register`, `/forgot-password`, `/reset-password` | Email + wallet sign-in/up |+| **Agent (Platform)** | `/agent/[id]`, `/agent/[id]/embed`, `/agent/[id]/edit` | Agent chat, chromeless embed, manifest editor |+| **Agent (On-Chain)** | `/a/[chain]/[id]`, `/a/sol/[asset]` | ERC-8004 and Metaplex Core passports |+| **Profile** | `/profile`, `/u/[username]`, `/avatars/[id]` | User and avatar public pages |+| **Dashboard** | `/dashboard`, `/dashboard/actions`, `/dashboard/wallets`, `/dashboard/usage`, … | Account management and settings |+| **Studio / Tools** | `/studio`, `/hydrate`, `/validation`, `/strategy-lab` | Widget Studio, on-chain import, glTF validator, DCA |+| **Widgets** | `/widgets`, `/w/[id]` | Widget gallery and public widget pages (OG + oEmbed) |+| **Artifacts** | `/artifact`, `/artifact/snippet`, `/artifact-example` | Claude Artifact viewer |+| **Solana / DeFi** | `/pumpfun`, `/vanity-wallet` | Token launcher, vanity address grinder |+| **Admin / Rep** | `/admin`, `/reputation` | Staff admin, reputation registry |+| **Integrations** | `/cz`, `/lobehub/iframe` | CZ demo, LobeHub plugin |+| **Docs** | `/docs`, `/docs/widgets` | Developer documentation |+| **Legal** | `/legal/privacy`, `/legal/tos` | Privacy policy and terms |++---+## Screenshots| Viewer | Widget Studio |diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex 9e6c2af21..cbbb9b4dd 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -1523,6 +1523,35 @@let agentPickerOpen = false;let showAgentSettings = false;+ // Drag state for the floating agent widget+ let dragPos = { x: null, y: null };+ let dragging = false;+ let dragOffset = { x: 0, y: 0 };++ function onAvatarDragStart(e) {+ if (e.button !== 0) return;+ if (e.target.closest('button, input, a, select')) return;+ e.preventDefault();+ const rect = e.currentTarget.getBoundingClientRect();+ dragOffset = { x: e.clientX - rect.left, y: e.clientY - rect.top };+ dragging = true;+ window.addEventListener('mousemove', onAvatarDragMove);+ window.addEventListener('mouseup', onAvatarDragEnd);+ }++ function onAvatarDragMove(e) {+ if (!dragging) return;+ const x = Math.max(0, Math.min(window.innerWidth - 240, e.clientX - dragOffset.x));+ const y = Math.max(0, Math.min(window.innerHeight - 60, e.clientY - dragOffset.y));+ dragPos = { x, y };+ }++ function onAvatarDragEnd() {+ dragging = false;+ window.removeEventListener('mousemove', onAvatarDragMove);+ window.removeEventListener('mouseup', onAvatarDragEnd);+ }+$: effectiveAgentId = $localAgentId || $brandConfig.agent_id || '';$: if (effectiveAgentId && !agentScriptLoaded) {@@ -1539,6 +1568,7 @@$: if (agentEl && !agentReady) {agentEl.addEventListener('agent:ready', () => {agentReady = true;+ agentEl.play('idle', { loop: true }).catch(() => {});if (agentPendingSpeak) {agentEl.speak(agentPendingSpeak);agentPendingSpeak = null;@@ -2366,7 +2396,16 @@{/if}{#if true}- <div class="fixed bottom-4 right-4 z-50 flex flex-col items-end gap-2">+ <!-- svelte-ignore a11y-no-static-element-interactions -->+ <div+ class="z-[100] flex flex-col items-end gap-2 select-none"+ class:cursor-grabbing={dragging}+ style={dragPos.x !== null+ ? `position: fixed; left: ${dragPos.x}px; top: ${dragPos.y}px;`+ : 'position: fixed; bottom: 1rem; right: 1rem;'}+ on:mousedown={onAvatarDragStart}+ role="none"+ >{#if agentPickerOpen}<div class="mb-1 w-72 rounded-xl border border-gray-200 bg-white p-3 shadow-xl"><AgentPicker on:pick={(e) => { agentPickerOpen = false; if (!e.detail) clearAgentFromConvo(); }} />@@ -2384,10 +2423,12 @@background="transparent"kioskname-plate="off"- style="width:220px;height:220px;"+ style="width:220px;height:220px; cursor: grab;"></agent-3d>{:else if $talkingHeadEnabled && agentVisible}- <TalkingHead bind:this={talkingHead} on:ready={onTalkingHeadReady} avatarUrl={$talkingHeadAvatarUrl || undefined} />+ <div style="cursor: grab;">+ <TalkingHead bind:this={talkingHead} on:ready={onTalkingHeadReady} avatarUrl={$talkingHeadAvatarUrl || undefined} />+ </div>{/if}<div class="flex items-center gap-1.5">diff --git a/chat/src/manus/MoreDropdown.svelte b/chat/src/manus/MoreDropdown.svelteindex 9255f0ca8..f8161fef5 100644--- a/chat/src/manus/MoreDropdown.svelte+++ b/chat/src/manus/MoreDropdown.svelte@@ -3,19 +3,19 @@import Icon from '../Icon.svelte';import { mode } from '../stores.js';import {- feRotateCw, feCamera, feLink, feSliders, feActivity, feLayers, feZap,+ feZap, feBarChart2, feLink, feRotateCw, feCode, feCamera, feSliders,} from '../feather.js';const dispatch = createEventDispatcher();const items = [- { id: 'animate', label: 'Animate model', icon: feRotateCw },- { id: 'ar', label: 'AR experience', icon: feCamera },- { id: 'wallet', label: 'Connect wallet', icon: feLink },- { id: 'emotions', label: 'Configure emotions', icon: feSliders },- { id: 'reputation', label: 'Track reputation', icon: feActivity },- { id: 'skills', label: 'Add agent skills', icon: feLayers },- { id: 'solana', label: 'Mint on Solana', icon: feZap },+ { id: 'pumpfun', label: 'Pump.fun live feed', icon: feZap },+ { id: 'curve', label: 'Bonding curve', icon: feBarChart2 },+ { id: 'wallet', label: 'Connect wallet', icon: feLink },+ { id: 'animate', label: 'Animate mascot', icon: feRotateCw },+ { id: 'embed', label: 'Embed on token site', icon: feCode },+ { id: 'ar', label: 'AR showcase', icon: feCamera },+ { id: 'emotions', label: 'Mascot emotions', icon: feSliders },];function pick(item) {diff --git a/chat/src/manus/SuggestionChips.svelte b/chat/src/manus/SuggestionChips.svelteindex 9c69287a2..1393e45f6 100644--- a/chat/src/manus/SuggestionChips.svelte+++ b/chat/src/manus/SuggestionChips.svelte@@ -1,16 +1,16 @@<script>import { mode } from '../stores.js';import Icon from '../Icon.svelte';- import { feBox, feHexagon, feTrendingUp, feCode, feMoreHorizontal } from '../feather.js';+ import { feTrendingUp, feBox, feActivity, feHexagon, feMoreHorizontal } from '../feather.js';import MoreDropdown from './MoreDropdown.svelte';let moreOpen = false;const chips = [- { id: '3d-avatar', label: 'Build 3D avatar', icon: feBox },- { id: 'onchain', label: 'Mint agent on-chain', icon: feHexagon },- { id: 'token', label: 'Launch token', icon: feTrendingUp },- { id: 'widget', label: 'Deploy as widget', icon: feCode },+ { id: 'token', label: 'Launch a memecoin', icon: feTrendingUp },+ { id: 'mascot', label: 'Build token mascot', icon: feBox },+ { id: 'monitor', label: 'Monitor my coin', icon: feActivity },+ { id: 'onchain', label: 'Mint mascot as NFT', icon: feHexagon },];function pick(id) {diff --git a/prompts/avatar-features/01-gaze-at-user.md b/prompts/avatar-features/01-gaze-at-user.mdnew file mode 100644index 000000000..0a6ad9f65--- /dev/null+++ b/prompts/avatar-features/01-gaze-at-user.md@@ -0,0 +1,63 @@+# Feature: Gaze at User When Speaking++## Goal+When the user is actively speaking (mic input) or has just sent a message, the avatar should bias its gaze toward the camera (i.e., "look at" the user) instead of drifting with saccades. When the agent is thinking/processing, the avatar should break eye contact and look slightly down or away — exactly as humans do.++## Context++**File to edit: `src/agent-avatar.js`**++The avatar already has a continuous gaze system:+- `this._mouseGaze { x, y }` — normalised -1..1 mouse position drives head yaw when `followMode === 'mouse'`+- `this._currentYaw` / `this._targetYaw` — horizontal gaze, lerped each frame in `_updateHeadTransform()`+- `this._currentTilt` / `this._targetTilt` — vertical lean+- `_lookTarget` — a `Vector3 | null`; when null, avatar looks at camera++**File to edit: `src/idle-animation.js`**++The idle animation already has:+- `_saccPauseTimer` — when > 0, saccade micro-movements pause (already wired to LOOK_AT events)+- `_blinkPauseTimer` — when > 0, blink is suppressed (already wired to SPEAK events)++**Protocol events already available** (from `src/agent-protocol.js` `ACTION_TYPES`):+- `speak` — agent is speaking (payload: `{ text, sentiment }`)+- `think` — agent is processing (payload: `{ thought }`)+- `load-start` / `load-end` — skill running++## What to build++### 1. Add a `_userSpeaking` flag to `AgentAvatar`++Wire it to whatever STT/input signal is available. For now, expose a public method:+```js+setUserSpeaking(active) {+ this._userSpeaking = active;+}+```++### 2. Gaze bias logic in `_updateHeadTransform()` (around line 615 in agent-avatar.js)++When `_userSpeaking === true`:+- Override `targetYaw` to 0 (face camera directly)+- Override `targetTilt` to slight upward (+0.04 rad) — attentive posture+- Suppress saccade drift by calling `this._idle?.setPauseSaccade(true)`++When agent is thinking (`this._emotion.patience > 0.3` or a new `_agentThinking` flag):+- Bias `targetYaw` to a small random offset (±0.15 rad) — looking away to "think"+- Bias `targetTilt` slightly downward (-0.06 rad)++When neither: restore normal follow-mode behavior.++### 3. Suppress saccade during user-speaking++In `src/idle-animation.js`, add a `setPauseSaccade(active)` method that sets `_saccPauseTimer` to a large value (e.g., 999) when active, and 0 when released. The existing `_tickSaccade()` already skips when `_saccPauseTimer > 0`.++### 4. Wire `think` protocol event++In `attach()` in agent-avatar.js, subscribe to `ACTION_TYPES.THINK` and set `this._agentThinking = true`. On `speak` events, set `this._agentThinking = false`. Decay `_agentThinking` after 3 seconds (track with a timer in `_tickEmotion()`).++## Conventions+- ESM only, tabs 4-wide, JSDoc for public methods, no TypeScript+- No new imports needed — `Vector3` and `MathUtils` already imported+- Don't touch `src/viewer.js` or `src/runtime/scene.js`+- All state in `AgentAvatar` instance fields, prefixed `_`diff --git a/prompts/avatar-features/02-interrupt-reaction.md b/prompts/avatar-features/02-interrupt-reaction.mdnew file mode 100644index 000000000..297f08103--- /dev/null+++ b/prompts/avatar-features/02-interrupt-reaction.md@@ -0,0 +1,73 @@+# Feature: Interrupt Body Reaction++## Goal+When the user speaks while the agent is mid-response (interrupts the TTS), the avatar should physically react — a small startled head snap or "wait" gesture — before the LLM catches up. Makes the interaction feel alive instead of the avatar blankly continuing to talk while the audio cuts off.++## Context++**`src/runtime/speech.js`** — contains `BrowserTTS` and `ElevenLabsTTS`. Both have a `stop()` method and a `_speaking` getter. ElevenLabs streams audio and can be interrupted mid-stream.++**`src/agent-avatar.js`** — has `_triggerOneShot(slot, duration)` which plays a named gesture clip from the animation library. The slot system is in `src/runtime/animation-slots.js`. Existing slots include `talk`, `nod`, `wave`, `think`, `celebrate`.++**`src/agent-protocol.js`** — the event bus. To add a new event type, add it to `ACTION_TYPES` and emit/subscribe like the others.++**`src/idle-animation.js`** — has `_saccPauseTimer` for pausing saccades (already used by LOOK_AT events).++## What to build++### 1. Add `ACTION_TYPES.INTERRUPTED` to `src/agent-protocol.js`++```js+INTERRUPTED: 'interrupted',+```++### 2. Emit `interrupted` from wherever TTS is stopped mid-speech++In both `BrowserTTS.stop()` and `ElevenLabsTTS` cancel path — emit if `_speaking` was true when stop was called:+```js+// Only if we were actually speaking, not a clean end+if (this._speaking) {+ this._speaking = false;+ protocol.emit(ACTION_TYPES.INTERRUPTED, {});+}+```+The `protocol` reference needs to be passed in at construction or as a param to `stop()`. Check how it's currently wired in `src/runtime/index.js` or `src/element.js` to find the right injection point. Prefer passing it to `stop()` to avoid changing the constructor signature.++### 3. Subscribe in `AgentAvatar.attach()`++```js+this._sub(ACTION_TYPES.INTERRUPTED, this._onInterrupted.bind(this));+```++### 4. Implement `_onInterrupted()`++```js+_onInterrupted() {+ // Quick head snap — "oh, you're talking"+ this._triggerOneShot('startle', 0.6);+ // Drain patience, inject curiosity (they're taking over)+ this._emotion.patience = 0;+ this._injectStimulus('curiosity', 0.5);+}+```++The `startle` slot probably won't exist in the animation library. Add a fallback in `_triggerOneShot` or `_playSlot`: if the clip isn't found, do a quick morph-only reaction instead (raise `browInnerUp` to 0.8, decay over 0.5s). This avoids a hard dependency on a specific animation clip existing.++### 5. Morph-only fallback for missing `startle` clip++In `_onInterrupted()`, always fire the morph reaction regardless of clip availability:+```js+this._setMorphTarget('browInnerUp', 0.9);+this._setMorphTarget('mouthOpen', 0.3);+// These will lerp back to emotion-driven values naturally in _tickEmotion+```++## Testing+- Open the app, trigger a long agent response+- Speak/click interrupt before it finishes+- Avatar should snap brows up briefly, curiosity should spike (visible in face morph)++## Conventions+- ESM only, tabs 4-wide+- Don't add `startle` to DEFAULT_ANIMATION_MAP unless the clip actually exists in the animation library — the fallback handles the missing-clip case+- Update the event vocabulary table in `src/CLAUDE.md` with the new `interrupted` typediff --git a/prompts/avatar-features/03-confidence-signaling.md b/prompts/avatar-features/03-confidence-signaling.mdnew file mode 100644index 000000000..a185a2f27--- /dev/null+++ b/prompts/avatar-features/03-confidence-signaling.md@@ -0,0 +1,117 @@+# Feature: Confidence Signaling via Avatar Body Language++## Goal+When the LLM's response is hedged or uncertain ("I think", "not sure", "might be", "probably"), the avatar should visually signal low confidence — a subtle fidget, slight head tilt, softer posture. When the response is assertive and confident, the avatar should reflect that too. Users unconsciously read this and calibrate their trust appropriately.++## Context++**`src/agent-avatar.js`** — The emotion system currently has: `neutral`, `concern`, `celebration`, `patience`, `curiosity`, `empathy`. All are continuous weighted blends.++The `_onSpeak` handler already does sentiment analysis via `_analyzeSentiment(text)` (valence + arousal) and injects stimuli. This is the right place to also detect confidence.++The morph targets already driven each frame (in `_tickEmotion` around line 490–510):+- `mouthSmile` ← celebration+- `mouthFrown` ← concern+- `browInnerUp` ← concern + empathy+- `browOuterUp` ← curiosity+- `eyeSquint` ← empathy++**`src/idle-animation.js`** — `_tickWeightShift()` drives hip bone Y rotation on a slow sine wave. The amplitude is fixed. This could be modulated by confidence level.++**`src/runtime/animation-slots.js`** — `DEFAULT_ANIMATION_MAP` maps slot names to clip names. A `fidget` slot could be added here.++## What to build++### 1. Add `uncertain` to the emotion state++In `AgentAvatar` constructor and `attach()` reset:+```js+this._emotion = {+ neutral: 1.0,+ concern: 0,+ celebration: 0,+ patience: 0,+ curiosity: 0,+ empathy: 0,+ uncertain: 0, // ← add this+};+```++In `DECAY` constant at the top of the file:+```js+uncertain: 0.10, // half-life ~7s+```++### 2. Hedge vocabulary detection++Add to the `VOCAB` object at the top of `agent-avatar.js`:+```js+uncertain: [+ "i think", "not sure", "might be", "probably", "possibly",+ "i believe", "i'm not certain", "could be", "maybe", "roughly",+ "approximately", "unclear", "uncertain", "hard to say", "it depends",+ "i'd guess", "seems like", "appears to", "not entirely sure",+],+```++Note: `_analyzeSentiment()` already scans text for vocab keywords. Check whether it handles multi-word phrases or only single tokens — if single tokens, add the single-word variants and skip phrases.++### 3. Inject `uncertain` stimulus from `_onSpeak`++In `_onSpeak()`, after the existing valence checks:+```js+const uncertainScore = this._scoreVocab(text, 'uncertain');+if (uncertainScore > 0) this._injectStimulus('uncertain', Math.min(uncertainScore * 0.4, 0.8));+```++### 4. Wire `uncertain` to morph targets in `_tickEmotion()`++Add to the morph target section:+```js+// Uncertain: slight lip press, raised inner brow (questioning look)+this._setMorphTarget('mouthPressLeft', w.uncertain * 0.35);+this._setMorphTarget('mouthPressRight', w.uncertain * 0.35);+this._setMorphTarget('browInnerUp',+ Math.max(w.concern * 0.6, w.uncertain * 0.45, w.empathy * 0.5)+);+```++### 5. Modulate idle weight-shift amplitude++In `src/idle-animation.js`, `_tickWeightShift()` currently has a fixed amplitude. Add an `_uncertaintyBias` field to `IdleAnimation` that the avatar can set:++```js+// In IdleAnimation constructor:+this._uncertaintyBias = 0; // 0..1, increases hip drift amplitude++// In IdleAnimation, add setter:+setUncertainty(value) {+ this._uncertaintyBias = Math.max(0, Math.min(1, value));+}++// In _tickWeightShift(), multiply amplitude:+const amplitude = (0.018 + this._uncertaintyBias * 0.025) * DEG2RAD;+```++In `AgentAvatar._tickEmotion()`, after computing `w`:+```js+this._idle?.setUncertainty(w.uncertain);+```++### 6. Add `fidget` slot to DEFAULT_ANIMATION_MAP (optional)++In `src/runtime/animation-slots.js`, add:+```js+fidget: 'Fidget',+```+Only matters if a Fidget clip exists in the animation library. Skip if not — the morph targets cover the visual signal.++## Testing+- Send a message that produces a hedging response ("what's the capital of France?" shouldn't trigger it; "explain quantum entanglement" likely will)+- Watch for subtle brow raise + lip press during hedged sentences+- Hip drift should increase slightly during uncertain passages++## Conventions+- ESM only, tabs 4-wide+- `uncertain` should never sum with other emotions to push `neutral` negative — `_injectStimulus` already clamps, but verify `_tickEmotion()` normalization handles the new bucket+- Update `src/CLAUDE.md` Empathy Layer tables with `uncertain` decay rate and morph mappingdiff --git a/prompts/avatar-features/04-phoneme-lip-sync.md b/prompts/avatar-features/04-phoneme-lip-sync.mdnew file mode 100644index 000000000..97e8da364--- /dev/null+++ b/prompts/avatar-features/04-phoneme-lip-sync.md@@ -0,0 +1,130 @@+# Feature: Phoneme-Based Lip Sync++## Goal+Replace the current blunt `mouthOpen` hint (triggered once per `speak` event, held for word-count duration) with per-frame viseme-driven mouth morphs that actually match the spoken audio. The avatar's mouth should move with the words, not just hang open while talking.++## Context++**Current state in `src/agent-avatar.js`:**+- `_onSpeak()` calls `_triggerOneShot('talk', duration)` which sets `_isPlayingOneShot = true`+- In `_tickEmotion()`, `mouthOpen` is set to `0.4` when `_isPlayingOneShot && _oneShotAction === 'talk'`+- That's the entire lip sync system — a flat morph hold++**`src/runtime/speech.js`** — Two TTS providers:+1. `BrowserTTS` — uses `window.SpeechSynthesis`. The `SpeechSynthesisUtterance` fires `boundary` events with word/sentence markers but no viseme data natively (Chrome 98+ has `onboundary` but not phoneme events).+2. `ElevenLabsTTS` — streams MP3 audio via fetch. No viseme stream in the current implementation.++**Morph targets already plumbed** in `src/agent-avatar.js`:+- `_morphMeshes` cache is built in `attach()`+- `_setMorphTarget(name, weight)` and `_morphLerpAll(dt)` are already called each frame+- Common ReadyPlayerMe/Mixamo viseme morph names: `viseme_PP`, `viseme_FF`, `viseme_TH`, `viseme_DD`, `viseme_kk`, `viseme_CH`, `viseme_SS`, `viseme_nn`, `viseme_RR`, `viseme_aa`, `viseme_E`, `viseme_I`, `viseme_O`, `viseme_U`++## Approach: OVR Lip Sync via Web Audio API (no external API needed)++Use the browser's `AnalyserNode` to get frequency data from the playing audio, then map frequency bands to viseme groups. This works for both BrowserTTS and ElevenLabs audio without any API changes.++This is an approximation (not true phoneme detection), but it's frame-accurate, zero-latency, and works offline.++### 1. Create `src/lip-sync-analyser.js`++```js+/**+ * LipSyncAnalyser — drives viseme morph weights from live audio via AnalyserNode.+ *+ * Frequency band → viseme group mapping (rough phoneme clustering):+ * 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+ * Closure (any gap) → bilabials: viseme_PP (mapped from amplitude dips)+ */+export class LipSyncAnalyser {+ constructor() {+ this._ctx = null;+ this._analyser = null;+ this._source = null;+ this._freqBuf = null;+ this._active = false;+ }++ /**+ * Connect an HTMLAudioElement or MediaStreamSource to the analyser.+ * @param {HTMLAudioElement|MediaStream} audioSource+ */+ connect(audioSource) { ... }++ /** Disconnect and release. */+ disconnect() { ... }++ /**+ * Call every frame. Returns a viseme weight map or null if inactive.+ * @returns {Record<string,number>|null}+ */+ sample() { ... }+}+```++Implementation notes:+- Use `FFT_SIZE = 256`, `smoothingTimeConstant = 0.7`+- `getByteFrequencyData()` into a `Uint8Array` — no allocations per frame+- Map bin ranges to the three frequency groups, normalize 0–255 → 0–1+- Apply a `0.15` silence threshold — below it, return all-zero (mouth closed)+- Smooth output values with a simple `lerp(prev, new, 0.25)` — the `AnalyserNode` already smooths internally but the output can still jitter++### 2. Integrate into `ElevenLabsTTS`++`ElevenLabsTTS` plays audio via an `<audio>` element or `AudioContext`. Find where the audio is created and:+1. Create/reuse an `AudioContext`+2. Create a `MediaElementAudioSourceNode` from the audio element+3. Connect to an `AnalyserNode`+4. Connect the analyser to `ctx.destination`+5. Expose the analyser node: `tts.analyserNode`++### 3. Integrate into `BrowserTTS` (best-effort)++`SpeechSynthesis` audio is not exposed to the Web Audio API in most browsers (security restriction). For `BrowserTTS`, fall back to a word-boundary-driven simulation:+- On each `boundary` event (word), pick a random viseme sequence of 2–4 frames (100ms each)+- Simulate a consonant → vowel → consonant arc using `_scheduleVisemeSequence()`++### 4. Wire into `AgentAvatar`++Add a `_lipSync: LipSyncAnalyser | null` field.++In `_tickEmotion(dt)`, after existing morph updates:+```js+if (this._lipSync) {+ const visemes = this._lipSync.sample();+ if (visemes) {+ for (const [name, weight] of Object.entries(visemes)) {+ this._setMorphTarget(name, weight);+ }+ // Suppress the blunt mouthOpen when real visemes are active+ this._setMorphTarget('mouthOpen', 0);+ }+}+```++Add public method:+```js+connectLipSync(analyserOrTTS) {+ this._lipSync?.disconnect();+ this._lipSync = new LipSyncAnalyser();+ this._lipSync.connect(analyserOrTTS);+}+```++### 5. Activate from wherever TTS is started++In `src/element.js` or wherever `BrowserTTS`/`ElevenLabsTTS` is wired to the avatar:+```js+tts.onStart = () => avatar.connectLipSync(tts.analyserNode ?? tts);+tts.onEnd = () => avatar._lipSync?.disconnect();+```++## Fallback behavior+If the avatar's model has no `viseme_*` morph targets (e.g. a custom non-RPM model), `_setMorphTarget` silently no-ops (it already does — the morph cache just won't have those indices). No defensive code needed.++## Conventions+- ESM only, tabs 4-wide+- `LipSyncAnalyser` must not allocate in `sample()` — pre-allocate all buffers in constructor+- Test with both BrowserTTS and ElevenLabs paths+- Don't remove the existing `mouthOpen` hint path — it serves as the fallback when `_lipSync` is nulldiff --git a/prompts/avatar-features/05-agent-to-agent-reactions.md b/prompts/avatar-features/05-agent-to-agent-reactions.mdnew file mode 100644index 000000000..5e5a0177c--- /dev/null+++ b/prompts/avatar-features/05-agent-to-agent-reactions.md@@ -0,0 +1,105 @@+# Feature: Agent-to-Agent Reactions++## Goal+When Bob roasts Alice, Alice's avatar should physically react — not just stand idle until her next turn. Cross-agent reactions make multi-agent scenes feel like actual people in the same room rather than two chatbots taking turns.++## Context++**`agent-voice-chat/agents.config.json`** — defines Bob and Alice as two separate agents, each with their own personality, voice, and avatar.++**`src/agent-protocol.js`** — each agent instance has its own `AgentProtocol` bus. Currently there is no cross-agent event forwarding.++**`src/agent-avatar.js`** — `AgentAvatar` listens to its own agent's protocol. It has no awareness of other agents.++**`agent-voice-chat/server.js`** or `src/element.js`** — where multiple agent instances are likely instantiated. This is where we can wire cross-agent reactions without modifying the avatar layer.++## Architecture++Don't add cross-agent coupling inside `AgentAvatar`. Instead, create a thin **reaction bridge** that listens to agent A's protocol and emits targeted stimuli on agent B's protocol. The bridge lives outside both agents.++### 1. Create `src/agent-reaction-bridge.js`++```js+/**+ * AgentReactionBridge — forwards emotional triggers cross-agent.+ *+ * When agentA speaks, agentB's avatar gets a stimulus proportional+ * to how "directed" the speech is (detected via name mention or sentiment).+ */+export class AgentReactionBridge {+ /**+ * @param {import('./agent-protocol.js').AgentProtocol} sourceProtocol+ * @param {import('./agent-protocol.js').AgentProtocol} targetProtocol+ * @param {string} targetName — e.g. "Alice", used for mention detection+ */+ constructor(sourceProtocol, targetProtocol, targetName) { ... }++ attach() { ... } // subscribe to source events+ detach() { ... } // unsubscribe+}+```++### 2. Reaction rules (implement in `attach()`)++Subscribe to `ACTION_TYPES.SPEAK` on `sourceProtocol`. On each speak event:++**Name mention** (`text.toLowerCase().includes(targetName.toLowerCase())`):+- Inject `curiosity: 0.6` on target (they look up / take notice)+- If sentiment < -0.3 (roast): also inject `concern: 0.3` (mock-defensive posture)+- If sentiment > 0.4 (praise): inject `celebration: 0.4`++**No name mention but high arousal** (agent is animated/excited):+- Inject `curiosity: 0.2` on target — ambient awareness of the other agent being loud++**Reaction gesture** (optional, only if a `react` slot exists):+```js+targetProtocol.emit(ACTION_TYPES.GESTURE, { name: 'react', duration: 0.8 });+```++Use `targetProtocol.emit()` to inject — the target avatar's `_onEmote` and `_onGesture` handlers already handle these.++### 3. Gaze direction during cross-agent speech++When a `SPEAK` event comes from the *other* agent, the listener's avatar should look toward that agent's position in 3D space (not at the camera).++Add an optional `targetPosition: Vector3` to the bridge constructor. When source speaks and target has a position:+```js+targetProtocol.emit(ACTION_TYPES.LOOK_AT, { target: 'agent', worldPosition: this._sourcePosition });+```++You'll need to add `'agent'` as a valid `look-at` target in `AgentAvatar._onLookAt()`:+```js+} else if (target === 'agent' && action.payload?.worldPosition) {+ const p = action.payload.worldPosition;+ this._lookTarget = new Vector3(p.x, p.y, p.z);+}+```++### 4. Wire the bridge where agents are instantiated++Find where Bob and Alice's `AgentProtocol` instances are created (likely in `agent-voice-chat/server.js` or the room manager). Add:++```js+const bobToAlice = new AgentReactionBridge(bobProtocol, aliceProtocol, 'Alice');+const aliceToBob = new AgentReactionBridge(aliceProtocol, bobProtocol, 'Bob');+bobToAlice.attach();+aliceToBob.attach();+```++Detach when agents are destroyed.++### 5. Throttle cross-agent reactions++Add a `_lastReactionAt` timestamp to the bridge. Minimum 800ms between reactions per source speak event — prevents rapid-fire stimuli when the agent speaks quickly.++## Testing+- Load the two-agent scene (Bob + Alice)+- Say something to Bob that mentions Alice+- Alice's avatar should show a curiosity/reaction without Alice speaking+- Bob saying something sarcastic ("Alice is being dramatic again") → Alice shows mild concern morph++## Conventions+- ESM only, tabs 4-wide+- The bridge is purely additive — it only injects stimuli, never suppresses or overrides+- Don't modify `AgentAvatar` internals except to add the `'agent'` look-at case+- Update `src/CLAUDE.md` event vocabulary if you add new look-at targetsdiff --git a/prompts/avatar-features/06-spatial-audio.md b/prompts/avatar-features/06-spatial-audio.mdnew file mode 100644index 000000000..de414344b--- /dev/null+++ b/prompts/avatar-features/06-spatial-audio.md@@ -0,0 +1,115 @@+# Feature: Spatial Audio for Multi-Agent Scenes++## Goal+In scenes with multiple agents (e.g. Bob + Alice side by side), each agent's voice should come from where their avatar is positioned in 3D space. Bob on the left sounds like he's on the left. Turning toward the camera makes the voice more center. This is a drop-in Three.js feature that requires no changes to the LLM or agent layers.++## Context++**`src/runtime/speech.js`** — `ElevenLabsTTS` plays audio via an `<audio>` element or `AudioContext`. This is the integration point. `BrowserTTS` uses `window.speechSynthesis` which doesn't support positional audio (browser limitation) — skip it for this feature.++**`src/viewer.js`** — contains the Three.js scene, camera, and renderer. The `camera` is accessible as `this.viewer.camera`. The `AudioListener` needs to be attached to the camera.++**`src/agent-avatar.js`** — has access to `this.viewer` and the loaded avatar model root (`this.viewer.content`). The head bone position is already discovered in `idle-animation.js` — reuse that or find the avatar root position.++**Three.js audio classes needed:**+- `THREE.AudioListener` — attached to camera once, shared across all agents+- `THREE.PositionalAudio` — one per agent, attached to a bone or the avatar root++## What to build++### 1. Singleton `AudioListener` on the camera++In `src/viewer.js` (or wherever camera setup happens), add once:+```js+if (!this._audioListener) {+ this._audioListener = new THREE.AudioListener();+ this.camera.add(this._audioListener);+}+```++Expose it: `viewer.audioListener`.++### 2. Add `PositionalAudio` support to `ElevenLabsTTS`++`ElevenLabsTTS` currently streams audio to an `<audio>` element. To make it positional, the audio needs to go through the Web Audio API graph.++Modify `ElevenLabsTTS` to accept an optional `positionalAudio: THREE.PositionalAudio`:++```js+constructor({ voiceId, proxyURL, positionalAudio = null } = {}) {+ ...+ this._positionalAudio = positionalAudio;+}+```++When `_positionalAudio` is set, route the audio source through it instead of playing directly:+```js+// Instead of: audioEl.play()+// Do:+const source = this._positionalAudio.context.createMediaElementSource(audioEl);+source.connect(this._positionalAudio.panner);+this._positionalAudio.play();+```++Three.js `PositionalAudio` wraps a `PannerNode`. You wire the source → panner → destination yourself.++### 3. Create and position `PositionalAudio` in `AgentAvatar`++In `AgentAvatar.attach()`, after the model loads:++```js+_initSpatialAudio() {+ if (!this.viewer.audioListener) return;+ if (this._positionalAudio) {+ this._positionalAudio.parent?.remove(this._positionalAudio);+ }+ this._positionalAudio = new THREE.PositionalAudio(this.viewer.audioListener);+ this._positionalAudio.setRefDistance(1.5);+ this._positionalAudio.setRolloffFactor(1.0);+ this._positionalAudio.setDistanceModel('inverse');++ // Attach to head bone if available, else avatar root+ const anchor = this._headBone ?? this.viewer.content;+ if (anchor) anchor.add(this._positionalAudio);+}+```++The `_headBone` is found in `idle-animation.js`. Either pass it up or re-traverse in `AgentAvatar` — `_buildMorphCache()` already traverses the model, so add bone discovery there.++### 4. Pass `PositionalAudio` to TTS++After `_initSpatialAudio()`, update the TTS instance:+```js+if (this._tts instanceof ElevenLabsTTS && this._positionalAudio) {+ this._tts.setPositionalAudio(this._positionalAudio);+}+```++Add `setPositionalAudio(pa)` to `ElevenLabsTTS`.++### 5. Teardown++In `AgentAvatar.detach()`:+```js+if (this._positionalAudio) {+ this._positionalAudio.stop();+ this._positionalAudio.parent?.remove(this._positionalAudio);+ this._positionalAudio = null;+}+```++## Positioning multiple agents++The spatial audio is automatic once each avatar's `PositionalAudio` node is attached to their head bone — Three.js handles panning based on world position relative to the camera/listener. No extra positioning code needed.++For Bob and Alice to sound spatially distinct, their avatar models just need to be at different X positions in the scene. Confirm the multi-agent scene layout does this.++## Fallback+- If `viewer.audioListener` is null (single-agent mode or BrowserTTS), `_initSpatialAudio()` returns early — existing audio path unchanged+- If no head bone is found, audio anchors to avatar root — still better than nothing++## Conventions+- ESM only, tabs 4-wide+- Import `AudioListener`, `PositionalAudio` from `'three'` (already a dependency)+- One `AudioListener` per page — check `viewer.audioListener` before creating+- Don't modify `BrowserTTS` — spatial audio via SpeechSynthesis isn't possible in browsersdiff --git a/prompts/avatar-features/07-screen-context-awareness.md b/prompts/avatar-features/07-screen-context-awareness.mdnew file mode 100644index 000000000..47668f79a--- /dev/null+++ b/prompts/avatar-features/07-screen-context-awareness.md@@ -0,0 +1,146 @@+# Feature: Screen / Context Awareness++## Goal+The avatar can "see" what the user is looking at — a shared canvas, a 3D model on screen, a block of code — and reference it in conversation. "The error in line 42 there" instead of "the error you mentioned." Requires a screen capture or DOM snapshot pipeline feeding context into the LLM prompt.++## Context++**`src/runtime/index.js`** — the tool loop. `MAX_TOOL_ITERATIONS = 8`. This is where the LLM system prompt is assembled and where context can be injected. Find where `messages` or the system prompt is built.++**`src/runtime/tools.js`** — `BUILTIN_TOOLS` array + `BUILTIN_HANDLERS`. Tool handlers have signature `async (args, ctx) => ({ ok: true, ... })`. The `ctx` object includes `viewer`, `memory`, `llm`, `speak`, `fetch`.++**`src/agent-skills.js`** — built-in skills. A `look_at_screen` tool could live here or in `runtime/tools.js`.++**`src/runtime/scene.js`** — `SceneController`. Has access to the Three.js renderer via `viewer.renderer`. `renderer.domElement` is the canvas.++## What to build++### 1. Add a `captureContext()` utility in `src/runtime/screen-context.js`++Three capture modes, tried in order:++**Mode A: Three.js canvas snapshot (always available)**+```js+async function captureCanvas(renderer) {+ // renderer.render() should have just run — read pixels+ return renderer.domElement.toDataURL('image/jpeg', 0.6);+}+```++**Mode B: Visible text DOM snapshot (no permissions needed)**+```js+function captureVisibleText() {+ // Walk document.body, extract text from visible elements+ // Skip hidden (display:none, visibility:hidden, off-viewport)+ // Return first 2000 chars of visible text content+}+```++**Mode C: Screen capture (requires user permission, one-time)**+```js+async function captureScreen() {+ const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });+ const track = stream.getVideoTracks()[0];+ const imageCapture = new ImageCapture(track);+ const bitmap = await imageCapture.grabFrame();+ track.stop();+ // Convert bitmap to base64 via OffscreenCanvas+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);+ canvas.getContext('2d').drawImage(bitmap, 0, 0);+ return canvas.convertToBlob({ type: 'image/jpeg', quality: 0.6 });+}+```++Export:+```js+export async function captureContext(renderer, { mode = 'canvas' } = {}) {+ if (mode === 'canvas') return { type: 'image', data: await captureCanvas(renderer) };+ if (mode === 'text') return { type: 'text', data: captureVisibleText() };+ if (mode === 'screen') return { type: 'image', data: await captureScreen() };+}+```++### 2. Add a `see_screen` built-in tool in `src/runtime/tools.js`++```js+{+ name: 'see_screen',+ description: 'Capture what is currently visible on screen and describe it to inform your response.',+ input_schema: {+ type: 'object',+ properties: {+ mode: {+ type: 'string',+ enum: ['canvas', 'text', 'screen'],+ description: 'canvas=3D viewport only, text=page text, screen=full screen (requires permission)',+ }+ },+ required: [],+ }+}+```++Handler in `BUILTIN_HANDLERS`:+```js+see_screen: async (args, ctx) => {+ const { captureContext } = await import('./screen-context.js');+ const result = await captureContext(ctx.viewer.renderer, { mode: args.mode ?? 'canvas' });+ if (result.type === 'image') {+ // Return base64 for inclusion in next LLM message as image content block+ return { ok: true, imageData: result.data, description: 'Screen captured.' };+ }+ return { ok: true, text: result.data };+},+```++### 3. Inject screen context into the LLM message++In `src/runtime/index.js`, after a `see_screen` tool result comes back, include the image as a vision content block in the next user message sent to the LLM:++```js+// If tool result contains imageData, add as image content block+if (toolResult.imageData) {+ nextUserContent.push({+ type: 'image',+ source: { type: 'base64', media_type: 'image/jpeg', data: toolResult.imageData.split(',')[1] }+ });+}+```++This requires the LLM provider to support vision (Claude claude-sonnet-4-6+ does via Anthropic API).++### 4. Auto-capture on model load (optional enhancement)++In `src/agent-avatar.js`, `_onLoadEnd()` already fires when a GLB loads. After load, auto-trigger a canvas capture and store it as context in memory:++```js+_onLoadEnd(action) {+ if (!action.payload?.error) {+ // Capture 3D scene state for reference+ setTimeout(() => {+ captureContext(this.viewer.renderer, { mode: 'canvas' }).then(ctx => {+ this.protocol.emit(ACTION_TYPES.REMEMBER, {+ type: 'scene_snapshot',+ content: ctx.data,+ uri: action.payload.uri,+ });+ });+ }, 500); // wait one render frame+ }+}+```++### 5. Privacy gate++Screen capture (`mode: 'screen'`) must only trigger on explicit user request or tool call — never automatically. Canvas and text modes are safe to use automatically since they only capture the app itself.++## Testing+- Load a GLB, ask "what color is the model?"+- The `see_screen` tool should fire, capture the canvas, and the LLM should correctly describe the visible model color+- Test `mode: 'text'` on a page with visible text content++## Conventions+- ESM only, tabs 4-wide+- `ImageCapture` API is not available in all browsers — wrap in try/catch and return `{ ok: false, error: 'Screen capture not supported' }` on failure+- Base64 image payloads are large — don't store in protocol history or memory by default+- Only `mode: 'screen'` requires user permission — document this clearly in the tool descriptiondiff --git a/prompts/avatar-features/08-avatar-push-notifications.md b/prompts/avatar-features/08-avatar-push-notifications.mdnew file mode 100644index 000000000..2788980b8--- /dev/null+++ b/prompts/avatar-features/08-avatar-push-notifications.md@@ -0,0 +1,195 @@+# Feature: Push Notifications via Avatar++## Goal+Instead of a toast or browser notification, the avatar walks into frame, delivers a short message, and retreats. Works for async events: a background skill completing, a watched value changing, a reminder firing. Makes notifications feel personal rather than system-generated.++## Context++**`src/element.js`** — `<agent-3d>` custom element. Controls the avatar's lifecycle. Has `IntersectionObserver` for lazy boot. This is where "avatar enters/exits frame" would be orchestrated.++**`src/agent-protocol.js`** — the event bus. A new `ACTION_TYPES.NOTIFY` would trigger the notification flow.++**`src/agent-avatar.js`** — `_triggerOneShot(slot, duration)` plays clips. The `SPEAK` event already drives TTS. Relevant slots: `wave`, `nod`, `think`.++**`src/runtime/data-reactive.js`** — `startDataReactive({ protocol, source, bindings, signal })` wires live SSE/WS/poll sources to the protocol bus via `{ match, emit }` bindings. This is the right trigger source for data-driven notifications.++**CSS/positioning:** The `<agent-3d>` element is typically embedded in a fixed position or inline. "Walking into frame" means animating from off-screen (transform: translateX) into a visible docked position.++## What to build++### 1. Add `ACTION_TYPES.NOTIFY` to `src/agent-protocol.js`++```js+NOTIFY: 'notify',+```++Payload: `{ message: string, priority: 'low'|'normal'|'high', duration?: number }`++### 2. Create `src/agent-notifier.js`++This class manages the notification queue and the avatar enter/exit animation. It operates on the `<agent-3d>` host element.++```js+export class AgentNotifier {+ /**+ * @param {HTMLElement} hostEl — the <agent-3d> element+ * @param {import('./agent-protocol.js').AgentProtocol} protocol+ */+ constructor(hostEl, protocol) {+ this._host = hostEl;+ this._protocol = protocol;+ this._queue = [];+ this._busy = false;+ this._originalStyles = null;+ }++ attach() {+ this._protocol.on(ACTION_TYPES.NOTIFY, this._onNotify.bind(this));+ }++ detach() {+ this._protocol.off(ACTION_TYPES.NOTIFY, this._onNotify.bind(this));+ }++ _onNotify(action) {+ this._queue.push(action.payload);+ if (!this._busy) this._processNext();+ }++ async _processNext() {+ if (!this._queue.length) { this._busy = false; return; }+ this._busy = true;+ const { message, duration = 6000 } = this._queue.shift();+ await this._enterFrame();+ this._protocol.emit(ACTION_TYPES.SPEAK, { text: message });+ await this._wait(duration);+ await this._exitFrame();+ this._processNext();+ }+}+```++### 3. Enter / exit frame animations++The enter/exit should use CSS transitions on the host element — no JS animation loop needed.++```js+async _enterFrame() {+ // Save current position/visibility state+ this._originalStyles = {+ transform: this._host.style.transform,+ opacity: this._host.style.opacity,+ visibility: this._host.style.visibility,+ };++ // Snap to off-screen start position+ this._host.style.transition = 'none';+ this._host.style.transform = 'translateX(120%)';+ this._host.style.visibility = 'visible';+ this._host.style.opacity = '0';++ // Force reflow+ void this._host.offsetWidth;++ // Slide in+ this._host.style.transition = 'transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s ease';+ this._host.style.transform = 'translateX(0)';+ this._host.style.opacity = '1';++ await this._wait(450);+}++async _exitFrame() {+ this._host.style.transition = 'transform 0.35s ease-in, opacity 0.25s ease';+ this._host.style.transform = 'translateX(120%)';+ this._host.style.opacity = '0';+ await this._wait(380);++ // Restore original state+ Object.assign(this._host.style, this._originalStyles);+ this._host.style.transition = '';+}++_wait(ms) {+ return new Promise(r => setTimeout(r, ms));+}+```++### 4. Docked position CSS++When the notifier is active, the avatar should render in a fixed docked corner (bottom-right, for example). Add a class that the notifier applies during the notification:++```css+/* In the element's shadow DOM or a global style */+agent-3d.notifying {+ position: fixed;+ bottom: 24px;+ right: 24px;+ width: 200px;+ height: 300px;+ z-index: 9999;+}+```++The notifier adds/removes the `notifying` class around `_enterFrame` / `_exitFrame`.++### 5. Wire to `element.js`++In `<agent-3d>` element's boot sequence, after protocol is initialized:++```js+this._notifier = new AgentNotifier(this, this.agent_protocol);+this._notifier.attach();+```++In `disconnectedCallback`:+```js+this._notifier?.detach();+```++### 6. Public API for external triggers++Expose a method on the element:++```js+notify(message, { priority = 'normal', duration = 6000 } = {}) {+ this.agent_protocol.emit(ACTION_TYPES.NOTIFY, { message, priority, duration });+}+```++Usage from outside:+```js+document.querySelector('agent-3d').notify("Your file finished processing.");+```++### 7. Data-reactive integration (optional)++A data-reactive binding can automatically fire notifications when a watched value changes:++```js+ctx.dataReactive.start({+ source: { type: 'poll', url: '/api/job-status', intervalMs: 5000 },+ bindings: [+ {+ match: (data) => data.status === 'complete',+ emit: {+ type: ACTION_TYPES.NOTIFY,+ payload: { message: 'Your job finished!', priority: 'high' },+ }+ }+ ],+ signal: abortController.signal,+});+```++## Testing+- Call `document.querySelector('agent-3d').notify("Hello, test notification")` from the browser console+- Avatar should slide in from the right, speak the message, then slide out+- Queue two notifications back-to-back — second should wait for first to complete+- Test that the original element position is restored after exit++## Conventions+- ESM only, tabs 4-wide+- Don't use `setTimeout` chains for sequencing — use async/await with the `_wait()` helper+- The notifier must restore original element styles completely — don't leave the element in a broken position if detached mid-notification+- Update the event vocabulary table in `src/CLAUDE.md` with the `notify` typediff --git a/public/chat/index.html b/public/chat/index.htmlindex 09fd38792..034829295 100644--- a/public/chat/index.html+++ b/public/chat/index.html@@ -43,8 +43,8 @@}}</script>- <script type="module" crossorigin src="/chat/assets/index-Cl6-dzSj.js"></script>- <link rel="stylesheet" crossorigin href="/chat/assets/index-B4ufJJBD.css">+ <script type="module" crossorigin src="/chat/assets/index-mxqepqba.js"></script>+ <link rel="stylesheet" crossorigin href="/chat/assets/index-CQdqInHP.css"></head><body><div id="app"></div>diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex 61d0c2b63..8cb112de5 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -145,6 +145,12 @@ export class AgentAvatar {this._keystrokePitch = 0; // look-down impulse (radians, decays)this._keystrokeYaw = 0; // lateral drift impulse (radians, decays)+ // Gaze bias state+ this._userSpeaking = false;+ this._agentThinking = false;+ this._agentThinkTimer = 0;+ this._thinkGazeYaw = 0.1; // randomised on each THINK event+// One-shot gesture trackingthis._oneShotAction = null;this._oneShotDuration = 0;@@ -193,6 +199,7 @@ export class AgentAvatar {// Subscribe to protocol eventsthis._sub(ACTION_TYPES.SPEAK, this._onSpeak.bind(this));+ this._sub(ACTION_TYPES.THINK, this._onThink.bind(this));this._sub(ACTION_TYPES.GESTURE, this._onGesture.bind(this));this._sub(ACTION_TYPES.EMOTE, this._onEmote.bind(this));this._sub(ACTION_TYPES.LOOK_AT, this._onLookAt.bind(this));@@ -248,6 +255,15 @@ export class AgentAvatar {this._triggerOneShot(name);}+ /**+ * Signal whether the user is actively speaking (mic input active).+ * When true the avatar holds eye contact; when false normal gaze resumes.+ * @param {boolean} active+ */+ setUserSpeaking(active) {+ this._userSpeaking = active;+ }+/*** Set the agent's animation slot override map (from meta.edits.animations).* @param {Object|null} map — { slotName: clipName, … }@@ -331,6 +347,7 @@ export class AgentAvatar {// ── Protocol Handlers ─────────────────────────────────────────────────────_onSpeak(action) {+ this._agentThinking = false; // agent started speaking — done thinkingconst text = action.payload?.text || '';const { valence, arousal } = this._analyzeSentiment(text);@@ -346,6 +363,15 @@ export class AgentAvatar {this._triggerOneShot('talk', duration);}+ _onThink(_action) {+ if (!this._agentThinking) {+ // Pick a stable look-away direction for this thinking episode.+ this._thinkGazeYaw = (Math.random() * 2 - 1) * 0.15;+ }+ this._agentThinking = true;+ this._agentThinkTimer = 0;+ }+_onGesture(action) {const name = action.payload?.name || 'nod';this._triggerOneShot(name, action.payload?.duration || 1.5);@@ -460,6 +486,12 @@ export class AgentAvatar {}this._normaliseNeutral();+ // Decay _agentThinking flag after 3 s+ if (this._agentThinking) {+ this._agentThinkTimer += dt;+ if (this._agentThinkTimer >= 3.0) this._agentThinking = false;+ }+// Stage 2: One-shot gesture timerif (this._isPlayingOneShot) {this._oneShotTimer += dt;@@ -522,6 +554,15 @@ export class AgentAvatar {// ── Head tilt (curiosity + empathy both tilt the head) ────────────this._targetTilt = (w.curiosity * 12 + w.empathy * 9 + w.concern * 4) * DEG2RAD;++ // Gaze bias — overrides emotion-derived tilt+ if (this._userSpeaking) {+ this._targetTilt = 0.04; // slight upward attentive posture+ this._idle?.setPauseSaccade(true);+ } else if (this._agentThinking || w.patience > 0.3) {+ this._targetTilt = -0.06; // look slightly down when thinking / waiting+ }+this._currentTilt = _lerp(this._currentTilt, this._targetTilt, dt * 3.0);// ── Forward lean (curiosity leans in, patience leans back) ────────@@ -619,6 +660,14 @@ export class AgentAvatar {} else if (followMode === 'keystrokes') {targetYaw = this._keystrokeYaw;}++ // Gaze bias — highest priority wins+ if (this._userSpeaking) {+ targetYaw = 0; // face camera directly+ } else if (this._agentThinking || this._emotion.patience > 0.3) {+ targetYaw = this._thinkGazeYaw; // look away to think+ }+this._currentYaw = _lerp(this._currentYaw, targetYaw, 0.08);const yaw = MathUtils.clamp(diff --git a/src/agent-protocol.js b/src/agent-protocol.jsindex 4335e7c20..8ca5f27ad 100644--- a/src/agent-protocol.js+++ b/src/agent-protocol.js@@ -23,6 +23,7 @@ export const ACTION_TYPES = {VALIDATE: 'validate', // validation result (errors, warnings, hints)PRESENCE: 'presence', // agent came online / went idlePROTOCOL_ERROR: 'protocol-error', // emitted by the rate limiter on cascade detection+ INTERRUPTED: 'interrupted', // user spoke while agent was mid-TTSPERMISSIONS_REDEEM_START: 'permissions.redeem.start',PERMISSIONS_REDEEM_SUCCESS: 'permissions.redeem.success',PERMISSIONS_REDEEM_ERROR: 'permissions.redeem.error',diff --git a/src/idle-animation.js b/src/idle-animation.jsindex 24f22eff2..952cb9bbe 100644--- a/src/idle-animation.js+++ b/src/idle-animation.js@@ -136,6 +136,14 @@ export class IdleAnimation {Object.assign(this._channels, partial);}+ /**+ * Pause or resume saccade micro-movements externally (e.g. while user is speaking).+ * @param {boolean} active — true = pause indefinitely, false = release immediately+ */+ setPauseSaccade(active) {+ this._saccPauseTimer = active ? 999 : 0;+ }+/** Remove protocol listeners. */dispose() {this._protocol.off(ACTION_TYPES.SPEAK, this._onSpeak);diff --git a/src/runtime/index.js b/src/runtime/index.jsindex d97fb8b66..f1562c609 100644--- a/src/runtime/index.js+++ b/src/runtime/index.js@@ -4,6 +4,7 @@import { createProvider } from './providers.js';import { createTTS, createSTT } from './speech.js';import { BUILTIN_TOOLS, BUILTIN_HANDLERS, STAGE_TOOLS } from './tools.js';+import { protocol } from '../agent-protocol.js';const MAX_TOOL_ITERATIONS = 8;diff --git a/src/runtime/speech.js b/src/runtime/speech.jsindex e73223c9f..d339aa4ca 100644--- a/src/runtime/speech.js+++ b/src/runtime/speech.js@@ -2,6 +2,7 @@export { LiveKitVoice } from './livekit-voice.js';import { startLipsync } from './lipsync.js';+import { ACTION_TYPES } from '../agent-protocol.js';export class BrowserTTS {constructor({ voiceId = 'default', rate = 1, pitch = 1, lang = 'en-US' } = {}) {@@ -45,11 +46,15 @@ export class BrowserTTS {});}- cancel() {+ cancel(protocol) {+ const wasSpeak = this._speaking;if ('speechSynthesis' in window) window.speechSynthesis.cancel();this._lipsync?.stop();this._lipsync = null;this._speaking = false;+ if (wasSpeak && protocol) {+ protocol.emit({ type: ACTION_TYPES.INTERRUPTED, payload: {} });+ }}get speaking() {@@ -286,7 +291,8 @@ export class ElevenLabsTTS {});}- cancel() {+ cancel(protocol) {+ const wasSpeak = this._speaking;if (this._abort) {try {this._abort.abort();@@ -299,6 +305,9 @@ export class ElevenLabsTTS {this._speaking = false;// Resolve any pending speak() promise so callers don't hangif (this._onEnd) this._onEnd();+ if (wasSpeak && protocol) {+ protocol.emit({ type: ACTION_TYPES.INTERRUPTED, payload: {} });+ }}get speaking() {