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: add rate limiting for X (Twitter) memory seeding and withdrawal requests

nirholas31647ea59299
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 62b8d3b96..9cd92e4df 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -131,6 +131,10 @@ export const limits = {
memorySeed: (agentId) => getLimiter('memory:seed', { limit: 1, window: '1 d' }).limit(agentId),
// Edge TTS: free upstream but cached in R2 — limit unique synthesis requests per user/min.
ttsEdge: (userId) => getLimiter('tts:edge', { limit: 20, window: '1 m' }).limit(userId),
+ // X (Twitter) memory seeding: 1 seed per agent per 6 hours.
+ xSeed: (agentId) => getLimiter('memory:seed:x', { limit: 1, window: '6 h' }).limit(agentId),
+ // Withdrawal requests: 5 per user per day to prevent spam.
+ withdrawalPerUser: (userId) => getLimiter('withdrawal:user', { limit: 5, window: '1 d' }).limit(userId),
};
// Trust only proxy headers that Vercel itself sets and signs. Naively reading
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 2c40ac3e1..e25615098 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -65,13 +65,11 @@ async function handleActivity(req, res, id) {
const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
const limit = Math.min(parseInt(url.searchParams.get('limit') || '20', 10) || 20, 50);
- let signatures = [];
- try {
- const conn = solanaConnection(network);
+ const fetchActivity = async (conn) => {
const pk = new PublicKey(address);
const sigs = await conn.getSignaturesForAddress(pk, { limit });
const parsed = await conn.getParsedTransactions(sigs.map((s) => s.signature), { maxSupportedTransactionVersion: 0, commitment: 'confirmed' });
- signatures = sigs.map((s, i) => {
+ return sigs.map((s, i) => {
const tx = parsed[i];
let lamportDelta = null, summary = null;
if (tx?.meta && tx?.transaction) {
@@ -84,9 +82,26 @@ async function handleActivity(req, res, id) {
}
return { signature: s.signature, slot: s.slot, block_time: s.blockTime ?? null, success: !s.err && !tx?.meta?.err, error: s.err || tx?.meta?.err || null, lamport_delta: lamportDelta, sol_delta: lamportDelta == null ? null : lamportDelta / 1e9, summary };
});
+ };
+
+ let signatures = [];
+ try {
+ signatures = await fetchActivity(solanaConnection(network));
} catch (err) {
- console.error('[agents/solana/activity] RPC fetch failed', err);
- return error(res, 502, 'rpc_error', 'failed to fetch on-chain activity');
+ const hasCustomRpc = !!(network === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET
+ : process.env.SOLANA_RPC_URL);
+ if (hasCustomRpc) {
+ try {
+ signatures = await fetchActivity(solanaPublicConnection(network));
+ } catch (fallbackErr) {
+ console.error('[agents/solana/activity] RPC fetch failed (fallback)', fallbackErr);
+ return error(res, 502, 'rpc_error', 'failed to fetch on-chain activity');
+ }
+ } else {
+ console.error('[agents/solana/activity] RPC fetch failed', err);
+ return error(res, 502, 'rpc_error', 'failed to fetch on-chain activity');
+ }
}
return json(res, 200, { data: { address, network, signatures } });
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 98af94d87..3610dbb63 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -240,6 +240,8 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', `model "${model}" not in allowlist`);
}
+ const isStreaming = body.stream === true;
+
// 7. Forward to Anthropic
const t0 = Date.now();
const upstream = await fetch('https://api.anthropic.com/v1/messages', {
@@ -251,10 +253,79 @@ export default wrap(async (req, res) => {
},
body: JSON.stringify({ ...body, model }),
});
+
+ // 8a. Sanitize upstream errors before branching — do not forward Anthropic's error JSON.
+ if (upstream.status >= 400) {
+ const errText = await upstream.text();
+ log.error('upstream_error', { agentId, model, status: upstream.status, body: errText.slice(0, 2000) });
+ return json(res, 502, { error: 'upstream_error', status: upstream.status });
+ }
+
+ // 8b. Streaming path — pipe SSE chunks directly; extract token counts in-flight.
+ if (isStreaming) {
+ res.statusCode = upstream.status;
+ res.setHeader('content-type', 'text/event-stream');
+ res.setHeader('cache-control', 'no-cache');
+ res.setHeader('x-accel-buffering', 'no');
+
+ const reader = upstream.body.getReader();
+ const decoder = new TextDecoder();
+ let inputTokens = 0;
+ let outputTokens = 0;
+ let sseBuffer = '';
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ res.write(value);
+
+ // Parse SSE lines for usage events without buffering the whole body.
+ sseBuffer += decoder.decode(value, { stream: true });
+ const lines = sseBuffer.split('\n');
+ sseBuffer = lines.pop(); // keep the incomplete trailing line
+ for (const line of lines) {
+ if (!line.startsWith('data: ')) continue;
+ try {
+ const ev = JSON.parse(line.slice(6));
+ if (ev.type === 'message_start') inputTokens = ev.message?.usage?.input_tokens ?? 0;
+ if (ev.type === 'message_delta') outputTokens = ev.usage?.output_tokens ?? 0;
+ } catch {
+ // not every data line is JSON (e.g. [DONE]) — skip
+ }
+ }
+ }
+ } finally {
+ res.end();
+ }
+
+ const latencyMs = Date.now() - t0;
+
+ if (inputTokens || outputTokens) {
+ try {
+ await addMonthlyTokens(agentId, inputTokens + outputTokens);
+ } catch (err) {
+ log.warn('token_counter_write_failed', { agentId, msg: err?.message });
+ }
+ }
+
+ recordEvent({
+ kind: 'llm',
+ tool: 'anthropic.messages',
+ agentId,
+ bytes: 0,
+ latencyMs,
+ status: 'ok',
+ meta: { model, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },
+ });
+
+ return;
+ }
+
+ // 8c. Non-streaming path — buffer and parse as before.
const upstreamText = await upstream.text();
const latencyMs = Date.now() - t0;
- // 8. Parse upstream JSON once — extract token usage and detect errors.
let upstreamJson = null;
try {
upstreamJson = JSON.parse(upstreamText);
@@ -264,8 +335,7 @@ export default wrap(async (req, res) => {
const inputTokens = upstreamJson?.usage?.input_tokens ?? 0;
const outputTokens = upstreamJson?.usage?.output_tokens ?? 0;
- // Debit the per-agent token counter when we got a successful response.
- if (upstream.ok && (inputTokens || outputTokens)) {
+ if (inputTokens || outputTokens) {
try {
await addMonthlyTokens(agentId, inputTokens + outputTokens);
} catch (err) {
@@ -280,7 +350,7 @@ export default wrap(async (req, res) => {
agentId,
bytes: upstreamText.length,
latencyMs,
- status: upstream.ok ? 'ok' : 'error',
+ status: 'ok',
meta: {
model,
input_tokens: inputTokens,
@@ -289,18 +359,7 @@ export default wrap(async (req, res) => {
},
});
- // 10a. Sanitize upstream errors — do not forward Anthropic's error JSON.
- if (upstream.status >= 400) {
- log.error('upstream_error', {
- agentId,
- model,
- status: upstream.status,
- body: upstreamText.slice(0, 2000),
- });
- return json(res, 502, { error: 'upstream_error', status: upstream.status });
- }
-
- // 10b. Proxy Anthropic's successful response faithfully (unchanged shape).
+ // 10. Proxy Anthropic's successful response faithfully (unchanged shape).
res.statusCode = upstream.status;
res.setHeader('content-type', upstream.headers.get('content-type') || 'application/json');
return res.end(upstreamText);
diff --git a/prompts/avatar-chat/01-fix-bubble-dom.md b/prompts/avatar-chat/01-fix-bubble-dom.md
new file mode 100644
index 000000000..423b9e4c0
--- /dev/null
+++ b/prompts/avatar-chat/01-fix-bubble-dom.md
@@ -0,0 +1,24 @@
+# 01 — Fix thought bubble DOM: add `.text` span
+
+## Status
+Bug — code calls `thoughtBubble.querySelector('.text')` and stores it as `this._thoughtTextEl`, but the innerHTML only creates three `.dot` spans. The text span is missing so streaming text never appears.
+
+## File
+`src/element.js` — `_renderShell()` around line 593
+
+## Current code
+```js
+thoughtBubble.innerHTML = '<span class="dot"></span><span class="dot"></span><span class="dot"></span>';
+```
+
+## Fix
+```js
+thoughtBubble.innerHTML =
+ '<span class="text"></span>' +
+ '<span class="dot"></span><span class="dot"></span><span class="dot"></span>';
+```
+
+The `.text` span must come first so flex layout renders text before dots. The CSS rules `.thought-bubble[data-streaming="true"] .text { display: block; }` and `.thought-bubble[data-streaming="true"] .dot { display: none; }` already toggle between modes correctly — this just adds the missing element.
+
+## Verification
+After the fix, open the app, send a message, and confirm the thought bubble shows streaming words rather than staying empty.
diff --git a/prompts/avatar-chat/02-fix-brain-thinking-event-order.md b/prompts/avatar-chat/02-fix-brain-thinking-event-order.md
new file mode 100644
index 000000000..2977e1014
--- /dev/null
+++ b/prompts/avatar-chat/02-fix-brain-thinking-event-order.md
@@ -0,0 +1,42 @@
+# 02 — Fix brain:thinking event order in runtime loop
+
+## Status
+Bug — in `src/runtime/index.js` `_loop()`, the sequence is:
+1. `brain:thinking { thinking: true }` — correct, shown at start
+2. `brain:thinking { thinking: false }` — fires when `complete()` resolves
+3. `brain:thinking { content: response.thinking }` — fires AFTER the false, re-triggering the indicator
+
+This causes the tool indicator and thought bubble to flicker off then back on.
+
+## File
+`src/runtime/index.js` — `_loop()` around line 100
+
+## Current code
+```js
+this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { thinking: true } }));
+const response = await this.provider.complete({ ... });
+this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { thinking: false } }));
+
+if (response.thinking) {
+ this.dispatchEvent(
+ new CustomEvent('brain:thinking', { detail: { content: response.thinking } }),
+ );
+}
+```
+
+## Fix
+Merge the thinking content into the `thinking: false` event so it's a single emission:
+```js
+this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { thinking: true } }));
+const response = await this.provider.complete({ ... });
+this.dispatchEvent(new CustomEvent('brain:thinking', {
+ detail: { thinking: false, content: response.thinking || '' }
+}));
+```
+
+Remove the separate `if (response.thinking)` block entirely — it's now merged.
+
+Update `element.js` handler for `brain:thinking` to read `e.detail.content` if needed for future display (currently unused, but preserve the field for consumers listening on the host element).
+
+## Verification
+Console-log brain:thinking events. There should be exactly 2 per LLM turn: `{ thinking: true }` then `{ thinking: false, content: '...' }`. No third emission.
diff --git a/prompts/avatar-chat/03-fix-stale-timer-refs.md b/prompts/avatar-chat/03-fix-stale-timer-refs.md
new file mode 100644
index 000000000..b45cb7e51
--- /dev/null
+++ b/prompts/avatar-chat/03-fix-stale-timer-refs.md
@@ -0,0 +1,22 @@
+# 03 — Remove stale `_walkReturnTimer` and `_startWalkAnimation` references
+
+## Status
+Bug — `_startWalkAnimation()` and `_walkReturnTimer` were replaced by `_onStreamChunk()` / `_walkStopDebounce` but stale references remain in the file causing confusion and potential double-cleanup.
+
+## File
+`src/element.js`
+
+## What to audit and remove
+
+Search for every occurrence of:
+- `_startWalkAnimation` — should be zero. If any exist, remove the call site and the method definition.
+- `_walkReturnTimer` — should be zero. Remove from constructor init, teardown cleanup, and any clearTimeout calls.
+
+The replacement pattern is:
+- Old: `this._startWalkAnimation(text)` called in `brain:message` handler
+- New: `this._onStreamChunk()` called in `brain:stream` handler (already wired)
+
+Also verify `_teardown()` only clears `this._walkStopDebounce`, not `_walkReturnTimer`.
+
+## Verification
+`grep -n "_walkReturnTimer\|_startWalkAnimation" src/element.js` returns zero results.
diff --git a/prompts/avatar-chat/04-preload-walk-idle-clips.md b/prompts/avatar-chat/04-preload-walk-idle-clips.md
new file mode 100644
index 000000000..125a53aad
--- /dev/null
+++ b/prompts/avatar-chat/04-preload-walk-idle-clips.md
@@ -0,0 +1,28 @@
+# 04 — Preload walk and idle animation clips on boot
+
+## Status
+Gap — `AnimationManager.ensureLoaded()` fetches clips lazily on first play. If `walk` hasn't been fetched yet when the first `brain:stream` fires, `playClipByName('walk')` logs a warning and skips. Same risk for returning to `idle`.
+
+## Files
+`src/runtime/scene.js` — `SceneController`
+`src/element.js` — boot sequence around line 993
+
+## What to do
+
+In `SceneController` (or wherever the viewer's `animationManager.loadAll()` is called after model load), ensure `walk` and `idle` are among the first clips resolved. The `AnimationManager` already supports parallel loading via `loadAll()` — this is just about ensuring these two are loaded before the first user message is sent.
+
+**Option A (preferred):** After `animationManager.loadAll()` completes, explicitly call:
+```js
+await Promise.all([
+ animationManager.ensureLoaded('idle'),
+ animationManager.ensureLoaded('walk'),
+]);
+```
+Place this in `Viewer.load()` or in the post-load hook in `element.js` after `agent:ready` fires.
+
+**Option B (fallback):** In `_onStreamChunk()` in `element.js`, if `walk` isn't loaded yet, skip starting the animation rather than showing a console warning. Change `playClipByName` to check `viewer.animationManager.isLoaded('walk')` first.
+
+Use Option A — it's cleaner. Option B is a safety net only.
+
+## Verification
+Add `console.time('walk-ready')` before the preload and `console.timeEnd` after. Confirm it completes within 500ms of boot. Send a message immediately after page load — the avatar should walk on the first response.
diff --git a/prompts/avatar-chat/05-walk-during-tool-calls.md b/prompts/avatar-chat/05-walk-during-tool-calls.md
new file mode 100644
index 000000000..a744b94df
--- /dev/null
+++ b/prompts/avatar-chat/05-walk-during-tool-calls.md
@@ -0,0 +1,59 @@
+# 05 — Walk during tool call execution
+
+## Status
+Gap — between LLM turns when a tool is running, no streaming chunks arrive (the LLM is waiting for tool results). The avatar stands still. It should walk during tool execution to signal activity.
+
+## File
+`src/element.js` — `skill:tool-called` handler around line 1215
+
+## Current code
+```js
+if (ev === 'skill:tool-called') {
+ const { tool, result } = e.detail || {};
+ this._setToolIndicator(tool);
+ this._clearToolIndicator();
+ ...
+}
+```
+
+## What to add
+
+When a tool call starts (before the result is back), trigger a walk. When the tool finishes, the next LLM stream will continue walking naturally, or `_stopWalkAnimation()` will fire on `brain:thinking: false`.
+
+The `skill:tool-called` event currently fires AFTER the tool result is available (it carries both `tool` and `result`). To walk DURING execution, the runtime needs to emit a `skill:tool-start` event before awaiting the tool handler.
+
+### In `src/runtime/index.js` — `_loop()` tool dispatch loop
+
+Add a `skill:tool-start` event before `await this._dispatchTool(call)`:
+```js
+for (const call of response.toolCalls) {
+ this.dispatchEvent(new CustomEvent('skill:tool-start', {
+ detail: { tool: call.name, args: call.input }
+ }));
+ let output, isError = false;
+ try {
+ output = await this._dispatchTool(call);
+ } catch (err) { ... }
+ this.dispatchEvent(new CustomEvent('skill:tool-called', { ... }));
+ ...
+}
+```
+
+### In `src/element.js`
+
+Add `'skill:tool-start'` to the re-dispatch list.
+
+In the event handler:
+```js
+if (ev === 'skill:tool-start') {
+ this._onStreamChunk(); // start walking
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ // Show tool name in bubble (dots mode, not streaming mode)
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'false';
+ }
+}
+```
+
+## Verification
+Install a slow skill (or add a `setTimeout(2000)` inside a tool handler temporarily). Send a message that triggers it. Avatar should walk while the tool runs.
diff --git a/prompts/avatar-chat/06-walk-during-tts.md b/prompts/avatar-chat/06-walk-during-tts.md
new file mode 100644
index 000000000..a8e5ab8cb
--- /dev/null
+++ b/prompts/avatar-chat/06-walk-during-tts.md
@@ -0,0 +1,48 @@
+# 06 — Walk during TTS voice playback
+
+## Status
+Gap — when voice mode is on and the TTS speaks the reply aloud, the avatar stands still. It should walk while speaking.
+
+## Files
+`src/element.js` — `voice:speech-start` / `voice:speech-end` handlers
+
+## What to do
+
+The runtime already dispatches `voice:speech-start` and `voice:speech-end` events, and element.js already re-dispatches them to the host. Add walk behavior to those handlers.
+
+In the `for (const ev of [...])` listener block in element.js:
+
+```js
+if (ev === 'voice:speech-start') {
+ this._onStreamChunk(); // start walking
+}
+if (ev === 'voice:speech-end') {
+ this._stopWalkAnimation(); // return to idle
+}
+```
+
+This works because `_onStreamChunk()` already handles the debounce — if the avatar is already walking from a stream, the TTS start just resets the debounce timer keeping it walking.
+
+### Thought bubble during TTS
+
+Optionally, show the text being spoken in the thought bubble during TTS:
+
+```js
+if (ev === 'voice:speech-start') {
+ this._onStreamChunk();
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ const text = e.detail?.text || '';
+ this._streamToBubble(''); // activate bubble in streaming mode
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ this._thoughtBubbleEl.dataset.active = 'true';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = text.slice(0, 80);
+ }
+}
+if (ev === 'voice:speech-end') {
+ this._stopWalkAnimation();
+ this._clearThoughtBubble();
+}
+```
+
+## Verification
+Set `voice="browser"` on the element. Send a message. Avatar should walk while TTS speaks and return to idle when TTS ends.
diff --git a/prompts/avatar-chat/07-walk-on-user-send.md b/prompts/avatar-chat/07-walk-on-user-send.md
new file mode 100644
index 000000000..ccbd57dbc
--- /dev/null
+++ b/prompts/avatar-chat/07-walk-on-user-send.md
@@ -0,0 +1,48 @@
+# 07 — Brief walk when user sends a message
+
+## Status
+Enhancement — when the user hits Enter or clicks send, there's a visible pause before the first `brain:stream` chunk arrives. During this gap the avatar stands idle. A brief "acknowledgement" walk makes the system feel instantly responsive.
+
+## File
+`src/element.js` — input `keydown` handler and `say()` method
+
+## What to do
+
+In `_renderShell()`, the Enter key handler is:
+```js
+input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && input.value.trim()) {
+ const v = input.value.trim();
+ input.value = '';
+ this.say(v);
+ }
+});
+```
+
+Add a `_onStreamChunk()` call immediately when the user submits, before `say()` dispatches to the runtime. This starts the walk immediately on keypress. The stream will then keep it going, or the debounce will expire after 600ms if something goes wrong.
+
+```js
+input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && input.value.trim()) {
+ const v = input.value.trim();
+ input.value = '';
+ this._onStreamChunk(); // immediate visual feedback
+ this.say(v);
+ }
+});
+```
+
+Apply the same to the `say()` public method itself so programmatic calls also trigger it:
+
+```js
+async say(text, opts = {}) {
+ this._onStreamChunk(); // acknowledge immediately
+ if (!this._runtime) await this._waitForReady();
+ ...
+}
+```
+
+Guard with `avatar-chat !== 'off'` — `_onStreamChunk()` already does this internally.
+
+## Verification
+Type a message and press Enter. Avatar should start walking instantly, before the LLM responds.
diff --git a/prompts/avatar-chat/08-reduced-motion.md b/prompts/avatar-chat/08-reduced-motion.md
new file mode 100644
index 000000000..acd68150e
--- /dev/null
+++ b/prompts/avatar-chat/08-reduced-motion.md
@@ -0,0 +1,41 @@
+# 08 — Respect prefers-reduced-motion for walk animation and bubble
+
+## Status
+Accessibility gap — users with vestibular disorders or motion sensitivity who set `prefers-reduced-motion: reduce` in their OS should not see the avatar walking or the thought bubble bouncing.
+
+## Files
+`src/element.js` — `_onStreamChunk()`, `BASE_STYLE`
+
+## CSS changes
+
+Add to `BASE_STYLE`:
+```css
+@media (prefers-reduced-motion: reduce) {
+ .thought-bubble .dot { animation: none; opacity: 0.6; }
+ @keyframes thought-dot { to {} }
+}
+```
+
+This stills the bouncing dots while keeping the bubble visible.
+
+## JS changes
+
+In `_onStreamChunk()`, check the media query before starting the walk animation:
+
+```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 });
+ }
+ clearTimeout(this._walkStopDebounce);
+ this._walkStopDebounce = setTimeout(() => this._stopWalkAnimation(), 600);
+}
+```
+
+The thought bubble still appears (it's informational) but doesn't animate. The avatar stays in idle pose instead of walking.
+
+## Verification
+In Chrome DevTools → Rendering panel, check "Emulate CSS media feature prefers-reduced-motion: reduce". Send a message. Bubble should appear with static dots. Avatar should not walk.
diff --git a/prompts/avatar-chat/09-bubble-tool-call-label.md b/prompts/avatar-chat/09-bubble-tool-call-label.md
new file mode 100644
index 000000000..3144476db
--- /dev/null
+++ b/prompts/avatar-chat/09-bubble-tool-call-label.md
@@ -0,0 +1,37 @@
+# 09 — Show tool call name in thought bubble during tool execution
+
+## Status
+Enhancement — after prompt 05 adds `skill:tool-start`, the thought bubble shows dots during tool calls. It should show a human-readable label like "Searching pump.fun…" so the user knows what the avatar is doing.
+
+## File
+`src/element.js` — `skill:tool-start` handler (added in prompt 05)
+
+## What to do
+
+Reuse the existing `_toolIndicatorLabel(toolName)` map. When `skill:tool-start` fires, populate the bubble `.text` span with the label and switch to streaming mode (text visible, dots hidden):
+
+```js
+if (ev === 'skill:tool-start') {
+ this._onStreamChunk();
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ const label = this._toolIndicatorLabel(e.detail?.tool ?? '');
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = label;
+ }
+}
+```
+
+When `brain:thinking` fires with `thinking: true` (next LLM iteration begins), the bubble reverts to dots mode naturally because `_streamToBubble` will switch it back on the first chunk.
+
+Add a clear in `skill:tool-called` (after tool finishes) to reset the label so it doesn't persist:
+```js
+if (ev === 'skill:tool-called') {
+ // existing code...
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
+ if (this._thoughtBubbleEl) this._thoughtBubbleEl.dataset.streaming = 'false';
+}
+```
+
+## Verification
+Send a message that triggers a tool call (e.g. pump.fun search). The thought bubble should show "Searching pump.fun…" as text (not dots) while the tool runs, then switch back to streaming text when the next LLM turn starts.
diff --git a/prompts/avatar-chat/10-bubble-css-custom-properties.md b/prompts/avatar-chat/10-bubble-css-custom-properties.md
new file mode 100644
index 000000000..d8de71cac
--- /dev/null
+++ b/prompts/avatar-chat/10-bubble-css-custom-properties.md
@@ -0,0 +1,52 @@
+# 10 — Thought bubble CSS custom properties
+
+## Status
+Enhancement — the thought bubble's visual appearance (background, text color, border radius, shadow) is hardcoded. Embedders need to be able to brand it.
+
+## File
+`src/element.js` — `BASE_STYLE`, `:host` block and `.thought-bubble` block
+
+## What to add
+
+Add to the `:host` CSS custom property block:
+```css
+:host {
+ ...existing vars...
+ --agent-bubble-bg: rgba(255, 255, 255, 0.95);
+ --agent-bubble-color: #1a1a2e;
+ --agent-bubble-shadow: 0 4px 24px rgba(0, 0, 0, 0.25);
+ --agent-bubble-font-size: 13px;
+}
+```
+
+Update `.thought-bubble` to consume them:
+```css
+.thought-bubble {
+ background: var(--agent-bubble-bg);
+ color: var(--agent-bubble-color);
+ box-shadow: var(--agent-bubble-shadow);
+ font-size: var(--agent-bubble-font-size);
+ /* rest unchanged */
+}
+.thought-bubble::after {
+ border-top-color: var(--agent-bubble-bg);
+}
+```
+
+Update `.thought-bubble .text`:
+```css
+.thought-bubble .text {
+ color: var(--agent-bubble-color);
+}
+```
+
+## Embedder usage
+```html
+<agent-3d style="
+ --agent-bubble-bg: rgba(30, 30, 50, 0.95);
+ --agent-bubble-color: #ffffff;
+" ...></agent-3d>
+```
+
+## Verification
+Apply inline style overrides and confirm bubble color changes. The `::after` tail should match the bubble background.
diff --git a/prompts/avatar-chat/11-bubble-light-background.md b/prompts/avatar-chat/11-bubble-light-background.md
new file mode 100644
index 000000000..8e96fb4ca
--- /dev/null
+++ b/prompts/avatar-chat/11-bubble-light-background.md
@@ -0,0 +1,39 @@
+# 11 — Thought bubble adaptation for light background
+
+## Status
+Gap — when `background="light"` is set, the canvas is white and the thought bubble (white background, dark text) becomes nearly invisible.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## What to add
+
+Add a host selector override for light background:
+```css
+:host([background="light"]) {
+ --agent-bubble-bg: rgba(30, 30, 50, 0.92);
+ --agent-bubble-color: #f9fafb;
+}
+```
+
+This inverts the bubble to dark when the canvas is light, matching the existing pattern where `.name-plate` gets different colors for light background.
+
+If prompt 10 (CSS custom properties) is done first, this is two lines. If not, directly override `.thought-bubble` inside the host selector:
+```css
+:host([background="light"]) .thought-bubble {
+ background: rgba(30, 30, 50, 0.92);
+ color: #f9fafb;
+}
+:host([background="light"]) .thought-bubble::after {
+ border-top-color: rgba(30, 30, 50, 0.92);
+}
+:host([background="light"]) .thought-bubble .text {
+ color: #f9fafb;
+}
+:host([background="light"]) .thought-bubble .dot {
+ background: #f9fafb;
+}
+```
+
+## Verification
+Add `background="light"` to the element. Send a message. Bubble should be dark with light text.
diff --git a/prompts/avatar-chat/12-bubble-enter-exit-animation.md b/prompts/avatar-chat/12-bubble-enter-exit-animation.md
new file mode 100644
index 000000000..8e35642da
--- /dev/null
+++ b/prompts/avatar-chat/12-bubble-enter-exit-animation.md
@@ -0,0 +1,36 @@
+# 12 — Thought bubble enter/exit animation (scale + fade)
+
+## Status
+Enhancement — the bubble currently appears/disappears with only an opacity transition (`transition: opacity 0.25s`). A subtle scale-up on enter and scale-down on exit makes it feel alive and natural.
+
+## File
+`src/element.js` — `BASE_STYLE`, `.thought-bubble` rule
+
+## What to change
+
+Replace the current transition with a combined opacity + transform transition and add `transform-origin`:
+
+```css
+.thought-bubble {
+ ...existing styles...
+ opacity: 0;
+ transform: translateX(-50%) scale(0.85);
+ transform-origin: center bottom;
+ transition:
+ opacity 0.22s cubic-bezier(0.34, 1.56, 0.64, 1),
+ transform 0.22s cubic-bezier(0.34, 1.56, 0.64, 1);
+}
+
+.thought-bubble[data-active="true"] {
+ opacity: 1;
+ transform: translateX(-50%) scale(1);
+}
+```
+
+The `cubic-bezier(0.34, 1.56, 0.64, 1)` is a "spring" curve — it slightly overshoots then settles. `transform-origin: center bottom` makes it feel like the bubble inflates upward from the tail toward the avatar's head.
+
+## Note
+The existing `transform: translateX(-50%)` on `.thought-bubble` must be merged into the transition states — otherwise `translateX(-50%)` and `scale()` fight each other. Both states above include `translateX(-50%)`.
+
+## Verification
+Send a message. Watch the bubble appear — it should scale up with a light spring overshoot. When it disappears it should scale back down simultaneously with fading out.
diff --git a/prompts/avatar-chat/13-bubble-head-tracking.md b/prompts/avatar-chat/13-bubble-head-tracking.md
new file mode 100644
index 000000000..c6e357b0e
--- /dev/null
+++ b/prompts/avatar-chat/13-bubble-head-tracking.md
@@ -0,0 +1,83 @@
+# 13 — Thought bubble position tracks avatar's head in 3D space
+
+## Status
+Enhancement — the thought bubble is currently positioned at `top: 12%` of the avatar anchor, which is a fixed guess. When the avatar is framed differently (different camera angle, different model height), the bubble drifts away from the head.
+
+## Files
+`src/element.js` — `_renderShell()`, new `_updateBubblePosition()` method
+`src/runtime/scene.js` or `src/viewer.js` — expose head world position
+
+## Approach
+
+Use Three.js `Vector3.project()` to convert the head bone's world position to NDC, then to CSS coordinates on the canvas.
+
+### Step 1 — Expose head screen position from viewer
+
+In `src/viewer.js` (or `src/runtime/scene.js`), add a method:
+```js
+getHeadScreenPosition() {
+ // Find the head bone (same search used by agent-avatar.js)
+ let headBone = null;
+ this.content?.traverse((obj) => {
+ if (!headBone && obj.isBone && /^head$/i.test(obj.name)) headBone = obj;
+ });
+ if (!headBone || !this.camera || !this.renderer) return null;
+
+ const pos = new THREE.Vector3();
+ headBone.getWorldPosition(pos);
+ pos.project(this.camera);
+
+ const canvas = this.renderer.domElement;
+ const x = (pos.x * 0.5 + 0.5) * canvas.clientWidth;
+ const y = (-pos.y * 0.5 + 0.5) * canvas.clientHeight;
+ return { x, y }; // pixels from top-left of canvas
+}
+```
+
+### Step 2 — Update bubble position on every frame
+
+In `element.js`, add a method:
+```js
+_updateBubblePosition() {
+ if (!this._thoughtBubbleEl || !this._viewer) return;
+ const pos = this._viewer.getHeadScreenPosition?.();
+ if (!pos) return;
+ // Offset bubble ~60px above the head
+ const anchorRect = this._avatarAnchorEl?.getBoundingClientRect();
+ const stageRect = this._stageEl?.getBoundingClientRect();
+ if (!anchorRect || !stageRect) return;
+ const relY = pos.y - (anchorRect.top - stageRect.top) - 60;
+ const relX = pos.x;
+ this._thoughtBubbleEl.style.top = `${Math.max(8, relY)}px`;
+ this._thoughtBubbleEl.style.left = `${relX}px`;
+ this._thoughtBubbleEl.style.transform = 'translateX(-50%) scale(var(--bubble-scale, 1))';
+}
+```
+
+Store `this._avatarAnchorEl = avatarAnchor` in `_renderShell()`.
+
+Hook `_updateBubblePosition()` into the viewer's render loop via `_afterAnimateHooks` (same pattern as agent-avatar.js):
+```js
+// After viewer is created in _boot():
+this._viewer._afterAnimateHooks = this._viewer._afterAnimateHooks || [];
+this._viewer._afterAnimateHooks.push(() => this._updateBubblePosition());
+```
+
+### Step 3 — Remove fixed CSS top
+
+In `BASE_STYLE`, change `.thought-bubble`:
+```css
+.thought-bubble {
+ position: absolute;
+ /* Remove: top: 12%; */
+ top: 0; /* JS will override */
+ left: 50%; /* JS will override */
+ ...
+}
+```
+
+## Fallback
+If `getHeadScreenPosition()` returns null (model not loaded, no head bone), the bubble stays at `top: 0` with `left: 50%` — acceptable degraded state.
+
+## Verification
+Load a model. Trigger the thought bubble. It should appear just above the avatar's head. Orbit the camera — the bubble should follow the head as it moves on screen.
diff --git a/prompts/avatar-chat/14-bubble-raf-batching.md b/prompts/avatar-chat/14-bubble-raf-batching.md
new file mode 100644
index 000000000..2624f838c
--- /dev/null
+++ b/prompts/avatar-chat/14-bubble-raf-batching.md
@@ -0,0 +1,61 @@
+# 14 — Batch thought bubble DOM updates with requestAnimationFrame
+
+## Status
+Performance — `_streamToBubble(chunk)` writes to `textContent` on every token chunk. At high streaming rates (50+ tokens/sec) this causes layout thrashing. The user can't read that fast anyway — batching to 60fps is sufficient.
+
+## File
+`src/element.js` — `_streamToBubble()` and constructor
+
+## Current code
+```js
+_streamToBubble(chunk) {
+ if (!this._thoughtBubbleEl || !this._thoughtTextEl) return;
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ this._thoughtTextEl.textContent += chunk;
+ const t = this._thoughtTextEl.textContent;
+ if (t.length > 120) {
+ this._thoughtTextEl.textContent = '…' + t.slice(-110);
+ }
+}
+```
+
+## New approach
+
+Accumulate chunks in a string buffer and flush to DOM on the next animation frame:
+
+```js
+// In constructor:
+this._bubbleBuffer = '';
+this._bubbleRafPending = false;
+
+// Replace _streamToBubble:
+_streamToBubble(chunk) {
+ if (!this._thoughtBubbleEl || !this._thoughtTextEl) return;
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ 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;
+ });
+ }
+}
+
+// Update _clearThoughtBubble to also clear the buffer:
+_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 = '';
+}
+```
+
+## Verification
+Open Chrome Performance panel. Record while receiving a long LLM response. There should be at most 60 layout operations per second for the bubble — not one per token.
diff --git a/prompts/avatar-chat/15-chat-live-streaming-message.md b/prompts/avatar-chat/15-chat-live-streaming-message.md
new file mode 100644
index 000000000..8f2b4bb22
--- /dev/null
+++ b/prompts/avatar-chat/15-chat-live-streaming-message.md
@@ -0,0 +1,104 @@
+# 15 — Live streaming text in chat message body
+
+## Status
+Enhancement — currently the chat shows the complete assistant message only after streaming finishes. The thought bubble shows the in-progress text. For a production-quality experience, the chat should also stream text live into a message placeholder — like ChatGPT or Claude.ai — so the user can read ahead while the bubble runs.
+
+## File
+`src/element.js` — `brain:stream` handler, `brain:message` handler, `_renderMessage()`
+
+## What to do
+
+### On first chunk: create a placeholder message in chat
+
+In the `brain:stream` handler, before calling `_streamToBubble`, check if a streaming placeholder exists. If not, create one:
+
+```js
+if (ev === 'brain:stream') {
+ const chunk = e.detail?.chunk ?? '';
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ this._streamToBubble(chunk);
+ }
+ this._appendStreamChunkToChat(chunk);
+ this._onStreamChunk();
+}
+```
+
+Add the method:
+```js
+_appendStreamChunkToChat(chunk) {
+ if (!this._chatEl || !chunk) return;
+ if (!this._streamingMsgEl) {
+ // Create the streaming placeholder
+ this._chatEl.querySelector('.suggest-row')?.remove();
+ const msg = document.createElement('div');
+ msg.className = 'msg streaming';
+ msg.innerHTML = '<div class="role"></div><div class="body"></div>';
+ msg.querySelector('.role').textContent = 'assistant';
+ this._chatEl.appendChild(msg);
+ this._streamingMsgEl = msg.querySelector('.body');
+ }
+ this._streamingChatBuffer = (this._streamingChatBuffer || '') + chunk;
+ if (!this._streamingChatRafPending) {
+ this._streamingChatRafPending = true;
+ requestAnimationFrame(() => {
+ this._streamingChatRafPending = false;
+ if (this._streamingMsgEl) {
+ this._streamingMsgEl.textContent = this._streamingChatBuffer;
+ this._chatEl.scrollTop = this._chatEl.scrollHeight;
+ }
+ });
+ }
+}
+```
+
+### On brain:message (assistant, final): replace placeholder with real message
+
+In the `brain:message` handler, when the final assistant message arrives, remove the streaming placeholder before calling `_renderMessage`:
+
+```js
+if (ev === 'brain:message') {
+ ...
+ if (detail.role === 'assistant') {
+ // Remove the streaming placeholder — _renderMessage will add the final message
+ this._streamingMsgEl?.closest('.msg')?.remove();
+ this._streamingMsgEl = null;
+ this._streamingChatBuffer = '';
+ this._streamingChatRafPending = false;
+ this._clearThoughtBubble();
+ }
+ if (this._chatEl) this._renderMessage(detail);
+}
+```
+
+### CSS — streaming cursor
+
+Add to `BASE_STYLE`:
+```css
+.msg.streaming .body::after {
+ content: '▋';
+ opacity: 1;
+ animation: blink-cursor 0.7s step-end infinite;
+ margin-left: 2px;
+}
+@keyframes blink-cursor {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0; }
+}
+```
+
+### Constructor additions
+```js
+this._streamingMsgEl = null;
+this._streamingChatBuffer = '';
+this._streamingChatRafPending = false;
+```
+
+### Teardown additions
+```js
+this._streamingMsgEl = null;
+this._streamingChatBuffer = '';
+this._streamingChatRafPending = false;
+```
+
+## Verification
+Send a message. Text should appear live in the chat with a blinking cursor. When the full message arrives, the cursor disappears and the message is finalized.
diff --git a/prompts/avatar-chat/16-input-state-during-streaming.md b/prompts/avatar-chat/16-input-state-during-streaming.md
new file mode 100644
index 000000000..8c96c126a
--- /dev/null
+++ b/prompts/avatar-chat/16-input-state-during-streaming.md
@@ -0,0 +1,56 @@
+# 16 — Input state management during thinking and streaming
+
+## Status
+Gap — while the avatar is thinking/streaming, the text input remains fully active. The user can submit another message which throws a "Runtime busy" error. The input should visually indicate the busy state and block submission.
+
+## File
+`src/element.js` — `_renderShell()`, `brain:thinking` handler, CSS
+
+## CSS additions
+
+```css
+.input-row input:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+.input-row input[data-state="thinking"] {
+ opacity: 0.6;
+}
+.input-row[data-busy="true"] {
+ opacity: 0.75;
+}
+```
+
+## JS changes
+
+Add a `_setBusy(busy)` helper:
+```js
+_setBusy(busy) {
+ if (!this._inputEl) return;
+ this._inputEl.disabled = busy;
+ this._inputEl.dataset.state = busy ? 'thinking' : '';
+ const row = this._inputEl.closest('.input-row');
+ if (row) row.dataset.busy = busy ? 'true' : 'false';
+ if (!busy) this._inputEl.placeholder = 'Say something...';
+ else this._inputEl.placeholder = 'Thinking…';
+}
+```
+
+Call `_setBusy(true)` when `brain:thinking` fires with `thinking: true`.
+Call `_setBusy(false)` when `brain:thinking` fires with `thinking: false`.
+
+In the `brain:thinking` handler:
+```js
+if (ev === 'brain:thinking') {
+ const isThinking = !!e.detail?.thinking;
+ this._setBusy(isThinking);
+ // ... existing code ...
+}
+```
+
+Also call `_setBusy(false)` on error — in the `send()` promise rejection path if element.js catches it, or on `agent:error` event.
+
+Add `this._setBusy(false)` to `_teardown()` so the input is never left locked after a reboot.
+
+## Verification
+Send a message. Input should disable and show "Thinking…". After the response arrives, input should re-enable. Trying to submit while busy should be impossible (input is `disabled`).
diff --git a/prompts/avatar-chat/17-chat-auto-scroll-streaming.md b/prompts/avatar-chat/17-chat-auto-scroll-streaming.md
new file mode 100644
index 000000000..3e148aabf
--- /dev/null
+++ b/prompts/avatar-chat/17-chat-auto-scroll-streaming.md
@@ -0,0 +1,51 @@
+# 17 — Auto-scroll chat to bottom during live streaming
+
+## Status
+Gap — when prompt 15 (live streaming message) is implemented, the streaming text grows the `.msg.streaming` div but `scrollTop` is only updated inside an RAF. At high text volumes or when the user has manually scrolled up, the chat may not follow.
+
+## File
+`src/element.js` — `_appendStreamChunkToChat()`
+
+## What to do
+
+Implement "smart scroll" — only auto-scroll if the user hasn't manually scrolled up to read history.
+
+```js
+_appendStreamChunkToChat(chunk) {
+ if (!this._chatEl || !chunk) return;
+
+ // Track whether user has scrolled away from the bottom
+ if (!this._streamingMsgEl) {
+ this._chatEl.querySelector('.suggest-row')?.remove();
+ const msg = document.createElement('div');
+ msg.className = 'msg streaming';
+ msg.innerHTML = '<div class="role"></div><div class="body"></div>';
+ msg.querySelector('.role').textContent = 'assistant';
+ this._chatEl.appendChild(msg);
+ this._streamingMsgEl = msg.querySelector('.body');
+ this._chatAutoScroll = true; // reset on new message
+ }
+
+ // Detect manual scroll-up (more than 40px from bottom = user is reading history)
+ const el = this._chatEl;
+ this._chatAutoScroll = (el.scrollHeight - el.scrollTop - el.clientHeight) < 40;
+
+ this._streamingChatBuffer = (this._streamingChatBuffer || '') + chunk;
+ if (!this._streamingChatRafPending) {
+ this._streamingChatRafPending = true;
+ requestAnimationFrame(() => {
+ this._streamingChatRafPending = false;
+ if (!this._streamingMsgEl) return;
+ this._streamingMsgEl.textContent = this._streamingChatBuffer;
+ if (this._chatAutoScroll) {
+ this._chatEl.scrollTop = this._chatEl.scrollHeight;
+ }
+ });
+ }
+}
+```
+
+Also add `this._chatAutoScroll = true` to the constructor and teardown.
+
+## Verification
+Start a long response. Manually scroll up mid-stream — the chat should stop auto-scrolling. Scroll back to the bottom — it should resume following.
diff --git a/prompts/avatar-chat/18-layout-floating-mode.md b/prompts/avatar-chat/18-layout-floating-mode.md
new file mode 100644
index 000000000..90b90fd8e
--- /dev/null
+++ b/prompts/avatar-chat/18-layout-floating-mode.md
@@ -0,0 +1,44 @@
+# 18 — Floating mode layout compatibility
+
+## Status
+Gap — the new vertical column chrome layout (`inset: 0`, `flex-direction: column`) needs to work correctly in floating mode. Floating mode has `border-radius`, `overflow: hidden`, and fixed `width`/`height` — the avatar anchor must fill the center correctly.
+
+## File
+`src/element.js` — `BASE_STYLE`
+
+## What to verify and fix
+
+Floating mode spec: `position: fixed; width: 320px; height: 420px; border-radius: 16px; overflow: hidden`.
+
+The vertical chrome column should work as-is since it uses `inset: 0` to fill the host. But verify these specific issues:
+
+### Issue 1 — Border radius clip
+The chrome's children should not overflow the rounded corners. `overflow: hidden` on the host handles this, but the `padding: 12px` on `.chrome` must ensure the chat and input don't visually clip at corners.
+
+Verify: In floating mode, the chat bubbles and input pill should have comfortable padding from the rounded corners. If not, increase padding to `14px` in floating mode:
+```css
+:host([mode="floating"]) .chrome {
+ padding: 14px;
+}
+```
+
+### Issue 2 — Avatar anchor height in small floating window
+In a 420px tall floating window with 38% max chat + input (~44px) + 12px×2 padding = ~52px overhead, the avatar anchor gets roughly 420 - 44*0.38 - 44 - 24 ≈ 320px. This is fine for most models.
+
+If the floating window is custom-sized smaller than 300px tall, the anchor may collapse. Add:
+```css
+:host([mode="floating"]) .avatar-anchor {
+ min-height: 60px;
+}
+```
+
+### Issue 3 — Drag handle overlap
+The `.drag-handle` (top 24px, z-index 15) overlaps the top of the chrome. The chrome starts at `top: 0` (inset: 0). Add top padding in floating mode to clear the drag handle:
+```css
+:host([mode="floating"]) .chrome {
+ padding-top: 28px; /* clear the 24px drag handle */
+}
+```
+
+## Verification
+Open floating mode (`mode="floating"`). Chat messages, avatar anchor, and input should all be correctly positioned within the rounded floating card. The drag handle should not overlap the chat.
diff --git a/prompts/avatar-chat/19-layout-mobile-pill.md b/prompts/avatar-chat/19-layout-mobile-pill.md
new file mode 100644
index 000000000..7442c93e5
--- /dev/null
+++ b/prompts/avatar-chat/19-layout-mobile-pill.md
@@ -0,0 +1,37 @@
+# 19 — Mobile pill mode compatibility
+
+## Status
+Gap — on narrow viewports (< 500px), floating mode collapses to a 56×56px pill. When expanded, it becomes a bottom-sheet. The vertical chrome column must work in both collapsed and expanded states.
+
+## File
+`src/element.js` — `BASE_STYLE`, pill expand/collapse logic
+
+## What to verify
+
+### Pill state (56×56px)
+When `this._pillActive = true`, the element is tiny. The chrome (`inset: 0`) tries to render inside 56px × 56px. This is fine because `.chat:empty { display: none }` hides the chat, and the `.avatar-anchor` and `.input-row` will be hidden by the pill overflow.
+
+Verify: add `overflow: hidden` check — it should already be inherited from the floating `overflow: hidden`. If not:
+```css
+:host([data-pill="true"]) .chrome { display: none; }
+```
+
+Check whether the pill state uses `data-pill` or class. Look at `_collapsePill()` and `_expandPill()` in element.js for the actual attribute/class toggled.
+
+### Expanded bottom-sheet state
+When expanded from pill, the element stretches to the bottom sheet size. The chrome column must fill this correctly.
+
+The chat should show at the top of the sheet, avatar anchor in the middle, input at the bottom. This is the default behavior of the vertical column — should work without changes.
+
+### Swipe handle
+The `.pill-drag` element is at `top: 8px`. Add padding to match floating mode fix from prompt 18:
+```css
+:host([mode="floating"][data-expanded]) .chrome {
+ padding-top: 20px;
+}
+```
+
+(Check the exact attribute set on the host when the pill is expanded — it may be a class or data attribute.)
+
+## Verification
+On a mobile viewport (375px wide), open the floating agent. Collapse to pill — chrome should be hidden. Expand — chrome column should appear correctly with chat, avatar window, and input.
diff --git a/prompts/avatar-chat/20-camera-framing-inline.md b/prompts/avatar-chat/20-camera-framing-inline.md
new file mode 100644
index 000000000..90011743d
--- /dev/null
+++ b/prompts/avatar-chat/20-camera-framing-inline.md
@@ -0,0 +1,63 @@
+# 20 — Camera framing: center avatar in the anchor window
+
+## Status
+Gap — the Three.js camera is set to frame the full avatar body against the full canvas. With the new layout, the avatar anchor is roughly the center 40-60% of the canvas height. The camera should be adjusted so the avatar's upper body / head fills the anchor window, not the full canvas.
+
+## Files
+`src/viewer.js` — camera setup, `fitCameraToModel()`
+`src/element.js` — post-boot camera adjustment
+
+## Background
+
+The viewer places the camera using `fitCameraToModel()` which centers the bounding box of the loaded model and sets distance to fit it. With the chrome taking top and bottom space, the avatar is framed against the full canvas but visible only through the anchor in the middle.
+
+## Approach
+
+After the model loads and the `agent:ready` event fires in element.js, offset the camera vertically to push the avatar into the visible anchor window.
+
+### Option A — Camera target offset (preferred)
+
+In element.js, after boot completes, adjust the camera's target to be slightly above center (toward the head), effectively panning the view to center the avatar in the anchor:
+
+```js
+// After this._viewer is set up and model is loaded:
+const moveCamera = () => {
+ const v = this._viewer;
+ if (!v?.camera || !v?.controls) return;
+ // Shift camera target upward by ~15% of the scene height
+ // so the avatar's upper body fills the anchor window
+ const box = new THREE.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();
+};
+
+// Subscribe to load-end on the protocol bus to trigger after model loads
+protocol.on(ACTION_TYPES.LOAD_END, moveCamera);
+```
+
+Import THREE.Box3 from 'three' at the top of element.js (or use `this._viewer.scene` to access it).
+
+### Option B — CSS anchor positioning
+
+A simpler but less precise alternative: adjust the `top` percentage of `.avatar-anchor` and `min-height` so the window aligns better with where the avatar's upper body lands naturally.
+
+Try first with the CSS of `.avatar-anchor`:
+```css
+.avatar-anchor {
+ flex: 1;
+ position: relative;
+ pointer-events: none;
+ min-height: 100px;
+ /* Pull down slightly so avatar upper body is visible */
+ margin-top: 8px;
+}
+```
+
+And adjust the thought bubble `top` from `12%` to `8%`.
+
+Use Option A for production — Option B is a quick preview.
+
+## Verification
+Load a humanoid avatar. The avatar's head and shoulders should be visible and centered in the avatar anchor window (the space between chat and input). The feet may be cropped — that is acceptable and intentional.
diff --git a/prompts/avatar-chat/21-stream-abort-error-handling.md b/prompts/avatar-chat/21-stream-abort-error-handling.md
new file mode 100644
index 000000000..e18b21b6c
--- /dev/null
+++ b/prompts/avatar-chat/21-stream-abort-error-handling.md
@@ -0,0 +1,108 @@
+# 21 — Stream abort and error recovery
+
+## Status
+Gap — if the user navigates away, tears down the component, or a network error occurs mid-stream, the SSE reader in `AnthropicProvider.complete()` will hang or throw unhandled. The thought bubble and walk state may get stuck on.
+
+## Files
+`src/runtime/providers.js` — `AnthropicProvider.complete()`
+`src/runtime/index.js` — `_loop()`
+`src/element.js` — teardown
+
+## Changes needed
+
+### 1 — AbortController in provider
+
+`complete()` should accept an `AbortSignal` and cancel the fetch + reader:
+
+```js
+async complete({ system, messages, tools, onChunk, signal }) {
+ const url = ...;
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body), signal });
+ if (!res.ok) { ... }
+
+ const reader = res.body.getReader();
+ // If aborted, cancel the reader
+ signal?.addEventListener('abort', () => reader.cancel());
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (signal?.aborted) break;
+ // ... existing SSE parsing ...
+ }
+ } catch (err) {
+ if (err.name === 'AbortError') return out; // graceful exit
+ throw err;
+ }
+ return out;
+}
+```
+
+### 2 — AbortController in runtime
+
+In `Runtime`, store a controller per `send()` call:
+
+```js
+async send(userText, opts = {}) {
+ if (this._busy) throw new Error('Runtime busy');
+ this._busy = true;
+ this._abortController = new AbortController();
+ try {
+ ...
+ const reply = await this._loop(this._abortController.signal);
+ ...
+ } finally {
+ this._busy = false;
+ this._abortController = null;
+ }
+}
+
+async _loop(signal) {
+ ...
+ const response = await this.provider.complete({
+ ...,
+ signal,
+ onChunk: (chunk) => {
+ if (signal?.aborted) return;
+ this.dispatchEvent(new CustomEvent('brain:stream', { detail: { chunk } }));
+ },
+ });
+ ...
+}
+```
+
+Add a `cancel()` method to `Runtime`:
+```js
+cancel() {
+ this._abortController?.abort();
+}
+```
+
+### 3 — Call cancel on teardown in element.js
+
+In `_teardown()`, before destroying the runtime:
+```js
+this._runtime?.cancel();
+```
+
+### 4 — Recover UI state on error
+
+In element.js, if `say()` rejects (network error, abort), ensure the UI resets:
+```js
+async say(text, opts = {}) {
+ try {
+ this._onStreamChunk();
+ ...
+ return await this._runtime.send(text, ...);
+ } catch (err) {
+ this._stopWalkAnimation();
+ this._clearThoughtBubble();
+ this._setBusy(false);
+ throw err;
+ }
+}
+```
+
+## Verification
+Start a message. Close/reopen the agent component before the response arrives. No hanging readers, no stuck walk animation, no console errors.
diff --git a/prompts/avatar-chat/22-concurrent-request-guard.md b/prompts/avatar-chat/22-concurrent-request-guard.md
new file mode 100644
index 000000000..efca69e78
--- /dev/null
+++ b/prompts/avatar-chat/22-concurrent-request-guard.md
@@ -0,0 +1,57 @@
+# 22 — Concurrent request guard and queue
+
+## Status
+Gap — if the user sends a message while the input is not yet disabled (brief window before prompt 16 lands), or via the programmatic `say()` API, the runtime throws "Runtime busy". This error surfaces as an unhandled rejection with no user feedback.
+
+## File
+`src/element.js` — `say()` method
+
+## Current behavior
+```js
+async say(text, opts = {}) {
+ if (!this._runtime) await this._waitForReady();
+ return await this._runtime.send(text, { voice: ... });
+ // If runtime is busy, send() throws "Runtime busy"
+}
+```
+
+## What to do
+
+Queue the message instead of erroring. Only one message can be in-flight, but a pending message can wait:
+
+```js
+say(text, opts = {}) {
+ if (this._pendingSay) {
+ // Replace any previously queued message with the latest
+ this._pendingSay = { text, opts };
+ return;
+ }
+ this._pendingSay = { text, opts };
+ this._drainSayQueue();
+}
+
+async _drainSayQueue() {
+ while (this._pendingSay) {
+ const { text, opts } = this._pendingSay;
+ this._pendingSay = null;
+ try {
+ if (!this._runtime) await this._waitForReady();
+ this._onStreamChunk();
+ await this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
+ } catch (err) {
+ this._stopWalkAnimation();
+ this._clearThoughtBubble();
+ this._setBusy(false);
+ this.dispatchEvent(new CustomEvent('agent:error', {
+ detail: { phase: 'send', error: err },
+ bubbles: true, composed: true,
+ }));
+ }
+ }
+}
+```
+
+Also add `this._pendingSay = null` to the constructor and clear it in `_teardown()`.
+
+## Verification
+Rapidly type and submit three messages. The first should be processed, the third (latest) should be queued and sent next. The second should be silently dropped (replaced by the third). No unhandled rejections in the console.
diff --git a/prompts/avatar-chat/23-proxy-sse-passthrough.md b/prompts/avatar-chat/23-proxy-sse-passthrough.md
new file mode 100644
index 000000000..48ee9be28
--- /dev/null
+++ b/prompts/avatar-chat/23-proxy-sse-passthrough.md
@@ -0,0 +1,62 @@
+# 23 — Proxy server: pass SSE streaming headers to browser
+
+## Status
+Critical gap — the provider now sends `stream: true` to Anthropic. The proxy at `/api/llm/anthropic` must forward the SSE stream to the browser with correct headers. If it buffers the full response, streaming is silently broken (the response works but arrives all at once, no `brain:stream` events until completion).
+
+## File
+`api/llm/anthropic.js` (or wherever the proxy route lives — check the server directory)
+
+## What to verify
+
+Find the proxy handler. It likely does something like:
+```js
+const resp = await fetch('https://api.anthropic.com/v1/messages', { ... body });
+const data = await resp.json();
+return res.json(data);
+```
+
+This buffers everything — **must be replaced** with a streaming passthrough.
+
+## Fix
+
+```js
+export default async function handler(req, res) {
+ const body = await readRequestBody(req); // parse POST body
+ body.stream = true; // ensure streaming is on
+
+ const upstream = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': process.env.ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (!upstream.ok) {
+ const text = await upstream.text();
+ return res.status(upstream.status).send(text);
+ }
+
+ // Forward SSE headers
+ res.setHeader('content-type', 'text/event-stream');
+ res.setHeader('cache-control', 'no-cache');
+ res.setHeader('connection', 'keep-alive');
+ res.setHeader('transfer-encoding', 'chunked');
+
+ // Pipe the stream
+ const reader = upstream.body.getReader();
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ res.write(value);
+ }
+ res.end();
+}
+```
+
+Adapt to whatever server framework is used (Express, Vercel edge, Hono, etc.). The key is: **no buffering**, **pipe the raw SSE chunks directly**.
+
+## Verification
+Open DevTools → Network. Send a message. Find the `/api/llm/anthropic` request. In the Response tab, you should see `text/event-stream` content type and multiple `data:` lines arriving incrementally. If you see a single response payload arriving all at once, the proxy is still buffering.
diff --git a/prompts/avatar-chat/24-kiosk-mode-disable.md b/prompts/avatar-chat/24-kiosk-mode-disable.md
new file mode 100644
index 000000000..8c458d900
--- /dev/null
+++ b/prompts/avatar-chat/24-kiosk-mode-disable.md
@@ -0,0 +1,34 @@
+# 24 — Kiosk mode: fully disable avatar-chat features
+
+## Status
+Gap — kiosk mode hides all chat UI chrome but the avatar-chat JS logic (walk animation, thought bubble) still runs. The thought bubble element doesn't exist in kiosk mode (created inside `if (!this.hasAttribute('kiosk'))`), so `_thoughtBubbleEl` is null, which is fine. But `_onStreamChunk()` still triggers walk animations.
+
+This is mostly harmless but kiosk mode should be a clean "no chat interaction" mode.
+
+## File
+`src/element.js`
+
+## What to do
+
+In `_onStreamChunk()`, also check for kiosk mode:
+```js
+_onStreamChunk() {
+ if (!this._scene) return;
+ if (this.getAttribute('avatar-chat') === 'off') return;
+ if (this.hasAttribute('kiosk')) return;
+ ...
+}
+```
+
+Same check in `_stopWalkAnimation()` is not needed (stopping is always safe).
+
+Also ensure `_setBusy()` (from prompt 16) is a no-op in kiosk mode:
+```js
+_setBusy(busy) {
+ if (!this._inputEl) return; // null in kiosk mode — already safe
+ ...
+}
+```
+
+## Verification
+Add `kiosk` attribute. Send a message via `element.say('hi')`. Avatar should NOT walk (kiosk is a display mode, not an interaction mode).
diff --git a/prompts/avatar-chat/25-action-types-stream.md b/prompts/avatar-chat/25-action-types-stream.md
new file mode 100644
index 000000000..6dabfab4f
--- /dev/null
+++ b/prompts/avatar-chat/25-action-types-stream.md
@@ -0,0 +1,42 @@
+# 25 — Add STREAM action type to protocol bus
+
+## Status
+Gap — `brain:stream` is dispatched by the runtime and re-dispatched by element.js but `ACTION_TYPES` in `agent-protocol.js` doesn't include it. This means skill authors and external protocol listeners can't reference it by a named constant, and the src/CLAUDE.md vocabulary table is incomplete.
+
+## Files
+`src/agent-protocol.js`
+`src/CLAUDE.md`
+
+## Changes to agent-protocol.js
+
+Add to `ACTION_TYPES`:
+```js
+export const ACTION_TYPES = {
+ // ...existing...
+ STREAM: 'brain:stream', // LLM token chunk arriving during streaming response
+ TOOL_START: 'skill:tool-start', // tool execution beginning (before result)
+};
+```
+
+Note: `brain:stream` uses the `brain:` prefix (it's a runtime event, not a protocol bus action) — keep the constant name `STREAM` with value `'brain:stream'` to be consistent with how `THINK` maps to `'think'` in protocol context. However, check if these are actually fired on the protocol bus vs the Runtime EventTarget — if `brain:stream` only flows through the Runtime and host element, it does NOT belong in ACTION_TYPES (which is for the protocol bus). Audit this and only add it to ACTION_TYPES if it's actually emitted on `protocol.emit()`.
+
+If `brain:stream` is only on the Runtime EventTarget (not the protocol bus), add a note to ACTION_TYPES:
+```js
+// NOTE: 'brain:stream' is a Runtime EventTarget event, not a protocol bus action.
+// Listen on the host element: element.addEventListener('brain:stream', handler).
+// Skill:tool-start is also Runtime-only.
+```
+
+## Changes to src/CLAUDE.md
+
+In the "The protocol bus — event vocabulary" table, add a row:
+
+| `brain:stream` | `{ chunk: string }` | runtime `_loop()` via Runtime EventTarget | element.js (re-dispatched to host as composed event) |
+
+Also add `skill:tool-start`:
+
+| `skill:tool-start` | `{ tool: string, args: object }` | runtime `_loop()` | element.js (walk animation, bubble label) |
+
+## Verification
+`grep -n "STREAM\|TOOL_START" src/agent-protocol.js` returns the new constants.
+The src/CLAUDE.md table includes both new event types.
diff --git a/prompts/avatar-chat/26-embed-spec-docs.md b/prompts/avatar-chat/26-embed-spec-docs.md
new file mode 100644
index 000000000..1ba8f52bb
--- /dev/null
+++ b/prompts/avatar-chat/26-embed-spec-docs.md
@@ -0,0 +1,42 @@
+# 26 — Document avatar-chat attribute in EMBED_SPEC.md
+
+## Status
+Gap — `avatar-chat="off"` is a new public attribute of `<agent-3d>` and must be documented in `specs/EMBED_SPEC.md` alongside the other boolean/string attributes.
+
+## File
+`specs/EMBED_SPEC.md`
+
+## What to find
+
+Locate the attribute table — it should have rows for `responsive`, `kiosk`, `name-plate`, `background`, etc. Find the section (around the `responsive` row based on the current file) and add:
+
+| Attribute | Type | Default | Description |
+|---|---|---|---|
+| `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. |
+
+Also add a brief prose section explaining the feature:
+
+```markdown
+## 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
+```
+```
+
+## Verification
+The EMBED_SPEC.md attribute table includes the `avatar-chat` row. The prose section explains the feature and the `"off"` toggle.
diff --git a/prompts/avatar-chat/27-js-api-toggle.md b/prompts/avatar-chat/27-js-api-toggle.md
new file mode 100644
index 000000000..59390bc7d
--- /dev/null
+++ b/prompts/avatar-chat/27-js-api-toggle.md
@@ -0,0 +1,41 @@
+# 27 — JS API methods: enableAvatarChat() / disableAvatarChat()
+
+## Status
+Enhancement — while `setAttribute('avatar-chat', 'off')` works, it's not discoverable. Public methods make the API ergonomic for JS consumers.
+
+## File
+`src/element.js` — public API section (near `wave()`, `lookAt()`, `playClip()`)
+
+## What to add
+
+```js
+/**
+ * Enable the inline avatar-in-chat mode (thought bubble + walk animation).
+ * This is the default state — call this to re-enable after disabling.
+ */
+enableAvatarChat() {
+ this.removeAttribute('avatar-chat');
+}
+
+/**
+ * Disable the inline avatar-in-chat mode.
+ * Restores the original bottom-bar chat layout.
+ * Avatar walk animation and thought bubble will not fire while disabled.
+ */
+disableAvatarChat() {
+ this.setAttribute('avatar-chat', 'off');
+ this._stopWalkAnimation();
+ this._clearThoughtBubble();
+}
+```
+
+Place these after `playClip()` (line ~1679 in the current file).
+
+## Verification
+```js
+const el = document.querySelector('agent-3d');
+el.disableAvatarChat();
+// Layout reverts to bottom-bar. Walk and bubble stop.
+el.enableAvatarChat();
+// Layout returns to vertical column.
+```
diff --git a/prompts/avatar-chat/28-notifier-walk-integration.md b/prompts/avatar-chat/28-notifier-walk-integration.md
new file mode 100644
index 000000000..d6e927cda
--- /dev/null
+++ b/prompts/avatar-chat/28-notifier-walk-integration.md
@@ -0,0 +1,43 @@
+# 28 — AgentNotifier integration: walk when notification plays
+
+## Status
+Gap — `AgentNotifier` (src/agent-notifier.js) handles `notify` protocol events by having the avatar enter frame, deliver a message, then retreat. The avatar currently uses its own animation logic for this. The walk animation should coordinate with notify events so the avatar walks during notification delivery.
+
+## Files
+`src/agent-notifier.js` — understand its animation pattern
+`src/element.js` — wire walk to notify events
+
+## What to investigate first
+
+Read `src/agent-notifier.js`. Find where it triggers avatar movement or animation. The notifier likely calls `protocol.emit({ type: ACTION_TYPES.SPEAK, ... })` and possibly `ACTION_TYPES.GESTURE`. Determine if it fires any event that element.js can listen to for walk timing.
+
+## What to implement
+
+If AgentNotifier fires `notify` events that element.js already listens for (check the re-dispatch list), add walk behavior:
+
+In the `for (const ev of [...])` listener block, if `'notify'` is not already there, add it. Then:
+```js
+if (ev === 'notify') {
+ const duration = e.detail?.duration ?? 3000;
+ if (this.getAttribute('avatar-chat') !== 'off' && !this.hasAttribute('kiosk')) {
+ this._onStreamChunk(); // start walking
+ // Stop after notification duration
+ setTimeout(() => this._stopWalkAnimation(), duration + 500);
+ }
+}
+```
+
+Or subscribe directly to the `protocol` bus for `ACTION_TYPES.NOTIFY`:
+```js
+protocol.on(ACTION_TYPES.NOTIFY, ({ payload }) => {
+ if (this.getAttribute('avatar-chat') === 'off') return;
+ const duration = payload?.duration ?? 3000;
+ this._onStreamChunk();
+ setTimeout(() => this._stopWalkAnimation(), duration + 500);
+});
+```
+
+Ensure the protocol listener is cleaned up in `_teardown()` by storing the unsubscribe function.
+
+## Verification
+Trigger a notification (via `element.notify('Hello!')` if that's the API, or via protocol.emit). The avatar should walk for the duration of the notification then return to idle.
diff --git a/prompts/avatar-chat/29-animation-preload-strategy.md b/prompts/avatar-chat/29-animation-preload-strategy.md
new file mode 100644
index 000000000..6618f5990
--- /dev/null
+++ b/prompts/avatar-chat/29-animation-preload-strategy.md
@@ -0,0 +1,55 @@
+# 29 — Animation preload strategy: walk + idle ready before first message
+
+## Status
+Gap (detail of prompt 04) — walk and idle clips must be loaded before the first user interaction. This requires hooking into the model load lifecycle correctly, not just calling ensureLoaded() at any point.
+
+## Files
+`src/viewer.js` — `load()` method, model-loaded callback
+`src/element.js` — `_boot()` sequence
+
+## Background
+
+The Viewer's `load()` method loads the GLB and fires `load-end` on the protocol bus. After that, `animationManager.loadAll()` is called (find where in viewer.js — it may be in the post-load hook). Walk and idle must be in memory before the first `brain:stream` event can fire.
+
+## What to implement
+
+### In viewer.js (or wherever animationManager.loadAll is called)
+
+After `animationManager.loadAll()` completes:
+```js
+// Explicitly ensure the two avatar-chat clips are hot in memory
+await Promise.allSettled([
+ this.animationManager.ensureLoaded('idle'),
+ this.animationManager.ensureLoaded('walk'),
+]);
+```
+
+`allSettled` (not `all`) so a missing walk clip doesn't block the rest of boot.
+
+### In element.js (belt-and-suspenders)
+
+After the viewer emits `load-end`, run:
+```js
+protocol.on(ACTION_TYPES.LOAD_END, async () => {
+ const am = this._viewer?.animationManager;
+ if (!am) return;
+ await Promise.allSettled([
+ am.ensureLoaded('idle'),
+ am.ensureLoaded('walk'),
+ ]);
+});
+```
+
+### Walk clip is 106kB — acceptable first-load cost
+
+The walk.json clip is 106kB (from the build output). This is fine. It will be served with normal HTTP caching. Subsequent page loads will be cache hits.
+
+### Verify idle defaults to playing
+
+After the model loads, the avatar should be in the `idle` animation. Check whether `animationManager.play('idle')` is called on load. If not, add it after the preload:
+```js
+am.play('idle');
+```
+
+## Verification
+Load the page. In the browser's Network panel, confirm `walk.json` and `idle.json` are requested during page load (not on first message send). Send a message — the avatar should walk immediately with no delay.
diff --git a/prompts/avatar-chat/30-aria-live-regions.md b/prompts/avatar-chat/30-aria-live-regions.md
new file mode 100644
index 000000000..8d110a77a
--- /dev/null
+++ b/prompts/avatar-chat/30-aria-live-regions.md
@@ -0,0 +1,58 @@
+# 30 — Accessible aria-live regions for thought bubble and streaming chat
+
+## Status
+Accessibility gap — screen reader users get no feedback while the avatar is "thinking" or streaming. The thought bubble is aria-hidden effectively (no live region). Chat messages appear silently.
+
+## File
+`src/element.js` — `_renderShell()`
+
+## What to do
+
+### Thought bubble
+
+The thought bubble element already has `aria-live="polite"` (added in the initial implementation). Verify this is present. If the DOM change is `textContent` of `.thought-bubble .text`, aria-live should announce it.
+
+However, a better pattern for a loading indicator is `role="status"` with `aria-live="polite"` and `aria-label`:
+```js
+thoughtBubble.setAttribute('role', 'status');
+thoughtBubble.setAttribute('aria-live', 'polite');
+thoughtBubble.setAttribute('aria-label', 'Agent is thinking');
+```
+
+When streaming starts, update the label:
+```js
+// In _streamToBubble:
+this._thoughtBubbleEl.setAttribute('aria-label', 'Agent is responding');
+```
+
+When cleared:
+```js
+// In _clearThoughtBubble:
+this._thoughtBubbleEl.setAttribute('aria-label', '');
+```
+
+### Chat messages
+
+The chat div should be a live region so new messages are announced:
+```js
+chat.setAttribute('aria-live', 'polite');
+chat.setAttribute('aria-label', 'Conversation');
+chat.setAttribute('role', 'log');
+```
+
+`role="log"` implies `aria-live="polite"` and is semantically correct for chat. New `.msg` divs appended to it will be read aloud by screen readers.
+
+### Input accessibility
+
+The input should have a clear label:
+```js
+input.setAttribute('aria-label', 'Message to agent');
+```
+
+The mic button already has `title="Push to talk"` but needs `aria-label`:
+```js
+micBtn.setAttribute('aria-label', 'Push to talk');
+```
+
+## Verification
+Enable VoiceOver (Mac) or NVDA (Windows). Send a message. VoiceOver should announce "Agent is responding" when the bubble appears, and read out new chat messages as they arrive.
diff --git a/prompts/avatar-chat/31-keyboard-nav.md b/prompts/avatar-chat/31-keyboard-nav.md
new file mode 100644
index 000000000..99a171c64
--- /dev/null
+++ b/prompts/avatar-chat/31-keyboard-nav.md
@@ -0,0 +1,72 @@
+# 31 — Keyboard navigation and focus management
+
+## Status
+Accessibility gap — with the new chrome layout (vertical column filling the entire element), focus order and tab stops may be broken. The avatar anchor is `pointer-events: none` which is correct, but the overall tab order should be: chat messages → input → mic button.
+
+## File
+`src/element.js` — `_renderShell()`, CSS
+
+## What to audit
+
+### Tab order
+The shadow DOM's tab order follows DOM order. Current DOM order:
+1. `.stage` (canvas — no focusable children unless Three.js adds any)
+2. `.poster`
+3. `.loading`
+4. `.drag-handle`
+5. `.name-plate`
+6. `.pill-btn`
+7. `.pill-drag`
+8. `.chrome`
+ - `.chat` (not focusable but scrollable — should it be?)
+ - `.avatar-anchor` (pointer-events: none, not focusable — correct)
+ - `.input-row`
+ - `input` (focusable)
+ - `button.mic` (focusable)
+9. `.tool-indicator`
+10. `.alert-banner`
+
+This order is correct. The canvas is not in the tab sequence.
+
+### Fix: Make chat scrollable via keyboard
+
+The `.chat` div is scrollable (`overflow-y: auto`) but not keyboard-focusable. Users who want to scroll through history can't without a mouse. Add:
+```js
+chat.setAttribute('tabindex', '0');
+```
+
+This lets keyboard users Tab to the chat area and use arrow keys / Page Up/Down to scroll.
+
+### Fix: Alert banner dismiss button
+
+The alert banner's close button must be keyboard accessible. Verify it already has `aria-label="Dismiss"` and is a real `<button>` (not a div). It should be — check and confirm.
+
+### Fix: Focus management on message send
+
+After the user submits a message (Enter key), focus should remain on the input. Confirm `input.focus()` is called after clearing the value:
+```js
+input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && input.value.trim()) {
+ const v = input.value.trim();
+ input.value = '';
+ this._onStreamChunk();
+ this.say(v);
+ input.focus(); // keep focus
+ }
+});
+```
+
+### Fix: Disabled input focus (prompt 16 interaction)
+
+When `input.disabled = true` (during streaming), Tab will skip it. When re-enabled, focus won't automatically return. After `_setBusy(false)`:
+```js
+_setBusy(busy) {
+ ...
+ if (!busy && document.activeElement === document.body) {
+ this._inputEl?.focus();
+ }
+}
+```
+
+## Verification
+Tab through the page. Focus should reach the chat (scrollable), then the input, then the mic button. No tab stops land on the avatar or canvas.
diff --git a/prompts/avatar-chat/32-walk-animation-alternatives.md b/prompts/avatar-chat/32-walk-animation-alternatives.md
new file mode 100644
index 000000000..d3d741c64
--- /dev/null
+++ b/prompts/avatar-chat/32-walk-animation-alternatives.md
@@ -0,0 +1,41 @@
+# 32 — Walk animation review: is strafe-left the right clip?
+
+## Status
+Design question — the current walk clip is "Walk Strafe Left.fbx" which is a lateral strafe movement (sliding sideways). On screen, with the avatar facing the camera, this makes the avatar appear to shimmy sideways. For the "walking in place while talking" effect, a forward walk or in-place bob may look more natural.
+
+## What to evaluate
+
+### Current clip
+- Source: `Walk Strafe Left.fbx` → `walk.json`
+- Motion: lateral strafe (avatar moves sideways relative to their facing direction)
+- On-screen look: since the avatar faces the camera, strafe = horizontal body sway
+
+### Alternative clips to consider building
+
+From the available FBX files in `/workspaces/3D-Agent/public/animations/`:
+- Check if there's a forward walk FBX (there currently isn't in the directory listing)
+- `Stepping Backward.fbx` — walking backward, might look like awkward retreat
+- `Cover To Stand.fbx` — a tactical crouch-to-stand, probably not right
+
+### Recommendation
+
+The strafe walk actually works well for "in-place walking while talking" because:
+1. The avatar doesn't move forward into or away from the camera
+2. The upper body sway and leg movement read as "active" and "thinking"
+3. It's self-contained — the avatar doesn't drift in space
+
+**However**, test it visually with the actual avatar model in the inline layout before finalizing. If the strafe creates an odd visual (avatar appears to shuffle awkwardly), consider two alternatives:
+
+**Alternative A — Use the idle animation with empathy layer**
+The idle animation already has breathing and weight-shift. Instead of walking, just let the empathy layer's `patience` weight increase (which adds hip sway and subtle bobbing). This is "free" — no animation change needed.
+
+**Alternative B — Download a proper in-place walk**
+Add a Mixamo "Walking In Place" animation (different from strafe walk). If Mixamo has it, download the FBX, add to `animations.config.json` as `name: "walk_inplace"`, and rebuild with `npm run build:animations`.
+
+## Action required
+
+1. Load the app, send a message, observe the avatar walking.
+2. If strafe walk looks fine → no action needed, mark resolved.
+3. If it looks awkward → implement Alternative A (simplest) or Alternative B.
+
+Document the decision here and close this prompt.
diff --git a/prompts/avatar-chat/33-bubble-tail-dynamic-direction.md b/prompts/avatar-chat/33-bubble-tail-dynamic-direction.md
new file mode 100644
index 000000000..f185779e8
--- /dev/null
+++ b/prompts/avatar-chat/33-bubble-tail-dynamic-direction.md
@@ -0,0 +1,48 @@
+# 33 — Thought bubble tail direction: point toward avatar head
+
+## Status
+Enhancement — the thought bubble `::after` pseudo-element creates a downward-pointing triangle (`border-top` = solid). This assumes the bubble is always above the avatar's head, which is the default. But if the avatar is very tall or the camera is angled, the bubble may appear below or beside the head and the tail points wrong.
+
+## File
+`src/element.js` — `BASE_STYLE`, `_updateBubblePosition()` (from prompt 13)
+
+## What to do
+
+If prompt 13 (head tracking) is implemented: once we know the bubble's position relative to the head, determine whether the bubble is above or below the head, and dynamically set a data attribute:
+
+```js
+// In _updateBubblePosition():
+const bubbleBottom = relY + this._thoughtBubbleEl.offsetHeight;
+const isAbove = relY < pos.y; // bubble top is above head
+this._thoughtBubbleEl.dataset.tailDir = isAbove ? 'down' : 'up';
+```
+
+CSS:
+```css
+/* Default (bubble above head): tail points down */
+.thought-bubble::after {
+ 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, rgba(255,255,255,0.95));
+ border-bottom: none;
+}
+
+/* Bubble below head: tail points up */
+.thought-bubble[data-tail-dir="up"]::after {
+ bottom: auto;
+ top: -8px;
+ border-top: none;
+ border-bottom: 8px solid var(--agent-bubble-bg, rgba(255,255,255,0.95));
+}
+```
+
+If prompt 13 is NOT implemented (fixed position): keep the default downward tail as-is. The fixed `top: 12%` positioning means the bubble is almost always above the head for typical humanoid models in the anchor window.
+
+## Verification
+With head tracking active, test with a model where the avatar's head is near the bottom of the anchor window. The tail should point up when the bubble appears below the head.
diff --git a/public/chat/index.html b/public/chat/index.html
index a7e56e686..eb0697ddc 100644
--- a/public/chat/index.html
+++ b/public/chat/index.html
@@ -43,7 +43,7 @@
}
}
</script>
- <script type="module" crossorigin src="/chat/assets/index-BoQasYoQ.js"></script>
+ <script type="module" crossorigin src="/chat/assets/index-BTEzDLIq.js"></script>
<link rel="stylesheet" crossorigin href="/chat/assets/index-CgrzNPtI.css">
</head>
<body>
diff --git a/public/first-meet/first-meet.js b/public/first-meet/first-meet.js
index ec05e9992..9a2d18c76 100644
--- a/public/first-meet/first-meet.js
+++ b/public/first-meet/first-meet.js
@@ -73,12 +73,10 @@ function renderPreview() {
return;
}
- const viewer = document.createElement('model-viewer');
- viewer.src = state.avatar.model_url;
- viewer.alt = state.avatar.name || 'Avatar';
- viewer.setAttribute('auto-rotate', '');
- viewer.setAttribute('camera-controls', '');
- viewer.setAttribute('enable-shadow', '');
+ const viewer = document.createElement('agent-3d');
+ viewer.setAttribute('body', state.avatar.model_url);
+ viewer.setAttribute('eager', '');
+ viewer.style.cssText = 'width:100%;height:100%;display:block';
container.innerHTML = '';
container.appendChild(viewer);
@@ -210,13 +208,11 @@ async function renderGreeting() {
}
}, 500);
} else {
- // Fallback: model-viewer + text
- const viewer = document.createElement('model-viewer');
- viewer.src = state.avatar.model_url;
- viewer.alt = state.avatar.name || 'Avatar';
- viewer.setAttribute('auto-rotate', '');
- viewer.setAttribute('camera-controls', '');
- viewer.setAttribute('enable-shadow', '');
+ // Fallback: agent-3d (no voice/agent-id) + browser TTS
+ const viewer = document.createElement('agent-3d');
+ viewer.setAttribute('body', state.avatar.model_url);
+ viewer.setAttribute('eager', '');
+ viewer.style.cssText = 'width:100%;height:100%;display:block';
container.innerHTML = '';
container.appendChild(viewer);
diff --git a/public/first-meet/index.html b/public/first-meet/index.html
index bb1053fdb..9a7aad577 100644
--- a/public/first-meet/index.html
+++ b/public/first-meet/index.html
@@ -313,7 +313,6 @@
</div>
<script src="/dist-lib/agent-3d.js" type="module"></script>
- <script src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
<script type="module" src="./first-meet.js"></script>
</body>
</html>
diff --git a/rider/src/components/beat-generator.js b/rider/src/components/beat-generator.js
index a61e499df..112b5c696 100644
--- a/rider/src/components/beat-generator.js
+++ b/rider/src/components/beat-generator.js
@@ -422,9 +422,9 @@ AFRAME.registerComponent('beat-generator', {
this.index.notes = 0;
this.index.obstacles = 0;
- for (let i = 0; i < this.beatContainer.children.length; i++) {
- const child = this.beatContainer.children[i];
- child.object3D.position.set(0, 0, -9999);
+ const beatChildren = Array.from(this.beatContainer.children);
+ for (let i = 0; i < beatChildren.length; i++) {
+ const child = beatChildren[i];
if (child.components.beat) { child.components.beat.returnToPool(); }
}
diff --git a/rider/src/components/beat.js b/rider/src/components/beat.js
index 781ec189d..d04ffce5c 100644
--- a/rider/src/components/beat.js
+++ b/rider/src/components/beat.js
@@ -286,6 +286,7 @@ AFRAME.registerComponent('beat', {
this.brokenPoolName = undefined;
this.destroyed = false;
this.hitEventDetail = {};
+ this.inUse = false;
this.poolName = undefined;
this.returnToPoolTimer = DESTROY_TIME;
this.rotationAxis = new THREE.Vector3();
@@ -367,6 +368,7 @@ AFRAME.registerComponent('beat', {
const el = this.el;
this.beatSystem.registerBeat(this);
+ this.inUse = true;
// Model is 0.29 size. We make it 1.0 so we can easily scale based on 1m size.
const FACTOR = 1 / 0.29;
@@ -490,6 +492,8 @@ AFRAME.registerComponent('beat', {
* Check if need to return to pool.
*/
returnToPool: function () {
+ if (!this.inUse) { return; }
+ this.inUse = false;
this.beatSystem.unregisterBeat(this);
this.el.object3D.position.set(0, 0, -9999);
this.el.object3D.visible = false;
diff --git a/rider/src/templates/news.html b/rider/src/templates/news.html
index 84fc5f031..be38d9702 100644
--- a/rider/src/templates/news.html
+++ b/rider/src/templates/news.html
@@ -39,7 +39,7 @@
<a-entity
id="supportImage"
geometry="primitive: plane; width: 0.6; height: 0.5"
- material="shader: flat; src: /assets/img/banner.jpg"
+ material="shader: flat; src: assets/img/banner.jpg"
position="-0.5 0 0.001"></a-entity>
<a-entity
diff --git a/src/element.js b/src/element.js
index 6690be18b..ebb7b2f3a 100644
--- a/src/element.js
+++ b/src/element.js
@@ -65,6 +65,10 @@ const BASE_STYLE = `
--agent-chat-font: system-ui, -apple-system, sans-serif;
--agent-mic-glow: #22c55e;
--agent-shadow: 0 20px 60px rgba(0,0,0,0.3);
+ --agent-bubble-bg: rgba(255, 255, 255, 0.95);
+ --agent-bubble-color: #1a1a2e;
+ --agent-bubble-shadow: 0 4px 24px rgba(0, 0, 0, 0.25);
+ --agent-bubble-font-size: 13px;
contain: layout style;
}
:host([mode="floating"]) {
@@ -163,22 +167,25 @@ const BASE_STYLE = `
/* Thought bubble — appears above avatar's head while thinking */
.thought-bubble {
position: absolute;
- top: 12%;
+ top: 0;
left: 50%;
- transform: translateX(-50%);
- background: rgba(255, 255, 255, 0.95);
- color: #1a1a2e;
+ background: var(--agent-bubble-bg);
+ color: var(--agent-bubble-color);
border-radius: 20px;
padding: 8px 14px;
- font: 600 13px/1 var(--agent-chat-font);
+ font: 600 var(--agent-bubble-font-size)/1 var(--agent-chat-font);
max-width: min(280px, 60%);
white-space: normal;
min-width: 80px;
min-height: 28px;
pointer-events: none;
opacity: 0;
- transition: opacity 0.25s ease;
- box-shadow: 0 4px 24px rgba(0, 0, 0, 0.25);
+ transform: translateX(-50%) scale(0.85);
+ transform-origin: center bottom;
+ transition:
+ opacity 0.22s cubic-bezier(0.34, 1.56, 0.64, 1),
+ transform 0.22s cubic-bezier(0.34, 1.56, 0.64, 1);
+ box-shadow: var(--agent-bubble-shadow);
display: flex;
align-items: center;
gap: 5px;
@@ -192,12 +199,12 @@ const BASE_STYLE = `
transform: translateX(-50%);
border-left: 8px solid transparent;
border-right: 8px solid transparent;
- border-top: 8px solid rgba(255, 255, 255, 0.95);
+ border-top: 8px solid var(--agent-bubble-bg);
}
- .thought-bubble[data-active="true"] { opacity: 1; }
+ .thought-bubble[data-active="true"] { opacity: 1; transform: translateX(-50%) scale(1); }
.thought-bubble .text {
- font: 13px/1.4 var(--agent-chat-font);
- color: #1a1a2e;
+ font: var(--agent-bubble-font-size)/1.4 var(--agent-chat-font);
+ color: var(--agent-bubble-color);
display: none;
}
.thought-bubble[data-streaming="true"] .text { display: block; }
@@ -216,12 +223,18 @@ const BASE_STYLE = `
0%, 60%, 100% { transform: translateY(0); opacity: 0.35; }
30% { transform: translateY(-4px); opacity: 1; }
}
+ @media (prefers-reduced-motion: reduce) {
+ .thought-bubble .dot { animation: none; opacity: 0.6; }
+ @keyframes thought-dot { to {} }
+ }
.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); }
.msg.curiosity { border-left-color: rgba(59,130,246,0.7); background: rgba(59,130,246,0.05); }
.msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
.msg .body { white-space: pre-wrap; }
+ .msg.streaming .body::after { content: '▋'; opacity: 1; animation: blink-cursor 0.7s step-end infinite; margin-left: 2px; }
+ @keyframes blink-cursor { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
/* Suggestion chips when the conversation is empty */
.suggest-row { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 0 0; }
.suggest-chip { font: 600 11px/1 var(--agent-chat-font); color: var(--agent-on-surface); background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.1); padding: 6px 10px; border-radius: 999px; cursor: pointer; transition: all .12s; }
@@ -270,6 +283,16 @@ const BASE_STYLE = `
font: 14px var(--agent-chat-font);
outline: none;
}
+ .input-row input:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ .input-row input[data-state="thinking"] {
+ opacity: 0.6;
+ }
+ .input-row[data-busy="true"] {
+ opacity: 0.75;
+ }
button.icon {
width: 36px;
height: 36px;
@@ -339,12 +362,29 @@ const BASE_STYLE = `
color: rgba(0, 0, 0, 0.55);
text-shadow: none;
}
+ :host([background="light"]) .thought-bubble {
+ background: rgba(30, 30, 50, 0.92);
+ color: #f9fafb;
+ }
+ :host([background="light"]) .thought-bubble::after {
+ border-top-color: rgba(30, 30, 50, 0.92);
+ }
+ :host([background="light"]) .thought-bubble .text {
+ color: #f9fafb;
+ }
+ :host([background="light"]) .thought-bubble .dot {
+ background: #f9fafb;
+ }
/* Transparent floating: remove box chrome so avatar composites over the page */
:host([mode="floating"][background="transparent"]) {
box-shadow: none;
border-radius: 0;
overflow: visible;
}
+ /* Pill expanded (bottom-sheet): offset chrome below swipe handle */
+ :host([aria-expanded="true"]) .chrome {
+ padding-top: 20px;
+ }
/* Drag handle — visible in floating mode, used to reposition the widget */
.drag-handle {
display: none;
@@ -387,6 +427,14 @@ const BASE_STYLE = `
:host([avatar-chat="off"]) .chat { flex: 1; max-height: 40%; }
:host([avatar-chat="off"]) .input-row { flex: 1; }
:host([avatar-chat="off"]) .avatar-anchor { display: none; }
+ /* Floating mode layout fixes */
+ :host([mode="floating"]) .chrome {
+ padding: 14px;
+ padding-top: 28px; /* clear the 24px drag handle */
+ }
+ :host([mode="floating"]) .avatar-anchor {
+ min-height: 60px;
+ }
`;
class Agent3DElement extends HTMLElement {
@@ -435,9 +483,15 @@ class Agent3DElement extends HTMLElement {
this._voiceClient = null;
this._notifier = null;
this._thoughtBubbleEl = null;
- this._walkReturnTimer = null;
+ this._bubbleBuffer = '';
+ this._bubbleRafPending = false;
this._isWalking = false;
this._walkStopDebounce = null;
+ this._streamingMsgEl = null;
+ this._streamingChatBuffer = '';
+ this._streamingChatRafPending = false;
+ this._chatAutoScroll = true;
+ this._pendingSay = null;
}
connectedCallback() {
@@ -578,6 +632,7 @@ class Agent3DElement extends HTMLElement {
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);
}
});
@@ -608,6 +663,7 @@ class Agent3DElement extends HTMLElement {
this._chatEl = chat;
this._inputEl = input;
this._micEl = micBtn;
+ this._avatarAnchorEl = avatarAnchor;
this._thoughtBubbleEl = thoughtBubble;
this._thoughtTextEl = thoughtBubble.querySelector('.text');
@@ -1078,6 +1134,8 @@ class Agent3DElement extends HTMLElement {
);
const viewer = new Viewer(this._stageEl, { kiosk: this.hasAttribute('kiosk') });
this._viewer = viewer;
+ viewer._afterAnimateHooks = viewer._afterAnimateHooks || [];
+ viewer._afterAnimateHooks.push(() => this._updateBubblePosition());
// Apply the embed surface attributes (`background`, `name-plate`) now
// that the viewer exists. They are also re-applied on attribute change.
this._applyBackground();
@@ -1159,6 +1217,7 @@ class Agent3DElement extends HTMLElement {
'brain:thinking',
'brain:stream',
'brain:message',
+ 'skill:tool-start',
'skill:tool-called',
'voice:speech-start',
'voice:speech-end',
@@ -1188,14 +1247,25 @@ class Agent3DElement extends HTMLElement {
payload: { text: detail.content, sentiment: detail.sentiment ?? 0 },
});
}
+ if (detail.role === 'assistant') {
+ this._streamingMsgEl?.closest('.msg')?.remove();
+ this._streamingMsgEl = null;
+ this._streamingChatBuffer = '';
+ this._streamingChatRafPending = false;
+ this._clearThoughtBubble();
+ }
if (this._chatEl) this._renderMessage(detail);
}
if (ev === 'brain:stream') {
if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
this._streamToBubble(e.detail?.chunk ?? '');
}
+ this._appendStreamChunkToChat(e.detail?.chunk ?? '');
+ this._onStreamChunk();
}
if (ev === 'brain:thinking') {
+ const isThinking = !!e.detail?.thinking;
+ this._setBusy(isThinking);
if (this._toolIndicatorEl) {
if (e.detail?.thinking) this._setToolIndicator('thinking');
else this._clearToolIndicator();
@@ -1211,10 +1281,35 @@ class Agent3DElement extends HTMLElement {
}
}
}
+ if (ev === 'skill:tool-start') {
+ this._onStreamChunk();
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ const label = this._toolIndicatorLabel(e.detail?.tool ?? '');
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = label;
+ }
+ }
+ if (ev === 'voice:speech-start') {
+ this._onStreamChunk();
+ if (this._thoughtBubbleEl && this.getAttribute('avatar-chat') !== 'off') {
+ const text = e.detail?.text || '';
+ this._streamToBubble('');
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ this._thoughtBubbleEl.dataset.active = 'true';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = text.slice(0, 80);
+ }
+ }
+ if (ev === 'voice:speech-end') {
+ this._stopWalkAnimation();
+ this._clearThoughtBubble();
+ }
if (ev === 'skill:tool-called') {
const { tool, result } = e.detail || {};
this._setToolIndicator(tool);
this._clearToolIndicator();
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
+ if (this._thoughtBubbleEl) this._thoughtBubbleEl.dataset.streaming = 'false';
if (typeof result?.sentiment === 'number') {
this._lastToolSentiment = result.sentiment;
}
@@ -1412,9 +1507,86 @@ class Agent3DElement extends HTMLElement {
}, 350);
}
+ _updateBubblePosition() {
+ if (!this._thoughtBubbleEl || !this._viewer) return;
+ const pos = this._viewer.getHeadScreenPosition?.();
+ if (!pos) return;
+ const anchorRect = this._avatarAnchorEl?.getBoundingClientRect();
+ 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`;
+ this._thoughtBubbleEl.style.left = `${pos.x}px`;
+ this._thoughtBubbleEl.style.transform = 'translateX(-50%) scale(var(--bubble-scale, 1))';
+ }
+
+ _appendStreamChunkToChat(chunk) {
+ if (!this._chatEl || !chunk) return;
+ if (!this._streamingMsgEl) {
+ this._chatEl.querySelector('.suggest-row')?.remove();
+ const msg = document.createElement('div');
+ msg.className = 'msg streaming';
+ msg.innerHTML = '<div class="role"></div><div class="body"></div>';
+ msg.querySelector('.role').textContent = 'assistant';
+ this._chatEl.appendChild(msg);
+ this._streamingMsgEl = msg.querySelector('.body');
+ this._chatAutoScroll = true;
+ }
+ const el = this._chatEl;
+ this._chatAutoScroll = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
+ this._streamingChatBuffer = (this._streamingChatBuffer || '') + chunk;
+ if (!this._streamingChatRafPending) {
+ this._streamingChatRafPending = true;
+ requestAnimationFrame(() => {
+ this._streamingChatRafPending = false;
+ if (this._streamingMsgEl) {
+ this._streamingMsgEl.textContent = this._streamingChatBuffer;
+ if (this._chatAutoScroll) {
+ this._chatEl.scrollTop = this._chatEl.scrollHeight;
+ }
+ }
+ });
+ }
+ }
+
+ _streamToBubble(chunk) {
+ if (!this._thoughtBubbleEl || !this._thoughtTextEl) return;
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ 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;
+ });
+ }
+ }
+
+ _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 = '';
+ }
+
+ _setBusy(busy) {
+ if (!this._inputEl) return;
+ this._inputEl.disabled = busy;
+ this._inputEl.dataset.state = busy ? 'thinking' : '';
+ const row = this._inputEl.closest('.input-row');
+ if (row) row.dataset.busy = busy ? 'true' : 'false';
+ this._inputEl.placeholder = busy ? 'Thinking…' : 'Say something...';
+ }
+
_onStreamChunk() {
if (!this._scene || this.getAttribute('avatar-chat') === 'off') return;
- if (!this._isWalking) {
+ 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 });
}
@@ -1640,7 +1812,7 @@ class Agent3DElement extends HTMLElement {
this._micEl.dataset.listening = 'true';
try {
const text = await this._runtime.listen();
- if (text) await this.say(text, { voice: true });
+ if (text) this.say(text, { voice: true });
} catch (e) {
console.warn('[agent-3d] listen failed', e);
} finally {
@@ -1719,12 +1891,17 @@ class Agent3DElement extends HTMLElement {
}
this._notifier?.detach();
this._notifier = null;
- clearTimeout(this._walkReturnTimer);
- this._walkReturnTimer = null;
+ this._setBusy(false);
clearTimeout(this._walkStopDebounce);
this._walkStopDebounce = null;
this._isWalking = false;
+ this._streamingMsgEl = null;
+ this._streamingChatBuffer = '';
+ this._streamingChatRafPending = false;
+ this._chatAutoScroll = true;
+ this._pendingSay = null;
try {
+ this._runtime?.cancel();
this._runtime?.destroy();
} catch {}
try {
@@ -1737,17 +1914,37 @@ class Agent3DElement extends HTMLElement {
// --- Public JS API ---
- async say(text, opts = {}) {
- if (!this._runtime) await this._waitForReady();
- 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 } });
- try {
- return await this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
- } catch (err) {
- protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'concern', weight: 0.8 } });
- throw err;
+ say(text, opts = {}) {
+ if (this._pendingSay) {
+ this._pendingSay = { text, opts };
+ return;
+ }
+ this._pendingSay = { text, opts };
+ this._drainSayQueue();
+ }
+
+ async _drainSayQueue() {
+ while (this._pendingSay) {
+ const { text, opts } = this._pendingSay;
+ this._pendingSay = null;
+ try {
+ 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 } });
+ 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,
+ }));
+ }
}
}
@@ -1762,8 +1959,22 @@ class Agent3DElement extends HTMLElement {
}
async ask(text, opts = {}) {
- const reply = await this.say(text, opts);
- return reply?.text || '';
+ 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 } });
+ try {
+ 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 } });
+ throw err;
+ }
}
clearConversation() {
diff --git a/src/runtime/index.js b/src/runtime/index.js
index 77d0ce943..12cbe111f 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -62,11 +62,16 @@ export class Runtime extends EventTarget {
return [...builtins, ...stageTools, ...skillTools];
}
+ cancel() {
+ this._abortController?.abort();
+ }
+
async send(userText, { voice = false } = {}) {
if (this._busy) {
throw new Error('Runtime busy — wait for current turn to finish');
}
this._busy = true;
+ this._abortController = new AbortController();
try {
this.memory?.note('user_said', { text: userText });
this.messages.push({ role: 'user', content: userText });
@@ -76,7 +81,7 @@ export class Runtime extends EventTarget {
}),
);
- const reply = await this._loop();
+ const reply = await this._loop(this._abortController.signal);
if (voice && reply.text && this.tts) {
this.dispatchEvent(
@@ -89,10 +94,11 @@ export class Runtime extends EventTarget {
return reply;
} finally {
this._busy = false;
+ this._abortController = null;
}
}
- async _loop() {
+ async _loop(signal) {
let iter = 0;
let finalText = '';
@@ -102,17 +108,15 @@ export class Runtime extends EventTarget {
system: this.systemPrompt,
messages: this.messages,
tools: this.tools,
+ signal,
onChunk: (chunk) => {
+ if (signal?.aborted) return;
this.dispatchEvent(new CustomEvent('brain:stream', { detail: { chunk } }));
},
});
- this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { thinking: false } }));
-
- if (response.thinking) {
- this.dispatchEvent(
- new CustomEvent('brain:thinking', { detail: { content: response.thinking } }),
- );
- }
+ this.dispatchEvent(new CustomEvent('brain:thinking', {
+ detail: { thinking: false, content: response.thinking || '' },
+ }));
if (!response.toolCalls.length) {
finalText = response.text;
@@ -140,6 +144,9 @@ 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 },
+ }));
let output,
isError = false;
try {
diff --git a/src/runtime/providers.js b/src/runtime/providers.js
index b916b07c3..b1924250c 100644
--- a/src/runtime/providers.js
+++ b/src/runtime/providers.js
@@ -28,7 +28,7 @@ export class AnthropicProvider {
}
}
- async complete({ system, messages, tools, onChunk }) {
+ async complete({ system, messages, tools, onChunk, signal }) {
const body = {
model: this.model,
max_tokens: this.maxTokens,
@@ -50,7 +50,7 @@ export class AnthropicProvider {
headers['anthropic-dangerous-direct-browser-access'] = 'true';
}
- const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body) });
+ 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}`);
@@ -62,43 +62,51 @@ export class AnthropicProvider {
const decoder = new TextDecoder();
let buf = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buf += decoder.decode(value, { stream: true });
- const lines = buf.split('\n');
- buf = lines.pop();
- for (const line of lines) {
- if (!line.startsWith('data: ')) continue;
- const payload = line.slice(6).trim();
- if (payload === '[DONE]') break;
- let evt;
- 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') {
- const block = evt.content_block;
- if (block?.type === 'tool_use') {
- currentToolCall = { id: block.id, name: block.name, input: '' };
- }
- } else if (evt.type === 'content_block_delta') {
- const delta = evt.delta;
- if (delta?.type === 'text_delta') {
- out.text += delta.text;
- onChunk?.(delta.text);
- } else if (delta?.type === 'thinking_delta') {
- out.thinking += delta.thinking;
- } else if (delta?.type === 'input_json_delta' && currentToolCall) {
- currentToolCall.input += delta.partial_json;
- }
- } else if (evt.type === 'content_block_stop') {
- if (currentToolCall) {
- try { currentToolCall.input = JSON.parse(currentToolCall.input); } catch { currentToolCall.input = {}; }
- out.toolCalls.push(currentToolCall);
- currentToolCall = null;
+ signal?.addEventListener('abort', () => reader.cancel());
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (signal?.aborted) break;
+ buf += decoder.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop();
+ for (const line of lines) {
+ if (!line.startsWith('data: ')) continue;
+ const payload = line.slice(6).trim();
+ if (payload === '[DONE]') break;
+ let evt;
+ 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') {
+ const block = evt.content_block;
+ if (block?.type === 'tool_use') {
+ currentToolCall = { id: block.id, name: block.name, input: '' };
+ }
+ } else if (evt.type === 'content_block_delta') {
+ const delta = evt.delta;
+ if (delta?.type === 'text_delta') {
+ out.text += delta.text;
+ onChunk?.(delta.text);
+ } else if (delta?.type === 'thinking_delta') {
+ out.thinking += delta.thinking;
+ } else if (delta?.type === 'input_json_delta' && currentToolCall) {
+ currentToolCall.input += delta.partial_json;
+ }
+ } else if (evt.type === 'content_block_stop') {
+ if (currentToolCall) {
+ try { currentToolCall.input = JSON.parse(currentToolCall.input); } catch { currentToolCall.input = {}; }
+ out.toolCalls.push(currentToolCall);
+ currentToolCall = null;
+ }
}
}
}
+ } catch (err) {
+ if (err.name === 'AbortError') return out;
+ throw err;
}
return out;
diff --git a/src/viewer.js b/src/viewer.js
index 9fabf8794..ea66ac26b 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -432,6 +432,27 @@ export class Viewer {
return el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);
}
+ getHeadScreenPosition() {
+ if (!this.content || !this.activeCamera || !this.renderer) return null;
+ let headBone = null, neckBone = null;
+ this.content.traverse((obj) => {
+ if (!obj.isBone) return;
+ const canon = obj.name.replace(/^mixamorig/i, '').replace(/^.*[:_]/, '').toLowerCase();
+ if (!headBone && canon === 'head') headBone = obj;
+ else if (!neckBone && canon === 'neck') neckBone = obj;
+ });
+ const bone = headBone || neckBone;
+ if (!bone) return null;
+ const pos = new Vector3();
+ bone.getWorldPosition(pos);
+ pos.project(this.activeCamera);
+ const canvas = this.renderer.domElement;
+ return {
+ x: (pos.x * 0.5 + 0.5) * canvas.clientWidth,
+ y: (-pos.y * 0.5 + 0.5) * canvas.clientHeight,
+ };
+ }
+
render() {
this.renderer.render(this.scene, this.activeCamera);
if (this.state.grid) {