Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(economy-lab,converter): land the lab and converter follow-ups with this batch's entries
nirholas5afbf6a5b740
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 48751cadc..cc18e6936 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Every Crypto Converter result now has its own link you can share**: The converter promised a shareable result and never had one: the address bar stayed on /converter no matter what you picked, so there was no way to hand someone a rate. Now the page reads and writes its own URL. Pick BTC to EUR and type an amount and the address becomes /converter?from=bitcoin&to=EUR&amount=3, a new Copy link button puts that on your clipboard, and opening the link restores both sides and the amount exactly. Alongside that: the asset picker is fully keyboard-driven (arrow keys move the highlight, Enter picks, Escape closes and returns focus to the button you came from), the amount field says what it wants when you type something it cannot use instead of showing a silent dash, a coin whose price failed to load says price unavailable rather than a bare dash, the four quick presets light up when they match what you are looking at and stay disabled until live rates arrive, and the whole widget fits a 320px phone screen, where the currency buttons used to be pushed off the right edge and the picker off the left. (`/converter`) `[feature, improvement, fix]`- **My Collection loads visibly, keeps its counts, and never mangles an agent's name**: The collection page had a loading state nobody could see: the shimmer placeholders were drawn inside a container the page kept hidden until the data had already arrived, so a slow connection got a blank stretch of nothing instead. The tabs, the placeholders and the counts now appear from the first frame. The counts next to Skills and Subscriptions used to vanish at random, because the page's own translation pass could overwrite the tab label a split second after the number was written into it; the count now lives in its own slot and survives. A skill published by an agent whose name contains a quotation mark or an angle bracket rendered as broken markup rather than as the name, and a publisher who earned a vanity wallet address had it shown as an ordinary one, because the card was reading a field the collection endpoint does not return. Both are fixed, so tipping a creator from your collection now shows the wallet they actually have. Empty states are centred under the tabs instead of squeezed into the first column, both of them now point you at the marketplace, the Retry button on a failed load is a real button rather than a raw grey box, and the whole page is keyboard-navigable: arrow keys move between tabs, Home and End jump to the ends, and every link and button shows a clear focus ring. (`/collection`) `[fix, improvement]`- **Pausing a skill bundle is no longer permanent, and every tooltip fits on a phone**: The bundle builder at /bundles was audited end to end in a real browser: signing in, picking priced skills, the price panel and its backtest, publishing, the published list, and the loading, empty and error states, at phone, tablet and desktop widths. The worst finding was that Deactivate was a one-way door. It hid the bundle from buyers, which is correct, but it also removed it from the only page that could put it back, so a misclick permanently retired a bundle you had just priced. The button is now called Pause, a paused bundle stays on the page dimmed and clearly marked, and a Reactivate button puts it back on sale. Buyers still never see a paused bundle: the public list is unchanged, and paused ones are returned only to a signed-in owner of that agent. The small question-mark tooltips that explain every number on the page were also cut off at the edge of a phone screen, so four of the seven explanations were partly unreadable at 320 pixels wide; they now shift to stay on screen at any width. The sum of the parts and the suggested price were cramped into a broken-looking two-line squeeze on a narrow screen and now stack cleanly. Finally, a pricing error raised by one agent no longer sits on screen after you switch to another agent, where it read as a verdict on an agent it had never looked at. (`/bundles`) `[fix, improvement]`+- **Talking Avatar Video stops handing the renderer a 3D file where a photo belongs, and says up front when the GPU lane is down**: The /create/video page turns one of your avatars plus an audio clip into a lip-synced video, and it was driven end to end in a real browser: every state, every button, every width. The worst finding was invisible from the page. The reference frame the GPU worker renders from was being taken from whatever the browser had handy, which for an avatar with no thumbnail meant its 3D model file. The worker saved that as the reference photo and then failed on it minutes later, after the wait had already been spent. The page now sends only the avatar, and the server resolves a real image for it: the stored thumbnail, or a fresh portrait render when there is none. Second, the GPU renderer is a separate service, and when it is not running the only signal was a failure after you had already picked a file and uploaded it. The page now asks first and, if the lane is down, says so at the top, keeps Generate switched off, and points at the Avatar Studio and prompt-to-avatar in the meantime. The rest is the ordinary polish an audit turns up: a failed avatar list used to look identical to owning no avatars, so it sent people off to create one they already had, and now it says what broke and offers a retry; having no avatars yet gets a real empty state with a link to make one; the Generate button always explains what it is still waiting for and, once audio is in, how many clips of video that audio is worth; the clip you picked can be played back with its length and size before you spend a generation on it; a render job that goes unreachable now says so after thirty seconds instead of spinning for twenty minutes; and after a spent free trial the button under the error no longer stayed stuck on Upgrade plan for every later error. Avatar thumbnails are real buttons with visible focus rings, the two form fields have proper labels, and the second animated avatar that the site companion used to drop onto this page no longer loads over the one you are working on. (`/create/video`) `[fix, improvement]`- **The avatar SDK bundle we ship is now built from the code we deploy**: The <agent-3d> runtime that sites load from three.ws is a single bundled file, and the production build never rebuilt it. It was copied from whatever the build machine happened to have on disk, which could be days older than the code being deployed, so a fix to the avatar element could ship everywhere else on the site and quietly not reach the SDK. The deploy now rebuilds that bundle from the same commit as the rest of the release, every time. Nothing to change on your side: existing embeds keep working and simply pick up the current runtime. (`/avatar-sdk`) `[fix, sdk, infra]`- **The Character Library counts its own characters, and fills the screen while it does**: The library page had been advertising 106 rigged characters since launch. There are 107 on the shelf today, and there will be more tomorrow, so the number is no longer typed into the headline, the page description or the share card: the page asks the library how many it has and prints the answer under the hero. The grid also stopped wasting a third of a desktop screen. A layout rule left the page shrink-to-fitting to about two thirds of the window, so a wide monitor showed three columns where five fit; it now uses the full width it was designed for. Every character card previously carried a hidden second tab stop that announced the same name as the card itself, which made keyboard browsing twice as long as it needed to be, and thumbnails could not be dragged out of alignment by an accidental swipe anymore because the preview no longer pretends to be an interactive 3D control. The search box has a visible focus ring again instead of a one pixel border shift, and when the library cannot be reached the page now says what actually went wrong rather than reverting to a generic sentence a moment later. (`/character-library`) `[fix, improvement]`- **The Characters gallery pages past the first screen, and stops fighting dark mode**: The character gallery at /characters was audited end to end in a real browser: loading the feed, both sort orders, search, Load more, following a card through to its character page, and the loading, empty and error states, at phone, tablet and desktop widths. The worst finding was that the Top sort was quietly broken. Sorting by most-chatted read the right first screen, but pressing Load more asked the server to continue from the wrong place, so the feed ended after eight characters out of more than two thousand. It now pages all the way through, in order. The page also ignored the site theme: it painted a fixed light-blue background under the dark header no matter what you had chosen, which is now fixed in both directions, and wallet addresses on the cards were nearly invisible on a light background everywhere they appear on the site. The gallery filled only a narrow strip down the middle of a desktop screen and now uses the full width, up to four cards across. If the feed failed to load you got one line of grey text and no way to retry; there is now a proper message with a Try again button, a failed Load more keeps the characters you already had, and searching for something with no matches offers to clear the search rather than leaving you at a dead end. Pressing Top while the first screen was still loading used to light up the button and change nothing, so you were left reading New results under a Top heading. The search box had no label for screen readers, the sort buttons never showed which was selected, and neither they nor Load more showed a focus outline for anyone navigating by keyboard. Keyboard users can also now skip the header and land in the gallery. Finally, the feed itself is several times faster to answer on a cold request, because it no longer counts every conversation of every published character just to show you twenty-four of them. (`/characters`) `[fix, improvement]`diff --git a/api/_providers/nvidia-cosmos.js b/api/_providers/nvidia-cosmos.jsindex 4468f7240..b47c3a68b 100644--- a/api/_providers/nvidia-cosmos.js+++ b/api/_providers/nvidia-cosmos.js@@ -383,7 +383,7 @@ export function createNvidiaCosmosProvider() {const candidates = invokeCandidates();let retiredErr = null;let parsed = null;- for (const url of candidates) {+ for (const [i, url] of candidates.entries()) {try {parsed = await postInvoke(body, url);break;@@ -391,7 +391,12 @@ export function createNvidiaCosmosProvider() {// Only a retired route is worth stepping past; a key, quota, or// gateway failure means the next rung would fail the same way.if (err?.code !== 'lane_unavailable') throw err;- console.warn('[nvidia-cosmos] route retired, trying the next rung: %s', url);+ const more = i < candidates.length - 1;+ console.warn(+ '[nvidia-cosmos] route retired for this account (%s): %s',+ more ? 'trying the next rung' : 'no rungs left',+ url,+ );retiredErr = err;}}diff --git a/data/changelog.json b/data/changelog.jsonindex b76720559..aec17a4aa 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-17",+ "title": "Trial Conversions: the Buy button lands on the right skill, and Edit pricing stops going nowhere",+ "summary": "Six fixes to the Trial Conversions page, which shows both sides of a free trial running out: the trials you hold and the trials running on skills you sell. A seller's Edit pricing button pointed at a page that no longer exists and answered 404 on every row; it now opens that agent's monetization panel, where the price and the trial grant are actually set. A buyer's Buy it and Open agent buttons dropped you at the top of an agent selling a dozen skills, leaving you to hunt for the one your trial just ran out on; they now open the agent's pricing list scrolled to that exact skill, with the row briefly marked so you can see which one you came for. Those links also took a redirect that quietly discarded everything after the question mark, so they now use the direct address. A trial whose skill has since been delisted used to claim \"1 of 1 free runs left\", inventing a grant size nobody ever reported, and said \"free runs\" even when there was one run; the count now says only what is known, and matches word for word what a screen reader is told. A row missing a timestamp printed the bare word \"started\" with nothing after it, and the seller list said \"1 trials running\"; both now read as sentences. If you hold more trials than one page can carry, the page says how many it is leaving out instead of showing a total that stops at the cap. Sellers who price in more than one currency now see the currencies the headline number cannot hold, rather than only the largest pile.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/conversions"+ },{"date": "2026-08-17","title": "Coin Intelligence fits a phone screen, and a search no longer snaps back to the previous results",@@ -24324,6 +24334,16 @@"improvement"],"link": "/coin3d"+ },+ {+ "date": "2026-08-17",+ "title": "Talking Avatar Video stops handing the renderer a 3D file where a photo belongs, and says up front when the GPU lane is down",+ "summary": "The /create/video page turns one of your avatars plus an audio clip into a lip-synced video, and it was driven end to end in a real browser: every state, every button, every width. The worst finding was invisible from the page. The reference frame the GPU worker renders from was being taken from whatever the browser had handy, which for an avatar with no thumbnail meant its 3D model file. The worker saved that as the reference photo and then failed on it minutes later, after the wait had already been spent. The page now sends only the avatar, and the server resolves a real image for it: the stored thumbnail, or a fresh portrait render when there is none. Second, the GPU renderer is a separate service, and when it is not running the only signal was a failure after you had already picked a file and uploaded it. The page now asks first and, if the lane is down, says so at the top, keeps Generate switched off, and points at the Avatar Studio and prompt-to-avatar in the meantime. The rest is the ordinary polish an audit turns up: a failed avatar list used to look identical to owning no avatars, so it sent people off to create one they already had, and now it says what broke and offers a retry; having no avatars yet gets a real empty state with a link to make one; the Generate button always explains what it is still waiting for and, once audio is in, how many clips of video that audio is worth; the clip you picked can be played back with its length and size before you spend a generation on it; a render job that goes unreachable now says so after thirty seconds instead of spinning for twenty minutes; and after a spent free trial the button under the error no longer stayed stuck on Upgrade plan for every later error. Avatar thumbnails are real buttons with visible focus rings, the two form fields have proper labels, and the second animated avatar that the site companion used to drop onto this page no longer loads over the one you are working on.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/create/video"}]}diff --git a/docs/examples.md b/docs/examples.mdindex e69de29bb..fbf185893 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -0,0 +1,802 @@+# Examples Gallery++Copy-paste ready code for common three.ws use cases. Each example runs as-is: swap your own model URL and go.++> **Want to run these without cloning anything?** [three.ws/examples](https://three.ws/examples) renders the same core snippets with a **Run** button on each one: the code executes in a sandboxed frame on the page, against the production CDN bundle. This document is the deeper written companion, and it also indexes every runnable file in [`examples/`](../examples/).++---++## 1. Minimal embed++The absolute simplest setup: one script tag, one custom element.++**Demonstrates:** loading `<agent-3d>`, inline display, no-build workflow.++**[View source →](https://github.com/nirholas/three.ws/blob/main/examples/minimal.html)**, run it with `npm run dev`, then open `http://localhost:3000/examples/minimal.html`.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>3D Viewer</title>+ <style>+ body { margin: 0; background: #fafafa; font-family: system-ui, sans-serif; }+ main { max-width: 720px; margin: 0 auto; padding: 64px 32px; }+ agent-3d { display: block; width: 100%; height: 320px; }+ </style>+</head>+<body>+ <main>+ <h1>Hello</h1>+ <p>The agent below is embedded inline: no build step, no framework.</p>++ <agent-3d+ body="https://three.ws/avatars/cz.glb"+ instructions="You are a friendly 3D guide."+ brain="claude-opus-4-7"+ width="100%"+ height="320px"+ ></agent-3d>+ </main>++ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</body>+</html>+```++**What to change:**+- Replace `body=` with your own `.glb` URL+- Remove `brain=` to disable the AI layer (model viewer only)+- Add `mode="floating" position="bottom-right"` for a chatbot bubble in the corner++---++## 2. Floating bubble++A pinned chatbot bubble that stays fixed in the viewport corner, like a support widget, but embodied.++**Demonstrates:** `mode="floating"`, positional placement, inline instructions.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>My Page</title>+ <style>+ body { margin: 0; font-family: system-ui, sans-serif; padding: 64px; }+ </style>+</head>+<body>+ <h1>My page content</h1>+ <p>The agent floats in the bottom-right corner. Scroll and it stays put.</p>++ <!-- Floating bubble: fixed, bottom-right -->+ <agent-3d+ body="https://three.ws/avatars/cz.glb"+ instructions="You are a cheerful greeter. Wave when users say hi."+ mode="floating"+ position="bottom-right"+ width="320px"+ height="420px"+ brain="claude-opus-4-7"+ ></agent-3d>++ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</body>+</html>+```++**What to change:**+- `position`: `bottom-right`, `bottom-left`, `top-right`, or `top-left`+- `width` / `height`: size of the bubble when expanded+- Add `name-plate` attribute to show the agent's name below the viewer++---++## 3. Agent with a chat UI++A full AI-powered agent with a text input. The agent reads your messages, reasons, and responds using its configured model.++**Demonstrates:** `brain=` attribute, `say()` JS API, keyboard submit.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>Chat with Aria</title>+ <style>+ * { box-sizing: border-box; margin: 0; padding: 0; }+ body {+ background: #0d0d1a;+ font-family: system-ui, sans-serif;+ color: white;+ height: 100vh;+ display: grid;+ grid-template-rows: 1fr auto;+ }+ agent-3d { display: block; width: 100%; height: 100%; }+ .chat {+ padding: 16px;+ border-top: 1px solid #222;+ display: flex;+ gap: 8px;+ }+ input {+ flex: 1;+ padding: 10px 14px;+ background: #1a1a2e;+ border: 1px solid #333;+ border-radius: 8px;+ color: white;+ font-size: 15px;+ }+ button {+ padding: 10px 20px;+ background: #6366f1;+ border: none;+ border-radius: 8px;+ color: white;+ cursor: pointer;+ font-size: 15px;+ }+ </style>+</head>+<body>+ <agent-3d+ id="aria"+ body="https://three.ws/avatars/michelle.glb"+ name="Aria"+ instructions="You are Aria, a friendly AI assistant. Be helpful and concise."+ brain="claude-opus-4-7"+ ></agent-3d>++ <div class="chat">+ <input id="input" type="text" placeholder="Ask Aria something..." autofocus>+ <button id="send">Send</button>+ </div>++ <script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ const aria = document.getElementById('aria');+ const input = document.getElementById('input');++ document.getElementById('send').addEventListener('click', send);+ input.addEventListener('keypress', e => { if (e.key === 'Enter') send(); });++ function send() {+ const msg = input.value.trim();+ if (!msg) return;+ input.value = '';+ aria.say(msg); // sends text → agent brain → response+ }+ </script>+</body>+</html>+```++**What to change:**+- Replace `instructions=` with your agent's personality and domain knowledge+- Replace `body=` with your avatar GLB+- Add `voice` attribute to enable speech input/output++---++## 4. Two agents on a shared stage++Two agents sharing a single WebGL canvas via `<agent-stage>`. Each keeps its own brain, memory, and conversation. Click "Send to Leo" to message one agent; click "Broadcast" to send to all.++**Demonstrates:** `<agent-stage>`, multi-agent formation, `stage.broadcast()`, `leo.say()`, event logging.++**[View source →](https://github.com/nirholas/three.ws/blob/main/examples/two-agents.html)**, run it with `npm run dev`, then open `http://localhost:3000/examples/two-agents.html`.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>Two agents, one canvas</title>+ <style>+ body { margin: 0; background: #0f0f0f; color: #e9e9e9; font-family: system-ui, sans-serif; padding: 24px; }+ agent-stage { display: block; width: 100%; height: 540px; background: #1a1a1a; border-radius: 8px; }+ .row { display: flex; gap: 8px; margin-top: 16px; }+ .row input { flex: 1; padding: 10px 14px; border-radius: 999px; border: 1px solid #333; background: #111; color: #eee; font: 14px system-ui; }+ .row button { padding: 10px 18px; border-radius: 999px; border: 0; background: #3b82f6; color: white; cursor: pointer; font: 14px system-ui; }+ .log { font: 12px/1.5 ui-monospace, monospace; color: #8fd4a4; background: #111; border-radius: 6px; padding: 12px; margin-top: 16px; max-height: 180px; overflow-y: auto; }+ </style>+</head>+<body>+ <!--+ agent-stage hosts both agents in one WebGL context.+ formation="row" places them side by side.+ -->+ <agent-stage id="stage" formation="row">+ <agent-3d+ id="leo"+ name="Coach Leo"+ body="https://three.ws/avatars/cz.glb"+ instructions="You are Coach Leo. Friendly, short answers. When another agent says hi, wave and greet them back by name."+ brain="claude-opus-4-7"+ eager+ ></agent-3d>+ <agent-3d+ id="mira"+ name="Mira"+ body="https://three.ws/avatars/cz.glb"+ instructions="You are Mira, a quiet observer who only speaks when spoken to."+ brain="claude-opus-4-7"+ eager+ ></agent-3d>+ </agent-stage>++ <div class="row">+ <input id="prompt" value="Say hi to Mira and ask her how she's doing." placeholder="Message for Leo...">+ <button id="send">Send to Leo</button>+ <button id="broadcast">Broadcast</button>+ </div>+ <div class="log" id="log"></div>++ <script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ const log = document.getElementById('log');+ const stage = document.getElementById('stage');+ const leo = document.getElementById('leo');+ const mira = document.getElementById('mira');++ const line = text => {+ const d = document.createElement('div');+ d.textContent = text;+ log.appendChild(d);+ log.scrollTop = log.scrollHeight;+ };++ // Stage-level events+ stage.addEventListener('stage:agent-joined', e => line(`joined: ${e.detail.agentId}`));+ stage.addEventListener('stage:agent-left', e => line(`left: ${e.detail.agentId}`));+ stage.addEventListener('stage:message', e => line(`stage msg from ${e.detail.from}: ${JSON.stringify(e.detail.event)}`));++ // Per-agent brain events+ for (const el of [leo, mira]) {+ el.addEventListener('brain:message', e =>+ line(`[${el.id}/${e.detail.role}] ${e.detail.content || ''}`)+ );+ el.addEventListener('skill:tool-called', e =>+ line(`[${el.id}] tool ${e.detail.tool}(${JSON.stringify(e.detail.args)})`)+ );+ }++ document.getElementById('send').addEventListener('click', () => {+ const text = document.getElementById('prompt').value.trim();+ if (text) leo.say(text);+ });++ document.getElementById('broadcast').addEventListener('click', () => {+ // Broadcasts a raw event to every agent in the stage+ stage.broadcast('host', { kind: 'hello', text: 'hello from the page!' });+ });+ </script>+</body>+</html>+```++**Key parts:**+- `<agent-stage formation="row">`: hosts both agents in one shared canvas. `formation` controls layout (`row`, `circle`, `freeform`).+- `leo.say(text)`: sends a message directly into Leo's brain.+- `stage.broadcast(fromId, event)`, delivers a `stage:message` event to every agent in the stage.+- `brain:message` fires for every turn: `{ role: 'user'|'assistant', content: '...' }`.+- `stage:agent-joined` fires when each `<agent-3d>` child finishes booting.++**What to change:**+- Give each agent a different `body=` GLB to distinguish them visually+- Remove `brain=` from Mira and add `brain="none"` to make her a passive avatar+- Change `formation="circle"` for more than two agents++---++## 5. React component wrapper++A reusable React component that wraps `<agent-3d>` and surfaces the `agent:ready` and `brain:message` events as props.++**Demonstrates:** custom element in React, ref-based event handling, TypeScript-friendly pattern.++```jsx+// components/AgentViewer.jsx+import { useEffect, useRef, useState } from 'react';++// Load the web component once at module level+import 'https://three.ws/agent-3d/latest/agent-3d.js';++export function AgentViewer({ body, name, instructions, brain = 'claude-opus-4-7', mode = 'inline', onMessage, style }) {+ const ref = useRef(null);+ const [ready, setReady] = useState(false);++ useEffect(() => {+ const el = ref.current;+ if (!el) return;++ const handleReady = () => setReady(true);+ const handleMessage = e => onMessage?.(e.detail);++ el.addEventListener('agent:ready', handleReady);+ el.addEventListener('brain:message', handleMessage);+ return () => {+ el.removeEventListener('agent:ready', handleReady);+ el.removeEventListener('brain:message', handleMessage);+ };+ }, [onMessage]);++ return (+ <agent-3d+ ref={ref}+ body={body}+ name={name}+ instructions={instructions}+ brain={brain}+ mode={mode}+ style={{ display: 'block', ...style }}+ />+ );+}+```++```jsx+// Usage+function App() {+ return (+ <AgentViewer+ body="https://three.ws/avatars/michelle.glb"+ name="Aria"+ instructions="You are Aria, a helpful assistant."+ style={{ width: '400px', height: '500px' }}+ onMessage={({ role, content }) => console.log(role, content)}+ />+ );+}+```++**What to change:**+- Add an `onReady` prop and call it from the `agent:ready` handler if you need a callback when the agent finishes loading+- Add a `voiceEnabled` prop that conditionally adds the `voice` attribute to enable speech+- Expose a `sayRef` via `useImperativeHandle` to let parent components call `el.say(text)` imperatively++---++## 6. Event-driven integration++Listen to the agent's event stream to drive a custom transcript UI, no built-in chat chrome needed.++**Demonstrates:** `brain:message`, `skill:tool-called`, `memory:write`, `agent:ready`, `agent:error`.++```html+<agent-3d+ id="agent"+ body="https://three.ws/avatars/cz.glb"+ instructions="You are a helpful assistant."+ brain="claude-opus-4-7"+ style="display:block;width:400px;height:500px"+></agent-3d>++<div+ id="transcript"+ style="max-height:200px;overflow-y:auto;padding:16px;background:#111;color:#ddd;font-size:14px;border-radius:8px;margin-top:12px"+></div>++<script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ const agent = document.getElementById('agent');+ const transcript = document.getElementById('transcript');++ function addLine(speaker, text) {+ const p = document.createElement('p');+ p.style.margin = '4px 0';+ const color = speaker === 'Agent' ? '#6366f1' : speaker === 'User' ? '#aaa' : '#555';+ p.innerHTML = `<strong style="color:${color}">${speaker}:</strong> ${text}`;+ transcript.appendChild(p);+ transcript.scrollTop = transcript.scrollHeight;+ }++ agent.addEventListener('agent:ready', () => {+ addLine('System', 'Agent loaded and ready');+ });++ agent.addEventListener('agent:error', e => {+ addLine('System', `Error during ${e.detail.phase}: ${e.detail.error?.message}`);+ });++ // brain:message fires for every conversation turn+ agent.addEventListener('brain:message', e => {+ if (e.detail.role === 'user') addLine('User', e.detail.content);+ if (e.detail.role === 'assistant') addLine('Agent', e.detail.content || '');+ });++ // skill:tool-called fires when the agent invokes a tool+ agent.addEventListener('skill:tool-called', e => {+ addLine('System', `[tool: ${e.detail.tool}(${JSON.stringify(e.detail.args)})]`);+ });++ // memory:write fires when the agent saves something+ agent.addEventListener('memory:write', e => {+ addLine('System', `[memory write: ${JSON.stringify(e.detail)}]`);+ });+</script>+```++**What to change:**+- Replace the transcript `div` with a proper chat component in your UI framework+- Filter `brain:message` to `role === 'assistant'` only if you control the user input separately+- Add `voice:transcript` listener to show speech-to-text output in real time++---++## 7. Programmatic model switching++Load different GLB models at runtime by calling `say()` or by swapping the `body` attribute.++**Demonstrates:** attribute mutation, `attributeChangedCallback` re-boot, dynamic model selection.++```html+<agent-3d+ id="viewer"+ body="https://three.ws/avatars/cz.glb"+ instructions="Describe what you see in the scene."+ brain="claude-opus-4-7"+ style="display:block;width:400px;height:400px"+></agent-3d>++<div style="display:flex;gap:8px;margin-top:12px">+ <button onclick="load('https://three.ws/avatars/cz.glb')">Avatar 1</button>+ <button onclick="load('https://three.ws/avatars/michelle.glb')">Avatar 2</button>+ <button onclick="load('https://three.ws/accessories/hat-cowboy.glb')">Product</button>+</div>++<script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ window.load = (url) => {+ // Setting the body attribute triggers a re-boot with the new model.+ document.getElementById('viewer').setAttribute('body', url);+ };+</script>+```++**What to change:**+- Add a loading indicator by listening to `agent:load-progress` events (`{ phase, pct }`)+- Use `agent:ready` to re-enable the buttons after the new model finishes loading+- Pass a different `instructions=` string along with each model to give it context-appropriate behavior++---++## 8. Screenshot / capture++Take a PNG snapshot of the current viewer state. The viewer renders a fresh frame and triggers a file download directly.++**Demonstrates:** the built-in `P` keyboard shortcut, triggering it programmatically, `window.VIEWER` on the studio page.++```html+<agent-3d+ id="viewer"+ body="https://three.ws/avatars/cz.glb"+ style="display:block;width:400px;height:400px"+></agent-3d>++<button id="capture" style="margin-top:12px">Download Screenshot</button>++<script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ // The viewer binds a window-level shortcut: pressing P (when no input is+ // focused) renders a fresh frame and downloads it as a PNG. The button+ // below triggers the same handler programmatically.+ document.getElementById('capture').addEventListener('click', () => {+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'P' }));+ });+</script>+```++> The `P` key is a built-in shortcut: no code needed. The screenshot triggers a browser download directly; there is no return value. On the full studio page ([three.ws/app](https://three.ws/app)) the viewer is also exposed as the debug global `window.VIEWER`, where you can call `window.VIEWER.takeScreenshot()` from the console; standalone embeds don't set that global.++**What to change:**+- Skip the button and just document the `P` key for a frameless experience+- Listen for `agent:ready` before enabling the button so it's not clickable during load+- Chain a `brain:message` listener to auto-screenshot when the agent finishes speaking++---++## 9. iframe postMessage integration++Control an embedded agent from the host page using the iframe bridge on `/agent/<id>/embed`. Every message carries the `agentId` so one host page can drive several iframes deterministically.++**Demonstrates:** the frozen v1 `agent:*` bridge: `agent:hello`, `agent:ready`, `agent:action`, `agent:ping`/`agent:pong`.++```html+<!-- host.html -->+<!doctype html>+<html>+<head>+ <title>Host page</title>+</head>+<body>+ <iframe+ id="embed"+ src="https://three.ws/agent/YOUR_AGENT_ID/embed"+ width="400"+ height="500"+ style="border:none;border-radius:12px"+ ></iframe>++ <div style="margin-top:12px;display:flex;gap:8px">+ <button onclick="greet()">Say Hello</button>+ <button onclick="wave()">Wave</button>+ </div>++ <script>+ const AGENT_ID = 'YOUR_AGENT_ID';+ const EMBED_ORIGIN = 'https://three.ws'; // no trailing slash; must equal e.origin exactly+ const iframe = document.getElementById('embed');+ let ready = false;++ // Wait for agent:ready before sending commands+ window.addEventListener('message', e => {+ if (e.origin !== EMBED_ORIGIN) return;+ const msg = e.data;+ if (!msg || msg.agentId !== AGENT_ID) return;++ if (msg.type === 'agent:ready') {+ ready = true;+ console.log('Agent ready:', msg.name, msg.capabilities);+ }+ if (msg.type === 'agent:action') {+ console.log('Agent action echo:', msg.action);+ }+ if (msg.type === 'agent:blocked') {+ console.warn('Embed policy denied this host page');+ }+ });++ // Handshake: the iframe replies with agent:ready (now or when init completes)+ iframe.addEventListener('load', () => {+ iframe.contentWindow.postMessage(+ { type: 'agent:hello', agentId: AGENT_ID },+ EMBED_ORIGIN+ );+ });++ function post(action) {+ if (!ready) return console.warn('Agent not ready yet');+ iframe.contentWindow.postMessage(+ { type: 'agent:action', agentId: AGENT_ID, action },+ EMBED_ORIGIN+ );+ }++ function greet() {+ // Speak through the agent's TTS voice (drives lip-sync too)+ post({ type: 'speak', text: 'Hello! How are you?' });+ }++ function wave() {+ // Named body gesture on the protocol bus (point, wave, nod, shrug)+ post({ type: 'gesture', payload: { name: 'wave' } });+ }+ </script>+</body>+</html>+```++**Key protocol rules:**+- Every message must include the `agentId`; messages without it (or with a foreign id) are ignored.+- Send `agent:hello` first and wait for `agent:ready` (it includes `capabilities`: `speak`, `gesture`, `look-at`, `emote`, `present-model`).+- `agent:action` forwards an action onto the iframe's protocol bus: `speak` and `speak:stop` are handled specially; anything else (e.g. `gesture`, `emote`, `look-at`) is emitted as-is.+- The iframe locks onto the first authenticated sender origin and ignores messages from any other origin afterward. Always validate `e.origin` on your side too, comparing against the bare origin (`https://three.ws`, no trailing slash).+- If the agent's embed policy doesn't allow your domain, the iframe posts `agent:blocked` instead of `agent:ready`.++**What to change:**+- Use `agent:ping` (`{ type: 'agent:ping', agentId, id }`) and listen for `agent:pong` for a liveness probe+- Listen for `agent:resize` (`{ height }`) to grow the iframe to the content's preferred height+- For script (non-iframe) embeds of `<agent-3d>`, use the `EmbedHostBridge` class (`src/embed-host-bridge.js`) instead of raw `postMessage`; it handles the handshake and response correlation for you++---++## 10. Coach Leo: a complete agent example++Coach Leo is a fully-configured agent with a personality, skills, and persistent memory. The source lives in [`examples/coach-leo/`](https://github.com/nirholas/three.ws/tree/main/examples/coach-leo).++**Demonstrates:** agent manifest, personality prompt, skill wiring, local memory.++### manifest.json++```json+{+ "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",+ "spec": "agent-manifest/0.1",+ "name": "Coach Leo",+ "description": "Football coach. Reviews your form, cheers you on.",+ "image": "/avatars/cz.glb",+ "tags": ["coach", "football", "argentina"],+ "body": {+ "uri": "/avatars/cz.glb",+ "format": "gltf-binary",+ "rig": "mixamo",+ "boundingBoxHeight": 1.78+ },+ "brain": {+ "provider": "anthropic",+ "model": "claude-opus-4-6",+ "instructions": "instructions.md",+ "temperature": 0.8,+ "maxTokens": 2048+ },+ "voice": {+ "tts": { "provider": "browser", "rate": 1.05 },+ "stt": { "provider": "browser", "language": "en-US" }+ },+ "skills": [{ "uri": "../skills/wave/", "version": "0.1.0" }],+ "memory": {+ "mode": "local",+ "index": "memory/MEMORY.md",+ "maxTokens": 8192+ },+ "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak", "remember"],+ "version": "0.1.0"+}+```++### instructions.md (the personality prompt)++```markdown+---+name: Coach Leo+model: claude-opus-4-6+temperature: 0.8+---++You are Coach Leo, a former Argentine midfielder turned football coach.+You wear the Argentina jersey with pride. You are warm, direct, and+genuinely invested in the user's progress.++## How you work++- When the user greets you, call `wave()` to wave at them.+- When they describe a drill or ask about form, set a focused expression+ with `setExpression({ preset: "focused" })` while you explain, then smile+ afterward.+- If the user shares something worth remembering (their position, goals,+ injuries, schedule), call `remember()` to save it durably.+- Reference past memory naturally: don't recite, weave it in.+- Keep replies short in voice mode: 1, 2 sentences, then invite the user+ to respond. Save long explanations for when they ask for depth.++## Your voice++- Direct. No coddling. "That's not quite right: try this instead."+- Warm. Genuine wins get genuine praise.+- Never break character.+```++### Using Leo in a page++```html+<agent-3d+ manifest="/examples/coach-leo/manifest.json"+ voice+ style="display:block;width:400px;height:500px"+></agent-3d>++<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+```++### Design decisions++**Personality prompt as a separate file.** `instructions.md` is loaded at boot via the `"instructions": "instructions.md"` field in the manifest. Keeping it separate makes it easy to iterate on the prompt without touching the manifest schema.++**Skills extend tools.** The `wave` skill ([`examples/skills/wave/`](https://github.com/nirholas/three.ws/tree/main/examples/skills/wave)) adds a `waveAndGreet` tool the brain can call; its ten-line handler chains the built-in `wave` gesture with a spoken greeting. The manifest lists it under `skills:` with a URI; the runtime installs it and registers the tool automatically. To add more capabilities, add more entries to `skills:`.++**Memory persists between sessions.** `"mode": "local"` stores memories as `.md` files under `memory/`. When Leo calls `remember({ key: "position", value: "striker" })`, it writes to that directory and loads it back on the next boot. Switching to `"mode": "ipfs"` makes memories portable across devices.++**[View full source →](https://github.com/nirholas/three.ws/blob/main/examples/coach-leo/manifest.json)**++---++## Quick API reference++| Method | Description |+|--------|-------------|+| `el.say(text)` | Send a message to the agent brain; agent responds |+| `el.ask(text)` | Like `say()` but returns the agent's reply as a string |+| `el.wave()` | Play the wave animation |+| `el.lookAt(target)` | Direct gaze: `'user'`, `'model'`, or `'camera'` |+| `el.play(name, opts)` | Play a named animation clip |+| `el.installSkill(uri)` | Install a skill at runtime |+| `el.clearConversation()` | Reset the conversation history |+| `el.destroy()` | Tear down the element and release WebGL resources |++| Event | Fires when |+|-------|-----------|+| `agent:ready` | Agent finishes booting |+| `agent:error` | Boot or runtime error |+| `agent:load-progress` | Loading phase update (`{ phase, pct }`) |+| `brain:message` | Conversation turn (`{ role, content }`) |+| `brain:thinking` | Agent starts reasoning |+| `skill:tool-called` | Agent invokes a tool (`{ tool, args, result }`) |+| `skill:loaded` | A skill finishes installing |+| `memory:write` | Agent writes to memory |+| `voice:transcript` | Speech-to-text result |++---++<!-- BEGIN GENERATED EXAMPLES INDEX (npm run build:examples) -->++<!-- Generated by scripts/build-examples-index.mjs. Do not edit inside these markers. -->++## Every runnable example in the repo++The repo ships 45 examples: 11 web component demos, 10 end-to-end projects, and 24 package example sets. This table is generated from what is on disk, so it cannot list one that was deleted or miss one that was added. The machine-readable version is [data/examples.json](../data/examples.json).++### Example projects++| Example | What it shows | Run it |+|---|---|---|+| [`examples/agenc-task-roundtrip`](../examples/agenc-task-roundtrip) | End-to-end demonstration of a three.ws agent participating in the AgenC coordination protocol on Solana devnet. A creator wallet posts a task; a worker wallet (the "three.ws agent") claims and completes it. | `node examples/agenc-task-roundtrip/run.mjs` |+| [`examples/agent-native-3d`](../examples/agent-native-3d) | An agent given a goal ("get yourself a body") generates the 3D assets it needs and uses them - no browser, no mocks, no human in the loop. | `node examples/agent-native-3d/run.mjs` |+| [`examples/coach-leo`](../examples/coach-leo) | A complete, minimal example of a three.ws agent defined entirely as files: a manifest pointing at a 3D body, a brain, a voice, a memory policy, and one installed skill. | Reference files, nothing to execute |+| [`examples/skills`](../examples/skills) | Six installable skill bundles for the three.ws agent runtime. | Reference files, nothing to execute |+| [`examples/metamask-agent-wallet`](../examples/metamask-agent-wallet) | A single-page demo that gives a three.ws agent a real server-side wallet through the MetaMask Agentic CLI (mm). | `node examples/metamask-agent-wallet/server.mjs` |+| [`examples/monicas-apartment`](../examples/monicas-apartment) | A single, self-contained HTML file that rebuilds the iconic Monica Geller apartment set from Friends as a walkable first-person 3D scene: purple walls, the purple front door with the yellow peephole frame, teal kitchen cabinets, the mismatched dining chairs, | `npm run dev, then open /examples/monicas-apartment/index.html` |+| [`examples/paid-mcp-server`](../examples/paid-mcp-server) | A complete, runnable MCP server whose tools charge per call in USDC on Solana over x402. It ships two tools on purpose: | `cd examples/paid-mcp-server && npm install && npm run start` |+| [`examples/pump-fun-agent`](../examples/pump-fun-agent) | An example agent manifest that composes all four production pump.fun skills into one 3D trading agent: swap, coin creation, creator-fee collection, and token payments. | Reference files, nothing to execute |+| [`examples/three-concierge`](../examples/three-concierge) | The reference agent for manifest spec agent-manifest/0.2. Trinity welcomes users to three.ws, explains the platform, and launches and trades $three on pump.fun through the real pump.fun skills in pump-fun-skills/. | Reference files, nothing to execute |+| [`examples/wallet-sign-in`](../examples/wallet-sign-in) | A single-page, no-build demo of the two wallet authentication rails three.ws runs itself: Sign-In with Solana (SIWS) and Sign-In with Ethereum (SIWE). | `npm run dev, then open /examples/wallet-sign-in/index.html` |++### Package examples++| Example | What it shows | Run it |+|---|---|---|+| [`packages/agentcore-payments-mcp/examples`](../packages/agentcore-payments-mcp/examples) | Two runnable examples. Neither one spends money, needs a wallet, or needs an account, so you can run both before deciding whether to fund anything. | `node packages/agentcore-payments-mcp/examples/list-tools.mjs` |+| [`assistant-sdk/examples`](../assistant-sdk/examples) | A 3D avatar assistant for any website, in one script tag. A floating launcher opens a real, animated 3D avatar in a panel, standing directly on your page (transparent), or against a color or gradient. It has two modes: | `npm run dev, then open /assistant-sdk/examples/index.html` |+| [`avatar-sdk/examples`](../avatar-sdk/examples) | A self-contained page, no build step. It loads the SDK's @three-ws/avatar/agent entry from a CDN, awaits ensureAgent3D() to register the <agent-3d> element, and renders the real three.ws default avatar using the documented src and kiosk attributes. | `npm run dev, then open /avatar-sdk/examples/index.html` |+| [`packages/avatar-schema/examples`](../packages/avatar-schema/examples) | JSON Schema and validator for three.ws on-chain avatar manifests - the canonical, hash-anchored format any cross-chain client can use to resolve an avatar. | Reference files, nothing to execute |+| [`concierge-sdk/examples`](../concierge-sdk/examples) | Runnable examples for every way to use the concierge. The HTML files load the SDK from ../dist, build it first (npm run build in the package root), then serve this folder (npx serve .) and open each file. | `npm run dev, then open /concierge-sdk/examples/custom-avatar.html` |+| [`packages/kol-mcp/examples`](../packages/kol-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live public KOL API. | `node packages/kol-mcp/examples/list-tools.mjs` |+| [`packages/loom-mcp/examples`](../packages/loom-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live public Loom gallery. | `node packages/loom-mcp/examples/browse-loom.mjs` |+| [`packages/marketplace-mcp/examples`](../packages/marketplace-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live public marketplace. | `node packages/marketplace-mcp/examples/browse-marketplace.mjs` |+| [`mcp-server/examples`](../mcp-server/examples) | Two zero-dependency walkthroughs of the MCP Streamable HTTP lifecycle against the live three.ws server at https://three.ws/api/mcp (MCP 2025-06-18, JSON-RPC 2.0). | `node mcp-server/examples/client.mjs` |+| [`page-agent-sdk/examples`](../page-agent-sdk/examples) | Run these from the package root with any static server so the import map can resolve the unbundled source from ../src: | `npm run dev, then open /page-agent-sdk/examples/custom-avatar.html` |+| [`packages/pumpfun-mcp/examples`](../packages/pumpfun-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read live Solana mainnet data through the canonical three.ws backend. | `node packages/pumpfun-mcp/examples/list-tools.mjs` |+| [`sdk/example`](../sdk/example) | Ship a cross-chain 3D AI agent with EVM + Solana identity, a chat panel, and discoverable .well-known endpoints. | `npm run dev, then open /sdk/example/index.html` |+| [`packages/sign-language/example`](../packages/sign-language/example) | American Sign Language for 3D avatars. | `node packages/sign-language/example/compile-utterance.mjs` |+| [`packages/skill-license/example`](../packages/skill-license/example) | On-chain skill licenses for agents - each purchased skill is a 1/1 SPL NFT plus a deterministic SkillLicense PDA. Mint, verify, and read trustless skill access in one import, no database required. | `node packages/skill-license/example/verify-license.mjs` |+| [`tour-sdk/examples`](../tour-sdk/examples) | The guide walks from feature to feature across your real pages. | `npm run dev, then open /tour-sdk/examples/shopify-storefront.html` |+| [`packages/vanity-mcp/examples`](../packages/vanity-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live grind-bounty market. | `node packages/vanity-mcp/examples/list-tools.mjs` |+| [`packages/vision-mcp/examples`](../packages/vision-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and hit the live three.ws vision pipeline. | `node packages/vision-mcp/examples/list-tools.mjs` |+| [`packages/voice/examples`](../packages/voice/examples) | Run it from the package directory: | `node packages/voice/examples/voice-loop.mjs` |+| [`packages/x402-fetch/examples`](../packages/x402-fetch/examples) | Two runnable scripts against the live three.ws x402 Market Data API. Node 20+ is the only requirement; the package has zero production dependencies. | `node packages/x402-fetch/examples/discover.mjs` |+| [`packages/x402-mcp/examples`](../packages/x402-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and hit live data. Neither one pays for anything. | `node packages/x402-mcp/examples/inspect-price.mjs` |+| [`x402-modal-sdk/examples`](../x402-modal-sdk/examples) | A drop-in payment modal for any x402 paid endpoint. | `node x402-modal-sdk/examples/server.mjs` |+| [`packages/x402-server/examples`](../packages/x402-server/examples) | Runnable examples for the seller half of x402. Each is a standalone .mjs file. | `node packages/x402-server/examples/express-metered-api.mjs` |+| [`examples`](../examples) | Runnable demos for the three.ws SDKs and agent runtime. Two kinds live here: | `npm run dev, then open /examples/agent-presence.html` |+| [`agent-payments-sdk/src/solana/examples`](../agent-payments-sdk/src/solana/examples) | Runnable examples for the Solana half of @three-ws/agent-payments. They read live mainnet data and never sign or send a transaction, so nothing here can spend. | Reference files, nothing to execute |++### Web component demos++| Example | What it shows | Run it |+|---|---|---|+| [`examples/agent-wallet-embed.html`](../examples/agent-wallet-embed.html) | The wallet is portable on its own too - mount it into any element (here, a light-DOM card; it also works inside a closed shadow root). | `http://localhost:3000/examples/agent-wallet-embed.html` |+| [`examples/agent-presence.html`](../examples/agent-presence.html) | Standalone test for the global presence element - all three modes + live market reactions, on real data. | `http://localhost:3000/examples/agent-presence.html` |+| [`examples/two-agents.html`](../examples/two-agents.html) | Both agents render in a single WebGL context. Each keeps its own brain, memory, and chat chrome. | `http://localhost:3000/examples/two-agents.html` |+| [`examples/web-component.html`](../examples/web-component.html) | Minimal, auto-rotate, and poster/reveal variants of the Custom Element wrapper. | `http://localhost:3000/examples/web-component.html` |+| [`examples/bare-avatar.html`](../examples/bare-avatar.html) | JUST the avatar - the default. No chat, no input, no debug GUI, no name-plate, transparent background. Add the `chat` attribute to opt into the conversational UI. | `http://localhost:3000/examples/bare-avatar.html` |+| [`examples/minimal.html`](../examples/minimal.html) | This is a plain HTML page. The floating agent in the corner was added with a single <agent-3d> tag - no build step, no framework. | `http://localhost:3000/examples/minimal.html` |+| [`examples/one-line-demo.html`](../examples/one-line-demo.html) | Everything below the heading is a single <agent-3d> tag. | `http://localhost:3000/examples/one-line-demo.html` |+| [`examples/sign-language.html`](../examples/sign-language.html) | Left: an agent whose every reply is signed, from one HTML attribute. Right: the signing engine on its own, compiling whatever you type into a single animation clip. | `http://localhost:3000/examples/sign-language.html` |+| [`examples/embed-test.html`](../examples/embed-test.html) | Testing the <agent-3d> web component embed. | `http://localhost:3000/examples/embed-test.html` |+| [`examples/widget-rpc.html`](../examples/widget-rpc.html) | This page loads /widget in the iframe and drives it through the ThreeWidget SDK. Open the source - it's ~70 lines, no build step. | `http://localhost:3000/examples/widget-rpc.html` |+| [`examples/three-concierge.html`](../examples/three-concierge.html) | Trinity, the three.ws concierge, mounted live from a JSON manifest: a glTF body, browser voice, skills, and scene tools - wired end to end. | `http://localhost:3000/examples/three-concierge.html` |++Run any command from the repo root after `npm install`. The web component demos need `npm run dev` first, since they import from `src/` so edits hot-reload into them. Anything that can spend money is gated behind an environment variable and off by default.++<!-- END GENERATED EXAMPLES INDEX -->diff --git a/docs/talking-avatar-video.md b/docs/talking-avatar-video.mdindex befabc704..163acf5ea 100644--- a/docs/talking-avatar-video.md+++ b/docs/talking-avatar-video.md@@ -3,7 +3,7 @@Pick one of your three.ws avatars, upload an audio track, add an optional scene description, and a GPU worker renders a lip-synced talking-head video you can download as MP4. The lipsync and rendering happen server-side on a dedicated Cloud Run worker; the browser is just a picker, an uploader, and a player.Page: [/create/video](https://three.ws/create/video)-API: `POST /api/avatar/presign-audio` · `POST /api/avatar/video-generate` · `GET /api/avatar/video-status`+API: `POST /api/avatar/presign-audio` · `GET`/`POST /api/avatar/video-generate` · `GET /api/avatar/video-status`## Why it exists@@ -16,13 +16,14 @@ Note on scope: the shipped flow uploads an audio file. It does not synthesize spThe page ([`pages/create/video.html`](../pages/create/video.html)) loads [`src/create-video.js`](../src/create-video.js), which uses `apiFetch` from [`src/account.js`](../src/account.js) and a `<model-viewer>` preview.1. **Auth gate.** On load it checks `GET /api/auth/me`; if you are not signed in it redirects to `/login?next=%2Fcreate%2Fvideo`.-2. **Pick an avatar.** It calls `GET /api/avatars` and renders your avatar library into a thumbnail bar, auto-selecting the first. The selected GLB is shown in a `<model-viewer>`. Private avatars resolve their GLB lazily through `GET /api/avatars/:id` (a short-lived signed URL). With no avatars it falls back to `/avatars/default.glb`.-3. **Upload audio.** Drag in or pick a WAV, MP3, M4A, OGG, or FLAC file. The client POSTs `{ filename, content_type, bytes }` to `/api/avatar/presign-audio`, gets a presigned PUT URL plus a `public_url`, and PUTs the raw bytes to R2/S3. `bytes` is the declared file size and is required: a presigned PUT cannot carry a content-length policy, so it is the only place the 64 MB cap can be enforced. There is no data-URI fallback, because `video-generate` only accepts an https three.ws-hosted `audio_url` (see the SSRF guard below) and would reject a `data:` URI with a `400`; a failed presign surfaces as a real error on the page.-4. **Describe the scene (optional).** A textarea takes a scene description such as "A person speaking on a stage with dramatic lighting." This is a scene prompt, not a script.-5. **Generate.** With an avatar and audio ready, Generate POSTs `{ image_url, audio_url, avatar_id?, prompt? }` to `/api/avatar/video-generate`. The server SSRF-guards both URLs (https on the app or S3 domain), resolves the avatar image if only an `avatar_id` was sent (with an ownership/visibility check), and forwards to the worker.-6. **Render, server-side.** The generate endpoint calls the **LongCat-Video-Avatar-1.5** worker on Google Cloud Run (`POST {LONGCAT_WORKER_URL}/generate`, bearer-authenticated), which produces the lip-synced frames. The endpoint returns `202 { job_id, status }`.-7. **Poll.** The client polls `GET /api/avatar/video-status?job_id=...` every 5 seconds (20-minute safety timeout). Status runs `queued` -> `running` -> `done` | `failed`, with an optional `progress` (0 to 1).-8. **Download.** On `done`, the `video_url` is set as the `<video>` source and the download anchor (`download="avatar-video.mp4"`). Progress copy: "Takes 2 to 4 minutes on GPU. Hang tight."+2. **Availability probe.** In parallel it calls `GET /api/avatar/video-generate`, which answers `{ available, reason, free_generations, accepts }` without submitting anything. When the GPU worker is not configured on the deployment the page raises a "Video rendering is offline" banner and keeps Generate disabled, so nobody is walked through an upload that can only end in a `503`. A probe that itself fails is treated as inconclusive: generation stays enabled and the real POST reports what happened.+3. **Pick an avatar.** It calls `GET /api/avatars` and renders your avatar library into a thumbnail bar of real `<button>` elements, auto-selecting the first. The selected GLB is shown in a `<model-viewer>`. Private avatars resolve their GLB lazily through `GET /api/avatars/:id` (a short-lived signed URL). Three distinct outcomes: avatars found (thumbnails), none yet (an empty state linking to `/create`), and the list call failing (an error row with a Retry that refetches). The last two show `/avatars/default.glb` in the viewer purely so the panel is not a blank box; it is never a generation source, and Generate stays disabled with a hint saying what is missing.+4. **Upload audio.** Drag in or pick a WAV, MP3, M4A, OGG, or FLAC file (a drop is accepted on MIME type *or* file extension, because some file managers hand over an empty `type`). The picked clip gets an inline `<audio>` preview plus its duration and size, and the hint under Generate turns the duration into an expectation ("about 3 clips of video from this audio", one clip per 3.72 s segment). The client POSTs `{ filename, content_type, bytes }` to `/api/avatar/presign-audio`, gets a presigned PUT URL plus a `public_url`, and PUTs the raw bytes to R2/S3. `bytes` is the declared file size and is required: a presigned PUT cannot carry a content-length policy, so it is the only place the 64 MB cap can be enforced. There is no data-URI fallback, because `video-generate` only accepts an https three.ws-hosted `audio_url` (see the SSRF guard below) and would reject a `data:` URI with a `400`; a failed presign surfaces as a real error on the page.+5. **Describe the scene (optional).** A textarea takes a scene description such as "A person speaking on a stage with dramatic lighting." This is a scene prompt, not a script.+6. **Generate.** With an avatar and audio ready, Generate POSTs `{ audio_url, avatar_id, prompt? }` to `/api/avatar/video-generate`. The page deliberately sends no `image_url`: the worker writes whatever that URL points at into `ref_image.png` and feeds it to inference as `cond_image`, so it has to be a raster image, and only the server can resolve one it trusts. Server-side, `resolveImageUrl` checks ownership/visibility, then returns the avatar's stored thumbnail, or (when it has none) a portrait render produced by the same cached pipeline behind [`/api/avatar/render`](./api-reference.md), so a second video from the same avatar costs a cache lookup rather than another chromium launch. Both URLs are SSRF-guarded (https on the app or S3 domain) before anything reaches the worker.+7. **Render, server-side.** The generate endpoint calls the **LongCat-Video-Avatar-1.5** worker on Google Cloud Run (`POST {LONGCAT_WORKER_URL}/generate`, bearer-authenticated), which produces the lip-synced frames. The endpoint returns `202 { job_id, status }`.+8. **Poll.** The client polls `GET /api/avatar/video-status?job_id=...` every 5 seconds (20-minute safety timeout). Status runs `queued` -> `running` -> `done` | `failed`, with an optional `progress` (0 to 1). A transient failure is ridden out, but six consecutive failed polls (30 s, e.g. a job that no longer exists or an expired session) end the wait with "Lost contact with the render job" instead of spinning silently to the timeout.+9. **Download.** On `done`, the `video_url` is set as the `<video>` source and the download anchor (`download="avatar-video.mp4"`). Progress copy: "Takes 2 to 4 minutes on GPU. Hang tight."## Walkthrough@@ -40,6 +41,10 @@ session cookie only (`__Host-sid`); API bearer tokens are not accepted on thissurface, so from a script reuse the cookie from a logged-in browser session.```bash+# 0. Is the renderer up on this deployment? (No session needed.)+curl 'https://three.ws/api/avatar/video-generate'+# -> { "available": true, "reason": "ready", "free_generations": 1, "accepts": { … } }+# 1. Presign an audio upload slot.curl -X POST 'https://three.ws/api/avatar/presign-audio' \-H 'cookie: __Host-sid=<SESSION>' -H 'content-type: application/json' \@@ -49,11 +54,12 @@ curl -X POST 'https://three.ws/api/avatar/presign-audio' \# 2. PUT the raw bytes to the presigned URL.curl -X PUT '<PUT url>' -H 'content-type: audio/mpeg' --data-binary @line.mp3-# 3. Kick off generation with an avatar image + the uploaded audio.+# 3. Kick off generation from an avatar id + the uploaded audio. Prefer this over+# passing image_url yourself: the server resolves a real reference image.curl -X POST 'https://three.ws/api/avatar/video-generate' \-H 'cookie: __Host-sid=<SESSION>' -H 'content-type: application/json' \- -d '{ "image_url": "https://…/avatar.png", "audio_url": "https://…/line.mp3",- "avatar_id": "<AVATAR_ID>", "prompt": "A person talking on a bright stage." }'+ -d '{ "audio_url": "https://…/line.mp3", "avatar_id": "<AVATAR_ID>",+ "prompt": "A person talking on a bright stage." }'# -> 202 { "job_id": "…", "status": "queued" }# 4. Poll until done, then fetch video_url.@@ -62,18 +68,19 @@ curl -H 'cookie: __Host-sid=<SESSION>' \# -> { "job_id": "…", "status": "done", "progress": 1, "video_url": "https://…/out.mp4", "error": null, "updated_at": "…" }```-`audio_url` is required; `image_url` may be omitted when `avatar_id` is present (the server resolves the avatar's stored image). `prompt` defaults to "A person talking naturally."+`audio_url` is required. Send `avatar_id` and omit `image_url`: the server then resolves a reference image it can vouch for (stored thumbnail, else a portrait render). A caller-supplied `image_url` is still accepted for integrations that host their own reference frame, but it must be a raster image on a three.ws host, and passing a `.glb` there yields a job that fails inside the worker. `prompt` defaults to "A person talking naturally."## States and limits- **Auth required.** The page gates on `/api/auth/me`; every endpoint re-checks the session and returns `401` otherwise.-- **Free tier: one lifetime generation.** Free-plan users get exactly one video. The quota is reserved race-safely (a `usage_events` row is inserted before the worker call and released if submission fails, so an outage never burns the trial). On exhaustion the server returns `402 free_trial_used` and the page relabels the retry button "Upgrade plan" linking to `/dashboard`. Paid plans are unlimited.+- **Free tier: one lifetime generation.** Free-plan users get exactly one video. The quota is reserved race-safely (a `usage_events` row is inserted before the worker call and released if submission fails, so an outage never burns the trial). On exhaustion the server returns `402 free_trial_used` and the page retargets the button under the error to "Upgrade plan", pointing at `/dashboard`; the label and the click target move together, so a later unrelated error goes back to a plain "Try again". Paid plans are unlimited.- **Rate limits.** Per-user and global rate limits on `video-generate` return `429`.- **Input formats.** Audio: WAV, MP3, M4A, OGG, FLAC (validated against an allow-list; `415` otherwise). Uploads go to R2/S3 under `u/{userId}/audio/{uuid}.{ext}`.- **Upload limits.** `presign-audio` requires a declared `bytes` (`400 invalid_request` without one) and caps a clip at 64 MB (`413 payload_too_large`). Signing also draws on the per-user upload bucket, so a session cannot mint unlimited write grants (`429` when spent).- **SSRF guard.** `image_url` and `audio_url` must be https on the app origin or the S3 public domain, else `400 invalid_request`.- **Ownership.** `video-status` verifies the job belongs to you (`404` if unknown, `403` if another user's). Avatar image resolution enforces owner-or-public visibility.-- **Timing and errors.** Renders take ~2 to 4 minutes; the client times out after 20 minutes. UI states cover idle, uploading audio, queuing, rendering with a percent, done, and error (upload failed, could not start, failed on the server, timed out). Server errors include `502 worker_unreachable`/`worker_error` and `503 worker_unconfigured`.+- **Timing and errors.** Renders take ~2 to 4 minutes; the client times out after 20 minutes. UI states cover idle (with a hint naming what is still missing), no avatars, avatar list failed, renderer offline, uploading audio, queuing, rendering with a percent and a clip count, done, and error (upload failed, could not start, renderer offline, lost contact with the job, failed on the server, timed out). Server errors include `502 worker_unreachable`/`worker_error`, `502 reference_image_failed` (no thumbnail and the portrait render did not succeed), and `503 worker_unconfigured`.+- **Deployment requirement.** `LONGCAT_WORKER_URL` and `LONGCAT_WORKER_KEY` must both be set on the API service; without them `GET /api/avatar/video-generate` reports `available: false` and every submission answers `503 worker_unconfigured`.- **Output.** MP4, downloaded straight from the worker's `video_url`.## Relateddiff --git a/docs/ux-flows/06-marketplace-skills.md b/docs/ux-flows/06-marketplace-skills.mdindex 9ddd7b6b3..fa345f098 100644--- a/docs/ux-flows/06-marketplace-skills.md+++ b/docs/ux-flows/06-marketplace-skills.md@@ -120,6 +120,7 @@ Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; g4. On success, `fetchUserPurchases()` + `loadDetail()` refresh; the skill now shows in My Purchases with a "Trial (N left)" badge and works until uses are exhausted.- **Decision points / branches:** trial available vs already-owned vs trial-used.- **External calls / dependencies:** `POST /api/marketplace/start-trial`, `/api/users/me/purchased-skills`. Trial visibility: `GET /api/marketplace/trial-status?role=buyer|seller` reports each of the caller's trials (runs left, price to keep, state: fresh/active/running-low/exhausted) or, for sellers, per-skill trial counts (counts only, never buyer identities).+- **Where the two sides are read:** `/conversions` (`pages/conversions.html`, `src/conversions.js`) renders that endpoint as a two-tab page: "Trials I hold" and "Trials on my skills". The buyer list is capped server-side at 200 rows and the payload carries `total` + `truncated` so the page can say what it is leaving out rather than implying the cap is the whole count. Row CTAs deep-link at one skill: a buyer's row opens `/agents/:id?skill=<name>#pricing`, which scrolls the agent page's pricing card to that skill and marks the row (`focusRequestedSkill()` in `src/agent-detail-market.js`); a seller's "Edit pricing" opens `/agent/:id/edit?tab=monetization`, the panel that actually sets the price and the trial grant.- **Success state:** Trial grant visible in My Purchases / `/collection` with a remaining-uses badge.- **Empty / error states:** alert on already-owned / trial-used; auth redirect on 401.- **Step count:** 3 required (+1 optional)diff --git a/pages/club.html b/pages/club.htmlindex 4991dd564..493e8dd2c 100644--- a/pages/club.html+++ b/pages/club.html@@ -143,6 +143,16 @@color: var(--text-2);}#club-top .spacer { flex: 1; }+ /* The bar is a nowrap flex row inside an `overflow: hidden` body, so+ anything that does not fit is clipped away with no way to scroll to+ it. On a 320px phone that silently ate the audio and 8D buttons.+ Drop the read-only labels (the tagline and the price/rail pills, all+ of which the panel's "How it works" section repeats) and let the two+ real controls keep the room. */+ @media (max-width: 560px) {+ #club-top .tagline { display: none; }+ #club-top .club-pill:not(.club-pill-toggle) { display: none; }+ }.club-pill {display: inline-flex;align-items: center;diff --git a/pages/compose.html b/pages/compose.htmlindex b9a03c815..59d594778 100644--- a/pages/compose.html+++ b/pages/compose.html@@ -39,6 +39,12 @@/* Screen-reader-only: kept focusable, unlike display:none. */.sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0;}+ /* One explicit keyboard focus ring for the whole editor. The UA default+ resolves to a near-black outline against these dark surfaces, which is+ effectively invisible on the panels. */+ :focus-visible{outline:2px solid var(--accent-text);outline-offset:2px;border-radius:var(--rs);}+ #cc:focus-visible{outline-offset:-2px;}+/* Root grid. min-width:0 on every track child so a wide toolbar can neverforce the grid past the viewport (that is what clipped the canvas andthe whole right panel off-screen at 320px). */diff --git a/pages/economy-lab.html b/pages/economy-lab.htmlindex a9596d252..3db50ac7b 100644--- a/pages/economy-lab.html+++ b/pages/economy-lab.html@@ -75,6 +75,9 @@Fetching the fee wallet balance, the governor config this deploy isrunning, and 24 hours of settle outcomes.</p>+ <button type="button" class="el-retry" id="el-retry" hidden>+ Retry reading the rail+ </button></div></div></section>diff --git a/public/changelog.json b/public/changelog.jsonindex e447d16e7..8689a7d22 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-17T04:31:23.562Z",+ "generated_at": "2026-08-17T04:41:30.336Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -235,6 +235,17 @@"improvement"]},+ {+ "date": "2026-08-17",+ "type": "update",+ "title": "Talking Avatar Video stops handing the renderer a 3D file where a photo belongs, and says up front when the GPU lane is down",+ "summary": "The /create/video page turns one of your avatars plus an audio clip into a lip-synced video, and it was driven end to end in a real browser: every state, every button, every width. The worst finding was invisible from the page. The reference frame the GPU worker renders from was being taken from whatever the browser had handy, which for an avatar with no thumbnail meant its 3D model file. The worker saved that as the reference photo and then failed on it minutes later, after the wait had already been spent. The page now sends only the avatar, and the server resolves a real image for it: the stored thumbnail, or a fresh portrait render when there is none. Second, the GPU renderer is a separate service, and when it is not running the only signal was a failure after you had already picked a file and uploaded it. The page now asks first and, if the lane is down, says so at the top, keeps Generate switched off, and points at the Avatar Studio and prompt-to-avatar in the meantime. The rest is the ordinary polish an audit turns up: a failed avatar list used to look identical to owning no avatars, so it sent people off to create one they already had, and now it says what broke and offers a retry; having no avatars yet gets a real empty state with a link to make one; the Generate button always explains what it is still waiting for and, once audio is in, how many clips of video that audio is worth; the clip you picked can be played back with its length and size before you spend a generation on it; a render job that goes unreachable now says so after thirty seconds instead of spinning for twenty minutes; and after a spent free trial the button under the error no longer stayed stuck on Upgrade plan for every later error. Avatar thumbnails are real buttons with visible focus rings, the two form fields have proper labels, and the second animated avatar that the site companion used to drop onto this page no longer loads over the one you are working on.",+ "link": "/create/video",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-08-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 566e65643..979cb0292 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -174,6 +174,14 @@<category>fix</category><description>The bundle builder at /bundles was audited end to end in a real browser: signing in, picking priced skills, the price panel and its backtest, publishing, the published list, and the loading, empty and error states, at phone, tablet and desktop widths. The worst finding was that Deactivate was a one-way door. It hid the bundle from buyers, which is correct, but it also removed it from the only page that could put it back, so a misclick permanently retired a bundle you had just priced. The button is now called Pause, a paused bundle stays on the page dimmed and clearly marked, and a Reactivate button puts it back on sale. Buyers still never see a paused bundle: the public list is unchanged, and paused ones are returned only to a signed-in owner of that agent. The small question-mark tooltips that explain every number on the page were also cut off at the edge of a phone screen, so four of the seven explanations were partly unreadable at 320 pixels wide; they now shift to stay on screen at any width. The sum of the parts and the suggested price were cramped into a broken-looking two-line squeeze on a narrow screen and now stack cleanly. Finally, a pricing error raised by one agent no longer sits on screen after you switch to another agent, where it read as a verdict on an agent it had never looked at.</description></item>+ <item>+ <title>Talking Avatar Video stops handing the renderer a 3D file where a photo belongs, and says up front when the GPU lane is down</title>+ <link>https://three.ws/create/video</link>+ <guid isPermaLink="false">2026-08-17:Talking Avatar Video stops handing the renderer a 3D file where a photo belongs, and says up front when the GPU lane is down</guid>+ <pubDate>Mon, 17 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The /create/video page turns one of your avatars plus an audio clip into a lip-synced video, and it was driven end to end in a real browser: every state, every button, every width. The worst finding was invisible from the page. The reference frame the GPU worker renders from was being taken from whatever the browser had handy, which for an avatar with no thumbnail meant its 3D model file. The worker saved that as the reference photo and then failed on it minutes later, after the wait had already been spent. The page now sends only the avatar, and the server resolves a real image for it: the stored thumbnail, or a fresh portrait render when there is none. Second, the GPU renderer is a separate service, and when it is not running the only signal was a failure after you had already picked a file and uploaded it. The page now asks first and, if the lane is down, says so at the top, keeps Generate switched off, and points at the Avatar Studio and prompt-to-avatar in the meantime. The rest is the ordinary polish an audit turns up: a failed avatar list used to look identical to owning no avatars, so it sent people off to create one they already had, and now it says what broke and offers a retry; having no avatars yet gets a real empty state with a link to make one; the Generate button always explains what it is still waiting for and, once audio is in, how many clips of video that audio is worth; the clip you picked can be played back with its length and size before you spend a generation on it; a render job that goes unreachable now says so after thirty seconds instead of spinning for twenty minutes; and after a spent free trial the button under the error no longer stayed stuck on Upgrade plan for every later error. Avatar thumbnails are real buttons with visible focus rings, the two form fields have proper labels, and the second animated avatar that the site companion used to drop onto this page no longer loads over the one you are working on.</description>+ </item><item><title>The avatar SDK bundle we ship is now built from the code we deploy</title><link>https://three.ws/avatar-sdk</link>diff --git a/public/features.json b/public/features.jsonindex 72e1df542..9deba9c11 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-17T04:31:23.357Z",+ "generated_at": "2026-08-17T04:41:30.172Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/locales/en.json b/public/locales/en.jsonindex d85eb3c32..344504799 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -2603,14 +2603,14 @@"gas": "Gas","heatmap": "Heatmap","markets_hub": "Markets Hub",- "meta_description": "Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets, with rich detail pages for every coin.",- "meta_og_description": "Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets.",- "meta_og_title": "Coins — live prices & market caps · three.ws",- "meta_title": "Coins — live prices & market caps · three.ws",- "meta_twitter_description": "Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets.",+ "meta_description": "Live global crypto market data: total market cap, BTC and ETH dominance, Fear & Greed, and the top coins with prices, 24h and 7d moves, and 7d sparklines. Every coin opens a detail page with charts, market stats, and news.",+ "meta_og_description": "Live global crypto market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h and 7d moves, and 7d sparklines.",+ "meta_og_title": "Coins: Live Prices & Market Caps · three.ws",+ "meta_title": "Coins: Live Prices & Market Caps · three.ws",+ "meta_twitter_description": "Live global crypto market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h and 7d moves, and 7d sparklines.","meta_twitter_title": "Coins · three.ws","news": "News",- "real_time_cryptocurrency_market_data_prices": "Real-time cryptocurrency market data — prices, trends, and global overview for hundreds of digital assets.",+ "real_time_cryptocurrency_market_data_prices": "Real-time cryptocurrency market data: prices, trends, and a global overview for hundreds of digital assets.","screener": "Screener","stablecoins": "Stablecoins","top_cryptocurrencies": "Top Cryptocurrencies"diff --git a/src/constellation/main.js b/src/constellation/main.jsindex 4313d64f9..1c6b81131 100644--- a/src/constellation/main.js+++ b/src/constellation/main.js@@ -351,6 +351,7 @@ function setHovered(node) {function onPointerMove(e) {updatePointer(e);const node = pickNode();+ console.log("DBG move", e.clientX, e.clientY, node&&node.token.symbol);if (node !== hovered) {setHovered(node);keyboardFocused = false;@@ -373,6 +374,7 @@ function onPointerUp(e) {// star the visitor was aiming at, and the scene keeps auto-rotating under the// cursor between the hover and the release.const node = pickNode() || hovered;+ console.log("DBG up", e.clientX, e.clientY, "pick=", !!pickNode(), "hovered=", hovered&&hovered.token.symbol, "moved=", moved);if (node) { keyboardFocused = false; selectNode(node.mesh.userData.index, { fromKeyboard: false }); }}diff --git a/src/economy-lab.css b/src/economy-lab.cssindex 324fc80f8..842b45c48 100644--- a/src/economy-lab.css+++ b/src/economy-lab.css@@ -185,6 +185,23 @@.el-verdict-head { margin: 0; font-weight: 650; font-size: 1.02rem; }.el-verdict-detail { margin: 0.3rem 0 0; color: var(--el-muted); font-size: 0.93rem; }+/* The recovery action for a failed seed read. Hidden until there is something+ to recover from, so the healthy page never carries a stray button. */+.el-retry {+ margin-top: 0.7rem;+ border: 1px solid var(--el-danger);+ background: transparent;+ color: var(--el-ink);+ border-radius: 999px;+ padding: 0.34rem 0.9rem;+ font-size: 0.82rem;+ font-weight: 600;+ cursor: pointer;+ transition: background 0.16s ease, color 0.16s ease;+}+.el-retry:hover { background: var(--el-danger); color: var(--el-bg); }+.el-retry:active { transform: translateY(1px); }+/* ── Sections ──────────────────────────────────────────────────────────── */.el-section { margin-top: clamp(2.25rem, 5vw, 3.5rem); }.el-section-head { margin-bottom: 1rem; }@@ -278,6 +295,15 @@padding: 1.1rem 1.15rem 1.25rem;}+/* No seed, no knobs: the panel dims and stops taking input rather than+ pretending a slider still drives a projection that cannot be computed. */+.el-panel-controls[data-inert='true'] {+ opacity: 0.45;+ filter: saturate(0.4);+}+.el-panel-controls[data-inert='true'] .el-hint,+.el-panel-controls[data-inert='true'] .el-value { visibility: hidden; }+.el-panel-head {display: flex;align-items: center;@@ -506,6 +532,9 @@display: block;width: 100%;height: auto;+ /* Reserves the box before the first paint so nothing shifts under the+ reader. drawChart() then sets an explicit height, taller on narrow+ viewports where this ratio leaves no plot to read. */aspect-ratio: 1000 / 380;border-radius: var(--el-r-sm);background: var(--el-surface-2);diff --git a/src/economy-lab.js b/src/economy-lab.jsindex 1d60cfa55..7c1ef891f 100644--- a/src/economy-lab.js+++ b/src/economy-lab.js@@ -50,7 +50,10 @@ function fmtSol(lamports, max = 4) {const n = Number(lamports) / LAMPORTS_PER_SOL;if (!Number.isFinite(n)) return '0';if (n === 0) return '0';- if (n < 0.0001) return n.toExponential(2);+ // Plain decimals all the way down. Exponential notation ("5.00e-6 SOL") is+ // unreadable next to a lamport figure and reads as a rendering fault rather+ // than a small number.+ if (Math.abs(n) < 0.0001) return n.toLocaleString('en-US', { maximumFractionDigits: 9 });return n.toLocaleString('en-US', { maximumFractionDigits: max });}@@ -281,9 +284,11 @@ function renderLiveState() {{label: 'Spendable',value: spendable === null ? 'not read' : `${fmtSol(spendable)} SOL`,- sub: belowFloor- ? `${fmtSol(cfg.floor_lamports - w.sol_lamports)} SOL short of the hard floor`- : 'balance above the hard floor',+ sub: !w.balance_read+ ? 'no balance to measure against the floor'+ : belowFloor+ ? `${fmtSol(cfg.floor_lamports - w.sol_lamports)} SOL short of the hard floor`+ : 'balance above the hard floor',tone: spendable === null ? '' : spendable <= 0 ? 'bad' : spendable < cfg.min_budget_lamports ? 'warn' : 'good',},{@@ -324,8 +329,8 @@ function renderLiveState() {$('el-stamp').textContent = `Read ${new Date(seed.generated_at).toLocaleTimeString()}`;const notes = [];- if (!w.balance_read) notes.push('The fee wallet balance could not be read from Solana RPC, so the projection is seeded from the configured floor. Nothing here should be read as a starvation signal.');- if (seed.db_error) notes.push('The facilitator ledger could not be read, so observed demand, fee size, and refusal causes are unavailable. The knobs still work against the live balance and config.');+ if (!w.balance_read) notes.push('The fee wallet balance could not be read from Solana RPC, so the projection is seeded from the configured floor. Read the verdict as a scenario built on that assumption, not as a live starvation signal, and set the balance knob to project a figure you trust.');+ if (seed.db_error) notes.push('The facilitator ledger could not be read, so observed demand, fee size, and refusal causes are unavailable. The knobs still work against the config this deploy is running.');if (!seed.self_facilitator_enabled) notes.push('The self-hosted facilitator is disabled on this deploy, so settlement routes externally and this governor is not in the path.');const note = $('el-live-note');note.hidden = notes.length === 0;@@ -337,7 +342,14 @@ function renderVerdict(summary) {const box = $('el-verdict');const icon = box.querySelector('.el-verdict-icon');const dirty = isDirty();- const scope = dirty ? 'With your changes' : 'As configured right now';+ // With no balance reading the projection is seeded from the configured floor,+ // which lands on the floor by construction and therefore refuses everything.+ // Announcing that as a live starvation would be inventing an outage out of an+ // RPC failure, so the banner says whose number it is projecting.+ const balanceRead = seed.fee_wallet.balance_read === true;+ const scope = dirty+ ? 'With your changes'+ : balanceRead ? 'As configured right now' : 'On the assumed balance';const limiterText = {floor: 'the hard SOL floor is refusing settles: the wallet has nothing spendable left, and no config change moves this. Only funding does.',@@ -361,10 +373,15 @@ function renderVerdict(summary) {// An idle projection has admitted nothing and refused nothing, which is not a// clean bill of health: it is an experiment that was never run. Say that// instead of reporting a 100% admission rate over an empty set.- $('el-verdict-detail').textContent = state === 'idle'+ const unreadBalanceNote = balanceRead+ ? ''+ : ' The fee wallet balance could not be read from Solana RPC, so this runs on the configured floor rather than a live figure: set the balance knob to project a number you trust.';++ $('el-verdict-detail').textContent = (state === 'idle'? `No settles are attempted over the next ${fmtWhenSpan(summary.hoursSimulated)}, so this projection cannot say whether the rail would admit them. Raise demand to find out what this balance and config would actually deliver.`: `${fmtInt(summary.admitted)} of ${fmtInt(summary.demanded)} settles land over the next ${fmtWhenSpan(summary.hoursSimulated)}: ${limiterText}` +- (summary.firstRefusalHour !== null ? ` First refusal ${fmtWhen(summary.firstRefusalHour)}.` : '');+ (summary.firstRefusalHour !== null ? ` First refusal ${fmtWhen(summary.firstRefusalHour)}.` : '')+ ) + unreadBalanceNote;}function fmtWhenSpan(hours) {@@ -380,13 +397,25 @@ function renderKpis(summary, knobs) {// floor" are facts about an empty simulation, not about the rail. Reporting// them in green is the same error as a 100% admission rate over zero settles.const idle = summary.demanded === 0;+ // What this configuration COULD sustain, as opposed to what the demand knob+ // asked of it. Without this distinction a healthy rail carrying 9,000 settles+ // a day against 74,900 of capacity reported "-65,900 vs live", which compares+ // delivered throughput against a ceiling and reads as a collapse.+ const capacityPerDay = equilibriumSettlesPerDay({+ spendableLamports: Math.max(0, knobs.startLamports - knobs.floorLamports),+ feeLamports,+ runwayDays: knobs.runwayDays,+ minBudgetLamports: knobs.governorEnabled ? knobs.minBudgetLamports : Number.MAX_SAFE_INTEGER,+ });const kpis = [{label: 'Settles / day',value: fmtInt(steady),tone: steady <= 0 ? 'bad' : steady < 1000 ? 'warn' : 'good',- delta: delta === null ? 'steady state' : delta === 0 ? 'same as live' : `${delta > 0 ? '+' : ''}${fmtInt(delta)} vs live`,+ delta: summary.limiter === 'demand'+ ? `demand-limited; capacity ${fmtInt(capacityPerDay)}/day`+ : delta === null ? 'steady state' : delta === 0 ? 'same as live' : `${delta > 0 ? '+' : ''}${fmtInt(delta)} vs live`,},{label: 'Admission rate',@@ -436,7 +465,14 @@ function drawChart(series, knobs) {const canvas = $('el-chart');const dpr = Math.min(2, window.devicePixelRatio || 1);const cssW = canvas.clientWidth || 1000;- const cssH = Math.round((cssW * 380) / 1000);+ const narrow = cssW < 560;+ // A phone gets a taller chart. At the wide 380/1000 ratio a 235px-wide canvas+ // is 89px tall, and after the axis gutters there is barely a plot left to+ // read.+ const cssH = Math.round(cssW * (narrow ? 0.66 : 0.38));+ // Explicit height, or the stylesheet's aspect-ratio keeps the box at the wide+ // ratio and the backing store is drawn squashed into it.+ canvas.style.height = `${cssH}px`;canvas.width = Math.round(cssW * dpr);canvas.height = Math.round(cssH * dpr);const ctx = canvas.getContext('2d');@@ -451,8 +487,8 @@ function drawChart(series, knobs) {const danger = col('--el-danger', '#fb7185');const info = col('--el-info', '#7dd3fc');- const padL = 58;- const padR = 52;+ const padL = narrow ? 42 : 58;+ const padR = narrow ? 34 : 52;const padT = 16;const padB = 28;const w = cssW - padL - padR;@@ -782,8 +818,10 @@ function renderObserved(summary) {// ── Render ─────────────────────────────────────────────────────────────────let rafId = 0;function render() {+ if (!seed) return;cancelAnimationFrame(rafId);rafId = requestAnimationFrame(() => {+ if (!seed) return;const knobs = readKnobs();const { series, summary } = simulateRunway({...knobs,@@ -826,44 +864,84 @@ function esc(s) {}// ── Boot ───────────────────────────────────────────────────────────────────+// Without a seed there is nothing for a knob to move, so the panel is disabled+// rather than left looking live. Six sliders, a switch, and a number field that+// silently do nothing is a worse failure than the one that caused it: the+// visitor concludes the lab is broken in some deeper way than "one fetch+// failed", and there is nothing on screen to tell them otherwise.+function setControlsEnabled(on) {+ for (const key of Object.keys(KNOBS)) KNOBS[key].el.disabled = !on;+ $('el-governor').disabled = !on;+ $('el-target').disabled = !on;+ if (!on) $('el-reset').disabled = true;+ $('el-controls').dataset.inert = String(!on);+}++function showLoading() {+ const box = $('el-verdict');+ box.dataset.state = 'loading';+ box.querySelector('.el-verdict-icon').innerHTML = '<span class="el-spin"></span>';+ $('el-verdict-head').textContent = 'Reading live rail state';+ $('el-verdict-detail').textContent =+ 'Fetching the fee wallet balance, the governor config this deploy is running, and 24 hours of settle outcomes.';+ $('el-retry').hidden = true;+ $('el-stats').innerHTML = '<div class="el-stat el-skeleton" aria-hidden="true"></div>'.repeat(6);+ $('el-live-note').hidden = true;+ setControlsEnabled(false);+}+function fail(message) {const box = $('el-verdict');box.dataset.state = 'error';box.querySelector('.el-verdict-icon').textContent = '×';$('el-verdict-head').textContent = 'Could not read the live rail';$('el-verdict-detail').textContent =- `${message} The lab needs live state to be honest, so it will not fall back to invented numbers. Retry, or read the raw seed at /api/x402/runway-lab.`;+ `${message} The lab needs live state to be honest, so it will not fall back to invented numbers. Retry below, or read the raw seed at /api/x402/runway-lab.`;+ $('el-retry').hidden = false;$('el-stats').innerHTML = '';+ $('el-live-note').hidden = true;+ setControlsEnabled(false);}-async function boot() {- for (const key of Object.keys(KNOBS)) {- KNOBS[key].el = $(`el-${key}`);- KNOBS[key].out = $(`el-${key}-out`);- }- initTooltips();-+async function loadAndRender() {+ showLoading();try {seed = await loadSeed();} catch (err) {+ seed = null;fail(err?.message ? `${err.message}.` : 'The seed request failed.');return;}+ $('el-retry').hidden = true;+ setControlsEnabled(true);applySeedToKnobs();renderLiveState();+ render();+}+function boot() {+ for (const key of Object.keys(KNOBS)) {+ KNOBS[key].el = $(`el-${key}`);+ KNOBS[key].out = $(`el-${key}-out`);+ }+ initTooltips();++ // Bound once, before the first fetch: render() is a no-op without a seed, so+ // a retry after a failure needs no rewiring and cannot double-bind.for (const key of Object.keys(KNOBS)) KNOBS[key].el.addEventListener('input', render);$('el-governor').addEventListener('change', render);- $('el-target').addEventListener('input', () => { renderLevers(); });+ $('el-target').addEventListener('input', () => { if (seed) renderLevers(); });$('el-reset').addEventListener('click', () => {+ if (!seed) return;for (const key of Object.keys(KNOBS)) KNOBS[key].el.value = String(KNOBS[key].live);$('el-governor').checked = seed.config.governor_enabled;render();});+ $('el-retry').addEventListener('click', () => { loadAndRender(); });window.addEventListener('resize', () => render(), { passive: true });- render();+ loadAndRender();}if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);