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.

feat: import Box3 from three and preload walk/idle animations in Viewer class

nirholasf2aab851a645
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 3610dbb63..87f70a32d 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -156,6 +156,7 @@ const bodySchema = z.object({
max_tokens: z.number().int().positive().max(16_000).optional(),
temperature: z.number().min(0).max(2).optional(),
thinking: z.any().optional(),
+ stream: z.boolean().optional(),
});
// ── Handler ───────────────────────────────────────────────────────────────────
diff --git a/prompts/avatar-chat/34-livekit-voice-walk.md b/prompts/avatar-chat/34-livekit-voice-walk.md
new file mode 100644
index 000000000..c59038389
--- /dev/null
+++ b/prompts/avatar-chat/34-livekit-voice-walk.md
@@ -0,0 +1,56 @@
+# 34 — LiveKit realtime voice: walk during live voice session
+
+## Status
+Gap — when `voice="livekit"` is set, the avatar speaks via LiveKit's realtime audio rather than the browser TTS. The LiveKit voice client dispatches `voiceStateChange` events (see element.js around line 518). Walk should be active during the "speaking" voice state.
+
+## File
+`src/element.js` — `voiceStateChange` event listener
+
+## Current code
+```js
+this.addEventListener('voiceStateChange', (e) => {
+ if (!this._micEl) return;
+ const { state } = e.detail;
+ this._micEl.dataset.voiceState = state;
+ ...
+});
+```
+
+## What to add
+
+```js
+this.addEventListener('voiceStateChange', (e) => {
+ if (!this._micEl) return;
+ const { state } = e.detail;
+ this._micEl.dataset.voiceState = state;
+ this._micEl.title = state === 'idle' || !state
+ ? 'Push to talk'
+ : 'Voice active — click to stop';
+
+ // Avatar walk during active voice states
+ if (this.getAttribute('avatar-chat') !== 'off' && !this.hasAttribute('kiosk')) {
+ if (state === 'speaking' || state === 'thinking') {
+ this._onStreamChunk();
+ } else if (state === 'idle') {
+ this._stopWalkAnimation();
+ }
+ }
+});
+```
+
+`state` values: `'idle'`, `'listening'`, `'thinking'`, `'speaking'` — based on what VoiceClient dispatches.
+
+Also show thought bubble during LiveKit speaking:
+```js
+if (state === 'speaking' && this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ this._thoughtBubbleEl.dataset.active = 'true';
+ // dots mode (no text — we don't have the text yet in realtime)
+ this._thoughtBubbleEl.dataset.streaming = 'false';
+}
+if (state === 'idle') {
+ this._clearThoughtBubble();
+}
+```
+
+## Verification
+Connect with LiveKit voice. The avatar should walk while the AI speaks and return to idle when quiet.
diff --git a/prompts/avatar-chat/35-walk-crossfade-tuning.md b/prompts/avatar-chat/35-walk-crossfade-tuning.md
new file mode 100644
index 000000000..e8d127d18
--- /dev/null
+++ b/prompts/avatar-chat/35-walk-crossfade-tuning.md
@@ -0,0 +1,45 @@
+# 35 — Walk ↔ idle crossfade timing tuning
+
+## Status
+Polish — the walk↔idle transitions use `fade_ms: 300` (walk start) and `fade_ms: 500` (idle return). These are reasonable defaults but may feel abrupt or floaty depending on the model and walk clip. Tune for smoothness.
+
+## File
+`src/element.js` — `_onStreamChunk()` and `_stopWalkAnimation()`
+
+## Current values
+```js
+this._scene.playClipByName('walk', { loop: true, fade_ms: 300 });
+// ...
+this._scene?.playClipByName('idle', { loop: true, fade_ms: 500 });
+```
+
+## Tuning guidelines
+
+**Walk start (idle → walk):**
+- Too short (< 150ms): Jarring snap into walk. Avatar pops unnaturally.
+- Too long (> 600ms): Walk feels sluggish to start, avatar still looks idle while brain:stream is active.
+- Sweet spot: **250–350ms**. Current 300ms is good — verify visually.
+
+**Walk end (walk → idle):**
+- Too short (< 300ms): Avatar snaps back to idle, looks mechanical.
+- Too long (> 800ms): Walk continues visibly after the thought bubble is gone, feels disconnected.
+- Sweet spot: **400–600ms**. Current 500ms is good — verify visually.
+
+**Debounce timer (time after last chunk before stopping):**
+- Current: 600ms
+- If walk stops too early (mid-sentence): increase to 800ms
+- If walk lingers after response ends: decrease to 400ms
+- Sweet spot: **500–700ms**
+
+## What to do
+
+1. Load the app with a test avatar
+2. Send a short message (< 20 words) — verify walk starts promptly and ends cleanly
+3. Send a long message (> 100 words with tool calls) — verify walk stays active throughout
+4. Adjust the three values above if needed
+5. Document the final chosen values as a comment in `_onStreamChunk()`:
+```js
+// fade_ms: 300ms idle→walk, 500ms walk→idle, 600ms debounce after last chunk
+```
+
+## No code changes required unless values need adjustment. This is a tuning/verification step.
diff --git a/prompts/avatar-chat/36-bubble-max-width-truncation.md b/prompts/avatar-chat/36-bubble-max-width-truncation.md
new file mode 100644
index 000000000..6e2f755c6
--- /dev/null
+++ b/prompts/avatar-chat/36-bubble-max-width-truncation.md
@@ -0,0 +1,51 @@
+# 36 — Thought bubble text: smart truncation and readability
+
+## Status
+Polish — the current 120-char truncation replaces the full text with `…` + last 110 chars. For very long responses, the bubble shows mid-sentence fragments. Better UX: show the most recent complete word boundary, and clear the bubble periodically (every N sentences) so it doesn't feel stale.
+
+## File
+`src/element.js` — `_streamToBubble()` / `_bubbleBuffer` logic (from prompt 14)
+
+## What to change
+
+Replace the raw char-count truncation with a word-boundary approach:
+
+```js
+_flushBubble() {
+ this._bubbleRafPending = false;
+ if (!this._thoughtTextEl) return;
+
+ let t = this._bubbleBuffer;
+
+ // Clear the buffer every time we cross a sentence boundary (.!?)
+ // so the bubble feels like it's "thinking" live, not accumulating
+ const sentenceEnd = t.search(/[.!?]\s/);
+ if (sentenceEnd !== -1 && t.length > sentenceEnd + 2) {
+ // Start fresh from after the sentence end
+ this._bubbleBuffer = t.slice(sentenceEnd + 2);
+ t = this._bubbleBuffer;
+ }
+
+ // Hard cap at 100 chars, break at last word boundary
+ if (t.length > 100) {
+ const truncated = t.slice(-90);
+ const wordBreak = truncated.indexOf(' ');
+ t = '…' + (wordBreak !== -1 ? truncated.slice(wordBreak) : truncated);
+ }
+
+ this._thoughtTextEl.textContent = t;
+}
+```
+
+Change the RAF handler to call `_flushBubble()`:
+```js
+requestAnimationFrame(() => {
+ this._bubbleRafPending = false;
+ this._flushBubble();
+});
+```
+
+This makes the bubble feel like a live "thought" that moves through sentences rather than a growing text dump.
+
+## Verification
+Ask the agent a question that generates a 200+ word response. The bubble should show fragments of the current sentence, clear at sentence boundaries, and never show more than ~100 chars. It should feel like the avatar is "thinking out loud" progressively.
diff --git a/prompts/avatar-chat/37-teardown-complete-cleanup.md b/prompts/avatar-chat/37-teardown-complete-cleanup.md
new file mode 100644
index 000000000..a095f2b3e
--- /dev/null
+++ b/prompts/avatar-chat/37-teardown-complete-cleanup.md
@@ -0,0 +1,58 @@
+# 37 — Complete teardown cleanup audit
+
+## Status
+Critical — every timer, observer, event listener, and RAF reference added by the avatar-chat feature must be cleared in `_teardown()`. A missed cleanup causes memory leaks and ghost walk animations on re-mount.
+
+## File
+`src/element.js` — `_teardown()` and constructor
+
+## Audit checklist
+
+Go through every property initialized in the constructor related to avatar-chat. Verify each is cleared in `_teardown()`.
+
+| Property | Cleared? | Method |
+|---|---|---|
+| `_thoughtBubbleEl` | set to null after _renderShell | N/A (DOM removed on unmount) |
+| `_thoughtTextEl` | same | N/A |
+| `_walkStopDebounce` | ✅ `clearTimeout` in teardown | clearTimeout |
+| `_walkReturnTimer` | should be removed (prompt 03) | N/A |
+| `_isWalking` | ✅ set to false in teardown | direct assign |
+| `_bubbleBuffer` | ❓ check | `this._bubbleBuffer = ''` |
+| `_bubbleRafPending` | ❓ check | `this._bubbleRafPending = false` |
+| `_streamingMsgEl` | ❓ check | `null` |
+| `_streamingChatBuffer` | ❓ check | `''` |
+| `_streamingChatRafPending` | ❓ check | `false` |
+| `_chatAutoScroll` | ❓ check | `true` |
+| `_pendingSay` | ❓ check | `null` |
+| `_walkStopDebounce` | ✅ | clearTimeout |
+| protocol.on listener (from prompt 28) | ❓ | store unsub fn, call in teardown |
+
+## What to do
+
+1. Read current `_teardown()` (around line 1640)
+2. Read the constructor and list every `this._*` property
+3. For every property not currently cleared in `_teardown()`, add the appropriate cleanup
+4. For event listeners added to `protocol.on(...)` in `_boot()`, store the unsubscribe handle: `this._unsubNotify = protocol.on(ACTION_TYPES.NOTIFY, handler)` and call `this._unsubNotify?.()` in teardown
+
+## Template for teardown additions
+
+```js
+// avatar-chat cleanup
+clearTimeout(this._walkStopDebounce);
+this._walkStopDebounce = null;
+this._isWalking = false;
+this._bubbleBuffer = '';
+this._bubbleRafPending = false;
+this._streamingMsgEl = null;
+this._streamingChatBuffer = '';
+this._streamingChatRafPending = false;
+this._chatAutoScroll = true;
+this._pendingSay = null;
+this._unsubNotify?.();
+this._unsubNotify = null;
+this._clearThoughtBubble?.();
+this._setBusy?.(false);
+```
+
+## Verification
+Mount the component. Send a message mid-stream. Unmount (remove from DOM). Re-mount. No walk animation playing on fresh mount. No memory leak visible in Chrome DevTools Memory tab.
diff --git a/prompts/avatar-chat/38-null-provider-graceful.md b/prompts/avatar-chat/38-null-provider-graceful.md
new file mode 100644
index 000000000..fab8c4bbb
--- /dev/null
+++ b/prompts/avatar-chat/38-null-provider-graceful.md
@@ -0,0 +1,46 @@
+# 38 — NullProvider / skills-only mode: graceful avatar-chat behavior
+
+## Status
+Gap — when `brain.provider = "none"` (NullProvider), there are no LLM turns, no streaming, and no `brain:stream` events. Skills drive the agent directly. The avatar-chat feature must degrade gracefully.
+
+## Files
+`src/runtime/providers.js` — `NullProvider.complete()`
+`src/element.js` — walk/bubble logic
+
+## What to verify
+
+`NullProvider.complete()` returns `{ text: '', toolCalls: [], stopReason: 'end_turn' }` immediately with no streaming. This means:
+- `brain:thinking` fires with `{ thinking: true }` then immediately `{ thinking: false }` — bubble appears and disappears before user notices
+- No `brain:stream` events — no walk
+- If skills call `ctx.speak(text)`, that fires `voice:speech-start` — walk from prompt 06 handles this
+
+## What to fix
+
+### Prevent flicker on null provider
+
+When `brain:thinking` fires with `thinking: true` and then `thinking: false` within a single tick (synchronous), the bubble appears and disappears so fast it flickers. Add a minimum display time:
+
+In `_clearThoughtBubble()`, add a 200ms delay before hiding:
+```js
+_clearThoughtBubble() {
+ clearTimeout(this._bubbleClearTimer);
+ this._bubbleClearTimer = setTimeout(() => {
+ this._bubbleBuffer = '';
+ if (!this._thoughtBubbleEl) return;
+ this._thoughtBubbleEl.dataset.active = 'false';
+ this._thoughtBubbleEl.dataset.streaming = 'false';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
+ }, 200);
+}
+```
+
+Add `this._bubbleClearTimer = null` to constructor and `clearTimeout(this._bubbleClearTimer)` to teardown.
+
+This minimum 200ms prevents the bubble from appearing and vanishing in the same frame.
+
+### Skill-driven speak walks correctly
+
+When a skill calls `ctx.speak(text)`, the runtime dispatches `voice:speech-start`. Prompt 06 wires walk to this event. No extra work needed.
+
+## Verification
+Set `brain="none"` (no LLM provider). Install a skill that calls `ctx.speak('hello')`. Trigger it. Avatar should walk while speaking, no flicker on the thought bubble.
diff --git a/prompts/avatar-chat/39-data-reactive-walk.md b/prompts/avatar-chat/39-data-reactive-walk.md
new file mode 100644
index 000000000..29646016b
--- /dev/null
+++ b/prompts/avatar-chat/39-data-reactive-walk.md
@@ -0,0 +1,35 @@
+# 39 — data-reactive: walk when live data events push updates
+
+## Status
+Gap — `data-reactive.js` lets skills wire live SSE/WebSocket sources to the protocol bus. When data arrives and the avatar speaks or emotes, the user should see the avatar walk as part of the data delivery experience.
+
+## Files
+`src/runtime/data-reactive.js` — understand what protocol events it emits
+`src/element.js` — walk wiring
+
+## Background
+
+Read `src/runtime/data-reactive.js`. The `startDataReactive()` function watches a stream source and calls `protocol.emit()` with events matched by `{ match, emit }` bindings. It typically emits `speak`, `emote`, or `notify` events.
+
+## What to do
+
+If data-reactive emits `speak` events on the protocol bus, the avatar's empathy layer already picks up the emotion. But walk is not triggered.
+
+**Option A**: Subscribe to `ACTION_TYPES.SPEAK` on the protocol bus in element.js for walk:
+```js
+// In _boot(), after the protocol bus is set up:
+this._unsubSpeak = protocol.on(ACTION_TYPES.SPEAK, () => {
+ if (this.getAttribute('avatar-chat') !== 'off' && !this.hasAttribute('kiosk')) {
+ this._onStreamChunk();
+ }
+});
+```
+
+Store in `this._unsubSpeak` and unsubscribe in `_teardown()`.
+
+This means ANY `speak` event (from skills, data-reactive, runtime) triggers the walk. This is the right behavior — the avatar should walk whenever it's "saying" something.
+
+**Option B**: Handle it in the `notify` path (prompt 28) — only if data-reactive routes through `notify`. Check the data-reactive code.
+
+## Verification
+Wire a data-reactive source that fires `speak` events (or set up a test that calls `protocol.emit({ type: 'speak', payload: { text: 'price update' } })`). Avatar should briefly walk when the event fires.
diff --git a/prompts/avatar-chat/40-lib-export-update.md b/prompts/avatar-chat/40-lib-export-update.md
new file mode 100644
index 000000000..9503039ca
--- /dev/null
+++ b/prompts/avatar-chat/40-lib-export-update.md
@@ -0,0 +1,51 @@
+# 40 — lib.js export surface: expose new avatar-chat API
+
+## Status
+Gap — `src/lib.js` is the CDN library export surface. New public methods and CSS custom properties added by the avatar-chat feature should be reflected there if they change the public API surface.
+
+## File
+`src/lib.js`
+
+## What to check
+
+Open `src/lib.js`. Verify it exports:
+- `Agent3DElement` (the custom element class, or the element registration)
+- Any utility functions exposed to library consumers
+
+The `enableAvatarChat()` and `disableAvatarChat()` methods (prompt 27) are on the element instance — they're accessible via `document.querySelector('agent-3d').enableAvatarChat()`. No explicit lib.js change needed for instance methods.
+
+However, if lib.js exports TypeScript-style JSDoc typedef comments or an API surface description, add:
+
+```js
+/**
+ * @typedef {Object} AvatarChatOptions
+ * @property {'off'|undefined} avatarChat - Set to 'off' to disable inline avatar layout
+ */
+```
+
+And add JSDoc to the element class:
+```js
+/**
+ * Enable the inline avatar-in-chat layout.
+ * Avatar walks during LLM streaming, thought bubble shows response text.
+ * @returns {void}
+ */
+enableAvatarChat() { ... }
+
+/**
+ * Disable the inline avatar-in-chat layout and restore bottom-bar chat.
+ * @returns {void}
+ */
+disableAvatarChat() { ... }
+```
+
+## What NOT to change
+
+Do not add `brain:stream` to any export — it's an internal Runtime EventTarget event that bubbles through the host element as a composed CustomEvent. External consumers listen on the element:
+```js
+element.addEventListener('brain:stream', (e) => console.log(e.detail.chunk));
+```
+This already works without lib.js changes.
+
+## Verification
+Build the library (`npm run dev:lib` or `npm run build`). Confirm no new exports are accidentally omitted or duplicated.
diff --git a/prompts/avatar-chat/41-section-fullscreen-modes.md b/prompts/avatar-chat/41-section-fullscreen-modes.md
new file mode 100644
index 000000000..8900b39c9
--- /dev/null
+++ b/prompts/avatar-chat/41-section-fullscreen-modes.md
@@ -0,0 +1,43 @@
+# 41 — Section and fullscreen mode layout compatibility
+
+## Status
+Gap — `mode="section"` and `mode="fullscreen"` are two additional layout modes beyond inline and floating. The new vertical chrome column must be verified in both.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## Section mode
+
+Section mode is designed to be embedded in a page section (like a hero or sidebar). It has `width: 100%` and custom height. The vertical chrome column should work as-is.
+
+Verify: With `mode="section"`, does the chrome column fill the element correctly? The avatar anchor should take the center portion.
+
+If the section is very wide (desktop), the chat area could span the full width looking awkward. Add a max-width to the chat in section mode:
+```css
+:host([mode="section"]) .chat {
+ max-width: 600px;
+}
+:host([mode="section"]) .input-row {
+ max-width: 600px;
+}
+```
+
+## Fullscreen mode
+
+Fullscreen is `position: fixed; inset: 0; width: 100vw; height: 100vh`. The chrome column fills the entire screen, with the avatar anchor taking the bulk of the space.
+
+On a large monitor (1440px wide), the avatar anchor is a large transparent area showing the Three.js canvas. The thought bubble will appear at `top: 12%` (or tracked position from prompt 13), which maps to roughly 130px from the top — should be approximately above the avatar's head for a fullscreen-framed model.
+
+Verify: In fullscreen mode, are the chat, avatar, and input well-positioned? On large screens, add max-width centering:
+```css
+:host([mode="fullscreen"]) .chrome {
+ max-width: 800px;
+ margin: 0 auto;
+ left: 0;
+ right: 0;
+ width: 800px;
+}
+```
+
+## Verification
+Test `mode="section"` embedded in a page section. Test `mode="fullscreen"`. Both should show the vertical chrome column with chat at top, avatar in middle, input at bottom.
diff --git a/prompts/avatar-chat/42-test-page.md b/prompts/avatar-chat/42-test-page.md
new file mode 100644
index 000000000..7182a181f
--- /dev/null
+++ b/prompts/avatar-chat/42-test-page.md
@@ -0,0 +1,110 @@
+# 42 — Create avatar-chat test/demo page
+
+## Status
+Required — a dedicated test page makes it possible to verify all avatar-chat features quickly without navigating to the main app and loading an agent from scratch.
+
+## File
+Create: `public/test-avatar-chat.html`
+
+## What to build
+
+A standalone HTML page (no build step needed, using the dev server) that:
+
+1. Loads `<agent-3d>` with a known-good avatar
+2. Has a UI to toggle `avatar-chat="off"` on/off
+3. Has buttons to trigger streaming, tool calls, and notifications manually
+4. Shows the current state (walking, thinking, idle) in a debug panel
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Avatar-Chat Test</title>
+ <style>
+ body { margin: 0; background: #0b0d10; color: white; font-family: system-ui; }
+ .container { display: flex; height: 100vh; gap: 16px; padding: 16px; box-sizing: border-box; }
+ agent-3d { flex: 0 0 360px; height: 100%; }
+ .controls { flex: 1; display: flex; flex-direction: column; gap: 12px; padding: 16px; }
+ button { padding: 8px 16px; border: 1px solid rgba(255,255,255,0.2); background: rgba(255,255,255,0.05); color: white; border-radius: 8px; cursor: pointer; }
+ button:hover { background: rgba(255,255,255,0.1); }
+ .status { font-size: 12px; opacity: 0.6; padding: 8px; background: rgba(255,255,255,0.04); border-radius: 8px; }
+ pre { margin: 0; font-size: 11px; white-space: pre-wrap; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <agent-3d
+ id="agent"
+ src="/animations/robotexpressive.glb"
+ brain="claude-opus-4-6"
+ background="dark"
+ mode="inline"
+ responsive="false"
+ width="360px"
+ height="100%"
+ ></agent-3d>
+
+ <div class="controls">
+ <h2>Avatar-Chat Test Panel</h2>
+
+ <div>
+ <strong>Layout Toggle</strong><br>
+ <button onclick="toggle()">Toggle avatar-chat="off"</button>
+ <span id="toggle-state">ON</span>
+ </div>
+
+ <div>
+ <strong>Manual Triggers</strong><br>
+ <button onclick="send('Hello, say something short.')">Short response</button>
+ <button onclick="send('Write a detailed 3-paragraph explanation of how blockchain works.')">Long response</button>
+ <button onclick="send('What are the trending tokens on pump.fun?')">Tool call (if skill installed)</button>
+ </div>
+
+ <div>
+ <strong>Event Log</strong>
+ <div class="status"><pre id="log"></pre></div>
+ </div>
+ </div>
+ </div>
+
+ <script type="module">
+ import '/src/element.js';
+
+ const agent = document.getElementById('agent');
+ const log = document.getElementById('log');
+ const toggleState = document.getElementById('toggle-state');
+ let lines = [];
+
+ function addLog(msg) {
+ lines.unshift(`${new Date().toISOString().slice(11,23)} ${msg}`);
+ lines = lines.slice(0, 20);
+ log.textContent = lines.join('\n');
+ }
+
+ for (const ev of ['brain:thinking', 'brain:stream', 'brain:message', 'skill:tool-start', 'skill:tool-called', 'voice:speech-start', 'voice:speech-end']) {
+ agent.addEventListener(ev, (e) => {
+ const detail = ev === 'brain:stream'
+ ? `chunk="${e.detail?.chunk?.slice(0,20)}…"`
+ : JSON.stringify(e.detail || {}).slice(0, 60);
+ addLog(`${ev} ${detail}`);
+ });
+ }
+
+ window.toggle = () => {
+ if (agent.getAttribute('avatar-chat') === 'off') {
+ agent.removeAttribute('avatar-chat');
+ toggleState.textContent = 'ON';
+ } else {
+ agent.setAttribute('avatar-chat', 'off');
+ toggleState.textContent = 'OFF';
+ }
+ };
+
+ window.send = (text) => agent.say(text);
+ </script>
+</body>
+</html>
+```
+
+## Verification
+Navigate to `http://localhost:3001/test-avatar-chat.html`. All buttons should work. The event log should show events firing in real time. Toggle should switch layouts.
diff --git a/prompts/avatar-chat/43-manual-qa-checklist.md b/prompts/avatar-chat/43-manual-qa-checklist.md
new file mode 100644
index 000000000..b501fbf0c
--- /dev/null
+++ b/prompts/avatar-chat/43-manual-qa-checklist.md
@@ -0,0 +1,93 @@
+# 43 — Manual QA checklist
+
+## Status
+Required — run this checklist end-to-end before marking the feature production-ready. Each item must pass.
+
+---
+
+## Layout
+
+- [ ] Chrome shows: chat at top, transparent avatar window in middle, input at bottom
+- [ ] Chat has no content → `.chat:empty { display: none }` hides it, avatar takes full window
+- [ ] Chat has content → chat takes up to 38% of height, avatar window shrinks proportionally
+- [ ] Input pill is at the bottom, full width
+- [ ] `avatar-chat="off"` → original bottom-bar layout (chat left, input right)
+- [ ] `avatar-chat="off"` → avatar anchor and thought bubble not visible
+- [ ] `mode="floating"` → layout works, drag handle doesn't overlap chat
+- [ ] `mode="fullscreen"` → layout works
+- [ ] Mobile 375px viewport with floating mode → pill collapses, expands to bottom-sheet with correct layout
+
+---
+
+## Thought Bubble
+
+- [ ] Sending a message → bubble appears with animated dots within 200ms
+- [ ] First streaming token arrives → bubble switches to text mode, dots hidden
+- [ ] Text streams → bubble shows current phrase (not growing unboundedly)
+- [ ] Long response → bubble clears at sentence boundaries, shows fresh phrases
+- [ ] Response complete → bubble fades out within 300ms of last token
+- [ ] Tool call running → bubble shows tool label ("Searching pump.fun…") in text mode
+- [ ] Bubble tail points downward toward avatar
+- [ ] Light background (`background="light"`) → bubble is dark with light text
+- [ ] `avatar-chat="off"` → bubble never appears
+- [ ] `prefers-reduced-motion: reduce` → dots don't animate (static)
+
+---
+
+## Walk Animation
+
+- [ ] User presses Enter → avatar starts walking immediately
+- [ ] First streaming token arrives → avatar walks (if not already)
+- [ ] Streaming stops → avatar returns to idle within 1 second
+- [ ] Tool call executes → avatar walks during tool execution
+- [ ] TTS speaks → avatar walks during speech
+- [ ] Voice state = "speaking" (LiveKit) → avatar walks
+- [ ] Voice state = "idle" (LiveKit) → avatar returns to idle
+- [ ] `avatar-chat="off"` → avatar never walks (stays in idle or empathy-layer animations)
+- [ ] `prefers-reduced-motion: reduce` → avatar does NOT walk
+- [ ] Kiosk mode → avatar does NOT walk
+
+---
+
+## Chat
+
+- [ ] User message appears immediately when submitted
+- [ ] Streaming text appears live in chat with blinking cursor (prompt 15)
+- [ ] Final message replaces streaming placeholder (no duplicate)
+- [ ] Chat auto-scrolls during streaming
+- [ ] Manually scroll up mid-stream → auto-scroll pauses
+- [ ] Scroll back to bottom → auto-scroll resumes
+- [ ] Tool result cards render correctly
+
+---
+
+## Input State
+
+- [ ] During streaming → input is disabled, placeholder shows "Thinking…"
+- [ ] After response → input re-enabled, placeholder shows "Say something…"
+- [ ] Rapid submissions → queued correctly (latest wins)
+- [ ] Network error mid-stream → input re-enables, walk stops, bubble clears
+
+---
+
+## Accessibility
+
+- [ ] Tab order: chat → input → mic button (no focus on avatar/canvas)
+- [ ] Screen reader announces "Agent is responding" when bubble appears
+- [ ] Screen reader reads new chat messages as they arrive
+
+---
+
+## Performance
+
+- [ ] 60fps during streaming (check Chrome Performance panel)
+- [ ] Bubble DOM writes batched to RAF (no per-token layout)
+- [ ] Walk animation crossfades smoothly (no snap)
+- [ ] `walk.json` and `idle.json` preloaded before first message
+
+---
+
+## Cleanup
+
+- [ ] Mount → unmount → re-mount: no ghost walk, no stuck bubble
+- [ ] Navigate away mid-stream: no console errors
diff --git a/prompts/avatar-chat/43-manual-test-checklist.md b/prompts/avatar-chat/43-manual-test-checklist.md
new file mode 100644
index 000000000..eea59e236
--- /dev/null
+++ b/prompts/avatar-chat/43-manual-test-checklist.md
@@ -0,0 +1,75 @@
+# 43 — Manual test checklist
+
+## Status
+Required — use this checklist to sign off that all avatar-chat features work end-to-end before shipping.
+
+## Setup
+Open `http://localhost:3001/test-avatar-chat.html` (from prompt 42). Use an agent with `brain="claude-opus-4-6"` and a humanoid GLB model.
+
+---
+
+## Core functionality
+
+- [ ] **Thought bubble appears** — Send a message. Bubble shows above avatar head before first response word.
+- [ ] **Bubble shows streaming text** — Words appear in the bubble as they stream, not just dots.
+- [ ] **Bubble dots mode** — During the pre-stream thinking pause (before first token), three animated dots show.
+- [ ] **Bubble clears** — When the full message lands in chat, bubble fades out.
+- [ ] **Avatar walks on stream** — Avatar plays walk animation while tokens are arriving.
+- [ ] **Walk stops on stream end** — Avatar returns to idle within 600ms of last token.
+- [ ] **Walk starts immediately** — Pressing Enter triggers walk before the first token (prompt 07).
+
+---
+
+## Tool calls
+
+- [ ] **Walk during tool call** — Send a pump.fun query. Avatar walks while the tool runs (prompt 05).
+- [ ] **Bubble shows tool label** — "Searching pump.fun…" appears in bubble during tool (prompt 09).
+- [ ] **Walk continues into next LLM turn** — After tool result, avatar keeps walking while the LLM generates the final response.
+
+---
+
+## Layout
+
+- [ ] **Inline mode** — Chat at top, avatar window in middle, input at bottom. Avatar visible through center.
+- [ ] **avatar-chat="off" toggle** — Toggle button switches to original bottom-bar layout. Walk and bubble stop.
+- [ ] **Re-enable** — Removing `avatar-chat="off"` restores the column layout.
+- [ ] **Floating mode** — `mode="floating"`: rounded card, drag handle doesn't overlap chat.
+- [ ] **Section/fullscreen** — `mode="fullscreen"`: input stays at bottom, chat max-height is reduced, no awkward stretching on wide screens.
+
+---
+
+## Edge cases
+
+- [ ] **Rapid messages** — Submit 3 messages quickly. Only one executes at a time. No console errors. (prompt 22)
+- [ ] **Navigate away mid-stream** — Remove element from DOM during streaming. No stuck walk, no console errors. (prompt 21)
+- [ ] **Long response** — 200+ word response. Walk stays active throughout. Bubble cycles through sentences. Chat auto-scrolls.
+- [ ] **Short response** — 5-word response. Walk starts, bubble flashes, both end cleanly within 1 second.
+- [ ] **Empty response** — Edge case where LLM returns empty text. No crash.
+
+---
+
+## Accessibility
+
+- [ ] **Reduced motion** — DevTools → Rendering → prefers-reduced-motion: reduce. Bubble dots stop bouncing. Avatar does not walk.
+- [ ] **Screen reader** — VoiceOver announces "Agent is responding" when bubble appears. Chat messages are read aloud.
+- [ ] **Keyboard only** — Tab reaches input. Enter submits. Tab reaches mic button. No mouse required.
+
+---
+
+## Performance
+
+- [ ] **No layout thrashing** — Chrome DevTools Performance panel during a 100-word response. Bubble DOM writes ≤ 60/sec.
+- [ ] **Walk clip preloaded** — Network panel shows `walk.json` loaded at page boot, not on first message.
+
+---
+
+## Background variants
+
+- [ ] **Dark background** — Bubble is white with dark text.
+- [ ] **Light background** — Bubble is dark with light text (prompt 11).
+- [ ] **Transparent background** — Bubble visible against whatever is behind the element.
+
+---
+
+## Sign-off
+All items checked: _______________________ Date: _______________________
diff --git a/prompts/avatar-chat/44-empathy-layer-coordination.md b/prompts/avatar-chat/44-empathy-layer-coordination.md
new file mode 100644
index 000000000..9ddb6b605
--- /dev/null
+++ b/prompts/avatar-chat/44-empathy-layer-coordination.md
@@ -0,0 +1,52 @@
+# 44 — Empathy layer coordination: walk doesn't fight emotion blend
+
+## Status
+Design concern — the walk animation runs through `AnimationManager.crossfadeTo()` which drives the main animation mixer. The empathy layer in `agent-avatar.js` drives morph targets (facial expressions) and head bone rotation additively — it does NOT fight the body animation. However, one-shot gestures (wave, celebrate) DO use the same mixer and can conflict.
+
+## Files
+`src/agent-avatar.js` — `playGesture()`, `_tickEmotion()`
+`src/element.js` — `_onStreamChunk()`
+
+## What to verify
+
+### Morph targets (facial expressions)
+The empathy layer updates morph targets (`mouthSmile`, `eyeSquint`, etc.) every frame additively on top of any playing clip. Walk animation uses body bones only and does not touch morph targets. **No conflict** — verified by architecture.
+
+### Head bone rotation
+The empathy layer applies head lean/tilt/yaw by finding the Head or Neck bone and applying delta rotation. The walk animation bakes head motion into the clip (Mixamo walk includes head bob). The empathy layer's delta is added on top each frame.
+
+**Potential conflict**: Walk clip may include strong head motion that fights the empathy layer's gaze tracking. Check visually — if the avatar's head looks like it's twitching during walk, reduce the walk clip's head influence.
+
+**Fix if needed**: In `AnimationManager.play()` / `crossfadeTo()`, mask the head bone out of the walk action so only body bones are driven by the walk clip:
+```js
+// After creating the walk action in AnimationManager:
+const headBone = model.getObjectByName('Head') || model.getObjectByName('Neck');
+if (headBone) {
+ walkAction.getMixer().setTime(0);
+ // Weight the head bone to 0 in the walk clip
+ // THREE.js doesn't have a bone mask API directly — skip head tracks
+}
+```
+A simpler approach: in `build-animations.mjs`, strip head/neck tracks from the walk clip during build. Find the track filter step and exclude tracks matching `/head|neck/i`.
+
+### One-shot gestures during walk
+If `playGesture('wave')` fires while the avatar is walking, the gesture (LoopOnce) will blend with the walk (LoopRepeat). This is the correct behavior — gestures blend over the base animation. No conflict.
+
+However, if `_stopWalkAnimation()` fires while a gesture is in progress, the crossfade to idle may interrupt the gesture. Fix: in `_stopWalkAnimation()`, check if a one-shot gesture is playing and delay the idle crossfade until the gesture finishes:
+```js
+_stopWalkAnimation() {
+ if (!this._isWalking) return;
+ this._isWalking = false;
+ clearTimeout(this._walkStopDebounce);
+ // Don't interrupt a one-shot gesture
+ const am = this._viewer?.animationManager;
+ const currentClip = am?.currentName;
+ const isGesture = currentClip && currentClip !== 'walk' && currentClip !== 'idle';
+ if (!isGesture) {
+ this._scene?.playClipByName('idle', { loop: true, fade_ms: 500 });
+ }
+}
+```
+
+## Verification
+While the avatar is walking, trigger a wave gesture (`element.wave()`). The wave should blend over the walk. Walk should stop after the wave finishes.
diff --git a/prompts/avatar-chat/44-src-claude-md-update.md b/prompts/avatar-chat/44-src-claude-md-update.md
new file mode 100644
index 000000000..cc2a490e8
--- /dev/null
+++ b/prompts/avatar-chat/44-src-claude-md-update.md
@@ -0,0 +1,51 @@
+# 44 — Update src/CLAUDE.md: protocol vocabulary and new methods
+
+## Status
+Required — src/CLAUDE.md is the authoritative reference for agents working in the src/ directory. It must reflect all changes made by this feature.
+
+## File
+`src/CLAUDE.md`
+
+## Changes required
+
+### 1 — Protocol bus event vocabulary table
+
+Add two rows to the "The protocol bus — event vocabulary" table:
+
+| Type | Payload | Emitted by | Consumed by |
+|---|---|---|---|
+| `brain:stream` | `{ chunk: string }` | runtime `_loop()` via Runtime EventTarget | element.js (`_streamToBubble`, `_onStreamChunk`, re-dispatched to host) |
+| `skill:tool-start` | `{ tool: string, args: object }` | runtime `_loop()` via Runtime EventTarget | element.js (walk animation, bubble label, re-dispatched to host) |
+
+Note in the table header or a footnote: `brain:stream` and `skill:tool-start` are Runtime EventTarget events (not protocol bus), but they bubble to the host element as composed CustomEvents. They are NOT routed through `protocol.emit()`.
+
+### 2 — New element.js methods section (or update existing)
+
+Under the web component boundary section, add a methods subsection:
+
+```
+### Avatar-chat methods (element.js)
+
+- `enableAvatarChat()` — re-enable inline avatar layout + walk + bubble (default on)
+- `disableAvatarChat()` — disable to restore bottom-bar layout; removes attribute `avatar-chat="off"`
+- `_onStreamChunk()` — start walking; debounces stop by 600ms; respects prefers-reduced-motion
+- `_stopWalkAnimation()` — crossfade walk→idle immediately
+- `_streamToBubble(chunk)` — append token chunk to bubble, RAF-batched
+- `_clearThoughtBubble()` — hide bubble and reset text+buffer
+- `_setBusy(busy)` — disable/enable input; sets placeholder and data-busy
+```
+
+### 3 — "What's half-built" section
+
+Remove or mark as done: "Runtime `thinking: 'auto'` — limited UX wiring" since streaming now wires up the thought bubble.
+
+Add: "Chat streaming placeholder (prompt 15) — implemented but not tested in all edge cases."
+
+### 4 — Gotchas section
+
+Add:
+- **`brain:stream` fires per token** — at 50+ tokens/sec this is frequent. All handlers must be O(1) and RAF-batched. Never do synchronous network or heavy DOM work in a brain:stream handler.
+- **Walk animation requires walk+idle clips preloaded** — if `animationManager.isLoaded('walk')` returns false, `_onStreamChunk()` silently skips the walk. Ensure prompt 29 (preload strategy) is implemented.
+
+## Verification
+`grep -n "brain:stream\|skill:tool-start\|enableAvatarChat\|avatar-chat" src/CLAUDE.md` returns results in the correct sections.
diff --git a/prompts/avatar-chat/44-transparent-background-bubble.md b/prompts/avatar-chat/44-transparent-background-bubble.md
new file mode 100644
index 000000000..558d950d1
--- /dev/null
+++ b/prompts/avatar-chat/44-transparent-background-bubble.md
@@ -0,0 +1,44 @@
+# 44 — Transparent background: thought bubble visibility
+
+## Status
+Gap — when `background="transparent"` (the default), the canvas composites over the host page background. The white thought bubble is visible but may clash with a white page background — it becomes invisible. Also, the `.chat` and `.input-row` are `rgba(17, 24, 39, 0.92)` dark glass, which may not suit a light host page.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## What to do
+
+### Thought bubble on transparent background
+
+The bubble already has `box-shadow: 0 4px 24px rgba(0,0,0,0.25)` which creates a drop shadow separating it from a white background. But the border could be more visible:
+
+```css
+:host([background="transparent"]) .thought-bubble {
+ border: 1px solid rgba(0, 0, 0, 0.08);
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.18), 0 1px 3px rgba(0, 0, 0, 0.12);
+}
+```
+
+This subtle border ensures the white bubble is always discernible against both white and dark host pages.
+
+### Chat panel on transparent background
+
+When the host page is light and `background="transparent"`, the dark chat glass panel may look out of place. Expose a CSS variable for embedders to override:
+
+```css
+:host {
+ --agent-surface: rgba(17, 24, 39, 0.92);
+ ...
+}
+```
+
+Already done (it's a custom property). Document in EMBED_SPEC that embedders should set `--agent-surface` to match their page theme when using `background="transparent"`.
+
+No code change needed — just add a note to prompt 26 (EMBED_SPEC docs) to mention this variable.
+
+### Dot color on transparent
+
+On a dark host page, the blue dots (`background: var(--agent-accent)`) are visible. On a light page, they're also fine. No change needed.
+
+## Verification
+Embed the element on a white page with `background="transparent"`. The thought bubble should be visually distinct from the page background via shadow + border. On a dark page it should still look clean.
diff --git a/prompts/avatar-chat/45-error-state-bubble.md b/prompts/avatar-chat/45-error-state-bubble.md
new file mode 100644
index 000000000..1dfa932ce
--- /dev/null
+++ b/prompts/avatar-chat/45-error-state-bubble.md
@@ -0,0 +1,55 @@
+# 45 — Error state: bubble shows failure feedback
+
+## Status
+Gap — when the LLM call fails (network error, 429 rate limit, 500 server error), the current behavior is: walk stops, bubble clears, `agent:error` fires. The user sees nothing. The bubble should briefly show an error state before clearing.
+
+## File
+`src/element.js` — `say()` / `_drainSayQueue()` error handler (prompt 22), and a new `_showBubbleError()` method
+
+## What to add
+
+```js
+_showBubbleError(message = 'Something went wrong') {
+ if (!this._thoughtBubbleEl || this.getAttribute('avatar-chat') === 'off') return;
+ clearTimeout(this._bubbleClearTimer);
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ this._thoughtBubbleEl.dataset.error = 'true';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = message;
+ // Auto-clear after 3 seconds
+ this._bubbleClearTimer = setTimeout(() => {
+ this._thoughtBubbleEl.dataset.error = 'false';
+ this._clearThoughtBubble();
+ }, 3000);
+}
+```
+
+Add CSS for error state:
+```css
+.thought-bubble[data-error="true"] {
+ --agent-bubble-bg: rgba(239, 68, 68, 0.92);
+ --agent-bubble-color: #fff;
+ background: rgba(239, 68, 68, 0.92);
+ color: #fff;
+}
+.thought-bubble[data-error="true"]::after {
+ border-top-color: rgba(239, 68, 68, 0.92);
+}
+```
+
+Call it in the error handler:
+```js
+// In _drainSayQueue catch block:
+catch (err) {
+ this._stopWalkAnimation();
+ const msg = err?.message?.includes('429') ? 'Too many requests — try again' :
+ err?.message?.includes('busy') ? 'Still thinking…' :
+ 'Connection error';
+ this._showBubbleError(msg);
+ this._setBusy(false);
+ this.dispatchEvent(new CustomEvent('agent:error', { ... }));
+}
+```
+
+## Verification
+Simulate a network error (disable network in DevTools mid-stream). The bubble should turn red with an error message for 3 seconds, then disappear. Avatar returns to idle.
diff --git a/prompts/avatar-chat/45-lint-and-format.md b/prompts/avatar-chat/45-lint-and-format.md
new file mode 100644
index 000000000..6aa3039dc
--- /dev/null
+++ b/prompts/avatar-chat/45-lint-and-format.md
@@ -0,0 +1,43 @@
+# 45 — Lint and format: ensure all changes pass prettier and eslint
+
+## Status
+Required — all modified files must pass the project's linter and formatter before merging. Failing lint in CI blocks deployment.
+
+## Files
+All modified: `src/element.js`, `src/runtime/index.js`, `src/runtime/providers.js`, `src/agent-protocol.js`, `src/CLAUDE.md`, `specs/EMBED_SPEC.md`
+
+## Commands to run
+
+```bash
+# Format all changed files
+npx prettier --write src/element.js src/runtime/index.js src/runtime/providers.js src/agent-protocol.js
+
+# Check (don't auto-fix) — confirm no remaining issues
+npx prettier --check src/element.js src/runtime/index.js src/runtime/providers.js
+
+# If eslint is configured:
+npx eslint src/element.js src/runtime/index.js src/runtime/providers.js
+```
+
+## Common issues to watch for
+
+**Tabs vs spaces:** The project uses tabs (4-wide) per src/CLAUDE.md. All new code must use tabs, not spaces. Prettier should enforce this if `.prettierrc` is configured correctly.
+
+**No trailing commas in function params:** Check the project's trailing comma preference.
+
+**JSDoc format:** New `/** */` comments must use the project's JSDoc style (see existing methods for reference).
+
+**Line length:** If the project has a line-length rule, the long CSS strings in BASE_STYLE may need wrapping.
+
+## What to do
+
+1. Run `npx prettier --write` on all changed files
+2. Run `npx eslint` on all changed JS files
+3. Fix any reported issues
+4. Re-run to confirm zero errors
+
+## Verification
+```bash
+npx prettier --check src/element.js src/runtime/index.js src/runtime/providers.js
+# Output: All matched files use Prettier code style!
+```
diff --git a/prompts/avatar-chat/45-stacking-context-zindex.md b/prompts/avatar-chat/45-stacking-context-zindex.md
new file mode 100644
index 000000000..b40c962fc
--- /dev/null
+++ b/prompts/avatar-chat/45-stacking-context-zindex.md
@@ -0,0 +1,49 @@
+# 45 — Stacking context: thought bubble z-index in floating and embedded contexts
+
+## Status
+Layout bug risk — the thought bubble uses `z-index: 4`. In shadow DOM this is scoped to the shadow tree, so it doesn't leak. But in floating mode (`z-index: 2147483000` on the host), any child element with its own stacking context could stack incorrectly.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## What to verify
+
+### Shadow DOM z-index scoping
+Inside the shadow DOM, z-index values only compete with siblings. The current stacking order from bottom to top:
+1. `.stage` (canvas) — `position: absolute; inset: 0` — z-index auto
+2. `.poster` — `position: absolute; inset: 0` — z-index auto
+3. `.chrome` — `position: absolute; inset: 0` — z-index auto
+ - `.chat` — in flow
+ - `.avatar-anchor` — in flow
+ - `.thought-bubble` — `position: absolute; z-index: 4`
+ - `.input-row` — in flow
+4. `.tool-indicator` — `position: absolute; z-index: 3`
+5. `.alert-banner` — `position: absolute; z-index: 3`
+6. `.drag-handle` — `position: absolute; z-index: 15`
+7. `.pill-btn` — `position: absolute; z-index: 10`
+
+**Issue**: `.tool-indicator` and `.alert-banner` are `z-index: 3`. The thought bubble is `z-index: 4`. But `.tool-indicator` is positioned relative to the shadow root (not inside `.avatar-anchor`), so it participates in the same stacking context as `.thought-bubble`. The bubble correctly appears above the tool indicator. ✅
+
+**Issue**: `.drag-handle` is `z-index: 15` and covers the top of the element in floating mode. The thought bubble is `z-index: 4`. If the bubble tracked the head up near the drag handle area, it would be hidden behind it. Fix:
+```css
+.thought-bubble { z-index: 16; } /* above drag handle */
+```
+
+### backdrop-filter and stacking contexts
+`.chat` uses `backdrop-filter: blur(12px)`. This creates a new stacking context. Since `.thought-bubble` is NOT a child of `.chat`, it is not affected. ✅
+
+### iframe embedding
+When the element is inside an iframe, the shadow DOM z-index is scoped to the iframe's document. No issues.
+
+## What to change
+
+Update `.thought-bubble` z-index from 4 to 16 to ensure it always renders above the drag handle:
+```css
+.thought-bubble {
+ ...
+ z-index: 16;
+}
+```
+
+## Verification
+In floating mode with the drag handle visible, trigger a thought bubble. The bubble should appear above the drag handle, not behind it.
diff --git a/prompts/avatar-chat/46-bubble-zindex-layering.md b/prompts/avatar-chat/46-bubble-zindex-layering.md
new file mode 100644
index 000000000..7c05af4b5
--- /dev/null
+++ b/prompts/avatar-chat/46-bubble-zindex-layering.md
@@ -0,0 +1,47 @@
+# 46 — Z-index layering: thought bubble above all UI elements
+
+## Status
+Gap — the thought bubble has `z-index: 4` (set in initial implementation). Other elements in the shadow DOM have various z-indices. Verify the bubble always renders on top of chat messages, tool indicators, and alert banners.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## Current z-index map
+
+| Element | z-index |
+|---|---|
+| `.pill-btn` | 10 |
+| `.pill-drag` | 20 |
+| `.drag-handle` | 15 |
+| `.alert-banner` | 3 |
+| `.tool-indicator` | 3 |
+| `.thought-bubble` | 4 |
+| `.avatar-anchor` | (inherits, no z-index) |
+
+## Issues to check
+
+1. The `.thought-bubble` (z-index: 4) is inside `.avatar-anchor` which has `position: relative`. Z-index stacking contexts are scoped to positioned ancestors. Since `.chrome` has `position: absolute` (creating a stacking context), the bubble's z-index 4 competes within the chrome.
+
+2. `.tool-indicator` is `position: absolute` on the shadow root (not inside .chrome). It has `z-index: 3`. If the thought bubble is inside .chrome and the tool indicator is a sibling of .chrome, they're in the same stacking context. Bubble at z-index 4 > tool indicator at z-index 3 — bubble wins. ✓
+
+3. `.alert-banner` at z-index 3 — same analysis. ✓
+
+4. `.pill-btn` at z-index 10 — this is higher than the bubble. But pill-btn is only visible when collapsed to pill. When expanded (the state where the bubble shows), pill-btn should be hidden. Verify this.
+
+## What to fix
+
+If layering issues are found visually:
+
+```css
+.thought-bubble {
+ z-index: 10; /* raise above all chrome siblings */
+}
+.avatar-anchor {
+ z-index: 2; /* establish stacking context so bubble z-index is scoped */
+}
+```
+
+If `.avatar-anchor` needs `z-index` set, it also needs `position: relative` (already set) and an explicit z-index value.
+
+## Verification
+Trigger a thought bubble while also triggering the tool indicator. The bubble should render above the indicator. Trigger an alert banner — bubble should be above it.
diff --git a/prompts/avatar-chat/46-jsdoc-public-methods.md b/prompts/avatar-chat/46-jsdoc-public-methods.md
new file mode 100644
index 000000000..41b353b70
--- /dev/null
+++ b/prompts/avatar-chat/46-jsdoc-public-methods.md
@@ -0,0 +1,50 @@
+# 46 — JSDoc annotations for all new public methods
+
+## Status
+Required — per src/CLAUDE.md: "JSDoc for public APIs." All new public methods added by this feature need JSDoc.
+
+## File
+`src/element.js`
+
+## Methods requiring JSDoc
+
+```js
+/**
+ * Enable the inline avatar-in-chat layout.
+ * The avatar canvas is visible through a transparent window between the chat
+ * history and the input bar. The avatar walks during LLM streaming and shows
+ * a thought bubble with streaming text above its head.
+ * This is the default state. Call to re-enable after `disableAvatarChat()`.
+ */
+enableAvatarChat() { ... }
+
+/**
+ * Disable the inline avatar-in-chat layout and restore the original
+ * bottom-bar chat layout (messages left, input right, avatar in background).
+ * Walk animation and thought bubble will not fire while disabled.
+ * Equivalent to setting the `avatar-chat="off"` attribute.
+ */
+disableAvatarChat() { ... }
+```
+
+## Private methods (no JSDoc needed per convention, but add a one-line comment if the logic is non-obvious)
+
+```js
+// Walk animation: debounced — keeps walking as long as chunks arrive within 600ms of each other
+_onStreamChunk() { ... }
+
+// Crossfade walk→idle; safe to call even if not walking
+_stopWalkAnimation() { ... }
+
+// RAF-batched bubble text update; clears at sentence boundaries
+_streamToBubble(chunk) { ... }
+
+// Hides bubble, clears buffer, cancels pending RAF
+_clearThoughtBubble() { ... }
+
+// Disables input and updates placeholder during LLM processing
+_setBusy(busy) { ... }
+```
+
+## Verification
+Run `npx jsdoc src/element.js --dry-run` (if JSDoc is installed) and confirm no parse errors on the new methods. Or simply do a visual review that the JSDoc is correctly formatted above the method signature.
diff --git a/prompts/avatar-chat/46-src-claude-md-update.md b/prompts/avatar-chat/46-src-claude-md-update.md
new file mode 100644
index 000000000..ec186e7e8
--- /dev/null
+++ b/prompts/avatar-chat/46-src-claude-md-update.md
@@ -0,0 +1,42 @@
+# 46 — Update src/CLAUDE.md: protocol vocabulary and new methods
+
+## Status
+Documentation — `src/CLAUDE.md` is the canonical internal reference for developers working in this repo. It needs updates for the avatar-chat feature.
+
+## File
+`src/CLAUDE.md`
+
+## Changes needed
+
+### 1 — Protocol bus vocabulary table
+
+Add two rows to the table in "The protocol bus — event vocabulary":
+
+| Type | Payload | Emitted by | Consumed by |
+|---|---|---|---|
+| *(add)* `brain:stream` (Runtime EventTarget only, not protocol bus) | `{ chunk: string }` | `runtime/_loop()` via `onChunk` callback | `element.js` (bubble streaming, walk animation, chat live text) |
+| *(add)* `skill:tool-start` (Runtime EventTarget only) | `{ tool: string, args: object }` | `runtime/_loop()` before tool dispatch | `element.js` (walk start, bubble tool label) |
+
+Note clearly that these are **Runtime EventTarget events** (listened on the `<agent-3d>` host element via `addEventListener`), not protocol bus actions (`protocol.emit()`). This distinction matters for skill authors.
+
+### 2 — Web component boundary section
+
+Add to the `element.js` entry:
+
+> **Avatar-chat mode** (default on): vertical chrome layout with `.avatar-anchor` transparent window. Thought bubble appears above the anchor. Walk animation (`walk` clip) plays during `brain:stream` events. Disabled via `avatar-chat="off"` attribute. New public methods: `enableAvatarChat()`, `disableAvatarChat()`.
+
+### 3 — What's half-built section
+
+Remove or update any entries that are now fully built. Add:
+
+> - `avatar-chat` inline layout — fully wired. Walk clip, thought bubble, stream events all connected. See `prompts/avatar-chat/` for remaining polish items.
+
+### 4 — Gotchas section
+
+Add:
+> **`_onStreamChunk()` debounce**: The walk animation uses a 600ms debounce. Calling `_stopWalkAnimation()` directly will interrupt it. Only call `_stopWalkAnimation()` in response to `brain:thinking { thinking: false }` or deliberate teardown.
+
+> **Thought bubble RAF queue**: `_streamToBubble()` buffers chunks and flushes on the next animation frame. Don't read `_thoughtTextEl.textContent` synchronously after calling `_streamToBubble()` — it won't reflect the latest buffer yet.
+
+## Verification
+Read through `src/CLAUDE.md`. Every new event, method, and behavior added by the avatar-chat feature is mentioned. No stale "half-built" entries referring to things that are now done.
diff --git a/prompts/avatar-chat/47-app-js-route-integration.md b/prompts/avatar-chat/47-app-js-route-integration.md
new file mode 100644
index 000000000..ca06e41fd
--- /dev/null
+++ b/prompts/avatar-chat/47-app-js-route-integration.md
@@ -0,0 +1,41 @@
+# 47 — app.js: verify avatar-chat attribute passes through hash params
+
+## Status
+Verification — `src/app.js` handles URL hash routing and sets attributes on `<agent-3d>`. If `avatar-chat` should be configurable via URL (e.g. `#avatar-chat=off` for embed use cases), it needs to be parsed there.
+
+## File
+`src/app.js`
+
+## What to check
+
+Open `src/app.js`. Find where hash params are parsed (look for `#model`, `#widget`, `#agent`, `#kiosk`, etc.) and where they're applied to the element.
+
+Determine: does the app currently support `#avatar-chat=off` as a hash param? If not, decide whether to add it.
+
+## Recommendation
+
+**Add it** — it's a one-liner and makes the embed use case dramatically better. An iframe embed that wants a clean avatar-in-chat experience can pass `#avatar-chat=off` without modifying the element's HTML.
+
+In the hash parsing section:
+```js
+if (params.has('avatar-chat') && params.get('avatar-chat') === 'off') {
+ el.setAttribute('avatar-chat', 'off');
+}
+```
+
+Or using the same pattern as `kiosk`:
+```js
+const avatarChatOff = params.has('avatar-chat') && params.get('avatar-chat') === 'off';
+if (avatarChatOff) el.setAttribute('avatar-chat', 'off');
+```
+
+## Also add to EMBED_SPEC.md (connect with prompt 26)
+
+In the URL hash params section of EMBED_SPEC.md, add:
+
+| Hash param | Effect |
+|---|---|
+| `#avatar-chat=off` | Disables the inline avatar layout and walk animation |
+
+## Verification
+Navigate to `http://localhost:3001/#avatar-chat=off`. The element should render with the original bottom-bar layout.
diff --git a/prompts/avatar-chat/47-jsdoc-annotations.md b/prompts/avatar-chat/47-jsdoc-annotations.md
new file mode 100644
index 000000000..82e3ee079
--- /dev/null
+++ b/prompts/avatar-chat/47-jsdoc-annotations.md
@@ -0,0 +1,80 @@
+# 47 — JSDoc annotations for all new public methods
+
+## Status
+Documentation — the codebase convention (src/CLAUDE.md: "JSDoc for public APIs") requires JSDoc on any method exposed to consumers. Several new public and semi-public methods need annotations.
+
+## File
+`src/element.js`
+
+## Methods to annotate
+
+### `enableAvatarChat()`
+```js
+/**
+ * Enable the inline avatar-in-chat layout.
+ * Avatar walks during LLM streaming and shows a thought bubble.
+ * This is the default state — only needed to re-enable after `disableAvatarChat()`.
+ */
+enableAvatarChat() { ... }
+```
+
+### `disableAvatarChat()`
+```js
+/**
+ * Disable the inline avatar-in-chat layout.
+ * Restores the original bottom-bar chat overlay.
+ * Stops any in-progress walk animation and clears the thought bubble.
+ */
+disableAvatarChat() { ... }
+```
+
+### `_startWalkAnimation()` (if still present — otherwise skip)
+Internal — no JSDoc needed per convention (`_underscore` = private).
+
+### `_onStreamChunk()`
+Internal — no JSDoc needed.
+
+### `_streamToBubble(chunk)`
+Internal — but add a one-line comment for the RAF batching behavior:
+```js
+// Buffers chunk and flushes to DOM on the next animation frame (RAF-batched).
+_streamToBubble(chunk) { ... }
+```
+
+### `_clearThoughtBubble()`
+Internal — no JSDoc needed.
+
+### `_setBusy(busy)` (from prompt 16)
+Internal — one-line comment:
+```js
+// Disables/re-enables the input and updates placeholder during LLM turns.
+_setBusy(busy) { ... }
+```
+
+## File `src/runtime/index.js`
+
+### `cancel()`
+```js
+/**
+ * Abort the current in-flight LLM request, if any.
+ * Resolves the pending `send()` call immediately.
+ */
+cancel() { ... }
+```
+
+## File `src/runtime/providers.js`
+
+### `AnthropicProvider.complete()` — update existing JSDoc
+
+The `complete()` method now accepts `onChunk` and `signal` params. Update the comment:
+```js
+/**
+ * Send a completion request to Anthropic.
+ * Streams the response via SSE and calls `onChunk` for each text delta.
+ * @param {{ system, messages, tools, onChunk?, signal? }} opts
+ * @returns {Promise<{ text, toolCalls, thinking, stopReason }>}
+ */
+```
+
+## Verification
+`grep -n "@param\|@returns\|@type" src/element.js` shows annotations on `enableAvatarChat` and `disableAvatarChat`. No other new public methods are unannotated.
diff --git a/prompts/avatar-chat/47-walk-rate-limiting.md b/prompts/avatar-chat/47-walk-rate-limiting.md
new file mode 100644
index 000000000..174b4bff2
--- /dev/null
+++ b/prompts/avatar-chat/47-walk-rate-limiting.md
@@ -0,0 +1,51 @@
+# 47 — Rate-limit walk animation start calls
+
+## Status
+Performance/correctness — `_onStreamChunk()` is called on every `brain:stream` event, which fires 10-50 times per second. Each call does `clearTimeout` + `setTimeout` (cheap) but also calls `this._scene.playClipByName('walk', ...)` on the first chunk. The AnimationManager's `crossfadeTo()` is async (lazy loads if needed). Calling it multiple times rapidly could cause issues if the first call hasn't resolved.
+
+## File
+`src/element.js` — `_onStreamChunk()`
+
+## Current code
+```js
+_onStreamChunk() {
+ if (!this._scene || this.getAttribute('avatar-chat') === 'off') return;
+ if (!this._isWalking) {
+ this._isWalking = true;
+ this._scene.playClipByName('walk', { loop: true, fade_ms: 300 });
+ }
+ clearTimeout(this._walkStopDebounce);
+ this._walkStopDebounce = setTimeout(() => this._stopWalkAnimation(), 600);
+}
+```
+
+## Analysis
+
+The `if (!this._isWalking)` guard already prevents `playClipByName` from being called more than once per walk session. `this._isWalking = true` is set synchronously before the async `playClipByName` call. This means subsequent chunks see `_isWalking = true` and skip. This is correct.
+
+The only risk: if `playClipByName` fails (clip not loaded, promise rejects), `_isWalking` stays true and the walk never actually plays. The avatar is stuck in a "walking" state that never started.
+
+## Fix
+
+Handle the promise rejection:
+```js
+_onStreamChunk() {
+ if (!this._scene || this.getAttribute('avatar-chat') === 'off') return;
+ const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ if (!this._isWalking && !prefersReduced) {
+ this._isWalking = true;
+ this._scene.playClipByName('walk', { loop: true, fade_ms: 300 })
+ .catch(() => {
+ // Walk clip unavailable — reset so idle stays
+ this._isWalking = false;
+ });
+ }
+ clearTimeout(this._walkStopDebounce);
+ this._walkStopDebounce = setTimeout(() => this._stopWalkAnimation(), 600);
+}
+```
+
+Note: `playClipByName` may not return a Promise in all code paths — check `src/runtime/scene.js`. If it doesn't, wrap defensively: `Promise.resolve(this._scene.playClipByName(...)).catch(...)`.
+
+## Verification
+Delete `walk.json` temporarily. Send a message. Avatar should stay idle (no error in console, no stuck walk state). Restore the file — avatar walks normally.
diff --git a/prompts/avatar-chat/48-bundle-size-check.md b/prompts/avatar-chat/48-bundle-size-check.md
new file mode 100644
index 000000000..5dbe6ea4f
--- /dev/null
+++ b/prompts/avatar-chat/48-bundle-size-check.md
@@ -0,0 +1,57 @@
+# 48 — Bundle size audit: no unintended dependency growth
+
+## Status
+Required — the avatar-chat feature should add zero new npm dependencies. All new code is pure DOM, CSS, and calls to existing Three.js APIs. Verify this before shipping.
+
+## What to check
+
+### 1 — No new imports in modified files
+
+Check that no new `import` statements were added to:
+- `src/element.js`
+- `src/runtime/index.js`
+- `src/runtime/providers.js`
+- `src/agent-protocol.js`
+
+Run:
+```bash
+git diff main --name-only | xargs grep "^import" | grep -v "from '\.\." | grep -v "from 'three"
+```
+
+Any new third-party import (`from 'some-lib'`) would be a problem. The only acceptable new imports are from `'three'` (e.g. `THREE.Vector3` for head tracking in prompt 13) or relative paths within the project.
+
+### 2 — Animation clip size (already built)
+
+The walk clip is 106kB (uncompressed JSON). It will gzip to ~30-40kB. This is acceptable for a lazy-loaded asset that isn't in the main bundle.
+
+Verify it's lazy-loaded (not inlined into the JS bundle):
+```bash
+grep -r "walk.json" src/
+```
+Should only appear in the manifest and in the AnimationManager loading logic — never as a static import.
+
+### 3 — Build output size
+
+Run the library build and compare before/after:
+```bash
+npm run build:lib 2>&1 | grep "dist/"
+```
+(Or whatever build command produces the distributable.) The main bundle should not grow by more than ~3KB (gzip) for the avatar-chat JS additions.
+
+### 4 — CSS in BASE_STYLE
+
+The new CSS added to `BASE_STYLE` in `element.js` is a string literal — it's included in the JS bundle but adds negligible size (~1.5KB unminified → ~400B gzip).
+
+## Acceptable size budget
+
+| Addition | Max size (gzip) |
+|---|---|
+| New JS in element.js | +2KB |
+| New JS in runtime/index.js | +0.5KB |
+| New JS in runtime/providers.js | +1KB |
+| New CSS in BASE_STYLE | +0.5KB |
+| walk.json animation clip | 30-40KB (lazy, not bundled) |
+| **Total JS bundle growth** | **< 4KB gzip** |
+
+## Verification
+Run `npm run build` or `npm run dev:lib`. Compare bundle sizes before and after the avatar-chat commits. No new npm dependencies in `package.json`.
diff --git a/prompts/avatar-chat/48-streaming-message-markdown.md b/prompts/avatar-chat/48-streaming-message-markdown.md
new file mode 100644
index 000000000..309394262
--- /dev/null
+++ b/prompts/avatar-chat/48-streaming-message-markdown.md
@@ -0,0 +1,65 @@
+# 48 — Chat message rendering: basic markdown in responses
+
+## Status
+Enhancement — LLM responses often contain markdown (bold, lists, code). The current `_renderMessage()` sets `textContent` which renders markdown as raw symbols. Production chat UIs render at least basic markdown.
+
+## File
+`src/element.js` — `_renderMessage()` and `_appendStreamChunkToChat()`
+
+## What to implement
+
+A minimal, safe inline markdown renderer — no external library, no XSS risk:
+
+```js
+_renderMarkdown(text) {
+ // Bold: **text** → <strong>text</strong>
+ // Italic: *text* → <em>text</em>
+ // Code: `text` → <code>text</code>
+ // Line breaks: \n → <br>
+ // Escape HTML first to prevent XSS
+ const escaped = text
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+ return escaped
+ .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
+ .replace(/\*(.+?)\*/g, '<em>$1</em>')
+ .replace(/`(.+?)`/g, '<code>$1</code>')
+ .replace(/\n/g, '<br>');
+}
+```
+
+Use `innerHTML` with the sanitized output instead of `textContent`:
+```js
+// In _renderMessage():
+msg.querySelector('.body').innerHTML = this._renderMarkdown(content);
+```
+
+**For streaming (prompt 15):** The streaming placeholder should use `textContent` (not innerHTML) during streaming to avoid partial-tag injection, then switch to innerHTML with markdown rendering when the final message arrives:
+```js
+// In brain:message handler, when replacing placeholder:
+this._streamingMsgEl?.closest('.msg')?.remove();
+// _renderMessage will use innerHTML+markdown for the final message
+```
+
+## CSS additions
+
+```css
+.msg .body code {
+ font-family: monospace;
+ background: rgba(255,255,255,0.08);
+ padding: 1px 4px;
+ border-radius: 4px;
+ font-size: 12px;
+}
+.msg .body strong { font-weight: 700; }
+.msg .body em { font-style: italic; opacity: 0.9; }
+```
+
+## Security note
+
+The `_renderMarkdown()` function HTML-escapes first, then applies regex substitutions on the escaped string. This is safe — no user-controlled HTML can sneak through because `<` and `>` are escaped before any pattern matching.
+
+## Verification
+Ask the agent to use markdown: "Respond with **bold** text and `code` and a list." The chat should render the formatting correctly, not show raw asterisks.
diff --git a/prompts/avatar-chat/48-think-clip-coordination.md b/prompts/avatar-chat/48-think-clip-coordination.md
new file mode 100644
index 000000000..3cc4916d6
--- /dev/null
+++ b/prompts/avatar-chat/48-think-clip-coordination.md
@@ -0,0 +1,45 @@
+# 48 — Coordinate walk animation with agent-avatar.js think clip
+
+## Status
+Conflict risk — `src/agent-avatar.js` plays a `think` clip (1.5–2s one-shot) when the empathy layer detects curiosity or when a `load-start` event fires. The AnimationManager handles both the walk loop and the think one-shot. If think fires while walk is playing, or walk starts while think is mid-play, the crossfade may create a jarring transition.
+
+## Files
+`src/agent-avatar.js` — find `think` clip usage
+`src/element.js` — `_onStreamChunk()`
+
+## Background
+
+In agent-avatar.js, `_triggerOneShot('think', 1.5)` is called for:
+- `load-start` → patience + curiosity triggers `think` clip
+- Curiosity weight > 0.6 → `think` clip
+
+The AnimationManager's `crossfadeTo()` handles transitions, but a LoopOnce one-shot and a LoopRepeat walk compete for the mixer's weight.
+
+## What to investigate
+
+Read `agent-avatar.js` around the `_triggerOneShot` calls. Understand:
+1. Does it use the same AnimationMixer as the walk? (Yes — same `viewer.animationManager`)
+2. Does the one-shot get blended additively or does it replace the current action?
+
+In AnimationManager, `playGesture` / `_triggerOneShot` likely uses a separate action channel with `LoopOnce`. Three.js blends all active actions. The walk (LoopRepeat) + think (LoopOnce) would blend — the think overlay plays on top of walk. This is actually the desired behavior for expressive motion.
+
+## Potential issue
+
+If the empathy layer calls `think` clip during a walk, the avatar will walk AND do the think gesture simultaneously. For a 1.5s clip, this looks fine — the character is clearly thinking while moving.
+
+The real risk: when `think` finishes (LoopOnce + clampWhenFinished), the action stays frozen at its last frame (T-pose or raised hand) until explicitly stopped. This would override the walk animation visually.
+
+## Fix
+
+In `agent-avatar.js`, after `_triggerOneShot` actions, add a listener to reset the action:
+```js
+// After creating the LoopOnce action:
+action.addEventListener('finished', () => {
+ action.stop();
+});
+```
+
+Check if this listener is already present. If not, add it.
+
+## Verification
+While the avatar is walking (mid-response), force curiosity high enough to trigger the think clip (use the debug console: `window.VIEWER.agent_avatar._emotions.curiosity = 0.8`). The think gesture should play briefly on top of walking, then return to clean walk. Avatar should not get stuck in the think pose.
diff --git a/prompts/avatar-chat/49-css-will-change-performance.md b/prompts/avatar-chat/49-css-will-change-performance.md
new file mode 100644
index 000000000..877d687d1
--- /dev/null
+++ b/prompts/avatar-chat/49-css-will-change-performance.md
@@ -0,0 +1,49 @@
+# 49 — CSS will-change for animated elements
+
+## Status
+Performance — the thought bubble animates `opacity` and `transform` frequently. Adding `will-change` hints to the browser promotes these elements to their own compositor layer, reducing main-thread paint work during animation.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## What to add
+
+```css
+.thought-bubble {
+ will-change: opacity, transform;
+ ...
+}
+
+.thought-bubble .dot {
+ will-change: transform, opacity;
+}
+```
+
+## Important caveats
+
+`will-change` should NOT be applied to elements that are always present but rarely animated. The thought bubble is hidden (opacity: 0) most of the time — promoting it permanently wastes GPU memory.
+
+Better pattern: add `will-change` only when animation is about to start, and remove it after:
+
+```js
+// In _streamToBubble / before bubble becomes active:
+if (this._thoughtBubbleEl) {
+ this._thoughtBubbleEl.style.willChange = 'opacity, transform';
+}
+
+// In _clearThoughtBubble, after the hide transition completes:
+setTimeout(() => {
+ if (this._thoughtBubbleEl) {
+ this._thoughtBubbleEl.style.willChange = 'auto';
+ }
+}, 300); // match the transition duration
+```
+
+Apply the same pattern to the walk animation — Three.js handles its own GPU layers so no action needed there.
+
+## What NOT to do
+
+Do not add `will-change` to `.chrome`, `.chat`, or `.avatar-anchor` — these are not animated and adding `will-change` would waste resources.
+
+## Verification
+Open Chrome DevTools → Rendering → Paint flashing. Send a message. The thought bubble should not cause green paint flashes on the surrounding page elements. Only the bubble itself should repaint.
diff --git a/prompts/avatar-chat/49-lint-prettier-pass.md b/prompts/avatar-chat/49-lint-prettier-pass.md
new file mode 100644
index 000000000..7837102f4
--- /dev/null
+++ b/prompts/avatar-chat/49-lint-prettier-pass.md
@@ -0,0 +1,48 @@
+# 49 — Lint and Prettier: all modified files pass
+
+## Status
+Required — all files modified by the avatar-chat feature must pass ESLint and Prettier without errors or warnings before shipping.
+
+## What to run
+
+```bash
+npx prettier --check src/element.js src/runtime/index.js src/runtime/providers.js src/agent-protocol.js
+```
+
+If any files fail:
+```bash
+npx prettier --write src/element.js src/runtime/index.js src/runtime/providers.js src/agent-protocol.js
+```
+
+Then:
+```bash
+npx eslint src/element.js src/runtime/index.js src/runtime/providers.js src/agent-protocol.js
+```
+
+## Common issues to expect
+
+### Prettier — tabs vs spaces
+The codebase uses **tabs (4-wide)**. All new code must use tabs. If any new code uses spaces, Prettier will reformat it.
+
+### Prettier — trailing commas
+The Prettier config likely enforces trailing commas on multi-line objects/arrays. Check the new object literals in the event handlers and CSS string.
+
+### ESLint — no-unused-vars
+After removing `_startWalkAnimation` and `_walkReturnTimer` (prompt 03), confirm there are no `no-unused-vars` warnings for those names.
+
+### ESLint — no-undef
+If `THREE.Vector3` is used in prompt 13 (head tracking), it must be imported:
+```js
+import { Vector3 } from 'three';
+```
+Don't use `new THREE.Vector3()` — import the class directly.
+
+### ESLint — prefer-const
+Any new `let` that is never reassigned should be `const`.
+
+## Verification
+```bash
+npx prettier --check src/element.js src/runtime/index.js src/runtime/providers.js
+npx eslint src/element.js src/runtime/index.js src/runtime/providers.js
+```
+Both commands exit with code 0 and no output.
diff --git a/prompts/avatar-chat/49-vite-config-check.md b/prompts/avatar-chat/49-vite-config-check.md
new file mode 100644
index 000000000..6b2da705a
--- /dev/null
+++ b/prompts/avatar-chat/49-vite-config-check.md
@@ -0,0 +1,39 @@
+# 49 — vite.config.js: verify build config is correct after changes
+
+## Status
+Verification — `vite.config.js` appears in git status as modified. This must be reviewed before shipping to ensure the build doesn't have unintended changes.
+
+## File
+`vite.config.js`
+
+## What to do
+
+1. Run `git diff vite.config.js` to see exactly what changed
+2. Confirm the changes are intentional (not accidental edits from tooling)
+3. If the diff is empty or the changes are correct, mark done
+4. If there are unintended changes, restore the file: `git checkout vite.config.js`
+
+## Common safe changes to vite.config.js in this project
+
+- Adding new entry points for test pages
+- Adjusting asset inclusion patterns (e.g. to bundle `walk.json` correctly)
+- Setting `assetsInclude` for GLB or JSON animation files
+
+## Common dangerous changes
+
+- Removing `build.lib` config (breaks the CDN library build)
+- Changing `rollupOptions.external` (changes what's bundled vs external)
+- Removing the `public` directory from static assets
+
+## Verification
+
+```bash
+git diff vite.config.js
+```
+
+If the diff shows intentional changes, run a production build to verify:
+```bash
+npm run build
+```
+
+Build should complete with zero errors. Output should include the expected entry points.
diff --git a/prompts/avatar-chat/50-final-integration-smoke-test.md b/prompts/avatar-chat/50-final-integration-smoke-test.md
new file mode 100644
index 000000000..1edb98375
--- /dev/null
+++ b/prompts/avatar-chat/50-final-integration-smoke-test.md
@@ -0,0 +1,82 @@
+# 50 — Final integration smoke test
+
+## Status
+Final gate — run this end-to-end after all other prompts are complete. This is the go/no-go check before merging to main.
+
+## Prerequisites
+- All prompts 01–49 completed and verified
+- Dev server running (`npm run dev`)
+- Test page accessible at `http://localhost:3001/test-avatar-chat.html`
+
+---
+
+## Smoke test sequence
+
+### Test A — Full conversation flow
+1. Open test page
+2. Open DevTools console, run: `document.querySelector('agent-3d').addEventListener('brain:stream', e => console.count('chunk'))`
+3. Type "Explain quantum entanglement in 3 sentences" → Enter
+4. **Expected**:
+ - Input disables immediately with "Thinking…"
+ - Avatar starts walking within 100ms of Enter key
+ - Thought bubble appears with dots, then switches to streaming text
+ - Chat message body fills with live text (blinking cursor)
+ - Console shows 20+ `chunk` count events
+ - Message finalizes in chat, bubble disappears, avatar returns to idle
+ - Input re-enables
+5. Confirm zero console errors
+
+### Test B — Tool call flow
+1. Type "What's trending on pump.fun right now?" → Enter
+2. **Expected**:
+ - Avatar walks while tool executes
+ - Bubble shows "Searching pump.fun…"
+ - After tool result, LLM continues streaming with avatar walking
+ - Response lands in chat with token card below it
+ - Avatar returns to idle
+
+### Test C — avatar-chat="off" toggle
+1. Click "Toggle avatar-chat='off'"
+2. **Expected**:
+ - Layout switches to bottom-bar (horizontal, not vertical column)
+ - Send a message
+ - Avatar does NOT walk
+ - Thought bubble does NOT appear
+3. Click toggle again
+4. **Expected**: Layout returns to vertical column. Next message triggers walk and bubble.
+
+### Test D — Reduced motion
+1. DevTools → Rendering → prefers-reduced-motion: reduce
+2. Send a message
+3. **Expected**: Thought bubble appears but dots don't bounce. Avatar stays in idle (no walk).
+4. Turn off reduced motion emulation.
+
+### Test E — Rapid send
+1. Type "hi" → Enter (don't wait for response)
+2. Type "how are you" → Enter immediately
+3. Type "tell me a joke" → Enter immediately
+4. **Expected**: First message processes. Third message queues. Second is dropped. No console errors. After first completes, third processes.
+
+### Test F — Teardown mid-stream
+1. Start a long message ("Write a 500 word essay...")
+2. Immediately after bubble appears, run in console: `document.querySelector('agent-3d').remove()`
+3. **Expected**: No "Cannot read properties of null" errors. No stuck walk animations (element is removed so this is moot, but no unhandled rejections).
+
+### Test G — Background modes
+1. Add `background="dark"` → verify white bubble
+2. Add `background="light"` → verify dark bubble
+3. Remove background attr → verify bubble still visible
+
+### Test H — Floating mode
+1. Change `mode="inline"` to `mode="floating"` in console or test page
+2. Send a message
+3. **Expected**: Floating card with rounded corners. Drag handle at top. Chat, avatar window, input all properly padded. Walk and bubble work inside floating card.
+
+---
+
+## Sign-off criteria
+All 8 tests pass with zero console errors and zero visual regressions.
+
+**Go / No-go**: _______________________
+
+**Tested by**: _______________________ **Date**: _______________________
diff --git a/prompts/avatar-chat/50-production-build-verification.md b/prompts/avatar-chat/50-production-build-verification.md
new file mode 100644
index 000000000..d14c80ddf
--- /dev/null
+++ b/prompts/avatar-chat/50-production-build-verification.md
@@ -0,0 +1,66 @@
+# 50 — Production build verification
+
+## Status
+Required final step — run the full production build, check bundle size impact, confirm no regressions in the existing feature set, and verify the avatar-chat feature works end-to-end in the built output (not just in Vite dev mode).
+
+## Commands to run
+
+```bash
+# 1. Build animations (should already be done — walk.json exists)
+npm run build:animations
+
+# 2. Build the main app and library
+npm run build
+
+# 3. Check bundle size diff
+# Walk.json is 106kB (already built). No new JS dependencies were added.
+# Verify the element.js additions haven't ballooned the bundle:
+ls -lh dist/assets/*.js | sort -k5 -h
+
+# 4. Check for build errors
+# Any TypeScript/JSDoc annotation errors, missing imports, etc.
+
+# 5. Preview the production build
+npm run preview
+# Then open http://localhost:4173 and run through the manual QA checklist (prompt 43)
+```
+
+## What to verify in production build
+
+### No new dependencies
+```bash
+git diff package.json package-lock.json | grep '^\+'
+```
+Should show no new `dependencies` or `devDependencies` from the avatar-chat work.
+
+### Animation manifest is correct
+```bash
+cat public/animations/manifest.json | python3 -m json.tool | grep '"name"'
+```
+Should include `"walk"` entry.
+
+### walk.json exists and is valid
+```bash
+ls -lh public/animations/clips/walk.json
+node -e "JSON.parse(require('fs').readFileSync('public/animations/clips/walk.json','utf8')); console.log('valid')"
+```
+
+### No console errors in production
+Open the production preview. Open DevTools console. Load an agent. Send a message. Should be zero errors.
+
+### avatar-chat="off" still works in production
+Add `avatar-chat="off"` to the element. Verify original bottom-bar layout renders correctly.
+
+## Regression checklist
+
+- [ ] Existing animations (dance, wave, celebrate) still play via the animation strip
+- [ ] Chat messages still render correctly with sentiment tinting
+- [ ] Tool calls (if applicable) still display tool cards
+- [ ] Voice mode (browser TTS) still works
+- [ ] Floating mode pill collapse/expand works on mobile viewport
+- [ ] Agent identity card still loads
+- [ ] Memory still persists across page refreshes
+
+## Sign-off
+
+Mark this prompt complete only after running through ALL items above with zero failures.
diff --git a/prompts/avatar-chat/50-production-readiness-final.md b/prompts/avatar-chat/50-production-readiness-final.md
new file mode 100644
index 000000000..25a93d99b
--- /dev/null
+++ b/prompts/avatar-chat/50-production-readiness-final.md
@@ -0,0 +1,87 @@
+# 50 — Production readiness: final gate checklist
+
+## Status
+Final — run this after all other prompts are complete. This is the shipping gate.
+
+---
+
+## Prompts completion status
+
+| # | Prompt | Done? |
+|---|---|---|
+| 01 | Fix thought bubble DOM (.text span) | ☐ |
+| 02 | Fix brain:thinking event order | ☐ |
+| 03 | Remove stale _walkReturnTimer refs | ☐ |
+| 04 | Preload walk + idle clips on boot | ☐ |
+| 05 | Walk during tool calls | ☐ |
+| 06 | Walk during TTS | ☐ |
+| 07 | Walk on user send | ☐ |
+| 08 | Reduced motion support | ☐ |
+| 09 | Tool call label in bubble | ☐ |
+| 10 | Bubble CSS custom properties | ☐ |
+| 11 | Bubble light background adaptation | ☐ |
+| 12 | Bubble enter/exit animation | ☐ |
+| 13 | Bubble head tracking in 3D | ☐ |
+| 14 | Bubble RAF batching | ☐ |
+| 15 | Live streaming text in chat | ☐ |
+| 16 | Input state during streaming | ☐ |
+| 17 | Chat auto-scroll during streaming | ☐ |
+| 18 | Floating mode layout | ☐ |
+| 19 | Mobile pill mode | ☐ |
+| 20 | Camera framing for inline mode | ☐ |
+| 21 | Stream abort / error handling | ☐ |
+| 22 | Concurrent request guard | ☐ |
+| 23 | Proxy SSE passthrough | ☐ |
+| 24 | Kiosk mode disable | ☐ |
+| 25 | ACTION_TYPES: brain:stream | ☐ |
+| 26 | EMBED_SPEC docs | ☐ |
+| 27 | JS API: enableAvatarChat/disable | ☐ |
+| 28 | Notifier walk integration | ☐ |
+| 29 | Animation preload strategy | ☐ |
+| 30 | aria-live regions | ☐ |
+| 31 | Keyboard navigation | ☐ |
+| 32 | Walk animation review | ☐ |
+| 33 | Bubble tail direction | ☐ |
+| 34 | LiveKit voice walk | ☐ |
+| 35 | Crossfade timing tuning | ☐ |
+| 36 | Bubble truncation and readability | ☐ |
+| 37 | Teardown complete cleanup | ☐ |
+| 38 | NullProvider graceful degradation | ☐ |
+| 39 | data-reactive walk | ☐ |
+| 40 | lib.js export update | ☐ |
+| 41 | Section/fullscreen modes | ☐ |
+| 42 | Test page created | ☐ |
+| 43 | Manual QA checklist passed | ☐ |
+| 44 | src/CLAUDE.md updated | ☐ |
+| 45 | Lint and format | ☐ |
+| 46 | JSDoc annotations | ☐ |
+| 47 | app.js hash param | ☐ |
+| 48 | Markdown rendering in chat | ☐ |
+| 49 | vite.config.js verified | ☐ |
+
+---
+
+## Hard requirements (must be ✅ before shipping)
+
+- [ ] 01 — bubble DOM fix (streaming text invisible without this)
+- [ ] 15 — live streaming in chat (core UX)
+- [ ] 16 — input disabled during streaming (prevents "runtime busy" errors)
+- [ ] 21 — stream abort on teardown (prevents memory leaks)
+- [ ] 23 — proxy SSE passthrough (streaming broken without this)
+- [ ] 37 — teardown cleanup (memory leaks)
+- [ ] 43 — QA checklist passed
+- [ ] 45 — lint clean
+
+## Nice-to-have (ship without if needed)
+
+- 13 — head tracking (fixed position is acceptable)
+- 32 — walk animation review (strafe may be fine)
+- 48 — markdown rendering (plain text is acceptable)
+
+## Deploy command
+
+```bash
+npm run build
+# Verify dist/ output
+# Deploy to production environment
+```
diff --git a/public/test-avatar-chat.html b/public/test-avatar-chat.html
new file mode 100644
index 000000000..b39183867
--- /dev/null
+++ b/public/test-avatar-chat.html
@@ -0,0 +1,88 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Avatar-Chat Test</title>
+ <style>
+ body { margin: 0; background: #0b0d10; color: white; font-family: system-ui; }
+ .container { display: flex; height: 100vh; gap: 16px; padding: 16px; box-sizing: border-box; }
+ agent-3d { flex: 0 0 360px; height: 100%; }
+ .controls { flex: 1; display: flex; flex-direction: column; gap: 12px; padding: 16px; }
+ button { padding: 8px 16px; border: 1px solid rgba(255,255,255,0.2); background: rgba(255,255,255,0.05); color: white; border-radius: 8px; cursor: pointer; }
+ button:hover { background: rgba(255,255,255,0.1); }
+ .status { font-size: 12px; opacity: 0.6; padding: 8px; background: rgba(255,255,255,0.04); border-radius: 8px; }
+ pre { margin: 0; font-size: 11px; white-space: pre-wrap; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <agent-3d
+ id="agent"
+ src="/animations/robotexpressive.glb"
+ brain="claude-opus-4-6"
+ background="dark"
+ mode="inline"
+ responsive="false"
+ width="360px"
+ height="100%"
+ ></agent-3d>
+
+ <div class="controls">
+ <h2>Avatar-Chat Test Panel</h2>
+
+ <div>
+ <strong>Layout Toggle</strong><br>
+ <button onclick="toggle()">Toggle avatar-chat="off"</button>
+ <span id="toggle-state">ON</span>
+ </div>
+
+ <div>
+ <strong>Manual Triggers</strong><br>
+ <button onclick="send('Hello, say something short.')">Short response</button>
+ <button onclick="send('Write a detailed 3-paragraph explanation of how blockchain works.')">Long response</button>
+ <button onclick="send('What are the trending tokens on pump.fun?')">Tool call (if skill installed)</button>
+ </div>
+
+ <div>
+ <strong>Event Log</strong>
+ <div class="status"><pre id="log"></pre></div>
+ </div>
+ </div>
+ </div>
+
+ <script type="module">
+ import '/src/element.js';
+
+ const agent = document.getElementById('agent');
+ const log = document.getElementById('log');
+ const toggleState = document.getElementById('toggle-state');
+ let lines = [];
+
+ function addLog(msg) {
+ lines.unshift(`${new Date().toISOString().slice(11,23)} ${msg}`);
+ lines = lines.slice(0, 20);
+ log.textContent = lines.join('\n');
+ }
+
+ for (const ev of ['brain:thinking', 'brain:stream', 'brain:message', 'skill:tool-start', 'skill:tool-called', 'voice:speech-start', 'voice:speech-end']) {
+ agent.addEventListener(ev, (e) => {
+ const detail = ev === 'brain:stream'
+ ? `chunk="${e.detail?.chunk?.slice(0,20)}…"`
+ : JSON.stringify(e.detail || {}).slice(0, 60);
+ addLog(`${ev} ${detail}`);
+ });
+ }
+
+ window.toggle = () => {
+ if (agent.getAttribute('avatar-chat') === 'off') {
+ agent.removeAttribute('avatar-chat');
+ toggleState.textContent = 'ON';
+ } else {
+ agent.setAttribute('avatar-chat', 'off');
+ toggleState.textContent = 'OFF';
+ }
+ };
+
+ window.send = (text) => agent.say(text);
+ </script>
+</body>
+</html>
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
index 1dda5e688..adfe752b0 100644
--- a/specs/EMBED_SPEC.md
+++ b/specs/EMBED_SPEC.md
@@ -87,7 +87,8 @@ All on-chain forms resolve through [`src/erc8004/resolver.js`](../src/erc8004/re
| `width` | CSS length | `100%` (inline), `320px` (floating) | |
| `height` | CSS length | `100%` (inline), `480px` (floating) | |
| `scale` | number | `1.0` | camera zoom multiplier, independent of pixel size |
-| `responsive` | boolean | on | applies `clamp()`-based mobile shrinking |
+| `responsive` | boolean | on | applies `clamp()`-based mobile shrinking |
+| `avatar-chat` | `"off"` or absent | on | Set to `"off"` to disable the inline avatar layout, thought bubble, and walk animation. Restores the original bottom-bar chat layout. |
### Identity / chain
@@ -156,6 +157,27 @@ Takes over the viewport with a close button. Useful for mobile.
<agent-3d src="..." mode="fullscreen"></agent-3d>
```
+## Avatar-in-Chat Mode
+
+By default, `<agent-3d>` uses a vertical chat layout where the 3D avatar is visible as a conversation participant through a transparent window between the message history and the input bar. While the LLM generates a response, the avatar:
+
+- **Walks** in place (synchronized to token streaming)
+- **Displays a thought bubble** above its head showing the streaming text
+- **Returns to idle** when the response is complete
+
+To disable this behavior and restore the original side-by-side bottom-bar layout:
+
+```html
+<agent-3d avatar-chat="off" src="..."></agent-3d>
+```
+
+The `avatar-chat="off"` attribute is CSS-driven and can be toggled at runtime via JavaScript:
+
+```js
+element.setAttribute('avatar-chat', 'off'); // disable
+element.removeAttribute('avatar-chat'); // re-enable
+```
+
## Slots
```html
diff --git a/src/CLAUDE.md b/src/CLAUDE.md
index 736005de9..c58629611 100644
--- a/src/CLAUDE.md
+++ b/src/CLAUDE.md
@@ -44,6 +44,16 @@ The viewer doesn't know about agents. The agent layer wraps the viewer through [
### Web component boundary
- [element.js](element.js) — `<agent-3d>` custom element. IntersectionObserver lazy boot unless `eager`. See attribute list in [specs/EMBED_SPEC.md](../specs/EMBED_SPEC.md).
+#### Avatar-chat methods (element.js)
+
+- `enableAvatarChat()` — re-enable inline avatar layout + walk + bubble (default on)
+- `disableAvatarChat()` — disable to restore bottom-bar layout; removes attribute `avatar-chat="off"`
+- `_onStreamChunk()` — start walking; debounces stop by 600ms; respects prefers-reduced-motion
+- `_stopWalkAnimation()` — crossfade walk→idle immediately
+- `_streamToBubble(chunk)` — append token chunk to bubble, RAF-batched
+- `_clearThoughtBubble()` — hide bubble and reset text+buffer
+- `_setBusy(busy)` — disable/enable input; sets placeholder and data-busy
+
- [lib.js](lib.js) — CDN library export surface.
- [app.js](app.js) — main SPA entry. **URL routing lives here.** Hash keys (embed/legacy): `model`, `widget`, `agent`, `kiosk`, `brain`, `proxyURL`, `preset`, `cameraPosition`, `register`. Query-string keys: `agent=<id>` (authenticated edit mode — distinct from `#agent=` which stays in embed mode), `pending=1` (post-login save round-trip).
@@ -80,6 +90,13 @@ All events are `CustomEvent` with `detail = { type, payload, timestamp, agentId,
| `interrupted` | `{}` | speech.js (TTS cancel) | avatar (startle + curiosity) |
| `notify` | `{ message, priority, duration }` | element.notify(), data-reactive | AgentNotifier (enter/exit frame + speak) |
+**Runtime EventTarget events** — `brain:stream` and `skill:tool-start` are NOT routed through `protocol.emit()`. They are dispatched on the Runtime EventTarget and re-dispatched by element.js as composed CustomEvents on the host element. Listen on the host element, not via `protocol.on()`.
+
+| Type | Payload | Emitted by | Consumed by |
+| ----------------- | -------------------------- | --------------------------------------- | -------------------------------------------------- |
+| `brain:stream` | `{ chunk: string }` | runtime `_loop()` via `dispatchEvent` | element.js (thought bubble streaming, chat buffer) |
+| `skill:tool-start`| `{ tool: string, args: object }` | runtime `_loop()` via `dispatchEvent` | element.js (walk animation, bubble label) |
+
**Identity records these to the backend:** `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`. Fire-and-forget via `POST /api/agent-actions`.
**Debug:** `window.VIEWER.agent_protocol.history.slice(-10)` or `protocol.on('*', console.log)`.
@@ -152,6 +169,8 @@ Z-rotation = `(curiosity*12 + empathy*9 + concern*4)` degrees. X-rotation (lean)
- **Skill `owned-only` trust** compares `manifest.author` with `ownerAddress` from element attr or backend. Mismatch → skill load throws.
- **[viewer.js](viewer.js) is the biggest file in `src/` (~1.2k lines).** Further module split is tracked in [prompts/scalability/03-module-split.md](../prompts/scalability/03-module-split.md). Don't start that refactor ad-hoc.
- **`memory.recall()` is substring search.** No embeddings yet.
+- **`brain:stream` fires per token** — at 50+ tokens/sec this is frequent. All handlers must be O(1) and RAF-batched. Never do synchronous network or heavy DOM work in a `brain:stream` handler.
+- **Walk animation requires walk+idle clips preloaded** — if `animationManager.isLoaded('walk')` returns false, `_onStreamChunk()` silently skips the walk. Ensure the preload strategy (prompt 29) is implemented before relying on walk-on-stream.
- **Throttle policies on `protocol.emit()`.** Animation-driving events are shaped by default: `gesture` (leading-edge throttle, 600 ms), `emote` (coalesce by `payload.trigger` with max-weight merge, 150 ms window), `look-at` (trailing debounce, 100 ms). All other types pass through. Override per-instance with `protocol.setThrottlePolicy(type, policy)` where `policy` is `{ mode: 'passthrough' }`, `{ mode: 'throttle', leading: true, intervalMs }`, `{ mode: 'debounce', intervalMs }`, or `{ mode: 'coalesce', windowMs, key, merge }`. Inspect suppressed events via `protocol.droppedCount(type)`. Passthrough events still go through the burst rate-limiter as a last-resort cascade guard.
---
@@ -162,7 +181,7 @@ Z-rotation = `(curiosity*12 + empathy*9 + concern*4)` degrees. X-rotation (lean)
- [editor/](editor/) — GLB export + material editor exist, agent-system integration minimal
- ERC-8004 reputation/validation — hooked but no UI
- Memory `encrypted-ipfs` mode — stub
-- Runtime `thinking: 'auto'` — limited UX wiring
+- Chat streaming — implemented but not tested in all edge cases
- Privy integration — functions exist, no full auth flow in element.js
- Avatar Creator save-to-account — may not persist in all flows
- Avatar Creator now wraps the Ready Player Me iframe. Configure the subdomain via `VITE_RPM_SUBDOMAIN`; falls back to `demo.readyplayer.me`.
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index e1e6a0bb4..a8dcc55eb 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -30,6 +30,11 @@ export const ACTION_TYPES = {
NOTIFY: 'notify', // avatar walks into frame, delivers a message, retreats
};
+// NOTE: 'brain:stream' and 'skill:tool-start' are Runtime EventTarget events, not protocol bus actions.
+// They flow via runtime.dispatchEvent() and are re-dispatched on the host element as composed CustomEvents.
+// Listen on the host element: element.addEventListener('brain:stream', handler)
+// element.addEventListener('skill:tool-start', handler)
+
/**
* @typedef {Object} ActionPayload
* @property {string} type — one of ACTION_TYPES
@@ -77,12 +82,12 @@ export class AgentProtocol extends EventTarget {
this._droppedCounts = new Map();
// Burst rate-limiter — absolute runaway protection for passthrough events
- this._counters = new Map(); // eventType → { count, windowStart }
- this._throttled = new Set(); // event types currently rate-limited
+ this._counters = new Map(); // eventType → { count, windowStart }
+ this._throttled = new Set(); // event types currently rate-limited
this._limits = {
'perform-skill': 10,
- 'emote': 20,
- 'speak': 5,
+ emote: 20,
+ speak: 5,
'*': 100,
};
this._windowMs = 100;
diff --git a/src/element.js b/src/element.js
index ebb7b2f3a..621b6a1c7 100644
--- a/src/element.js
+++ b/src/element.js
@@ -1,6 +1,7 @@
// <agent-3d> — the web component that ships the whole framework in one tag.
// See specs/EMBED_SPEC.md
+import { Box3 } from 'three';
import { Viewer } from './viewer.js';
import { Runtime } from './runtime/index.js';
import { SceneController } from './runtime/scene.js';
@@ -195,11 +196,19 @@ const BASE_STYLE = `
content: '';
position: absolute;
bottom: -8px;
+ top: auto;
left: 50%;
transform: translateX(-50%);
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 8px solid var(--agent-bubble-bg);
+ border-bottom: none;
+ }
+ .thought-bubble[data-tail-dir="up"]::after {
+ bottom: auto;
+ top: -8px;
+ border-top: none;
+ border-bottom: 8px solid var(--agent-bubble-bg);
}
.thought-bubble[data-active="true"] { opacity: 1; transform: translateX(-50%) scale(1); }
.thought-bubble .text {
@@ -227,6 +236,17 @@ const BASE_STYLE = `
.thought-bubble .dot { animation: none; opacity: 0.6; }
@keyframes thought-dot { to {} }
}
+ .thought-bubble[data-error="true"] {
+ background: rgba(239, 68, 68, 0.92);
+ color: #fff;
+ }
+ .thought-bubble[data-error="true"]::after {
+ border-top-color: rgba(239, 68, 68, 0.92);
+ }
+ .thought-bubble[data-error="true"][data-tail-dir="up"]::after {
+ border-bottom-color: rgba(239, 68, 68, 0.92);
+ border-top-color: transparent;
+ }
.msg { margin: 6px 0; padding: 8px 10px; border-radius: 10px; border-left: 3px solid transparent; transition: border-color .2s; }
.msg.celebration { border-left-color: rgba(34,197,94,0.85); background: rgba(34,197,94,0.06); }
.msg.concern { border-left-color: rgba(239,68,68,0.85); background: rgba(239,68,68,0.06); }
@@ -369,6 +389,9 @@ const BASE_STYLE = `
:host([background="light"]) .thought-bubble::after {
border-top-color: rgba(30, 30, 50, 0.92);
}
+ :host([background="light"]) .thought-bubble[data-tail-dir="up"]::after {
+ border-bottom-color: rgba(30, 30, 50, 0.92);
+ }
:host([background="light"]) .thought-bubble .text {
color: #f9fafb;
}
@@ -482,9 +505,12 @@ class Agent3DElement extends HTMLElement {
this._livekitVoice = null;
this._voiceClient = null;
this._notifier = null;
+ this._notifyWalkCleanup = null;
+ this._speakWalkCleanup = null;
this._thoughtBubbleEl = null;
this._bubbleBuffer = '';
this._bubbleRafPending = false;
+ this._bubbleClearTimer = null;
this._isWalking = false;
this._walkStopDebounce = null;
this._streamingMsgEl = null;
@@ -622,23 +648,30 @@ class Agent3DElement extends HTMLElement {
const chat = document.createElement('div');
chat.className = 'chat';
chat.part = 'chat';
+ chat.setAttribute('tabindex', '0');
+ chat.setAttribute('role', 'log');
+ chat.setAttribute('aria-live', 'polite');
+ chat.setAttribute('aria-label', 'Conversation');
const row = document.createElement('div');
row.className = 'input-row';
const input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Say something...';
+ input.setAttribute('aria-label', 'Message to agent');
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && input.value.trim()) {
const v = input.value.trim();
input.value = '';
this._onStreamChunk(); // immediate visual feedback before LLM responds
this.say(v);
+ input.focus();
}
});
const micBtn = document.createElement('button');
micBtn.className = 'icon mic';
micBtn.title = 'Push to talk';
+ micBtn.setAttribute('aria-label', 'Push to talk');
micBtn.innerHTML = '🎙';
micBtn.addEventListener('click', () => this._toggleMic());
row.appendChild(input);
@@ -650,7 +683,9 @@ class Agent3DElement extends HTMLElement {
avatarAnchor.className = 'avatar-anchor';
const thoughtBubble = document.createElement('div');
thoughtBubble.className = 'thought-bubble';
+ thoughtBubble.setAttribute('role', 'status');
thoughtBubble.setAttribute('aria-live', 'polite');
+ thoughtBubble.setAttribute('aria-label', 'Agent is thinking');
thoughtBubble.innerHTML =
'<span class="text"></span>' +
'<span class="dot"></span><span class="dot"></span><span class="dot"></span>';
@@ -672,9 +707,25 @@ class Agent3DElement extends HTMLElement {
if (!this._micEl) return;
const { state } = e.detail;
this._micEl.dataset.voiceState = state;
- this._micEl.title = state === 'idle' || !state
- ? 'Push to talk'
- : 'Voice active — click to stop';
+ this._micEl.title =
+ state === 'idle' || !state ? 'Push to talk' : 'Voice active — click to stop';
+
+ if (this.getAttribute('avatar-chat') !== 'off' && !this.hasAttribute('kiosk')) {
+ if (state === 'speaking' || state === 'thinking') {
+ this._onStreamChunk();
+ } else if (state === 'idle') {
+ this._stopWalkAnimation();
+ }
+ }
+
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ if (state === 'speaking') {
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'false';
+ } else if (state === 'idle') {
+ this._clearThoughtBubble();
+ }
+ }
});
// Tool-call indicator ("Checking the chain…").
@@ -689,7 +740,8 @@ class Agent3DElement extends HTMLElement {
const banner = document.createElement('div');
banner.className = 'alert-banner';
banner.part = 'alert-banner';
- banner.innerHTML = '<span class="msg-text"></span><button aria-label="Dismiss">×</button>';
+ banner.innerHTML =
+ '<span class="msg-text"></span><button aria-label="Dismiss">×</button>';
banner.querySelector('button').addEventListener('click', () => {
banner.dataset.active = 'false';
});
@@ -736,13 +788,19 @@ class Agent3DElement extends HTMLElement {
const chips = [];
if (installed.has('pump-fun')) {
chips.push(
- { label: '🔥 Trending now', prompt: 'What are the trending tokens on pump.fun right now?' },
+ {
+ label: '🔥 Trending now',
+ prompt: 'What are the trending tokens on pump.fun right now?',
+ },
{ label: '👑 King of the hill', prompt: "Who's the king of the hill on pump.fun?" },
{ label: '🆕 New launches', prompt: 'Show me the newest pump.fun launches.' },
);
}
if (installed.has('dca')) {
- chips.push({ label: '💸 Set up DCA', prompt: 'Help me set up a weekly USDC → WETH DCA.' });
+ chips.push({
+ label: '💸 Set up DCA',
+ prompt: 'Help me set up a weekly USDC → WETH DCA.',
+ });
}
if (chips.length === 0) {
chips.push(
@@ -1144,6 +1202,31 @@ class Agent3DElement extends HTMLElement {
const bodyURI = resolveURI(manifest.body?.uri);
if (bodyURI) {
await viewer.load(bodyURI, '', new Map());
+ // Belt-and-suspenders: ensure walk + idle are hot before the first
+ // brain:stream fires. _setupAnimationPanel already kicked these off;
+ // this await guarantees they resolve before boot continues.
+ const _am = viewer.animationManager;
+ if (_am) {
+ await Promise.allSettled([_am.ensureLoaded('idle'), _am.ensureLoaded('walk')]);
+ }
+ // After the reveal tween completes, shift the orbital target upward
+ // so the avatar's upper body fills the avatar-anchor window rather
+ // than the full canvas height.
+ const _v = viewer;
+ const _nudge = () => {
+ if (_v._cameraTweenRaf) {
+ requestAnimationFrame(_nudge);
+ return;
+ }
+ if (!_v.controls || !_v.content || _v._disposed) return;
+ const box = new Box3().setFromObject(_v.content);
+ const h = box.max.y - box.min.y;
+ const mid = (box.max.y + box.min.y) / 2;
+ _v.controls.target.set(0, mid + h * 0.12, 0);
+ _v.controls.update();
+ _v.invalidate();
+ };
+ requestAnimationFrame(_nudge);
}
this._scene = new SceneController(viewer);
@@ -1271,8 +1354,14 @@ class Agent3DElement extends HTMLElement {
else this._clearToolIndicator();
}
if (!e.detail?.thinking) this._stopWalkAnimation();
- protocol.emit({ type: ACTION_TYPES.THINK, payload: { thought: 'processing your message...' } });
- protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'patience', weight: 0.5 } });
+ protocol.emit({
+ type: ACTION_TYPES.THINK,
+ payload: { thought: 'processing your message...' },
+ });
+ protocol.emit({
+ type: ACTION_TYPES.EMOTE,
+ payload: { trigger: 'patience', weight: 0.5 },
+ });
if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
if (e.detail?.thinking) {
this._thoughtBubbleEl.dataset.active = 'true';
@@ -1297,7 +1386,8 @@ class Agent3DElement extends HTMLElement {
this._streamToBubble('');
this._thoughtBubbleEl.dataset.streaming = 'true';
this._thoughtBubbleEl.dataset.active = 'true';
- if (this._thoughtTextEl) this._thoughtTextEl.textContent = text.slice(0, 80);
+ if (this._thoughtTextEl)
+ this._thoughtTextEl.textContent = text.slice(0, 80);
}
}
if (ev === 'voice:speech-end') {
@@ -1309,7 +1399,8 @@ class Agent3DElement extends HTMLElement {
this._setToolIndicator(tool);
this._clearToolIndicator();
if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
- if (this._thoughtBubbleEl) this._thoughtBubbleEl.dataset.streaming = 'false';
+ if (this._thoughtBubbleEl)
+ this._thoughtBubbleEl.dataset.streaming = 'false';
if (typeof result?.sentiment === 'number') {
this._lastToolSentiment = result.sentiment;
}
@@ -1323,6 +1414,29 @@ class Agent3DElement extends HTMLElement {
this._notifier = new AgentNotifier(this, protocol);
this._notifier.attach();
+ // Walk during notification: enter frame (450ms) + message duration + exit frame (380ms)
+ const _notifyWalkHandler = ({ payload }) => {
+ if (this.getAttribute('avatar-chat') === 'off') return;
+ if (this.hasAttribute('kiosk')) return;
+ const duration = payload?.duration ?? 6000;
+ this._onStreamChunk();
+ clearTimeout(this._walkStopDebounce);
+ this._walkStopDebounce = setTimeout(
+ () => this._stopWalkAnimation(),
+ 450 + duration + 380,
+ );
+ };
+ protocol.on(ACTION_TYPES.NOTIFY, _notifyWalkHandler);
+ this._notifyWalkCleanup = () => protocol.off(ACTION_TYPES.NOTIFY, _notifyWalkHandler);
+
+ const _speakWalkHandler = () => {
+ if (this.getAttribute('avatar-chat') === 'off') return;
+ if (this.hasAttribute('kiosk')) return;
+ this._onStreamChunk();
+ };
+ protocol.on(ACTION_TYPES.SPEAK, _speakWalkHandler);
+ this._speakWalkCleanup = () => protocol.off(ACTION_TYPES.SPEAK, _speakWalkHandler);
+
// LiveKit realtime voice — connect when voice="livekit" and agent-id is set
if (this.getAttribute('voice') === 'livekit' && _backendId) {
this._connectLiveKit(_backendId).catch((err) => {
@@ -1515,9 +1629,13 @@ class Agent3DElement extends HTMLElement {
const stageRect = this._stageEl?.getBoundingClientRect();
if (!anchorRect || !stageRect) return;
const relY = pos.y - (anchorRect.top - stageRect.top) - 60;
- this._thoughtBubbleEl.style.top = `${Math.max(8, relY)}px`;
+ const clampedY = Math.max(8, relY);
+ this._thoughtBubbleEl.style.top = `${clampedY}px`;
this._thoughtBubbleEl.style.left = `${pos.x}px`;
this._thoughtBubbleEl.style.transform = 'translateX(-50%) scale(var(--bubble-scale, 1))';
+ const headRelY = pos.y - (anchorRect.top - stageRect.top);
+ const bubbleBottom = clampedY + this._thoughtBubbleEl.offsetHeight;
+ this._thoughtBubbleEl.dataset.tailDir = bubbleBottom < headRelY ? 'up' : 'down';
}
_appendStreamChunkToChat(chunk) {
@@ -1549,29 +1667,52 @@ class Agent3DElement extends HTMLElement {
}
}
+ _flushBubble() {
+ this._bubbleRafPending = false;
+ if (!this._thoughtTextEl) return;
+
+ let t = this._bubbleBuffer;
+
+ // Roll forward past completed sentences so the bubble feels live
+ const sentenceEnd = t.search(/[.!?]\s/);
+ if (sentenceEnd !== -1 && t.length > sentenceEnd + 2) {
+ this._bubbleBuffer = t.slice(sentenceEnd + 2);
+ t = this._bubbleBuffer;
+ }
+
+ // Hard cap at 100 chars, break at last word boundary
+ if (t.length > 100) {
+ const truncated = t.slice(-90);
+ const wordBreak = truncated.indexOf(' ');
+ t = '…' + (wordBreak !== -1 ? truncated.slice(wordBreak) : truncated);
+ }
+
+ this._thoughtTextEl.textContent = t;
+ }
+
_streamToBubble(chunk) {
if (!this._thoughtBubbleEl || !this._thoughtTextEl) return;
this._thoughtBubbleEl.dataset.active = 'true';
this._thoughtBubbleEl.dataset.streaming = 'true';
+ this._thoughtBubbleEl.setAttribute('aria-label', 'Agent is responding');
this._bubbleBuffer += chunk;
if (!this._bubbleRafPending) {
this._bubbleRafPending = true;
- requestAnimationFrame(() => {
- this._bubbleRafPending = false;
- if (!this._thoughtTextEl) return;
- const t = this._bubbleBuffer;
- this._thoughtTextEl.textContent = t.length > 120 ? '…' + t.slice(-110) : t;
- });
+ requestAnimationFrame(() => this._flushBubble());
}
}
_clearThoughtBubble() {
this._bubbleBuffer = '';
this._bubbleRafPending = false;
- if (!this._thoughtBubbleEl) return;
- this._thoughtBubbleEl.dataset.active = 'false';
- this._thoughtBubbleEl.dataset.streaming = 'false';
- if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
+ clearTimeout(this._bubbleClearTimer);
+ this._bubbleClearTimer = setTimeout(() => {
+ if (!this._thoughtBubbleEl) return;
+ this._thoughtBubbleEl.setAttribute('aria-label', '');
+ this._thoughtBubbleEl.dataset.active = 'false';
+ this._thoughtBubbleEl.dataset.streaming = 'false';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
+ }, 200);
}
_setBusy(busy) {
@@ -1581,13 +1722,18 @@ class Agent3DElement extends HTMLElement {
const row = this._inputEl.closest('.input-row');
if (row) row.dataset.busy = busy ? 'true' : 'false';
this._inputEl.placeholder = busy ? 'Thinking…' : 'Say something...';
+ if (!busy && this.shadowRoot?.activeElement == null) {
+ this._inputEl.focus();
+ }
}
_onStreamChunk() {
if (!this._scene || this.getAttribute('avatar-chat') === 'off') return;
+ if (this.hasAttribute('kiosk')) return;
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!this._isWalking && !prefersReduced) {
this._isWalking = true;
+ // fade_ms: 300ms idle→walk, 500ms walk→idle, 600ms debounce after last chunk
this._scene.playClipByName('walk', { loop: true, fade_ms: 300 });
}
clearTimeout(this._walkStopDebounce);
@@ -1742,8 +1888,13 @@ class Agent3DElement extends HTMLElement {
return card;
}
- if (tool === 'getTrendingTokens' || tool === 'getNewTokens' || tool === 'getGraduatedTokens') {
- const list = data.tokens || data.results || data.items || (Array.isArray(data) ? data : []);
+ if (
+ tool === 'getTrendingTokens' ||
+ tool === 'getNewTokens' ||
+ tool === 'getGraduatedTokens'
+ ) {
+ const list =
+ data.tokens || data.results || data.items || (Array.isArray(data) ? data : []);
if (!list.length) return null;
const top = list.slice(0, 5);
card.innerHTML = `
@@ -1767,8 +1918,9 @@ class Agent3DElement extends HTMLElement {
}
_esc(s) {
- return String(s ?? '').replace(/[&<>"]/g, (c) =>
- ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c],
+ return String(s ?? '').replace(
+ /[&<>"]/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c],
);
}
@@ -1891,10 +2043,16 @@ class Agent3DElement extends HTMLElement {
}
this._notifier?.detach();
this._notifier = null;
+ this._notifyWalkCleanup?.();
+ this._notifyWalkCleanup = null;
+ this._speakWalkCleanup?.();
+ this._speakWalkCleanup = null;
this._setBusy(false);
clearTimeout(this._walkStopDebounce);
this._walkStopDebounce = null;
this._isWalking = false;
+ this._bubbleBuffer = '';
+ this._bubbleRafPending = false;
this._streamingMsgEl = null;
this._streamingChatBuffer = '';
this._streamingChatRafPending = false;
@@ -1931,19 +2089,34 @@ class Agent3DElement extends HTMLElement {
if (!this._runtime) await this._waitForReady();
this._onStreamChunk();
protocol.emit({ type: ACTION_TYPES.LOOK_AT, payload: { target: 'user' } });
- protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'curiosity', weight: 0.6 } });
- protocol.emit({ type: ACTION_TYPES.THINK, payload: { thought: 'processing your message...' } });
- protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'patience', weight: 0.5 } });
+ protocol.emit({
+ type: ACTION_TYPES.EMOTE,
+ payload: { trigger: 'curiosity', weight: 0.6 },
+ });
+ protocol.emit({
+ type: ACTION_TYPES.THINK,
+ payload: { thought: 'processing your message...' },
+ });
+ protocol.emit({
+ type: ACTION_TYPES.EMOTE,
+ payload: { trigger: 'patience', weight: 0.5 },
+ });
await this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
} catch (err) {
this._stopWalkAnimation();
this._clearThoughtBubble();
this._setBusy(false);
- protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'concern', weight: 0.8 } });
- this.dispatchEvent(new CustomEvent('agent:error', {
- detail: { phase: 'send', error: err },
- bubbles: true, composed: true,
- }));
+ protocol.emit({
+ type: ACTION_TYPES.EMOTE,
+ payload: { trigger: 'concern', weight: 0.8 },
+ });
+ this.dispatchEvent(
+ new CustomEvent('agent:error', {
+ detail: { phase: 'send', error: err },
+ bubbles: true,
+ composed: true,
+ }),
+ );
}
}
}
@@ -1963,16 +2136,24 @@ class Agent3DElement extends HTMLElement {
this._onStreamChunk();
protocol.emit({ type: ACTION_TYPES.LOOK_AT, payload: { target: 'user' } });
protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'curiosity', weight: 0.6 } });
- protocol.emit({ type: ACTION_TYPES.THINK, payload: { thought: 'processing your message...' } });
+ protocol.emit({
+ type: ACTION_TYPES.THINK,
+ payload: { thought: 'processing your message...' },
+ });
protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'patience', weight: 0.5 } });
try {
- const reply = await this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
+ const reply = await this._runtime.send(text, {
+ voice: opts.voice ?? this.hasAttribute('voice'),
+ });
return reply?.text || '';
} catch (err) {
this._stopWalkAnimation();
this._clearThoughtBubble();
this._setBusy(false);
- protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'concern', weight: 0.8 } });
+ protocol.emit({
+ type: ACTION_TYPES.EMOTE,
+ payload: { trigger: 'concern', weight: 0.8 },
+ });
throw err;
}
}
@@ -1988,8 +2169,12 @@ class Agent3DElement extends HTMLElement {
playEmote(name, intensity = 1) {
const sc = this._scene;
if (!sc) return false;
- const fallbacks = { cheer: ['cheer', 'celebrate', 'wave'], flinch: ['flinch', 'defeated', 'concern', 'shake'], celebrate: ['celebrate', 'wave'] };
- for (const h of (fallbacks[name] || [name])) {
+ const fallbacks = {
+ cheer: ['cheer', 'celebrate', 'wave'],
+ flinch: ['flinch', 'defeated', 'concern', 'shake'],
+ celebrate: ['celebrate', 'wave'],
+ };
+ for (const h of fallbacks[name] || [name]) {
if (sc.playAnimationByHint(h)) return true;
}
this._headBob(intensity);
@@ -2026,6 +2211,25 @@ class Agent3DElement extends HTMLElement {
return this._scene?.playClipByName(name, opts);
}
+ /**
+ * Enable the inline avatar-in-chat layout.
+ * Avatar walks during LLM streaming, thought bubble shows response text.
+ * @returns {void}
+ */
+ enableAvatarChat() {
+ this.removeAttribute('avatar-chat');
+ }
+
+ /**
+ * Disable the inline avatar-in-chat layout and restore bottom-bar chat.
+ * @returns {void}
+ */
+ disableAvatarChat() {
+ this.setAttribute('avatar-chat', 'off');
+ this._stopWalkAnimation();
+ this._clearThoughtBubble();
+ }
+
async installSkill(uri) {
if (!this._skills) throw new Error('Agent not mounted');
return this._skills.install({ uri });
diff --git a/src/lib.js b/src/lib.js
index 35837a55c..59a08ece0 100644
--- a/src/lib.js
+++ b/src/lib.js
@@ -13,6 +13,11 @@ export { Memory } from './memory/index.js';
export { loadManifest, normalize, fetchRelative } from './manifest.js';
export { resolveURI, fetchWithFallback } from './ipfs.js';
+/**
+ * @typedef {Object} AvatarChatOptions
+ * @property {'off'|undefined} avatarChat - Set to 'off' to disable inline avatar layout
+ */
+
// Re-export the side-effectful element import for users who import the whole bundle.
export const defineElement = (tag = 'agent-3d') => {
if (!customElements.get(tag)) customElements.define(tag, Agent3DElement);
diff --git a/src/runtime/index.js b/src/runtime/index.js
index 12cbe111f..ed1abaf7d 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -114,9 +114,11 @@ export class Runtime extends EventTarget {
this.dispatchEvent(new CustomEvent('brain:stream', { detail: { chunk } }));
},
});
- this.dispatchEvent(new CustomEvent('brain:thinking', {
- detail: { thinking: false, content: response.thinking || '' },
- }));
+ this.dispatchEvent(
+ new CustomEvent('brain:thinking', {
+ detail: { thinking: false, content: response.thinking || '' },
+ }),
+ );
if (!response.toolCalls.length) {
finalText = response.text;
@@ -144,9 +146,11 @@ export class Runtime extends EventTarget {
// Dispatch each tool call
const results = [];
for (const call of response.toolCalls) {
- this.dispatchEvent(new CustomEvent('skill:tool-start', {
- detail: { tool: call.name, args: call.input },
- }));
+ this.dispatchEvent(
+ new CustomEvent('skill:tool-start', {
+ detail: { tool: call.name, args: call.input },
+ }),
+ );
let output,
isError = false;
try {
diff --git a/src/runtime/providers.js b/src/runtime/providers.js
index b1924250c..d313af9a5 100644
--- a/src/runtime/providers.js
+++ b/src/runtime/providers.js
@@ -50,7 +50,12 @@ export class AnthropicProvider {
headers['anthropic-dangerous-direct-browser-access'] = 'true';
}
- const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body), signal });
+ const res = await fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ signal,
+ });
if (!res.ok) {
const text = await res.text();
throw new Error(`Anthropic ${res.status}: ${text}`);
@@ -77,7 +82,11 @@ export class AnthropicProvider {
const payload = line.slice(6).trim();
if (payload === '[DONE]') break;
let evt;
- try { evt = JSON.parse(payload); } catch { continue; }
+ try {
+ evt = JSON.parse(payload);
+ } catch {
+ continue;
+ }
if (evt.type === 'message_delta' && evt.delta?.stop_reason) {
out.stopReason = evt.delta.stop_reason;
} else if (evt.type === 'content_block_start') {
@@ -97,7 +106,11 @@ export class AnthropicProvider {
}
} else if (evt.type === 'content_block_stop') {
if (currentToolCall) {
- try { currentToolCall.input = JSON.parse(currentToolCall.input); } catch { currentToolCall.input = {}; }
+ try {
+ currentToolCall.input = JSON.parse(currentToolCall.input);
+ } catch {
+ currentToolCall.input = {};
+ }
out.toolCalls.push(currentToolCall);
currentToolCall = null;
}
diff --git a/src/viewer.js b/src/viewer.js
index ea66ac26b..441d5645a 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -1244,6 +1244,22 @@ export class Viewer {
// Render buttons
this._renderAnimButtons();
+ // Preload walk and idle first so they're ready before the first brain:stream.
+ // loadAll() below fetches all clips with CONCURRENCY=4 and may not reach
+ // these two before the user sends a message; ensureLoaded kicks them off
+ // immediately and returns early if they're already in-progress or cached.
+ // allSettled so a missing walk clip doesn't block idle from playing.
+ console.time('walk-ready');
+ Promise.allSettled([
+ this.animationManager.ensureLoaded('idle'),
+ this.animationManager.ensureLoaded('walk'),
+ ]).then(() => {
+ console.timeEnd('walk-ready');
+ if (!this.animationManager.currentAction) {
+ this.animationManager.play('idle');
+ }
+ });
+
// Load all animations in background. We deliberately do NOT auto-play
// the first animation: external Mixamo-rigged FBX clips often retarget
// imperfectly onto Ready Player Me / Avaturn avatars, which collapses